agent-blackboard 0.8.0 → 0.9.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 (63) hide show
  1. package/dist/cli/append.mjs +11 -1
  2. package/dist/cli/index.mjs +5 -1
  3. package/dist/cli/outbox.d.mts +2 -0
  4. package/dist/cli/outbox.mjs +60 -0
  5. package/dist/cli/snapshot-partition-options.d.mts +6 -0
  6. package/dist/cli/snapshot-partition-options.mjs +25 -0
  7. package/dist/cli/snapshot.mjs +3 -12
  8. package/dist/cli/usage.d.mts +1 -1
  9. package/dist/cli/usage.mjs +7 -3
  10. package/dist/client/append.d.mts +3 -1
  11. package/dist/client/append.mjs +39 -1
  12. package/dist/client/sessions.d.mts +2 -2
  13. package/dist/client/snapshot-digest-stage.d.mts +10 -0
  14. package/dist/client/snapshot-digest-stage.mjs +33 -0
  15. package/dist/client/snapshot-digest.d.mts +43 -0
  16. package/dist/client/snapshot-digest.mjs +130 -0
  17. package/dist/client/snapshot-partition-cleanup.d.mts +1 -1
  18. package/dist/client/snapshot-partition-copy.d.mts +1 -0
  19. package/dist/client/snapshot-partition-copy.mjs +8 -0
  20. package/dist/client/snapshot-partition-format.d.mts +1 -1
  21. package/dist/client/snapshot-partition-read.d.mts +3 -2
  22. package/dist/client/snapshot-partition-read.mjs +23 -1
  23. package/dist/client/snapshot-partition-write.d.mts +8 -3
  24. package/dist/client/snapshot-partition-write.mjs +24 -23
  25. package/dist/client/snapshot-partitions.d.mts +1 -1
  26. package/dist/client/snapshot-partitions.mjs +5 -3
  27. package/dist/client/snapshot-response.d.mts +1 -1
  28. package/dist/client/snapshot-types.d.mts +113 -0
  29. package/dist/client/snapshot-types.mjs +1 -0
  30. package/dist/client/snapshots.d.mts +2 -1
  31. package/dist/client/types.d.mts +24 -84
  32. package/dist/index.d.mts +5 -1
  33. package/dist/index.mjs +2 -0
  34. package/dist/mcp/dispatch.mjs +12 -1
  35. package/dist/mcp/schemas-outbox-tools.d.mts +2 -0
  36. package/dist/mcp/schemas-outbox-tools.mjs +45 -0
  37. package/dist/mcp/schemas-snapshot-tools.d.mts +2 -0
  38. package/dist/mcp/schemas-snapshot-tools.mjs +109 -0
  39. package/dist/mcp/schemas.mjs +9 -26
  40. package/dist/mcp/tool-append.mjs +7 -1
  41. package/dist/mcp/tool-outbox.d.mts +6 -0
  42. package/dist/mcp/tool-outbox.mjs +29 -0
  43. package/dist/mcp/tool-snapshot.d.mts +7 -0
  44. package/dist/mcp/tool-snapshot.mjs +62 -1
  45. package/dist/outbox/classify.d.mts +9 -0
  46. package/dist/outbox/classify.mjs +48 -0
  47. package/dist/outbox/client.d.mts +11 -0
  48. package/dist/outbox/client.mjs +90 -0
  49. package/dist/outbox/fs.d.mts +9 -0
  50. package/dist/outbox/fs.mjs +51 -0
  51. package/dist/outbox/store.d.mts +22 -0
  52. package/dist/outbox/store.mjs +128 -0
  53. package/dist/outbox/target.d.mts +10 -0
  54. package/dist/outbox/target.mjs +21 -0
  55. package/dist/outbox/types.d.mts +72 -0
  56. package/dist/outbox/types.mjs +1 -0
  57. package/dist/plugin/.claude-mcp.json +1 -1
  58. package/dist/plugin/.codex-plugin/plugin.json +1 -1
  59. package/dist/plugin/.mcp.json +1 -1
  60. package/dist/plugin/skills/agent-blackboard/SKILL.md +26 -15
  61. package/dist/plugin/skills/distill/SKILL.md +127 -0
  62. package/dist/plugin/skills/distill/references/output-schema.md +87 -0
  63. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { extname } from 'node:path';
3
3
  import { appendEntry } from '../client/append.mjs';
4
+ import { resolveOutboxDir } from '../outbox/store.mjs';
4
5
  import { parseSchemaRef } from '../schemas/id.mjs';
5
6
  import { parseArgs, stringFlag } from './args.mjs';
6
7
  import { clientConfigFromEnv } from './env.mjs';
