agent-blackboard 0.6.1 → 0.7.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/README.md +3 -1
- package/dist/cli/append.mjs +3 -4
- package/dist/cli/args.d.mts +3 -2
- package/dist/cli/args.mjs +4 -3
- package/dist/cli/context.d.mts +2 -0
- package/dist/cli/get.mjs +4 -5
- package/dist/cli/index.d.mts +1 -0
- package/dist/cli/index.mjs +5 -1
- package/dist/cli/session-resolution.d.mts +19 -0
- package/dist/cli/session-resolution.mjs +63 -0
- package/dist/cli/sessions.mjs +21 -14
- package/dist/cli/usage.d.mts +1 -1
- package/dist/cli/usage.mjs +9 -5
- package/dist/index.d.mts +13 -0
- package/dist/index.mjs +8 -0
- package/dist/mcp/dispatch.d.mts +2 -1
- package/dist/mcp/dispatch.mjs +5 -5
- package/dist/mcp/schema-fields.d.mts +37 -0
- package/dist/mcp/schema-fields.mjs +41 -0
- package/dist/mcp/schemas.mjs +10 -39
- package/dist/mcp/server.d.mts +3 -2
- package/dist/mcp/server.mjs +4 -4
- package/dist/mcp/session-resolution.d.mts +16 -0
- package/dist/mcp/session-resolution.mjs +27 -0
- package/dist/mcp/tool-append.d.mts +2 -1
- package/dist/mcp/tool-append.mjs +4 -3
- package/dist/mcp/tool-get.d.mts +2 -1
- package/dist/mcp/tool-get.mjs +4 -3
- package/dist/mcp/tool-sessions.d.mts +3 -2
- package/dist/mcp/tool-sessions.mjs +10 -11
- package/dist/plugin/.claude-mcp.json +1 -1
- package/dist/plugin/.codex-plugin/plugin.json +1 -1
- package/dist/plugin/.mcp.json +2 -2
- package/dist/plugin/skills/agent-blackboard/SKILL.md +12 -11
- package/dist/session-id/harness.d.mts +44 -0
- package/dist/session-id/harness.mjs +61 -0
- package/dist/session-id/hook-payload.d.mts +19 -0
- package/dist/session-id/hook-payload.mjs +52 -0
- package/dist/session-id/persist.d.mts +53 -0
- package/dist/session-id/persist.mjs +114 -0
- package/dist/session-id/resolve.d.mts +46 -0
- package/dist/session-id/resolve.mjs +131 -0
- package/dist/session-id/root-codex-options.d.mts +9 -0
- package/dist/session-id/root-codex-options.mjs +13 -0
- package/dist/session-id/valid-id.d.mts +8 -0
- package/dist/session-id/valid-id.mjs +16 -0
- package/package.json +2 -2
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { requireSessionAgent, requireSessionId, requireSessionIdentity, } from '../session-id/resolve.mjs';
|
|
2
|
+
import { requiredString } from './validate.mjs';
|
|
3
|
+
/**
|
|
4
|
+
* An explicit `sessionId` wins and is passed through (the server validates it). When omitted and
|
|
5
|
+
* a resolution context is available, the id is resolved from the harness environment or the
|
|
6
|
+
* per-worktree persisted file; otherwise `sessionId` is required.
|
|
7
|
+
*/
|
|
8
|
+
export function toolSessionId(args, resolution) {
|
|
9
|
+
if (args.sessionId !== undefined || resolution === undefined)
|
|
10
|
+
return requiredString(args.sessionId, 'sessionId');
|
|
11
|
+
return requireSessionId(resolution);
|
|
12
|
+
}
|
|
13
|
+
/** `sessionId` and `agent` for `session_create`/`session_ensure`, resolved as a pair. */
|
|
14
|
+
export function toolSessionIdentity(args, resolution) {
|
|
15
|
+
const sessionIdArg = args.sessionId === undefined ? undefined : requiredString(args.sessionId, 'sessionId');
|
|
16
|
+
const agentArg = args.agent === undefined ? undefined : requiredString(args.agent, 'agent');
|
|
17
|
+
if (resolution === undefined || (sessionIdArg !== undefined && agentArg !== undefined)) {
|
|
18
|
+
return {
|
|
19
|
+
sessionId: requiredString(sessionIdArg, 'sessionId'),
|
|
20
|
+
agent: requiredString(agentArg, 'agent'),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
const options = { ...resolution, agentArg };
|
|
24
|
+
if (sessionIdArg === undefined)
|
|
25
|
+
return requireSessionIdentity(options);
|
|
26
|
+
return { sessionId: sessionIdArg, agent: requireSessionAgent({ ...options, sessionIdArg }) };
|
|
27
|
+
}
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
+
import { type SessionResolutionContext } from './session-resolution.mjs';
|
|
1
2
|
import type { ClientConfig, SessionEntry } from '../client/types.mjs';
|
|
2
|
-
export declare function handleEntryAppend(args: Record<string, unknown>, config: ClientConfig): Promise<SessionEntry>;
|
|
3
|
+
export declare function handleEntryAppend(args: Record<string, unknown>, config: ClientConfig, resolution?: SessionResolutionContext): Promise<SessionEntry>;
|
package/dist/mcp/tool-append.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { appendEntry } from '../client/append.mjs';
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import { toolSessionId } from './session-resolution.mjs';
|
|
3
|
+
import { expectObject } from './validate.mjs';
|
|
4
|
+
export function handleEntryAppend(args, config, resolution) {
|
|
4
5
|
return appendEntry(config, {
|
|
5
|
-
sessionId:
|
|
6
|
+
sessionId: toolSessionId(args, resolution),
|
|
6
7
|
data: expectObject(args.data, 'data'),
|
|
7
8
|
});
|
|
8
9
|
}
|
package/dist/mcp/tool-get.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
+
import { type SessionResolutionContext } from './session-resolution.mjs';
|
|
1
2
|
import type { ClientConfig, SessionEntry } from '../client/types.mjs';
|
|
2
|
-
export declare function handleEntryGet(args: Record<string, unknown>, config: ClientConfig): Promise<{
|
|
3
|
+
export declare function handleEntryGet(args: Record<string, unknown>, config: ClientConfig, resolution?: SessionResolutionContext): Promise<{
|
|
3
4
|
entries: SessionEntry[];
|
|
4
5
|
}>;
|
package/dist/mcp/tool-get.mjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { streamEntries } from '../client/stream.mjs';
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import { toolSessionId } from './session-resolution.mjs';
|
|
3
|
+
import { optionalEntryFormat } from './validate.mjs';
|
|
4
|
+
export async function handleEntryGet(args, config, resolution) {
|
|
4
5
|
const entries = [];
|
|
5
6
|
const format = optionalEntryFormat(args.format);
|
|
6
7
|
const query = {
|
|
7
|
-
sessionId:
|
|
8
|
+
sessionId: toolSessionId(args, resolution),
|
|
8
9
|
...(format === undefined ? {} : { format }),
|
|
9
10
|
};
|
|
10
11
|
for await (const entry of streamEntries(config, query)) {
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import type { ClientConfig, Session } from '../client/types.mjs';
|
|
2
2
|
import type { EnsureSessionResult } from '../client/sessions.mjs';
|
|
3
|
+
import { type SessionResolutionContext } from './session-resolution.mjs';
|
|
3
4
|
export declare function handleSessionSearch(args: Record<string, unknown>, config: ClientConfig, now?: Date): Promise<{
|
|
4
5
|
sessions: Session[];
|
|
5
6
|
nextCursor: string | null;
|
|
6
7
|
}>;
|
|
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>;
|
|
8
|
+
export declare function handleSessionCreate(args: Record<string, unknown>, config: ClientConfig, resolution?: SessionResolutionContext): Promise<Session>;
|
|
9
|
+
export declare function handleSessionEnsure(args: Record<string, unknown>, config: ClientConfig, resolution?: SessionResolutionContext): Promise<EnsureSessionResult>;
|
|
9
10
|
export declare function handleSessionPatch(args: Record<string, unknown>, config: ClientConfig): Promise<Session>;
|
|
10
11
|
export declare function handleSessionArchive(args: Record<string, unknown>, config: ClientConfig): Promise<Session>;
|
|
@@ -2,6 +2,7 @@ import { isDeepStrictEqual } from 'node:util';
|
|
|
2
2
|
import { AgentBlackboardError } from '../client/errors.mjs';
|
|
3
3
|
import { Sessions } from '../client/sessions.mjs';
|
|
4
4
|
import { expectObject, nullableString, optionalPositiveInt, optionalPositiveNumber, requiredString, } from './validate.mjs';
|
|
5
|
+
import { toolSessionIdentity } from './session-resolution.mjs';
|
|
5
6
|
function parseSessionSearchArgs(args) {
|
|
6
7
|
if (args.archived !== undefined && args.archived !== 0 && args.archived !== 1) {
|
|
7
8
|
throw new Error('"archived" must be 0 or 1.');
|
|
@@ -110,19 +111,17 @@ export async function handleSessionSearch(args, config, now = new Date()) {
|
|
|
110
111
|
return new Sessions(config).list(query);
|
|
111
112
|
}
|
|
112
113
|
/** Shared by `session_create` and `session_ensure`, which take identical args. */
|
|
113
|
-
function parseCreateSessionArgs(args) {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
version: requiredString(args.version, 'version'),
|
|
119
|
-
};
|
|
114
|
+
function parseCreateSessionArgs(args, resolution) {
|
|
115
|
+
const parentSessionId = nullableString(args.parentSessionId, 'parentSessionId');
|
|
116
|
+
const version = requiredString(args.version, 'version');
|
|
117
|
+
const { sessionId, agent } = toolSessionIdentity(args, resolution);
|
|
118
|
+
return { id: sessionId, parentSessionId, agent, version };
|
|
120
119
|
}
|
|
121
|
-
export function handleSessionCreate(args, config) {
|
|
122
|
-
return new Sessions(config).create(parseCreateSessionArgs(args));
|
|
120
|
+
export function handleSessionCreate(args, config, resolution) {
|
|
121
|
+
return new Sessions(config).create(parseCreateSessionArgs(args, resolution));
|
|
123
122
|
}
|
|
124
|
-
export function handleSessionEnsure(args, config) {
|
|
125
|
-
return new Sessions(config).ensure(parseCreateSessionArgs(args));
|
|
123
|
+
export function handleSessionEnsure(args, config, resolution) {
|
|
124
|
+
return new Sessions(config).ensure(parseCreateSessionArgs(args, resolution));
|
|
126
125
|
}
|
|
127
126
|
export function handleSessionPatch(args, config) {
|
|
128
127
|
const data = expectObject(args.data, 'data');
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"mcpServers": {
|
|
3
3
|
"agent-blackboard": {
|
|
4
4
|
"command": "npx",
|
|
5
|
-
"args": ["-y", "agent-blackboard@0.
|
|
5
|
+
"args": ["-y", "agent-blackboard@0.7.0", "mcp"],
|
|
6
6
|
"env": {
|
|
7
7
|
"AGENT_BLACKBOARD_URL": "${AGENT_BLACKBOARD_URL}",
|
|
8
8
|
"AGENT_BLACKBOARD_TOKEN": "${AGENT_BLACKBOARD_TOKEN}"
|
package/dist/plugin/.mcp.json
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
"mcpServers": {
|
|
3
3
|
"agent-blackboard": {
|
|
4
4
|
"command": "npx",
|
|
5
|
-
"args": ["-y", "agent-blackboard@0.
|
|
6
|
-
"env_vars": ["AGENT_BLACKBOARD_URL", "AGENT_BLACKBOARD_TOKEN"]
|
|
5
|
+
"args": ["-y", "agent-blackboard@0.7.0", "mcp"],
|
|
6
|
+
"env_vars": ["AGENT_BLACKBOARD_URL", "AGENT_BLACKBOARD_TOKEN", "CODEX_THREAD_ID"]
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
9
|
}
|
|
@@ -10,8 +10,9 @@ skill explains how to use it; project instructions decide what is worth recordin
|
|
|
10
10
|
|
|
11
11
|
## How it works
|
|
12
12
|
|
|
13
|
-
- **Session ids are explicit.**
|
|
14
|
-
|
|
13
|
+
- **Session ids are explicit.** Choose an id and create the session before writing. The service
|
|
14
|
+
never infers or generates one. When an id is omitted, the MCP server or CLI resolves it from the
|
|
15
|
+
host's harness environment. Never rely on this for subagents.
|
|
15
16
|
- **Subagents get their own sessions.** Create each subagent session with its direct parent's id in
|
|
16
17
|
`parentSessionId`. Root sessions use `parentSessionId: null`.
|
|
17
18
|
- **Agent identity is explicit.** Every session creation includes the actual agent name and version.
|
|
@@ -53,17 +54,17 @@ Without MCP, or from a shell/script, run the published CLI through `npx`. This d
|
|
|
53
54
|
local clone of the agent-blackboard repository:
|
|
54
55
|
|
|
55
56
|
```bash
|
|
56
|
-
npx -y agent-blackboard@0.
|
|
57
|
-
npx -y agent-blackboard@0.
|
|
57
|
+
npx -y agent-blackboard@0.7.0 sessions create root-123 --agent claude-code --version 1.0.13
|
|
58
|
+
npx -y agent-blackboard@0.7.0 sessions create worker-456 --parent-session-id root-123 \
|
|
58
59
|
--agent claude-code --version 1.0.13
|
|
59
|
-
npx -y agent-blackboard@0.
|
|
60
|
-
npx -y agent-blackboard@0.
|
|
61
|
-
npx -y agent-blackboard@0.
|
|
62
|
-
npx -y agent-blackboard@0.
|
|
63
|
-
npx -y agent-blackboard@0.
|
|
64
|
-
npx -y agent-blackboard@0.
|
|
60
|
+
npx -y agent-blackboard@0.7.0 sessions patch worker-456 --data '{"branch":"fix/retry"}'
|
|
61
|
+
npx -y agent-blackboard@0.7.0 sessions patch worker-456 --data '{"repositories":["owner/name"]}'
|
|
62
|
+
npx -y agent-blackboard@0.7.0 append --session-id worker-456 '{"repositories":["owner/name"],"note":"found the failing edge case"}'
|
|
63
|
+
npx -y agent-blackboard@0.7.0 get --session-id worker-456 --format markdown
|
|
64
|
+
npx -y agent-blackboard@0.7.0 snapshot export --root-only --inactive-for-hours 8
|
|
65
|
+
npx -y agent-blackboard@0.7.0 snapshot partition --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl \
|
|
65
66
|
--cleanup-token <cleanup-token>
|
|
66
|
-
npx -y agent-blackboard@0.
|
|
67
|
+
npx -y agent-blackboard@0.7.0 snapshot cleanup --path /tmp/agent-blackboard-snapshot-<uuid>.jsonl \
|
|
67
68
|
--directory /tmp/agent-blackboard-partitions-<suffix> --cleanup-token <cleanup-token>
|
|
68
69
|
```
|
|
69
70
|
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** Every coding-agent harness this package can recognize from its environment. */
|
|
2
|
+
export declare const HARNESS_IDS: readonly ['claude', 'codex', 'grok', 'cursor'];
|
|
3
|
+
export type HarnessId = (typeof HARNESS_IDS)[number];
|
|
4
|
+
/**
|
|
5
|
+
* The precedence used when picking a single harness session id from the environment, for callers
|
|
6
|
+
* that need one answer (e.g. agent derivation). Ambient resolution in `resolveSessionIdentity`
|
|
7
|
+
* applies its own, finer-grained rules instead.
|
|
8
|
+
*/
|
|
9
|
+
export declare const HARNESS_SESSION_PRECEDENCE: readonly HarnessId[];
|
|
10
|
+
/** Every harness signal present in an environment, without choosing between them. */
|
|
11
|
+
export interface HarnessEnvironment {
|
|
12
|
+
readonly claude: {
|
|
13
|
+
readonly compatMode: boolean;
|
|
14
|
+
readonly sessionId?: string;
|
|
15
|
+
};
|
|
16
|
+
readonly codex: {
|
|
17
|
+
readonly sessionId?: string;
|
|
18
|
+
};
|
|
19
|
+
readonly cursor: {
|
|
20
|
+
readonly agentMarker: boolean;
|
|
21
|
+
readonly sessionId?: string;
|
|
22
|
+
};
|
|
23
|
+
readonly grok: {
|
|
24
|
+
readonly agentMarker: boolean;
|
|
25
|
+
readonly hookEvent: boolean;
|
|
26
|
+
readonly sessionId?: string;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export interface HarnessSessionIdentity {
|
|
30
|
+
readonly harness: HarnessId;
|
|
31
|
+
readonly sessionId: string;
|
|
32
|
+
}
|
|
33
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
34
|
+
/**
|
|
35
|
+
* Reads the env-marker table: `CLAUDECODE`/`CLAUDE_CODE_SESSION_ID`, `CODEX_THREAD_ID`,
|
|
36
|
+
* `CURSOR_AGENT`/`CURSOR_SESSION_ID`, and `GROK_AGENT`/`GROK_HOOK_EVENT`/`GROK_SESSION_ID`.
|
|
37
|
+
* Empty values count as absent. Never throws.
|
|
38
|
+
*/
|
|
39
|
+
export declare function inspectHarnessEnvironment(env: Env): HarnessEnvironment;
|
|
40
|
+
/** The first harness in `precedence` with a session id, or `undefined` when none has one. */
|
|
41
|
+
export declare function selectHarnessSession(environment: HarnessEnvironment, precedence: readonly HarnessId[]): HarnessSessionIdentity | undefined;
|
|
42
|
+
/** Classifies a transcript path by the harness directory layout it lives under. */
|
|
43
|
+
export declare function transcriptPathHarness(transcriptPath: string | undefined): HarnessId | undefined;
|
|
44
|
+
export {};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** Every coding-agent harness this package can recognize from its environment. */
|
|
2
|
+
export const HARNESS_IDS = ['claude', 'codex', 'grok', 'cursor'];
|
|
3
|
+
/**
|
|
4
|
+
* The precedence used when picking a single harness session id from the environment, for callers
|
|
5
|
+
* that need one answer (e.g. agent derivation). Ambient resolution in `resolveSessionIdentity`
|
|
6
|
+
* applies its own, finer-grained rules instead.
|
|
7
|
+
*/
|
|
8
|
+
export const HARNESS_SESSION_PRECEDENCE = [
|
|
9
|
+
'codex',
|
|
10
|
+
'claude',
|
|
11
|
+
'cursor',
|
|
12
|
+
'grok',
|
|
13
|
+
];
|
|
14
|
+
function session(value) {
|
|
15
|
+
return value ? { sessionId: value } : {};
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Reads the env-marker table: `CLAUDECODE`/`CLAUDE_CODE_SESSION_ID`, `CODEX_THREAD_ID`,
|
|
19
|
+
* `CURSOR_AGENT`/`CURSOR_SESSION_ID`, and `GROK_AGENT`/`GROK_HOOK_EVENT`/`GROK_SESSION_ID`.
|
|
20
|
+
* Empty values count as absent. Never throws.
|
|
21
|
+
*/
|
|
22
|
+
export function inspectHarnessEnvironment(env) {
|
|
23
|
+
return {
|
|
24
|
+
claude: {
|
|
25
|
+
compatMode: env.CLAUDECODE === '1',
|
|
26
|
+
...session(env.CLAUDE_CODE_SESSION_ID),
|
|
27
|
+
},
|
|
28
|
+
codex: session(env.CODEX_THREAD_ID),
|
|
29
|
+
cursor: {
|
|
30
|
+
agentMarker: Boolean(env.CURSOR_AGENT),
|
|
31
|
+
...session(env.CURSOR_SESSION_ID),
|
|
32
|
+
},
|
|
33
|
+
grok: {
|
|
34
|
+
agentMarker: Boolean(env.GROK_AGENT),
|
|
35
|
+
hookEvent: Boolean(env.GROK_HOOK_EVENT),
|
|
36
|
+
...session(env.GROK_SESSION_ID),
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** The first harness in `precedence` with a session id, or `undefined` when none has one. */
|
|
41
|
+
export function selectHarnessSession(environment, precedence) {
|
|
42
|
+
for (const harness of precedence) {
|
|
43
|
+
const sessionId = environment[harness].sessionId;
|
|
44
|
+
if (sessionId)
|
|
45
|
+
return { harness, sessionId };
|
|
46
|
+
}
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
/** Classifies a transcript path by the harness directory layout it lives under. */
|
|
50
|
+
export function transcriptPathHarness(transcriptPath) {
|
|
51
|
+
const path = transcriptPath?.replaceAll('\\', '/');
|
|
52
|
+
if (!path)
|
|
53
|
+
return undefined;
|
|
54
|
+
if (path.includes('/.codex/') && path.endsWith('.jsonl'))
|
|
55
|
+
return 'codex';
|
|
56
|
+
if (path.includes('/.grok/') && path.endsWith('/updates.jsonl'))
|
|
57
|
+
return 'grok';
|
|
58
|
+
if (path.includes('/.claude/projects/') && path.endsWith('.jsonl'))
|
|
59
|
+
return 'claude';
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { HarnessId } from './harness.mjs';
|
|
2
|
+
/** A harness hook's JSON payload. Only its session-id keys and `cwd` are read. */
|
|
3
|
+
export type HookPayload = Readonly<Record<string, unknown>>;
|
|
4
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
5
|
+
/** The first key in `keys` holding a valid session id, or `''`. */
|
|
6
|
+
export declare function hookPayloadSessionId(payload: HookPayload, keys?: readonly string[]): string;
|
|
7
|
+
export declare function cursorPayloadSessionId(payload: HookPayload): string;
|
|
8
|
+
export declare function grokHookSessionId(payload: HookPayload, env: Env): string;
|
|
9
|
+
/**
|
|
10
|
+
* SessionStart hook: persists (or generates) the Cursor/Grok id. No-op for other runtimes. Writes
|
|
11
|
+
* under the payload's `cwd` when present, else `root`; either is normalized to its worktree root.
|
|
12
|
+
*/
|
|
13
|
+
export declare function persistHookSessionStart(runtime: HarnessId | undefined, payload: HookPayload, env: Env, root: string, generateId?: () => string): {
|
|
14
|
+
generated: boolean;
|
|
15
|
+
sessionId: string;
|
|
16
|
+
} | undefined;
|
|
17
|
+
/** Later hooks: refreshes the persisted Cursor/Grok id when the payload carries a real one. */
|
|
18
|
+
export declare function persistHookRealSessionId(runtime: HarnessId | undefined, payload: HookPayload, env: Env, root: string): void;
|
|
19
|
+
export {};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { persistRealSessionId, resolveAndPersistSessionStartId, } from './persist.mjs';
|
|
2
|
+
import { sanitizeSessionId } from './valid-id.mjs';
|
|
3
|
+
/** The first key in `keys` holding a valid session id, or `''`. */
|
|
4
|
+
export function hookPayloadSessionId(payload, keys = ['session_id', 'sessionId']) {
|
|
5
|
+
for (const key of keys) {
|
|
6
|
+
const id = sanitizeSessionId(payload[key]);
|
|
7
|
+
if (id !== '')
|
|
8
|
+
return id;
|
|
9
|
+
}
|
|
10
|
+
return '';
|
|
11
|
+
}
|
|
12
|
+
export function cursorPayloadSessionId(payload) {
|
|
13
|
+
return hookPayloadSessionId(payload, ['session_id', 'sessionId', 'conversation_id']);
|
|
14
|
+
}
|
|
15
|
+
export function grokHookSessionId(payload, env) {
|
|
16
|
+
return sanitizeSessionId(env.GROK_SESSION_ID) || hookPayloadSessionId(payload);
|
|
17
|
+
}
|
|
18
|
+
// The payload's own `cwd` (when present) decides the worktree, so a hook process launched from an
|
|
19
|
+
// outer checkout still writes where resolution from that cwd will read.
|
|
20
|
+
function hookRoot(payload, root) {
|
|
21
|
+
return typeof payload.cwd === 'string' && payload.cwd !== '' ? payload.cwd : root;
|
|
22
|
+
}
|
|
23
|
+
// Claude and Codex expose their session id to every process through env, so only the
|
|
24
|
+
// Claude-compat runtimes without one (Grok and Cursor) persist it for later hook-less readers.
|
|
25
|
+
function hookRuntimeSessionId(runtime, payload, env) {
|
|
26
|
+
if (runtime === 'grok')
|
|
27
|
+
return { harness: 'grok', sessionId: grokHookSessionId(payload, env) };
|
|
28
|
+
if (runtime === 'cursor')
|
|
29
|
+
return { harness: 'cursor', sessionId: cursorPayloadSessionId(payload) };
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* SessionStart hook: persists (or generates) the Cursor/Grok id. No-op for other runtimes. Writes
|
|
34
|
+
* under the payload's `cwd` when present, else `root`; either is normalized to its worktree root.
|
|
35
|
+
*/
|
|
36
|
+
export function persistHookSessionStart(runtime, payload, env, root, generateId) {
|
|
37
|
+
const hook = hookRuntimeSessionId(runtime, payload, env);
|
|
38
|
+
if (hook === undefined)
|
|
39
|
+
return undefined;
|
|
40
|
+
return resolveAndPersistSessionStartId({
|
|
41
|
+
harness: hook.harness,
|
|
42
|
+
root: hookRoot(payload, root),
|
|
43
|
+
generateId,
|
|
44
|
+
payloadId: hook.sessionId,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
/** Later hooks: refreshes the persisted Cursor/Grok id when the payload carries a real one. */
|
|
48
|
+
export function persistHookRealSessionId(runtime, payload, env, root) {
|
|
49
|
+
const hook = hookRuntimeSessionId(runtime, payload, env);
|
|
50
|
+
if (hook !== undefined)
|
|
51
|
+
persistRealSessionId(hookRoot(payload, root), hook.harness, hook.sessionId);
|
|
52
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** Harnesses that do not expose their session id to every child process, so it is persisted. */
|
|
2
|
+
export type PersistedHarness = 'codex' | 'cursor' | 'grok';
|
|
3
|
+
/** Persisted-file locations, relative to a worktree root. Each holds one id and a newline. */
|
|
4
|
+
export declare const SESSION_PERSIST_RELATIVE: {
|
|
5
|
+
readonly codex: '.local/codex-session-id';
|
|
6
|
+
readonly cursor: '.local/cursor-session-id';
|
|
7
|
+
readonly grok: '.local/grok-session-id';
|
|
8
|
+
};
|
|
9
|
+
/** The nearest ancestor of `cwd` (inclusive) containing `.git`, or `cwd` itself if none does. */
|
|
10
|
+
export declare function enclosingWorktreeRoot(cwd: string): string;
|
|
11
|
+
/**
|
|
12
|
+
* The persisted-file path for `harness`. `root` may be any directory inside the worktree: it is
|
|
13
|
+
* normalized through `enclosingWorktreeRoot`, so every read and write in this module agrees on the
|
|
14
|
+
* same file regardless of which subdirectory a caller runs from. A directory without its own
|
|
15
|
+
* `.git` inside a repository therefore maps to that repository's `.local/`.
|
|
16
|
+
*/
|
|
17
|
+
export declare function sessionPersistPath(root: string, harness: PersistedHarness): string;
|
|
18
|
+
/**
|
|
19
|
+
* Reads a persisted id. Missing or malformed files yield `undefined`, unless `strict`, where a
|
|
20
|
+
* malformed file or any read error other than `ENOENT` throws.
|
|
21
|
+
*/
|
|
22
|
+
export declare function readPersistedSessionId(root: string, harness: PersistedHarness, options?: {
|
|
23
|
+
strict?: boolean;
|
|
24
|
+
}): string | undefined;
|
|
25
|
+
/** Persists a real (harness-supplied) id; invalid or empty ids and write failures are ignored. */
|
|
26
|
+
export declare function persistRealSessionId(root: string, harness: PersistedHarness, sessionId: string): void;
|
|
27
|
+
/**
|
|
28
|
+
* Session-start persistence for hook callers: a real payload id wins and is written; otherwise a
|
|
29
|
+
* valid persisted id is reused; otherwise `<harness>-<uuid>` is generated and written. Never
|
|
30
|
+
* throws on write failure.
|
|
31
|
+
*/
|
|
32
|
+
export declare function resolveAndPersistSessionStartId(options: {
|
|
33
|
+
root: string;
|
|
34
|
+
harness: PersistedHarness;
|
|
35
|
+
payloadId: string;
|
|
36
|
+
generateId?: (() => string) | undefined;
|
|
37
|
+
}): {
|
|
38
|
+
generated: boolean;
|
|
39
|
+
sessionId: string;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Root Codex persistence. Unlike the hook path, an interactive root Codex caller cannot continue
|
|
43
|
+
* without a durable id, so write and read-back failures surface as errors.
|
|
44
|
+
*/
|
|
45
|
+
export declare function resolveAndPersistRootCodexSessionId(options: {
|
|
46
|
+
root: string;
|
|
47
|
+
payloadId?: string | undefined;
|
|
48
|
+
newSession?: boolean | undefined;
|
|
49
|
+
generateId?: (() => string) | undefined;
|
|
50
|
+
}): {
|
|
51
|
+
generated: boolean;
|
|
52
|
+
sessionId: string;
|
|
53
|
+
};
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { isValidSessionId, sanitizeSessionId } from './valid-id.mjs';
|
|
5
|
+
/** Persisted-file locations, relative to a worktree root. Each holds one id and a newline. */
|
|
6
|
+
export const SESSION_PERSIST_RELATIVE = {
|
|
7
|
+
codex: '.local/codex-session-id',
|
|
8
|
+
cursor: '.local/cursor-session-id',
|
|
9
|
+
grok: '.local/grok-session-id',
|
|
10
|
+
};
|
|
11
|
+
/** The nearest ancestor of `cwd` (inclusive) containing `.git`, or `cwd` itself if none does. */
|
|
12
|
+
export function enclosingWorktreeRoot(cwd) {
|
|
13
|
+
let candidate = resolve(cwd);
|
|
14
|
+
while (!existsSync(join(candidate, '.git'))) {
|
|
15
|
+
const parent = dirname(candidate);
|
|
16
|
+
if (parent === candidate)
|
|
17
|
+
return resolve(cwd);
|
|
18
|
+
candidate = parent;
|
|
19
|
+
}
|
|
20
|
+
return candidate;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The persisted-file path for `harness`. `root` may be any directory inside the worktree: it is
|
|
24
|
+
* normalized through `enclosingWorktreeRoot`, so every read and write in this module agrees on the
|
|
25
|
+
* same file regardless of which subdirectory a caller runs from. A directory without its own
|
|
26
|
+
* `.git` inside a repository therefore maps to that repository's `.local/`.
|
|
27
|
+
*/
|
|
28
|
+
export function sessionPersistPath(root, harness) {
|
|
29
|
+
return join(enclosingWorktreeRoot(root), SESSION_PERSIST_RELATIVE[harness]);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Reads a persisted id. Missing or malformed files yield `undefined`, unless `strict`, where a
|
|
33
|
+
* malformed file or any read error other than `ENOENT` throws.
|
|
34
|
+
*/
|
|
35
|
+
export function readPersistedSessionId(root, harness, options = {}) {
|
|
36
|
+
try {
|
|
37
|
+
const raw = readFileSync(sessionPersistPath(root, harness), 'utf8').trim();
|
|
38
|
+
if (isValidSessionId(raw))
|
|
39
|
+
return raw;
|
|
40
|
+
if (options.strict)
|
|
41
|
+
throw new Error(`invalid persisted ${harness} session id format`);
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
if (options.strict && err.code !== 'ENOENT')
|
|
46
|
+
throw err;
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function writePersistFile(root, harness, sessionId) {
|
|
51
|
+
const path = sessionPersistPath(root, harness);
|
|
52
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
53
|
+
writeFileSync(path, `${sessionId}\n`, { encoding: 'utf8' });
|
|
54
|
+
}
|
|
55
|
+
function tryWritePersistFile(root, harness, sessionId) {
|
|
56
|
+
try {
|
|
57
|
+
writePersistFile(root, harness, sessionId);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
// Hooks must not fail closed when the persist file cannot be written.
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function generatedId(prefix, generateId) {
|
|
64
|
+
const generated = sanitizeSessionId(generateId?.() ?? `${prefix}${randomUUID()}`);
|
|
65
|
+
return generated === '' ? `${prefix}${randomUUID()}` : generated;
|
|
66
|
+
}
|
|
67
|
+
/** Persists a real (harness-supplied) id; invalid or empty ids and write failures are ignored. */
|
|
68
|
+
export function persistRealSessionId(root, harness, sessionId) {
|
|
69
|
+
const id = sanitizeSessionId(sessionId);
|
|
70
|
+
if (id !== '')
|
|
71
|
+
tryWritePersistFile(root, harness, id);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Session-start persistence for hook callers: a real payload id wins and is written; otherwise a
|
|
75
|
+
* valid persisted id is reused; otherwise `<harness>-<uuid>` is generated and written. Never
|
|
76
|
+
* throws on write failure.
|
|
77
|
+
*/
|
|
78
|
+
export function resolveAndPersistSessionStartId(options) {
|
|
79
|
+
const real = sanitizeSessionId(options.payloadId);
|
|
80
|
+
if (real !== '') {
|
|
81
|
+
tryWritePersistFile(options.root, options.harness, real);
|
|
82
|
+
return { generated: false, sessionId: real };
|
|
83
|
+
}
|
|
84
|
+
const existing = readPersistedSessionId(options.root, options.harness);
|
|
85
|
+
if (existing !== undefined)
|
|
86
|
+
return { generated: false, sessionId: existing };
|
|
87
|
+
const sessionId = generatedId(`${options.harness}-`, options.generateId);
|
|
88
|
+
tryWritePersistFile(options.root, options.harness, sessionId);
|
|
89
|
+
return { generated: true, sessionId };
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Root Codex persistence. Unlike the hook path, an interactive root Codex caller cannot continue
|
|
93
|
+
* without a durable id, so write and read-back failures surface as errors.
|
|
94
|
+
*/
|
|
95
|
+
export function resolveAndPersistRootCodexSessionId(options) {
|
|
96
|
+
const real = options.payloadId?.trim() ?? '';
|
|
97
|
+
if (real !== '' && !isValidSessionId(real)) {
|
|
98
|
+
throw new Error('invalid root Codex session id format');
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
const existing = real === '' && !options.newSession
|
|
102
|
+
? readPersistedSessionId(options.root, 'codex', { strict: true })
|
|
103
|
+
: undefined;
|
|
104
|
+
const sessionId = real || existing || generatedId('codex-', options.generateId);
|
|
105
|
+
writePersistFile(options.root, 'codex', sessionId);
|
|
106
|
+
if (readPersistedSessionId(options.root, 'codex', { strict: true }) !== sessionId) {
|
|
107
|
+
throw new Error('persisted session id did not match the selected id');
|
|
108
|
+
}
|
|
109
|
+
return { generated: real === '' && existing === undefined, sessionId };
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
throw new Error('failed to persist root Codex session id', { cause: err });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { type HarnessEnvironment, type HarnessId } from './harness.mjs';
|
|
2
|
+
/** The `agent` value `sessions create|ensure` records for each harness. */
|
|
3
|
+
export type SessionAgent = 'claude-code' | 'codex' | 'cursor' | 'grok';
|
|
4
|
+
export interface SessionIdentity {
|
|
5
|
+
readonly agent: SessionAgent;
|
|
6
|
+
readonly harness: HarnessId;
|
|
7
|
+
readonly sessionId?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ResolveSessionIdentityOptions {
|
|
10
|
+
/** The environment to read harness markers from. Never defaulted to `process.env`. */
|
|
11
|
+
env: Readonly<Record<string, string | undefined>>;
|
|
12
|
+
/** Where persisted ids are looked up (walking up to the nearest `.git`). */
|
|
13
|
+
cwd: string;
|
|
14
|
+
/** Overrides harness detection; defaults to the built-in `inspectHarnessEnvironment`. */
|
|
15
|
+
inspectEnvironment?: (env: ResolveSessionIdentityOptions['env']) => HarnessEnvironment;
|
|
16
|
+
/** A runtime the caller already knows it is running under (e.g. from hook argv). */
|
|
17
|
+
runtime?: HarnessId | undefined;
|
|
18
|
+
/** A transcript path hint, classified by harness directory layout. */
|
|
19
|
+
transcriptPath?: string | undefined;
|
|
20
|
+
agentArg?: string | undefined;
|
|
21
|
+
sessionIdArg?: string | undefined;
|
|
22
|
+
parentSessionId?: string | undefined;
|
|
23
|
+
rootCodex?: boolean | undefined;
|
|
24
|
+
newRootCodexSession?: boolean | undefined;
|
|
25
|
+
}
|
|
26
|
+
export declare function agentForHarness(harness: HarnessId): SessionAgent;
|
|
27
|
+
/**
|
|
28
|
+
* Resolves `{ agent, harness, sessionId? }` from an explicit id, then environment markers, then a
|
|
29
|
+
* runtime or transcript hint, then the per-worktree persisted id. Returns `undefined` when nothing
|
|
30
|
+
* identifies a harness. `sessionId` is absent when the harness is known but its id is not.
|
|
31
|
+
*/
|
|
32
|
+
export declare function resolveSessionIdentity(options: ResolveSessionIdentityOptions): SessionIdentity | undefined;
|
|
33
|
+
/** The explicit id if given, else the resolved one. Does not validate. */
|
|
34
|
+
export declare function resolveSessionId(options: ResolveSessionIdentityOptions): string | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* Like `resolveSessionId`, but throws when no id resolves. An explicit `sessionIdArg` is returned
|
|
37
|
+
* as-is (the server validates it); only a resolved id must be a plain token.
|
|
38
|
+
*/
|
|
39
|
+
export declare function requireSessionId(options: ResolveSessionIdentityOptions): string;
|
|
40
|
+
/** The explicit `agentArg` if given, else the resolved agent; throws when neither exists. */
|
|
41
|
+
export declare function requireSessionAgent(options: ResolveSessionIdentityOptions): string;
|
|
42
|
+
/** Both the session id and the agent, resolved together so they always pair. */
|
|
43
|
+
export declare function requireSessionIdentity(options: ResolveSessionIdentityOptions): {
|
|
44
|
+
agent: string;
|
|
45
|
+
sessionId: string;
|
|
46
|
+
};
|