agent-blackboard 0.0.0 → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jonathan Ong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -3,6 +3,9 @@
3
3
  Client library, CLI, and MCP server for [agent-blackboard](https://github.com/jonathanong/agent-blackboard).
4
4
  Requires Node 24+ and talks to a separately deployed HTTP service over `fetch`.
5
5
 
6
+ See the complete [TypeScript API reference](https://github.com/jonathanong/agent-blackboard/blob/master/docs/typescript-api.md)
7
+ for the supported public surface and tooling integration details.
8
+
6
9
  ```sh
7
10
  pnpm add agent-blackboard
8
11
  ```
@@ -16,10 +19,21 @@ const config = { baseUrl, token }
16
19
  const sessions = new Sessions(config)
17
20
  const entries = new Entries(config)
18
21
 
19
- await sessions.create({ id: 'root-123', parentSessionId: null })
20
- await sessions.create({ id: 'worker-456', parentSessionId: 'root-123' })
22
+ await sessions.create({
23
+ id: 'root-123',
24
+ parentSessionId: null,
25
+ agent: 'claude-code',
26
+ version: '1.0.13',
27
+ })
28
+ await sessions.create({
29
+ id: 'worker-456',
30
+ parentSessionId: 'root-123',
31
+ agent: 'claude-code',
32
+ version: '1.0.13',
33
+ })
34
+ await sessions.patch({ sessionId: 'worker-456', data: { branch: 'fix/retry' } })
21
35
 
22
- const entry = await entries.append({
36
+ await entries.append({
23
37
  sessionId: 'worker-456',
24
38
  data: { note: 'found a flaky retry' },
25
39
  })
@@ -28,42 +42,39 @@ for await (const current of entries.get({ sessionId: 'worker-456' })) {
28
42
  console.log(current)
29
43
  }
30
44
 
31
- await entries.patch({
32
- sessionId: entry.sessionId,
33
- createdAt: entry.createdAt,
34
- data: { pr: 7777 },
35
- })
36
-
37
45
  await sessions.archive('worker-456')
38
46
 
39
47
  const auth = new Auth({ baseUrl, adminToken })
40
48
  await auth.createCredentials({ name: 'ci-bot' })
41
49
  ```
42
50
 
43
- All session ids are caller-provided. `parentSessionId` is required and nullable. The service only
44
- generates `createdAt`/`archivedAt` timestamps. `Entries.get()` returns an
45
- `AsyncIterable<SessionEntry>` and uses incremental JSONL by default. Non-2xx responses throw
46
- `AgentBlackboardError`.
51
+ All session ids, agent names, and versions are caller-provided. `parentSessionId` is required and
52
+ nullable. The service generates `createdAt`/`lastEntryAt`/`archivedAt` timestamps.
53
+ `Entries.get()` returns an `AsyncIterable<SessionEntry>` and uses incremental JSONL by default.
54
+ Non-2xx responses throw `AgentBlackboardError`.
47
55
 
48
56
  ## CLI
49
57
 
50
58
  ```sh
51
- agent-blackboard sessions create root-123
52
- agent-blackboard sessions create worker-456 --parent-session-id root-123
59
+ agent-blackboard sessions create root-123 --agent claude-code --version 1.0.13
60
+ agent-blackboard sessions create worker-456 --parent-session-id root-123 \
61
+ --agent claude-code --version 1.0.13
62
+ agent-blackboard sessions patch worker-456 --data '{"branch":"fix/retry"}'
53
63
  agent-blackboard sessions list
64
+ agent-blackboard sessions list --inactive-for-hours 8
54
65
  agent-blackboard sessions get worker-456
55
66
  agent-blackboard append --session-id worker-456 '{"note":"investigating"}'
67
+ agent-blackboard append --session-id worker-456 --file findings.md
56
68
  agent-blackboard get --session-id worker-456 --format jsonl
57
- agent-blackboard patch --session-id worker-456 --created-at <timestamp> --data '{"pr":7777}'
58
69
  agent-blackboard sessions archive worker-456
59
70
  agent-blackboard mcp
60
71
  ```
61
72
 
62
73
  ## MCP
63
74
 
64
- The stdio MCP server exposes `session_create`, `session_archive`, `entry_append`, `entry_get`, and
65
- `entry_patch`. Every session and entry operation requires an explicit session id. Credential
66
- management remains CLI/admin-only.
75
+ The stdio MCP server exposes `session_create`, `session_ensure`, `session_search`, `session_patch`,
76
+ `session_archive`, `entry_append`, and `entry_get`. Every session and entry operation requires
77
+ explicit session ids where applicable. Credential management remains CLI/admin-only.
67
78
 
68
79
  ## Configuration
69
80
 
@@ -1,3 +1,5 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { extname } from 'node:path';
1
3
  import { appendEntry } from '../client/append.mjs';
2
4
  import { parseArgs, stringFlag } from './args.mjs';
3
5
  import { clientConfigFromEnv } from './env.mjs';
@@ -9,25 +11,55 @@ async function readStdin(stdin) {
9
11
  chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
10
12
  return Buffer.concat(chunks).toString('utf8');
11
13
  }
12
- export async function runAppend(argv, ctx) {
13
- const { positional, flags } = parseArgs(argv);
14
- const sessionId = stringFlag(flags, 'session-id');
15
- if (!sessionId)
16
- throw new CliError('append requires --session-id <id>.');
17
- const raw = positional[0] ?? (await readStdin(ctx.stdin));
14
+ function parseJsonObject(raw) {
18
15
  let data;
19
16
  try {
20
17
  data = JSON.parse(raw);
21
18
  }
22
19
  catch {
23
- throw new CliError('append expects a JSON object, either as an argument or piped via stdin.');
20
+ throw new CliError('append expects a JSON object, either as an argument, file, or stdin.');
24
21
  }
25
22
  if (typeof data !== 'object' || data === null || Array.isArray(data)) {
26
23
  throw new CliError('append expects a JSON object (not an array or primitive).');
27
24
  }
25
+ return data;
26
+ }
27
+ async function readFileData(path) {
28
+ let contents;
29
+ try {
30
+ contents = await readFile(path, 'utf8');
31
+ }
32
+ catch (error) {
33
+ throw new CliError(`could not read --file ${path}: ${String(error)}`);
34
+ }
35
+ switch (extname(path).toLowerCase()) {
36
+ case '.json':
37
+ return parseJsonObject(contents);
38
+ case '.md':
39
+ case '.markdown':
40
+ return { markdown: contents };
41
+ case '.txt':
42
+ return { text: contents };
43
+ default:
44
+ throw new CliError('--file must have a .json, .md, .markdown, or .txt extension.');
45
+ }
46
+ }
47
+ export async function runAppend(argv, ctx) {
48
+ const { positional, flags } = parseArgs(argv);
49
+ const sessionId = stringFlag(flags, 'session-id');
50
+ if (!sessionId)
51
+ throw new CliError('append requires --session-id <id>.');
52
+ const file = stringFlag(flags, 'file');
53
+ if (flags.file !== undefined && !file)
54
+ throw new CliError('append requires a path after --file.');
55
+ if (file && positional.length > 0)
56
+ throw new CliError('append accepts either --file or positional JSON, not both.');
57
+ const data = file
58
+ ? await readFileData(file)
59
+ : parseJsonObject(positional[0] ?? (await readStdin(ctx.stdin)));
28
60
  const entry = await appendEntry(clientConfigFromEnv(ctx.env), {
29
61
  sessionId,
30
- data: data,
62
+ data,
31
63
  });
32
64
  writeLine(ctx.stdout, JSON.stringify(entry));
33
65
  }
@@ -9,7 +9,6 @@ import { CliError } from './errors.mjs';
9
9
  import { clientConfigFromEnv } from './env.mjs';
10
10
  import { runGet } from './get.mjs';
11
11
  import { writeLine } from './output.mjs';
12
- import { runPatch } from './patch.mjs';
13
12
  import { runSessions } from './sessions.mjs';
14
13
  import { USAGE } from './usage.mjs';
15
14
  const HELP_COMMANDS = new Set(['help', '--help', '-h']);
@@ -37,9 +36,6 @@ export async function runCli(argv, options = {}) {
37
36
  case 'get':
38
37
  await runGet(rest, ctx);
39
38
  break;
40
- case 'patch':
41
- await runPatch(rest, ctx);
42
- break;
43
39
  case 'sessions':
44
40
  await runSessions(rest, ctx);
45
41
  break;
@@ -50,7 +46,7 @@ export async function runCli(argv, options = {}) {
50
46
  await (options.startMcpServer ?? startMcpServer)(clientConfigFromEnv(ctx.env));
51
47
  break;
52
48
  default:
53
- throw new CliError(`Unknown command: ${command}. Expected one of: sessions, append, get, patch, credentials, mcp.`);
49
+ throw new CliError(`Unknown command: ${command}. Expected one of: sessions, append, get, credentials, mcp.`);
54
50
  }
55
51
  return 0;
56
52
  }
@@ -3,20 +3,82 @@ import { parseArgs, stringFlag } from './args.mjs';
3
3
  import { clientConfigFromEnv } from './env.mjs';
4
4
  import { CliError } from './errors.mjs';
5
5
  import { writeLine } from './output.mjs';
6
+ /** Shared by `create` and `ensure`, which take identical flags. */
7
+ function parseCreateSessionInput(subcommand, positional, flags) {
8
+ const id = positional[0];
9
+ if (!id)
10
+ throw new CliError(`sessions ${subcommand} requires <session-id>.`);
11
+ const parentFlag = stringFlag(flags, 'parent-session-id');
12
+ if (Object.hasOwn(flags, 'parent-session-id') && !parentFlag) {
13
+ throw new CliError(`sessions ${subcommand} --parent-session-id requires <session-id>.`);
14
+ }
15
+ const agent = stringFlag(flags, 'agent');
16
+ const version = stringFlag(flags, 'version');
17
+ if (!agent)
18
+ throw new CliError(`sessions ${subcommand} requires --agent <name>.`);
19
+ if (!version)
20
+ throw new CliError(`sessions ${subcommand} requires --version <version>.`);
21
+ return { id, parentSessionId: parentFlag ?? null, agent, version };
22
+ }
6
23
  export async function runSessions(argv, ctx) {
7
24
  const [subcommand, ...rest] = argv;
8
25
  const { positional, flags } = parseArgs(rest);
9
26
  const sessions = new Sessions(clientConfigFromEnv(ctx.env));
10
27
  if (subcommand === 'create') {
11
- const id = positional[0];
12
- if (!id)
13
- throw new CliError('sessions create requires <session-id>.');
14
- const parentSessionId = stringFlag(flags, 'parent-session-id') ?? null;
15
- writeLine(ctx.stdout, JSON.stringify(await sessions.create({ id, parentSessionId })));
28
+ const input = parseCreateSessionInput('create', positional, flags);
29
+ writeLine(ctx.stdout, JSON.stringify(await sessions.create(input)));
30
+ return;
31
+ }
32
+ if (subcommand === 'ensure') {
33
+ const input = parseCreateSessionInput('ensure', positional, flags);
34
+ writeLine(ctx.stdout, JSON.stringify(await sessions.ensure(input)));
16
35
  return;
17
36
  }
18
37
  if (subcommand === 'list') {
19
- writeLine(ctx.stdout, JSON.stringify(await sessions.list()));
38
+ const archivedFlag = stringFlag(flags, 'archived');
39
+ if (archivedFlag !== undefined && archivedFlag !== 'true' && archivedFlag !== 'false') {
40
+ throw new CliError('sessions list --archived must be true or false.');
41
+ }
42
+ const inactiveForHoursFlag = stringFlag(flags, 'inactive-for-hours');
43
+ const inactiveForHours = inactiveForHoursFlag === undefined ? undefined : Number(inactiveForHoursFlag);
44
+ if (inactiveForHours !== undefined &&
45
+ (!Number.isFinite(inactiveForHours) || inactiveForHours <= 0)) {
46
+ throw new CliError('sessions list --inactive-for-hours must be a positive number.');
47
+ }
48
+ const limitFlag = stringFlag(flags, 'limit');
49
+ if (Object.hasOwn(flags, 'limit') && limitFlag === undefined) {
50
+ throw new CliError('sessions list --limit requires <n>.');
51
+ }
52
+ const limit = limitFlag === undefined ? undefined : Number(limitFlag);
53
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1)) {
54
+ throw new CliError('sessions list --limit must be a positive integer.');
55
+ }
56
+ const query = {
57
+ ...(archivedFlag === undefined ? {} : { archived: archivedFlag === 'true' }),
58
+ ...(inactiveForHours === undefined ? {} : { inactiveForHours }),
59
+ };
60
+ if (limit !== undefined) {
61
+ // `--limit` fetches a single bounded page instead of the full drain below —
62
+ // for a cheap connectivity probe (e.g. a health check) that only needs to
63
+ // confirm the call succeeds. The store applies filters after the page limit,
64
+ // so this page can be shorter than `n` (even empty) while more matching
65
+ // sessions exist further in the table — do not treat this as a reliable
66
+ // existence or count check.
67
+ const page = await sessions.list({ ...query, limit });
68
+ writeLine(ctx.stdout, JSON.stringify(page.sessions));
69
+ return;
70
+ }
71
+ // The CLI's stdout contract is a flat JSON array (pre-pagination shape) —
72
+ // drain every page here rather than surfacing cursors, so scripts piping
73
+ // `sessions list` output don't need to know pagination exists.
74
+ const all = [];
75
+ let cursor;
76
+ do {
77
+ const page = await sessions.list(cursor === undefined ? query : { ...query, cursor });
78
+ all.push(...page.sessions);
79
+ cursor = page.nextCursor ?? undefined;
80
+ } while (cursor !== undefined);
81
+ writeLine(ctx.stdout, JSON.stringify(all));
20
82
  return;
21
83
  }
22
84
  const id = positional[0];
@@ -30,5 +92,25 @@ export async function runSessions(argv, ctx) {
30
92
  writeLine(ctx.stdout, JSON.stringify(await sessions.archive(id)));
31
93
  return;
32
94
  }
33
- throw new CliError('sessions requires one of: create, list, get, archive.');
95
+ if (subcommand === 'patch') {
96
+ const raw = stringFlag(flags, 'data');
97
+ if (!raw)
98
+ throw new CliError('sessions patch requires --data <json>.');
99
+ let data;
100
+ try {
101
+ data = JSON.parse(raw);
102
+ }
103
+ catch {
104
+ throw new CliError('--data must be a JSON object.');
105
+ }
106
+ if (typeof data !== 'object' ||
107
+ data === null ||
108
+ Array.isArray(data) ||
109
+ Object.keys(data).length === 0) {
110
+ throw new CliError('--data must be a non-empty JSON object.');
111
+ }
112
+ writeLine(ctx.stdout, JSON.stringify(await sessions.patch({ sessionId: id, data: data })));
113
+ return;
114
+ }
115
+ throw new CliError('sessions requires one of: create, ensure, list, get, patch, archive.');
34
116
  }
@@ -1 +1 @@
1
- export declare const USAGE = "agent-blackboard \u2014 an entry stream for autonomous agents\n\nUsage:\n agent-blackboard sessions create <id> [--parent-session-id <id>]\n agent-blackboard sessions list\n agent-blackboard sessions get <id>\n agent-blackboard sessions archive <id>\n agent-blackboard append --session-id <id> <json>\n agent-blackboard get --session-id <id> [--format json|jsonl|markdown]\n agent-blackboard patch --session-id <id> --created-at <timestamp> --data <json>\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 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,13 +1,15 @@
1
1
  export const USAGE = `agent-blackboard — an entry stream for autonomous agents
2
2
 
3
3
  Usage:
4
- agent-blackboard sessions create <id> [--parent-session-id <id>]
5
- agent-blackboard sessions list
4
+ agent-blackboard sessions create <id> --agent <name> --version <version> [--parent-session-id <id>]
5
+ agent-blackboard sessions ensure <id> --agent <name> --version <version> [--parent-session-id <id>]
6
+ agent-blackboard sessions list [--archived true|false] [--inactive-for-hours <hours>]
6
7
  agent-blackboard sessions get <id>
8
+ agent-blackboard sessions patch <id> --data <json>
7
9
  agent-blackboard sessions archive <id>
8
10
  agent-blackboard append --session-id <id> <json>
11
+ agent-blackboard append --session-id <id> --file <json|markdown|text>
9
12
  agent-blackboard get --session-id <id> [--format json|jsonl|markdown]
10
- agent-blackboard patch --session-id <id> --created-at <timestamp> --data <json>
11
13
  agent-blackboard credentials <subcommand>
12
14
  agent-blackboard mcp
13
15
 
@@ -1,8 +1,7 @@
1
- import type { AppendEntryInput, ClientConfig, GetEntriesQuery, PatchEntryInput, SessionEntry } from './types.mjs';
1
+ import type { AppendEntryInput, ClientConfig, GetEntriesQuery, SessionEntry } from './types.mjs';
2
2
  export declare class Entries {
3
3
  #private;
4
4
  constructor(config: ClientConfig);
5
5
  append(input: AppendEntryInput): Promise<SessionEntry>;
6
6
  get(query: GetEntriesQuery): AsyncIterable<SessionEntry>;
7
- patch(input: PatchEntryInput): Promise<SessionEntry>;
8
7
  }
@@ -1,5 +1,4 @@
1
1
  import { appendEntry } from './append.mjs';
2
- import { patchEntry } from './patch.mjs';
3
2
  import { streamEntries } from './stream.mjs';
4
3
  export class Entries {
5
4
  #config;
@@ -12,7 +11,4 @@ export class Entries {
12
11
  get(query) {
13
12
  return streamEntries(this.#config, query);
14
13
  }
15
- patch(input) {
16
- return patchEntry(this.#config, input);
17
- }
18
14
  }
@@ -1,9 +1,20 @@
1
- import type { ClientConfig, CreateSessionInput, Session } from './types.mjs';
1
+ import type { ClientConfig, CreateSessionInput, ListSessionsQuery, ListSessionsResult, PatchSessionInput, Session } from './types.mjs';
2
+ export interface EnsureSessionResult {
3
+ status: 'created' | 'exists';
4
+ session: Session;
5
+ }
2
6
  export declare class Sessions {
3
7
  #private;
4
8
  constructor(config: ClientConfig);
5
9
  create(input: CreateSessionInput): Promise<Session>;
6
- list(): Promise<Session[]>;
10
+ /**
11
+ * Idempotent `create`: a 409 (session already exists) is treated as success
12
+ * only when the existing session's `parentSessionId`/`agent`/`version` match
13
+ * `input` exactly; any other mismatch or error propagates.
14
+ */
15
+ ensure(input: CreateSessionInput): Promise<EnsureSessionResult>;
16
+ list(query?: ListSessionsQuery): Promise<ListSessionsResult>;
7
17
  get(sessionId: string): Promise<Session>;
18
+ patch(input: PatchSessionInput): Promise<Session>;
8
19
  archive(sessionId: string): Promise<Session>;
9
20
  }
@@ -1,5 +1,42 @@
1
+ import { AgentBlackboardError } from './errors.mjs';
1
2
  import { requestJson } from './http.mjs';
2
3
  const JSON_HEADERS = { 'content-type': 'application/json' };
4
+ /** Fields compared against an existing session when a `create` conflicts. */
5
+ const COMPARED_FIELDS = ['parentSessionId', 'agent', 'version'];
6
+ function fieldMismatches(input, existing) {
7
+ const mismatches = [];
8
+ for (const field of COMPARED_FIELDS) {
9
+ const expected = input[field] ?? null;
10
+ const actual = existing[field] ?? null;
11
+ if (expected !== actual) {
12
+ mismatches.push(`${field}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
13
+ }
14
+ }
15
+ return mismatches;
16
+ }
17
+ /** Converts a typed `listSessions` query into wire-format string params. */
18
+ function buildListSessionsQuery(query) {
19
+ const wire = {};
20
+ if (query.archived !== undefined)
21
+ wire.archived = String(query.archived);
22
+ if (query.agent !== undefined)
23
+ wire.agent = query.agent;
24
+ if (query.version !== undefined)
25
+ wire.version = query.version;
26
+ if (query.parentSessionId !== undefined) {
27
+ wire.parentSessionId = query.parentSessionId ?? '';
28
+ }
29
+ if (query.data !== undefined)
30
+ wire.data = JSON.stringify(query.data);
31
+ if (query.inactiveForHours !== undefined) {
32
+ wire.inactiveForHours = String(query.inactiveForHours);
33
+ }
34
+ if (query.limit !== undefined)
35
+ wire.limit = String(query.limit);
36
+ if (query.cursor !== undefined)
37
+ wire.cursor = query.cursor;
38
+ return wire;
39
+ }
3
40
  export class Sessions {
4
41
  #config;
5
42
  constructor(config) {
@@ -12,14 +49,45 @@ export class Sessions {
12
49
  body: JSON.stringify(input),
13
50
  });
14
51
  }
15
- list() {
16
- return requestJson(this.#config, '/sessions', { method: 'GET' });
52
+ /**
53
+ * Idempotent `create`: a 409 (session already exists) is treated as success
54
+ * only when the existing session's `parentSessionId`/`agent`/`version` match
55
+ * `input` exactly; any other mismatch or error propagates.
56
+ */
57
+ async ensure(input) {
58
+ try {
59
+ const session = await this.create(input);
60
+ return { status: 'created', session };
61
+ }
62
+ catch (error) {
63
+ if (!(error instanceof AgentBlackboardError) || error.status !== 409)
64
+ throw error;
65
+ const existing = await this.get(input.id);
66
+ const mismatches = fieldMismatches(input, existing);
67
+ if (mismatches.length > 0) {
68
+ throw new Error(`session ${input.id} exists with different fields: ${mismatches.join('; ')}`);
69
+ }
70
+ return { status: 'exists', session: existing };
71
+ }
72
+ }
73
+ list(query = {}) {
74
+ return requestJson(this.#config, '/sessions', {
75
+ method: 'GET',
76
+ query: buildListSessionsQuery(query),
77
+ });
17
78
  }
18
79
  get(sessionId) {
19
80
  return requestJson(this.#config, `/sessions/${encodeURIComponent(sessionId)}`, {
20
81
  method: 'GET',
21
82
  });
22
83
  }
84
+ patch(input) {
85
+ return requestJson(this.#config, `/sessions/${encodeURIComponent(input.sessionId)}`, {
86
+ method: 'PATCH',
87
+ headers: JSON_HEADERS,
88
+ body: JSON.stringify({ data: input.data }),
89
+ });
90
+ }
23
91
  archive(sessionId) {
24
92
  return requestJson(this.#config, `/sessions/${encodeURIComponent(sessionId)}`, {
25
93
  method: 'PATCH',
@@ -5,8 +5,12 @@ export interface ClientConfig {
5
5
  export interface Session {
6
6
  id: string;
7
7
  parentSessionId: string | null;
8
+ agent: string;
9
+ version: string;
8
10
  createdAt: string;
11
+ lastEntryAt: string | null;
9
12
  archivedAt: string | null;
13
+ data: Record<string, unknown>;
10
14
  }
11
15
  export interface SessionEntry {
12
16
  sessionId: string;
@@ -16,14 +20,37 @@ export interface SessionEntry {
16
20
  export interface CreateSessionInput {
17
21
  id: string;
18
22
  parentSessionId: string | null;
23
+ agent: string;
24
+ version: string;
19
25
  }
20
- export interface AppendEntryInput {
26
+ export interface PatchSessionInput {
21
27
  sessionId: string;
22
28
  data: Record<string, unknown>;
23
29
  }
24
- export interface PatchEntryInput {
30
+ /**
31
+ * Duplicated independently from `packages/server`'s `ListSessionsQuery`
32
+ * rather than imported/re-exported: dependency-cruiser forbids
33
+ * `agent-blackboard` from depending on `packages/server` or `@aws-sdk` at
34
+ * all, so the wire contract for `GET /sessions` is intentionally maintained
35
+ * in both places. Keep this shape in sync with
36
+ * `packages/server/src/store/store.mts`'s `ListSessionsQuery` by hand.
37
+ */
38
+ export interface ListSessionsQuery {
39
+ archived?: boolean;
40
+ agent?: string;
41
+ version?: string;
42
+ parentSessionId?: string | null;
43
+ data?: Record<string, unknown>;
44
+ inactiveForHours?: number;
45
+ limit?: number;
46
+ cursor?: string;
47
+ }
48
+ export interface ListSessionsResult {
49
+ sessions: Session[];
50
+ nextCursor: string | null;
51
+ }
52
+ export interface AppendEntryInput {
25
53
  sessionId: string;
26
- createdAt: string;
27
54
  data: Record<string, unknown>;
28
55
  }
29
56
  export type EntryWireFormat = 'json' | 'jsonl' | 'markdown';
package/dist/index.d.mts CHANGED
@@ -3,7 +3,7 @@
3
3
  * agent-blackboard HTTP service.
4
4
  *
5
5
  * - `Sessions` — explicit session lifecycle and parent relationships.
6
- * - `Entries` — append/read/patch entries using caller-supplied session ids.
6
+ * - `Entries` — append/read entries using caller-supplied session ids.
7
7
  * - `Auth` — admin-only credential management.
8
8
  *
9
9
  * This module must never import `@aws-sdk/*` or anything from
@@ -14,4 +14,4 @@ export type { AuthOptions } from './client/auth.mjs';
14
14
  export { AgentBlackboardError } from './client/errors.mjs';
15
15
  export { Entries } from './client/entries.mjs';
16
16
  export { Sessions } from './client/sessions.mjs';
17
- export type { AppendEntryInput, ClientConfig, CreateSessionInput, CredentialCreated, CredentialSummary, EntryWireFormat, GetEntriesQuery, GetRawEntriesQuery, PatchEntryInput, Session, SessionEntry, StructuredEntryFormat, } from './client/types.mjs';
17
+ export type { AppendEntryInput, ClientConfig, CreateSessionInput, CredentialCreated, CredentialSummary, EntryWireFormat, GetEntriesQuery, GetRawEntriesQuery, ListSessionsQuery, PatchSessionInput, Session, SessionEntry, StructuredEntryFormat, } from './client/types.mjs';
package/dist/index.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  * agent-blackboard HTTP service.
4
4
  *
5
5
  * - `Sessions` — explicit session lifecycle and parent relationships.
6
- * - `Entries` — append/read/patch entries using caller-supplied session ids.
6
+ * - `Entries` — append/read entries using caller-supplied session ids.
7
7
  * - `Auth` — admin-only credential management.
8
8
  *
9
9
  * This module must never import `@aws-sdk/*` or anything from
@@ -1,19 +1,22 @@
1
1
  import { handleEntryAppend } from './tool-append.mjs';
2
2
  import { handleEntryGet } from './tool-get.mjs';
3
- import { handleEntryPatch } from './tool-patch.mjs';
4
- import { handleSessionArchive, handleSessionCreate } from './tool-sessions.mjs';
3
+ import { handleSessionArchive, handleSessionCreate, handleSessionEnsure, handleSessionPatch, handleSessionSearch, } from './tool-sessions.mjs';
5
4
  export function dispatchTool(name, args, config) {
6
5
  switch (name) {
7
6
  case 'session_create':
8
7
  return handleSessionCreate(args, config);
8
+ case 'session_ensure':
9
+ return handleSessionEnsure(args, config);
9
10
  case 'session_archive':
10
11
  return handleSessionArchive(args, config);
12
+ case 'session_search':
13
+ return handleSessionSearch(args, config);
14
+ case 'session_patch':
15
+ return handleSessionPatch(args, config);
11
16
  case 'entry_append':
12
17
  return handleEntryAppend(args, config);
13
18
  case 'entry_get':
14
19
  return handleEntryGet(args, config);
15
- case 'entry_patch':
16
- return handleEntryPatch(args, config);
17
20
  default:
18
21
  throw new Error(`Unknown tool: ${name}`);
19
22
  }
@@ -14,54 +14,115 @@ export const ENTRY_TOOLS = [
14
14
  type: ['string', 'null'],
15
15
  description: 'Null for a root session; the direct parent session id for a subagent.',
16
16
  },
17
+ agent: { type: 'string', description: 'Agent name, for example claude-code.' },
18
+ version: { type: 'string', description: 'Agent version, for example 1.0.13.' },
17
19
  },
18
- required: ['sessionId', 'parentSessionId'],
20
+ required: ['sessionId', 'parentSessionId', 'agent', 'version'],
19
21
  },
20
22
  },
21
23
  {
22
- name: 'session_archive',
23
- description: 'Archives a session, preventing further entry reads and writes.',
24
+ name: 'session_ensure',
25
+ description: 'Idempotently creates a session: if it already exists, verifies parentSessionId/agent/version ' +
26
+ 'match instead of erroring, returning status "created" or "exists" either way.',
24
27
  inputSchema: {
25
28
  type: 'object',
26
- properties: { sessionId: SESSION_ID },
27
- required: ['sessionId'],
29
+ properties: {
30
+ sessionId: SESSION_ID,
31
+ parentSessionId: {
32
+ type: ['string', 'null'],
33
+ description: 'Null for a root session; the direct parent session id for a subagent.',
34
+ },
35
+ agent: { type: 'string', description: 'Agent name, for example claude-code.' },
36
+ version: { type: 'string', description: 'Agent version, for example 1.0.13.' },
37
+ },
38
+ required: ['sessionId', 'parentSessionId', 'agent', 'version'],
28
39
  },
29
40
  },
30
41
  {
31
- name: 'entry_append',
32
- description: 'Appends unstructured data to an existing active session.',
42
+ name: 'session_search',
43
+ description: 'Searches undistilled or archived sessions using exact metadata, data, and inactivity filters. Returns ' +
44
+ 'one page at a time via limit/cursor; page until nextCursor is null for the complete ' +
45
+ 'result set.',
46
+ inputSchema: {
47
+ type: 'object',
48
+ properties: {
49
+ archived: {
50
+ type: 'integer',
51
+ enum: [0, 1],
52
+ description: '0 or omitted searches undistilled sessions; 1 searches archived sessions.',
53
+ },
54
+ sessionId: { type: 'string', description: 'Exact session id to match.' },
55
+ parentSessionId: {
56
+ type: ['string', 'null'],
57
+ description: 'Exact parent id to match; null matches root sessions.',
58
+ },
59
+ agent: { type: 'string', description: 'Exact agent name to match.' },
60
+ version: { type: 'string', description: 'Exact agent version to match.' },
61
+ data: {
62
+ type: 'object',
63
+ description: 'Top-level data fields whose JSON values must match exactly.',
64
+ },
65
+ inactiveForHours: {
66
+ type: 'number',
67
+ exclusiveMinimum: 0,
68
+ description: 'Matches sessions whose last entry is strictly older than this many hours; sessions without entries do not match.',
69
+ },
70
+ limit: {
71
+ type: 'integer',
72
+ minimum: 1,
73
+ maximum: 200,
74
+ description: 'Max sessions per page (server default 50, hard max 200 — see MAX_SESSIONS_LIMIT in packages/server/src/store/store.mts).',
75
+ },
76
+ cursor: {
77
+ type: 'string',
78
+ description: "Opaque cursor from a previous call's nextCursor. Omit to fetch the first page.",
79
+ },
80
+ },
81
+ },
82
+ },
83
+ {
84
+ name: 'session_patch',
85
+ description: 'Shallow-merges arbitrary data into one unarchived session.',
33
86
  inputSchema: {
34
87
  type: 'object',
35
88
  properties: {
36
89
  sessionId: SESSION_ID,
37
- data: { type: 'object', description: 'Unstructured JSON payload.' },
90
+ data: { type: 'object', description: 'Non-empty session data to shallow-merge.' },
38
91
  },
39
92
  required: ['sessionId', 'data'],
40
93
  },
41
94
  },
42
95
  {
43
- name: 'entry_get',
44
- description: 'Reads entries from one existing active session.',
96
+ name: 'session_archive',
97
+ description: 'Marks a session as distilled. Metadata becomes immutable, but entries remain appendable.',
98
+ inputSchema: {
99
+ type: 'object',
100
+ properties: { sessionId: SESSION_ID },
101
+ required: ['sessionId'],
102
+ },
103
+ },
104
+ {
105
+ name: 'entry_append',
106
+ description: 'Appends unstructured data to an existing session, including an archived one.',
45
107
  inputSchema: {
46
108
  type: 'object',
47
109
  properties: {
48
110
  sessionId: SESSION_ID,
49
- format: { type: 'string', enum: ['json', 'jsonl'] },
111
+ data: { type: 'object', description: 'Unstructured JSON payload.' },
50
112
  },
51
- required: ['sessionId'],
113
+ required: ['sessionId', 'data'],
52
114
  },
53
115
  },
54
116
  {
55
- name: 'entry_patch',
56
- description: 'Shallow-merges data into one timestamp-addressed session entry.',
117
+ name: 'entry_get',
118
+ description: 'Reads entries from one existing session.',
57
119
  inputSchema: {
58
120
  type: 'object',
59
121
  properties: {
60
122
  sessionId: SESSION_ID,
61
- createdAt: { type: 'string', description: 'The entry timestamp returned by entry_append.' },
62
- data: { type: 'object', description: 'Non-empty data to shallow-merge.' },
123
+ format: { type: 'string', enum: ['json', 'jsonl'] },
63
124
  },
64
- required: ['sessionId', 'createdAt', 'data'],
125
+ required: ['sessionId'],
65
126
  },
66
127
  },
67
128
  ];
@@ -1,3 +1,10 @@
1
1
  import type { ClientConfig, Session } from '../client/types.mjs';
2
+ import type { EnsureSessionResult } from '../client/sessions.mjs';
3
+ export declare function handleSessionSearch(args: Record<string, unknown>, config: ClientConfig, now?: Date): Promise<{
4
+ sessions: Session[];
5
+ nextCursor: string | null;
6
+ }>;
2
7
  export declare function handleSessionCreate(args: Record<string, unknown>, config: ClientConfig): Promise<Session>;
8
+ export declare function handleSessionEnsure(args: Record<string, unknown>, config: ClientConfig): Promise<EnsureSessionResult>;
9
+ export declare function handleSessionPatch(args: Record<string, unknown>, config: ClientConfig): Promise<Session>;
3
10
  export declare function handleSessionArchive(args: Record<string, unknown>, config: ClientConfig): Promise<Session>;
@@ -1,9 +1,115 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { AgentBlackboardError } from '../client/errors.mjs';
1
3
  import { Sessions } from '../client/sessions.mjs';
2
- import { nullableString, requiredString } from './validate.mjs';
3
- export function handleSessionCreate(args, config) {
4
- return new Sessions(config).create({
4
+ import { expectObject, nullableString, optionalPositiveInt, optionalPositiveNumber, requiredString, } from './validate.mjs';
5
+ function parseSessionSearchArgs(args) {
6
+ if (args.archived !== undefined && args.archived !== 0 && args.archived !== 1) {
7
+ throw new Error('"archived" must be 0 or 1.');
8
+ }
9
+ const hasParent = Object.hasOwn(args, 'parentSessionId');
10
+ return {
11
+ archived: args.archived === 1,
12
+ limit: optionalPositiveInt(args.limit, 'limit'),
13
+ cursor: args.cursor === undefined ? undefined : requiredString(args.cursor, 'cursor'),
14
+ hasParent,
15
+ parentSessionId: hasParent
16
+ ? nullableString(args.parentSessionId, 'parentSessionId')
17
+ : undefined,
18
+ agent: args.agent === undefined ? undefined : requiredString(args.agent, 'agent'),
19
+ version: args.version === undefined ? undefined : requiredString(args.version, 'version'),
20
+ data: args.data === undefined ? undefined : expectObject(args.data, 'data'),
21
+ inactiveForHours: optionalPositiveNumber(args.inactiveForHours, 'inactiveForHours'),
22
+ };
23
+ }
24
+ function matchesData(session, data) {
25
+ if (data === undefined)
26
+ return true;
27
+ return Object.entries(data).every(([key, value]) => isDeepStrictEqual(session.data[key], value));
28
+ }
29
+ function isInactiveFor(session, hours, now) {
30
+ if (hours === undefined)
31
+ return true;
32
+ if (session.lastEntryAt === null)
33
+ return false;
34
+ const cutoff = now.getTime() - hours * 60 * 60 * 1000;
35
+ return Date.parse(session.lastEntryAt) < cutoff;
36
+ }
37
+ /** Whether a single directly-fetched session satisfies every supplied `session_search` filter. */
38
+ function matchesDirectSession(session, parsed, now) {
39
+ if ((session.archivedAt !== null) !== parsed.archived)
40
+ return false;
41
+ if (parsed.hasParent && session.parentSessionId !== parsed.parentSessionId)
42
+ return false;
43
+ if (parsed.agent !== undefined && session.agent !== parsed.agent)
44
+ return false;
45
+ if (parsed.version !== undefined && session.version !== parsed.version)
46
+ return false;
47
+ return matchesData(session, parsed.data) && isInactiveFor(session, parsed.inactiveForHours, now);
48
+ }
49
+ /**
50
+ * `sessionId` is not a server-side `ListSessionsQuery` filter (on DynamoDB that would be a PK
51
+ * lookup disguised as a scan filter), so a `sessionId`-scoped search is a direct `Sessions.get()`
52
+ * instead of a list call, with the remaining filters applied in-process to that one session.
53
+ */
54
+ async function searchBySessionId(sessionId, config, parsed, now) {
55
+ let session;
56
+ try {
57
+ session = await new Sessions(config).get(sessionId);
58
+ }
59
+ catch (error) {
60
+ if (error instanceof AgentBlackboardError && error.status === 404)
61
+ session = null;
62
+ else
63
+ throw error;
64
+ }
65
+ const matches = session !== null && matchesDirectSession(session, parsed, now);
66
+ return { sessions: matches ? [session] : [], nextCursor: null };
67
+ }
68
+ export async function handleSessionSearch(args, config, now = new Date()) {
69
+ const parsed = parseSessionSearchArgs(args);
70
+ if (args.sessionId !== undefined) {
71
+ const sessionId = requiredString(args.sessionId, 'sessionId');
72
+ return searchBySessionId(sessionId, config, parsed, now);
73
+ }
74
+ const query = { archived: parsed.archived };
75
+ if (parsed.hasParent)
76
+ query.parentSessionId = parsed.parentSessionId ?? null;
77
+ if (parsed.agent !== undefined)
78
+ query.agent = parsed.agent;
79
+ if (parsed.version !== undefined)
80
+ query.version = parsed.version;
81
+ if (parsed.data !== undefined)
82
+ query.data = parsed.data;
83
+ if (parsed.inactiveForHours !== undefined)
84
+ query.inactiveForHours = parsed.inactiveForHours;
85
+ if (parsed.limit !== undefined)
86
+ query.limit = parsed.limit;
87
+ if (parsed.cursor !== undefined)
88
+ query.cursor = parsed.cursor;
89
+ return new Sessions(config).list(query);
90
+ }
91
+ /** Shared by `session_create` and `session_ensure`, which take identical args. */
92
+ function parseCreateSessionArgs(args) {
93
+ return {
5
94
  id: requiredString(args.sessionId, 'sessionId'),
6
95
  parentSessionId: nullableString(args.parentSessionId, 'parentSessionId'),
96
+ agent: requiredString(args.agent, 'agent'),
97
+ version: requiredString(args.version, 'version'),
98
+ };
99
+ }
100
+ export function handleSessionCreate(args, config) {
101
+ return new Sessions(config).create(parseCreateSessionArgs(args));
102
+ }
103
+ export function handleSessionEnsure(args, config) {
104
+ return new Sessions(config).ensure(parseCreateSessionArgs(args));
105
+ }
106
+ export function handleSessionPatch(args, config) {
107
+ const data = expectObject(args.data, 'data');
108
+ if (Object.keys(data).length === 0)
109
+ throw new Error('data must be a non-empty object');
110
+ return new Sessions(config).patch({
111
+ sessionId: requiredString(args.sessionId, 'sessionId'),
112
+ data,
7
113
  });
8
114
  }
9
115
  export function handleSessionArchive(args, config) {
@@ -3,3 +3,5 @@ export declare function expectObject(value: unknown, field: string): Record<stri
3
3
  export declare function requiredString(value: unknown, field: string): string;
4
4
  export declare function nullableString(value: unknown, field: string): string | null;
5
5
  export declare function optionalEntryFormat(value: unknown): StructuredEntryFormat | undefined;
6
+ export declare function optionalPositiveInt(value: unknown, field: string): number | undefined;
7
+ export declare function optionalPositiveNumber(value: unknown, field: string): number | undefined;
@@ -22,3 +22,19 @@ export function optionalEntryFormat(value) {
22
22
  return value;
23
23
  throw new Error('"format" must be "json" or "jsonl".');
24
24
  }
25
+ export function optionalPositiveInt(value, field) {
26
+ if (value === undefined)
27
+ return undefined;
28
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) {
29
+ throw new Error(`"${field}" must be a positive integer.`);
30
+ }
31
+ return value;
32
+ }
33
+ export function optionalPositiveNumber(value, field) {
34
+ if (value === undefined)
35
+ return undefined;
36
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
37
+ throw new Error(`"${field}" must be a positive number.`);
38
+ }
39
+ return value;
40
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-blackboard",
3
- "version": "0.0.0",
3
+ "version": "0.1.0",
4
4
  "description": "Client library, CLI, and MCP server for Agent Blackboard session entries.",
5
5
  "homepage": "https://github.com/jonathanong/agent-blackboard#readme",
6
6
  "bugs": {
@@ -32,15 +32,14 @@
32
32
  "publishConfig": {
33
33
  "access": "public"
34
34
  },
35
- "scripts": {
36
- "build": "node scripts/build.mjs",
37
- "prepack": "pnpm run build",
38
- "typecheck": "tsc --noEmit --project tsconfig.json"
39
- },
40
35
  "dependencies": {
41
36
  "@modelcontextprotocol/sdk": "^1.29.0"
42
37
  },
43
38
  "engines": {
44
39
  "node": ">=24.0.0"
40
+ },
41
+ "scripts": {
42
+ "build": "node scripts/build.mjs",
43
+ "typecheck": "tsc --noEmit --project tsconfig.json"
45
44
  }
46
- }
45
+ }
@@ -1,2 +0,0 @@
1
- import type { CliContext } from './context.mjs';
2
- export declare function runPatch(argv: string[], ctx: CliContext): Promise<void>;
@@ -1,33 +0,0 @@
1
- import { patchEntry } from '../client/patch.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
- export async function runPatch(argv, ctx) {
7
- const { flags } = parseArgs(argv);
8
- const sessionId = stringFlag(flags, 'session-id');
9
- const createdAt = stringFlag(flags, 'created-at');
10
- const rawData = stringFlag(flags, 'data');
11
- if (!sessionId)
12
- throw new CliError('patch requires --session-id <id>.');
13
- if (!createdAt)
14
- throw new CliError('patch requires --created-at <timestamp>.');
15
- if (!rawData)
16
- throw new CliError('patch requires --data <json>.');
17
- let data;
18
- try {
19
- data = JSON.parse(rawData);
20
- }
21
- catch {
22
- throw new CliError('--data must be a JSON object.');
23
- }
24
- if (typeof data !== 'object' || data === null || Array.isArray(data)) {
25
- throw new CliError('--data must be a JSON object.');
26
- }
27
- const entry = await patchEntry(clientConfigFromEnv(ctx.env), {
28
- sessionId,
29
- createdAt,
30
- data: data,
31
- });
32
- writeLine(ctx.stdout, JSON.stringify(entry));
33
- }
@@ -1,2 +0,0 @@
1
- import type { ClientConfig, PatchEntryInput, SessionEntry } from './types.mjs';
2
- export declare function patchEntry(config: ClientConfig, input: PatchEntryInput): Promise<SessionEntry>;
@@ -1,8 +0,0 @@
1
- import { requestJson } from './http.mjs';
2
- export async function patchEntry(config, input) {
3
- return requestJson(config, `/sessions/${encodeURIComponent(input.sessionId)}/entries`, {
4
- method: 'PATCH',
5
- headers: { 'content-type': 'application/json' },
6
- body: JSON.stringify({ createdAt: input.createdAt, data: input.data }),
7
- });
8
- }
@@ -1,2 +0,0 @@
1
- import type { ClientConfig, SessionEntry } from '../client/types.mjs';
2
- export declare function handleEntryPatch(args: Record<string, unknown>, config: ClientConfig): Promise<SessionEntry>;
@@ -1,9 +0,0 @@
1
- import { patchEntry } from '../client/patch.mjs';
2
- import { expectObject, requiredString } from './validate.mjs';
3
- export function handleEntryPatch(args, config) {
4
- return patchEntry(config, {
5
- sessionId: requiredString(args.sessionId, 'sessionId'),
6
- createdAt: requiredString(args.createdAt, 'createdAt'),
7
- data: expectObject(args.data, 'data'),
8
- });
9
- }