@ai-devkit/agent-manager 0.22.1 → 0.25.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 -0
- package/dist/__tests__/AgentManager.test.js +9 -1
- package/dist/__tests__/AgentManager.test.js.map +1 -1
- package/dist/__tests__/adapters/GrokCliAdapter.test.js +403 -0
- package/dist/__tests__/adapters/GrokCliAdapter.test.js.map +1 -0
- package/dist/__tests__/terminal/TerminalFocusManager.test.js +180 -0
- package/dist/__tests__/terminal/TerminalFocusManager.test.js.map +1 -1
- package/dist/__tests__/terminal/TtyWriter.test.js +206 -0
- package/dist/__tests__/terminal/TtyWriter.test.js.map +1 -1
- package/dist/__tests__/utils/agent-requests.test.js +90 -0
- package/dist/__tests__/utils/agent-requests.test.js.map +1 -0
- package/dist/__tests__/utils/agents.test.js +6 -0
- package/dist/__tests__/utils/agents.test.js.map +1 -1
- package/dist/adapters/AgentAdapter.d.ts +1 -1
- package/dist/adapters/AgentAdapter.d.ts.map +1 -1
- package/dist/adapters/AgentAdapter.js.map +1 -1
- package/dist/adapters/GrokCliAdapter.d.ts +79 -0
- package/dist/adapters/GrokCliAdapter.d.ts.map +1 -0
- package/dist/adapters/GrokCliAdapter.js +306 -0
- package/dist/adapters/GrokCliAdapter.js.map +1 -0
- package/dist/adapters/index.d.ts +1 -0
- package/dist/adapters/index.d.ts.map +1 -1
- package/dist/adapters/index.js +1 -0
- package/dist/adapters/index.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/terminal/TerminalFocusManager.d.ts +11 -0
- package/dist/terminal/TerminalFocusManager.d.ts.map +1 -1
- package/dist/terminal/TerminalFocusManager.js +84 -10
- package/dist/terminal/TerminalFocusManager.js.map +1 -1
- package/dist/terminal/TtyWriter.d.ts +19 -0
- package/dist/terminal/TtyWriter.d.ts.map +1 -1
- package/dist/terminal/TtyWriter.js +167 -1
- package/dist/terminal/TtyWriter.js.map +1 -1
- package/dist/utils/agent-requests.d.ts +10 -0
- package/dist/utils/agent-requests.d.ts.map +1 -0
- package/dist/utils/agent-requests.js +22 -0
- package/dist/utils/agent-requests.js.map +1 -0
- package/dist/utils/agents.d.ts +1 -1
- package/dist/utils/agents.d.ts.map +1 -1
- package/dist/utils/agents.js +4 -0
- package/dist/utils/agents.js.map +1 -1
- package/package.json +2 -2
- package/src/__tests__/AgentManager.test.ts +7 -1
- package/src/__tests__/adapters/GrokCliAdapter.test.ts +307 -0
- package/src/__tests__/terminal/TerminalFocusManager.test.ts +187 -0
- package/src/__tests__/terminal/TtyWriter.test.ts +234 -0
- package/src/__tests__/utils/agent-requests.test.ts +74 -0
- package/src/__tests__/utils/agents.test.ts +7 -0
- package/src/adapters/AgentAdapter.ts +1 -1
- package/src/adapters/GrokCliAdapter.ts +394 -0
- package/src/adapters/index.ts +1 -0
- package/src/index.ts +4 -0
- package/src/terminal/TerminalFocusManager.ts +103 -11
- package/src/terminal/TtyWriter.ts +161 -1
- package/src/utils/agent-requests.ts +28 -0
- package/src/utils/agents.ts +2 -1
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
|
|
2
|
+
import { tmpdir } from 'os';
|
|
3
|
+
import { join } from 'path';
|
|
4
|
+
import { getAgentRequestPath, readLatestAgentRequest, writeAgentRequest } from '../../utils/agent-requests.js';
|
|
5
|
+
describe('agent-requests', ()=>{
|
|
6
|
+
let homeDir;
|
|
7
|
+
beforeEach(()=>{
|
|
8
|
+
homeDir = mkdtempSync(join(tmpdir(), 'agent-requests-test-'));
|
|
9
|
+
});
|
|
10
|
+
afterEach(()=>{
|
|
11
|
+
rmSync(homeDir, {
|
|
12
|
+
recursive: true,
|
|
13
|
+
force: true
|
|
14
|
+
});
|
|
15
|
+
});
|
|
16
|
+
describe('getAgentRequestPath', ()=>{
|
|
17
|
+
it('returns ~/.ai-devkit/agent-requests/<sessionId>.json', ()=>{
|
|
18
|
+
expect(getAgentRequestPath(homeDir, 'abc-123')).toBe(join(homeDir, '.ai-devkit', 'agent-requests', 'abc-123.json'));
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
describe('writeAgentRequest', ()=>{
|
|
22
|
+
it('creates the directory and file on first write', ()=>{
|
|
23
|
+
const entry = {
|
|
24
|
+
sessionId: 'sess-1',
|
|
25
|
+
toolName: 'Bash',
|
|
26
|
+
toolInput: {
|
|
27
|
+
command: 'ls /tmp'
|
|
28
|
+
},
|
|
29
|
+
timestamp: '2026-06-29T00:00:00.000Z'
|
|
30
|
+
};
|
|
31
|
+
writeAgentRequest(homeDir, entry);
|
|
32
|
+
expect(readLatestAgentRequest(homeDir, 'sess-1')).toEqual(entry);
|
|
33
|
+
});
|
|
34
|
+
it('overwrites an existing entry on subsequent writes', ()=>{
|
|
35
|
+
const first = {
|
|
36
|
+
sessionId: 'sess-2',
|
|
37
|
+
toolName: 'Bash',
|
|
38
|
+
toolInput: {
|
|
39
|
+
command: 'echo first'
|
|
40
|
+
},
|
|
41
|
+
timestamp: '2026-06-29T00:00:01.000Z'
|
|
42
|
+
};
|
|
43
|
+
const second = {
|
|
44
|
+
sessionId: 'sess-2',
|
|
45
|
+
toolName: 'Bash',
|
|
46
|
+
toolInput: {
|
|
47
|
+
command: 'echo second'
|
|
48
|
+
},
|
|
49
|
+
timestamp: '2026-06-29T00:00:02.000Z'
|
|
50
|
+
};
|
|
51
|
+
writeAgentRequest(homeDir, first);
|
|
52
|
+
writeAgentRequest(homeDir, second);
|
|
53
|
+
expect(readLatestAgentRequest(homeDir, 'sess-2')).toEqual(second);
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
describe('readLatestAgentRequest', ()=>{
|
|
57
|
+
it('returns null when no file exists for the session', ()=>{
|
|
58
|
+
expect(readLatestAgentRequest(homeDir, 'no-such-session')).toBeNull();
|
|
59
|
+
});
|
|
60
|
+
it('returns null when the file contains malformed JSON', ()=>{
|
|
61
|
+
const entry = {
|
|
62
|
+
sessionId: 'bad',
|
|
63
|
+
toolName: 'Bash',
|
|
64
|
+
toolInput: {},
|
|
65
|
+
timestamp: '2026-06-29T00:00:00.000Z'
|
|
66
|
+
};
|
|
67
|
+
writeAgentRequest(homeDir, entry);
|
|
68
|
+
writeFileSync(getAgentRequestPath(homeDir, 'bad'), 'NOT JSON{{{', 'utf-8');
|
|
69
|
+
expect(readLatestAgentRequest(homeDir, 'bad')).toBeNull();
|
|
70
|
+
});
|
|
71
|
+
it('returns the stored entry when the file is valid', ()=>{
|
|
72
|
+
const entry = {
|
|
73
|
+
sessionId: 'good',
|
|
74
|
+
toolName: 'AskUserQuestion',
|
|
75
|
+
toolInput: {
|
|
76
|
+
question: 'Which option?',
|
|
77
|
+
options: [
|
|
78
|
+
'A',
|
|
79
|
+
'B'
|
|
80
|
+
]
|
|
81
|
+
},
|
|
82
|
+
timestamp: '2026-06-29T12:00:00.000Z'
|
|
83
|
+
};
|
|
84
|
+
writeAgentRequest(homeDir, entry);
|
|
85
|
+
expect(readLatestAgentRequest(homeDir, 'good')).toEqual(entry);
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
//# sourceMappingURL=agent-requests.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/__tests__/utils/agent-requests.test.ts"],"sourcesContent":["import { mkdtempSync, rmSync, writeFileSync } from 'fs';\nimport { tmpdir } from 'os';\nimport { join } from 'path';\nimport { getAgentRequestPath, readLatestAgentRequest, writeAgentRequest, type AgentRequest } from '../../utils/agent-requests.js';\n\ndescribe('agent-requests', () => {\n let homeDir: string;\n\n beforeEach(() => {\n homeDir = mkdtempSync(join(tmpdir(), 'agent-requests-test-'));\n });\n\n afterEach(() => {\n rmSync(homeDir, { recursive: true, force: true });\n });\n\n describe('getAgentRequestPath', () => {\n it('returns ~/.ai-devkit/agent-requests/<sessionId>.json', () => {\n expect(getAgentRequestPath(homeDir, 'abc-123')).toBe(\n join(homeDir, '.ai-devkit', 'agent-requests', 'abc-123.json'),\n );\n });\n });\n\n describe('writeAgentRequest', () => {\n it('creates the directory and file on first write', () => {\n const entry: AgentRequest = {\n sessionId: 'sess-1',\n toolName: 'Bash',\n toolInput: { command: 'ls /tmp' },\n timestamp: '2026-06-29T00:00:00.000Z',\n };\n writeAgentRequest(homeDir, entry);\n\n expect(readLatestAgentRequest(homeDir, 'sess-1')).toEqual(entry);\n });\n\n it('overwrites an existing entry on subsequent writes', () => {\n const first: AgentRequest = { sessionId: 'sess-2', toolName: 'Bash', toolInput: { command: 'echo first' }, timestamp: '2026-06-29T00:00:01.000Z' };\n const second: AgentRequest = { sessionId: 'sess-2', toolName: 'Bash', toolInput: { command: 'echo second' }, timestamp: '2026-06-29T00:00:02.000Z' };\n\n writeAgentRequest(homeDir, first);\n writeAgentRequest(homeDir, second);\n\n expect(readLatestAgentRequest(homeDir, 'sess-2')).toEqual(second);\n });\n });\n\n describe('readLatestAgentRequest', () => {\n it('returns null when no file exists for the session', () => {\n expect(readLatestAgentRequest(homeDir, 'no-such-session')).toBeNull();\n });\n\n it('returns null when the file contains malformed JSON', () => {\n const entry: AgentRequest = { sessionId: 'bad', toolName: 'Bash', toolInput: {}, timestamp: '2026-06-29T00:00:00.000Z' };\n writeAgentRequest(homeDir, entry);\n writeFileSync(getAgentRequestPath(homeDir, 'bad'), 'NOT JSON{{{', 'utf-8');\n\n expect(readLatestAgentRequest(homeDir, 'bad')).toBeNull();\n });\n\n it('returns the stored entry when the file is valid', () => {\n const entry: AgentRequest = {\n sessionId: 'good',\n toolName: 'AskUserQuestion',\n toolInput: { question: 'Which option?', options: ['A', 'B'] },\n timestamp: '2026-06-29T12:00:00.000Z',\n };\n writeAgentRequest(homeDir, entry);\n\n expect(readLatestAgentRequest(homeDir, 'good')).toEqual(entry);\n });\n });\n});\n"],"names":["mkdtempSync","rmSync","writeFileSync","tmpdir","join","getAgentRequestPath","readLatestAgentRequest","writeAgentRequest","describe","homeDir","beforeEach","afterEach","recursive","force","it","expect","toBe","entry","sessionId","toolName","toolInput","command","timestamp","toEqual","first","second","toBeNull","question","options"],"mappings":"AAAA,SAASA,WAAW,EAAEC,MAAM,EAAEC,aAAa,QAAQ,KAAK;AACxD,SAASC,MAAM,QAAQ,KAAK;AAC5B,SAASC,IAAI,QAAQ,OAAO;AAC5B,SAASC,mBAAmB,EAAEC,sBAAsB,EAAEC,iBAAiB,QAA2B,gCAAgC;AAElIC,SAAS,kBAAkB;IACvB,IAAIC;IAEJC,WAAW;QACPD,UAAUT,YAAYI,KAAKD,UAAU;IACzC;IAEAQ,UAAU;QACNV,OAAOQ,SAAS;YAAEG,WAAW;YAAMC,OAAO;QAAK;IACnD;IAEAL,SAAS,uBAAuB;QAC5BM,GAAG,wDAAwD;YACvDC,OAAOV,oBAAoBI,SAAS,YAAYO,IAAI,CAChDZ,KAAKK,SAAS,cAAc,kBAAkB;QAEtD;IACJ;IAEAD,SAAS,qBAAqB;QAC1BM,GAAG,iDAAiD;YAChD,MAAMG,QAAsB;gBACxBC,WAAW;gBACXC,UAAU;gBACVC,WAAW;oBAAEC,SAAS;gBAAU;gBAChCC,WAAW;YACf;YACAf,kBAAkBE,SAASQ;YAE3BF,OAAOT,uBAAuBG,SAAS,WAAWc,OAAO,CAACN;QAC9D;QAEAH,GAAG,qDAAqD;YACpD,MAAMU,QAAsB;gBAAEN,WAAW;gBAAUC,UAAU;gBAAQC,WAAW;oBAAEC,SAAS;gBAAa;gBAAGC,WAAW;YAA2B;YACjJ,MAAMG,SAAuB;gBAAEP,WAAW;gBAAUC,UAAU;gBAAQC,WAAW;oBAAEC,SAAS;gBAAc;gBAAGC,WAAW;YAA2B;YAEnJf,kBAAkBE,SAASe;YAC3BjB,kBAAkBE,SAASgB;YAE3BV,OAAOT,uBAAuBG,SAAS,WAAWc,OAAO,CAACE;QAC9D;IACJ;IAEAjB,SAAS,0BAA0B;QAC/BM,GAAG,oDAAoD;YACnDC,OAAOT,uBAAuBG,SAAS,oBAAoBiB,QAAQ;QACvE;QAEAZ,GAAG,sDAAsD;YACrD,MAAMG,QAAsB;gBAAEC,WAAW;gBAAOC,UAAU;gBAAQC,WAAW,CAAC;gBAAGE,WAAW;YAA2B;YACvHf,kBAAkBE,SAASQ;YAC3Bf,cAAcG,oBAAoBI,SAAS,QAAQ,eAAe;YAElEM,OAAOT,uBAAuBG,SAAS,QAAQiB,QAAQ;QAC3D;QAEAZ,GAAG,mDAAmD;YAClD,MAAMG,QAAsB;gBACxBC,WAAW;gBACXC,UAAU;gBACVC,WAAW;oBAAEO,UAAU;oBAAiBC,SAAS;wBAAC;wBAAK;qBAAI;gBAAC;gBAC5DN,WAAW;YACf;YACAf,kBAAkBE,SAASQ;YAE3BF,OAAOT,uBAAuBG,SAAS,SAASc,OAAO,CAACN;QAC5D;IACJ;AACJ"}
|
|
@@ -12,6 +12,12 @@ describe('AGENTS', ()=>{
|
|
|
12
12
|
expect(AGENTS.pi.matches('/usr/local/bin/pi --model x')).toBe(true);
|
|
13
13
|
expect(AGENTS.pi.matches('node /repo/feature-pi-adapter/script.js')).toBe(false);
|
|
14
14
|
});
|
|
15
|
+
it('includes Grok as a startable agent', ()=>{
|
|
16
|
+
expect(AGENTS.grok_cli.command).toBe('grok');
|
|
17
|
+
expect(AGENTS.grok_cli.matches('grok')).toBe(true);
|
|
18
|
+
expect(AGENTS.grok_cli.matches('/Users/dev/.grok/bin/grok --always-approve')).toBe(true);
|
|
19
|
+
expect(AGENTS.grok_cli.matches('node /repo/feature-grok-cli/script.js')).toBe(false);
|
|
20
|
+
});
|
|
15
21
|
});
|
|
16
22
|
|
|
17
23
|
//# sourceMappingURL=agents.test.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/__tests__/utils/agents.test.ts"],"sourcesContent":["import { describe, expect, it } from 'vitest';\nimport { AGENTS } from '../../../src/utils/agents.js';\n\ndescribe('AGENTS', () => {\n it('includes Copilot as a startable agent', () => {\n expect(AGENTS.copilot.command).toBe('copilot');\n expect(AGENTS.copilot.matches('/opt/homebrew/Caskroom/copilot-cli/1.0.60/copilot')).toBe(true);\n expect(AGENTS.copilot.matches('node /repo/feature-cli-copilot-cli/script.js')).toBe(false);\n });\n\n it('includes Pi as a startable agent', () => {\n expect(AGENTS.pi.command).toBe('pi');\n expect(AGENTS.pi.matches('pi')).toBe(true);\n expect(AGENTS.pi.matches('/usr/local/bin/pi --model x')).toBe(true);\n expect(AGENTS.pi.matches('node /repo/feature-pi-adapter/script.js')).toBe(false);\n });\n});\n"],"names":["describe","expect","it","AGENTS","copilot","command","toBe","matches","pi"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAC9C,SAASC,MAAM,QAAQ,+BAA+B;AAEtDH,SAAS,UAAU;IACfE,GAAG,yCAAyC;QACxCD,OAAOE,OAAOC,OAAO,CAACC,OAAO,EAAEC,IAAI,CAAC;QACpCL,OAAOE,OAAOC,OAAO,CAACG,OAAO,CAAC,sDAAsDD,IAAI,CAAC;QACzFL,OAAOE,OAAOC,OAAO,CAACG,OAAO,CAAC,iDAAiDD,IAAI,CAAC;IACxF;IAEAJ,GAAG,oCAAoC;QACnCD,OAAOE,OAAOK,EAAE,CAACH,OAAO,EAAEC,IAAI,CAAC;QAC/BL,OAAOE,OAAOK,EAAE,CAACD,OAAO,CAAC,OAAOD,IAAI,CAAC;QACrCL,OAAOE,OAAOK,EAAE,CAACD,OAAO,CAAC,gCAAgCD,IAAI,CAAC;QAC9DL,OAAOE,OAAOK,EAAE,CAACD,OAAO,CAAC,4CAA4CD,IAAI,CAAC;IAC9E;AACJ"}
|
|
1
|
+
{"version":3,"sources":["../../../src/__tests__/utils/agents.test.ts"],"sourcesContent":["import { describe, expect, it } from 'vitest';\nimport { AGENTS } from '../../../src/utils/agents.js';\n\ndescribe('AGENTS', () => {\n it('includes Copilot as a startable agent', () => {\n expect(AGENTS.copilot.command).toBe('copilot');\n expect(AGENTS.copilot.matches('/opt/homebrew/Caskroom/copilot-cli/1.0.60/copilot')).toBe(true);\n expect(AGENTS.copilot.matches('node /repo/feature-cli-copilot-cli/script.js')).toBe(false);\n });\n\n it('includes Pi as a startable agent', () => {\n expect(AGENTS.pi.command).toBe('pi');\n expect(AGENTS.pi.matches('pi')).toBe(true);\n expect(AGENTS.pi.matches('/usr/local/bin/pi --model x')).toBe(true);\n expect(AGENTS.pi.matches('node /repo/feature-pi-adapter/script.js')).toBe(false);\n });\n\n it('includes Grok as a startable agent', () => {\n expect(AGENTS.grok_cli.command).toBe('grok');\n expect(AGENTS.grok_cli.matches('grok')).toBe(true);\n expect(AGENTS.grok_cli.matches('/Users/dev/.grok/bin/grok --always-approve')).toBe(true);\n expect(AGENTS.grok_cli.matches('node /repo/feature-grok-cli/script.js')).toBe(false);\n });\n});\n"],"names":["describe","expect","it","AGENTS","copilot","command","toBe","matches","pi","grok_cli"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAC9C,SAASC,MAAM,QAAQ,+BAA+B;AAEtDH,SAAS,UAAU;IACfE,GAAG,yCAAyC;QACxCD,OAAOE,OAAOC,OAAO,CAACC,OAAO,EAAEC,IAAI,CAAC;QACpCL,OAAOE,OAAOC,OAAO,CAACG,OAAO,CAAC,sDAAsDD,IAAI,CAAC;QACzFL,OAAOE,OAAOC,OAAO,CAACG,OAAO,CAAC,iDAAiDD,IAAI,CAAC;IACxF;IAEAJ,GAAG,oCAAoC;QACnCD,OAAOE,OAAOK,EAAE,CAACH,OAAO,EAAEC,IAAI,CAAC;QAC/BL,OAAOE,OAAOK,EAAE,CAACD,OAAO,CAAC,OAAOD,IAAI,CAAC;QACrCL,OAAOE,OAAOK,EAAE,CAACD,OAAO,CAAC,gCAAgCD,IAAI,CAAC;QAC9DL,OAAOE,OAAOK,EAAE,CAACD,OAAO,CAAC,4CAA4CD,IAAI,CAAC;IAC9E;IAEAJ,GAAG,sCAAsC;QACrCD,OAAOE,OAAOM,QAAQ,CAACJ,OAAO,EAAEC,IAAI,CAAC;QACrCL,OAAOE,OAAOM,QAAQ,CAACF,OAAO,CAAC,SAASD,IAAI,CAAC;QAC7CL,OAAOE,OAAOM,QAAQ,CAACF,OAAO,CAAC,+CAA+CD,IAAI,CAAC;QACnFL,OAAOE,OAAOM,QAAQ,CAACF,OAAO,CAAC,0CAA0CD,IAAI,CAAC;IAClF;AACJ"}
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
/**
|
|
8
8
|
* Type of AI agent
|
|
9
9
|
*/
|
|
10
|
-
export type AgentType = 'claude' | 'gemini_cli' | 'codex' | 'opencode' | 'copilot' | 'pi' | 'other';
|
|
10
|
+
export type AgentType = 'claude' | 'gemini_cli' | 'grok_cli' | 'codex' | 'opencode' | 'copilot' | 'pi' | 'other';
|
|
11
11
|
/**
|
|
12
12
|
* Current status of an agent
|
|
13
13
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentAdapter.d.ts","sourceRoot":"","sources":["../../src/adapters/AgentAdapter.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,QAAQ,GAAG,YAAY,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,IAAI,GAAG,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"AgentAdapter.d.ts","sourceRoot":"","sources":["../../src/adapters/AgentAdapter.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,QAAQ,GAAG,YAAY,GAAG,UAAU,GAAG,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,IAAI,GAAG,OAAO,CAAC;AAEjH;;GAEG;AACH,oBAAY,WAAW;IACnB,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,IAAI,SAAS;IACb,OAAO,YAAY;CACtB;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F;IACpF,SAAS,EAAE,IAAI,CAAC;IAEhB,oEAAoE;IACpE,eAAe,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;;GAMG;AACH,MAAM,WAAW,mBAAmB;IAChC;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IAEb;;;;;;OAMG;IACH,IAAI,CAAC,EAAE,SAAS,CAAC;CACpB;AAED;;;;GAIG;AACH,MAAM,WAAW,YAAY;IACzB,yCAAyC;IACzC,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IAEzB;;;OAGG;IACH,YAAY,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAErC;;;;OAIG;IACH,SAAS,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO,CAAC;IAE7C;;;;;OAKG;IACH,eAAe,CAAC,eAAe,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,mBAAmB,EAAE,CAAC;IAEjG;;;;;;;;;OASG;IACH,YAAY,CAAC,IAAI,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CAAC;CACvE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/AgentAdapter.ts"],"sourcesContent":["/**\n * Agent Adapter Interface\n * \n * Defines the contract for detecting and managing different types of AI agents.\n * Each adapter is responsible for detecting agents of a specific type (e.g., claude).\n */\n\n/**\n * Type of AI agent\n */\nexport type AgentType = 'claude' | 'gemini_cli' | 'codex' | 'opencode' | 'copilot' | 'pi' | 'other';\n\n/**\n * Current status of an agent\n */\nexport enum AgentStatus {\n RUNNING = 'running',\n WAITING = 'waiting',\n IDLE = 'idle',\n UNKNOWN = 'unknown'\n}\n\n/**\n * Information about a detected agent\n */\nexport interface AgentInfo {\n /** Project-based name (e.g., \"ai-devkit\" or \"ai-devkit (merry)\") */\n name: string;\n\n /** Type of agent */\n type: AgentType;\n\n /** Current status */\n status: AgentStatus;\n\n /** Last user prompt from history */\n summary: string;\n\n /** Process ID */\n pid: number;\n\n /** Working directory/project path */\n projectPath: string;\n\n /** Session UUID */\n sessionId: string;\n\n /** Timestamp of last activity */\n lastActive: Date;\n\n /** Path to the session JSONL file on disk */\n sessionFilePath?: string;\n}\n\n/**\n * Information about a running process\n */\nexport interface ProcessInfo {\n /** Process ID */\n pid: number;\n\n /** Parent process ID, populated by listAgentProcesses when available */\n ppid?: number;\n\n /** Process command */\n command: string;\n\n /** Working directory */\n cwd: string;\n\n /** Terminal TTY (e.g., \"ttys030\") */\n tty: string;\n\n /** Process start time, populated by enrichProcesses */\n startTime?: Date;\n}\n\n/**\n * A single message in a conversation\n */\nexport interface ConversationMessage {\n role: 'user' | 'assistant' | 'system';\n content: string;\n timestamp?: string;\n}\n\n/**\n * A historical session discovered on disk (running or not).\n *\n * Used by `listSessions` to surface enough context for a user to identify\n * a session and resume it via the originating tool's resume command.\n */\nexport interface SessionSummary {\n /** Tool that produced this session */\n type: AgentType;\n\n /**\n * ID accepted by the tool's resume command. Adapters MUST pass this\n * through verbatim — no normalization, no encoding/decoding — so it\n * round-trips into `claude --resume <id>` (and equivalents).\n */\n sessionId: string;\n\n /** Working directory the session was started in (best-known value) */\n cwd: string;\n\n /**\n * Trimmed first user message; empty string if none. Adapters apply\n * the same noise-filter their existing parsers use (skip tool_result\n * blocks, request-interruption notices, system-injected skill\n * content). The CLI table renderer substitutes a placeholder for\n * empty values; JSON output keeps the empty string raw.\n */\n firstUserMessage: string;\n\n /** Last activity timestamp (from session content; falls back to file mtime) */\n lastActive: Date;\n\n /** Session start time (from session content; falls back to file birthtime/mtime) */\n startedAt: Date;\n\n /** Absolute path to the session file on disk (debug/diagnostics) */\n sessionFilePath: string;\n}\n\n/**\n * Filters passed by the CLI to {@link AgentAdapter.listSessions}.\n *\n * The CLI is the source of truth for filter defaults and semantics\n * (e.g. cwd defaults to process.cwd(); --all clears it). Adapters apply\n * the values they receive — they don't invent defaults.\n */\nexport interface ListSessionsOptions {\n /**\n * Filter to sessions whose recorded cwd matches this path using strict\n * equality (no prefix/ancestor matching in v1). Undefined = no cwd\n * filter.\n */\n cwd?: string;\n\n /**\n * Filter to a single tool. Enforced by `AgentManager.listSessions`,\n * which skips adapters whose `type` doesn't match. Adapters MAY\n * ignore this field — by the time their `listSessions` runs, the\n * type filter is already satisfied. Undefined = include every\n * registered adapter.\n */\n type?: AgentType;\n}\n\n/**\n * Agent Adapter Interface\n *\n * Implementations must provide detection logic for a specific agent type.\n */\nexport interface AgentAdapter {\n /** Type of agent this adapter handles */\n readonly type: AgentType;\n\n /**\n * Detect running agents of this type\n * @returns List of detected agents\n */\n detectAgents(): Promise<AgentInfo[]>;\n\n /**\n * Check if this adapter can handle the given process\n * @param processInfo Process information\n * @returns True if this adapter can handle the process\n */\n canHandle(processInfo: ProcessInfo): boolean;\n\n /**\n * Read the full conversation from a session file\n * @param sessionFilePath Path to the session JSONL file\n * @param options.verbose Include tool call/result details\n * @returns Array of conversation messages\n */\n getConversation(sessionFilePath: string, options?: { verbose?: boolean }): ConversationMessage[];\n\n /**\n * Enumerate historical sessions for this tool from disk.\n *\n * Applies `opts.cwd` as a strict-equality filter when set. Returns\n * {@link SessionSummary} entries unsorted; sorting and global filters\n * are handled by `AgentManager` and the CLI.\n *\n * @param opts Filter options computed by the CLI\n * @returns Array of sessions discovered on disk\n */\n listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]>;\n}\n"],"names":["AgentStatus"],"mappings":"AAAA;;;;;CAKC,GAED;;CAEC,GAGD;;CAEC,GACD,OAAO,IAAA,AAAKA,qCAAAA;;;;;WAAAA;MAKX"}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/AgentAdapter.ts"],"sourcesContent":["/**\n * Agent Adapter Interface\n * \n * Defines the contract for detecting and managing different types of AI agents.\n * Each adapter is responsible for detecting agents of a specific type (e.g., claude).\n */\n\n/**\n * Type of AI agent\n */\nexport type AgentType = 'claude' | 'gemini_cli' | 'grok_cli' | 'codex' | 'opencode' | 'copilot' | 'pi' | 'other';\n\n/**\n * Current status of an agent\n */\nexport enum AgentStatus {\n RUNNING = 'running',\n WAITING = 'waiting',\n IDLE = 'idle',\n UNKNOWN = 'unknown'\n}\n\n/**\n * Information about a detected agent\n */\nexport interface AgentInfo {\n /** Project-based name (e.g., \"ai-devkit\" or \"ai-devkit (merry)\") */\n name: string;\n\n /** Type of agent */\n type: AgentType;\n\n /** Current status */\n status: AgentStatus;\n\n /** Last user prompt from history */\n summary: string;\n\n /** Process ID */\n pid: number;\n\n /** Working directory/project path */\n projectPath: string;\n\n /** Session UUID */\n sessionId: string;\n\n /** Timestamp of last activity */\n lastActive: Date;\n\n /** Path to the session JSONL file on disk */\n sessionFilePath?: string;\n}\n\n/**\n * Information about a running process\n */\nexport interface ProcessInfo {\n /** Process ID */\n pid: number;\n\n /** Parent process ID, populated by listAgentProcesses when available */\n ppid?: number;\n\n /** Process command */\n command: string;\n\n /** Working directory */\n cwd: string;\n\n /** Terminal TTY (e.g., \"ttys030\") */\n tty: string;\n\n /** Process start time, populated by enrichProcesses */\n startTime?: Date;\n}\n\n/**\n * A single message in a conversation\n */\nexport interface ConversationMessage {\n role: 'user' | 'assistant' | 'system';\n content: string;\n timestamp?: string;\n}\n\n/**\n * A historical session discovered on disk (running or not).\n *\n * Used by `listSessions` to surface enough context for a user to identify\n * a session and resume it via the originating tool's resume command.\n */\nexport interface SessionSummary {\n /** Tool that produced this session */\n type: AgentType;\n\n /**\n * ID accepted by the tool's resume command. Adapters MUST pass this\n * through verbatim — no normalization, no encoding/decoding — so it\n * round-trips into `claude --resume <id>` (and equivalents).\n */\n sessionId: string;\n\n /** Working directory the session was started in (best-known value) */\n cwd: string;\n\n /**\n * Trimmed first user message; empty string if none. Adapters apply\n * the same noise-filter their existing parsers use (skip tool_result\n * blocks, request-interruption notices, system-injected skill\n * content). The CLI table renderer substitutes a placeholder for\n * empty values; JSON output keeps the empty string raw.\n */\n firstUserMessage: string;\n\n /** Last activity timestamp (from session content; falls back to file mtime) */\n lastActive: Date;\n\n /** Session start time (from session content; falls back to file birthtime/mtime) */\n startedAt: Date;\n\n /** Absolute path to the session file on disk (debug/diagnostics) */\n sessionFilePath: string;\n}\n\n/**\n * Filters passed by the CLI to {@link AgentAdapter.listSessions}.\n *\n * The CLI is the source of truth for filter defaults and semantics\n * (e.g. cwd defaults to process.cwd(); --all clears it). Adapters apply\n * the values they receive — they don't invent defaults.\n */\nexport interface ListSessionsOptions {\n /**\n * Filter to sessions whose recorded cwd matches this path using strict\n * equality (no prefix/ancestor matching in v1). Undefined = no cwd\n * filter.\n */\n cwd?: string;\n\n /**\n * Filter to a single tool. Enforced by `AgentManager.listSessions`,\n * which skips adapters whose `type` doesn't match. Adapters MAY\n * ignore this field — by the time their `listSessions` runs, the\n * type filter is already satisfied. Undefined = include every\n * registered adapter.\n */\n type?: AgentType;\n}\n\n/**\n * Agent Adapter Interface\n *\n * Implementations must provide detection logic for a specific agent type.\n */\nexport interface AgentAdapter {\n /** Type of agent this adapter handles */\n readonly type: AgentType;\n\n /**\n * Detect running agents of this type\n * @returns List of detected agents\n */\n detectAgents(): Promise<AgentInfo[]>;\n\n /**\n * Check if this adapter can handle the given process\n * @param processInfo Process information\n * @returns True if this adapter can handle the process\n */\n canHandle(processInfo: ProcessInfo): boolean;\n\n /**\n * Read the full conversation from a session file\n * @param sessionFilePath Path to the session JSONL file\n * @param options.verbose Include tool call/result details\n * @returns Array of conversation messages\n */\n getConversation(sessionFilePath: string, options?: { verbose?: boolean }): ConversationMessage[];\n\n /**\n * Enumerate historical sessions for this tool from disk.\n *\n * Applies `opts.cwd` as a strict-equality filter when set. Returns\n * {@link SessionSummary} entries unsorted; sorting and global filters\n * are handled by `AgentManager` and the CLI.\n *\n * @param opts Filter options computed by the CLI\n * @returns Array of sessions discovered on disk\n */\n listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]>;\n}\n"],"names":["AgentStatus"],"mappings":"AAAA;;;;;CAKC,GAED;;CAEC,GAGD;;CAEC,GACD,OAAO,IAAA,AAAKA,qCAAAA;;;;;WAAAA;MAKX"}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { AgentAdapter, AgentInfo, ProcessInfo, ConversationMessage, SessionSummary, ListSessionsOptions } from './AgentAdapter.js';
|
|
2
|
+
export declare class GrokCliAdapter implements AgentAdapter {
|
|
3
|
+
readonly type: "grok_cli";
|
|
4
|
+
private base;
|
|
5
|
+
private sessionsDir;
|
|
6
|
+
constructor();
|
|
7
|
+
canHandle(processInfo: ProcessInfo): boolean;
|
|
8
|
+
private isGrokExecutable;
|
|
9
|
+
detectAgents(): Promise<AgentInfo[]>;
|
|
10
|
+
/**
|
|
11
|
+
* Read ~/.grok/active_sessions.json into a pid -> cwd map. Grok writes one
|
|
12
|
+
* { pid, cwd, opened_at } entry per running session and removes it on exit,
|
|
13
|
+
* so this is the reliable way to learn a live process's working directory.
|
|
14
|
+
*/
|
|
15
|
+
private readActiveSessions;
|
|
16
|
+
/**
|
|
17
|
+
* Full paths of the session subdirectories directly under a group dir,
|
|
18
|
+
* skipping any non-directory entries. Shared by latestSessionDir() and
|
|
19
|
+
* listSessions() so both enumerate session dirs the same way.
|
|
20
|
+
*/
|
|
21
|
+
private listSessionDirs;
|
|
22
|
+
/**
|
|
23
|
+
* Return the most recently active session subdirectory for a cwd, i.e. the
|
|
24
|
+
* ~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/ whose chat_history.jsonl
|
|
25
|
+
* was written last. Returns null when the group dir or any transcript is
|
|
26
|
+
* missing.
|
|
27
|
+
*/
|
|
28
|
+
private latestSessionDir;
|
|
29
|
+
private mapSessionToAgent;
|
|
30
|
+
private mapProcessOnlyAgent;
|
|
31
|
+
getConversation(sessionFilePath: string, options?: {
|
|
32
|
+
verbose?: boolean;
|
|
33
|
+
}): ConversationMessage[];
|
|
34
|
+
listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]>;
|
|
35
|
+
/**
|
|
36
|
+
* Parse a session directory into a {@link GrokSession} from its
|
|
37
|
+
* chat_history.jsonl transcript. Returns null when the transcript is
|
|
38
|
+
* missing — i.e. there is no real session to surface.
|
|
39
|
+
*/
|
|
40
|
+
private readSession;
|
|
41
|
+
/**
|
|
42
|
+
* Determine agent status from parsed session state.
|
|
43
|
+
*
|
|
44
|
+
* - past the idle threshold → IDLE
|
|
45
|
+
* - last transcript turn is an assistant message → WAITING (awaiting user)
|
|
46
|
+
* - otherwise (last turn was a user message, or unknown) → RUNNING
|
|
47
|
+
*/
|
|
48
|
+
private determineStatus;
|
|
49
|
+
/**
|
|
50
|
+
* Single pass over chat_history.jsonl. Each line is a
|
|
51
|
+
* { type: 'system' | 'user' | 'assistant', content } record where content is
|
|
52
|
+
* either a string or an array of { type: 'text', text } blocks.
|
|
53
|
+
*
|
|
54
|
+
* Grok wraps the real user prompt in <user_query>...</user_query>; the other
|
|
55
|
+
* user records are context injections (<user_info>, <system-reminder>, ...)
|
|
56
|
+
* and are skipped so the summary is the actual prompt, not boilerplate.
|
|
57
|
+
*/
|
|
58
|
+
private parseChatHistory;
|
|
59
|
+
/** Flatten a chat record's content (string or text-block array) to text. */
|
|
60
|
+
private extractText;
|
|
61
|
+
/**
|
|
62
|
+
* Extract the prompt inside <user_query>...</user_query>. Returns null when
|
|
63
|
+
* the record has no such tag (a context injection rather than a prompt).
|
|
64
|
+
*/
|
|
65
|
+
private extractUserQuery;
|
|
66
|
+
/** Resolve a session dir or an explicit chat_history.jsonl path to the file. */
|
|
67
|
+
private resolveChatPath;
|
|
68
|
+
private getProjectDir;
|
|
69
|
+
/**
|
|
70
|
+
* Resolve the working directory a session group dir was created for.
|
|
71
|
+
*
|
|
72
|
+
* The common case is `decodeURIComponent(<group-name>)`. For paths whose
|
|
73
|
+
* encoded form exceeds the filesystem limit Grok uses a slug+hash and records
|
|
74
|
+
* the original path in a `.cwd` file inside the group — prefer that when
|
|
75
|
+
* present.
|
|
76
|
+
*/
|
|
77
|
+
private decode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,aAAa;IAIrB;;;;;;;OAOG;IACH,OAAO,CAAC,cAAc;CASzB"}
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import * as path from 'path';
|
|
2
|
+
import { AgentStatus } from './AgentAdapter.js';
|
|
3
|
+
import { listAgentProcesses, enrichProcesses } 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. Finding running `grok` processes via shared listAgentProcesses() — 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
|
+
base;
|
|
29
|
+
sessionsDir;
|
|
30
|
+
constructor(){
|
|
31
|
+
// GROK_HOME overrides the ~/.grok base directory; sessions live under
|
|
32
|
+
// <base>/sessions/ and the active-session registry at
|
|
33
|
+
// <base>/active_sessions.json.
|
|
34
|
+
const homeDir = process.env.HOME || process.env.USERPROFILE || '';
|
|
35
|
+
this.base = process.env.GROK_HOME || path.join(homeDir, '.grok');
|
|
36
|
+
this.sessionsDir = path.join(this.base, 'sessions');
|
|
37
|
+
}
|
|
38
|
+
canHandle(processInfo) {
|
|
39
|
+
return this.isGrokExecutable(processInfo.command);
|
|
40
|
+
}
|
|
41
|
+
isGrokExecutable(command) {
|
|
42
|
+
const executable = command.trim().split(/\s+/)[0] || '';
|
|
43
|
+
const base = path.basename(executable).toLowerCase();
|
|
44
|
+
return base === 'grok' || base === 'grok.exe';
|
|
45
|
+
}
|
|
46
|
+
async detectAgents() {
|
|
47
|
+
const processes = enrichProcesses(listAgentProcesses('grok'));
|
|
48
|
+
if (processes.length === 0) {
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
// active_sessions.json is the authoritative pid -> cwd map for live
|
|
52
|
+
// sessions; the lsof-derived process cwd is only a fallback.
|
|
53
|
+
const pidToCwd = this.readActiveSessions();
|
|
54
|
+
const agents = [];
|
|
55
|
+
for (const proc of processes){
|
|
56
|
+
const cwd = pidToCwd.get(proc.pid) || proc.cwd || '';
|
|
57
|
+
const sessionDir = cwd ? this.latestSessionDir(cwd) : null;
|
|
58
|
+
const session = sessionDir ? this.readSession(sessionDir, cwd) : null;
|
|
59
|
+
if (session && sessionDir) {
|
|
60
|
+
agents.push(this.mapSessionToAgent(session, proc, sessionDir));
|
|
61
|
+
} else {
|
|
62
|
+
agents.push(this.mapProcessOnlyAgent(proc, cwd));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return agents;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Read ~/.grok/active_sessions.json into a pid -> cwd map. Grok writes one
|
|
69
|
+
* { pid, cwd, opened_at } entry per running session and removes it on exit,
|
|
70
|
+
* so this is the reliable way to learn a live process's working directory.
|
|
71
|
+
*/ readActiveSessions() {
|
|
72
|
+
const map = new Map();
|
|
73
|
+
const content = safeReadFile(path.join(this.base, ACTIVE_SESSIONS_FILE));
|
|
74
|
+
if (content === undefined) return map;
|
|
75
|
+
let entries;
|
|
76
|
+
try {
|
|
77
|
+
entries = JSON.parse(content);
|
|
78
|
+
} catch {
|
|
79
|
+
return map;
|
|
80
|
+
}
|
|
81
|
+
if (!Array.isArray(entries)) return map;
|
|
82
|
+
for (const entry of entries){
|
|
83
|
+
if (typeof entry?.pid === 'number' && typeof entry?.cwd === 'string' && entry.cwd) {
|
|
84
|
+
map.set(entry.pid, entry.cwd);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return map;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Full paths of the session subdirectories directly under a group dir,
|
|
91
|
+
* skipping any non-directory entries. Shared by latestSessionDir() and
|
|
92
|
+
* listSessions() so both enumerate session dirs the same way.
|
|
93
|
+
*/ listSessionDirs(groupDir) {
|
|
94
|
+
return safeReaddir(groupDir).map((sessionId)=>path.join(groupDir, sessionId)).filter((sessionDir)=>isDirectory(sessionDir));
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Return the most recently active session subdirectory for a cwd, i.e. the
|
|
98
|
+
* ~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/ whose chat_history.jsonl
|
|
99
|
+
* was written last. Returns null when the group dir or any transcript is
|
|
100
|
+
* missing.
|
|
101
|
+
*/ latestSessionDir(cwd) {
|
|
102
|
+
const groupDir = this.getProjectDir(cwd);
|
|
103
|
+
if (!isDirectory(groupDir)) return null;
|
|
104
|
+
let best = null;
|
|
105
|
+
for (const sessionDir of this.listSessionDirs(groupDir)){
|
|
106
|
+
const stat = safeStat(path.join(sessionDir, CHAT_HISTORY_FILE));
|
|
107
|
+
if (!stat) continue;
|
|
108
|
+
if (!best || stat.mtimeMs > best.mtimeMs) {
|
|
109
|
+
best = {
|
|
110
|
+
dir: sessionDir,
|
|
111
|
+
mtimeMs: stat.mtimeMs
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return best?.dir ?? null;
|
|
116
|
+
}
|
|
117
|
+
mapSessionToAgent(session, processInfo, sessionDir) {
|
|
118
|
+
const projectPath = session.projectPath || processInfo.cwd || '';
|
|
119
|
+
return {
|
|
120
|
+
name: generateAgentName(projectPath, processInfo.pid),
|
|
121
|
+
type: this.type,
|
|
122
|
+
status: this.determineStatus(session),
|
|
123
|
+
summary: session.summary || 'Grok CLI session active',
|
|
124
|
+
pid: processInfo.pid,
|
|
125
|
+
projectPath,
|
|
126
|
+
sessionId: session.sessionId,
|
|
127
|
+
lastActive: session.lastActive,
|
|
128
|
+
sessionFilePath: path.join(sessionDir, CHAT_HISTORY_FILE)
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
mapProcessOnlyAgent(processInfo, cwd) {
|
|
132
|
+
const projectPath = cwd || processInfo.cwd || '';
|
|
133
|
+
return {
|
|
134
|
+
name: generateAgentName(projectPath, processInfo.pid),
|
|
135
|
+
type: this.type,
|
|
136
|
+
status: AgentStatus.RUNNING,
|
|
137
|
+
summary: 'Grok CLI process running',
|
|
138
|
+
pid: processInfo.pid,
|
|
139
|
+
projectPath,
|
|
140
|
+
sessionId: `pid-${processInfo.pid}`,
|
|
141
|
+
lastActive: new Date()
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
getConversation(sessionFilePath, options) {
|
|
145
|
+
return this.parseChatHistory(this.resolveChatPath(sessionFilePath), options?.verbose ?? false).messages;
|
|
146
|
+
}
|
|
147
|
+
async listSessions(opts) {
|
|
148
|
+
if (!isDirectory(this.sessionsDir)) return [];
|
|
149
|
+
const filterCwd = opts?.cwd;
|
|
150
|
+
const summaries = [];
|
|
151
|
+
for (const groupName of safeReaddir(this.sessionsDir)){
|
|
152
|
+
const groupDir = path.join(this.sessionsDir, groupName);
|
|
153
|
+
if (!isDirectory(groupDir)) continue;
|
|
154
|
+
const decodedCwd = this.decodeGroupCwd(groupName, groupDir);
|
|
155
|
+
for (const sessionDir of this.listSessionDirs(groupDir)){
|
|
156
|
+
const session = this.readSession(sessionDir, decodedCwd);
|
|
157
|
+
if (!session) continue;
|
|
158
|
+
const cwd = session.projectPath || decodedCwd;
|
|
159
|
+
if (filterCwd !== undefined && cwd !== filterCwd) continue;
|
|
160
|
+
summaries.push({
|
|
161
|
+
type: this.type,
|
|
162
|
+
sessionId: session.sessionId,
|
|
163
|
+
cwd,
|
|
164
|
+
firstUserMessage: session.firstUserMessage || '',
|
|
165
|
+
lastActive: session.lastActive,
|
|
166
|
+
startedAt: session.sessionStart,
|
|
167
|
+
sessionFilePath: path.join(sessionDir, CHAT_HISTORY_FILE)
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return summaries;
|
|
172
|
+
}
|
|
173
|
+
// --- Session parsing (chat_history.jsonl) ---
|
|
174
|
+
/**
|
|
175
|
+
* Parse a session directory into a {@link GrokSession} from its
|
|
176
|
+
* chat_history.jsonl transcript. Returns null when the transcript is
|
|
177
|
+
* missing — i.e. there is no real session to surface.
|
|
178
|
+
*/ readSession(sessionDir, defaultCwd) {
|
|
179
|
+
const chatPath = path.join(sessionDir, CHAT_HISTORY_FILE);
|
|
180
|
+
const chatStat = safeStat(chatPath);
|
|
181
|
+
if (!chatStat) return null;
|
|
182
|
+
const scan = this.parseChatHistory(chatPath, false);
|
|
183
|
+
const dirStat = safeStat(sessionDir);
|
|
184
|
+
const lastActive = chatStat.mtime;
|
|
185
|
+
return {
|
|
186
|
+
sessionId: path.basename(sessionDir),
|
|
187
|
+
projectPath: defaultCwd || '',
|
|
188
|
+
summary: scan.lastUserMessage || 'Grok CLI session active',
|
|
189
|
+
sessionStart: dirStat?.birthtime || lastActive,
|
|
190
|
+
lastActive,
|
|
191
|
+
firstUserMessage: scan.firstUserMessage,
|
|
192
|
+
lastUserMessage: scan.lastUserMessage,
|
|
193
|
+
lastRole: scan.lastRole
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Determine agent status from parsed session state.
|
|
198
|
+
*
|
|
199
|
+
* - past the idle threshold → IDLE
|
|
200
|
+
* - last transcript turn is an assistant message → WAITING (awaiting user)
|
|
201
|
+
* - otherwise (last turn was a user message, or unknown) → RUNNING
|
|
202
|
+
*/ determineStatus(session) {
|
|
203
|
+
const diffMinutes = (Date.now() - session.lastActive.getTime()) / 60000;
|
|
204
|
+
if (diffMinutes > IDLE_THRESHOLD_MINUTES) {
|
|
205
|
+
return AgentStatus.IDLE;
|
|
206
|
+
}
|
|
207
|
+
if (session.lastRole === 'assistant') {
|
|
208
|
+
return AgentStatus.WAITING;
|
|
209
|
+
}
|
|
210
|
+
return AgentStatus.RUNNING;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Single pass over chat_history.jsonl. Each line is a
|
|
214
|
+
* { type: 'system' | 'user' | 'assistant', content } record where content is
|
|
215
|
+
* either a string or an array of { type: 'text', text } blocks.
|
|
216
|
+
*
|
|
217
|
+
* Grok wraps the real user prompt in <user_query>...</user_query>; the other
|
|
218
|
+
* user records are context injections (<user_info>, <system-reminder>, ...)
|
|
219
|
+
* and are skipped so the summary is the actual prompt, not boilerplate.
|
|
220
|
+
*/ parseChatHistory(chatPath, verbose) {
|
|
221
|
+
const empty = {
|
|
222
|
+
messages: []
|
|
223
|
+
};
|
|
224
|
+
const content = safeReadFile(chatPath);
|
|
225
|
+
if (content === undefined) return empty;
|
|
226
|
+
const messages = [];
|
|
227
|
+
let lastRole;
|
|
228
|
+
for (const line of content.trim().split('\n')){
|
|
229
|
+
if (!line.trim()) continue;
|
|
230
|
+
let record;
|
|
231
|
+
try {
|
|
232
|
+
record = JSON.parse(line);
|
|
233
|
+
} catch {
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
const text = this.extractText(record.content);
|
|
237
|
+
if (record.type === 'user') {
|
|
238
|
+
const query = this.extractUserQuery(text);
|
|
239
|
+
if (query === null) continue; // context injection, not a real prompt
|
|
240
|
+
messages.push({
|
|
241
|
+
role: 'user',
|
|
242
|
+
content: query
|
|
243
|
+
});
|
|
244
|
+
lastRole = 'user';
|
|
245
|
+
} else if (record.type === 'assistant') {
|
|
246
|
+
if (!text) continue;
|
|
247
|
+
messages.push({
|
|
248
|
+
role: 'assistant',
|
|
249
|
+
content: text
|
|
250
|
+
});
|
|
251
|
+
lastRole = 'assistant';
|
|
252
|
+
} else if (verbose && record.type === 'system') {
|
|
253
|
+
if (!text) continue;
|
|
254
|
+
messages.push({
|
|
255
|
+
role: 'system',
|
|
256
|
+
content: text
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
const userTurns = messages.filter((m)=>m.role === 'user');
|
|
261
|
+
return {
|
|
262
|
+
messages,
|
|
263
|
+
firstUserMessage: userTurns[0]?.content,
|
|
264
|
+
lastUserMessage: userTurns[userTurns.length - 1]?.content,
|
|
265
|
+
lastRole
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
/** Flatten a chat record's content (string or text-block array) to text. */ extractText(content) {
|
|
269
|
+
if (typeof content === 'string') return content;
|
|
270
|
+
if (Array.isArray(content)) {
|
|
271
|
+
return content.map((block)=>block && typeof block === 'object' && typeof block.text === 'string' ? block.text : '').join('');
|
|
272
|
+
}
|
|
273
|
+
return '';
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Extract the prompt inside <user_query>...</user_query>. Returns null when
|
|
277
|
+
* the record has no such tag (a context injection rather than a prompt).
|
|
278
|
+
*/ extractUserQuery(text) {
|
|
279
|
+
const match = text.match(/<user_query>\s*([\s\S]*?)\s*<\/user_query>/);
|
|
280
|
+
return match ? match[1].trim() : null;
|
|
281
|
+
}
|
|
282
|
+
/** Resolve a session dir or an explicit chat_history.jsonl path to the file. */ resolveChatPath(sessionPath) {
|
|
283
|
+
return sessionPath.endsWith('.jsonl') ? sessionPath : path.join(sessionPath, CHAT_HISTORY_FILE);
|
|
284
|
+
}
|
|
285
|
+
getProjectDir(cwd) {
|
|
286
|
+
return path.join(this.sessionsDir, encodeURIComponent(cwd));
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Resolve the working directory a session group dir was created for.
|
|
290
|
+
*
|
|
291
|
+
* The common case is `decodeURIComponent(<group-name>)`. For paths whose
|
|
292
|
+
* encoded form exceeds the filesystem limit Grok uses a slug+hash and records
|
|
293
|
+
* the original path in a `.cwd` file inside the group — prefer that when
|
|
294
|
+
* present.
|
|
295
|
+
*/ decodeGroupCwd(groupName, groupDir) {
|
|
296
|
+
const fromFile = safeReadFile(path.join(groupDir, CWD_FILE));
|
|
297
|
+
if (fromFile !== undefined && fromFile.trim()) return fromFile.trim();
|
|
298
|
+
try {
|
|
299
|
+
return decodeURIComponent(groupName);
|
|
300
|
+
} catch {
|
|
301
|
+
return '';
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
//# sourceMappingURL=GrokCliAdapter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/GrokCliAdapter.ts"],"sourcesContent":["import * as path from 'path';\nimport type {\n AgentAdapter,\n AgentInfo,\n ProcessInfo,\n ConversationMessage,\n SessionSummary,\n ListSessionsOptions,\n} from './AgentAdapter.js';\nimport { AgentStatus } from './AgentAdapter.js';\nimport { listAgentProcesses, enrichProcesses } from '../utils/process.js';\nimport { isDirectory, safeReadFile, safeReaddir, safeStat } from '../utils/session.js';\nimport { generateAgentName } from '../utils/matching.js';\n\n/**\n * Grok Build CLI Adapter\n *\n * Detects running Grok Build CLI agents by:\n * 1. Finding running `grok` processes via shared listAgentProcesses() — Grok is\n * a native binary at ~/.grok/bin/grok, so argv[0] basename is `grok`.\n * 2. Resolving each live process to its working directory via\n * ~/.grok/active_sessions.json, which Grok maintains as a list of\n * { pid, cwd, opened_at } for every running session. The cwd is then encoded\n * into the session group dir ~/.grok/sessions/<encodeURIComponent(cwd)>/, and\n * the most recently active session subdirectory is picked from it. The\n * process cwd from lsof is only a fallback when the PID is not registered.\n * 3. Reading the session transcript from chat_history.jsonl (the authoritative\n * record of the conversation). The last user turn (the text inside\n * <user_query>...</user_query>) is the summary; the file's mtime is the last\n * activity time. summary.json / updates.jsonl are intentionally not used.\n */\n\nconst CHAT_HISTORY_FILE = 'chat_history.jsonl';\nconst ACTIVE_SESSIONS_FILE = 'active_sessions.json';\nconst CWD_FILE = '.cwd';\nconst IDLE_THRESHOLD_MINUTES = 5;\n\n/** One entry of ~/.grok/active_sessions.json. */\ninterface ActiveSessionEntry {\n pid?: number;\n cwd?: string;\n opened_at?: number | string;\n}\n\n/** One line of chat_history.jsonl. */\ninterface ChatRecord {\n type?: string;\n content?: unknown;\n}\n\ninterface ChatScan {\n messages: ConversationMessage[];\n firstUserMessage?: string;\n lastUserMessage?: string;\n lastRole?: ConversationMessage['role'];\n}\n\n/** Parsed state for a single ~/.grok/sessions/<cwd>/<id>/ directory. */\ninterface GrokSession {\n sessionId: string;\n projectPath: string;\n summary: string;\n sessionStart: Date;\n lastActive: Date;\n firstUserMessage?: string;\n lastUserMessage?: string;\n lastRole?: ConversationMessage['role'];\n}\n\nexport class GrokCliAdapter implements AgentAdapter {\n readonly type = 'grok_cli' as const;\n\n private base: string;\n private sessionsDir: string;\n\n constructor() {\n // GROK_HOME overrides the ~/.grok base directory; sessions live under\n // <base>/sessions/ and the active-session registry at\n // <base>/active_sessions.json.\n const homeDir = process.env.HOME || process.env.USERPROFILE || '';\n this.base = process.env.GROK_HOME || path.join(homeDir, '.grok');\n this.sessionsDir = path.join(this.base, 'sessions');\n }\n\n canHandle(processInfo: ProcessInfo): boolean {\n return this.isGrokExecutable(processInfo.command);\n }\n\n private isGrokExecutable(command: string): boolean {\n const executable = command.trim().split(/\\s+/)[0] || '';\n const base = path.basename(executable).toLowerCase();\n return base === 'grok' || base === 'grok.exe';\n }\n\n async detectAgents(): Promise<AgentInfo[]> {\n const processes = enrichProcesses(listAgentProcesses('grok'));\n if (processes.length === 0) {\n return [];\n }\n\n // active_sessions.json is the authoritative pid -> cwd map for live\n // sessions; the lsof-derived process cwd is only a fallback.\n const pidToCwd = this.readActiveSessions();\n\n const agents: AgentInfo[] = [];\n for (const proc of processes) {\n const cwd = pidToCwd.get(proc.pid) || proc.cwd || '';\n const sessionDir = cwd ? this.latestSessionDir(cwd) : null;\n const session = sessionDir ? this.readSession(sessionDir, cwd) : null;\n\n if (session && sessionDir) {\n agents.push(this.mapSessionToAgent(session, proc, sessionDir));\n } else {\n agents.push(this.mapProcessOnlyAgent(proc, cwd));\n }\n }\n\n return agents;\n }\n\n /**\n * Read ~/.grok/active_sessions.json into a pid -> cwd map. Grok writes one\n * { pid, cwd, opened_at } entry per running session and removes it on exit,\n * so this is the reliable way to learn a live process's working directory.\n */\n private readActiveSessions(): Map<number, string> {\n const map = new Map<number, string>();\n const content = safeReadFile(path.join(this.base, ACTIVE_SESSIONS_FILE));\n if (content === undefined) return map;\n\n let entries: unknown;\n try {\n entries = JSON.parse(content);\n } catch {\n return map;\n }\n if (!Array.isArray(entries)) return map;\n\n for (const entry of entries as ActiveSessionEntry[]) {\n if (typeof entry?.pid === 'number' && typeof entry?.cwd === 'string' && entry.cwd) {\n map.set(entry.pid, entry.cwd);\n }\n }\n return map;\n }\n\n /**\n * Full paths of the session subdirectories directly under a group dir,\n * skipping any non-directory entries. Shared by latestSessionDir() and\n * listSessions() so both enumerate session dirs the same way.\n */\n private listSessionDirs(groupDir: string): string[] {\n return safeReaddir(groupDir)\n .map((sessionId) => path.join(groupDir, sessionId))\n .filter((sessionDir) => isDirectory(sessionDir));\n }\n\n /**\n * Return the most recently active session subdirectory for a cwd, i.e. the\n * ~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/ whose chat_history.jsonl\n * was written last. Returns null when the group dir or any transcript is\n * missing.\n */\n private latestSessionDir(cwd: string): string | null {\n const groupDir = this.getProjectDir(cwd);\n if (!isDirectory(groupDir)) return null;\n\n let best: { dir: string; mtimeMs: number } | null = null;\n for (const sessionDir of this.listSessionDirs(groupDir)) {\n const stat = safeStat(path.join(sessionDir, CHAT_HISTORY_FILE));\n if (!stat) continue;\n if (!best || stat.mtimeMs > best.mtimeMs) {\n best = { dir: sessionDir, mtimeMs: stat.mtimeMs };\n }\n }\n return best?.dir ?? null;\n }\n\n private mapSessionToAgent(session: GrokSession, processInfo: ProcessInfo, sessionDir: string): AgentInfo {\n const projectPath = session.projectPath || processInfo.cwd || '';\n return {\n name: generateAgentName(projectPath, processInfo.pid),\n type: this.type,\n status: this.determineStatus(session),\n summary: session.summary || 'Grok CLI session active',\n pid: processInfo.pid,\n projectPath,\n sessionId: session.sessionId,\n lastActive: session.lastActive,\n sessionFilePath: path.join(sessionDir, CHAT_HISTORY_FILE),\n };\n }\n\n private mapProcessOnlyAgent(processInfo: ProcessInfo, cwd: string): AgentInfo {\n const projectPath = cwd || processInfo.cwd || '';\n return {\n name: generateAgentName(projectPath, processInfo.pid),\n type: this.type,\n status: AgentStatus.RUNNING,\n summary: 'Grok CLI process running',\n pid: processInfo.pid,\n projectPath,\n sessionId: `pid-${processInfo.pid}`,\n lastActive: new Date(),\n };\n }\n\n getConversation(sessionFilePath: string, options?: { verbose?: boolean }): ConversationMessage[] {\n return this.parseChatHistory(this.resolveChatPath(sessionFilePath), options?.verbose ?? false).messages;\n }\n\n async listSessions(opts?: ListSessionsOptions): Promise<SessionSummary[]> {\n if (!isDirectory(this.sessionsDir)) return [];\n\n const filterCwd = opts?.cwd;\n const summaries: SessionSummary[] = [];\n\n for (const groupName of safeReaddir(this.sessionsDir)) {\n const groupDir = path.join(this.sessionsDir, groupName);\n if (!isDirectory(groupDir)) continue;\n\n const decodedCwd = this.decodeGroupCwd(groupName, groupDir);\n\n for (const sessionDir of this.listSessionDirs(groupDir)) {\n const session = this.readSession(sessionDir, decodedCwd);\n if (!session) continue;\n\n const cwd = session.projectPath || decodedCwd;\n if (filterCwd !== undefined && cwd !== filterCwd) continue;\n\n summaries.push({\n type: this.type,\n sessionId: session.sessionId,\n cwd,\n firstUserMessage: session.firstUserMessage || '',\n lastActive: session.lastActive,\n startedAt: session.sessionStart,\n sessionFilePath: path.join(sessionDir, CHAT_HISTORY_FILE),\n });\n }\n }\n\n return summaries;\n }\n\n // --- Session parsing (chat_history.jsonl) ---\n\n /**\n * Parse a session directory into a {@link GrokSession} from its\n * chat_history.jsonl transcript. Returns null when the transcript is\n * missing — i.e. there is no real session to surface.\n */\n private readSession(sessionDir: string, defaultCwd: string): GrokSession | null {\n const chatPath = path.join(sessionDir, CHAT_HISTORY_FILE);\n const chatStat = safeStat(chatPath);\n if (!chatStat) return null;\n\n const scan = this.parseChatHistory(chatPath, false);\n const dirStat = safeStat(sessionDir);\n const lastActive = chatStat.mtime;\n\n return {\n sessionId: path.basename(sessionDir),\n projectPath: defaultCwd || '',\n summary: scan.lastUserMessage || 'Grok CLI session active',\n sessionStart: dirStat?.birthtime || lastActive,\n lastActive,\n firstUserMessage: scan.firstUserMessage,\n lastUserMessage: scan.lastUserMessage,\n lastRole: scan.lastRole,\n };\n }\n\n /**\n * Determine agent status from parsed session state.\n *\n * - past the idle threshold → IDLE\n * - last transcript turn is an assistant message → WAITING (awaiting user)\n * - otherwise (last turn was a user message, or unknown) → RUNNING\n */\n private determineStatus(session: GrokSession): AgentStatus {\n const diffMinutes = (Date.now() - session.lastActive.getTime()) / 60000;\n if (diffMinutes > IDLE_THRESHOLD_MINUTES) {\n return AgentStatus.IDLE;\n }\n if (session.lastRole === 'assistant') {\n return AgentStatus.WAITING;\n }\n return AgentStatus.RUNNING;\n }\n\n /**\n * Single pass over chat_history.jsonl. Each line is a\n * { type: 'system' | 'user' | 'assistant', content } record where content is\n * either a string or an array of { type: 'text', text } blocks.\n *\n * Grok wraps the real user prompt in <user_query>...</user_query>; the other\n * user records are context injections (<user_info>, <system-reminder>, ...)\n * and are skipped so the summary is the actual prompt, not boilerplate.\n */\n private parseChatHistory(chatPath: string, verbose: boolean): ChatScan {\n const empty: ChatScan = { messages: [] };\n const content = safeReadFile(chatPath);\n if (content === undefined) return empty;\n\n const messages: ConversationMessage[] = [];\n let lastRole: ConversationMessage['role'] | undefined;\n\n for (const line of content.trim().split('\\n')) {\n if (!line.trim()) continue;\n\n let record: ChatRecord;\n try {\n record = JSON.parse(line);\n } catch {\n continue;\n }\n\n const text = this.extractText(record.content);\n if (record.type === 'user') {\n const query = this.extractUserQuery(text);\n if (query === null) continue; // context injection, not a real prompt\n messages.push({ role: 'user', content: query });\n lastRole = 'user';\n } else if (record.type === 'assistant') {\n if (!text) continue;\n messages.push({ role: 'assistant', content: text });\n lastRole = 'assistant';\n } else if (verbose && record.type === 'system') {\n if (!text) continue;\n messages.push({ role: 'system', content: text });\n }\n }\n\n const userTurns = messages.filter((m) => m.role === 'user');\n return {\n messages,\n firstUserMessage: userTurns[0]?.content,\n lastUserMessage: userTurns[userTurns.length - 1]?.content,\n lastRole,\n };\n }\n\n /** Flatten a chat record's content (string or text-block array) to text. */\n private extractText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n return content\n .map((block) =>\n block && typeof block === 'object' && typeof (block as { text?: unknown }).text === 'string'\n ? (block as { text: string }).text\n : '',\n )\n .join('');\n }\n return '';\n }\n\n /**\n * Extract the prompt inside <user_query>...</user_query>. Returns null when\n * the record has no such tag (a context injection rather than a prompt).\n */\n private extractUserQuery(text: string): string | null {\n const match = text.match(/<user_query>\\s*([\\s\\S]*?)\\s*<\\/user_query>/);\n return match ? match[1].trim() : null;\n }\n\n /** Resolve a session dir or an explicit chat_history.jsonl path to the file. */\n private resolveChatPath(sessionPath: string): string {\n return sessionPath.endsWith('.jsonl') ? sessionPath : path.join(sessionPath, CHAT_HISTORY_FILE);\n }\n\n private getProjectDir(cwd: string): string {\n return path.join(this.sessionsDir, encodeURIComponent(cwd));\n }\n\n /**\n * Resolve the working directory a session group dir was created for.\n *\n * The common case is `decodeURIComponent(<group-name>)`. For paths whose\n * encoded form exceeds the filesystem limit Grok uses a slug+hash and records\n * the original path in a `.cwd` file inside the group — prefer that when\n * present.\n */\n private decodeGroupCwd(groupName: string, groupDir: string): string {\n const fromFile = safeReadFile(path.join(groupDir, CWD_FILE));\n if (fromFile !== undefined && fromFile.trim()) return fromFile.trim();\n try {\n return decodeURIComponent(groupName);\n } catch {\n return '';\n }\n }\n}\n"],"names":["path","AgentStatus","listAgentProcesses","enrichProcesses","isDirectory","safeReadFile","safeReaddir","safeStat","generateAgentName","CHAT_HISTORY_FILE","ACTIVE_SESSIONS_FILE","CWD_FILE","IDLE_THRESHOLD_MINUTES","GrokCliAdapter","type","base","sessionsDir","homeDir","process","env","HOME","USERPROFILE","GROK_HOME","join","canHandle","processInfo","isGrokExecutable","command","executable","trim","split","basename","toLowerCase","detectAgents","processes","length","pidToCwd","readActiveSessions","agents","proc","cwd","get","pid","sessionDir","latestSessionDir","session","readSession","push","mapSessionToAgent","mapProcessOnlyAgent","map","Map","content","undefined","entries","JSON","parse","Array","isArray","entry","set","listSessionDirs","groupDir","sessionId","filter","getProjectDir","best","stat","mtimeMs","dir","projectPath","name","status","determineStatus","summary","lastActive","sessionFilePath","RUNNING","Date","getConversation","options","parseChatHistory","resolveChatPath","verbose","messages","listSessions","opts","filterCwd","summaries","groupName","decodedCwd","decodeGroupCwd","firstUserMessage","startedAt","sessionStart","defaultCwd","chatPath","chatStat","scan","dirStat","mtime","lastUserMessage","birthtime","lastRole","diffMinutes","now","getTime","IDLE","WAITING","empty","line","record","text","extractText","query","extractUserQuery","role","userTurns","m","block","match","sessionPath","endsWith","encodeURIComponent","fromFile","decodeURIComponent"],"mappings":"AAAA,YAAYA,UAAU,OAAO;AAS7B,SAASC,WAAW,QAAQ,oBAAoB;AAChD,SAASC,kBAAkB,EAAEC,eAAe,QAAQ,sBAAsB;AAC1E,SAASC,WAAW,EAAEC,YAAY,EAAEC,WAAW,EAAEC,QAAQ,QAAQ,sBAAs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AACP,WAAW,EAAE2G,mBAAmBnF;IAC1D;IAEA;;;;;;;KAOC,GACD,AAAQmD,eAAeF,SAAiB,EAAE3B,QAAgB,EAAU;QAChE,MAAM8D,WAAWvH,aAAaL,KAAKuB,IAAI,CAACuC,UAAUnD;QAClD,IAAIiH,aAAavE,aAAauE,SAAS/F,IAAI,IAAI,OAAO+F,SAAS/F,IAAI;QACnE,IAAI;YACA,OAAOgG,mBAAmBpC;QAC9B,EAAE,OAAM;YACJ,OAAO;QACX;IACJ;AACJ"}
|
package/dist/adapters/index.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ export { ClaudeCodeAdapter } from './ClaudeCodeAdapter.js';
|
|
|
2
2
|
export { CodexAdapter } from './CodexAdapter.js';
|
|
3
3
|
export { CopilotAdapter } from './CopilotAdapter.js';
|
|
4
4
|
export { GeminiCliAdapter } from './GeminiCliAdapter.js';
|
|
5
|
+
export { GrokCliAdapter } from './GrokCliAdapter.js';
|
|
5
6
|
export { OpenCodeAdapter } from './OpenCodeAdapter.js';
|
|
6
7
|
export { PiAdapter } from './PiAdapter.js';
|
|
7
8
|
export { AgentStatus } from './AgentAdapter.js';
|