@byok-sdk/client 0.8.0 → 0.9.0-rc.1

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 (39) hide show
  1. package/README.md +22 -1
  2. package/dist/adapters/index.js +14 -1
  3. package/dist/adapters/index.js.map +1 -1
  4. package/dist/agent-home.d.ts +29 -4
  5. package/dist/bin/agent-memory-mcp-server.d.ts +38 -0
  6. package/dist/bin/agent-message-mcp-server.d.ts +24 -0
  7. package/dist/bin/byok-agent-memory-mcp.d.ts +2 -0
  8. package/dist/bin/byok-agent-memory-mcp.js +432 -0
  9. package/dist/bin/byok-agent-memory-mcp.js.map +1 -0
  10. package/dist/bin/byok-agent-message-mcp.d.ts +2 -0
  11. package/dist/bin/byok-agent-message-mcp.js +441 -0
  12. package/dist/bin/byok-agent-message-mcp.js.map +1 -0
  13. package/dist/bin/byok-agent.js +7808 -5492
  14. package/dist/bin/byok-agent.js.map +1 -1
  15. package/dist/bin/byok-approval-mcp.js.map +1 -1
  16. package/dist/bin/commands/pair.d.ts +3 -0
  17. package/dist/daemon/agent-memory-filesystem.d.ts +23 -0
  18. package/dist/daemon/agent-memory-fs-helper.d.ts +10 -0
  19. package/dist/daemon/agent-memory.d.ts +160 -0
  20. package/dist/daemon/agent-message-outbox.d.ts +58 -0
  21. package/dist/daemon/auth-manager.d.ts +8 -0
  22. package/dist/daemon/control-protocol.d.ts +36 -0
  23. package/dist/daemon/create-daemon.d.ts +29 -2
  24. package/dist/daemon/daemon-owner.d.ts +9 -0
  25. package/dist/daemon/device-credential-store.d.ts +58 -0
  26. package/dist/daemon/device-proof-signer.d.ts +5 -4
  27. package/dist/daemon/memory-guidance.d.ts +8 -0
  28. package/dist/daemon/path-mutation-gate.d.ts +25 -0
  29. package/dist/daemon/resolve-agent-memory-mcp-bin.d.ts +6 -0
  30. package/dist/daemon/resolve-agent-message-mcp-bin.d.ts +6 -0
  31. package/dist/daemon/store.d.ts +45 -24
  32. package/dist/daemon/task-runner.d.ts +88 -3
  33. package/dist/daemon/toolset-registry.d.ts +2 -0
  34. package/dist/index.d.ts +7 -4
  35. package/dist/index.js +9976 -7469
  36. package/dist/index.js.map +1 -1
  37. package/dist/local-state-relocation.d.ts +24 -0
  38. package/dist/types.d.ts +2 -0
  39. package/package.json +7 -5
@@ -48,7 +48,11 @@ export interface AgentHomeProjectionApplyInput extends AgentHomeProjectionInput
48
48
  export interface AgentHomeProjection {
49
49
  /** Optional creation/task-time host preparation retained as a distinct lifecycle. */
50
50
  prepare?(input: AgentHomeProjectionInput): void | Promise<void>;
51
- /** Task-free opaque projection consumer. Its successful return means its own bytes are durable. */
51
+ /**
52
+ * Task-free opaque desired-state consumer. It must atomically and
53
+ * idempotently ensure its own durable bytes because exact revision/hash
54
+ * requests may replay after local derived-file loss or transport failure.
55
+ */
52
56
  apply?(input: AgentHomeProjectionApplyInput): void | Promise<void>;
53
57
  }
54
58
  export type AgentHomeProjectionFunction = (input: AgentHomeProjectionInput) => void | Promise<void>;
@@ -58,6 +62,11 @@ export interface AgentHomeLease {
58
62
  readonly agentRef: AgentRef;
59
63
  readonly canonicalHome: string;
60
64
  readonly cwd: string;
65
+ /** Filesystem identity captured under the writer lease; task-scoped memory rechecks it before pinning a descriptor. */
66
+ readonly homeIdentity: Readonly<{
67
+ dev: bigint;
68
+ ino: bigint;
69
+ }>;
61
70
  release(): Promise<void>;
62
71
  }
