nomad / scripts /lib /emit.js
LucioLiu's picture
Initial release - mirrors github.com/LucioLiu/nomad
0110783 verified
Raw
History Blame Contribute Delete
9.03 kB
'use strict';
/**
* emit.js — hook I/O wrapper shared by session-start.js / session-stop.js / precompact.js.
*
* Ported from a production hooks-core module, deployed at `91-team-tools/hooks-core/emit.js`, desensitized.
* One deliberate simplification versus the production version: this port covers
* `claude` and `codex` (byte-for-byte identical stdin/stdout schema for the three
* hook events used here) plus a best-effort `cursor` branch, since those are the
* two harnesses named in this batch's brief. The switch-per-event structure is
* kept exactly as the production version so adding another harness later means
* touching only this one file, never the three hook scripts.
*
* Output discipline: UTF-8, no BOM, one JSON object per line, trailing newline —
* matches what a hook host reading stdout line-by-line expects.
*/
const SUPPORTED_PLATFORMS = ['claude', 'codex', 'cursor'];
function normalizePlatform(p) {
p = String(p || '').trim().toLowerCase();
return SUPPORTED_PLATFORMS.includes(p) ? p : 'claude';
}
/** Read `--platform <name>` or `--platform=<name>` from argv; default 'claude'. */
function getPlatform(argv) {
argv = argv || process.argv.slice(2);
const idx = argv.indexOf('--platform');
if (idx >= 0 && argv[idx + 1]) return normalizePlatform(argv[idx + 1]);
const eq = argv.find((a) => a.startsWith('--platform='));
if (eq) return normalizePlatform(eq.split('=').slice(1).join('='));
return 'claude';
}
/** SessionStart event: inject additional context. */
function buildSessionStartPayload(additionalContext, platform) {
switch (normalizePlatform(platform)) {
case 'cursor':
// Cursor's `sessionStart` hook takes a top-level snake_case `additional_context`
// field, no hookSpecificOutput wrapper. Best-effort — not independently
// verified against a real Cursor install by this batch; see README.md.
return { additional_context: additionalContext };
case 'codex':
case 'claude':
default:
return { hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: additionalContext } };
}
}
/** Stop event: emitting nothing at all means "let the session end" — callers should not print when remind=false. */
function buildStopBlockPayload(reason, platform) {
switch (normalizePlatform(platform)) {
case 'cursor':
// Cursor's `stop` hook has no decision:block mechanism, only an optional
// `followup_message` (re-injected as a follow-up turn). Close enough in
// effect to "the reminder text reaches the session" — not identical semantics.
return { followup_message: reason };
case 'codex':
case 'claude':
default:
return { decision: 'block', reason: reason };
}
}
/** PreCompact event: only the top-level systemMessage field is honored by claude/codex — no hookSpecificOutput here. */
function buildPreCompactPayload(systemMessage, platform) {
switch (normalizePlatform(platform)) {
case 'cursor':
return { user_message: systemMessage };
case 'codex':
case 'claude':
default:
return { systemMessage: systemMessage };
}
}
/** Serialize payload as single-line JSON to stdout, UTF-8 no BOM, trailing newline. */
function writeJson(payload) {
process.stdout.write(JSON.stringify(payload) + '\n');
}
/**
* Read all of stdin as a UTF-8 string (Promise). No timeout — a real hook host
* closes stdin (EOF) after sending its payload; running this file directly in
* an interactive terminal with no redirection will hang waiting for input,
* which is expected (pipe in `echo ... |` or `printf '' |` for manual testing).
*/
function readStdin() {
return new Promise((resolve) => {
let data = '';
try {
process.stdin.setEncoding('utf8');
} catch (e) {
/* ignore */
}
process.stdin.on('data', (chunk) => {
data += chunk;
});
process.stdin.on('end', () => resolve(data));
process.stdin.on('error', () => resolve(data));
});
}
/** Rough mojibake detector — looks for the Unicode replacement character U+FFFD. */
function looksMojibake(s) {
return typeof s === 'string' && s.indexOf('�') !== -1;
}
/**
* Unified cwd resolution, shared by session-start.js / session-stop.js.
* Priority: ① stdin JSON's `cwd` field (not mojibake-damaged) → ② `process.cwd()`
* (the hook subprocess's own working directory, set by the OS directly, not routed
* through any text transcoding — usually equivalent to ① anyway) → ③ cursor-only
* fallback to stdin's `workspace_roots[0]` (must be pure ASCII and undamaged —
* non-ASCII workspace_roots are not trusted on Cursor, see production hooks-core's
* documented finding of a UTF-8-decoded-as-GBK corruption case) → '' if nothing works.
* @param {string} raw stdin raw text
* @param {string} platform claude|codex|cursor
* @param {Function} [pcwdFn] injectable process.cwd stand-in for tests
*/
function resolveCwd(raw, platform, pcwdFn) {
pcwdFn = pcwdFn || process.cwd;
let j = null;
try {
j = raw && raw.trim() ? JSON.parse(raw) : null;
} catch (e) {
j = null;
}
const stdinCwd = j && typeof j.cwd === 'string' ? j.cwd : '';
if (stdinCwd && !looksMojibake(stdinCwd)) return stdinCwd;
let pcwd = '';
try {
pcwd = pcwdFn() || '';
} catch (e) {
pcwd = '';
}
if (pcwd && !looksMojibake(pcwd)) return pcwd;
if (normalizePlatform(platform) === 'cursor') {
try {
const root = j && Array.isArray(j.workspace_roots) ? j.workspace_roots[0] : '';
if (root && /^[\x00-\x7F]+$/.test(root) && !looksMojibake(root)) {
// Only rewrite a POSIX-style Windows drive path (/D:/foo -> D:\foo).
// A genuine POSIX path (/home/user/...) has no drive-letter prefix and
// must be returned untouched — unconditionally turning every '/' into
// '\' (the previous behavior) would corrupt a real Mac/Linux path in
// the low-probability case where a Cursor session on a POSIX host falls
// through both earlier fallbacks to here. Gate the slash-flip on an
// actual drive-letter match rather than doing it always.
const winDrive = /^\/([A-Za-z]):/;
if (winDrive.test(root)) return root.replace(winDrive, '$1:').replace(/\//g, '\\');
return root;
}
} catch (e) {
/* ignore */
}
}
return '';
}
/** Safely extract session_id from raw stdin text. Never throws. */
function extractSessionId(raw) {
try {
if (!raw || !raw.trim()) return '';
const j = JSON.parse(raw);
return typeof j.session_id === 'string' ? j.session_id : '';
} catch (e) {
return '';
}
}
/**
* Double-fire dedup guard. Some harnesses (documented case: Claude Code's
* project-level config lookup climbing to a repository root that also has its
* own hooks config) can end up firing the same hook event twice for one
* session. This gives callers a short-window idempotency check: same event +
* same session_id within `windowMs` (default 5s) is treated as a duplicate.
* No session_id means no dedup (would rather occasionally double-fire than
* risk false-positively swallowing a legitimate single call).
* @param {string} eventName e.g. 'SessionStart' | 'Stop' | 'PreCompact'
* @param {string} sessionId
* @param {{windowMs?: number}} [opts]
* @returns {boolean} true = duplicate, caller should skip
*/
function isDuplicateInvocation(eventName, sessionId, opts) {
if (!sessionId) return false;
opts = opts || {};
const windowMs = typeof opts.windowMs === 'number' ? opts.windowMs : 5000;
const fs = require('fs');
const os = require('os');
const path = require('path');
const key = String(eventName) + '_' + String(sessionId).replace(/[^A-Za-z0-9]/g, '');
const markerFile = path.join(os.tmpdir(), 'nomad_dedupe_' + key + '.marker');
const now = Date.now();
try {
fs.writeFileSync(markerFile, String(now), { flag: 'wx' });
return false; // exclusive create succeeded — first arrival of this batch
} catch (e) {
if (e && e.code === 'EEXIST') {
try {
const raw = fs.readFileSync(markerFile, 'utf8');
const ts = parseInt(raw, 10);
if (Number.isFinite(ts) && now - ts < windowMs) return true; // within window = duplicate
fs.writeFileSync(markerFile, String(now), 'utf8'); // stale marker — treat as new batch
return false;
} catch (e2) {
return false; // read/overwrite failure — fail open
}
}
return false; // any other write failure — fail open
}
}
module.exports = {
SUPPORTED_PLATFORMS,
getPlatform,
normalizePlatform,
buildSessionStartPayload,
buildStopBlockPayload,
buildPreCompactPayload,
writeJson,
readStdin,
looksMojibake,
resolveCwd,
extractSessionId,
isDuplicateInvocation,
};