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
@@ -0,0 +1,109 @@
1
+ import { ADDITIVE, MUTATING } from './schema-fields.mjs';
2
+ export const SNAPSHOT_TOOLS = [
3
+ {
4
+ name: 'snapshot_export',
5
+ description: 'Streams an immutable non-archived snapshot into a local private JSONL file and returns its path, counts, checksum, manifest, and (when path is omitted) cleanupToken.',
6
+ inputSchema: {
7
+ type: 'object',
8
+ properties: {
9
+ path: { type: 'string', description: 'Optional new absolute destination path.' },
10
+ agent: { type: 'string', description: 'Exact agent name to include.' },
11
+ version: { type: 'string', description: 'Exact agent version to include.' },
12
+ parentSessionId: {
13
+ type: ['string', 'null'],
14
+ pattern: '^[A-Za-z0-9._:-]+$',
15
+ description: 'Exact parent id; null selects root sessions.',
16
+ },
17
+ data: { type: 'object', description: 'Top-level session data fields to match exactly.' },
18
+ dataArrayContains: { type: 'object', description: 'Exact string membership in arrays.' },
19
+ inactiveForHours: {
20
+ type: 'number',
21
+ exclusiveMinimum: 0,
22
+ description: 'Only sessions inactive for this many hours (createdAt if no entries).',
23
+ },
24
+ },
25
+ },
26
+ annotations: ADDITIVE,
27
+ },
28
+ {
29
+ name: 'snapshot_partition',
30
+ description: 'Splits a generated temporary snapshot JSONL file into bounded session-preserving read-only partitions using the cleanupToken from snapshot_export. A session larger than maxBytes is never split: it is left out and listed in oversized (sessionId, entries, bytes); read it alone with entry_get.',
31
+ inputSchema: {
32
+ type: 'object',
33
+ properties: {
34
+ path: {
35
+ type: 'string',
36
+ description: 'Generated temporary snapshot path returned by snapshot_export.',
37
+ },
38
+ cleanupToken: {
39
+ type: 'string',
40
+ description: 'Ownership capability returned by snapshot_export.',
41
+ },
42
+ maxSessions: {
43
+ type: 'integer',
44
+ minimum: 1,
45
+ description: 'Maximum whole sessions per partition (default 25).',
46
+ },
47
+ maxBytes: {
48
+ type: 'integer',
49
+ minimum: 1,
50
+ description: 'Maximum bytes per partition (default 1048576).',
51
+ },
52
+ since: {
53
+ type: 'string',
54
+ description: 'ISO-8601 cursor: keep only sessions whose lastEntryAt (or createdAt) is strictly after it.',
55
+ },
56
+ repository: {
57
+ type: 'string',
58
+ pattern: '^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$',
59
+ description: 'owner/name: keep only entries tagged for it (entry or session data.repositories / data.repository, case-insensitive); untagged entries are dropped.',
60
+ },
61
+ digest: {
62
+ type: 'boolean',
63
+ description: 'Write compact digest-N.jsonl files (session lines each followed by their entries) instead of raw records.',
64
+ },
65
+ checksum: {
66
+ type: 'string',
67
+ pattern: '^[a-f0-9]{64}$',
68
+ description: 'Optional SHA-256 hex digest to verify against the snapshot file.',
69
+ },
70
+ counts: {
71
+ type: 'object',
72
+ description: 'Optional exact snapshot counts to verify before partitioning.',
73
+ properties: {
74
+ sessions: { type: 'integer', minimum: 0 },
75
+ entries: { type: 'integer', minimum: 0 },
76
+ records: { type: 'integer', minimum: 0 },
77
+ bytes: { type: 'integer', minimum: 0 },
78
+ },
79
+ required: ['sessions', 'entries', 'records', 'bytes'],
80
+ },
81
+ },
82
+ required: ['path', 'cleanupToken'],
83
+ },
84
+ annotations: ADDITIVE,
85
+ },
86
+ {
87
+ name: 'snapshot_cleanup',
88
+ description: 'Removes a generated temporary snapshot file and/or partition directory using the cleanupToken from snapshot_export or snapshot_partition. Pass path, directory, or both: the token alone removes nothing and is rejected.',
89
+ inputSchema: {
90
+ type: 'object',
91
+ properties: {
92
+ path: {
93
+ type: 'string',
94
+ description: 'Generated temporary snapshot path to remove.',
95
+ },
96
+ directory: {
97
+ type: 'string',
98
+ description: 'Generated temporary partition directory to remove.',
99
+ },
100
+ cleanupToken: {
101
+ type: 'string',
102
+ description: 'Ownership capability returned by snapshot_export or snapshot_partition.',
103
+ },
104
+ },
105
+ required: ['cleanupToken'],
106
+ },
107
+ annotations: MUTATING,
108
+ },
109
+ ];
@@ -1,31 +1,9 @@
1
1
  import { ADDITIVE, AGENT, IDEMPOTENT_ADDITIVE, MUTATING, READ_ONLY, RESOLVABLE_SESSION_ID, SESSION_ID, } from './schema-fields.mjs';