63
72
  export interface AgentHomeBinding {
@@ -82,7 +91,15 @@ export declare class AgentHomeLayout {
82
91
  * file is created by this preflight.
83
92
  */
84
93
  preflight(): Promise<void>;
94
+ /**
95
+ * Construction-time validation is deliberately non-mutating. The actual
96
+ * writable preflight runs asynchronously after daemon ownership is acquired
97
+ * and before transport/capability publication, where it can participate in
98
+ * the cross-process relocation gate without a sync shadow lock.
99
+ */
100
+ preflightSync(): void;
85
101
  private resolveRoot;
102
+ private acquireRootMutationGate;
86
103
  }
87
104
  export declare function stableAgentHomeOwnerId(storeDir: string, productId: string): string;
88
105
  /** One-writer lease backed by both a process registry and an exclusive marker. */
@@ -108,6 +125,8 @@ export declare class AgentHomeManager {
108
125
  prepare(agentRef: AgentRef): Promise<AgentHomeBinding>;
109
126
  /** Validate the configured root before capability publication. */
110
127
  preflight(): Promise<void>;
128
+ /** Synchronous construction-time preflight for strict Agent-only admission. */
129
+ preflightSync(): void;
111
130
  /** Resolve and lease without applying downstream projection side effects. */
112
131
  acquire(agentRef: AgentRef): Promise<AgentHomeBinding>;
113
132
  /** Initialize only after any requested session exact-match has succeeded. */
@@ -115,11 +134,17 @@ export declare class AgentHomeManager {
115
134
  supportsTaskFreeProjection(): boolean;
116
135
  /**
117
136
  * Apply one task-free projection under the same canonical-home writer lease
118
- * used by Agent execution. Only a successful host hook followed by the
119
- * SDK-owned fsynced ordering record can return `applied`.
137
+ * used by Agent execution. The host hook owns an atomic/idempotent ensure of
138
+ * its opaque product bytes, so an exact desired-state replay invokes it again
139
+ * before returning `idempotent`. Only a successful new-state hook followed
140
+ * by the SDK-owned fsynced ordering record can return `applied`.
120
141
  */
121
142
  project(input: AgentHomeProjectionPayload): Promise<AgentHomeProjectionOutcome>;
122
143
  }
123
144
  export declare function createAgentHomeProjection(prepare: AgentHomeProjectionFunction): AgentHomeProjection;
124
- /** Create only the task-free opaque projection consumer; no task-time fallback is inferred. */
145
+ /**
146
+ * Create the task-free atomic/idempotent opaque desired-state consumer.
147
+ * Exact revision/hash delivery may invoke it again before an idempotent receipt;
148
+ * no task-time fallback is inferred.
149
+ */
125
150
  export declare function createAgentHomeProjectionConsumer(apply: AgentHomeProjectionApplyFunction): AgentHomeProjection;
@@ -0,0 +1,38 @@
1
+ export declare const AGENT_MEMORY_RECALL_TOOL_NAME = "memory.recall";
2
+ export declare const AGENT_MEMORY_SAVE_TOOL_NAME = "memory.save";
3
+ export interface AgentMemoryMcpDeps {
4
+ recall(input: {
5
+ path: string;
6
+ ifRevision?: string;
7
+ }): Promise<{
8
+ path: string;
9
+ revision: string;
10
+ content: string;
11
+ auditWarning?: {
12
+ code: 'agent_memory_audit_unavailable';
13
+ };
14
+ }>;
15
+ save(input: {
16
+ op: 'replace' | 'delete';
17
+ path: string;
18
+ expectedRevision: string;
19
+ content?: string;
20
+ }): Promise<{
21
+ path: string;
22
+ revision?: string;
23
+ deleted: boolean;
24
+ }>;
25
+ }
26
+ interface RequestLike {
27
+ jsonrpc?: unknown;
28
+ id?: unknown;
29
+ method?: unknown;
30
+ params?: unknown;
31
+ }
32
+ export declare function handleAgentMemoryMcpRequest(request: RequestLike, deps: AgentMemoryMcpDeps): Promise<Record<string, unknown> | undefined>;
33
+ export declare function serveAgentMemoryMcpOverStdio(input: {
34
+ deps: AgentMemoryMcpDeps;
35
+ stdin?: NodeJS.ReadableStream;
36
+ stdout?: NodeJS.WritableStream;
37
+ }): void;
38
+ export {};
@@ -0,0 +1,24 @@
1
+ import type { AgentMessageContentType } from '@byok-sdk/protocol';
2
+ export declare const AGENT_MESSAGE_TOOL_NAME = "send_agent_message";
3
+ export interface AgentMessageMcpDeps {
4
+ publish(input: {
5
+ contentType: AgentMessageContentType;
6
+ body: string;
7
+ }): Promise<{
8
+ messageId: string;
9
+ state: string;
10
+ }>;
11
+ }
12
+ interface RequestLike {
13
+ jsonrpc?: unknown;
14
+ id?: unknown;
15
+ method?: unknown;
16
+ params?: unknown;
17
+ }
18
+ export declare function handleAgentMessageMcpRequest(request: RequestLike, deps: AgentMessageMcpDeps): Promise<Record<string, unknown> | undefined>;
19
+ export declare function serveAgentMessageMcpOverStdio(input: {
20
+ deps: AgentMessageMcpDeps;
21
+ stdin?: NodeJS.ReadableStream;
22
+ stdout?: NodeJS.WritableStream;
23
+ }): void;
24
+ export {};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,432 @@
1
+ #!/usr/bin/env node
2
+ import { promises, constants } from 'fs';
3
+ import net from 'net';
4
+ import { randomBytes, createHash, timingSafeEqual, createHmac } from 'crypto';
5
+ import path from 'path';
6
+ import { createInterface } from 'readline';
7
+
8
+ var CONTROL_PROTOCOL_VERSION = 1;
9
+ var HANDSHAKE_TIMEOUT_MS = 3e3;
10
+ var UNIX_SOCKET_PATH_SOFT_LIMIT = 100;
11
+ var CONTROL_SOCKET_FALLBACK_ROOT = "/tmp";
12
+ function shortHash(input) {
13
+ return createHash("sha256").update(input, "utf8").digest("hex").slice(0, 16);
14
+ }
15
+ function controlSocketPath(storeDir) {
16
+ const candidate = path.join(storeDir, "control.sock");
17
+ if (Buffer.byteLength(candidate, "utf8") <= UNIX_SOCKET_PATH_SOFT_LIMIT) return candidate;
18
+ return path.join(CONTROL_SOCKET_FALLBACK_ROOT, `byok-${shortHash(storeDir)}`, "sock");
19
+ }
20
+ function controlPipeName(productId, storeDir) {
21
+ const id = shortHash(`${productId}|${path.resolve(storeDir)}`);
22
+ return `\\\\.\\pipe\\byok-${id}`;
23
+ }
24
+ function controlEndpointPath(productId, storeDir, platform = process.platform) {
25
+ return platform === "win32" ? controlPipeName(productId, storeDir) : controlSocketPath(storeDir);
26
+ }
27
+ function controlTokenPath(storeDir) {
28
+ return path.join(storeDir, "control.token");
29
+ }
30
+ var SERVER_PROOF_LABEL = "byok-control-server|";
31
+ var CLIENT_AUTH_LABEL = "byok-control-client|";
32
+ function randomNonceHex() {
33
+ return randomBytes(32).toString("hex");
34
+ }
35
+ function hmacHex(token, message) {
36
+ return createHmac("sha256", token).update(message, "utf8").digest("hex");
37
+ }
38
+ function computeServerProof(token, clientNonce) {
39
+ return hmacHex(token, SERVER_PROOF_LABEL + clientNonce);
40
+ }
41
+ function computeClientAuth(token, serverNonce) {
42
+ return hmacHex(token, CLIENT_AUTH_LABEL + serverNonce);
43
+ }
44
+ function timingSafeEqualHex(a, b) {
45
+ const bufA = Buffer.from(a, "hex");
46
+ const bufB = Buffer.from(b, "hex");
47
+ if (bufA.length !== bufB.length) return false;
48
+ return timingSafeEqual(bufA, bufB);
49
+ }
50
+ function isRecord(value) {
51
+ return typeof value === "object" && value !== null;
52
+ }
53
+ function parseServerHello(value) {
54
+ if (!isRecord(value)) return void 0;
55
+ if (value.v !== CONTROL_PROTOCOL_VERSION || value.hello !== "server" || typeof value.proof !== "string" || typeof value.nonce !== "string") {
56
+ return void 0;
57
+ }
58
+ return { v: CONTROL_PROTOCOL_VERSION, hello: "server", proof: value.proof, nonce: value.nonce };
59
+ }
60
+ function parseServerReady(value) {
61
+ if (!isRecord(value)) return void 0;
62
+ if (value.v !== CONTROL_PROTOCOL_VERSION || value.ready !== true) return void 0;
63
+ return { v: CONTROL_PROTOCOL_VERSION, ready: true };
64
+ }
65
+ function encodeFrame(frame) {
66
+ return `${JSON.stringify(frame)}
67
+ `;
68
+ }
69
+ var ControlError = class extends Error {
70
+ constructor(code, message) {
71
+ super(message);
72
+ this.code = code;
73
+ this.name = "ControlError";
74
+ }
75
+ code;
76
+ };
77
+ var MAX_LINE_BYTES = 64 * 1024;
78
+ var NdjsonLineReader = class {
79
+ pending = Buffer.alloc(0);
80
+ /** @throws if the still-unterminated remainder exceeds {@link MAX_LINE_BYTES} — see that constant's own doc comment. */
81
+ push(chunk) {
82
+ this.pending = this.pending.length > 0 ? Buffer.concat([this.pending, chunk]) : chunk;
83
+ const lines = [];
84
+ let newlineIndex;
85
+ while ((newlineIndex = this.pending.indexOf(10)) !== -1) {
86
+ const line = this.pending.subarray(0, newlineIndex).toString("utf8");
87
+ this.pending = this.pending.subarray(newlineIndex + 1);
88
+ if (line.length > 0) lines.push(line);
89
+ }
90
+ if (this.pending.length > MAX_LINE_BYTES) {
91
+ throw new Error(`NDJSON line exceeded ${MAX_LINE_BYTES} bytes without a terminating newline`);
92
+ }
93
+ return lines;
94
+ }
95
+ };
96
+
97
+ // src/bin/control-client.ts
98
+ var MAX_CONTROL_TOKEN_BYTES = 256;
99
+ function errorMessage(err) {
100
+ return err instanceof Error ? err.message : String(err);
101
+ }
102
+ function sameFileState(left, right) {
103
+ return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
104
+ }
105
+ async function readControlToken(tokenPath) {
106
+ let namedBefore;
107
+ try {
108
+ namedBefore = await promises.lstat(tokenPath, { bigint: true });
109
+ } catch (err) {
110
+ if (err.code === "ENOENT") return void 0;
111
+ throw err;
112
+ }
113
+ if (!namedBefore.isFile() || namedBefore.isSymbolicLink()) {
114
+ throw new Error("control token is not a real regular file");
115
+ }
116
+ const handle = await promises.open(
117
+ tokenPath,
118
+ constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0)
119
+ );
120
+ try {
121
+ const opened = await handle.stat({ bigint: true });
122
+ const namedAfterOpen = await promises.lstat(tokenPath, { bigint: true });
123
+ if (!opened.isFile() || !namedAfterOpen.isFile() || namedAfterOpen.isSymbolicLink() || !sameFileState(namedBefore, opened) || !sameFileState(opened, namedAfterOpen)) {
124
+ throw new Error("control token pathname changed before safe open");
125
+ }
126
+ if (opened.size < 0 || opened.size > BigInt(MAX_CONTROL_TOKEN_BYTES)) {
127
+ throw new Error("control token exceeds the bounded read limit");
128
+ }
129
+ const size = Number(opened.size);
130
+ const bytes = Buffer.alloc(size);
131
+ const { bytesRead } = await handle.read(bytes, 0, size, 0);
132
+ const afterRead = await handle.stat({ bigint: true });
133
+ const namedAfterRead = await promises.lstat(tokenPath, { bigint: true });
134
+ if (bytesRead !== size || namedAfterRead.isSymbolicLink() || !sameFileState(opened, afterRead) || !sameFileState(afterRead, namedAfterRead)) {
135
+ throw new Error("control token changed during bounded read");
136
+ }
137
+ return bytes.toString("utf8").trim();
138
+ } finally {
139
+ await handle.close();
140
+ }
141
+ }
142
+ async function connectControlClient(opts) {
143
+ const tokenPath = controlTokenPath(opts.storeDir);
144
+ let token;
145
+ try {
146
+ const read = await readControlToken(tokenPath);
147
+ if (read === void 0) {
148
+ return { ok: false, reason: "daemon is not running (no control.token found)" };
149
+ }
150
+ token = read;
151
+ } catch (err) {
152
+ return { ok: false, reason: `could not read the control token: ${errorMessage(err)}` };
153
+ }
154
+ if (!token) {
155
+ return { ok: false, reason: "control token file is empty" };
156
+ }
157
+ const endpoint = controlEndpointPath(opts.productId, opts.storeDir);
158
+ try {
159
+ const client = await connectAndHandshake(endpoint, token, opts);
160
+ return { ok: true, client };
161
+ } catch (err) {
162
+ return { ok: false, reason: `daemon control socket not reachable: ${errorMessage(err)}` };
163
+ }
164
+ }
165
+ function connectAndHandshake(endpoint, token, opts) {
166
+ return new Promise((resolve, reject) => {
167
+ const socket = net.createConnection(endpoint);
168
+ const reader = new NdjsonLineReader();
169
+ let phase = "server-hello";
170
+ let settled = false;
171
+ const clientNonce = randomNonceHex();
172
+ const timer = setTimeout(() => {
173
+ fail(new Error("handshake timed out"));
174
+ }, opts.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS);
175
+ timer.unref?.();
176
+ function fail(err) {
177
+ if (settled) return;
178
+ settled = true;
179
+ clearTimeout(timer);
180
+ socket.removeAllListeners();
181
+ socket.destroy();
182
+ reject(err instanceof Error ? err : new Error(String(err)));
183
+ }
184
+ function succeed() {
185
+ settled = true;
186
+ clearTimeout(timer);
187
+ socket.removeListener("error", onError);
188
+ socket.removeListener("data", onData);
189
+ resolve(createControlClient(socket, reader, opts));
190
+ }
191
+ function onData(chunk) {
192
+ let lines;
193
+ try {
194
+ lines = reader.push(chunk);
195
+ } catch (err) {
196
+ fail(err);
197
+ return;
198
+ }
199
+ for (const line of lines) {
200
+ let parsed;
201
+ try {
202
+ parsed = JSON.parse(line);
203
+ } catch {
204
+ fail(new Error("malformed handshake frame"));
205
+ return;
206
+ }
207
+ if (phase === "server-hello") {
208
+ const hello = parseServerHello(parsed);
209
+ if (!hello) {
210
+ fail(new Error("malformed or unexpected server hello"));
211
+ return;
212
+ }
213
+ if (!timingSafeEqualHex(hello.proof, computeServerProof(token, clientNonce))) {
214
+ fail(new Error("server failed to prove it holds the control token"));
215
+ return;
216
+ }
217
+ socket.write(encodeFrame({ v: CONTROL_PROTOCOL_VERSION, auth: computeClientAuth(token, hello.nonce) }));
218
+ phase = "ready";
219
+ continue;
220
+ }
221
+ if (!parseServerReady(parsed)) {
222
+ fail(new Error("server did not confirm readiness"));
223
+ return;
224
+ }
225
+ succeed();
226
+ return;
227
+ }
228
+ }
229
+ function onError(err) {
230
+ fail(err);
231
+ }
232
+ socket.once("error", onError);
233
+ socket.once("connect", () => {
234
+ socket.write(encodeFrame({ v: CONTROL_PROTOCOL_VERSION, hello: "client", nonce: clientNonce }));
235
+ socket.on("data", onData);
236
+ });
237
+ });
238
+ }
239
+ function withTimeout(promise, ms, message) {
240
+ return new Promise((resolve, reject) => {
241
+ const timer = setTimeout(() => reject(new Error(message)), ms);
242
+ timer.unref?.();
243
+ promise.then(
244
+ (value) => {
245
+ clearTimeout(timer);
246
+ resolve(value);
247
+ },
248
+ (err) => {
249
+ clearTimeout(timer);
250
+ reject(err);
251
+ }
252
+ );
253
+ });
254
+ }
255
+ function createControlClient(socket, reader, opts) {
256
+ const pending = /* @__PURE__ */ new Map();
257
+ let idSeq = 0;
258
+ let closed = false;
259
+ function handleFrame(parsed) {
260
+ if (!isRecord(parsed) || typeof parsed.id !== "string") return;
261
+ const entry = pending.get(parsed.id);
262
+ if (!entry) return;
263
+ if ("event" in parsed) {
264
+ entry.onEvent?.(parsed.event);
265
+ return;
266
+ }
267
+ if (parsed.ok === true) {
268
+ pending.delete(parsed.id);
269
+ entry.resolve(parsed.done === true ? void 0 : parsed.result);
270
+ return;
271
+ }
272
+ pending.delete(parsed.id);
273
+ const shape = parsed.error;
274
+ entry.reject(
275
+ new ControlError(
276
+ typeof shape?.code === "string" ? shape.code : "internal_error",
277
+ typeof shape?.message === "string" ? shape.message : "unknown control error"
278
+ )
279
+ );
280
+ }
281
+ socket.on("data", (chunk) => {
282
+ let lines;
283
+ try {
284
+ lines = reader.push(chunk);
285
+ } catch {
286
+ socket.destroy();
287
+ return;
288
+ }
289
+ for (const line of lines) {
290
+ let parsed;
291
+ try {
292
+ parsed = JSON.parse(line);
293
+ } catch {
294
+ continue;
295
+ }
296
+ handleFrame(parsed);
297
+ }
298
+ });
299
+ socket.on("close", () => {
300
+ closed = true;
301
+ for (const entry of pending.values()) entry.reject(new Error("control connection closed"));
302
+ pending.clear();
303
+ });
304
+ socket.on("error", () => {
305
+ });
306
+ function send(method, params, onEvent) {
307
+ const id = `c${++idSeq}`;
308
+ const promise = new Promise((resolve, reject) => {
309
+ pending.set(id, { resolve, reject, onEvent });
310
+ });
311
+ socket.write(encodeFrame({ v: CONTROL_PROTOCOL_VERSION, id, method, params }));
312
+ return { id, promise };
313
+ }
314
+ return {
315
+ async request(method, params) {
316
+ if (closed) throw new Error("control connection is closed");
317
+ const { promise } = send(method, params);
318
+ const result = await withTimeout(promise, opts.requestTimeoutMs ?? 1e4, `control request "${method}" timed out`);
319
+ return result;
320
+ },
321
+ subscribe(method, params, onEvent) {
322
+ const { id, promise } = send(method, params, onEvent);
323
+ promise.catch(() => {
324
+ });
325
+ return {
326
+ close: () => {
327
+ pending.delete(id);
328
+ socket.destroy();
329
+ }
330
+ };
331
+ },
332
+ close() {
333
+ socket.destroy();
334
+ }
335
+ };
336
+ }
337
+ var AGENT_MEMORY_RECALL_TOOL_NAME = "memory.recall";
338
+ var AGENT_MEMORY_SAVE_TOOL_NAME = "memory.save";
339
+ function record(value) {
340
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
341
+ }
342
+ function invalid(id, message) {
343
+ return { jsonrpc: "2.0", id, error: { code: -32602, message } };
344
+ }
345
+ function success(id, value) {
346
+ return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: JSON.stringify(value) }] } };
347
+ }
348
+ async function handleAgentMemoryMcpRequest(request, deps) {
349
+ const id = request.id;
350
+ if (request.method === "initialize") {
351
+ const params2 = record(request.params) ?? {};
352
+ return { jsonrpc: "2.0", id, result: { protocolVersion: typeof params2.protocolVersion === "string" ? params2.protocolVersion : "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "byok-agent-memory-mcp", version: "0.0.1" } } };
353
+ }
354
+ if (request.method === "notifications/initialized") return void 0;
355
+ if (request.method === "tools/list") return {
356
+ jsonrpc: "2.0",
357
+ id,
358
+ result: { tools: [
359
+ { name: AGENT_MEMORY_RECALL_TOOL_NAME, description: "Recall one SDK-owned memory file for this exact active Agent task. Identity and memory root are never model parameters.", inputSchema: { type: "object", additionalProperties: false, required: ["path"], properties: { path: { type: "string" }, ifRevision: { type: "string", pattern: "^sha256:[a-f0-9]{64}$" } } } },
360
+ { name: AGENT_MEMORY_SAVE_TOOL_NAME, description: "Atomically replace or delete one SDK-owned memory file with exact sha256 compare-and-swap.", inputSchema: { type: "object", additionalProperties: false, required: ["op", "path", "expectedRevision"], properties: { op: { type: "string", enum: ["replace", "delete"] }, path: { type: "string" }, expectedRevision: { type: "string", pattern: "^sha256:[a-f0-9]{64}$" }, content: { type: "string" } } } }
361
+ ] }
362
+ };
363
+ if (request.method !== "tools/call") return id === void 0 ? void 0 : { jsonrpc: "2.0", id, error: { code: -32601, message: `unknown method: ${String(request.method)}` } };
364
+ const params = record(request.params);
365
+ const args = record(params?.arguments);
366
+ if (!params || !args || typeof params.name !== "string") return invalid(id, "memory tool input must be an object");
367
+ try {
368
+ if (params.name === AGENT_MEMORY_RECALL_TOOL_NAME) {
369
+ if (Object.keys(args).some((key) => key !== "path" && key !== "ifRevision") || typeof args.path !== "string" || args.ifRevision !== void 0 && typeof args.ifRevision !== "string") return invalid(id, "memory.recall accepts only path and optional ifRevision");
370
+ return success(id, await deps.recall({ path: args.path, ...args.ifRevision === void 0 ? {} : { ifRevision: args.ifRevision } }));
371
+ }
372
+ if (params.name === AGENT_MEMORY_SAVE_TOOL_NAME) {
373
+ if (Object.keys(args).some((key) => key !== "op" && key !== "path" && key !== "expectedRevision" && key !== "content") || args.op !== "replace" && args.op !== "delete" || typeof args.path !== "string" || typeof args.expectedRevision !== "string" || args.op === "replace" && typeof args.content !== "string" || args.op === "delete" && args.content !== void 0) return invalid(id, "memory.save requires replace|delete, path, expectedRevision, and content only for replace");
374
+ const content = args.content;
375
+ return success(id, await deps.save({ op: args.op, path: args.path, expectedRevision: args.expectedRevision, ...typeof content === "string" ? { content } : {} }));
376
+ }
377
+ return invalid(id, "unknown Agent memory tool");
378
+ } catch (error) {
379
+ return { jsonrpc: "2.0", id, error: { code: -32e3, message: error instanceof Error ? error.message : String(error) } };
380
+ }
381
+ }
382
+ function serveAgentMemoryMcpOverStdio(input) {
383
+ const reader = createInterface({ input: input.stdin ?? process.stdin, terminal: false });
384
+ const output = input.stdout ?? process.stdout;
385
+ reader.on("line", (line) => {
386
+ const trimmed = line.trim();
387
+ if (!trimmed) return;
388
+ void (async () => {
389
+ let request;
390
+ try {
391
+ request = JSON.parse(trimmed);
392
+ } catch {
393
+ return;
394
+ }
395
+ const response = await handleAgentMemoryMcpRequest(request, input.deps);
396
+ if (response !== void 0) output.write(`${JSON.stringify(response)}
397
+ `);
398
+ })();
399
+ });
400
+ }
401
+
402
+ // src/bin/byok-agent-memory-mcp.ts
403
+ function required(name) {
404
+ const value = process.env[name];
405
+ if (!value) throw new Error(`missing required environment variable ${name}`);
406
+ return value;
407
+ }
408
+ async function main() {
409
+ const storeDir = required("BYOK_STORE_DIR");
410
+ const productId = required("BYOK_PRODUCT_ID");
411
+ const contextToken = required("BYOK_AGENT_MEMORY_CONTEXT");
412
+ let clientPromise;
413
+ const client = async () => {
414
+ if (!clientPromise) clientPromise = connectControlClient({ storeDir, productId }).then((result) => {
415
+ if (!result.ok) throw new Error(result.reason);
416
+ return result.client;
417
+ });
418
+ return clientPromise;
419
+ };
420
+ const deps = {
421
+ recall: async (input) => (await client()).request("agent_memory.recall", { contextToken, ...input }),
422
+ save: async (input) => (await client()).request("agent_memory.save", { contextToken, ...input })
423
+ };
424
+ serveAgentMemoryMcpOverStdio({ deps });
425
+ }
426
+ main().catch((error) => {
427
+ process.stderr.write(`byok-agent-memory-mcp: ${error instanceof Error ? error.message : String(error)}
428
+ `);
429
+ process.exit(1);
430
+ });
431
+ //# sourceMappingURL=byok-agent-memory-mcp.js.map
432
+ //# sourceMappingURL=byok-agent-memory-mcp.js.map