Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 41 additions & 7 deletions plugins/codex/scripts/session-lifecycle-hook.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
loadBrokerSession,
PID_FILE_ENV,
sendBrokerShutdown,
teardownBrokerSession
teardownBrokerSession,
} from "./lib/broker-lifecycle.mjs";
import { loadState, resolveStateFile, saveState } from "./lib/state.mjs";
import { TRANSCRIPT_PATH_ENV } from "./lib/claude-session-transfer.mjs";
Expand All @@ -33,10 +33,42 @@ function shellEscape(value) {
}

function appendEnvVar(name, value) {
if (!process.env.CLAUDE_ENV_FILE || value == null || value === "") {
const envFile = process.env.CLAUDE_ENV_FILE;
if (!envFile || value == null || value === "") {
return;
}
fs.appendFileSync(process.env.CLAUDE_ENV_FILE, `export ${name}=${shellEscape(value)}\n`, "utf8");

const line = `export ${name}=${shellEscape(value)}`;
let existingContent = "";

try {
existingContent = fs.readFileSync(envFile, "utf8");
} catch (error) {
if (error?.code !== "ENOENT") {
throw error;
}
}

const existingLines = existingContent.split(/\r?\n/);
const exportPrefix = `export ${name}=`;

let lastAssignment = null;

for (let index = existingLines.length - 1; index >= 0; index -= 1) {
if (existingLines[index].startsWith(exportPrefix)) {
lastAssignment = existingLines[index];
break;
}
}

if (lastAssignment === line) {
return;
}

const separator =
existingContent.length > 0 && !existingContent.endsWith("\n") ? "\n" : "";

fs.appendFileSync(envFile, `${separator}${line}\n`, "utf8");
}

function cleanupSessionJobs(cwd, sessionId) {
Expand Down Expand Up @@ -70,7 +102,7 @@ function cleanupSessionJobs(cwd, sessionId) {

saveState(workspaceRoot, {
...state,
jobs: state.jobs.filter((job) => job.sessionId !== sessionId)
jobs: state.jobs.filter((job) => job.sessionId !== sessionId),
});
}

Expand All @@ -88,7 +120,7 @@ async function handleSessionEnd(input) {
? {
endpoint: process.env[BROKER_ENDPOINT_ENV],
pidFile: process.env[PID_FILE_ENV] ?? null,
logFile: process.env[LOG_FILE_ENV] ?? null
logFile: process.env[LOG_FILE_ENV] ?? null,
}
: null);
const brokerEndpoint = brokerSession?.endpoint ?? null;
Expand All @@ -108,7 +140,7 @@ async function handleSessionEnd(input) {
logFile,
sessionDir,
pid,
killProcess: terminateProcessTree
killProcess: terminateProcessTree,
});
clearBrokerSession(cwd);
}
Expand All @@ -128,6 +160,8 @@ async function main() {
}

main().catch((error) => {
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
process.stderr.write(
`${error instanceof Error ? error.message : String(error)}\n`,
);
process.exit(1);
});
Loading