@@ -63,14 +64,23 @@ export async function runAppend(argv, ctx) {
63
64
  if (schemaFlag !== undefined && !parsedSchema) {
64
65
  throw new CliError(`Invalid --schema reference: ${schemaFlag}`);
65
66
  }
67
+ const sourceEventId = stringFlag(flags, 'source-event-id');
68
+ if (flags['source-event-id'] !== undefined && !sourceEventId) {
69
+ throw new CliError('append requires an id after --source-event-id.');
70
+ }
66
71
  const data = file
67
72
  ? await readFileData(file)
68
73
  : parseJsonObject(positional[0] ?? (await readStdin(ctx.stdin)));
69
- const entry = await appendEntry(clientConfigFromEnv(ctx.env, createRevisionNotifier(ctx)), {
74
+ const config = {
75
+ ...clientConfigFromEnv(ctx.env, createRevisionNotifier(ctx)),
76
+ outboxDir: resolveOutboxDir(ctx.cwd, ctx.env),
77
+ };
78
+ const entry = await appendEntry(config, {
70
79
  sessionId,
71
80
  data,
72
81
  ...(parsedSchema ? { schemaId: parsedSchema.id } : {}),
73
82
  ...(parsedSchema?.version !== undefined ? { schemaVersion: parsedSchema.version } : {}),
83
+ ...(sourceEventId !== undefined ? { sourceEventId } : {}),
74
84
  });
75
85
  writeLine(ctx.stdout, JSON.stringify(entry));
76
86
  }
@@ -8,6 +8,7 @@ import { runCredentials } from './credentials.mjs';
8
8
  import { CliError } from './errors.mjs';
9
9
  import { clientConfigFromEnv } from './env.mjs';
10
10
  import { runGet } from './get.mjs';
11
+ import { runOutbox } from './outbox.mjs';
11
12
  import { writeLine } from './output.mjs';
12
13
  import { runSchemas } from './schemas.mjs';
13
14
  import { runSessions } from './sessions.mjs';
@@ -51,6 +52,9 @@ export async function runCli(argv, options = {}) {
51
52
  case 'schemas':
52
53
  await runSchemas(rest, ctx);
53
54
  break;
55
+ case 'outbox':
56
+ await runOutbox(rest, ctx);
57
+ break;
54
58
  case 'mcp':
55
59
  await (options.startMcpServer ?? startMcpServer)(clientConfigFromEnv(ctx.env), {
56
60
  env: ctx.env,
@@ -58,7 +62,7 @@ export async function runCli(argv, options = {}) {
58
62
  });
59
63
  break;
60
64
  default:
61
- throw new CliError(`Unknown command: ${command}. Expected one of: sessions, append, get, snapshot, schemas, credentials, mcp.`);
65
+ throw new CliError(`Unknown command: ${command}. Expected one of: sessions, append, get, snapshot, schemas, outbox, credentials, mcp.`);
62
66
  }
63
67
  return 0;
64
68
  }
@@ -0,0 +1,2 @@
1
+ import type { CliContext } from './context.mjs';
2
+ export declare function runOutbox(argv: string[], ctx: CliContext): Promise<void>;
@@ -0,0 +1,60 @@
1
+ import { flushOutbox } from '../outbox/client.mjs';
2
+ import { getOutboxStatus, pruneOutboxRejected, resolveOutboxDir } from '../outbox/store.mjs';
3
+ import { parseArgs, stringFlag } from './args.mjs';
4
+ import { clientConfigFromEnv } from './env.mjs';
5
+ import { CliError } from './errors.mjs';
6
+ import { writeLine } from './output.mjs';
7
+ import { createRevisionNotifier } from './revision-notice.mjs';
8
+ function assertAllowedFlags(flags, allowed, command) {
9
+ const permitted = new Set(allowed);
10
+ for (const key of Object.keys(flags)) {
11
+ if (!permitted.has(key))
12
+ throw new CliError(`${command} does not accept --${key}.`);
13
+ }
14
+ }
15
+ function optionalFlag(flags, key, command) {
16
+ const value = stringFlag(flags, key);
17
+ if (Object.hasOwn(flags, key) && !value) {
18
+ throw new CliError(`${command} --${key} requires a value.`);
19
+ }
20
+ return value;
21
+ }
22
+ export async function runOutbox(argv, ctx) {
23
+ const [subcommand, ...rest] = argv;
24
+ if (!subcommand)
25
+ throw new CliError('outbox requires: status, flush, or prune.');
26
+ const { positional, flags } = parseArgs(rest);
27
+ if (positional.length > 0) {
28
+ throw new CliError(`outbox ${subcommand} accepts flags only.`);
29
+ }
30
+ const explicitDir = optionalFlag(flags, 'dir', `outbox ${subcommand}`);
31
+ const dir = resolveOutboxDir(ctx.cwd, ctx.env, explicitDir);
32
+ switch (subcommand) {
33
+ case 'status': {
34
+ assertAllowedFlags(flags, ['dir'], 'outbox status');
35
+ writeLine(ctx.stdout, JSON.stringify(getOutboxStatus(dir)));
36
+ return;
37
+ }
38
+ case 'flush': {
39
+ assertAllowedFlags(flags, ['dir', 'session-id'], 'outbox flush');
40
+ const sessionId = optionalFlag(flags, 'session-id', 'outbox flush');
41
+ const config = clientConfigFromEnv(ctx.env, createRevisionNotifier(ctx));
42
+ const result = await flushOutbox(config, dir, sessionId !== undefined ? { sessionId } : {});
43
+ writeLine(ctx.stdout, JSON.stringify(result));
44
+ return;
45
+ }
46
+ case 'prune': {
47
+ assertAllowedFlags(flags, ['dir', 'id', 'session-id'], 'outbox prune');
48
+ const id = optionalFlag(flags, 'id', 'outbox prune');
49
+ const sessionId = optionalFlag(flags, 'session-id', 'outbox prune');
50
+ const result = pruneOutboxRejected(dir, {
51
+ ...(id !== undefined ? { id } : {}),
52
+ ...(sessionId !== undefined ? { sessionId } : {}),
53
+ });
54
+ writeLine(ctx.stdout, JSON.stringify(result));
55
+ return;
56
+ }
57
+ default:
58
+ throw new CliError('outbox requires: status, flush, or prune.');
59
+ }
60
+ }
@@ -1,5 +1,11 @@
1
+ export declare const PARTITION_FLAGS: string[];
1
2
  type Flags = Record<string, string | boolean>;
2
3
  type OptionalString = (flags: Flags, key: string) => string | undefined;
4
+ export declare function partitionFilters(flags: Flags, optionalString: OptionalString): {
5
+ since?: string;
6
+ repository?: string;
7
+ digest?: true;
8
+ };
3
9
  export declare function partitionCounts(flags: Flags, optionalString: OptionalString): {
4
10
  sessions: number;
5
11
  entries: number;
@@ -1,4 +1,18 @@
1
1
  import { CliError } from './errors.mjs';
2
+ export const PARTITION_FLAGS = [
3
+ 'path',
4
+ 'cleanup-token',
5
+ 'max-sessions',
6
+ 'max-bytes',
7
+ 'since',
8
+ 'repository',
9
+ 'digest',
10
+ 'checksum',
11
+ 'sessions',
12
+ 'entries',
13
+ 'records',
14
+ 'bytes',
15
+ ];
2
16
  function nonNegativeInteger(raw, key) {
3
17
  if (raw === undefined)
4
18
  return undefined;
@@ -8,6 +22,17 @@ function nonNegativeInteger(raw, key) {
8
22
  }
9
23
  return value;
10
24
  }
25
+ export function partitionFilters(flags, optionalString) {
26
+ const since = optionalString(flags, 'since');
27
+ const repository = optionalString(flags, 'repository');
28
+ if (flags.digest !== undefined && flags.digest !== true)
29
+ throw new CliError('snapshot partition --digest does not accept a value.');
30
+ return {
31
+ ...(since === undefined ? {} : { since }),
32
+ ...(repository === undefined ? {} : { repository }),
33
+ ...(flags.digest === true ? { digest: true } : {}),
34
+ };
35
+ }
11
36
  export function partitionCounts(flags, optionalString) {
12
37
  const sessions = nonNegativeInteger(optionalString(flags, 'sessions'), 'sessions');
13
38
  const entries = nonNegativeInteger(optionalString(flags, 'entries'), 'entries');
@@ -7,18 +7,7 @@ import { CliError } from './errors.mjs';
7
7
  import { parseDataArrayContains } from './data-array-contains.mjs';
8
8
  import { writeLine } from './output.mjs';
9
9
  import { createRevisionNotifier } from './revision-notice.mjs';
10
- import { partitionCounts } from './snapshot-partition-options.mjs';
11
- const PARTITION_FLAGS = [
12
- 'path',
13
- 'cleanup-token',
14
- 'max-sessions',
15
- 'max-bytes',
16
- 'checksum',
17
- 'sessions',
18
- 'entries',
19
- 'records',
20
- 'bytes',
21
- ];
10
+ import { PARTITION_FLAGS, partitionCounts, partitionFilters, } from './snapshot-partition-options.mjs';
22
11
  function optionalString(flags, key, command = 'snapshot export') {
23
12
  const value = stringFlag(flags, key);
24
13
  if (Object.hasOwn(flags, key) && !value)
@@ -119,6 +108,7 @@ export async function runSnapshot(argv, ctx) {
119
108
  const maxSessions = positiveInteger(flags, 'max-sessions');
120
109
  const maxBytes = positiveInteger(flags, 'max-bytes');
121
110
  const checksum = optionalString(flags, 'checksum');
111
+ const filters = partitionFilters(flags, optionalString);
122
112
  const counts = partitionCounts(flags, optionalString);
123
113
  if (checksum !== undefined && !/^[a-f0-9]{64}$/.test(checksum)) {
124
114
  throw new CliError('snapshot partition --checksum must be a SHA-256 hex digest.');
@@ -131,6 +121,7 @@ export async function runSnapshot(argv, ctx) {
131
121
  ...(maxBytes === undefined ? {} : { maxBytes }),
132
122
  ...(checksum === undefined ? {} : { checksum: { algorithm: 'sha256', value: checksum } }),
133
123
  ...(counts === undefined ? {} : { counts }),
124
+ ...filters,
134
125
  });
135
126
  writeLine(ctx.stdout, JSON.stringify(result));
136
127
  return;
@@ -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>] [--schema <id>[@<version>]] <json>\n agent-blackboard append [--session-id <id>] [--schema <id>[@<version>]] --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 snapshot partition --path <generated-snapshot> --cleanup-token <token> [--max-sessions <count>]\n [--max-bytes <bytes>] [--checksum <sha256>] [--sessions <count> --entries <count> --records <count> --bytes <count>]\n agent-blackboard snapshot cleanup [--path <generated-snapshot>] [--directory <generated-partition-directory>] --cleanup-token <token>\n agent-blackboard schemas pull [--dir <path>]\n agent-blackboard schemas put <id> <file> [--breaking] [--shadow]\n agent-blackboard schemas promote <id>@<version>\n agent-blackboard schemas report <id>[@<version>] [--limit <n>]\n agent-blackboard schemas remove <id>\n agent-blackboard schemas list\n agent-blackboard schemas get <id>[@<version>]\n agent-blackboard schemas validate <id>[@<version>] <file> [--dir <path>]\n agent-blackboard credentials <subcommand>\n agent-blackboard mcp\n\nOmitted session ids and agents resolve from the harness environment (CLAUDE_CODE_SESSION_ID,\nCODEX_THREAD_ID, CURSOR_SESSION_ID, GROK_SESSION_ID) or <worktree>/.local/<harness>-session-id.\nInteractive root Codex: --root-codex creates or reuses the worktree id; --new-root-codex-session rotates it.\n\nEnv:\n AGENT_BLACKBOARD_URL Server base URL\n AGENT_BLACKBOARD_TOKEN Client credential\n AGENT_BLACKBOARD_ADMIN_TOKEN Admin credential\n AGENT_BLACKBOARD_SCHEMAS_DIR Optional local schema cache directory\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>] [--schema <id>[@<version>]] [--source-event-id <id>] <json>\n agent-blackboard append [--session-id <id>] [--schema <id>[@<version>]] [--source-event-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 snapshot partition --path <generated-snapshot> --cleanup-token <token> [--max-sessions <count>]\n [--max-bytes <bytes>] [--since <iso>] [--repository <owner/name>] [--digest] [--checksum <sha256>] [--sessions <count> --entries <count> --records <count> --bytes <count>]\n agent-blackboard snapshot cleanup [--path <generated-snapshot>] [--directory <generated-partition-directory>] --cleanup-token <token>\n agent-blackboard schemas pull [--dir <path>]\n agent-blackboard schemas put <id> <file> [--breaking] [--shadow]\n agent-blackboard schemas promote <id>@<version>\n agent-blackboard schemas report <id>[@<version>] [--limit <n>]\n agent-blackboard schemas remove <id>\n agent-blackboard schemas list\n agent-blackboard schemas get <id>[@<version>]\n agent-blackboard schemas validate <id>[@<version>] <file> [--dir <path>]\n agent-blackboard outbox status [--dir <path>]\n agent-blackboard outbox flush [--session-id <id>] [--dir <path>]\n agent-blackboard outbox prune [--id <id>] [--session-id <id>] [--dir <path>]\n agent-blackboard credentials <subcommand>\n agent-blackboard mcp\n\nOmitted session ids and agents resolve from the harness environment (CLAUDE_CODE_SESSION_ID,\nCODEX_THREAD_ID, CURSOR_SESSION_ID, GROK_SESSION_ID) or <worktree>/.local/<harness>-session-id.\nInteractive root Codex: --root-codex creates or reuses the worktree id; --new-root-codex-session rotates it.\n\nEnv:\n AGENT_BLACKBOARD_URL Server base URL\n AGENT_BLACKBOARD_TOKEN Client credential\n AGENT_BLACKBOARD_ADMIN_TOKEN Admin credential\n AGENT_BLACKBOARD_SCHEMAS_DIR Optional local schema cache directory\n AGENT_BLACKBOARD_OUTBOX_DIR Optional local entry outbox directory\n";
@@ -7,13 +7,13 @@ Usage:
7
7
  agent-blackboard sessions get <id>
8
8
  agent-blackboard sessions patch <id> --data <json>
9
9
  agent-blackboard sessions archive <id>
10
- agent-blackboard append [--session-id <id>] [--schema <id>[@<version>]] <json>
11
- agent-blackboard append [--session-id <id>] [--schema <id>[@<version>]] --file <json|markdown|text>
10
+ agent-blackboard append [--session-id <id>] [--schema <id>[@<version>]] [--source-event-id <id>] <json>
11
+ agent-blackboard append [--session-id <id>] [--schema <id>[@<version>]] [--source-event-id <id>] --file <json|markdown|text>
12
12
  agent-blackboard get [--session-id <id>] [--format json|jsonl|markdown]
13
13
  agent-blackboard snapshot export [--path <absolute-path>] [--agent <name>] [--version <version>]
14
14
  [--parent-session-id <id>|--root-only] [--data <json>] [--inactive-for-hours <hours>]
15
15
  agent-blackboard snapshot partition --path <generated-snapshot> --cleanup-token <token> [--max-sessions <count>]
16
- [--max-bytes <bytes>] [--checksum <sha256>] [--sessions <count> --entries <count> --records <count> --bytes <count>]
16
+ [--max-bytes <bytes>] [--since <iso>] [--repository <owner/name>] [--digest] [--checksum <sha256>] [--sessions <count> --entries <count> --records <count> --bytes <count>]
17
17
  agent-blackboard snapshot cleanup [--path <generated-snapshot>] [--directory <generated-partition-directory>] --cleanup-token <token>
18
18
  agent-blackboard schemas pull [--dir <path>]
19
19
  agent-blackboard schemas put <id> <file> [--breaking] [--shadow]
@@ -23,6 +23,9 @@ Usage:
23
23
  agent-blackboard schemas list
24
24
  agent-blackboard schemas get <id>[@<version>]
25
25
  agent-blackboard schemas validate <id>[@<version>] <file> [--dir <path>]
26
+ agent-blackboard outbox status [--dir <path>]
27
+ agent-blackboard outbox flush [--session-id <id>] [--dir <path>]
28
+ agent-blackboard outbox prune [--id <id>] [--session-id <id>] [--dir <path>]
26
29
  agent-blackboard credentials <subcommand>
27
30
  agent-blackboard mcp
28
31
 
@@ -35,4 +38,5 @@ Env:
35
38
  AGENT_BLACKBOARD_TOKEN Client credential
36
39
  AGENT_BLACKBOARD_ADMIN_TOKEN Admin credential
37
40
  AGENT_BLACKBOARD_SCHEMAS_DIR Optional local schema cache directory
41
+ AGENT_BLACKBOARD_OUTBOX_DIR Optional local entry outbox directory
38
42
  `;
@@ -1,2 +1,4 @@
1
- import type { AppendEntryInput, AppendEntryResult, ClientConfig } from './types.mjs';
1
+ import type { AppendEntryInput, AppendEntryResult, ClientConfig, StoredEntryResult } from './types.mjs';
2
+ /** Sends `POST /sessions/:id/entries` directly without outbox fallback. */
3
+ export declare function sendAppendEntry(config: ClientConfig, input: AppendEntryInput): Promise<StoredEntryResult>;
2
4
  export declare function appendEntry(config: ClientConfig, input: AppendEntryInput): Promise<AppendEntryResult>;
@@ -1,6 +1,12 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { formatError } from '../format-error.mjs';
3
+ import { isRetryableAppendError } from '../outbox/classify.mjs';
4
+ import { enqueueOutboxEntry } from '../outbox/store.mjs';
5
+ import { outboxTargetFromConfig } from '../outbox/target.mjs';
1
6
  import { requestJson } from './http.mjs';
2
7
  const JSON_HEADERS = { 'content-type': 'application/json' };
3
- export async function appendEntry(config, input) {
8
+ /** Sends `POST /sessions/:id/entries` directly without outbox fallback. */
9
+ export async function sendAppendEntry(config, input) {
4
10
  return requestJson(config, `/sessions/${encodeURIComponent(input.sessionId)}/entries`, {
5
11
  method: 'POST',
6
12
  headers: JSON_HEADERS,
@@ -8,6 +14,38 @@ export async function appendEntry(config, input) {
8
14
  data: input.data,
9
15
  ...(input.schemaId !== undefined ? { schemaId: input.schemaId } : {}),
10
16
  ...(input.schemaVersion !== undefined ? { schemaVersion: input.schemaVersion } : {}),
17
+ ...(input.sourceEventId !== undefined ? { sourceEventId: input.sourceEventId } : {}),
11
18
  }),
12
19
  });
13
20
  }
21
+ export async function appendEntry(config, input) {
22
+ // When outbox fallback is enabled, freeze the payload and bind a stable sourceEventId
23
+ // before the first POST so a stored-but-unacknowledged response deduplicates on flush.
24
+ const prepared = config.outboxDir !== undefined
25
+ ? {
26
+ ...input,
27
+ data: structuredClone(input.data),
28
+ sourceEventId: input.sourceEventId ?? `outbox-${randomUUID()}`,
29
+ }
30
+ : input;
31
+ try {
32
+ return await sendAppendEntry(config, prepared);
33
+ }
34
+ catch (error) {
35
+ if (config.outboxDir !== undefined && isRetryableAppendError(error)) {
36
+ const record = enqueueOutboxEntry(config.outboxDir, prepared, formatError(error), undefined, outboxTargetFromConfig(config));
37
+ return {
38
+ queued: true,
39
+ outboxId: record.id,
40
+ sessionId: record.sessionId,
41
+ data: record.data,
42
+ ...(record.schemaId !== undefined ? { schemaId: record.schemaId } : {}),
43
+ ...(record.schemaVersion !== undefined ? { schemaVersion: record.schemaVersion } : {}),
44
+ sourceEventId: record.sourceEventId,
45
+ queuedAt: record.queuedAt,
46
+ error: record.lastError,
47
+ };
48
+ }
49
+ throw error;
50
+ }
51
+ }
@@ -1,4 +1,4 @@
1
- import type { ClientConfig, CreateSessionInput, ListSessionsQuery, ListSessionsResult, PatchSessionInput, Session } from './types.mjs';
1
+ import type { ClientConfig, CreateSessionInput, ListSessionsQuery, ListSessionsResult, PatchSessionInput, PatchSessionResult, Session } from './types.mjs';
2
2
  export interface EnsureSessionResult {
3
3
  status: 'created' | 'exists';
4
4
  session: Session;
@@ -15,6 +15,6 @@ export declare class Sessions {
15
15
  ensure(input: CreateSessionInput): Promise<EnsureSessionResult>;
16
16
  list(query?: ListSessionsQuery): Promise<ListSessionsResult>;
17
17
  get(sessionId: string): Promise<Session>;
18
- patch(input: PatchSessionInput): Promise<Session>;
18
+ patch(input: PatchSessionInput): Promise<PatchSessionResult>;
19
19
  archive(sessionId: string): Promise<Session>;
20
20
  }
@@ -0,0 +1,10 @@
1
+ import { type SnapshotFilter } from './snapshot-digest.mjs';
2
+ import type { SnapshotBlock } from './snapshot-partition-format.mjs';
3
+ import { type Identity } from './snapshot-artifact-removal.mjs';
4
+ export interface PendingSession {
5
+ session: Record<string, unknown>;
6
+ entries: Record<string, unknown>[];
7
+ ordinal: number;
8
+ }
9
+ /** Stages one filtered session as a private block file, or returns undefined when nothing is left. */
10
+ export declare function stageFilteredSession(directory: string, directoryIdentity: Identity, pending: PendingSession, filter: SnapshotFilter): Promise<SnapshotBlock | undefined>;
@@ -0,0 +1,33 @@
1
+ import { open } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { renderSession } from './snapshot-digest.mjs';
4
+ import { writeAll } from './snapshot-partition-io.mjs';
5
+ import { assertDirectoryIdentity } from './snapshot-artifact-removal.mjs';
6
+ /** Stages one filtered session as a private block file, or returns undefined when nothing is left. */
7
+ export async function stageFilteredSession(directory, directoryIdentity, pending, filter) {
8
+ const rendered = renderSession(pending.session, pending.entries, filter);
9
+ if (!rendered)
10
+ return undefined;
11
+ const path = join(directory, `session-${pending.ordinal}.jsonl`);
12
+ const label = 'snapshot staging directory';
13
+ await assertDirectoryIdentity(directory, directoryIdentity, label);
14
+ const file = await open(path, 'wx', 0o600);
15
+ try {
16
+ await assertDirectoryIdentity(directory, directoryIdentity, label);
17
+ const bytes = Buffer.from(rendered.lines.join(''));
18
+ await writeAll(file, bytes);
19
+ await file.sync();
20
+ const identity = await file.stat({ bigint: true });
21
+ return {
22
+ sessionId: pending.session.id,
23
+ path,
24
+ identity: { dev: String(identity.dev), ino: String(identity.ino) },
25
+ bytes: bytes.byteLength,
26
+ sessions: 1,
27
+ entries: rendered.entries,
28
+ };
29
+ }
30
+ finally {
31
+ await file.close();
32
+ }
33
+ }
@@ -0,0 +1,43 @@
1
+ import type { SnapshotPartitionOptions } from './snapshot-types.mjs';
2
+ /** Validated, normalized form of the opt-in `since`, `repository`, and `digest` options. */
3
+ export interface SnapshotFilter {
4
+ since?: {
5
+ raw: string;
6
+ time: number;
7
+ };
8
+ repository?: {
9
+ raw: string;
10
+ key: string;
11
+ };
12
+ digest: boolean;
13
+ }
14
+ /** How one partition file is framed: its name prefix, optional header, and terminal line. */
15
+ export interface PartitionFormat {
16
+ prefix: string;
17
+ header: string;
18
+ trailer(counts: {
19
+ sessions: number;
20
+ entries: number;
21
+ }, manifestLine: string): string;
22
+ }
23
+ type Obj = Record<string, unknown>;
24
+ /** Returns undefined when no filtering option is set, so output stays byte-identical. */
25
+ export declare function filterFrom(options: Pick<SnapshotPartitionOptions, 'since' | 'repository' | 'digest'>): SnapshotFilter | undefined;
26
+ /**
27
+ * Renders one session as partition lines, or none when nothing is left to read. A session is
28
+ * kept only when `lastEntryAt ?? createdAt` is strictly after `since` (equal is dropped). An entry
29
+ * counts as tagged for `repository` when the entry or its session is tagged (case-insensitive);
30
+ * an untagged entry in an untagged session is dropped, and tags are never inferred. Sessions with
31
+ * no kept entries are dropped.
32
+ */
33
+ export declare function renderSession(session: Obj, entries: Obj[], filter: SnapshotFilter): {
34
+ lines: string[];
35
+ entries: number;
36
+ } | undefined;
37
+ /** True when `since` drops this session, so its entries need not be kept while staging. */
38
+ export declare function sinceExcludes(session: Obj, filter: SnapshotFilter): boolean;
39
+ /** Frames digest files (`digest-N.jsonl`); raw or unfiltered output keeps today's framing. */
40
+ export declare function formatFor(filter: SnapshotFilter | undefined): PartitionFormat;
41
+ /** Bytes the digest lines of a parsed snapshot JSONL would occupy, before partition framing. */
42
+ export declare function digestBytes(jsonl: string, options?: Pick<SnapshotPartitionOptions, 'since' | 'repository'>): number;
43
+ export {};
@@ -0,0 +1,130 @@
1
+ import { snapshotLine } from './snapshot-partition-format.mjs';
2
+ const REPOSITORY = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
3
+ /** Returns undefined when no filtering option is set, so output stays byte-identical. */
4
+ export function filterFrom(options) {
5
+ const { since, repository } = options;
6
+ const digest = options.digest === true;
7
+ if (since === undefined && repository === undefined && !digest)
8
+ return undefined;
9
+ const filter = { digest };
10
+ if (since !== undefined) {
11
+ const time = Date.parse(since);
12
+ if (!/^\d{4}-\d{2}-\d{2}T/.test(since) || !Number.isFinite(time))
13
+ throw new Error('since must be an ISO-8601 timestamp');
14
+ filter.since = { raw: since, time };
15
+ }
16
+ if (repository !== undefined) {
17
+ if (!REPOSITORY.test(repository))
18
+ throw new Error('repository must be owner/name');
19
+ filter.repository = { raw: repository, key: repository.toLowerCase() };
20
+ }
21
+ return filter;
22
+ }
23
+ function tagsOf(data) {
24
+ const tags = [];
25
+ if (Array.isArray(data.repositories))
26
+ for (const tag of data.repositories)
27
+ if (typeof tag === 'string' && tag)
28
+ tags.push(tag);
29
+ if (typeof data.repository === 'string' && data.repository)
30
+ tags.push(data.repository);
31
+ return tags;
32
+ }
33
+ function mergeTags(entry, session) {
34
+ const seen = new Set();
35
+ return [...tagsOf(entry), ...tagsOf(session)].filter((tag) => {
36
+ const key = tag.toLowerCase();
37
+ if (seen.has(key))
38
+ return false;
39
+ seen.add(key);
40
+ return true;
41
+ });
42
+ }
43
+ /**
44
+ * Renders one session as partition lines, or none when nothing is left to read. A session is
45
+ * kept only when `lastEntryAt ?? createdAt` is strictly after `since` (equal is dropped). An entry
46
+ * counts as tagged for `repository` when the entry or its session is tagged (case-insensitive);
47
+ * an untagged entry in an untagged session is dropped, and tags are never inferred. Sessions with
48
+ * no kept entries are dropped.
49
+ */
50
+ export function renderSession(session, entries, filter) {
51
+ if (sinceExcludes(session, filter))
52
+ return undefined;
53
+ const kept = entries
54
+ .map((entry) => ({ entry, tags: mergeTags(entry.data, session.data) }))
55
+ .filter(({ tags }) => !filter.repository || tags.some((tag) => tag.toLowerCase() === filter.repository.key));
56
+ if (kept.length === 0)
57
+ return undefined;
58
+ const sessionTags = mergeTags({}, session.data);
59
+ const lines = filter.digest
60
+ ? [
61
+ snapshotLine({
62
+ type: 'session',
63
+ sessionId: session.id,
64
+ parentSessionId: session.parentSessionId,
65
+ agent: session.agent,
66
+ lastEntryAt: session.lastEntryAt ?? null,
67
+ repositories: sessionTags.length > 0 ? sessionTags : null,
68
+ }),
69
+ ...kept.map(({ entry }) => snapshotLine({
70
+ createdAt: entry.createdAt,
71
+ ...(typeof entry.schemaId === 'string' ? { schemaId: entry.schemaId } : {}),
72
+ data: entry.data,
73
+ })),
74
+ ]
75
+ : [
76
+ snapshotLine({ type: 'session', session }),
77
+ ...kept.map(({ entry }) => snapshotLine({ type: 'entry', entry })),
78
+ ];
79
+ return { lines, entries: kept.length };
80
+ }
81
+ /** True when `since` drops this session, so its entries need not be kept while staging. */
82
+ export function sinceExcludes(session, filter) {
83
+ if (!filter.since)
84
+ return false;
85
+ const last = (session.lastEntryAt ?? session.createdAt);
86
+ return !(Date.parse(last) > filter.since.time);
87
+ }
88
+ /** Frames digest files (`digest-N.jsonl`); raw or unfiltered output keeps today's framing. */
89
+ export function formatFor(filter) {
90
+ if (!filter?.digest)
91
+ return { prefix: 'partition', header: '', trailer: (_counts, manifestLine) => manifestLine };
92
+ return {
93
+ prefix: 'digest',
94
+ header: snapshotLine({
95
+ type: 'digest',
96
+ format: 1,
97
+ since: filter.since?.raw ?? null,
98
+ repository: filter.repository?.raw ?? null,
99
+ }),
100
+ trailer: ({ sessions, entries }) => snapshotLine({ type: 'digest-summary', sessions, entries }),
101
+ };
102
+ }
103
+ /** Bytes the digest lines of a parsed snapshot JSONL would occupy, before partition framing. */
104
+ export function digestBytes(jsonl, options = {}) {
105
+ const filter = filterFrom({ ...options, digest: true });
106
+ let total = 0;
107
+ let session;
108
+ let entries = [];
109
+ const flush = () => {
110
+ if (!session)
111
+ return;
112
+ const rendered = renderSession(session, entries, filter);
113
+ for (const line of rendered?.lines ?? [])
114
+ total += Buffer.byteLength(line);
115
+ };
116
+ for (const line of jsonl.split('\n')) {
117
+ if (!line)
118
+ continue;
119
+ const record = JSON.parse(line);
120
+ if (record.type === 'session') {
121
+ flush();
122
+ session = record.session;
123
+ entries = [];
124
+ }
125
+ else if (record.type === 'entry')
126
+ entries.push(record.entry);
127
+ }
128
+ flush();
129
+ return total;
130
+ }
@@ -1,3 +1,3 @@
1
- import type { SnapshotCleanupOptions } from './types.mjs';
1
+ import type { SnapshotCleanupOptions } from './snapshot-types.mjs';
2
2
  /** Removes generated snapshot and/or partition evidence using an explicit capability. */
3
3
  export declare function cleanupSnapshotPartitions(options: SnapshotCleanupOptions): Promise<void>;
@@ -14,5 +14,6 @@ export type ExactFileIdentity = {
14
14
  size: bigint;
15
15
  };
16
16
  export declare function assertExactFile(stats: ExactFileStats, expected: ExactFileIdentity, message: string): void;
17
+ export declare function assertStagedBlockPath(block: SnapshotBlock, index: string): void;
17
18
  export declare function copyBlock(block: SnapshotBlock, output: FileHandle, hash: ReturnType<typeof createHash>): Promise<void>;
18
19
  export {};
@@ -1,6 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { constants } from 'node:fs';
3
3
  import { open } from 'node:fs/promises';
4
+ import { basename, dirname, isAbsolute, resolve } from 'node:path';
4
5
  import { writeAll } from './snapshot-partition-io.mjs';
5
6
  export function assertExactFile(stats, expected, message) {
6
7
  if (!stats.isFile() ||
@@ -10,6 +11,13 @@ export function assertExactFile(stats, expected, message) {
10
11
  stats.size !== expected.size)
11
12
  throw new Error(message);
12
13
  }
14
+ const STAGED_BLOCK_NAME = /^session-[1-9][0-9]*\.jsonl$/;
15
+ export function assertStagedBlockPath(block, index) {
16
+ if (!isAbsolute(block.path) ||
17
+ dirname(resolve(block.path)) !== dirname(resolve(index)) ||
18
+ !STAGED_BLOCK_NAME.test(basename(block.path)))
19
+ throw new Error('staged snapshot block path is invalid');
20
+ }
13
21
  export async function copyBlock(block, output, hash) {
14
22
  const input = await open(block.path, constants.O_RDONLY | constants.O_NOFOLLOW);
15
23
  const buffer = Buffer.allocUnsafe(64 * 1024);
@@ -1,4 +1,4 @@
1
- import type { SnapshotCounts, SnapshotManifest } from './types.mjs';
1
+ import type { SnapshotCounts, SnapshotManifest } from './snapshot-types.mjs';
2
2
  export type SnapshotBlock = {
3
3
  sessionId: string;
4
4
  path: string;
@@ -1,5 +1,6 @@
1
1
  import type { FileHandle } from 'node:fs/promises';
2
- import type { SnapshotManifest } from './types.mjs';
2
+ import { type SnapshotFilter } from './snapshot-digest.mjs';
3
+ import type { SnapshotManifest } from './snapshot-types.mjs';
3
4
  export interface StagedSnapshot {
4
5
  manifest: SnapshotManifest;
5
6
  bytes: number;
@@ -12,4 +13,4 @@ export interface StagedSnapshot {
12
13
  };
13
14
  }
14
15
  /** Reads source once through its opened descriptor and stages session groups privately on disk. */
15
- export declare function stageSnapshot(source: FileHandle, directory: string): Promise<StagedSnapshot>;
16
+ export declare function stageSnapshot(source: FileHandle, directory: string, filter?: SnapshotFilter): Promise<StagedSnapshot>;