agent-blackboard 0.2.0 → 0.3.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.
- package/README.md +10 -2
- package/dist/cli/index.mjs +5 -1
- package/dist/cli/snapshot.d.mts +3 -0
- package/dist/cli/snapshot.mjs +76 -0
- package/dist/cli/usage.d.mts +1 -1
- package/dist/cli/usage.mjs +2 -0
- package/dist/client/http.mjs +59 -5
- package/dist/client/snapshot-response.d.mts +15 -0
- package/dist/client/snapshot-response.mjs +111 -0
- package/dist/client/snapshots.d.mts +7 -0
- package/dist/client/snapshots.mjs +82 -0
- package/dist/client/types.d.mts +55 -0
- package/dist/index.d.mts +3 -1
- package/dist/index.mjs +2 -0
- package/dist/mcp/dispatch.mjs +3 -0
- package/dist/mcp/schemas.mjs +23 -0
- package/dist/mcp/tool-snapshot.d.mts +4 -0
- package/dist/mcp/tool-snapshot.mjs +29 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -13,11 +13,12 @@ pnpm add agent-blackboard
|
|
|
13
13
|
## Library
|
|
14
14
|
|
|
15
15
|
```ts
|
|
16
|
-
import { Auth, Entries, Sessions } from 'agent-blackboard'
|
|
16
|
+
import { Auth, Entries, Sessions, Snapshots } from 'agent-blackboard'
|
|
17
17
|
|
|
18
18
|
const config = { baseUrl, token }
|
|
19
19
|
const sessions = new Sessions(config)
|
|
20
20
|
const entries = new Entries(config)
|
|
21
|
+
const snapshots = new Snapshots(config)
|
|
21
22
|
|
|
22
23
|
await sessions.create({
|
|
23
24
|
id: 'root-123',
|
|
@@ -44,6 +45,10 @@ for await (const current of entries.get({ sessionId: 'worker-456' })) {
|
|
|
44
45
|
|
|
45
46
|
await sessions.archive('worker-456')
|
|
46
47
|
|
|
48
|
+
// The JSONL file stays local; the result contains only its verification metadata.
|
|
49
|
+
const snapshot = await snapshots.export({ selection: { agent: 'claude-code' } })
|
|
50
|
+
console.log(snapshot.path, snapshot.checksum.value)
|
|
51
|
+
|
|
47
52
|
const auth = new Auth({ baseUrl, adminToken })
|
|
48
53
|
await auth.createCredentials({ name: 'ci-bot' })
|
|
49
54
|
```
|
|
@@ -70,13 +75,16 @@ agent-blackboard append --session-id worker-456 '{"note":"investigating"}'
|
|
|
70
75
|
agent-blackboard append --session-id worker-456 --file findings.md
|
|
71
76
|
agent-blackboard get --session-id worker-456 --format jsonl
|
|
72
77
|
agent-blackboard sessions archive worker-456
|
|
78
|
+
agent-blackboard snapshot export --root-only --inactive-for-hours 8
|
|
73
79
|
agent-blackboard mcp
|
|
74
80
|
```
|
|
75
81
|
|
|
76
82
|
## MCP
|
|
77
83
|
|
|
78
84
|
The stdio MCP server exposes `session_create`, `session_ensure`, `session_search`, `session_patch`,
|
|
79
|
-
`session_archive`, `entry_append`, and `
|
|
85
|
+
`session_archive`, `entry_append`, `entry_get`, and `snapshot_export`. `snapshot_export` writes a
|
|
86
|
+
private, read-only JSONL file and returns only its path, counts, checksum, and terminal manifest;
|
|
87
|
+
it never puts snapshot records on the MCP connection. Every session and entry operation requires
|
|
80
88
|
explicit session ids where applicable. Credential management remains CLI/admin-only.
|
|
81
89
|
|
|
82
90
|
## Configuration
|
package/dist/cli/index.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { clientConfigFromEnv } from './env.mjs';
|
|
|
10
10
|
import { runGet } from './get.mjs';
|
|
11
11
|
import { writeLine } from './output.mjs';
|
|
12
12
|
import { runSessions } from './sessions.mjs';
|
|
13
|
+
import { runSnapshot } from './snapshot.mjs';
|
|
13
14
|
import { USAGE } from './usage.mjs';
|
|
14
15
|
const HELP_COMMANDS = new Set(['help', '--help', '-h']);
|
|
15
16
|
/**
|
|
@@ -42,11 +43,14 @@ export async function runCli(argv, options = {}) {
|
|
|
42
43
|
case 'credentials':
|
|
43
44
|
await runCredentials(rest, ctx);
|
|
44
45
|
break;
|
|
46
|
+
case 'snapshot':
|
|
47
|
+
await runSnapshot(rest, ctx);
|
|
48
|
+
break;
|
|
45
49
|
case 'mcp':
|
|
46
50
|
await (options.startMcpServer ?? startMcpServer)(clientConfigFromEnv(ctx.env));
|
|
47
51
|
break;
|
|
48
52
|
default:
|
|
49
|
-
throw new CliError(`Unknown command: ${command}. Expected one of: sessions, append, get, credentials, mcp.`);
|
|
53
|
+
throw new CliError(`Unknown command: ${command}. Expected one of: sessions, append, get, snapshot, credentials, mcp.`);
|
|
50
54
|
}
|
|
51
55
|
return 0;
|
|
52
56
|
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { Snapshots } from '../client/snapshots.mjs';
|
|
2
|
+
import { parseArgs, stringFlag } from './args.mjs';
|
|
3
|
+
import { clientConfigFromEnv } from './env.mjs';
|
|
4
|
+
import { CliError } from './errors.mjs';
|
|
5
|
+
import { writeLine } from './output.mjs';
|
|
6
|
+
function optionalString(flags, key) {
|
|
7
|
+
const value = stringFlag(flags, key);
|
|
8
|
+
if (Object.hasOwn(flags, key) && !value)
|
|
9
|
+
throw new CliError(`snapshot export --${key} requires a value.`);
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
function parentSelection(flags) {
|
|
13
|
+
const parentSessionId = optionalString(flags, 'parent-session-id');
|
|
14
|
+
if (flags['root-only'] !== undefined && parentSessionId !== undefined) {
|
|
15
|
+
throw new CliError('snapshot export --root-only cannot be combined with --parent-session-id.');
|
|
16
|
+
}
|
|
17
|
+
if (parentSessionId !== undefined && !/^[A-Za-z0-9._:-]+$/.test(parentSessionId)) {
|
|
18
|
+
throw new CliError('snapshot export --parent-session-id is invalid.');
|
|
19
|
+
}
|
|
20
|
+
if (flags['root-only'] !== undefined)
|
|
21
|
+
return { parentSessionId: null };
|
|
22
|
+
return parentSessionId === undefined ? {} : { parentSessionId };
|
|
23
|
+
}
|
|
24
|
+
function dataSelection(flags) {
|
|
25
|
+
const rawData = optionalString(flags, 'data');
|
|
26
|
+
if (rawData === undefined)
|
|
27
|
+
return undefined;
|
|
28
|
+
try {
|
|
29
|
+
const parsed = JSON.parse(rawData);
|
|
30
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
31
|
+
throw new Error();
|
|
32
|
+
return parsed;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
throw new CliError('snapshot export --data must be a JSON object.');
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function inactivitySelection(flags) {
|
|
39
|
+
const rawHours = optionalString(flags, 'inactive-for-hours');
|
|
40
|
+
if (rawHours === undefined)
|
|
41
|
+
return undefined;
|
|
42
|
+
const hours = Number(rawHours);
|
|
43
|
+
if (!Number.isFinite(hours) || hours <= 0) {
|
|
44
|
+
throw new CliError('snapshot export --inactive-for-hours must be a positive number.');
|
|
45
|
+
}
|
|
46
|
+
return hours;
|
|
47
|
+
}
|
|
48
|
+
function selectionFrom(flags) {
|
|
49
|
+
const agent = optionalString(flags, 'agent');
|
|
50
|
+
const version = optionalString(flags, 'version');
|
|
51
|
+
const data = dataSelection(flags);
|
|
52
|
+
const inactiveForHours = inactivitySelection(flags);
|
|
53
|
+
return {
|
|
54
|
+
...(agent === undefined ? {} : { agent }),
|
|
55
|
+
...(version === undefined ? {} : { version }),
|
|
56
|
+
...parentSelection(flags),
|
|
57
|
+
...(data === undefined ? {} : { data }),
|
|
58
|
+
...(inactiveForHours === undefined ? {} : { inactiveForHours }),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** Runs `snapshot export`, keeping JSONL evidence off stdout. */
|
|
62
|
+
export async function runSnapshot(argv, ctx) {
|
|
63
|
+
const [subcommand, ...rest] = argv;
|
|
64
|
+
if (subcommand !== 'export')
|
|
65
|
+
throw new CliError('snapshot requires: export.');
|
|
66
|
+
const { positional, flags } = parseArgs(rest);
|
|
67
|
+
if (positional.length > 0)
|
|
68
|
+
throw new CliError('snapshot export accepts flags only.');
|
|
69
|
+
const path = optionalString(flags, 'path');
|
|
70
|
+
const selection = selectionFrom(flags);
|
|
71
|
+
const result = await new Snapshots(clientConfigFromEnv(ctx.env)).export({
|
|
72
|
+
...(path === undefined ? {} : { path }),
|
|
73
|
+
selection,
|
|
74
|
+
});
|
|
75
|
+
writeLine(ctx.stdout, JSON.stringify(result));
|
|
76
|
+
}
|
package/dist/cli/usage.d.mts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const USAGE = "agent-blackboard \u2014 an entry stream for autonomous agents\n\nUsage:\n agent-blackboard sessions create <id> --agent <name> --version <version> [--parent-session-id <id>]\n agent-blackboard sessions ensure <id> --agent <name> --version <version> [--parent-session-id <id>]\n agent-blackboard sessions list [--archived true|false] [--inactive-for-hours <hours>]\n agent-blackboard sessions get <id>\n agent-blackboard sessions patch <id> --data <json>\n agent-blackboard sessions archive <id>\n agent-blackboard append --session-id <id> <json>\n agent-blackboard append --session-id <id> --file <json|markdown|text>\n agent-blackboard get --session-id <id> [--format json|jsonl|markdown]\n agent-blackboard credentials <subcommand>\n agent-blackboard mcp\n\nEnv:\n AGENT_BLACKBOARD_URL Server base URL\n AGENT_BLACKBOARD_TOKEN Client credential\n AGENT_BLACKBOARD_ADMIN_TOKEN Admin credential\n";
|
|
1
|
+
export declare const USAGE = "agent-blackboard \u2014 an entry stream for autonomous agents\n\nUsage:\n agent-blackboard sessions create <id> --agent <name> --version <version> [--parent-session-id <id>]\n agent-blackboard sessions ensure <id> --agent <name> --version <version> [--parent-session-id <id>]\n agent-blackboard sessions list [--archived true|false] [--inactive-for-hours <hours>]\n agent-blackboard sessions get <id>\n agent-blackboard sessions patch <id> --data <json>\n agent-blackboard sessions archive <id>\n agent-blackboard append --session-id <id> <json>\n agent-blackboard append --session-id <id> --file <json|markdown|text>\n agent-blackboard get --session-id <id> [--format json|jsonl|markdown]\n agent-blackboard snapshot export [--path <absolute-path>] [--agent <name>] [--version <version>]\n [--parent-session-id <id>|--root-only] [--data <json>] [--inactive-for-hours <hours>]\n agent-blackboard credentials <subcommand>\n agent-blackboard mcp\n\nEnv:\n AGENT_BLACKBOARD_URL Server base URL\n AGENT_BLACKBOARD_TOKEN Client credential\n AGENT_BLACKBOARD_ADMIN_TOKEN Admin credential\n";
|
package/dist/cli/usage.mjs
CHANGED
|
@@ -10,6 +10,8 @@ Usage:
|
|
|
10
10
|
agent-blackboard append --session-id <id> <json>
|
|
11
11
|
agent-blackboard append --session-id <id> --file <json|markdown|text>
|
|
12
12
|
agent-blackboard get --session-id <id> [--format json|jsonl|markdown]
|
|
13
|
+
agent-blackboard snapshot export [--path <absolute-path>] [--agent <name>] [--version <version>]
|
|
14
|
+
[--parent-session-id <id>|--root-only] [--data <json>] [--inactive-for-hours <hours>]
|
|
13
15
|
agent-blackboard credentials <subcommand>
|
|
14
16
|
agent-blackboard mcp
|
|
15
17
|
|
package/dist/client/http.mjs
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { AgentBlackboardError } from './errors.mjs';
|
|
2
|
+
const DEFAULT_READ_RETRY = { maxRetries: 2, initialDelayMs: 100, maxDelayMs: 1000 };
|
|
3
|
+
const MAX_READ_RETRIES = 10;
|
|
4
|
+
const MAX_READ_DELAY_MS = 60_000;
|
|
5
|
+
const RETRYABLE_READ_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
|
|
2
6
|
/** Converts a typed entry query into wire-format string params. */
|
|
3
7
|
export function buildEntriesQuery(format) {
|
|
4
8
|
const wire = {};
|
|
@@ -23,6 +27,14 @@ function buildUrl(baseUrl, path, query) {
|
|
|
23
27
|
}
|
|
24
28
|
return url;
|
|
25
29
|
}
|
|
30
|
+
function assertSecureUrl(url) {
|
|
31
|
+
if (url.protocol === 'https:')
|
|
32
|
+
return;
|
|
33
|
+
if (url.protocol === 'http:' &&
|
|
34
|
+
(url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]'))
|
|
35
|
+
return;
|
|
36
|
+
throw new TypeError('baseUrl must use HTTPS; HTTP is allowed only for local loopback servers');
|
|
37
|
+
}
|
|
26
38
|
async function parseErrorBody(response) {
|
|
27
39
|
const text = await response.text();
|
|
28
40
|
if (!text)
|
|
@@ -34,6 +46,34 @@ async function parseErrorBody(response) {
|
|
|
34
46
|
return text;
|
|
35
47
|
}
|
|
36
48
|
}
|
|
49
|
+
function readRetry(config, method) {
|
|
50
|
+
if (method !== 'GET' || config.readRetry === undefined)
|
|
51
|
+
return undefined;
|
|
52
|
+
if (typeof config.readRetry !== 'object' || config.readRetry === null)
|
|
53
|
+
throw new TypeError('readRetry must be an object');
|
|
54
|
+
const options = { ...DEFAULT_READ_RETRY, ...config.readRetry };
|
|
55
|
+
for (const [name, value, maximum] of [
|
|
56
|
+
['maxRetries', options.maxRetries, MAX_READ_RETRIES],
|
|
57
|
+
['initialDelayMs', options.initialDelayMs, MAX_READ_DELAY_MS],
|
|
58
|
+
['maxDelayMs', options.maxDelayMs, MAX_READ_DELAY_MS],
|
|
59
|
+
]) {
|
|
60
|
+
if (!Number.isSafeInteger(value) || value < 0 || value > maximum)
|
|
61
|
+
throw new RangeError(`${name} must be a non-negative integer no greater than ${maximum}`);
|
|
62
|
+
}
|
|
63
|
+
return options;
|
|
64
|
+
}
|
|
65
|
+
function delay(milliseconds) {
|
|
66
|
+
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
67
|
+
}
|
|
68
|
+
function retryDelay(options, attempt) {
|
|
69
|
+
return Math.min(options.initialDelayMs * 2 ** attempt, options.maxDelayMs);
|
|
70
|
+
}
|
|
71
|
+
async function errorFor(response, method, path) {
|
|
72
|
+
throw new AgentBlackboardError(`agent-blackboard request failed: ${method} ${path} -> ${response.status}`, response.status, await parseErrorBody(response));
|
|
73
|
+
}
|
|
74
|
+
async function discard(response) {
|
|
75
|
+
await response.body?.cancel().catch(() => undefined);
|
|
76
|
+
}
|
|
37
77
|
/**
|
|
38
78
|
* Issues an authenticated HTTP request and returns the raw `Response`,
|
|
39
79
|
* throwing `AgentBlackboardError` on any non-2xx status. Callers that need the
|
|
@@ -41,17 +81,31 @@ async function parseErrorBody(response) {
|
|
|
41
81
|
*/
|
|
42
82
|
export async function rawRequest(config, path, options) {
|
|
43
83
|
const url = buildUrl(config.baseUrl, path, options.query ?? {});
|
|
84
|
+
assertSecureUrl(url);
|
|
44
85
|
const headers = new Headers(options.headers);
|
|
45
86
|
headers.set('authorization', `Bearer ${config.token}`);
|
|
46
87
|
const init = { method: options.method, headers };
|
|
47
88
|
if (options.body !== undefined)
|
|
48
89
|
init.body = options.body;
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
90
|
+
const retry = readRetry(config, options.method);
|
|
91
|
+
for (let attempt = 0;; attempt++) {
|
|
92
|
+
let response;
|
|
93
|
+
try {
|
|
94
|
+
response = await fetch(url, init);
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
if (!retry || attempt === retry.maxRetries)
|
|
98
|
+
throw error;
|
|
99
|
+
await delay(retryDelay(retry, attempt));
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (response.ok)
|
|
103
|
+
return response;
|
|
104
|
+
if (!retry || attempt === retry.maxRetries || !RETRYABLE_READ_STATUSES.has(response.status))
|
|
105
|
+
return errorFor(response, options.method, path);
|
|
106
|
+
await discard(response);
|
|
107
|
+
await delay(retryDelay(retry, attempt));
|
|
53
108
|
}
|
|
54
|
-
return response;
|
|
55
109
|
}
|
|
56
110
|
/** Issues an authenticated HTTP request and parses the response body as JSON. */
|
|
57
111
|
export async function requestJson(config, path, options) {
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import type { FileHandle } from 'node:fs/promises';
|
|
3
|
+
import type { SnapshotManifest, SnapshotSelection } from './types.mjs';
|
|
4
|
+
type SnapshotState = {
|
|
5
|
+
sessions: number;
|
|
6
|
+
entries: number;
|
|
7
|
+
records: number;
|
|
8
|
+
manifest?: SnapshotManifest;
|
|
9
|
+
};
|
|
10
|
+
/** Writes and validates snapshot response records, cancelling unfinished failures. */
|
|
11
|
+
export declare function readSnapshot(response: Response, file: FileHandle, hash: ReturnType<typeof createHash>, selection: SnapshotSelection | undefined): Promise<{
|
|
12
|
+
state: SnapshotState;
|
|
13
|
+
manifest: SnapshotManifest;
|
|
14
|
+
}>;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
+
function parseLine(line) {
|
|
4
|
+
let record;
|
|
5
|
+
try {
|
|
6
|
+
record = JSON.parse(line);
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
throw new Error('snapshot contains invalid JSONL');
|
|
10
|
+
}
|
|
11
|
+
if (!record || typeof record !== 'object' || !('type' in record)) {
|
|
12
|
+
throw new Error('snapshot contains an invalid record');
|
|
13
|
+
}
|
|
14
|
+
return record;
|
|
15
|
+
}
|
|
16
|
+
function isObject(value) {
|
|
17
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
18
|
+
}
|
|
19
|
+
async function writeAll(file, bytes) {
|
|
20
|
+
let offset = 0;
|
|
21
|
+
while (offset < bytes.byteLength) {
|
|
22
|
+
const { bytesWritten } = await file.write(bytes, offset);
|
|
23
|
+
/* v8 ignore next -- a successful Node FileHandle write cannot make zero-byte progress */
|
|
24
|
+
if (bytesWritten === 0)
|
|
25
|
+
throw new Error('could not write snapshot file');
|
|
26
|
+
offset += bytesWritten;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function validateRecord(record, state) {
|
|
30
|
+
if (state.manifest)
|
|
31
|
+
throw new Error('snapshot contains records after its manifest');
|
|
32
|
+
if (record.type === 'session' && isObject(record.session))
|
|
33
|
+
state.sessions += 1;
|
|
34
|
+
else if (record.type === 'entry' && isObject(record.entry))
|
|
35
|
+
state.entries += 1;
|
|
36
|
+
else if (record.type === 'manifest' && isObject(record.manifest))
|
|
37
|
+
state.manifest = record.manifest;
|
|
38
|
+
else if (record.type === 'error' && typeof record.error?.code === 'string') {
|
|
39
|
+
throw new Error(`snapshot export failed: ${record.error.code}`);
|
|
40
|
+
}
|
|
41
|
+
else
|
|
42
|
+
throw new Error('snapshot contains an unsupported record');
|
|
43
|
+
state.records += 1;
|
|
44
|
+
}
|
|
45
|
+
function expectedSelection(selection) {
|
|
46
|
+
return JSON.parse(JSON.stringify({ archived: false, ...selection }));
|
|
47
|
+
}
|
|
48
|
+
function validateManifest(state, selection) {
|
|
49
|
+
const manifest = state.manifest;
|
|
50
|
+
if (!manifest || manifest.status !== 'complete' || manifest.schemaVersion !== 1) {
|
|
51
|
+
throw new Error('snapshot is missing a complete terminal manifest');
|
|
52
|
+
}
|
|
53
|
+
if (typeof manifest.createdAt !== 'string' || typeof manifest.completedAt !== 'string') {
|
|
54
|
+
throw new Error('snapshot terminal manifest is invalid');
|
|
55
|
+
}
|
|
56
|
+
const counts = manifest.counts;
|
|
57
|
+
if (counts.sessions !== state.sessions ||
|
|
58
|
+
counts.entries !== state.entries ||
|
|
59
|
+
counts.records !== state.records) {
|
|
60
|
+
throw new Error('snapshot manifest counts do not match its records');
|
|
61
|
+
}
|
|
62
|
+
if (manifest.ordering?.sessions !== 'createdAt ascending' ||
|
|
63
|
+
manifest.ordering?.entries !== 'createdAt ascending within session' ||
|
|
64
|
+
manifest.consistency !== 'best-effort' ||
|
|
65
|
+
!isDeepStrictEqual(manifest.selection, expectedSelection(selection))) {
|
|
66
|
+
throw new Error('snapshot terminal manifest is invalid');
|
|
67
|
+
}
|
|
68
|
+
return manifest;
|
|
69
|
+
}
|
|
70
|
+
/** Writes and validates snapshot response records, cancelling unfinished failures. */
|
|
71
|
+
export async function readSnapshot(response, file, hash, selection) {
|
|
72
|
+
if (!response.body)
|
|
73
|
+
throw new Error('snapshot response has no body');
|
|
74
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
75
|
+
const reader = response.body.getReader();
|
|
76
|
+
const state = { sessions: 0, entries: 0, records: 0 };
|
|
77
|
+
let pending = '';
|
|
78
|
+
let complete = false;
|
|
79
|
+
try {
|
|
80
|
+
for (;;) {
|
|
81
|
+
const { done, value } = await reader.read();
|
|
82
|
+
if (value) {
|
|
83
|
+
await writeAll(file, value);
|
|
84
|
+
hash.update(value);
|
|
85
|
+
pending += decoder.decode(value, { stream: true });
|
|
86
|
+
const lines = pending.split('\n');
|
|
87
|
+
pending = lines.pop();
|
|
88
|
+
for (const line of lines)
|
|
89
|
+
if (line)
|
|
90
|
+
validateRecord(parseLine(line), state);
|
|
91
|
+
}
|
|
92
|
+
if (done)
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
pending += decoder.decode();
|
|
96
|
+
if (pending)
|
|
97
|
+
validateRecord(parseLine(pending), state);
|
|
98
|
+
const manifest = validateManifest(state, selection);
|
|
99
|
+
complete = true;
|
|
100
|
+
return { state, manifest };
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
try {
|
|
104
|
+
if (!complete)
|
|
105
|
+
await reader.cancel();
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
reader.releaseLock();
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ClientConfig, SnapshotExportOptions, SnapshotExportResult } from './types.mjs';
|
|
2
|
+
/** Streams an immutable server snapshot directly into a private local JSONL file. */
|
|
3
|
+
export declare class Snapshots {
|
|
4
|
+
#private;
|
|
5
|
+
constructor(config: ClientConfig);
|
|
6
|
+
export(options?: SnapshotExportOptions): Promise<SnapshotExportResult>;
|
|
7
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { chmod, open, rm } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { isAbsolute, join } from 'node:path';
|
|
5
|
+
import { rawRequest } from './http.mjs';
|
|
6
|
+
import { readSnapshot } from './snapshot-response.mjs';
|
|
7
|
+
function queryFor(selection = {}) {
|
|
8
|
+
const query = {};
|
|
9
|
+
if (selection.agent !== undefined)
|
|
10
|
+
query.agent = selection.agent;
|
|
11
|
+
if (selection.version !== undefined)
|
|
12
|
+
query.version = selection.version;
|
|
13
|
+
if (selection.parentSessionId !== undefined)
|
|
14
|
+
query.parentSessionId = selection.parentSessionId ?? '';
|
|
15
|
+
if (selection.data !== undefined)
|
|
16
|
+
query.data = JSON.stringify(selection.data);
|
|
17
|
+
if (selection.inactiveForHours !== undefined)
|
|
18
|
+
query.inactiveForHours = String(selection.inactiveForHours);
|
|
19
|
+
return query;
|
|
20
|
+
}
|
|
21
|
+
async function createDestination(path) {
|
|
22
|
+
if (path !== undefined) {
|
|
23
|
+
if (!isAbsolute(path))
|
|
24
|
+
throw new Error('snapshot path must be absolute');
|
|
25
|
+
try {
|
|
26
|
+
return { path, file: await open(path, 'wx', 0o600) };
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (error.code === 'EEXIST') {
|
|
30
|
+
throw new Error(`snapshot path already exists: ${path}`);
|
|
31
|
+
}
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const generated = join(tmpdir(), `agent-blackboard-snapshot-${randomUUID()}.jsonl`);
|
|
36
|
+
return { path: generated, file: await open(generated, 'wx', 0o600) };
|
|
37
|
+
}
|
|
38
|
+
/** Streams an immutable server snapshot directly into a private local JSONL file. */
|
|
39
|
+
export class Snapshots {
|
|
40
|
+
#config;
|
|
41
|
+
constructor(config) {
|
|
42
|
+
this.#config = config;
|
|
43
|
+
}
|
|
44
|
+
async export(options = {}) {
|
|
45
|
+
const target = await createDestination(options.path);
|
|
46
|
+
let file = target.file;
|
|
47
|
+
let complete = false;
|
|
48
|
+
try {
|
|
49
|
+
const response = await rawRequest(this.#config, '/snapshot', {
|
|
50
|
+
method: 'GET',
|
|
51
|
+
headers: { accept: 'application/x-ndjson' },
|
|
52
|
+
query: queryFor(options.selection),
|
|
53
|
+
});
|
|
54
|
+
const hash = createHash('sha256');
|
|
55
|
+
const { state, manifest } = await readSnapshot(response, file, hash, options.selection);
|
|
56
|
+
const info = await file.stat();
|
|
57
|
+
await file.sync();
|
|
58
|
+
await file.close();
|
|
59
|
+
file = undefined;
|
|
60
|
+
await chmod(target.path, 0o400);
|
|
61
|
+
complete = true;
|
|
62
|
+
return {
|
|
63
|
+
path: target.path,
|
|
64
|
+
counts: {
|
|
65
|
+
sessions: state.sessions,
|
|
66
|
+
entries: state.entries,
|
|
67
|
+
records: state.records,
|
|
68
|
+
bytes: info.size,
|
|
69
|
+
},
|
|
70
|
+
checksum: { algorithm: 'sha256', value: hash.digest('hex') },
|
|
71
|
+
manifest,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
/* v8 ignore next -- cleanup must still remove partial output if close itself fails */
|
|
76
|
+
if (file)
|
|
77
|
+
await file.close().catch(() => undefined);
|
|
78
|
+
if (!complete)
|
|
79
|
+
await rm(target.path, { force: true });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
package/dist/client/types.d.mts
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
export interface ClientConfig {
|
|
2
2
|
baseUrl: string;
|
|
3
3
|
token: string;
|
|
4
|
+
/** Opt in to bounded retries for safe GET requests. */
|
|
5
|
+
readRetry?: ReadRetryOptions;
|
|
6
|
+
}
|
|
7
|
+
/** Bounded retry settings for GET requests that fail before a response or transiently. */
|
|
8
|
+
export interface ReadRetryOptions {
|
|
9
|
+
/** Retries after the initial request. Defaults to 2. */
|
|
10
|
+
maxRetries?: number;
|
|
11
|
+
/** First retry delay in milliseconds. Defaults to 100. */
|
|
12
|
+
initialDelayMs?: number;
|
|
13
|
+
/** Maximum retry delay in milliseconds. Defaults to 1000. */
|
|
14
|
+
maxDelayMs?: number;
|
|
4
15
|
}
|
|
5
16
|
export interface Session {
|
|
6
17
|
id: string;
|
|
@@ -71,3 +82,47 @@ export interface CredentialSummary {
|
|
|
71
82
|
export interface CredentialCreated extends CredentialSummary {
|
|
72
83
|
token: string;
|
|
73
84
|
}
|
|
85
|
+
/** Exact filters accepted by the immutable bulk snapshot endpoint. */
|
|
86
|
+
export interface SnapshotSelection {
|
|
87
|
+
agent?: string;
|
|
88
|
+
version?: string;
|
|
89
|
+
parentSessionId?: string | null;
|
|
90
|
+
data?: Record<string, unknown>;
|
|
91
|
+
inactiveForHours?: number;
|
|
92
|
+
}
|
|
93
|
+
export interface SnapshotCounts {
|
|
94
|
+
sessions: number;
|
|
95
|
+
entries: number;
|
|
96
|
+
records: number;
|
|
97
|
+
bytes: number;
|
|
98
|
+
}
|
|
99
|
+
/** Terminal record emitted by a completed `GET /snapshot` export. */
|
|
100
|
+
export interface SnapshotManifest {
|
|
101
|
+
schemaVersion: 1;
|
|
102
|
+
status: 'complete';
|
|
103
|
+
createdAt: string;
|
|
104
|
+
completedAt: string;
|
|
105
|
+
selection: SnapshotSelection & {
|
|
106
|
+
archived: false;
|
|
107
|
+
};
|
|
108
|
+
counts: Omit<SnapshotCounts, 'bytes'>;
|
|
109
|
+
ordering: {
|
|
110
|
+
sessions: 'createdAt ascending';
|
|
111
|
+
entries: 'createdAt ascending within session';
|
|
112
|
+
};
|
|
113
|
+
consistency: 'best-effort';
|
|
114
|
+
}
|
|
115
|
+
export interface SnapshotExportOptions {
|
|
116
|
+
/** New absolute destination; omitted creates a private file under the system temp directory. */
|
|
117
|
+
path?: string;
|
|
118
|
+
selection?: SnapshotSelection;
|
|
119
|
+
}
|
|
120
|
+
export interface SnapshotExportResult {
|
|
121
|
+
path: string;
|
|
122
|
+
counts: SnapshotCounts;
|
|
123
|
+
checksum: {
|
|
124
|
+
algorithm: 'sha256';
|
|
125
|
+
value: string;
|
|
126
|
+
};
|
|
127
|
+
manifest: SnapshotManifest;
|
|
128
|
+
}
|
package/dist/index.d.mts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*
|
|
5
5
|
* - `Sessions` — explicit session lifecycle and parent relationships.
|
|
6
6
|
* - `Entries` — append/read entries using caller-supplied session ids.
|
|
7
|
+
* - `Snapshots` — file-backed bulk export with compact verified metadata.
|
|
7
8
|
* - `Auth` — admin-only credential management.
|
|
8
9
|
*
|
|
9
10
|
* This module must never import `@aws-sdk/*` or anything from
|
|
@@ -15,4 +16,5 @@ export { AgentBlackboardError } from './client/errors.mjs';
|
|
|
15
16
|
export { Entries } from './client/entries.mjs';
|
|
16
17
|
export { formatError } from './format-error.mjs';
|
|
17
18
|
export { Sessions } from './client/sessions.mjs';
|
|
18
|
-
export
|
|
19
|
+
export { Snapshots } from './client/snapshots.mjs';
|
|
20
|
+
export type { AppendEntryInput, ClientConfig, CreateSessionInput, CredentialCreated, CredentialSummary, EntryWireFormat, GetEntriesQuery, GetRawEntriesQuery, ListSessionsQuery, PatchSessionInput, ReadRetryOptions, Session, SessionEntry, StructuredEntryFormat, SnapshotCounts, SnapshotExportOptions, SnapshotExportResult, SnapshotManifest, SnapshotSelection, } from './client/types.mjs';
|
package/dist/index.mjs
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*
|
|
5
5
|
* - `Sessions` — explicit session lifecycle and parent relationships.
|
|
6
6
|
* - `Entries` — append/read entries using caller-supplied session ids.
|
|
7
|
+
* - `Snapshots` — file-backed bulk export with compact verified metadata.
|
|
7
8
|
* - `Auth` — admin-only credential management.
|
|
8
9
|
*
|
|
9
10
|
* This module must never import `@aws-sdk/*` or anything from
|
|
@@ -14,3 +15,4 @@ export { AgentBlackboardError } from './client/errors.mjs';
|
|
|
14
15
|
export { Entries } from './client/entries.mjs';
|
|
15
16
|
export { formatError } from './format-error.mjs';
|
|
16
17
|
export { Sessions } from './client/sessions.mjs';
|
|
18
|
+
export { Snapshots } from './client/snapshots.mjs';
|
package/dist/mcp/dispatch.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { handleEntryAppend } from './tool-append.mjs';
|
|
2
2
|
import { handleEntryGet } from './tool-get.mjs';
|
|
3
|
+
import { handleSnapshotExport } from './tool-snapshot.mjs';
|
|
3
4
|
import { handleSessionArchive, handleSessionCreate, handleSessionEnsure, handleSessionPatch, handleSessionSearch, } from './tool-sessions.mjs';
|
|
4
5
|
export function dispatchTool(name, args, config) {
|
|
5
6
|
switch (name) {
|
|
@@ -17,6 +18,8 @@ export function dispatchTool(name, args, config) {
|
|
|
17
18
|
return handleEntryAppend(args, config);
|
|
18
19
|
case 'entry_get':
|
|
19
20
|
return handleEntryGet(args, config);
|
|
21
|
+
case 'snapshot_export':
|
|
22
|
+
return handleSnapshotExport(args, config);
|
|
20
23
|
default:
|
|
21
24
|
throw new Error(`Unknown tool: ${name}`);
|
|
22
25
|
}
|
package/dist/mcp/schemas.mjs
CHANGED
|
@@ -3,6 +3,29 @@ const SESSION_ID = {
|
|
|
3
3
|
description: 'Caller-supplied session id. Never inferred or generated.',
|
|
4
4
|
};
|
|
5
5
|
export const ENTRY_TOOLS = [
|
|
6
|
+
{
|
|
7
|
+
name: 'snapshot_export',
|
|
8
|
+
description: 'Streams an immutable non-archived snapshot into a local private JSONL file and returns only its path, counts, checksum, and manifest.',
|
|
9
|
+
inputSchema: {
|
|
10
|
+
type: 'object',
|
|
11
|
+
properties: {
|
|
12
|
+
path: { type: 'string', description: 'Optional new absolute destination path.' },
|
|
13
|
+
agent: { type: 'string', description: 'Exact agent name to include.' },
|
|
14
|
+
version: { type: 'string', description: 'Exact agent version to include.' },
|
|
15
|
+
parentSessionId: {
|
|
16
|
+
type: ['string', 'null'],
|
|
17
|
+
pattern: '^[A-Za-z0-9._:-]+$',
|
|
18
|
+
description: 'Exact parent id; null selects root sessions.',
|
|
19
|
+
},
|
|
20
|
+
data: { type: 'object', description: 'Top-level session data fields to match exactly.' },
|
|
21
|
+
inactiveForHours: {
|
|
22
|
+
type: 'number',
|
|
23
|
+
exclusiveMinimum: 0,
|
|
24
|
+
description: 'Only sessions inactive for this many hours.',
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
},
|
|
6
29
|
{
|
|
7
30
|
name: 'session_create',
|
|
8
31
|
description: 'Creates a root or subagent session before entries are appended.',
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { Snapshots } from '../client/snapshots.mjs';
|
|
2
|
+
import type { ClientConfig } from '../client/types.mjs';
|
|
3
|
+
/** Exports a local JSONL evidence file; never returns the snapshot records through MCP. */
|
|
4
|
+
export declare function handleSnapshotExport(args: Record<string, unknown>, config: ClientConfig): ReturnType<Snapshots['export']>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Snapshots } from '../client/snapshots.mjs';
|
|
2
|
+
import { expectObject, nullableString, optionalPositiveNumber, requiredString, } from './validate.mjs';
|
|
3
|
+
function parentSessionId(value) {
|
|
4
|
+
const id = nullableString(value, 'parentSessionId');
|
|
5
|
+
if (id !== null && !/^[A-Za-z0-9._:-]+$/.test(id)) {
|
|
6
|
+
throw new Error('"parentSessionId" is invalid.');
|
|
7
|
+
}
|
|
8
|
+
return id;
|
|
9
|
+
}
|
|
10
|
+
function selectionFrom(args) {
|
|
11
|
+
const hasParent = Object.hasOwn(args, 'parentSessionId');
|
|
12
|
+
return {
|
|
13
|
+
...(args.agent === undefined ? {} : { agent: requiredString(args.agent, 'agent') }),
|
|
14
|
+
...(args.version === undefined ? {} : { version: requiredString(args.version, 'version') }),
|
|
15
|
+
...(hasParent ? { parentSessionId: parentSessionId(args.parentSessionId) } : {}),
|
|
16
|
+
...(args.data === undefined ? {} : { data: expectObject(args.data, 'data') }),
|
|
17
|
+
...(args.inactiveForHours === undefined
|
|
18
|
+
? {}
|
|
19
|
+
: { inactiveForHours: optionalPositiveNumber(args.inactiveForHours, 'inactiveForHours') }),
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/** Exports a local JSONL evidence file; never returns the snapshot records through MCP. */
|
|
23
|
+
export function handleSnapshotExport(args, config) {
|
|
24
|
+
const path = args.path === undefined ? undefined : requiredString(args.path, 'path');
|
|
25
|
+
return new Snapshots(config).export({
|
|
26
|
+
...(path === undefined ? {} : { path }),
|
|
27
|
+
selection: selectionFrom(args),
|
|
28
|
+
});
|
|
29
|
+
}
|
package/package.json
CHANGED