@elaraai/east-codex-plugin 0.0.0-stage → 1.0.89

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.
@@ -0,0 +1,584 @@
1
+ // ../east-plugin/dist/lib/codex-hook.js
2
+ import { readFile as readFile2 } from "node:fs/promises";
3
+ import { existsSync, writeFileSync } from "node:fs";
4
+ import { createHash } from "node:crypto";
5
+ import { tmpdir } from "node:os";
6
+ import { join, resolve as resolve3 } from "node:path";
7
+
8
+ // ../east-plugin/dist/lib/codex-tools.js
9
+ import { resolve } from "node:path";
10
+ function patchFiles(command, cwd) {
11
+ const files = [];
12
+ let current;
13
+ for (const line of command.split(/\r?\n/)) {
14
+ const header = /^\*\*\* (Add|Update|Delete) File: (.+)$/.exec(line);
15
+ if (header) {
16
+ const path = resolve(cwd, header[2]);
17
+ current = { path, originalPath: path, code: "", deleted: header[1] === "Delete" };
18
+ files.push(current);
19
+ } else if (line.startsWith("*** Move to: ") && current) {
20
+ current.path = resolve(cwd, line.slice(13));
21
+ } else if (current && (line.startsWith("+") || line.startsWith(" "))) {
22
+ current.code += line.slice(1) + "\n";
23
+ }
24
+ }
25
+ return files;
26
+ }
27
+ function shellReadPaths(command, cwd) {
28
+ const paths = /* @__PURE__ */ new Set();
29
+ let dir = cwd;
30
+ for (const segment of command.split(/&&|;|\n|\|/)) {
31
+ const tokens = [...segment.matchAll(/"([^"\n]*)"|'([^'\n]*)'|([^\s]+)/g)].map((m) => m[1] ?? m[2] ?? m[3]);
32
+ if (tokens[0] === "cd" && tokens[1]) {
33
+ dir = resolve(dir, tokens[1]);
34
+ continue;
35
+ }
36
+ if (!["cat", "head", "tail", "sed", "rg", "grep", "less", "more"].includes(tokens[0] ?? ""))
37
+ continue;
38
+ for (const token of tokens.slice(1)) {
39
+ if (!token.startsWith("-") && !/[*?$`]/.test(token) && /\.(tsx?|js|py)$/.test(token))
40
+ paths.add(resolve(dir, token));
41
+ }
42
+ }
43
+ return [...paths];
44
+ }
45
+
46
+ // ../east-plugin/dist/lib/bash-writes.js
47
+ import { resolve as resolve2 } from "node:path";
48
+ function isRealPath(token) {
49
+ if (token === "" || token.startsWith("&"))
50
+ return false;
51
+ if (/^\d+$/.test(token))
52
+ return false;
53
+ return !token.startsWith("/dev/");
54
+ }
55
+ function unquote(token) {
56
+ const m = /^(['"])(.*)\1$/.exec(token);
57
+ return m?.[2] ?? token;
58
+ }
59
+ function segments(command) {
60
+ return command.split(/\|\||&&|[;|\n]/);
61
+ }
62
+ function lastToken(segment) {
63
+ const tokens = segment.trim().split(/\s+/).map(unquote).filter((t) => t !== "" && !t.startsWith("-"));
64
+ const last = tokens.at(-1);
65
+ return last !== void 0 && isRealPath(last) ? last : void 0;
66
+ }
67
+ function writtenPaths(command, cwd) {
68
+ const found = /* @__PURE__ */ new Set();
69
+ let dir = cwd;
70
+ const add = (path) => {
71
+ if (!isRealPath(path))
72
+ return;
73
+ found.add(dir === void 0 ? path : resolve2(dir, path));
74
+ };
75
+ for (const segment of segments(command)) {
76
+ const trimmed = segment.trim();
77
+ const moved = /^cd\s+(['"]?)([^\s'";|&<>]+)\1\s*$/.exec(trimmed);
78
+ if (moved !== null && dir !== void 0) {
79
+ dir = resolve2(dir, unquote(moved[2] ?? ""));
80
+ continue;
81
+ }
82
+ for (const match of trimmed.matchAll(/>>?\s*(['"]?)([^\s'";|&<>]+)\1/g))
83
+ add(unquote(match[2] ?? ""));
84
+ for (const match of trimmed.matchAll(/\btee\s+(?:-a\s+)?(['"]?)([^\s'";|&<>]+)\1/g))
85
+ add(unquote(match[2] ?? ""));
86
+ if (/^\s*(sed\s+(-[^\s]*\s+)*-i|cp|mv|install)\b/.test(trimmed)) {
87
+ const path = lastToken(trimmed);
88
+ if (path !== void 0)
89
+ add(path);
90
+ }
91
+ }
92
+ return [...found];
93
+ }
94
+
95
+ // ../east-plugin/dist/lib/transcript.js
96
+ import { readFile } from "node:fs/promises";
97
+ var SEARCH_TOOLS = ["mcp__plugin_east_east__search_east_examples", "mcp__plugin_east_east__get_east_example", "mcp__east__search_east_examples", "mcp__east__get_east_example"];
98
+ async function searchedInTranscript(transcriptPath, tools = SEARCH_TOOLS) {
99
+ let raw;
100
+ try {
101
+ raw = await readFile(transcriptPath, "utf-8");
102
+ } catch {
103
+ return false;
104
+ }
105
+ return tools.some((tool) => raw.includes(`"name":"${tool}"`) || raw.includes(`"name": "${tool}"`));
106
+ }
107
+
108
+ // ../east-plugin/dist/lib/search-guidance.js
109
+ var EAST_GUIDANCE = {
110
+ searchTool: "mcp__plugin_east_east__search_east_examples",
111
+ getTool: "mcp__plugin_east_east__get_east_example",
112
+ corpus: "East",
113
+ scope: "@elaraai"
114
+ };
115
+ function bare(tool) {
116
+ const at = tool.lastIndexOf("__");
117
+ return at < 0 ? tool : tool.slice(at + 2);
118
+ }
119
+ function gateText(g) {
120
+ return [
121
+ `STOP: no ${g.corpus} example search on record in this session, and this is ${g.corpus} code.`,
122
+ `Before writing or changing ${g.corpus} code, search the tested example index \u2014 it is the API reference:`,
123
+ `1. \`${g.searchTool}\` with what you are about to do (language: "python" for east-py, "typescript" otherwise); summaries come back \u2014 id, signature, inputs and result.`,
124
+ `2. \`${g.getTool}\` for the one or two that match, and pattern your code on them.`,
125
+ `Do not read node_modules/${g.scope}/** or *.examples.ts files instead: the index is the same corpus, exact and far cheaper. Every ${g.corpus} skill requires this step.`
126
+ ].join("\n");
127
+ }
128
+ function readText(g) {
129
+ return [
130
+ `Note: the ${g.corpus} example index is the API reference \u2014 \`${g.searchTool}\` (then \`${bare(g.getTool)}\`) returns the same tested programs as the ${g.corpus} packages' examples and type declarations, exact, printed in TypeScript or python, at a fraction of the tokens.`,
131
+ `Reading \`.d.ts\` signatures or sweeping \`*.examples.ts\` files reliably produces broken ${g.corpus} code that still type-checks: the signatures omit the runtime rules. Search instead, and read a specific file only when the search pointed you at it.`
132
+ ].join("\n");
133
+ }
134
+ function corpusReadFor(scope) {
135
+ const escaped = scope.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
136
+ const packagePath = new RegExp(`[/\\\\]node_modules[/\\\\]${escaped}[/\\\\]`);
137
+ const packagePattern = new RegExp(`(^|[/\\\\])node_modules[/\\\\]${escaped}([/\\\\]|$)`);
138
+ const examplesFile = /\.examples\.tsx?$/;
139
+ return (tool, input) => {
140
+ const file = typeof input["file_path"] === "string" ? input["file_path"] : "";
141
+ const dir = typeof input["path"] === "string" ? input["path"] : "";
142
+ const pattern = typeof input["pattern"] === "string" ? input["pattern"] : "";
143
+ return tool === "Read" ? packagePath.test(file) || examplesFile.test(file) : packagePath.test(dir) || packagePattern.test(pattern) || /\.examples\.tsx?/.test(pattern);
144
+ };
145
+ }
146
+ var GATE_TEXT = gateText(EAST_GUIDANCE);
147
+ var READ_TEXT = readText(EAST_GUIDANCE);
148
+ var isExampleCorpusRead = corpusReadFor(EAST_GUIDANCE.scope);
149
+
150
+ // ../east-plugin/dist/lib/codex-hook.js
151
+ function codexToolCall(event) {
152
+ const cwd = event.cwd || process.cwd();
153
+ const input = event.tool_input ?? {};
154
+ const command = typeof input.command === "string" ? input.command : typeof input["cmd"] === "string" ? input["cmd"] : "";
155
+ const tool = event.tool_name ?? "";
156
+ const patches = tool === "apply_patch" ? patchFiles(command, cwd) : [];
157
+ const shell = ["Bash", "exec_command", "shell_command"].includes(tool);
158
+ const filePath = typeof input.file_path === "string" ? resolve3(cwd, input.file_path) : void 0;
159
+ const paths = [.../* @__PURE__ */ new Set([
160
+ ...patches.filter((p) => !p.deleted).map((p) => p.path),
161
+ ...shell ? [...writtenPaths(command, cwd), ...shellReadPaths(command, cwd)] : [],
162
+ ...filePath ? [filePath] : []
163
+ ])];
164
+ return { tool, command, shell, patches, filePath, paths };
165
+ }
166
+ var EAST_CODEX_SEARCH_GATE = {
167
+ searchTools: SEARCH_TOOLS,
168
+ searchToolName: /__(?:search_east_examples|get_east_example)$/,
169
+ gateText: GATE_TEXT,
170
+ readText: READ_TEXT,
171
+ isCorpusRead: isExampleCorpusRead,
172
+ shellSweep: /node_modules\/@elaraai(?:\/|\b)|\.examples\.tsx?/,
173
+ corpusCode: /@elaraai\/east|(?:from|import)\s+east\b/,
174
+ markerPrefix: "east-codex-search-",
175
+ requireSearchEnv: "EAST_REQUIRE_SEARCH"
176
+ };
177
+ async function codexSearchGate(event, options, call = codexToolCall(event)) {
178
+ const input = event.tool_input ?? {};
179
+ const marker = join(tmpdir(), options.markerPrefix + createHash("sha256").update(event.session_id ?? "").digest("hex"));
180
+ if (event.hook_event_name === "PostToolUse") {
181
+ if (call.tool.startsWith("mcp__") && options.searchToolName.test(call.tool)) {
182
+ if (event.tool_response?.["isError"] !== true)
183
+ writeFileSync(marker, "searched");
184
+ return "recorded";
185
+ }
186
+ return null;
187
+ }
188
+ const context = [];
189
+ if (options.isCorpusRead(call.tool, input) || call.shell && options.shellSweep.test(call.command)) {
190
+ context.push(options.readText);
191
+ }
192
+ const writes = call.tool === "apply_patch" ? call.patches.filter((p) => !p.deleted) : call.shell ? writtenPaths(call.command, event.cwd || process.cwd()).map((path) => ({ path, originalPath: path, code: call.command })) : call.filePath && ["Edit", "Write"].includes(call.tool) ? [{ path: call.filePath, originalPath: call.filePath, code: input.content ?? input.new_string ?? "" }] : [];
193
+ let corpusWrite = false;
194
+ for (const file of writes) {
195
+ if (!/\.(tsx?|js|py)$/.test(file.path))
196
+ continue;
197
+ let old = "";
198
+ try {
199
+ old = await readFile2(file.originalPath, "utf8");
200
+ } catch {
201
+ }
202
+ if (options.corpusCode.test(old + "\n" + file.code))
203
+ corpusWrite = true;
204
+ }
205
+ if (corpusWrite && !existsSync(marker) && !(event.transcript_path && await searchedInTranscript(event.transcript_path, options.searchTools))) {
206
+ if (process.env[options.requireSearchEnv] === "deny")
207
+ return { decision: "deny", text: options.gateText };
208
+ context.push(options.gateText);
209
+ }
210
+ return context.length > 0 ? { decision: "context", text: context.join("\n\n") } : null;
211
+ }
212
+
213
+ // ../east-diagnostics/dist/src/python-lint.js
214
+ import { execFile } from "node:child_process";
215
+ import { existsSync as existsSync2, mkdtempSync, readFileSync, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
216
+ import { tmpdir as tmpdir2 } from "node:os";
217
+ import { basename, dirname, join as join2 } from "node:path";
218
+ var PYTHON_EAST_IMPORT = /^\s*(?:from\s+east(?:\.[\w.]+)?\s+import\b|import\s+east\b)/m;
219
+ function findEastPy(fromDir) {
220
+ const override = process.env["EAST_PY_LINT"];
221
+ if (override !== void 0 && override !== "")
222
+ return override;
223
+ let dir = fromDir;
224
+ for (; ; ) {
225
+ for (const candidate of [join2(dir, ".venv", "bin", "east-py"), join2(dir, ".venv", "Scripts", "east-py.exe")]) {
226
+ if (existsSync2(candidate))
227
+ return candidate;
228
+ }
229
+ const parent = dirname(dir);
230
+ if (parent === dir)
231
+ return "east-py";
232
+ dir = parent;
233
+ }
234
+ }
235
+ function runEastPyLint(file, content, budgetMs = 4e3, command = findEastPy(dirname(file))) {
236
+ let target = file;
237
+ let scratch = null;
238
+ if (content !== void 0) {
239
+ scratch = mkdtempSync(join2(tmpdir2(), "east-py-lint-"));
240
+ target = join2(scratch, basename(file));
241
+ writeFileSync2(target, content, "utf-8");
242
+ }
243
+ return new Promise((resolveFindings) => {
244
+ execFile(
245
+ command,
246
+ ["lint", "--format", "json", target],
247
+ // UTF-8 stdio: python encodes a piped stdout in the locale's code page on Windows (cp1252), and the findings carry em dashes
248
+ { timeout: budgetMs, encoding: "utf-8", maxBuffer: 4 * 1024 * 1024, env: { ...process.env, PYTHONIOENCODING: "utf-8" } },
249
+ (error, stdout) => {
250
+ if (scratch !== null)
251
+ rmSync(scratch, { recursive: true, force: true });
252
+ if (error !== null && error.code !== 1) {
253
+ resolveFindings(null);
254
+ return;
255
+ }
256
+ let records;
257
+ try {
258
+ records = JSON.parse(stdout);
259
+ } catch {
260
+ resolveFindings(null);
261
+ return;
262
+ }
263
+ resolveFindings(Array.isArray(records) ? records : null);
264
+ }
265
+ );
266
+ });
267
+ }
268
+ function runEastPyCheck(file, budgetMs = 8e3, command = findEastPy(dirname(file))) {
269
+ return new Promise((resolveFindings) => {
270
+ execFile(command, ["check", "--format", "json", "--only-if-enabled", file], { timeout: budgetMs, encoding: "utf-8", maxBuffer: 4 * 1024 * 1024, env: { ...process.env, PYTHONIOENCODING: "utf-8" } }, (error, stdout) => {
271
+ if (error !== null && error.code !== 1) {
272
+ resolveFindings(null);
273
+ return;
274
+ }
275
+ let records;
276
+ try {
277
+ records = JSON.parse(stdout);
278
+ } catch {
279
+ resolveFindings(null);
280
+ return;
281
+ }
282
+ resolveFindings(Array.isArray(records) ? records : null);
283
+ });
284
+ });
285
+ }
286
+ function renderPythonReview(records) {
287
+ if (records.length === 0)
288
+ return "";
289
+ const lines = records.map((r) => `- [${r.category}] ${r.line}:${r.column} (${r.rule}) ${r.message}`);
290
+ return ["<east-code-review>", "## East issues in this file", "", ...lines, "</east-code-review>"].join("\n");
291
+ }
292
+
293
+ // ../east-plugin/dist/lib/host.js
294
+ import { existsSync as existsSync3 } from "node:fs";
295
+ import { fileURLToPath } from "node:url";
296
+ var isCodex = existsSync3(fileURLToPath(new URL("../../.codex-plugin/plugin.json", import.meta.url)));
297
+ function hostText(text) {
298
+ return isCodex ? text.replaceAll("mcp__plugin_east_east__", "").replaceAll("/east:", "$east-codex-plugin:").replaceAll("Claude Code", "Codex") : text;
299
+ }
300
+
301
+ // ../east-plugin/dist/lib/hook-io.js
302
+ async function readHookInput() {
303
+ let input = "";
304
+ for await (const chunk of process.stdin) {
305
+ input += chunk;
306
+ }
307
+ return JSON.parse(input);
308
+ }
309
+ function writeHookOutput(hookEventName, additionalContext) {
310
+ const output = {
311
+ hookSpecificOutput: {
312
+ hookEventName,
313
+ additionalContext: hostText(additionalContext)
314
+ }
315
+ };
316
+ process.stdout.write(JSON.stringify(output));
317
+ }
318
+ function writeHookDecision(hookEventName, decision, reason) {
319
+ const output = {
320
+ hookSpecificOutput: {
321
+ hookEventName,
322
+ permissionDecision: decision,
323
+ permissionDecisionReason: hostText(reason)
324
+ }
325
+ };
326
+ process.stdout.write(JSON.stringify(output));
327
+ }
328
+
329
+ // ../east-plugin/dist/lib/east-project.js
330
+ import { readFile as readFile3 } from "node:fs/promises";
331
+ import { join as join3, dirname as dirname2 } from "node:path";
332
+ var PACKAGE_SKILL_MAP = {
333
+ "@elaraai/east": "east",
334
+ "@elaraai/east-node-std": "east-node-std",
335
+ "@elaraai/east-node-io": "east-node-io",
336
+ "@elaraai/east-py-datascience": "east-py-datascience",
337
+ "@elaraai/east-ui": "east-ui",
338
+ "@elaraai/e3": "e3",
339
+ "@elaraai/e3-ui": "e3-ui"
340
+ };
341
+ var PYTHON_SKILL_MAP = [
342
+ [/elaraai-east-py-datascience(?![\w-])/, "east-py-datascience"],
343
+ [/elaraai-east-py-std(?![\w-])/, "east-py-std"],
344
+ [/elaraai-east-py-io(?![\w-])/, "east-py-io"],
345
+ [/elaraai-east-py(?![\w-])/, "east-py"]
346
+ ];
347
+ async function findPackageJson(startDir) {
348
+ let dir = startDir;
349
+ while (true) {
350
+ try {
351
+ const content = await readFile3(join3(dir, "package.json"), "utf-8");
352
+ return JSON.parse(content);
353
+ } catch {
354
+ const parent = dirname2(dir);
355
+ if (parent === dir)
356
+ return null;
357
+ dir = parent;
358
+ }
359
+ }
360
+ }
361
+ async function findPyProject(startDir) {
362
+ let dir = startDir;
363
+ let nearest = null;
364
+ while (true) {
365
+ try {
366
+ const text = await readFile3(join3(dir, "pyproject.toml"), "utf-8");
367
+ if (PYTHON_SKILL_MAP.some(([pattern]) => pattern.test(text)))
368
+ return text;
369
+ nearest ??= text;
370
+ } catch {
371
+ }
372
+ const parent = dirname2(dir);
373
+ if (parent === dir)
374
+ return nearest;
375
+ dir = parent;
376
+ }
377
+ }
378
+ function detectEastSkills(pkg) {
379
+ if (!pkg)
380
+ return [];
381
+ const allDeps = {
382
+ ...pkg.dependencies,
383
+ ...pkg.devDependencies
384
+ };
385
+ const skills = [];
386
+ for (const [packageName, skillName] of Object.entries(PACKAGE_SKILL_MAP)) {
387
+ if (packageName in allDeps) {
388
+ skills.push(skillName);
389
+ }
390
+ }
391
+ return skills;
392
+ }
393
+ function detectPythonSkills(pyproject) {
394
+ if (pyproject === null)
395
+ return [];
396
+ const skills = [];
397
+ for (const [pattern, skill] of PYTHON_SKILL_MAP) {
398
+ if (pattern.test(pyproject))
399
+ skills.push(skill);
400
+ }
401
+ return skills;
402
+ }
403
+ async function getEastProjectInfo(cwd) {
404
+ const pkg = await findPackageJson(cwd);
405
+ const tsSkills = detectEastSkills(pkg);
406
+ const pySkills = detectPythonSkills(await findPyProject(cwd));
407
+ const languages = [];
408
+ if (tsSkills.length > 0)
409
+ languages.push("typescript");
410
+ if (pySkills.length > 0)
411
+ languages.push("python");
412
+ const skills = [...tsSkills, ...pySkills.filter((s) => !tsSkills.includes(s))];
413
+ return { isEast: skills.length > 0, skills, languages, pkg };
414
+ }
415
+
416
+ // ../east-plugin/dist/lib/search-hooks.js
417
+ function writeSearchHookReply(hookEventName, reply) {
418
+ if (reply.decision === "deny")
419
+ writeHookDecision(hookEventName, "deny", reply.text);
420
+ else
421
+ writeHookOutput(hookEventName, reply.text);
422
+ }
423
+
424
+ // ../east-plugin/dist/lib/review.js
425
+ import { readFile as readFile4 } from "node:fs/promises";
426
+ import { existsSync as existsSync5, writeFileSync as writeFileSync3 } from "node:fs";
427
+ import { createHash as createHash3 } from "node:crypto";
428
+ import { tmpdir as tmpdir4 } from "node:os";
429
+ import { join as join5, dirname as dirname4, resolve as resolve5 } from "node:path";
430
+
431
+ // ../east-plugin/dist/lib/diagnostics-client.js
432
+ import { createConnection } from "node:net";
433
+ import { spawn } from "node:child_process";
434
+ import { createHash as createHash2 } from "node:crypto";
435
+ import { tmpdir as tmpdir3 } from "node:os";
436
+ import { existsSync as existsSync4, unlinkSync } from "node:fs";
437
+ import { dirname as dirname3, join as join4, resolve as resolve4 } from "node:path";
438
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
439
+ function daemonSocket() {
440
+ const hash = createHash2("sha1").update(daemonEntry()).digest("hex").slice(0, 16);
441
+ return join4(tmpdir3(), `east-diag-${hash}.sock`);
442
+ }
443
+ function daemonEntry() {
444
+ return resolve4(dirname3(fileURLToPath2(import.meta.url)), "..", "daemon", "server.js");
445
+ }
446
+ function tryRequest(socketPath, file, timeoutMs) {
447
+ return new Promise((resolveResult) => {
448
+ const conn = createConnection(socketPath);
449
+ let buffer = "";
450
+ let settled = false;
451
+ const settle = (result) => {
452
+ if (settled)
453
+ return;
454
+ settled = true;
455
+ clearTimeout(timer);
456
+ conn.destroy();
457
+ resolveResult(result);
458
+ };
459
+ const timer = setTimeout(() => settle({ kind: "timeout" }), timeoutMs);
460
+ timer.unref();
461
+ conn.on("connect", () => conn.write(`${JSON.stringify({ file })}
462
+ `));
463
+ conn.on("data", (chunk) => {
464
+ buffer += chunk.toString("utf8");
465
+ const newline = buffer.indexOf("\n");
466
+ if (newline < 0)
467
+ return;
468
+ try {
469
+ const response = JSON.parse(buffer.slice(0, newline));
470
+ settle(response.ok === true ? { kind: "text", text: response.text ?? "" } : { kind: "error" });
471
+ } catch {
472
+ settle({ kind: "error" });
473
+ }
474
+ });
475
+ conn.on("error", (err) => {
476
+ settle(err.code === "ECONNREFUSED" || err.code === "ENOENT" ? { kind: "refused" } : { kind: "error" });
477
+ });
478
+ });
479
+ }
480
+ function spawnDaemon(socketPath, workspace) {
481
+ const entry = daemonEntry();
482
+ if (!existsSync4(entry))
483
+ return;
484
+ try {
485
+ spawn(process.execPath, [entry], {
486
+ detached: true,
487
+ stdio: "ignore",
488
+ env: { ...process.env, EAST_DIAG_SOCKET: socketPath, EAST_DIAG_CWD: workspace }
489
+ }).unref();
490
+ } catch {
491
+ }
492
+ }
493
+ async function getDiagnosticsText(workspace, file, budgetMs = 4e3) {
494
+ const socketPath = daemonSocket();
495
+ const deadline = Date.now() + budgetMs;
496
+ let spawned = false;
497
+ while (Date.now() < deadline) {
498
+ const attempt = await tryRequest(socketPath, file, Math.min(1500, deadline - Date.now()));
499
+ if (attempt.kind === "text")
500
+ return attempt.text;
501
+ if (attempt.kind === "refused" && !spawned) {
502
+ if (existsSync4(socketPath)) {
503
+ try {
504
+ unlinkSync(socketPath);
505
+ } catch {
506
+ }
507
+ }
508
+ spawnDaemon(socketPath, workspace);
509
+ spawned = true;
510
+ }
511
+ await new Promise((r) => setTimeout(r, 200));
512
+ }
513
+ return null;
514
+ }
515
+
516
+ // ../east-plugin/dist/lib/east-py-lint.js
517
+ async function getPythonDiagnosticsText(file, budgetMs = 4e3) {
518
+ const [rules, build] = await Promise.all([runEastPyLint(file, void 0, budgetMs), runEastPyCheck(file, budgetMs)]);
519
+ if (rules === null)
520
+ return null;
521
+ return renderPythonReview([...rules, ...build ?? []]);
522
+ }
523
+
524
+ // ../east-plugin/dist/lib/review.js
525
+ var EAST_IMPORT_PATTERN = /@elaraai\/east/;
526
+ var SKIP_PATH = /[/\\](node_modules|dist|build|\.venv|\.git)[/\\]/;
527
+ function reviewable(filePath) {
528
+ if (SKIP_PATH.test(filePath))
529
+ return false;
530
+ return /\.(py|ts|tsx|js)$/.test(filePath);
531
+ }
532
+ async function reviewFile(sessionId, filePath) {
533
+ if (!reviewable(filePath))
534
+ return null;
535
+ const python = filePath.endsWith(".py");
536
+ let content;
537
+ try {
538
+ content = await readFile4(filePath, "utf-8");
539
+ } catch {
540
+ return null;
541
+ }
542
+ if (!(python ? PYTHON_EAST_IMPORT : EAST_IMPORT_PATTERN).test(content))
543
+ return null;
544
+ const projectDir = dirname4(resolve5(filePath));
545
+ if (!python) {
546
+ const { isEast } = await getEastProjectInfo(projectDir);
547
+ if (!isEast)
548
+ return null;
549
+ }
550
+ const key = createHash3("sha1").update(`${sessionId}\0${filePath}\0`).update(content).digest("hex").slice(0, 20);
551
+ const marker = join5(tmpdir4(), `east-diag-seen-${key}`);
552
+ if (existsSync5(marker))
553
+ return null;
554
+ const text = python ? await getPythonDiagnosticsText(filePath) : await getDiagnosticsText(projectDir, filePath);
555
+ if (text === null)
556
+ return null;
557
+ try {
558
+ writeFileSync3(marker, "");
559
+ } catch {
560
+ }
561
+ return text;
562
+ }
563
+
564
+ // hooks/codex-tools.ts
565
+ async function main() {
566
+ const event = await readHookInput();
567
+ const call = codexToolCall(event);
568
+ const gate = await codexSearchGate(event, EAST_CODEX_SEARCH_GATE, call);
569
+ if (event.hook_event_name === "PostToolUse") {
570
+ if (gate === "recorded") return;
571
+ const reviews = await Promise.all(call.paths.map(async (path) => {
572
+ const text = await reviewFile(event.session_id, path);
573
+ return text ? `### ${path}
574
+ ${text}` : "";
575
+ }));
576
+ if (reviews.some(Boolean)) writeHookOutput("PostToolUse", reviews.filter(Boolean).join("\n\n"));
577
+ return;
578
+ }
579
+ if (gate !== null && gate !== "recorded") writeSearchHookReply("PreToolUse", gate);
580
+ }
581
+ main().catch((error) => {
582
+ process.stderr.write(`East hook: ${String(error)}
583
+ `);
584
+ });