2
+ import { OUTBOX_TOOLS } from './schemas-outbox-tools.mjs';
2
3
  import { SCHEMA_REGISTRY_TOOLS } from './schemas-registry-tools.mjs';
4
+ import { SNAPSHOT_TOOLS } from './schemas-snapshot-tools.mjs';
3
5
  export const ENTRY_TOOLS = [
4
- {
5
- name: 'snapshot_export',
6
- description: 'Streams an immutable non-archived snapshot into a local private JSONL file and returns only its path, counts, checksum, and manifest.',
7
- inputSchema: {
8
- type: 'object',
9
- properties: {
10
- path: { type: 'string', description: 'Optional new absolute destination path.' },
11
- agent: { type: 'string', description: 'Exact agent name to include.' },
12
- version: { type: 'string', description: 'Exact agent version to include.' },
13
- parentSessionId: {
14
- type: ['string', 'null'],
15
- pattern: '^[A-Za-z0-9._:-]+$',
16
- description: 'Exact parent id; null selects root sessions.',
17
- },
18
- data: { type: 'object', description: 'Top-level session data fields to match exactly.' },
19
- dataArrayContains: { type: 'object', description: 'Exact string membership in arrays.' },
20
- inactiveForHours: {
21
- type: 'number',
22
- exclusiveMinimum: 0,
23
- description: 'Only sessions inactive for this many hours (createdAt if no entries).',
24
- },
25
- },
26
- },
27
- annotations: ADDITIVE,
28
- },
6
+ ...SNAPSHOT_TOOLS,
29
7
  {
30
8
  name: 'session_create',
31
9
  description: 'Creates a root or subagent session before entries are appended.',
@@ -132,7 +110,7 @@ export const ENTRY_TOOLS = [
132
110
  },
133
111
  {
134
112
  name: 'entry_append',
135
- description: 'Appends an entry to an existing session, including an archived one. Optionally names a registered schemaId (and schemaVersion) for server-side validation.',
113
+ description: 'Appends an entry to an existing session, including an archived one. Optionally names a registered schemaId (and schemaVersion) for server-side validation and a per-session sourceEventId for idempotent retries.',
136
114
  inputSchema: {
137
115
  type: 'object',
138
116
  properties: {
@@ -144,6 +122,10 @@ export const ENTRY_TOOLS = [
144
122
  minimum: 1,
145
123
  description: 'Optional pinned schema version number (requires schemaId).',
146
124
  },
125
+ sourceEventId: {
126
+ type: 'string',
127
+ description: 'Optional per-session event id for idempotent writes: identical content returns the stored entry with duplicate: true; different content fails with 409.',
128
+ },
147
129
  },
148
130
  required: ['data'],
149
131
  },
@@ -161,5 +143,6 @@ export const ENTRY_TOOLS = [
161
143
  },
162
144
  annotations: READ_ONLY,
163
145
  },
146
+ ...OUTBOX_TOOLS,
164
147
  ...SCHEMA_REGISTRY_TOOLS,
165
148
  ];
@@ -1,4 +1,5 @@
1
1
  import { appendEntry } from '../client/append.mjs';
2
+ import { resolveOutboxDir } from '../outbox/store.mjs';
2
3
  import { toolSessionId } from './session-resolution.mjs';
3
4
  import { expectObject, optionalPositiveInt, requiredString } from './validate.mjs';
4
5
  export function handleEntryAppend(args, config, resolution) {
@@ -7,10 +8,15 @@ export function handleEntryAppend(args, config, resolution) {
7
8
  if (schemaVersion !== undefined && schemaId === undefined) {
8
9
  throw new Error('"schemaVersion" requires "schemaId".');
9
10
  }
10
- return appendEntry(config, {
11
+ const sourceEventId = args.sourceEventId === undefined
12
+ ? undefined
13
+ : requiredString(args.sourceEventId, 'sourceEventId');
14
+ const outboxDir = config.outboxDir ?? (resolution ? resolveOutboxDir(resolution.cwd, resolution.env) : undefined);
15
+ return appendEntry(outboxDir === undefined ? config : { ...config, outboxDir }, {
11
16
  sessionId: toolSessionId(args, resolution),
12
17
  data: expectObject(args.data, 'data'),
13
18
  ...(schemaId !== undefined ? { schemaId } : {}),
14
19
  ...(schemaVersion !== undefined ? { schemaVersion } : {}),
20
+ ...(sourceEventId !== undefined ? { sourceEventId } : {}),
15
21
  });
16
22
  }
@@ -0,0 +1,6 @@
1
+ import type { ClientConfig } from '../client/types.mjs';
2
+ import type { OutboxFlushResult, OutboxPruneResult, OutboxStatus } from '../outbox/types.mjs';
3
+ import type { SessionResolutionContext } from './session-resolution.mjs';
4
+ export declare function handleOutboxStatus(args: Record<string, unknown>, config: ClientConfig, resolution?: SessionResolutionContext): Promise<OutboxStatus>;
5
+ export declare function handleOutboxFlush(args: Record<string, unknown>, config: ClientConfig, resolution?: SessionResolutionContext): Promise<OutboxFlushResult>;
6
+ export declare function handleOutboxPruneRejected(args: Record<string, unknown>, config: ClientConfig, resolution?: SessionResolutionContext): Promise<OutboxPruneResult>;
@@ -0,0 +1,29 @@
1
+ import { Outbox } from '../outbox/client.mjs';
2
+ import { requiredString } from './validate.mjs';
3
+ function locationOptions(args, resolution) {
4
+ const dir = args.dir === undefined ? undefined : requiredString(args.dir, 'dir');
5
+ return {
6
+ ...(dir !== undefined ? { dir } : {}),
7
+ ...(resolution?.cwd !== undefined ? { cwd: resolution.cwd } : {}),
8
+ ...(resolution?.env !== undefined ? { env: resolution.env } : {}),
9
+ };
10
+ }
11
+ export async function handleOutboxStatus(args, config, resolution) {
12
+ return new Outbox(config).status(locationOptions(args, resolution));
13
+ }
14
+ export function handleOutboxFlush(args, config, resolution) {
15
+ const sessionId = args.sessionId === undefined ? undefined : requiredString(args.sessionId, 'sessionId');
16
+ return new Outbox(config).flush({
17
+ ...locationOptions(args, resolution),
18
+ ...(sessionId !== undefined ? { sessionId } : {}),
19
+ });
20
+ }
21
+ export async function handleOutboxPruneRejected(args, config, resolution) {
22
+ const id = args.id === undefined ? undefined : requiredString(args.id, 'id');
23
+ const sessionId = args.sessionId === undefined ? undefined : requiredString(args.sessionId, 'sessionId');
24
+ return new Outbox(config).pruneRejected({
25
+ ...locationOptions(args, resolution),
26
+ ...(id !== undefined ? { id } : {}),
27
+ ...(sessionId !== undefined ? { sessionId } : {}),
28
+ });
29
+ }
@@ -1,4 +1,11 @@
1
1
  import { Snapshots } from '../client/snapshots.mjs';
2
+ import type { SnapshotPartitionResult } from '../client/snapshot-types.mjs';
2
3
  import type { ClientConfig } from '../client/types.mjs';
3
4
  /** Exports a local JSONL evidence file; never returns the snapshot records through MCP. */
4
5
  export declare function handleSnapshotExport(args: Record<string, unknown>, config: ClientConfig): ReturnType<Snapshots['export']>;
6
+ /** Splits a generated temporary snapshot into bounded read-only partitions with ownership checks. */
7
+ export declare function handleSnapshotPartition(args: Record<string, unknown>): Promise<SnapshotPartitionResult>;
8
+ /** Cleans up generated temporary snapshot files and/or partition directories with ownership checks. */
9
+ export declare function handleSnapshotCleanup(args: Record<string, unknown>): Promise<{
10
+ removed: true;
11
+ }>;
@@ -1,5 +1,7 @@
1
+ import { cleanupSnapshotPartitions } from '../client/snapshot-partition-cleanup.mjs';
2
+ import { partitionSnapshot } from '../client/snapshot-partitions.mjs';
1
3
  import { Snapshots } from '../client/snapshots.mjs';
2
- import { expectObject, nullableString, optionalPositiveNumber, requiredString, } from './validate.mjs';
4
+ import { expectObject, nullableString, optionalPositiveInt, optionalPositiveNumber, requiredString, } from './validate.mjs';
3
5
  function parentSessionId(value) {
4
6
  const id = nullableString(value, 'parentSessionId');
5
7
  if (id !== null && !/^[A-Za-z0-9._:-]+$/.test(id)) {
@@ -30,6 +32,23 @@ function selectionFrom(args) {
30
32
  : { inactiveForHours: optionalPositiveNumber(args.inactiveForHours, 'inactiveForHours') }),
31
33
  };
32
34
  }
35
+ function nonNegativeInt(value, field) {
36
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
37
+ throw new Error(`"${field}" must be a non-negative integer.`);
38
+ }
39
+ return value;
40
+ }
41
+ function optionalCounts(value) {
42
+ if (value === undefined)
43
+ return undefined;
44
+ const counts = expectObject(value, 'counts');
45
+ return {
46
+ sessions: nonNegativeInt(counts.sessions, 'counts.sessions'),
47
+ entries: nonNegativeInt(counts.entries, 'counts.entries'),
48
+ records: nonNegativeInt(counts.records, 'counts.records'),
49
+ bytes: nonNegativeInt(counts.bytes, 'counts.bytes'),
50
+ };
51
+ }
33
52
  /** Exports a local JSONL evidence file; never returns the snapshot records through MCP. */
34
53
  export function handleSnapshotExport(args, config) {
35
54
  const path = args.path === undefined ? undefined : requiredString(args.path, 'path');
@@ -38,3 +57,45 @@ export function handleSnapshotExport(args, config) {
38
57
  selection: selectionFrom(args),
39
58
  });
40
59
  }
60
+ /** Splits a generated temporary snapshot into bounded read-only partitions with ownership checks. */
61
+ export function handleSnapshotPartition(args) {
62
+ const path = requiredString(args.path, 'path');
63
+ const cleanupToken = requiredString(args.cleanupToken, 'cleanupToken');
64
+ const maxSessions = optionalPositiveInt(args.maxSessions, 'maxSessions');
65
+ const maxBytes = optionalPositiveInt(args.maxBytes, 'maxBytes');
66
+ const checksum = args.checksum === undefined ? undefined : requiredString(args.checksum, 'checksum');
67
+ if (checksum !== undefined && !/^[a-f0-9]{64}$/.test(checksum)) {
68
+ throw new Error('"checksum" must be a SHA-256 hex digest.');
69
+ }
70
+ const counts = optionalCounts(args.counts);
71
+ const since = args.since === undefined ? undefined : requiredString(args.since, 'since');
72
+ const repository = args.repository === undefined ? undefined : requiredString(args.repository, 'repository');
73
+ if (args.digest !== undefined && typeof args.digest !== 'boolean')
74
+ throw new Error('"digest" must be a boolean.');
75
+ return partitionSnapshot({
76
+ path,
77
+ cleanupToken,
78
+ ...(maxSessions === undefined ? {} : { maxSessions }),
79
+ ...(maxBytes === undefined ? {} : { maxBytes }),
80
+ ...(checksum === undefined ? {} : { checksum: { algorithm: 'sha256', value: checksum } }),
81
+ ...(counts === undefined ? {} : { counts }),
82
+ ...(since === undefined ? {} : { since }),
83
+ ...(repository === undefined ? {} : { repository }),
84
+ ...(args.digest === undefined ? {} : { digest: args.digest }),
85
+ });
86
+ }
87
+ /** Cleans up generated temporary snapshot files and/or partition directories with ownership checks. */
88
+ export async function handleSnapshotCleanup(args) {
89
+ const path = args.path === undefined ? undefined : requiredString(args.path, 'path');
90
+ const directory = args.directory === undefined ? undefined : requiredString(args.directory, 'directory');
91
+ if (!path && !directory) {
92
+ throw new Error('"snapshot_cleanup" requires "path" or "directory".');
93
+ }
94
+ const cleanupToken = requiredString(args.cleanupToken, 'cleanupToken');
95
+ await cleanupSnapshotPartitions({
96
+ ...(path === undefined ? {} : { path }),
97
+ ...(directory === undefined ? {} : { directory }),
98
+ cleanupToken,
99
+ });
100
+ return { removed: true };
101
+ }
@@ -0,0 +1,9 @@
1
+ import { AgentBlackboardError } from '../client/errors.mjs';
2
+ /**
3
+ * Returns true when an `entry_append` failure is a transport/network failure or a retryable
4
+ * HTTP status (`401`, `408`, `429`, `5xx`), meaning the entry should be buffered in the outbox.
5
+ * Configuration and serialization errors (such as invalid URLs) return false and throw immediately.
6
+ */
7
+ export declare function isRetryableAppendError(error: unknown): boolean;
8
+ /** Returns true when the server permanently rejected the entry (non-retryable 4xx). */
9
+ export declare function isPermanentRejection(error: unknown): error is AgentBlackboardError;
@@ -0,0 +1,48 @@
1
+ import { AgentBlackboardError } from '../client/errors.mjs';
2
+ const RETRYABLE_APPEND_STATUSES = new Set([401, 408, 429]);
3
+ const NETWORK_ERROR_CODES = new Set([
4
+ 'ECONNREFUSED',
5
+ 'ECONNRESET',
6
+ 'ETIMEDOUT',
7
+ 'ENOTFOUND',
8
+ 'EAI_AGAIN',
9
+ 'EHOSTUNREACH',
10
+ 'ENETUNREACH',
11
+ 'EPIPE',
12
+ ]);
13
+ function isTransportCode(code) {
14
+ return typeof code === 'string' && (NETWORK_ERROR_CODES.has(code) || code.startsWith('UND_ERR_'));
15
+ }
16
+ function isTransportError(error) {
17
+ if (!(error instanceof Error))
18
+ return false;
19
+ if (error.name === 'AbortError' || error.name === 'TimeoutError')
20
+ return true;
21
+ if (isTransportCode(error.code))
22
+ return true;
23
+ if (error instanceof TypeError && error.message === 'fetch failed')
24
+ return true;
25
+ const cause = error.cause;
26
+ if (cause instanceof Error && isTransportCode(cause.code)) {
27
+ return true;
28
+ }
29
+ return false;
30
+ }
31
+ /**
32
+ * Returns true when an `entry_append` failure is a transport/network failure or a retryable
33
+ * HTTP status (`401`, `408`, `429`, `5xx`), meaning the entry should be buffered in the outbox.
34
+ * Configuration and serialization errors (such as invalid URLs) return false and throw immediately.
35
+ */
36
+ export function isRetryableAppendError(error) {
37
+ if (error instanceof AgentBlackboardError) {
38
+ return error.status >= 500 || RETRYABLE_APPEND_STATUSES.has(error.status);
39
+ }
40
+ return isTransportError(error);
41
+ }
42
+ /** Returns true when the server permanently rejected the entry (non-retryable 4xx). */
43
+ export function isPermanentRejection(error) {
44
+ return (error instanceof AgentBlackboardError &&
45
+ error.status >= 400 &&
46
+ error.status < 500 &&
47
+ !RETRYABLE_APPEND_STATUSES.has(error.status));
48
+ }
@@ -0,0 +1,11 @@
1
+ import type { ClientConfig } from '../client/types.mjs';
2
+ import type { OutboxFlushOptions, OutboxFlushResult, OutboxLocationOptions, OutboxPruneOptions, OutboxPruneResult, OutboxStatus } from './types.mjs';
3
+ /** Delivers pending entries from `dir`, moving permanent 4xx rejections aside so they do not block. */
4
+ export declare function flushOutbox(config: ClientConfig, dir: string, options?: Pick<OutboxFlushOptions, 'sessionId'>): Promise<OutboxFlushResult>;
5
+ export declare class Outbox {
6
+ #private;
7
+ constructor(config: ClientConfig);
8
+ status(options?: OutboxLocationOptions): OutboxStatus;
9
+ flush(options?: OutboxFlushOptions): Promise<OutboxFlushResult>;
10
+ pruneRejected(options?: OutboxPruneOptions): OutboxPruneResult;
11
+ }
@@ -0,0 +1,90 @@
1
+ import { sendAppendEntry } from '../client/append.mjs';
2
+ import { formatError } from '../format-error.mjs';
3
+ import { isPermanentRejection } from './classify.mjs';
4
+ import { getOutboxStatus, movePendingToRejected, pruneOutboxRejected, readOutboxPending, removePendingRecord, resolveOutboxDir, updatePendingError, } from './store.mjs';
5
+ import { matchesOutboxTarget, outboxTargetFromConfig } from './target.mjs';
6
+ function targetDir(config, options = {}) {
7
+ const explicitDir = options.dir ?? config.outboxDir;
8
+ return resolveOutboxDir(options.cwd ?? process.cwd(), options.env ?? {}, explicitDir);
9
+ }
10
+ /** Delivers pending entries from `dir`, moving permanent 4xx rejections aside so they do not block. */
11
+ export async function flushOutbox(config, dir, options = {}) {
12
+ const allPending = readOutboxPending(dir);
13
+ const items = options.sessionId === undefined
14
+ ? allPending
15
+ : allPending.filter(({ record }) => record.sessionId === options.sessionId);
16
+ const currentTarget = outboxTargetFromConfig(config);
17
+ let delivered = 0;
18
+ let duplicates = 0;
19
+ let rejected = 0;
20
+ let skipped = 0;
21
+ let remaining = 0;
22
+ for (let index = 0; index < items.length; index += 1) {
23
+ const { fileName, record } = items[index];
24
+ if (!matchesOutboxTarget(record.target, currentTarget)) {
25
+ skipped += 1;
26
+ continue;
27
+ }
28
+ try {
29
+ const result = await sendAppendEntry(config, {
30
+ sessionId: record.sessionId,
31
+ data: record.data,
32
+ ...(record.schemaId !== undefined ? { schemaId: record.schemaId } : {}),
33
+ ...(record.schemaVersion !== undefined ? { schemaVersion: record.schemaVersion } : {}),
34
+ sourceEventId: record.sourceEventId,
35
+ });
36
+ removePendingRecord(dir, fileName);
37
+ delivered += 1;
38
+ if (result.duplicate)
39
+ duplicates += 1;
40
+ }
41
+ catch (error) {
42
+ if (isPermanentRejection(error)) {
43
+ movePendingToRejected(dir, fileName, record, {
44
+ status: error.status,
45
+ error: formatError(error),
46
+ errorBody: error.body,
47
+ });
48
+ rejected += 1;
49
+ continue;
50
+ }
51
+ updatePendingError(dir, fileName, record, formatError(error));
52
+ remaining = skipped + (items.length - index);
53
+ return {
54
+ dir,
55
+ delivered,
56
+ duplicates,
57
+ rejected,
58
+ ...(skipped > 0 ? { skipped } : {}),
59
+ remaining,
60
+ };
61
+ }
62
+ }
63
+ remaining = skipped;
64
+ return {
65
+ dir,
66
+ delivered,
67
+ duplicates,
68
+ rejected,
69
+ ...(skipped > 0 ? { skipped } : {}),
70
+ remaining,
71
+ };
72
+ }
73
+ export class Outbox {
74
+ #config;
75
+ constructor(config) {
76
+ this.#config = config;
77
+ }
78
+ status(options = {}) {
79
+ return getOutboxStatus(targetDir(this.#config, options));
80
+ }
81
+ flush(options = {}) {
82
+ return flushOutbox(this.#config, targetDir(this.#config, options), options.sessionId !== undefined ? { sessionId: options.sessionId } : {});
83
+ }
84
+ pruneRejected(options = {}) {
85
+ return pruneOutboxRejected(targetDir(this.#config, options), {
86
+ ...(options.id !== undefined ? { id: options.id } : {}),
87
+ ...(options.sessionId !== undefined ? { sessionId: options.sessionId } : {}),
88
+ });
89
+ }
90
+ }
@@ -0,0 +1,9 @@
1
+ export declare function writeJsonAtomic(targetPath: string, payload: unknown): void;
2
+ export interface ReadRecordsResult<T> {
3
+ records: Array<{
4
+ fileName: string;
5
+ record: T;
6
+ }>;
7
+ corruptFiles: string[];
8
+ }
9
+ export declare function readValidatedRecords<T>(dir: string, isValid: (value: unknown) => value is T): ReadRecordsResult<T>;
@@ -0,0 +1,51 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ export function writeJsonAtomic(targetPath, payload) {
5
+ mkdirSync(dirname(targetPath), { recursive: true, mode: 0o700 });
6
+ const temp = `${targetPath}.${process.pid}.${randomUUID()}.tmp`;
7
+ try {
8
+ writeFileSync(temp, `${JSON.stringify(payload, null, 2)}\n`, {
9
+ encoding: 'utf8',
10
+ flag: 'wx',
11
+ mode: 0o600,
12
+ });
13
+ renameSync(temp, targetPath);
14
+ }
15
+ catch (error) {
16
+ rmSync(temp, { force: true });
17
+ throw error;
18
+ }
19
+ }
20
+ function listJsonFiles(dir) {
21
+ try {
22
+ return readdirSync(dir)
23
+ .filter((name) => name.endsWith('.json'))
24
+ .sort();
25
+ }
26
+ catch (error) {
27
+ if (error.code === 'ENOENT')
28
+ return [];
29
+ throw error;
30
+ }
31
+ }
32
+ export function readValidatedRecords(dir, isValid) {
33
+ const records = [];
34
+ const corruptFiles = [];
35
+ for (const fileName of listJsonFiles(dir)) {
36
+ const fullPath = join(dir, fileName);
37
+ try {
38
+ const parsed = JSON.parse(readFileSync(fullPath, 'utf8'));
39
+ if (isValid(parsed)) {
40
+ records.push({ fileName, record: parsed });
41
+ }
42
+ else {
43
+ corruptFiles.push(fullPath);
44
+ }
45
+ }
46
+ catch {
47
+ corruptFiles.push(fullPath);
48
+ }
49
+ }
50
+ return { records, corruptFiles };
51
+ }
@@ -0,0 +1,22 @@
1
+ import type { AppendEntryInput } from '../client/types.mjs';
2
+ import type { OutboxPendingRecord, OutboxPruneOptions, OutboxPruneResult, OutboxRejectedRecord, OutboxStatus, OutboxTarget } from './types.mjs';
3
+ export declare const DEFAULT_OUTBOX_RELATIVE = ".local/agent-blackboard/outbox";
4
+ /** Resolves the worktree-scoped or overridden local outbox directory. */
5
+ export declare function resolveOutboxDir(cwd: string, env: NodeJS.ProcessEnv, explicitDir?: string): string;
6
+ /** Appends a failed entry write into `<dir>/pending/` atomically. */
7
+ export declare function enqueueOutboxEntry(dir: string, input: AppendEntryInput, lastError: string, now?: () => Date, target?: OutboxTarget): OutboxPendingRecord;
8
+ export declare function readOutboxPending(dir: string): Array<{
9
+ fileName: string;
10
+ record: OutboxPendingRecord;
11
+ }>;
12
+ export declare function updatePendingError(dir: string, fileName: string, record: OutboxPendingRecord, lastError: string): void;
13
+ export declare function removePendingRecord(dir: string, fileName: string): void;
14
+ export declare function movePendingToRejected(dir: string, fileName: string, record: OutboxPendingRecord, rejection: {
15
+ status?: number;
16
+ error: string;
17
+ errorBody?: unknown;
18
+ }, now?: () => Date): OutboxRejectedRecord;
19
+ /** Summarizes pending and rejected entry counts per session plus rejected error details. */
20
+ export declare function getOutboxStatus(dir: string): OutboxStatus;
21
+ /** Removes matching rejected records from `<dir>/rejected/`. */
22
+ export declare function pruneOutboxRejected(dir: string, options?: Pick<OutboxPruneOptions, 'id' | 'sessionId'>): OutboxPruneResult;