-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteraction.js
More file actions
2124 lines (1903 loc) · 64.9 KB
/
interaction.js
File metadata and controls
2124 lines (1903 loc) · 64.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { spawn } from 'node:child_process';
import fsp from 'node:fs/promises';
import path from 'node:path';
import os, { tmpdir } from 'node:os';
import { randomUUID } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { loadRuntimeConfig } from './config.js';
const MAX_BODY_BYTES = 25 * 1024 * 1024;
const MAX_IMAGES = 6;
const _cfg = loadRuntimeConfig();
const WORKSPACE_ROOT = _cfg.workspaceRoot || os.homedir();
const COPILOT_BINARY = _cfg.copilotBin || 'copilot';
const COPILOT_CONFIG_DIR = _cfg.copilotConfigDir;
const COPILOT_CONFIG_FILE = _cfg.copilotConfigFile;
const VSCODE_EXTENSIONS_DIR = _cfg.vscodeExtensionsDir;
const VSCODE_CODEX_EXTENSION_PREFIX = 'openai.chatgpt-';
const DEFAULT_CODEX_BINARY = _cfg.codexBin || 'codex';
const DEFAULT_CODEX_ORIGINATOR = 'codex_vscode';
const CODEX_REQUEST_TIMEOUT_MS = 60000;
const CODEX_THREAD_RESUME_TIMEOUT_MS = 150000;
const CODEX_THREAD_RESUME_MAX_ATTEMPTS = 2;
const CODEX_THREAD_RESUME_RETRY_DELAY_MS = 800;
const CODEX_THREAD_RESUME_STATUS_INTERVAL_MS = 15000;
const CODEX_WARM_IDLE_TTL_MS = 10 * 60 * 1000;
const CODEX_WARM_SELF_REFRESH_GRACE_MS = 10000;
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const CLAUDE_MODELS_FILE = _cfg.claudeModelsFile;
const CLAUDE_PROVENANCE_FILE = path.join(__dirname, 'data', 'claude-session-provenance.json');
let resolvedCodexBinaryPromise = null;
let sharedCodexWarmWorker = null;
function safeJsonParse(text) {
try {
return JSON.parse(text);
} catch {
return null;
}
}
function normalizeText(value) {
if (typeof value === 'string') return value;
if (value == null) return '';
return JSON.stringify(value);
}
function truncateText(text, limit = 1200) {
const str = typeof text === 'string' ? text : JSON.stringify(text || '');
if (str.length <= limit) return str;
return str.slice(0, limit) + '...';
}
async function pathExists(filePath) {
try {
await fsp.access(filePath);
return true;
} catch {
return false;
}
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function codexBinaryName() {
return process.platform === 'win32' ? 'codex.exe' : 'codex';
}
function codexBinarySubdir() {
let platformPart = null;
if (process.platform === 'darwin') platformPart = 'macos';
if (process.platform === 'linux') platformPart = 'linux';
if (process.platform === 'win32') platformPart = 'windows';
let archPart = null;
if (process.arch === 'x64') archPart = 'x86_64';
if (process.arch === 'arm64') archPart = 'aarch64';
if (!platformPart || !archPart) return '';
return `${platformPart}-${archPart}`;
}
async function resolveCodexBinary() {
if (resolvedCodexBinaryPromise) {
return resolvedCodexBinaryPromise;
}
resolvedCodexBinaryPromise = (async () => {
const manualOverride = process.env.SESSION_DASHBOARD_CODEX_BINARY?.trim();
if (manualOverride) {
return manualOverride;
}
const binSubdir = codexBinarySubdir();
if (!binSubdir) {
return DEFAULT_CODEX_BINARY;
}
try {
const entries = await fsp.readdir(VSCODE_EXTENSIONS_DIR, { withFileTypes: true });
const extensionDirs = entries
.filter((entry) => entry.isDirectory() && entry.name.startsWith(VSCODE_CODEX_EXTENSION_PREFIX))
.map((entry) => entry.name)
.sort()
.reverse();
for (const dirName of extensionDirs) {
const candidate = path.join(
VSCODE_EXTENSIONS_DIR,
dirName,
'bin',
binSubdir,
codexBinaryName(),
);
if (await pathExists(candidate)) {
return candidate;
}
}
} catch {
// Fall back to whatever `codex` resolves to on PATH.
}
return DEFAULT_CODEX_BINARY;
})();
return resolvedCodexBinaryPromise;
}
function extractCopilotModel(message) {
if (typeof message !== 'string') return '';
const match = message.match(/Model changed to:\s*(.+)$/);
return match ? match[1].trim() : message.trim();
}
async function getCopilotToken() {
try {
const raw = await fsp.readFile(COPILOT_CONFIG_FILE, 'utf-8');
const config = JSON.parse(raw);
const token = Object.values(config.copilot_tokens || {})[0];
return typeof token === 'string' && token ? token : '';
} catch {
return '';
}
}
export async function getInteractionCapabilities() {
const copilotToken = await getCopilotToken();
const copilotReady = !!copilotToken;
return {
codex: {
enabled: true,
directImages: true,
streamMode: 'message',
note: 'Text is sent into the selected Codex session and continues that session context. Images are attached natively via the Codex CLI.',
},
claude: {
enabled: true,
directImages: false,
streamMode: 'delta',
note: 'Text is sent into the selected Claude session and continues that session context. Images are saved on the server and referenced by local file path for tool inspection.',
},
copilot: {
enabled: copilotReady,
directImages: false,
streamMode: 'delta',
note: copilotReady
? 'Text is sent into the selected Copilot session and continues that session context. Images are saved on the server and referenced by local file path.'
: 'Copilot CLI interaction is unavailable until a GitHub token is present in the local Copilot config.',
},
};
}
function beginNdjson(res) {
res.writeHead(200, {
'Content-Type': 'application/x-ndjson; charset=utf-8',
'Cache-Control': 'no-store, max-age=0',
Pragma: 'no-cache',
Connection: 'keep-alive',
});
}
function sendEvent(res, payload) {
res.write(JSON.stringify(payload) + '\n');
}
async function readJsonBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
req.on('data', (chunk) => {
size += chunk.length;
if (size > MAX_BODY_BYTES) {
reject(new Error('Request body too large'));
req.destroy();
return;
}
chunks.push(chunk);
});
req.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf-8').trim();
if (!raw) {
resolve({});
return;
}
try {
resolve(JSON.parse(raw));
} catch (err) {
reject(new Error('Invalid JSON body'));
}
});
req.on('error', reject);
});
}
function sanitizeFilename(name, fallback = 'image') {
const base = (name || fallback)
.replace(/[^A-Za-z0-9._-]+/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '');
return base || fallback;
}
function extensionFromMime(type) {
const map = {
'image/png': '.png',
'image/jpeg': '.jpg',
'image/jpg': '.jpg',
'image/webp': '.webp',
'image/gif': '.gif',
'image/svg+xml': '.svg',
};
return map[type] || '';
}
function safeJsonObject(text) {
const parsed = safeJsonParse(text);
return parsed && typeof parsed === 'object' ? parsed : {};
}
function buildSessionKey(locator) {
if (!locator?.source || !locator?.projectPath || !locator?.rawSessionId) return '';
return JSON.stringify({
source: locator.source,
projectPath: locator.projectPath,
rawSessionId: locator.rawSessionId,
});
}
async function loadClaudeProfiles() {
try {
const raw = await fsp.readFile(CLAUDE_MODELS_FILE, 'utf-8');
const parsed = safeJsonObject(raw);
return parsed.models && typeof parsed.models === 'object' ? parsed.models : {};
} catch {
return {};
}
}
async function loadClaudeProvenance() {
try {
const raw = await fsp.readFile(CLAUDE_PROVENANCE_FILE, 'utf-8');
return safeJsonObject(raw);
} catch {
return {};
}
}
async function persistClaudeProvenance(provenance) {
await fsp.mkdir(path.dirname(CLAUDE_PROVENANCE_FILE), { recursive: true });
await fsp.writeFile(CLAUDE_PROVENANCE_FILE, JSON.stringify(provenance, null, 2) + '\n', 'utf-8');
}
async function resolveClaudeLaunchContext(locator, sessionMeta = null, profileOverride = '') {
const models = await loadClaudeProfiles();
const provenance = await loadClaudeProvenance();
const key = buildSessionKey(locator);
const saved = key ? provenance[key] || null : null;
if (profileOverride && models[profileOverride]?.env) {
const env = models[profileOverride].env || {};
return {
profile: profileOverride,
profileLabel: profileOverride.toUpperCase(),
anthropicModel: env.ANTHROPIC_MODEL || '',
baseUrl: env.ANTHROPIC_BASE_URL || '',
env,
exact: true,
source: 'manual-profile',
};
}
if (saved?.profile && models[saved.profile]?.env) {
const env = models[saved.profile].env || {};
return {
profile: saved.profile,
profileLabel: saved.profileLabel || saved.profile.toUpperCase(),
anthropicModel: env.ANTHROPIC_MODEL || saved.anthropicModel || '',
baseUrl: env.ANTHROPIC_BASE_URL || saved.baseUrl || '',
env,
exact: true,
source: 'recorded',
};
}
const hintedProfile = sessionMeta?.claudeProfile || '';
if (hintedProfile && models[hintedProfile]?.env) {
const env = models[hintedProfile].env || {};
return {
profile: hintedProfile,
profileLabel: sessionMeta?.claudeProfileLabel || hintedProfile.toUpperCase(),
anthropicModel: env.ANTHROPIC_MODEL || sessionMeta?.claudeModel || '',
baseUrl: env.ANTHROPIC_BASE_URL || sessionMeta?.claudeBaseUrl || '',
env,
exact: !!sessionMeta?.claudeProfileExact,
source: sessionMeta?.claudeConfigSource || 'hinted',
};
}
return {
profile: '',
profileLabel: '',
anthropicModel: sessionMeta?.claudeModel || '',
baseUrl: sessionMeta?.claudeBaseUrl || '',
env: {},
exact: false,
source: 'default',
};
}
async function recordClaudeProvenance(locator, launchContext) {
const key = buildSessionKey(locator);
if (!key || !launchContext) return;
const provenance = await loadClaudeProvenance();
provenance[key] = {
profile: launchContext.profile || '',
profileLabel: launchContext.profileLabel || '',
anthropicModel: launchContext.anthropicModel || '',
baseUrl: launchContext.baseUrl || '',
source: launchContext.source || 'dashboard',
};
await persistClaudeProvenance(provenance);
}
async function materializeImages(images) {
if (!Array.isArray(images) || images.length === 0) {
return { dir: '', files: [] };
}
const limited = images.slice(0, MAX_IMAGES);
const uploadDir = path.join(tmpdir(), 'session-dashboard-uploads', randomUUID());
await fsp.mkdir(uploadDir, { recursive: true });
const files = [];
for (let index = 0; index < limited.length; index++) {
const image = limited[index] || {};
const mimeType = typeof image.type === 'string' ? image.type : '';
const dataUrl = typeof image.dataUrl === 'string' ? image.dataUrl : '';
if (!mimeType.startsWith('image/') || !dataUrl.startsWith('data:')) {
continue;
}
const match = dataUrl.match(/^data:(.*?);base64,(.+)$/);
if (!match) continue;
const ext = path.extname(image.name || '') || extensionFromMime(mimeType) || '.bin';
const filename = `${String(index + 1).padStart(2, '0')}-${sanitizeFilename(
path.basename(image.name || `image-${index + 1}`)
).replace(/\.[A-Za-z0-9]+$/, '')}${ext}`;
const filePath = path.join(uploadDir, filename);
await fsp.writeFile(filePath, Buffer.from(match[2], 'base64'));
files.push({
name: filename,
path: filePath,
mimeType,
});
}
return { dir: uploadDir, files };
}
function imageCountText(count) {
return `${count} image${count === 1 ? '' : 's'}`;
}
function buildPrompt(text, imageFiles, directImages) {
const trimmed = typeof text === 'string' ? text.trim() : '';
let prompt = trimmed;
if (!prompt && imageFiles.length > 0) {
prompt = 'Please inspect the attached image file(s) and help the user with them.';
}
if (!directImages && imageFiles.length > 0) {
const fileList = imageFiles.map((file) => `- ${file.path}`).join('\n');
const suffix = `\n\nThe user attached image file(s) saved locally on disk. Inspect them if helpful:\n${fileList}`;
prompt = prompt ? `${prompt}${suffix}` : suffix.trim();
}
return prompt || 'Please continue the session.';
}
function processJsonLines(stream, onLine) {
let buffer = '';
stream.on('data', (chunk) => {
buffer += chunk.toString('utf-8');
while (true) {
const idx = buffer.indexOf('\n');
if (idx === -1) break;
const line = buffer.slice(0, idx).trim();
buffer = buffer.slice(idx + 1);
if (line) onLine(line);
}
});
stream.on('end', () => {
const line = buffer.trim();
if (line) onLine(line);
});
}
function extractClaudeAssistantText(message) {
const blocks = Array.isArray(message?.content) ? message.content : [];
return blocks
.filter((block) => block.type === 'text')
.map((block) => block.text || '')
.join('');
}
function extractCopilotAssistantText(data) {
if (typeof data?.content === 'string') return data.content;
return '';
}
function createCodexArgs(locator, prompt, imageFiles) {
const args = locator.draft
? ['exec', '--json', '--skip-git-repo-check', prompt]
: ['exec', 'resume', locator.rawSessionId, prompt, '--json', '--skip-git-repo-check'];
for (const image of imageFiles) {
args.push('-i', image.path);
}
return args;
}
function createClaudeArgs(locator, prompt, uploadDir) {
const args = locator.draft
? ['-p', '--verbose', '--output-format', 'stream-json', '--session-id', locator.rawSessionId, prompt]
: ['-p', '--verbose', '--output-format', 'stream-json', '-r', locator.rawSessionId, prompt];
if (uploadDir) {
args.push('--add-dir', uploadDir);
}
return args;
}
function createCopilotArgs(locator, prompt, uploadDir) {
const args = [
'--config-dir',
COPILOT_CONFIG_DIR,
`--resume=${locator.rawSessionId}`,
'-p',
prompt,
'--output-format',
'json',
'--stream',
'on',
'--allow-all-tools',
'--allow-all-paths',
];
if (uploadDir) {
args.push('--add-dir', uploadDir);
}
return args;
}
function defaultCwd(locator) {
return locator.projectPath && locator.projectPath !== '(unknown)' ? locator.projectPath : WORKSPACE_ROOT;
}
function formatCommandForDisplay(command) {
if (typeof command !== 'string') return '';
const bashMatch = command.match(/^\/bin\/bash -lc "(.*)"$/s);
if (!bashMatch) return command;
return bashMatch[1]
.replace(/\\"/g, '"')
.replace(/\\\\/g, '\\');
}
function formatCommandResult(item) {
const exitCode = Number.isInteger(item?.exit_code) ? item.exit_code : null;
const output = typeof item?.aggregated_output === 'string' ? item.aggregated_output.trim() : '';
const parts = [];
if (exitCode != null) parts.push(`Result: Exit code ${exitCode}`);
if (output) {
parts.push('```text');
parts.push(output);
parts.push('```');
}
return parts.join('\n');
}
function formatFileChanges(item) {
const changes = Array.isArray(item?.changes) ? item.changes : [];
if (!changes.length) return 'Updated files.';
const lines = changes.map((change) => `- ${change.path}${change.kind ? ` (${change.kind})` : ''}`);
return `Updated files:\n${lines.join('\n')}`;
}
function buildCodexCommandStartEvent(item) {
const command = formatCommandForDisplay(item?.command || '');
return {
type: 'tool_event',
toolName: 'shell_command',
summary: truncateText(command.split('\n')[0] || 'shell_command', 180),
command,
content: command
? `shell_command\n\`\`\`bash\n${command}\n\`\`\``
: 'shell_command',
};
}
function buildCodexCommandResultEvent(item, formatter) {
const command = formatCommandForDisplay(item?.command || '');
const exitCode = Number.isInteger(item?.exitCode) ? item.exitCode : item?.exit_code;
const aggregatedOutput = typeof item?.aggregatedOutput === 'string'
? item.aggregatedOutput
: (typeof item?.aggregated_output === 'string' ? item.aggregated_output : '');
return {
type: 'tool_result',
toolName: 'shell_command',
summary: Number.isInteger(exitCode)
? `Exit code ${exitCode}`
: truncateText((aggregatedOutput || command || 'shell_command').split('\n')[0], 180),
command,
exitCode: Number.isInteger(exitCode) ? exitCode : null,
aggregatedOutput,
content: formatter(item),
};
}
function buildCodexFileChangeEvent(item, formatter) {
const changes = Array.isArray(item?.changes) ? item.changes : [];
return {
type: 'tool_event',
toolName: 'apply_patch',
summary: changes.length
? truncateText(changes.map((change) => change.path).join(', '), 180)
: 'Updated files.',
changes,
content: `apply_patch\n${formatter(item)}`,
};
}
function parseCodexLine(line, res) {
const obj = safeJsonParse(line);
if (!obj) {
sendEvent(res, { type: 'status', message: truncateText(line, 400) });
return;
}
if (obj.type === 'thread.started') {
sendEvent(res, { type: 'meta', source: 'codex', sessionId: obj.thread_id });
sendEvent(res, { type: 'session_created', source: 'codex', rawSessionId: obj.thread_id });
return;
}
if (obj.type === 'turn.started') {
sendEvent(res, { type: 'status', message: 'Codex resumed the selected session.' });
return;
}
if (obj.type === 'item.started' && obj.item?.type === 'command_execution') {
sendEvent(res, buildCodexCommandStartEvent(obj.item));
return;
}
if (obj.type === 'item.completed' && obj.item?.type === 'command_execution') {
sendEvent(res, buildCodexCommandResultEvent(obj.item, formatCommandResult));
return;
}
if (obj.type === 'item.completed' && obj.item?.type === 'file_change') {
sendEvent(res, buildCodexFileChangeEvent(obj.item, formatFileChanges));
return;
}
if (obj.type === 'item.completed' && obj.item?.type === 'agent_message') {
sendEvent(res, {
type: 'assistant_final',
text: obj.item.text || '',
itemId: obj.item.id || '',
phase: obj.item.phase || '',
});
return;
}
if (obj.type === 'turn.completed') {
sendEvent(res, { type: 'status', message: 'Codex turn completed.' });
}
}
function extractCodexExtensionVersion(codexBinary) {
if (typeof codexBinary !== 'string') return 'unknown';
const match = codexBinary.match(/openai\.chatgpt-([^/]+)/);
return match?.[1] || process.env.SESSION_DASHBOARD_CODEX_EXTENSION_VERSION || 'unknown';
}
function codexClientInfo(codexBinary) {
return {
name: 'VS Code',
title: 'Codex Extension',
version: extractCodexExtensionVersion(codexBinary),
};
}
function resolveCodexThreadTarget(locator, sessionMeta = null) {
const rawSessionId = (sessionMeta?.rawSessionId || locator?.rawSessionId || '').trim();
if (rawSessionId) {
return {
mode: 'resume',
rawSessionId,
};
}
return {
mode: 'start',
rawSessionId: '',
};
}
function buildCodexInputItems(text, imageFiles) {
const items = [];
const trimmed = typeof text === 'string' ? text.trim() : '';
const fallbackText = imageFiles.length > 0
? 'Please inspect the attached image file(s) and help the user with them.'
: '';
const contentText = trimmed || fallbackText;
if (contentText) {
items.push({
type: 'text',
text: contentText,
text_elements: [],
});
}
for (const image of imageFiles) {
if (!image?.path) continue;
items.push({
type: 'localImage',
path: image.path,
});
}
return items;
}
function formatAppServerCommandResult(item) {
const exitCode = Number.isInteger(item?.exitCode) ? item.exitCode : null;
const output = typeof item?.aggregatedOutput === 'string' ? item.aggregatedOutput.trim() : '';
const parts = [];
if (exitCode != null) parts.push(`Result: Exit code ${exitCode}`);
if (output) {
parts.push('```text');
parts.push(output);
parts.push('```');
}
return parts.join('\n');
}
function formatAppServerFileChanges(item) {
const changes = Array.isArray(item?.changes) ? item.changes : [];
if (!changes.length) return 'Updated files.';
const lines = changes.map((change) => `- ${change.path}${change.kind ? ` (${change.kind})` : ''}`);
return `Updated files:\n${lines.join('\n')}`;
}
function buildCodexTokenUsageMessage(tokenUsage) {
const last = tokenUsage?.last;
if (!last || !Number.isFinite(last.inputTokens)) return '';
const cached = Number.isFinite(last.cachedInputTokens) ? last.cachedInputTokens : 0;
const total = last.inputTokens;
if (total <= 0) return '';
const percent = Math.round((cached / total) * 100);
return `Cache hit: ${cached}/${total} input tokens (${percent}%).`;
}
function buildCodexAppServerEnv(extraEnv = {}) {
const env = { ...process.env, ...(extraEnv || {}) };
delete env.TERM;
delete env.COLORTERM;
delete env.TERM_PROGRAM;
delete env.TERM_PROGRAM_VERSION;
delete env.CODEX_CI;
delete env.CODEX_THREAD_ID;
return env;
}
function shouldIgnoreCodexAppServerLogLine(text) {
if (!text) return false;
return [
/chatgpt authentication required to sync remote plugins; api key auth is not supported/i,
/failed to warm featured plugin ids cache/i,
/remote plugin sync request to https:\/\/chatgpt\.com\/backend-api\/plugins\/featured/i,
/challenge-error-text/i,
/Enable JavaScript and cookies to continue/i,
/Failed to delete shell snapshot .*No such file or directory/i,
/sqlx::query: slow statement: execution time exceeded alert threshold/i,
/INSERT INTO logs \(ts,/i,
].some((pattern) => pattern.test(text));
}
function buildCodexWarmEnvSignature(env = {}) {
return JSON.stringify(
Object.entries(env || {})
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, value]) => [key, String(value)]),
);
}
function buildCodexWarmReuseKey(options) {
return JSON.stringify({
command: options.command || '',
cwd: options.cwd || '',
rawSessionId: options.threadTarget?.rawSessionId || '',
env: buildCodexWarmEnvSignature(options.env || {}),
});
}
async function resolveCodexTranscriptFingerprint(options) {
const relativePath = options.locator?.relativePath || '';
const codexSessionsDir = options.config?.codexSessionsDir || '';
if (!relativePath || !codexSessionsDir) return '';
try {
const stat = await fsp.stat(path.join(codexSessionsDir, relativePath));
return `${Math.floor(stat.mtimeMs)}:${stat.size}`;
} catch {
return '';
}
}
function canUseWarmCodexWorker(options) {
return Boolean(
options.threadTarget?.mode === 'resume' &&
options.threadTarget?.rawSessionId &&
options.locator?.relativePath &&
options.config?.codexSessionsDir,
);
}
function clearSharedCodexWarmWorker(worker) {
if (sharedCodexWarmWorker === worker) {
sharedCodexWarmWorker = null;
}
}
class CodexWarmWorker {
constructor(options) {
this.command = options.command;
this.cwd = options.cwd;
this.env = options.env || {};
this.reuseKey = options.reuseKey;
this.locator = options.locator;
this.config = options.config;
this.currentThreadId = '';
this.threadReady = false;
this.initialized = false;
this.closed = false;
this.activeRequest = null;
this.pendingRequests = new Map();
this.nextRequestId = 1;
this.stderr = '';
this.idleTimer = null;
this.forceKillTimer = null;
this.fingerprintRefreshTimer = null;
this.lastTurnCompletedAt = 0;
this.transcriptFingerprint = options.transcriptFingerprint || '';
this.needsFingerprintRefresh = false;
this.child = spawn(this.command, ['app-server', '--analytics-default-enabled'], {
cwd: this.cwd,
env: buildCodexAppServerEnv(this.env),
stdio: ['pipe', 'pipe', 'pipe'],
});
this.attachProcessHandlers();
}
describeContext() {
return `(cwd=${this.cwd}, thread=${this.currentThreadId || this.locator?.rawSessionId || ''})`;
}
attachProcessHandlers() {
processJsonLines(this.child.stdout, (line) => {
const message = safeJsonParse(line);
if (!message) {
this.sendStatusToActive(truncateText(line, 400));
return;
}
if (
Object.prototype.hasOwnProperty.call(message, 'id') &&
(Object.prototype.hasOwnProperty.call(message, 'result') ||
Object.prototype.hasOwnProperty.call(message, 'error'))
) {
const id = String(message.id);
const pending = this.pendingRequests.get(id);
if (!pending) return;
clearTimeout(pending.timer);
this.pendingRequests.delete(id);
const elapsedMs = Date.now() - (pending.startedAt || Date.now());
if (elapsedMs >= 5000) {
console.warn(
`[session-dashboard] Codex ${pending.method} completed in ${elapsedMs}ms ${this.describeContext()}`,
);
}
if (message.error) {
pending.reject(new Error(message.error.message || `${pending.method} failed.`));
return;
}
pending.resolve(message.result);
return;
}
if (Object.prototype.hasOwnProperty.call(message, 'id')) {
this.handleServerRequest(message);
return;
}
if (message.method) {
this.handleNotification(message);
}
});
this.child.stderr.on('data', (chunk) => {
const lines = chunk
.toString('utf-8')
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean)
.filter((line) => !shouldIgnoreCodexAppServerLogLine(line));
if (!lines.length) return;
const text = lines.join('\n');
this.stderr += (this.stderr ? '\n' : '') + text;
for (const line of lines) {
this.sendStatusToActive(truncateText(line, 400));
}
});
this.child.on('error', (err) => {
this.handleChildShutdown(err.message || 'Failed to start Codex app-server.');
});
this.child.on('close', (code) => {
if (this.forceKillTimer) {
clearTimeout(this.forceKillTimer);
this.forceKillTimer = null;
}
const active = this.activeRequest;
const graceful = !!active?.turnCompleted || code === 0;
const message = graceful
? ''
: (this.stderr.trim() || `Codex app-server exited with code ${code}`);
this.closed = true;
clearSharedCodexWarmWorker(this);
for (const { reject, timer } of this.pendingRequests.values()) {
clearTimeout(timer);
reject(new Error('Codex app-server interaction ended before the request completed.'));
}
this.pendingRequests.clear();
if (active && !active.finished) {
this.finishActiveRequest(message ? { type: 'error', message } : null);
}
});
}
handleChildShutdown(message) {
if (!message && this.closed) return;
this.destroy('child-shutdown');
if (this.activeRequest && !this.activeRequest.finished) {
this.finishActiveRequest({ type: 'error', message: message || 'Codex app-server interaction failed.' });
}
}
handleServerRequest(message) {
const method = message?.method;
const id = message?.id;
if (id == null || !method) return;
if (
method === 'item/commandExecution/requestApproval' ||
method === 'item/fileChange/requestApproval' ||
method === 'execCommandApproval' ||
method === 'applyPatchApproval'
) {
this.sendResponse(id, { decision: 'denied' });
return;
}
if (method === 'item/permissions/requestApproval') {
this.sendResponse(id, { permissions: {}, scope: 'turn' });
return;
}
if (method === 'item/tool/requestUserInput') {
this.sendResponse(id, { answers: {} });
return;
}
if (method === 'mcpServer/elicitation/request') {
this.sendResponse(id, { action: 'cancel', content: null, _meta: null });
return;
}
if (method === 'item/tool/call') {
this.sendResponse(id, { contentItems: [], success: false });
return;
}
this.sendErrorResponse(id, `Unsupported app-server request: ${method}`, -32601);
}
handleNotification(message) {
const method = message?.method;
const params = message?.params || {};
const active = this.activeRequest;
if (!method) return;
if (method === 'thread/started') {
this.currentThreadId = params?.thread?.id || this.currentThreadId;
this.threadReady = true;
if (active && !active.finished) {
sendEvent(active.res, { type: 'meta', source: 'codex', sessionId: this.currentThreadId });
if (active.expectSessionCreated && this.currentThreadId && !active.sentSessionCreated) {
active.sentSessionCreated = true;
sendEvent(active.res, { type: 'session_created', source: 'codex', rawSessionId: this.currentThreadId });
}
}
return;
}
if (!active || active.finished) return;
if (method === 'turn/started') {
sendEvent(active.res, {
type: 'status',
message: active.turnStartedMessage || 'Codex resumed the selected session.',
});
return;
}
if (method === 'item/agentMessage/delta' && params?.delta) {
sendEvent(active.res, {
type: 'assistant_delta',
text: params.delta,
itemId: params.itemId || '',
});
return;
}
if (method === 'item/started' && params?.item?.type === 'commandExecution') {
sendEvent(active.res, buildCodexCommandStartEvent(params.item));
return;
}
if (method === 'item/completed' && params?.item?.type === 'commandExecution') {
sendEvent(active.res, buildCodexCommandResultEvent(params.item, formatAppServerCommandResult));
return;
}
if (method === 'item/completed' && params?.item?.type === 'fileChange') {
sendEvent(active.res, buildCodexFileChangeEvent(params.item, formatAppServerFileChanges));
return;
}
if (method === 'item/completed' && params?.item?.type === 'agentMessage') {
sendEvent(active.res, {
type: 'assistant_final',
text: params.item.text || '',
itemId: params.item.id || '',
phase: params.item.phase || '',
});
return;
}
if (method === 'thread/tokenUsage/updated') {
const usageMessage = buildCodexTokenUsageMessage(params?.tokenUsage);
if (usageMessage) {
sendEvent(active.res, { type: 'status', message: usageMessage });
}
return;
}
if (method === 'error') {
const details = params?.message || params?.error || 'Codex app-server interaction failed.';
sendEvent(active.res, { type: 'error', message: truncateText(normalizeText(details), 800) });
return;
}
if (method === 'turn/completed') {
active.turnCompleted = true;
this.lastTurnCompletedAt = Date.now();
this.needsFingerprintRefresh = true;
this.scheduleFingerprintRefresh();