@ai-devkit/agent-manager 0.34.0 → 0.35.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/dist/AgentManager.d.ts +2 -0
- package/dist/AgentManager.d.ts.map +1 -1
- package/dist/AgentManager.js +25 -0
- package/dist/AgentManager.js.map +1 -1
- package/dist/__tests__/AgentManager.test.js +74 -0
- package/dist/__tests__/AgentManager.test.js.map +1 -1
- package/dist/__tests__/adapters/ClaudeCodeAdapter.test.js +28 -0
- package/dist/__tests__/adapters/ClaudeCodeAdapter.test.js.map +1 -1
- package/dist/__tests__/adapters/CodexAdapter.test.js +7 -0
- package/dist/__tests__/adapters/CodexAdapter.test.js.map +1 -1
- package/dist/__tests__/providers/copilot/CopilotAdapter.test.js +18 -0
- package/dist/__tests__/providers/copilot/CopilotAdapter.test.js.map +1 -1
- package/dist/__tests__/providers/gemini/GeminiCliAdapter.test.js +36 -0
- package/dist/__tests__/providers/gemini/GeminiCliAdapter.test.js.map +1 -1
- package/dist/__tests__/providers/grok/GrokAgentMapper.test.js +56 -0
- package/dist/__tests__/providers/grok/GrokAgentMapper.test.js.map +1 -0
- package/dist/__tests__/{adapters → providers/grok}/GrokCliAdapter.test.js +19 -6
- package/dist/__tests__/providers/grok/GrokCliAdapter.test.js.map +1 -0
- package/dist/__tests__/providers/grok/GrokSessionLocator.test.js +133 -0
- package/dist/__tests__/providers/grok/GrokSessionLocator.test.js.map +1 -0
- package/dist/__tests__/providers/opencode/OpenCodeAdapter.test.js +24 -0
- package/dist/__tests__/providers/opencode/OpenCodeAdapter.test.js.map +1 -1
- package/dist/__tests__/providers/pi/PiAdapter.test.js +30 -0
- package/dist/__tests__/providers/pi/PiAdapter.test.js.map +1 -1
- package/dist/__tests__/utils/session.test.js +18 -1
- package/dist/__tests__/utils/session.test.js.map +1 -1
- package/dist/adapters/AgentAdapter.d.ts +8 -0
- package/dist/adapters/AgentAdapter.d.ts.map +1 -1
- package/dist/adapters/AgentAdapter.js.map +1 -1
- package/dist/adapters/index.d.ts +1 -1
- package/dist/adapters/index.d.ts.map +1 -1
- package/dist/adapters/index.js +1 -1
- package/dist/adapters/index.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/providers/claude/ClaudeCodeAdapter.d.ts +2 -0
- package/dist/providers/claude/ClaudeCodeAdapter.d.ts.map +1 -1
- package/dist/providers/claude/ClaudeCodeAdapter.js +22 -19
- package/dist/providers/claude/ClaudeCodeAdapter.js.map +1 -1
- package/dist/providers/claude/ClaudeSessionLocator.d.ts +4 -0
- package/dist/providers/claude/ClaudeSessionLocator.d.ts.map +1 -1
- package/dist/providers/claude/ClaudeSessionLocator.js +18 -1
- package/dist/providers/claude/ClaudeSessionLocator.js.map +1 -1
- package/dist/providers/codex/CodexAdapter.d.ts +1 -0
- package/dist/providers/codex/CodexAdapter.d.ts.map +1 -1
- package/dist/providers/codex/CodexAdapter.js +8 -0
- package/dist/providers/codex/CodexAdapter.js.map +1 -1
- package/dist/providers/copilot/CopilotAdapter.d.ts +2 -0
- package/dist/providers/copilot/CopilotAdapter.d.ts.map +1 -1
- package/dist/providers/copilot/CopilotAdapter.js +24 -9
- package/dist/providers/copilot/CopilotAdapter.js.map +1 -1
- package/dist/providers/copilot/CopilotSessionLocator.d.ts +1 -0
- package/dist/providers/copilot/CopilotSessionLocator.d.ts.map +1 -1
- package/dist/providers/copilot/CopilotSessionLocator.js +9 -1
- package/dist/providers/copilot/CopilotSessionLocator.js.map +1 -1
- package/dist/providers/gemini/GeminiCliAdapter.d.ts +1 -0
- package/dist/providers/gemini/GeminiCliAdapter.d.ts.map +1 -1
- package/dist/providers/gemini/GeminiCliAdapter.js +9 -0
- package/dist/providers/gemini/GeminiCliAdapter.js.map +1 -1
- package/dist/providers/grok/GrokAgentMapper.d.ts +14 -0
- package/dist/providers/grok/GrokAgentMapper.d.ts.map +1 -0
- package/dist/providers/grok/GrokAgentMapper.js +36 -0
- package/dist/providers/grok/GrokAgentMapper.js.map +1 -0
- package/dist/providers/grok/GrokCliAdapter.d.ts +36 -0
- package/dist/providers/grok/GrokCliAdapter.d.ts.map +1 -0
- package/dist/providers/grok/GrokCliAdapter.js +98 -0
- package/dist/providers/grok/GrokCliAdapter.js.map +1 -0
- package/dist/providers/grok/GrokSessionLocator.d.ts +62 -0
- package/dist/providers/grok/GrokSessionLocator.d.ts.map +1 -0
- package/dist/providers/grok/GrokSessionLocator.js +140 -0
- package/dist/providers/grok/GrokSessionLocator.js.map +1 -0
- package/dist/providers/grok/GrokSessionParser.d.ts +54 -0
- package/dist/providers/grok/GrokSessionParser.d.ts.map +1 -0
- package/dist/providers/grok/GrokSessionParser.js +122 -0
- package/dist/providers/grok/GrokSessionParser.js.map +1 -0
- package/dist/providers/opencode/OpenCodeAdapter.d.ts +1 -0
- package/dist/providers/opencode/OpenCodeAdapter.d.ts.map +1 -1
- package/dist/providers/opencode/OpenCodeAdapter.js +3 -0
- package/dist/providers/opencode/OpenCodeAdapter.js.map +1 -1
- package/dist/providers/opencode/OpenCodeSessionLocator.d.ts +2 -0
- package/dist/providers/opencode/OpenCodeSessionLocator.d.ts.map +1 -1
- package/dist/providers/opencode/OpenCodeSessionLocator.js +31 -12
- package/dist/providers/opencode/OpenCodeSessionLocator.js.map +1 -1
- package/dist/providers/pi/PiAdapter.d.ts +1 -0
- package/dist/providers/pi/PiAdapter.d.ts.map +1 -1
- package/dist/providers/pi/PiAdapter.js +10 -0
- package/dist/providers/pi/PiAdapter.js.map +1 -1
- package/dist/providers/pi/PiSessionLocator.d.ts +1 -0
- package/dist/providers/pi/PiSessionLocator.d.ts.map +1 -1
- package/dist/providers/pi/PiSessionLocator.js +8 -1
- package/dist/providers/pi/PiSessionLocator.js.map +1 -1
- package/dist/utils/session.d.ts +2 -0
- package/dist/utils/session.d.ts.map +1 -1
- package/dist/utils/session.js +3 -0
- package/dist/utils/session.js.map +1 -1
- package/package.json +1 -1
- package/src/AgentManager.ts +34 -0
- package/src/__tests__/AgentManager.test.ts +60 -0
- package/src/__tests__/adapters/ClaudeCodeAdapter.test.ts +23 -0
- package/src/__tests__/adapters/CodexAdapter.test.ts +7 -0
- package/src/__tests__/providers/copilot/CopilotAdapter.test.ts +12 -0
- package/src/__tests__/providers/gemini/GeminiCliAdapter.test.ts +21 -0
- package/src/__tests__/providers/grok/GrokAgentMapper.test.ts +57 -0
- package/src/__tests__/{adapters → providers/grok}/GrokCliAdapter.test.ts +18 -9
- package/src/__tests__/providers/grok/GrokSessionLocator.test.ts +106 -0
- package/src/__tests__/providers/opencode/OpenCodeAdapter.test.ts +18 -0
- package/src/__tests__/providers/pi/PiAdapter.test.ts +15 -0
- package/src/__tests__/utils/session.test.ts +11 -1
- package/src/adapters/AgentAdapter.ts +9 -0
- package/src/adapters/index.ts +1 -1
- package/src/index.ts +1 -1
- package/src/providers/claude/ClaudeCodeAdapter.ts +28 -23
- package/src/providers/claude/ClaudeSessionLocator.ts +20 -0
- package/src/providers/codex/CodexAdapter.ts +8 -0
- package/src/providers/copilot/CopilotAdapter.ts +26 -10
- package/src/providers/copilot/CopilotSessionLocator.ts +7 -1
- package/src/providers/gemini/GeminiCliAdapter.ts +8 -0
- package/src/providers/grok/GrokAgentMapper.ts +41 -0
- package/src/providers/grok/GrokCliAdapter.ts +125 -0
- package/src/providers/grok/GrokSessionLocator.ts +179 -0
- package/src/providers/grok/GrokSessionParser.ts +166 -0
- package/src/providers/opencode/OpenCodeAdapter.ts +4 -0
- package/src/providers/opencode/OpenCodeSessionLocator.ts +43 -15
- package/src/providers/pi/PiAdapter.ts +12 -0
- package/src/providers/pi/PiSessionLocator.ts +16 -1
- package/src/utils/session.ts +11 -0
- package/dist/__tests__/adapters/GrokCliAdapter.test.js.map +0 -1
- package/dist/adapters/GrokCliAdapter.d.ts +0 -80
- package/dist/adapters/GrokCliAdapter.d.ts.map +0 -1
- package/dist/adapters/GrokCliAdapter.js +0 -310
- package/dist/adapters/GrokCliAdapter.js.map +0 -1
- package/src/adapters/GrokCliAdapter.ts +0 -408
|
@@ -16,6 +16,12 @@ export interface OpenCodeSession {
|
|
|
16
16
|
timeCreated: number;
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
interface OpenCodeSessionRow {
|
|
20
|
+
id: string;
|
|
21
|
+
directory: string;
|
|
22
|
+
timeCreated: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
19
25
|
export class OpenCodeSessionLocator {
|
|
20
26
|
private readonly dbPath: string;
|
|
21
27
|
private db: Database.Database | null = null;
|
|
@@ -82,7 +88,7 @@ export class OpenCodeSessionLocator {
|
|
|
82
88
|
|
|
83
89
|
try {
|
|
84
90
|
const rows = db
|
|
85
|
-
.prepare<[],
|
|
91
|
+
.prepare<[], OpenCodeSessionRow>(`
|
|
86
92
|
SELECT id, directory, time_created AS timeCreated
|
|
87
93
|
FROM session
|
|
88
94
|
ORDER BY time_created DESC
|
|
@@ -94,20 +100,7 @@ export class OpenCodeSessionLocator {
|
|
|
94
100
|
for (const row of rows) {
|
|
95
101
|
if (opts?.cwd !== undefined && row.directory !== opts.cwd) continue;
|
|
96
102
|
|
|
97
|
-
|
|
98
|
-
const lastActive =
|
|
99
|
-
stats.lastTimeUpdated > 0 ? new Date(stats.lastTimeUpdated) : new Date(row.timeCreated);
|
|
100
|
-
const startedAt = new Date(row.timeCreated);
|
|
101
|
-
|
|
102
|
-
summaries.push({
|
|
103
|
-
type: "opencode",
|
|
104
|
-
sessionId: row.id,
|
|
105
|
-
cwd: row.directory,
|
|
106
|
-
firstUserMessage: stats.summary,
|
|
107
|
-
lastActive,
|
|
108
|
-
startedAt,
|
|
109
|
-
sessionFilePath: encodeOpenCodeSessionRef(this.dbPath, row.id),
|
|
110
|
-
});
|
|
103
|
+
summaries.push(this.toSessionSummary(db, row));
|
|
111
104
|
}
|
|
112
105
|
|
|
113
106
|
return summaries;
|
|
@@ -117,6 +110,41 @@ export class OpenCodeSessionLocator {
|
|
|
117
110
|
}
|
|
118
111
|
}
|
|
119
112
|
|
|
113
|
+
findSessionsById(sessionId: string): SessionSummary[] {
|
|
114
|
+
const db = this.openDb();
|
|
115
|
+
if (!db) return [];
|
|
116
|
+
|
|
117
|
+
try {
|
|
118
|
+
const row = db
|
|
119
|
+
.prepare<[string], OpenCodeSessionRow>(`
|
|
120
|
+
SELECT id, directory, time_created AS timeCreated
|
|
121
|
+
FROM session
|
|
122
|
+
WHERE id = ?
|
|
123
|
+
`)
|
|
124
|
+
.get(sessionId);
|
|
125
|
+
return row ? [this.toSessionSummary(db, row)] : [];
|
|
126
|
+
} catch {
|
|
127
|
+
this.close();
|
|
128
|
+
return [];
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private toSessionSummary(db: Database.Database, row: OpenCodeSessionRow): SessionSummary {
|
|
133
|
+
const stats = this.parser.getSessionStats(db, row.id);
|
|
134
|
+
const lastActive =
|
|
135
|
+
stats.lastTimeUpdated > 0 ? new Date(stats.lastTimeUpdated) : new Date(row.timeCreated);
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
type: "opencode",
|
|
139
|
+
sessionId: row.id,
|
|
140
|
+
cwd: row.directory,
|
|
141
|
+
firstUserMessage: stats.summary,
|
|
142
|
+
lastActive,
|
|
143
|
+
startedAt: new Date(row.timeCreated),
|
|
144
|
+
sessionFilePath: encodeOpenCodeSessionRef(this.dbPath, row.id),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
120
148
|
get dbFilePath(): string {
|
|
121
149
|
return this.dbPath;
|
|
122
150
|
}
|
|
@@ -92,6 +92,18 @@ export class PiAdapter implements AgentAdapter {
|
|
|
92
92
|
return summaries;
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
+
async findSessionsById(sessionId: string): Promise<SessionSummary[]> {
|
|
96
|
+
const summaries: SessionSummary[] = [];
|
|
97
|
+
const filePaths = this.createLocator().findHistoricalSessionFilesById(sessionId);
|
|
98
|
+
for (const filePath of filePaths) {
|
|
99
|
+
const summary = this.parser.fileToSessionSummary(filePath);
|
|
100
|
+
if (summary?.sessionId === sessionId) summaries.push(summary);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (summaries.length > 0) return summaries;
|
|
104
|
+
return (await this.listSessions()).filter((summary) => summary.sessionId === sessionId);
|
|
105
|
+
}
|
|
106
|
+
|
|
95
107
|
private async getPiProcesses(context?: AgentDetectionContext): Promise<ProcessInfo[]> {
|
|
96
108
|
const snapshot = context?.processes ?? (await captureProcessSnapshot(this.processNames));
|
|
97
109
|
const relevant = filterByProcessNames(snapshot, this.processNames);
|
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import * as path from "path";
|
|
2
2
|
import type { ProcessInfo } from "../../adapters/AgentAdapter.js";
|
|
3
3
|
import { matchProcessesToSessions, type MatchResult } from "../../utils/matching.js";
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
isDirectory,
|
|
6
|
+
isSafePathSegment,
|
|
7
|
+
safeReaddir,
|
|
8
|
+
safeStat,
|
|
9
|
+
type SessionFile,
|
|
10
|
+
} from "../../utils/session.js";
|
|
5
11
|
import { PiSessionParser } from "./PiSessionParser.js";
|
|
6
12
|
|
|
7
13
|
export interface PiSessionLocatorOptions {
|
|
@@ -64,6 +70,15 @@ export class PiSessionLocator {
|
|
|
64
70
|
return this.collectJsonlFiles(this.sessionsDir);
|
|
65
71
|
}
|
|
66
72
|
|
|
73
|
+
findHistoricalSessionFilesById(sessionId: string): string[] {
|
|
74
|
+
if (!isSafePathSegment(sessionId)) return [];
|
|
75
|
+
|
|
76
|
+
return this.collectJsonlFiles(this.sessionsDir).filter((filePath) => {
|
|
77
|
+
const basename = path.basename(filePath, ".jsonl");
|
|
78
|
+
return basename === sessionId || basename.endsWith(`_${sessionId}`);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
67
82
|
private buildProjectDirCwdMap(processes: ProcessInfo[]): Map<string, string> {
|
|
68
83
|
const map = new Map<string, string>();
|
|
69
84
|
for (const proc of processes) {
|
package/src/utils/session.ts
CHANGED
|
@@ -36,6 +36,17 @@ export function isDirectory(p: string): boolean {
|
|
|
36
36
|
return safeStat(p)?.isDirectory() ?? false;
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
/** Return whether a value can be safely appended as one filesystem path segment. */
|
|
40
|
+
export function isSafePathSegment(value: string): boolean {
|
|
41
|
+
return (
|
|
42
|
+
value.length > 0 &&
|
|
43
|
+
value !== "." &&
|
|
44
|
+
value !== ".." &&
|
|
45
|
+
!value.includes("\0") &&
|
|
46
|
+
path.basename(value) === value
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
39
50
|
/**
|
|
40
51
|
* `fs.statSync` that swallows errors and returns `undefined` on failure.
|
|
41
52
|
* Callers can pull whichever fields they need (mtime, birthtime, ...).
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/__tests__/adapters/GrokCliAdapter.test.ts"],"sourcesContent":["/**\n * Tests for GrokCliAdapter\n *\n * The adapter resolves a live process to its cwd via ~/.grok/active_sessions.json\n * and reads session details from chat_history.jsonl (not summary.json/updates.jsonl).\n */\n\nimport type { MockedFunction } from \"vitest\";\nimport * as fs from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\n\nimport { GrokCliAdapter } from \"../../adapters/GrokCliAdapter.js\";\nimport type { ProcessInfo } from \"../../adapters/AgentAdapter.js\";\nimport { AgentStatus } from \"../../adapters/AgentAdapter.js\";\nimport {\n listAgentProcesses,\n enrichProcesses,\n captureProcessSnapshot,\n} from \"../../utils/process.js\";\nimport { generateAgentName } from \"../../utils/matching.js\";\n\nvi.mock(\"../../utils/process.js\", async (importOriginal) => {\n const actual = (await importOriginal()) as typeof import(\"../../utils/process.js\");\n return {\n ...actual,\n listAgentProcesses: vi.fn(),\n enrichProcesses: vi.fn(),\n captureProcessSnapshot: vi.fn(),\n };\n});\n\nvi.mock(\"../../utils/matching.js\", async (importOriginal) => {\n const actual = (await importOriginal()) as typeof import(\"../../utils/matching.js\");\n return {\n ...actual,\n generateAgentName: vi.fn(),\n };\n});\n\nconst mockedListAgentProcesses = listAgentProcesses as MockedFunction<typeof listAgentProcesses>;\nconst mockedEnrichProcesses = enrichProcesses as MockedFunction<typeof enrichProcesses>;\nconst mockedCaptureProcessSnapshot = captureProcessSnapshot as MockedFunction<\n typeof captureProcessSnapshot\n>;\nconst mockedGenerateAgentName = generateAgentName as MockedFunction<typeof generateAgentName>;\n\nconst SESSION_ID = \"019f16c3-5d5d-7dc3-85d1-bc629416ca2d\";\n\n/** A user transcript record: the real prompt wrapped in <user_query> like Grok writes it. */\nconst userRecord = (text: string) => ({\n type: \"user\",\n content: [{ type: \"text\", text: `<user_query>\\n${text}\\n</user_query>` }],\n});\n/** A user context-injection record (no <user_query>) — should be ignored as a prompt. */\nconst contextRecord = (text: string) => ({ type: \"user\", content: [{ type: \"text\", text }] });\nconst assistantRecord = (text: string) => ({\n type: \"assistant\",\n content: [{ type: \"text\", text }],\n});\nconst systemRecord = (text: string) => ({ type: \"system\", content: text });\n\ndescribe(\"GrokCliAdapter\", () => {\n let adapter: GrokCliAdapter;\n let tmpHome: string;\n let cwd: string;\n\n beforeEach(() => {\n tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), \"grok-adapter-test-\"));\n process.env.HOME = tmpHome;\n delete process.env.GROK_HOME;\n cwd = \"/Users/dev/my-project\";\n\n adapter = new GrokCliAdapter();\n\n mockedListAgentProcesses.mockReset();\n mockedEnrichProcesses.mockReset();\n mockedCaptureProcessSnapshot.mockReset();\n mockedGenerateAgentName.mockReset();\n\n mockedEnrichProcesses.mockImplementation((procs) => procs);\n // Compatibility shim for standalone adapter discovery; the manager captures once and slices by name.\n mockedCaptureProcessSnapshot.mockImplementation(async (names) =>\n enrichProcesses(names.flatMap((name) => listAgentProcesses(name))),\n );\n mockedGenerateAgentName.mockImplementation(\n (c: string, pid: number) => `${path.basename(c) || \"unknown\"}-${pid}`,\n );\n });\n\n afterEach(() => {\n fs.rmSync(tmpHome, { recursive: true, force: true });\n });\n\n /** Write a session dir under ~/.grok/sessions/<enc(cwd)>/<id>/chat_history.jsonl. */\n function writeSession(opts: {\n sessionCwd?: string;\n id?: string;\n records?: object[];\n chat?: boolean;\n mtime?: Date;\n }): string {\n const sessionCwd = opts.sessionCwd ?? cwd;\n const id = opts.id ?? SESSION_ID;\n const sessionDir = path.join(tmpHome, \".grok\", \"sessions\", encodeURIComponent(sessionCwd), id);\n fs.mkdirSync(sessionDir, { recursive: true });\n\n if (opts.chat !== false) {\n const records = opts.records ?? [userRecord(\"fix the bug\")];\n const chatPath = path.join(sessionDir, \"chat_history.jsonl\");\n fs.writeFileSync(chatPath, records.map((r) => JSON.stringify(r)).join(\"\\n\"));\n if (opts.mtime) fs.utimesSync(chatPath, opts.mtime, opts.mtime);\n }\n\n return sessionDir;\n }\n\n /** Write ~/.grok/active_sessions.json (the live pid -> cwd registry). */\n function writeActiveSessions(\n entries: Array<{ pid: number; cwd: string; opened_at?: number }>,\n ): void {\n fs.mkdirSync(path.join(tmpHome, \".grok\"), { recursive: true });\n fs.writeFileSync(path.join(tmpHome, \".grok\", \"active_sessions.json\"), JSON.stringify(entries));\n }\n\n function proc(overrides: Partial<ProcessInfo> = {}): ProcessInfo {\n return {\n pid: 4242,\n ppid: 1,\n command: \"grok\",\n cwd,\n tty: \"ttys010\",\n startTime: new Date(),\n ...overrides,\n };\n }\n\n describe(\"initialization\", () => {\n it(\"exposes the grok_cli type\", () => {\n expect(adapter.type).toBe(\"grok_cli\");\n });\n });\n\n describe(\"canHandle\", () => {\n it(\"returns true for a plain grok command\", () => {\n expect(adapter.canHandle(proc({ command: \"grok\" }))).toBe(true);\n });\n\n it(\"returns true for grok with a full path and args\", () => {\n expect(\n adapter.canHandle(proc({ command: \"/Users/dev/.grok/bin/grok --always-approve\" })),\n ).toBe(true);\n });\n\n it(\"returns false for non-grok processes\", () => {\n expect(adapter.canHandle(proc({ command: \"node app.js\" }))).toBe(false);\n });\n\n it('returns false when \"grok\" appears only in an argument path', () => {\n expect(adapter.canHandle(proc({ command: \"node /path/to/grok-thing.js\" }))).toBe(false);\n });\n });\n\n describe(\"detectAgents\", () => {\n it(\"returns [] when there are no grok processes\", async () => {\n mockedListAgentProcesses.mockReturnValue([]);\n expect(await adapter.detectAgents()).toEqual([]);\n });\n\n it(\"resolves the cwd via active_sessions.json (authoritative over the process cwd)\", async () => {\n const realCwd = \"/Users/dev/real-project\";\n writeSession({ sessionCwd: realCwd });\n // The process cwd is stale/wrong; active_sessions.json has the truth.\n writeActiveSessions([{ pid: 4242, cwd: realCwd, opened_at: 1 }]);\n mockedListAgentProcesses.mockReturnValue([proc({ cwd: \"/wrong/path\" })]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents).toHaveLength(1);\n expect(agents[0]).toMatchObject({\n type: \"grok_cli\",\n pid: 4242,\n projectPath: realCwd,\n sessionId: SESSION_ID,\n summary: \"fix the bug\",\n });\n expect(agents[0].sessionFilePath).toBe(\n path.join(\n tmpHome,\n \".grok\",\n \"sessions\",\n encodeURIComponent(realCwd),\n SESSION_ID,\n \"chat_history.jsonl\",\n ),\n );\n });\n\n it(\"falls back to the process cwd when the pid is not in active_sessions.json\", async () => {\n writeSession({});\n writeActiveSessions([{ pid: 9999, cwd: \"/somewhere/else\" }]);\n mockedListAgentProcesses.mockReturnValue([proc()]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents[0]).toMatchObject({ projectPath: cwd, sessionId: SESSION_ID });\n });\n\n it(\"picks the most recently active session dir when a cwd has several\", async () => {\n const older = new Date(Date.now() - 60 * 60 * 1000);\n writeSession({\n id: \"019f0000-0000-7000-8000-00000000000a\",\n records: [userRecord(\"old one\")],\n mtime: older,\n });\n writeSession({\n id: \"019f0000-0000-7000-8000-00000000000b\",\n records: [userRecord(\"newest one\")],\n });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents[0].sessionId).toBe(\"019f0000-0000-7000-8000-00000000000b\");\n expect(agents[0].summary).toBe(\"newest one\");\n });\n\n it(\"falls back to a process-only RUNNING agent when no session matches\", async () => {\n mockedListAgentProcesses.mockReturnValue([proc()]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents).toHaveLength(1);\n expect(agents[0].status).toBe(AgentStatus.RUNNING);\n expect(agents[0].sessionId).toBe(\"pid-4242\");\n expect(agents[0].sessionFilePath).toBeUndefined();\n });\n\n it(\"treats a session dir without chat_history.jsonl as no match (process-only)\", async () => {\n writeSession({ chat: false });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n\n const agents = await adapter.detectAgents();\n\n expect(agents).toHaveLength(1);\n expect(agents[0].sessionId).toBe(\"pid-4242\");\n });\n });\n\n describe(\"getConversation\", () => {\n it(\"maps user (<user_query>) and assistant records to roles\", () => {\n const dir = writeSession({ records: [userRecord(\"hi\"), assistantRecord(\"hello\")] });\n expect(adapter.getConversation(path.join(dir, \"chat_history.jsonl\"))).toEqual([\n { role: \"user\", content: \"hi\" },\n { role: \"assistant\", content: \"hello\" },\n ]);\n });\n\n it(\"accepts a session dir path and skips context-injection user records\", () => {\n const dir = writeSession({\n records: [contextRecord(\"<user_info>OS: macos</user_info>\"), userRecord(\"do the thing\")],\n });\n expect(adapter.getConversation(dir)).toEqual([{ role: \"user\", content: \"do the thing\" }]);\n });\n\n it(\"skips malformed lines\", () => {\n const dir = writeSession({ records: [userRecord(\"hi\")] });\n fs.appendFileSync(path.join(dir, \"chat_history.jsonl\"), \"\\n{bad json\");\n expect(adapter.getConversation(dir)).toEqual([{ role: \"user\", content: \"hi\" }]);\n });\n\n it(\"excludes system records unless verbose\", () => {\n const dir = writeSession({ records: [systemRecord(\"You are Grok\"), userRecord(\"go\")] });\n expect(adapter.getConversation(dir)).toEqual([{ role: \"user\", content: \"go\" }]);\n expect(adapter.getConversation(dir, { verbose: true }).map((m) => m.role)).toEqual([\n \"system\",\n \"user\",\n ]);\n });\n });\n\n describe(\"detectAgents status + summary mapping\", () => {\n const detectFirst = async () => (await adapter.detectAgents())[0];\n\n it(\"marks WAITING when the last transcript turn is an assistant message\", async () => {\n writeSession({ records: [userRecord(\"go\"), assistantRecord(\"done\")] });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n expect((await detectFirst()).status).toBe(AgentStatus.WAITING);\n });\n\n it(\"marks RUNNING when the last transcript turn is a user message\", async () => {\n writeSession({ records: [userRecord(\"still there?\")] });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n expect((await detectFirst()).status).toBe(AgentStatus.RUNNING);\n });\n\n it(\"marks IDLE when chat_history.jsonl is older than the threshold\", async () => {\n const old = new Date(Date.now() - 10 * 60 * 1000);\n writeSession({ records: [userRecord(\"go\")], mtime: old });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n expect((await detectFirst()).status).toBe(AgentStatus.IDLE);\n });\n\n it(\"uses the last user prompt as the agent summary\", async () => {\n writeSession({ records: [userRecord(\"refactor the parser\"), assistantRecord(\"on it\")] });\n mockedListAgentProcesses.mockReturnValue([proc()]);\n expect((await detectFirst()).summary).toBe(\"refactor the parser\");\n });\n });\n\n describe(\"listSessions\", () => {\n it(\"returns [] when the sessions dir does not exist\", async () => {\n expect(await adapter.listSessions()).toEqual([]);\n });\n\n it(\"lists historical sessions with cwd decoded from the group dir\", async () => {\n writeSession({});\n const summaries = await adapter.listSessions();\n expect(summaries).toHaveLength(1);\n expect(summaries[0]).toMatchObject({\n type: \"grok_cli\",\n sessionId: SESSION_ID,\n cwd,\n firstUserMessage: \"fix the bug\",\n });\n expect(summaries[0].sessionFilePath).toBe(\n path.join(\n tmpHome,\n \".grok\",\n \"sessions\",\n encodeURIComponent(cwd),\n SESSION_ID,\n \"chat_history.jsonl\",\n ),\n );\n });\n\n it(\"applies the cwd filter against the decoded cwd\", async () => {\n writeSession({\n sessionCwd: \"/Users/dev/project-a\",\n id: \"019f0000-0000-7000-8000-00000000000a\",\n });\n writeSession({\n sessionCwd: \"/Users/dev/project-b\",\n id: \"019f0000-0000-7000-8000-00000000000b\",\n });\n\n const all = await adapter.listSessions();\n expect(all).toHaveLength(2);\n\n const filtered = await adapter.listSessions({ cwd: \"/Users/dev/project-a\" });\n expect(filtered).toHaveLength(1);\n expect(filtered[0].cwd).toBe(\"/Users/dev/project-a\");\n });\n\n it(\"skips non-session entries (e.g. prompt_history.jsonl) in a group dir\", async () => {\n writeSession({});\n // Grok writes a group-level prompt_history.jsonl alongside session dirs.\n fs.writeFileSync(\n path.join(tmpHome, \".grok\", \"sessions\", encodeURIComponent(cwd), \"prompt_history.jsonl\"),\n '{\"text\":\"noise\"}',\n );\n const summaries = await adapter.listSessions();\n expect(summaries).toHaveLength(1);\n });\n });\n});\n"],"names":["fs","os","path","GrokCliAdapter","AgentStatus","listAgentProcesses","enrichProcesses","captureProcessSnapshot","generateAgentName","vi","mock","importOriginal","actual","fn","mockedListAgentProcesses","mockedEnrichProcesses","mockedCaptureProcessSnapshot","mockedGenerateAgentName","SESSION_ID","userRecord","text","type","content","contextRecord","assistantRecord","systemRecord","describe","adapter","tmpHome","cwd","beforeEach","mkdtempSync","join","tmpdir","process","env","HOME","GROK_HOME","mockReset","mockImplementation","procs","names","flatMap","name","c","pid","basename","afterEach","rmSync","recursive","force","writeSession","opts","sessionCwd","id","sessionDir","encodeURIComponent","mkdirSync","chat","records","chatPath","writeFileSync","map","r","JSON","stringify","mtime","utimesSync","writeActiveSessions","entries","proc","overrides","ppid","command","tty","startTime","Date","it","expect","toBe","canHandle","mockReturnValue","detectAgents","toEqual","realCwd","opened_at","agents","toHaveLength","toMatchObject","projectPath","sessionId","summary","sessionFilePath","older","now","status","RUNNING","toBeUndefined","dir","getConversation","role","appendFileSync","verbose","m","detectFirst","WAITING","old","IDLE","listSessions","summaries","firstUserMessage","all","filtered"],"mappings":"AAAA;;;;;CAKC,GAGD,YAAYA,QAAQ,KAAK;AACzB,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAA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;YACtC9B,OAAOiC,KAAKxB,YAAY,CAAC;YAEzB,MAAMyB,WAAW,MAAMrF,QAAQiF,YAAY,CAAC;gBAAE/E,KAAK;YAAuB;YAC1EiD,OAAOkC,UAAUzB,YAAY,CAAC;YAC9BT,OAAOkC,QAAQ,CAAC,EAAE,CAACnF,GAAG,EAAEkD,IAAI,CAAC;QAC/B;QAEAF,GAAG,wEAAwE;YACzE1B,aAAa,CAAC;YACd,yEAAyE;YACzEnD,GAAG6D,aAAa,CACd3D,KAAK8B,IAAI,CAACJ,SAAS,SAAS,YAAY4B,mBAAmB3B,MAAM,yBACjE;YAEF,MAAMgF,YAAY,MAAMlF,QAAQiF,YAAY;YAC5C9B,OAAO+B,WAAWtB,YAAY,CAAC;QACjC;IACF;AACF"}
|
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
import type { AgentAdapter, AgentInfo, ProcessInfo, ConversationMessage, SessionSummary, ListSessionsOptions, AgentDetectionContext } from "./AgentAdapter.js";
|
|
2
|
-
export declare class GrokCliAdapter implements AgentAdapter {
|
|
3
|
-
readonly type: "grok_cli";
|
|
4
|
-
readonly processNames: readonly ["grok"];
|
|
5
|
-
private base;
|
|
6
|
-
private sessionsDir;
|
|
7
|
-
constructor();
|
|
8
|
-
canHandle(processInfo: ProcessInfo): boolean;
|
|
9
|
-
private isGrokExecutable;
|
|
10
|
-
detectAgents(context?: AgentDetectionContext): Promise<AgentInfo[]>;
|
|
11
|
-
/**
|
|
12
|
-
* Read ~/.grok/active_sessions.json into a pid -> cwd map. Grok writes one
|
|
13
|
-
* { pid, cwd, opened_at } entry per running session and removes it on exit,
|
|
14
|
-
* so this is the reliable way to learn a live process's working directory.
|
|
15
|
-
*/
|
|
16
|
-
private readActiveSessions;
|
|
17
|
-
/**
|
|
18
|
-
* Full paths of the session subdirectories directly under a group dir,
|
|
19
|
-
* skipping any non-directory entries. Shared by latestSessionDir() and
|
|
20
|
-
* listSessions() so both enumerate session dirs the same way.
|
|
21
|
-
*/
|
|
22
|
-
private listSessionDirs;
|
|
23
|
-
/**
|
|
24
|
-
* Return the most recently active session subdirectory for a cwd, i.e. the
|
|
25
|
-
* ~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/ whose chat_history.jsonl
|
|
26
|
-
* was written last. Returns null when the group dir or any transcript is
|
|
27
|
-
* missing.
|
|
28
|
-
*/
|
|
29
|
-
private latestSessionDir;
|
|
30
|
-
private mapSessionToAgent;
|
|
31
|
-
private mapProcessOnlyAgent;
|
|
32
|
-
getConversation(sessionFilePath: string, options?: {
|
|
33
|
-
verbose?: boolean;
|
|
34
|
-
}): ConversationMessage[];
|
|
35
|
-
listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]>;
|
|
36
|
-
/**
|
|
37
|
-
* Parse a session directory into a {@link GrokSession} from its
|
|
38
|
-
* chat_history.jsonl transcript. Returns null when the transcript is
|
|
39
|
-
* missing — i.e. there is no real session to surface.
|
|
40
|
-
*/
|
|
41
|
-
private readSession;
|
|
42
|
-
/**
|
|
43
|
-
* Determine agent status from parsed session state.
|
|
44
|
-
*
|
|
45
|
-
* - past the idle threshold → IDLE
|
|
46
|
-
* - last transcript turn is an assistant message → WAITING (awaiting user)
|
|
47
|
-
* - otherwise (last turn was a user message, or unknown) → RUNNING
|
|
48
|
-
*/
|
|
49
|
-
private determineStatus;
|
|
50
|
-
/**
|
|
51
|
-
* Single pass over chat_history.jsonl. Each line is a
|
|
52
|
-
* { type: 'system' | 'user' | 'assistant', content } record where content is
|
|
53
|
-
* either a string or an array of { type: 'text', text } blocks.
|
|
54
|
-
*
|
|
55
|
-
* Grok wraps the real user prompt in <user_query>...</user_query>; the other
|
|
56
|
-
* user records are context injections (<user_info>, <system-reminder>, ...)
|
|
57
|
-
* and are skipped so the summary is the actual prompt, not boilerplate.
|
|
58
|
-
*/
|
|
59
|
-
private parseChatHistory;
|
|
60
|
-
/** Flatten a chat record's content (string or text-block array) to text. */
|
|
61
|
-
private extractText;
|
|
62
|
-
/**
|
|
63
|
-
* Extract the prompt inside <user_query>...</user_query>. Returns null when
|
|
64
|
-
* the record has no such tag (a context injection rather than a prompt).
|
|
65
|
-
*/
|
|
66
|
-
private extractUserQuery;
|
|
67
|
-
/** Resolve a session dir or an explicit chat_history.jsonl path to the file. */
|
|
68
|
-
private resolveChatPath;
|
|
69
|
-
private getProjectDir;
|
|
70
|
-
/**
|
|
71
|
-
* Resolve the working directory a session group dir was created for.
|
|
72
|
-
*
|
|
73
|
-
* The common case is `decodeURIComponent(<group-name>)`. For paths whose
|
|
74
|
-
* encoded form exceeds the filesystem limit Grok uses a slug+hash and records
|
|
75
|
-
* the original path in a `.cwd` file inside the group — prefer that when
|
|
76
|
-
* present.
|
|
77
|
-
*/
|
|
78
|
-
private decodeGroupCwd;
|
|
79
|
-
}
|
|
80
|
-
//# sourceMappingURL=GrokCliAdapter.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"GrokCliAdapter.d.ts","sourceRoot":"","sources":["../../src/adapters/GrokCliAdapter.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,YAAY,EACZ,SAAS,EACT,WAAW,EACX,mBAAmB,EACnB,cAAc,EACd,mBAAmB,EACnB,qBAAqB,EACtB,MAAM,mBAAmB,CAAC;AAiE3B,qBAAa,cAAe,YAAW,YAAY;IACjD,QAAQ,CAAC,IAAI,EAAG,UAAU,CAAU;IACpC,QAAQ,CAAC,YAAY,oBAAqB;IAE1C,OAAO,CAAC,IAAI,CAAS;IACrB,OAAO,CAAC,WAAW,CAAS;;IAW5B,SAAS,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO;IAI5C,OAAO,CAAC,gBAAgB;IAKlB,YAAY,CAAC,OAAO,CAAC,EAAE,qBAAqB,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IA4BzE;;;;OAIG;IACH,OAAO,CAAC,kBAAkB;IAqB1B;;;;OAIG;IACH,OAAO,CAAC,eAAe;IAMvB;;;;;OAKG;IACH,OAAO,CAAC,gBAAgB;IAexB,OAAO,CAAC,iBAAiB;IAmBzB,OAAO,CAAC,mBAAmB;IAc3B,eAAe,CAAC,eAAe,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,mBAAmB,EAAE;IAK1F,YAAY,CAAC,IAAI,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;IAoCzE;;;;OAIG;IACH,OAAO,CAAC,WAAW;IAqBnB;;;;;;OAMG;IACH,OAAO,CAAC,eAAe;IAWvB;;;;;;;;OAQG;IACH,OAAO,CAAC,gBAAgB;IA2CxB,4EAA4E;IAC5E,OAAO,CAAC,WAAW;IAgBnB;;;OAGG;IACH,OAAO,CAAC,gBAAgB;IAKxB,gFAAgF;IAChF,OAAO,CAAC,eAAe;IAIvB,OAAO,CAAC,aAAa;IAIrB;;;;;;;OAOG;IACH,OAAO,CAAC,cAAc;CASvB"}
|
|
@@ -1,310 +0,0 @@
|
|
|
1
|
-
import * as path from "path";
|
|
2
|
-
import { AgentStatus } from "./AgentAdapter.js";
|
|
3
|
-
import { captureProcessSnapshot, executableBasename, filterByProcessNames } from "../utils/process.js";
|
|
4
|
-
import { isDirectory, safeReadFile, safeReaddir, safeStat } from "../utils/session.js";
|
|
5
|
-
import { generateAgentName } from "../utils/matching.js";
|
|
6
|
-
/**
|
|
7
|
-
* Grok Build CLI Adapter
|
|
8
|
-
*
|
|
9
|
-
* Detects running Grok Build CLI agents by:
|
|
10
|
-
* 1. Filtering `grok` processes from a shared asynchronous snapshot — Grok is
|
|
11
|
-
* a native binary at ~/.grok/bin/grok, so argv[0] basename is `grok`.
|
|
12
|
-
* 2. Resolving each live process to its working directory via
|
|
13
|
-
* ~/.grok/active_sessions.json, which Grok maintains as a list of
|
|
14
|
-
* { pid, cwd, opened_at } for every running session. The cwd is then encoded
|
|
15
|
-
* into the session group dir ~/.grok/sessions/<encodeURIComponent(cwd)>/, and
|
|
16
|
-
* the most recently active session subdirectory is picked from it. The
|
|
17
|
-
* process cwd from lsof is only a fallback when the PID is not registered.
|
|
18
|
-
* 3. Reading the session transcript from chat_history.jsonl (the authoritative
|
|
19
|
-
* record of the conversation). The last user turn (the text inside
|
|
20
|
-
* <user_query>...</user_query>) is the summary; the file's mtime is the last
|
|
21
|
-
* activity time. summary.json / updates.jsonl are intentionally not used.
|
|
22
|
-
*/ const CHAT_HISTORY_FILE = "chat_history.jsonl";
|
|
23
|
-
const ACTIVE_SESSIONS_FILE = "active_sessions.json";
|
|
24
|
-
const CWD_FILE = ".cwd";
|
|
25
|
-
const IDLE_THRESHOLD_MINUTES = 5;
|
|
26
|
-
export class GrokCliAdapter {
|
|
27
|
-
type = "grok_cli";
|
|
28
|
-
processNames = [
|
|
29
|
-
"grok"
|
|
30
|
-
];
|
|
31
|
-
base;
|
|
32
|
-
sessionsDir;
|
|
33
|
-
constructor(){
|
|
34
|
-
// GROK_HOME overrides the ~/.grok base directory; sessions live under
|
|
35
|
-
// <base>/sessions/ and the active-session registry at
|
|
36
|
-
// <base>/active_sessions.json.
|
|
37
|
-
const homeDir = process.env.HOME || process.env.USERPROFILE || "";
|
|
38
|
-
this.base = process.env.GROK_HOME || path.join(homeDir, ".grok");
|
|
39
|
-
this.sessionsDir = path.join(this.base, "sessions");
|
|
40
|
-
}
|
|
41
|
-
canHandle(processInfo) {
|
|
42
|
-
return this.isGrokExecutable(processInfo.command);
|
|
43
|
-
}
|
|
44
|
-
isGrokExecutable(command) {
|
|
45
|
-
const base = executableBasename(command);
|
|
46
|
-
return base === "grok" || base === "grok.exe";
|
|
47
|
-
}
|
|
48
|
-
async detectAgents(context) {
|
|
49
|
-
const snapshot = context?.processes ?? await captureProcessSnapshot(this.processNames);
|
|
50
|
-
const relevant = filterByProcessNames(snapshot, this.processNames);
|
|
51
|
-
const processes = relevant.filter((process1)=>this.canHandle(process1));
|
|
52
|
-
if (processes.length === 0) {
|
|
53
|
-
return [];
|
|
54
|
-
}
|
|
55
|
-
// active_sessions.json is the authoritative pid -> cwd map for live
|
|
56
|
-
// sessions; the lsof-derived process cwd is only a fallback.
|
|
57
|
-
const pidToCwd = this.readActiveSessions();
|
|
58
|
-
const agents = [];
|
|
59
|
-
for (const proc of processes){
|
|
60
|
-
const cwd = pidToCwd.get(proc.pid) || proc.cwd || "";
|
|
61
|
-
const sessionDir = cwd ? this.latestSessionDir(cwd) : null;
|
|
62
|
-
const session = sessionDir ? this.readSession(sessionDir, cwd) : null;
|
|
63
|
-
if (session && sessionDir) {
|
|
64
|
-
agents.push(this.mapSessionToAgent(session, proc, sessionDir));
|
|
65
|
-
} else {
|
|
66
|
-
agents.push(this.mapProcessOnlyAgent(proc, cwd));
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
return agents;
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* Read ~/.grok/active_sessions.json into a pid -> cwd map. Grok writes one
|
|
73
|
-
* { pid, cwd, opened_at } entry per running session and removes it on exit,
|
|
74
|
-
* so this is the reliable way to learn a live process's working directory.
|
|
75
|
-
*/ readActiveSessions() {
|
|
76
|
-
const map = new Map();
|
|
77
|
-
const content = safeReadFile(path.join(this.base, ACTIVE_SESSIONS_FILE));
|
|
78
|
-
if (content === undefined) return map;
|
|
79
|
-
let entries;
|
|
80
|
-
try {
|
|
81
|
-
entries = JSON.parse(content);
|
|
82
|
-
} catch {
|
|
83
|
-
return map;
|
|
84
|
-
}
|
|
85
|
-
if (!Array.isArray(entries)) return map;
|
|
86
|
-
for (const entry of entries){
|
|
87
|
-
if (typeof entry?.pid === "number" && typeof entry?.cwd === "string" && entry.cwd) {
|
|
88
|
-
map.set(entry.pid, entry.cwd);
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
return map;
|
|
92
|
-
}
|
|
93
|
-
/**
|
|
94
|
-
* Full paths of the session subdirectories directly under a group dir,
|
|
95
|
-
* skipping any non-directory entries. Shared by latestSessionDir() and
|
|
96
|
-
* listSessions() so both enumerate session dirs the same way.
|
|
97
|
-
*/ listSessionDirs(groupDir) {
|
|
98
|
-
return safeReaddir(groupDir).map((sessionId)=>path.join(groupDir, sessionId)).filter((sessionDir)=>isDirectory(sessionDir));
|
|
99
|
-
}
|
|
100
|
-
/**
|
|
101
|
-
* Return the most recently active session subdirectory for a cwd, i.e. the
|
|
102
|
-
* ~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/ whose chat_history.jsonl
|
|
103
|
-
* was written last. Returns null when the group dir or any transcript is
|
|
104
|
-
* missing.
|
|
105
|
-
*/ latestSessionDir(cwd) {
|
|
106
|
-
const groupDir = this.getProjectDir(cwd);
|
|
107
|
-
if (!isDirectory(groupDir)) return null;
|
|
108
|
-
let best = null;
|
|
109
|
-
for (const sessionDir of this.listSessionDirs(groupDir)){
|
|
110
|
-
const stat = safeStat(path.join(sessionDir, CHAT_HISTORY_FILE));
|
|
111
|
-
if (!stat) continue;
|
|
112
|
-
if (!best || stat.mtimeMs > best.mtimeMs) {
|
|
113
|
-
best = {
|
|
114
|
-
dir: sessionDir,
|
|
115
|
-
mtimeMs: stat.mtimeMs
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
return best?.dir ?? null;
|
|
120
|
-
}
|
|
121
|
-
mapSessionToAgent(session, processInfo, sessionDir) {
|
|
122
|
-
const projectPath = session.projectPath || processInfo.cwd || "";
|
|
123
|
-
return {
|
|
124
|
-
name: generateAgentName(projectPath, processInfo.pid),
|
|
125
|
-
type: this.type,
|
|
126
|
-
status: this.determineStatus(session),
|
|
127
|
-
summary: session.summary || "Grok CLI session active",
|
|
128
|
-
pid: processInfo.pid,
|
|
129
|
-
projectPath,
|
|
130
|
-
sessionId: session.sessionId,
|
|
131
|
-
lastActive: session.lastActive,
|
|
132
|
-
sessionFilePath: path.join(sessionDir, CHAT_HISTORY_FILE)
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
mapProcessOnlyAgent(processInfo, cwd) {
|
|
136
|
-
const projectPath = cwd || processInfo.cwd || "";
|
|
137
|
-
return {
|
|
138
|
-
name: generateAgentName(projectPath, processInfo.pid),
|
|
139
|
-
type: this.type,
|
|
140
|
-
status: AgentStatus.RUNNING,
|
|
141
|
-
summary: "Grok CLI process running",
|
|
142
|
-
pid: processInfo.pid,
|
|
143
|
-
projectPath,
|
|
144
|
-
sessionId: `pid-${processInfo.pid}`,
|
|
145
|
-
lastActive: new Date()
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
getConversation(sessionFilePath, options) {
|
|
149
|
-
return this.parseChatHistory(this.resolveChatPath(sessionFilePath), options?.verbose ?? false).messages;
|
|
150
|
-
}
|
|
151
|
-
async listSessions(opts) {
|
|
152
|
-
if (!isDirectory(this.sessionsDir)) return [];
|
|
153
|
-
const filterCwd = opts?.cwd;
|
|
154
|
-
const summaries = [];
|
|
155
|
-
for (const groupName of safeReaddir(this.sessionsDir)){
|
|
156
|
-
const groupDir = path.join(this.sessionsDir, groupName);
|
|
157
|
-
if (!isDirectory(groupDir)) continue;
|
|
158
|
-
const decodedCwd = this.decodeGroupCwd(groupName, groupDir);
|
|
159
|
-
for (const sessionDir of this.listSessionDirs(groupDir)){
|
|
160
|
-
const session = this.readSession(sessionDir, decodedCwd);
|
|
161
|
-
if (!session) continue;
|
|
162
|
-
const cwd = session.projectPath || decodedCwd;
|
|
163
|
-
if (filterCwd !== undefined && cwd !== filterCwd) continue;
|
|
164
|
-
summaries.push({
|
|
165
|
-
type: this.type,
|
|
166
|
-
sessionId: session.sessionId,
|
|
167
|
-
cwd,
|
|
168
|
-
firstUserMessage: session.firstUserMessage || "",
|
|
169
|
-
lastActive: session.lastActive,
|
|
170
|
-
startedAt: session.sessionStart,
|
|
171
|
-
sessionFilePath: path.join(sessionDir, CHAT_HISTORY_FILE)
|
|
172
|
-
});
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
return summaries;
|
|
176
|
-
}
|
|
177
|
-
// --- Session parsing (chat_history.jsonl) ---
|
|
178
|
-
/**
|
|
179
|
-
* Parse a session directory into a {@link GrokSession} from its
|
|
180
|
-
* chat_history.jsonl transcript. Returns null when the transcript is
|
|
181
|
-
* missing — i.e. there is no real session to surface.
|
|
182
|
-
*/ readSession(sessionDir, defaultCwd) {
|
|
183
|
-
const chatPath = path.join(sessionDir, CHAT_HISTORY_FILE);
|
|
184
|
-
const chatStat = safeStat(chatPath);
|
|
185
|
-
if (!chatStat) return null;
|
|
186
|
-
const scan = this.parseChatHistory(chatPath, false);
|
|
187
|
-
const dirStat = safeStat(sessionDir);
|
|
188
|
-
const lastActive = chatStat.mtime;
|
|
189
|
-
return {
|
|
190
|
-
sessionId: path.basename(sessionDir),
|
|
191
|
-
projectPath: defaultCwd || "",
|
|
192
|
-
summary: scan.lastUserMessage || "Grok CLI session active",
|
|
193
|
-
sessionStart: dirStat?.birthtime || lastActive,
|
|
194
|
-
lastActive,
|
|
195
|
-
firstUserMessage: scan.firstUserMessage,
|
|
196
|
-
lastUserMessage: scan.lastUserMessage,
|
|
197
|
-
lastRole: scan.lastRole
|
|
198
|
-
};
|
|
199
|
-
}
|
|
200
|
-
/**
|
|
201
|
-
* Determine agent status from parsed session state.
|
|
202
|
-
*
|
|
203
|
-
* - past the idle threshold → IDLE
|
|
204
|
-
* - last transcript turn is an assistant message → WAITING (awaiting user)
|
|
205
|
-
* - otherwise (last turn was a user message, or unknown) → RUNNING
|
|
206
|
-
*/ determineStatus(session) {
|
|
207
|
-
const diffMinutes = (Date.now() - session.lastActive.getTime()) / 60000;
|
|
208
|
-
if (diffMinutes > IDLE_THRESHOLD_MINUTES) {
|
|
209
|
-
return AgentStatus.IDLE;
|
|
210
|
-
}
|
|
211
|
-
if (session.lastRole === "assistant") {
|
|
212
|
-
return AgentStatus.WAITING;
|
|
213
|
-
}
|
|
214
|
-
return AgentStatus.RUNNING;
|
|
215
|
-
}
|
|
216
|
-
/**
|
|
217
|
-
* Single pass over chat_history.jsonl. Each line is a
|
|
218
|
-
* { type: 'system' | 'user' | 'assistant', content } record where content is
|
|
219
|
-
* either a string or an array of { type: 'text', text } blocks.
|
|
220
|
-
*
|
|
221
|
-
* Grok wraps the real user prompt in <user_query>...</user_query>; the other
|
|
222
|
-
* user records are context injections (<user_info>, <system-reminder>, ...)
|
|
223
|
-
* and are skipped so the summary is the actual prompt, not boilerplate.
|
|
224
|
-
*/ parseChatHistory(chatPath, verbose) {
|
|
225
|
-
const empty = {
|
|
226
|
-
messages: []
|
|
227
|
-
};
|
|
228
|
-
const content = safeReadFile(chatPath);
|
|
229
|
-
if (content === undefined) return empty;
|
|
230
|
-
const messages = [];
|
|
231
|
-
let lastRole;
|
|
232
|
-
for (const line of content.trim().split("\n")){
|
|
233
|
-
if (!line.trim()) continue;
|
|
234
|
-
let record;
|
|
235
|
-
try {
|
|
236
|
-
record = JSON.parse(line);
|
|
237
|
-
} catch {
|
|
238
|
-
continue;
|
|
239
|
-
}
|
|
240
|
-
const text = this.extractText(record.content);
|
|
241
|
-
if (record.type === "user") {
|
|
242
|
-
const query = this.extractUserQuery(text);
|
|
243
|
-
if (query === null) continue; // context injection, not a real prompt
|
|
244
|
-
messages.push({
|
|
245
|
-
role: "user",
|
|
246
|
-
content: query
|
|
247
|
-
});
|
|
248
|
-
lastRole = "user";
|
|
249
|
-
} else if (record.type === "assistant") {
|
|
250
|
-
if (!text) continue;
|
|
251
|
-
messages.push({
|
|
252
|
-
role: "assistant",
|
|
253
|
-
content: text
|
|
254
|
-
});
|
|
255
|
-
lastRole = "assistant";
|
|
256
|
-
} else if (verbose && record.type === "system") {
|
|
257
|
-
if (!text) continue;
|
|
258
|
-
messages.push({
|
|
259
|
-
role: "system",
|
|
260
|
-
content: text
|
|
261
|
-
});
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
const userTurns = messages.filter((m)=>m.role === "user");
|
|
265
|
-
return {
|
|
266
|
-
messages,
|
|
267
|
-
firstUserMessage: userTurns[0]?.content,
|
|
268
|
-
lastUserMessage: userTurns[userTurns.length - 1]?.content,
|
|
269
|
-
lastRole
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
/** Flatten a chat record's content (string or text-block array) to text. */ extractText(content) {
|
|
273
|
-
if (typeof content === "string") return content;
|
|
274
|
-
if (Array.isArray(content)) {
|
|
275
|
-
return content.map((block)=>block && typeof block === "object" && typeof block.text === "string" ? block.text : "").join("");
|
|
276
|
-
}
|
|
277
|
-
return "";
|
|
278
|
-
}
|
|
279
|
-
/**
|
|
280
|
-
* Extract the prompt inside <user_query>...</user_query>. Returns null when
|
|
281
|
-
* the record has no such tag (a context injection rather than a prompt).
|
|
282
|
-
*/ extractUserQuery(text) {
|
|
283
|
-
const match = text.match(/<user_query>\s*([\s\S]*?)\s*<\/user_query>/);
|
|
284
|
-
return match ? match[1].trim() : null;
|
|
285
|
-
}
|
|
286
|
-
/** Resolve a session dir or an explicit chat_history.jsonl path to the file. */ resolveChatPath(sessionPath) {
|
|
287
|
-
return sessionPath.endsWith(".jsonl") ? sessionPath : path.join(sessionPath, CHAT_HISTORY_FILE);
|
|
288
|
-
}
|
|
289
|
-
getProjectDir(cwd) {
|
|
290
|
-
return path.join(this.sessionsDir, encodeURIComponent(cwd));
|
|
291
|
-
}
|
|
292
|
-
/**
|
|
293
|
-
* Resolve the working directory a session group dir was created for.
|
|
294
|
-
*
|
|
295
|
-
* The common case is `decodeURIComponent(<group-name>)`. For paths whose
|
|
296
|
-
* encoded form exceeds the filesystem limit Grok uses a slug+hash and records
|
|
297
|
-
* the original path in a `.cwd` file inside the group — prefer that when
|
|
298
|
-
* present.
|
|
299
|
-
*/ decodeGroupCwd(groupName, groupDir) {
|
|
300
|
-
const fromFile = safeReadFile(path.join(groupDir, CWD_FILE));
|
|
301
|
-
if (fromFile !== undefined && fromFile.trim()) return fromFile.trim();
|
|
302
|
-
try {
|
|
303
|
-
return decodeURIComponent(groupName);
|
|
304
|
-
} catch {
|
|
305
|
-
return "";
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
//# sourceMappingURL=GrokCliAdapter.js.map
|