()
| 59 | * Errors logged to debug, never thrown. |
| 60 | */ |
| 61 | export async function registerSession(): Promise<boolean> { |
| 62 | if (getAgentId() != null) return false |
| 63 | |
| 64 | const kind: SessionKind = envSessionKind() ?? 'interactive' |
| 65 | const dir = getSessionsDir() |
| 66 | const pidFile = join(dir, `${process.pid}.json`) |
| 67 | |
| 68 | registerCleanup(async () => { |
| 69 | try { |
| 70 | await unlink(pidFile) |
| 71 | } catch { |
| 72 | // ENOENT is fine (already deleted or never written) |
| 73 | } |
| 74 | }) |
| 75 | |
| 76 | try { |
| 77 | await mkdir(dir, { recursive: true, mode: 0o700 }) |
| 78 | await chmod(dir, 0o700) |
| 79 | await writeFile( |
| 80 | pidFile, |
| 81 | jsonStringify({ |
| 82 | pid: process.pid, |
| 83 | sessionId: getSessionId(), |
| 84 | cwd: getOriginalCwd(), |
| 85 | startedAt: Date.now(), |
| 86 | kind, |
| 87 | entrypoint: process.env.CLAUDE_CODE_ENTRYPOINT, |
| 88 | ...(feature('UDS_INBOX') |
| 89 | ? { messagingSocketPath: process.env.CLAUDE_CODE_MESSAGING_SOCKET } |
| 90 | : {}), |
| 91 | ...(feature('BG_SESSIONS') |
| 92 | ? { |
| 93 | name: process.env.CLAUDE_CODE_SESSION_NAME, |
| 94 | logPath: process.env.CLAUDE_CODE_SESSION_LOG, |
| 95 | agent: process.env.CLAUDE_CODE_AGENT, |
| 96 | } |
| 97 | : {}), |
| 98 | }), |
| 99 | ) |
| 100 | // --resume / /resume mutates getSessionId() via switchSession. Without |
| 101 | // this, the PID file's sessionId goes stale and `claude ps` sparkline |
| 102 | // reads the wrong transcript. |
| 103 | onSessionSwitch(id => { |
| 104 | void updatePidFile({ sessionId: id }) |
| 105 | }) |
| 106 | return true |
| 107 | } catch (e) { |
| 108 | logForDebugging(`[concurrentSessions] register failed: ${errorMessage(e)}`) |
| 109 | return false |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /** |
| 114 | * Update this session's name in its PID registry file so ListPeers |
no test coverage detected