@cybedefend/vibedefend 1.8.1 → 1.8.2
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.
- package/dist/auth/auth-store.js +37 -24
- package/dist/auth/auth-store.js.map +1 -1
- package/dist/auth/auth.js +30 -7
- package/dist/auth/auth.js.map +1 -1
- package/dist/auth/refresh-lock.js +139 -0
- package/dist/auth/refresh-lock.js.map +1 -0
- package/dist/diagnostics.js +0 -1
- package/dist/diagnostics.js.map +1 -1
- package/dist/hook-runner.js +524 -483
- package/dist/hooks/runtime/fetch-rules.js +1 -3
- package/dist/hooks/runtime/fetch-rules.js.map +1 -1
- package/dist/hooks/runtime/resolve.js +25 -243
- package/dist/hooks/runtime/resolve.js.map +1 -1
- package/dist/hooks/runtime/session-start.js +17 -5
- package/dist/hooks/runtime/session-start.js.map +1 -1
- package/dist/hooks/runtime/sign-in-notice.js +44 -0
- package/dist/hooks/runtime/sign-in-notice.js.map +1 -0
- package/dist/hooks/runtime/user-prompt-submit.js +3 -5
- package/dist/hooks/runtime/user-prompt-submit.js.map +1 -1
- package/dist/install.js +2 -6
- package/dist/install.js.map +1 -1
- package/dist/login.js +2 -3
- package/dist/login.js.map +1 -1
- package/dist/logout.js +2 -6
- package/dist/logout.js.map +1 -1
- package/package.json +2 -2
package/dist/hook-runner.js
CHANGED
|
@@ -5156,9 +5156,7 @@ function extractToolInputShape(input2, client) {
|
|
|
5156
5156
|
}
|
|
5157
5157
|
|
|
5158
5158
|
// src/hooks/runtime/resolve.ts
|
|
5159
|
-
import {
|
|
5160
|
-
import { createHash } from "node:crypto";
|
|
5161
|
-
import { existsSync as existsSync6, readFileSync as readFileSync6 } from "node:fs";
|
|
5159
|
+
import { existsSync as existsSync6, readFileSync as readFileSync7 } from "node:fs";
|
|
5162
5160
|
|
|
5163
5161
|
// src/auth/auth-store.ts
|
|
5164
5162
|
import { execFileSync } from "node:child_process";
|
|
@@ -5192,11 +5190,13 @@ function storeAuth(mcpName, auth) {
|
|
|
5192
5190
|
storeFileFallback(mcpName, auth);
|
|
5193
5191
|
}
|
|
5194
5192
|
function loadAuth(mcpName) {
|
|
5195
|
-
|
|
5196
|
-
if (process.platform
|
|
5197
|
-
|
|
5198
|
-
|
|
5199
|
-
|
|
5193
|
+
const fromFile = parseBundle(readFileFallback(mcpName));
|
|
5194
|
+
if (process.platform !== "darwin") return fromFile;
|
|
5195
|
+
const fromKeychain = parseBundle(readMacOSKeychain(mcpName));
|
|
5196
|
+
if (!fromKeychain) return fromFile;
|
|
5197
|
+
return fromFile && isSameSignIn(fromFile, fromKeychain) && fromFile.expiresAt > fromKeychain.expiresAt ? fromFile : fromKeychain;
|
|
5198
|
+
}
|
|
5199
|
+
function parseBundle(blob) {
|
|
5200
5200
|
if (!blob) return null;
|
|
5201
5201
|
try {
|
|
5202
5202
|
const parsed = JSON.parse(blob);
|
|
@@ -5208,6 +5208,9 @@ function loadAuth(mcpName) {
|
|
|
5208
5208
|
return null;
|
|
5209
5209
|
}
|
|
5210
5210
|
}
|
|
5211
|
+
function isSameSignIn(a, b) {
|
|
5212
|
+
return a.logtoEndpoint === b.logtoEndpoint && a.cliAppId === b.cliAppId && a.logtoResource === b.logtoResource;
|
|
5213
|
+
}
|
|
5211
5214
|
function clearAuth(mcpName) {
|
|
5212
5215
|
if (process.platform === "darwin") {
|
|
5213
5216
|
try {
|
|
@@ -5228,24 +5231,11 @@ function clearAuth(mcpName) {
|
|
|
5228
5231
|
removeFileFallback(mcpName);
|
|
5229
5232
|
}
|
|
5230
5233
|
function storeMacOSKeychain(mcpName, blob) {
|
|
5231
|
-
try {
|
|
5232
|
-
execFileSync(
|
|
5233
|
-
"security",
|
|
5234
|
-
[
|
|
5235
|
-
"delete-generic-password",
|
|
5236
|
-
"-s",
|
|
5237
|
-
KEYCHAIN_SERVICE,
|
|
5238
|
-
"-a",
|
|
5239
|
-
accountFor(mcpName)
|
|
5240
|
-
],
|
|
5241
|
-
{ stdio: "ignore" }
|
|
5242
|
-
);
|
|
5243
|
-
} catch {
|
|
5244
|
-
}
|
|
5245
5234
|
execFileSync(
|
|
5246
5235
|
"security",
|
|
5247
5236
|
[
|
|
5248
5237
|
"add-generic-password",
|
|
5238
|
+
"-U",
|
|
5249
5239
|
"-s",
|
|
5250
5240
|
KEYCHAIN_SERVICE,
|
|
5251
5241
|
"-a",
|
|
@@ -5253,7 +5243,10 @@ function storeMacOSKeychain(mcpName, blob) {
|
|
|
5253
5243
|
"-w",
|
|
5254
5244
|
blob
|
|
5255
5245
|
],
|
|
5256
|
-
|
|
5246
|
+
// A keychain whose dialog nobody answers hangs every client. Logto has
|
|
5247
|
+
// already consumed the previous refresh token: past this, the renewed
|
|
5248
|
+
// bundle goes to the file rather than wait with the hook.
|
|
5249
|
+
{ stdio: "ignore", timeout: 3e3 }
|
|
5257
5250
|
);
|
|
5258
5251
|
}
|
|
5259
5252
|
function readMacOSKeychain(mcpName) {
|
|
@@ -5348,6 +5341,110 @@ function removeFileFallback(mcpName, replacedBy) {
|
|
|
5348
5341
|
}
|
|
5349
5342
|
}
|
|
5350
5343
|
|
|
5344
|
+
// src/auth/refresh-lock.ts
|
|
5345
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
5346
|
+
import {
|
|
5347
|
+
closeSync,
|
|
5348
|
+
mkdirSync as mkdirSync2,
|
|
5349
|
+
openSync,
|
|
5350
|
+
readFileSync as readFileSync2,
|
|
5351
|
+
statSync,
|
|
5352
|
+
unlinkSync,
|
|
5353
|
+
writeSync
|
|
5354
|
+
} from "node:fs";
|
|
5355
|
+
import { homedir as homedir3 } from "node:os";
|
|
5356
|
+
import { dirname, join as join2 } from "node:path";
|
|
5357
|
+
var WAIT_MS = 5e3;
|
|
5358
|
+
var POLL_MS = 50;
|
|
5359
|
+
var STALE_AFTER_MS = 3e4;
|
|
5360
|
+
var RefreshLockBusyError = class extends Error {
|
|
5361
|
+
constructor() {
|
|
5362
|
+
super("Another process is refreshing the token.");
|
|
5363
|
+
this.name = "RefreshLockBusyError";
|
|
5364
|
+
}
|
|
5365
|
+
};
|
|
5366
|
+
function refreshLockPath(mcpName) {
|
|
5367
|
+
const digest = createHash("sha256").update(mcpName).digest("hex").slice(0, 16);
|
|
5368
|
+
return join2(homedir3(), ".cybedefend", `refresh-${digest}.lock`);
|
|
5369
|
+
}
|
|
5370
|
+
async function withRefreshLock(mcpName, body, options = {}) {
|
|
5371
|
+
const path = refreshLockPath(mcpName);
|
|
5372
|
+
const deadline = Date.now() + (options.waitMs ?? WAIT_MS);
|
|
5373
|
+
for (; ; ) {
|
|
5374
|
+
const attempt = tryAcquire(path);
|
|
5375
|
+
if (attempt === "unavailable") return body();
|
|
5376
|
+
if (attempt !== "held") {
|
|
5377
|
+
try {
|
|
5378
|
+
return await body();
|
|
5379
|
+
} finally {
|
|
5380
|
+
release(path, attempt);
|
|
5381
|
+
}
|
|
5382
|
+
}
|
|
5383
|
+
if (isAbandoned(path)) {
|
|
5384
|
+
removeQuietly(path);
|
|
5385
|
+
continue;
|
|
5386
|
+
}
|
|
5387
|
+
if (Date.now() >= deadline) throw new RefreshLockBusyError();
|
|
5388
|
+
await new Promise((resolve2) => setTimeout(resolve2, options.pollMs ?? POLL_MS));
|
|
5389
|
+
}
|
|
5390
|
+
}
|
|
5391
|
+
function tryAcquire(path) {
|
|
5392
|
+
let handle;
|
|
5393
|
+
try {
|
|
5394
|
+
mkdirSync2(dirname(path), { recursive: true });
|
|
5395
|
+
} catch {
|
|
5396
|
+
return "unavailable";
|
|
5397
|
+
}
|
|
5398
|
+
try {
|
|
5399
|
+
handle = openSync(path, "wx", 384);
|
|
5400
|
+
} catch (e) {
|
|
5401
|
+
return e.code === "EEXIST" ? "held" : "unavailable";
|
|
5402
|
+
}
|
|
5403
|
+
const token = randomUUID();
|
|
5404
|
+
try {
|
|
5405
|
+
writeSync(handle, JSON.stringify({ pid: process.pid, token }));
|
|
5406
|
+
} catch {
|
|
5407
|
+
} finally {
|
|
5408
|
+
closeSync(handle);
|
|
5409
|
+
}
|
|
5410
|
+
return token;
|
|
5411
|
+
}
|
|
5412
|
+
function isAbandoned(path) {
|
|
5413
|
+
let age;
|
|
5414
|
+
try {
|
|
5415
|
+
age = Date.now() - statSync(path).mtimeMs;
|
|
5416
|
+
} catch {
|
|
5417
|
+
return false;
|
|
5418
|
+
}
|
|
5419
|
+
if (age >= STALE_AFTER_MS) return true;
|
|
5420
|
+
const pid = holder(path)?.pid;
|
|
5421
|
+
return typeof pid === "number" && !isAlive(pid);
|
|
5422
|
+
}
|
|
5423
|
+
function holder(path) {
|
|
5424
|
+
try {
|
|
5425
|
+
return JSON.parse(readFileSync2(path, "utf8"));
|
|
5426
|
+
} catch {
|
|
5427
|
+
return null;
|
|
5428
|
+
}
|
|
5429
|
+
}
|
|
5430
|
+
function isAlive(pid) {
|
|
5431
|
+
try {
|
|
5432
|
+
process.kill(pid, 0);
|
|
5433
|
+
return true;
|
|
5434
|
+
} catch (e) {
|
|
5435
|
+
return e.code !== "ESRCH";
|
|
5436
|
+
}
|
|
5437
|
+
}
|
|
5438
|
+
function release(path, token) {
|
|
5439
|
+
if (holder(path)?.token === token) removeQuietly(path);
|
|
5440
|
+
}
|
|
5441
|
+
function removeQuietly(path) {
|
|
5442
|
+
try {
|
|
5443
|
+
unlinkSync(path);
|
|
5444
|
+
} catch {
|
|
5445
|
+
}
|
|
5446
|
+
}
|
|
5447
|
+
|
|
5351
5448
|
// src/auth/token-exchange.ts
|
|
5352
5449
|
var RefreshTokenInvalidError = class extends Error {
|
|
5353
5450
|
constructor(msg) {
|
|
@@ -5406,12 +5503,28 @@ async function getValidAccessToken(mcpName) {
|
|
|
5406
5503
|
);
|
|
5407
5504
|
}
|
|
5408
5505
|
if (!inFlightRefresh) {
|
|
5409
|
-
inFlightRefresh =
|
|
5506
|
+
inFlightRefresh = refreshUnderLock(mcpName).finally(() => {
|
|
5410
5507
|
inFlightRefresh = null;
|
|
5411
5508
|
});
|
|
5412
5509
|
}
|
|
5413
5510
|
return await inFlightRefresh;
|
|
5414
5511
|
}
|
|
5512
|
+
function hasUsableStoredAuth(mcpName, now = Date.now()) {
|
|
5513
|
+
const stored = loadAuth(mcpName);
|
|
5514
|
+
if (!stored) return false;
|
|
5515
|
+
if (stored.refreshToken) return true;
|
|
5516
|
+
return typeof stored.expiresAt === "number" && stored.expiresAt > now;
|
|
5517
|
+
}
|
|
5518
|
+
function refreshUnderLock(mcpName) {
|
|
5519
|
+
return withRefreshLock(mcpName, async () => {
|
|
5520
|
+
const current = loadAuth(mcpName);
|
|
5521
|
+
if (!current) {
|
|
5522
|
+
throw new LoginRequiredError("No stored credentials. Run `vibedefend login`.");
|
|
5523
|
+
}
|
|
5524
|
+
if (Date.now() < current.expiresAt) return current.accessToken;
|
|
5525
|
+
return doRefresh(mcpName, current);
|
|
5526
|
+
});
|
|
5527
|
+
}
|
|
5415
5528
|
async function doRefresh(mcpName, stored) {
|
|
5416
5529
|
if (!stored.refreshToken) {
|
|
5417
5530
|
throw new LoginRequiredError("No refresh_token available; re-login required.");
|
|
@@ -5436,6 +5549,11 @@ async function doRefresh(mcpName, stored) {
|
|
|
5436
5549
|
return updated.accessToken;
|
|
5437
5550
|
} catch (e) {
|
|
5438
5551
|
if (e instanceof RefreshTokenInvalidError) {
|
|
5552
|
+
const latest = loadAuth(mcpName);
|
|
5553
|
+
if (latest && latest.refreshToken !== stored.refreshToken) {
|
|
5554
|
+
if (Date.now() < latest.expiresAt) return latest.accessToken;
|
|
5555
|
+
throw e;
|
|
5556
|
+
}
|
|
5439
5557
|
clearAuth(mcpName);
|
|
5440
5558
|
throw new LoginRequiredError(
|
|
5441
5559
|
"Your session has expired. Run `vibedefend login` to re-authenticate."
|
|
@@ -5550,13 +5668,13 @@ async function resolveProjectByRepository(apiBase, token, q, deps = {}) {
|
|
|
5550
5668
|
}
|
|
5551
5669
|
|
|
5552
5670
|
// src/hooks/runtime/repo-link-cache.ts
|
|
5553
|
-
import { existsSync as existsSync3, mkdirSync as
|
|
5554
|
-
import { dirname as
|
|
5671
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "node:fs";
|
|
5672
|
+
import { dirname as dirname3 } from "node:path";
|
|
5555
5673
|
|
|
5556
5674
|
// src/utils.ts
|
|
5557
|
-
import { existsSync as existsSync2, mkdirSync as
|
|
5558
|
-
import { dirname, join as
|
|
5559
|
-
import { homedir as
|
|
5675
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
|
|
5676
|
+
import { dirname as dirname2, join as join3 } from "node:path";
|
|
5677
|
+
import { homedir as homedir4, platform } from "node:os";
|
|
5560
5678
|
|
|
5561
5679
|
// node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/index.mjs
|
|
5562
5680
|
var FORCE_COLOR;
|
|
@@ -5659,11 +5777,11 @@ function init(open2, close) {
|
|
|
5659
5777
|
|
|
5660
5778
|
// src/utils.ts
|
|
5661
5779
|
function home(...parts) {
|
|
5662
|
-
return
|
|
5780
|
+
return join3(homedir4(), ...parts);
|
|
5663
5781
|
}
|
|
5664
5782
|
function ensureDirFor(filePath) {
|
|
5665
|
-
const dir =
|
|
5666
|
-
if (!existsSync2(dir))
|
|
5783
|
+
const dir = dirname2(filePath);
|
|
5784
|
+
if (!existsSync2(dir)) mkdirSync3(dir, { recursive: true });
|
|
5667
5785
|
}
|
|
5668
5786
|
|
|
5669
5787
|
// src/hooks/runtime/repo-link-cache.ts
|
|
@@ -5679,7 +5797,7 @@ function readRepoLinkCache(deps = {}) {
|
|
|
5679
5797
|
const p = pathOf(deps);
|
|
5680
5798
|
if (!existsSync3(p)) return {};
|
|
5681
5799
|
try {
|
|
5682
|
-
const raw =
|
|
5800
|
+
const raw = readFileSync4(p, "utf8");
|
|
5683
5801
|
if (!raw.trim()) return {};
|
|
5684
5802
|
const parsed = JSON.parse(raw);
|
|
5685
5803
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
@@ -5725,25 +5843,25 @@ function writeCachedRepoLink(key, entry, deps = {}) {
|
|
|
5725
5843
|
resolvedAt: now()
|
|
5726
5844
|
};
|
|
5727
5845
|
const p = pathOf(deps);
|
|
5728
|
-
const dir =
|
|
5729
|
-
if (!existsSync3(dir))
|
|
5846
|
+
const dir = dirname3(p);
|
|
5847
|
+
if (!existsSync3(dir)) mkdirSync4(dir, { recursive: true });
|
|
5730
5848
|
writeFileSync3(p, JSON.stringify(map2, null, 2) + "\n");
|
|
5731
5849
|
} catch {
|
|
5732
5850
|
}
|
|
5733
5851
|
}
|
|
5734
5852
|
|
|
5735
5853
|
// src/hooks/runtime/config.ts
|
|
5736
|
-
import { existsSync as existsSync4, readFileSync as
|
|
5737
|
-
import { homedir as
|
|
5738
|
-
import { join as
|
|
5854
|
+
import { existsSync as existsSync4, readFileSync as readFileSync5 } from "node:fs";
|
|
5855
|
+
import { homedir as homedir5 } from "node:os";
|
|
5856
|
+
import { join as join4 } from "node:path";
|
|
5739
5857
|
function runtimeConfigPath() {
|
|
5740
|
-
return
|
|
5858
|
+
return join4(homedir5(), ".cybedefend", "runtime-config.json");
|
|
5741
5859
|
}
|
|
5742
5860
|
function loadRuntimeConfig(path) {
|
|
5743
5861
|
const p = path ?? runtimeConfigPath();
|
|
5744
5862
|
if (!existsSync4(p)) return null;
|
|
5745
5863
|
try {
|
|
5746
|
-
const raw =
|
|
5864
|
+
const raw = readFileSync5(p, "utf8");
|
|
5747
5865
|
return JSON.parse(raw);
|
|
5748
5866
|
} catch {
|
|
5749
5867
|
return null;
|
|
@@ -5765,9 +5883,9 @@ async function readStdinJson() {
|
|
|
5765
5883
|
}
|
|
5766
5884
|
|
|
5767
5885
|
// src/hooks/runtime/trusted-api-base.ts
|
|
5768
|
-
import { existsSync as existsSync5, readFileSync as
|
|
5769
|
-
import { homedir as
|
|
5770
|
-
import { join as
|
|
5886
|
+
import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
|
|
5887
|
+
import { homedir as homedir6 } from "node:os";
|
|
5888
|
+
import { join as join5 } from "node:path";
|
|
5771
5889
|
|
|
5772
5890
|
// src/config.ts
|
|
5773
5891
|
var REGIONS = [
|
|
@@ -5795,7 +5913,7 @@ var REGIONS = [
|
|
|
5795
5913
|
|
|
5796
5914
|
// src/hooks/runtime/trusted-api-base.ts
|
|
5797
5915
|
function userRegionsPath() {
|
|
5798
|
-
return
|
|
5916
|
+
return join5(homedir6(), ".cybedefend", "regions.json");
|
|
5799
5917
|
}
|
|
5800
5918
|
function normalizeOrigin(candidate) {
|
|
5801
5919
|
if (typeof candidate !== "string") return null;
|
|
@@ -5814,7 +5932,7 @@ function normalizeOrigin(candidate) {
|
|
|
5814
5932
|
function readUserRegionApiBases(path) {
|
|
5815
5933
|
try {
|
|
5816
5934
|
if (!existsSync5(path)) return [];
|
|
5817
|
-
const parsed = JSON.parse(
|
|
5935
|
+
const parsed = JSON.parse(readFileSync6(path, "utf8"));
|
|
5818
5936
|
if (!Array.isArray(parsed)) return [];
|
|
5819
5937
|
return parsed.map(
|
|
5820
5938
|
(entry) => entry && typeof entry === "object" ? entry.apiBase : null
|
|
@@ -5883,7 +6001,7 @@ function resolveProjectId(cwd = process.cwd(), deps = {}) {
|
|
|
5883
6001
|
const configPath = `${cwd}/.cybedefend/config.json`;
|
|
5884
6002
|
if (existsSync6(configPath)) {
|
|
5885
6003
|
try {
|
|
5886
|
-
const raw =
|
|
6004
|
+
const raw = readFileSync7(configPath, "utf8");
|
|
5887
6005
|
const cfg = JSON.parse(raw);
|
|
5888
6006
|
return {
|
|
5889
6007
|
projectId: cfg.projectId ?? null,
|
|
@@ -5898,119 +6016,9 @@ function resolveToken(mcpName, opts = {}) {
|
|
|
5898
6016
|
const envToken = process.env.CYBEDEFEND_TOKEN;
|
|
5899
6017
|
if (envToken && envToken.length > 0) return envToken;
|
|
5900
6018
|
const stored = (opts.loadStoredAuth ?? loadAuth)(mcpName);
|
|
5901
|
-
|
|
5902
|
-
return stored.accessToken;
|
|
5903
|
-
}
|
|
5904
|
-
const platform2 = opts.platform ?? process.platform;
|
|
5905
|
-
const readKeychain = opts.readKeychain ?? readMacOSKeychain2;
|
|
5906
|
-
if (platform2 === "darwin") {
|
|
5907
|
-
const now = (opts.now ?? Date.now)();
|
|
5908
|
-
return resolveTokenMacOS(mcpName, opts.mcpUrl, readKeychain, now) ?? resolveTokenCodexMacOS(mcpName, opts.mcpUrl, readKeychain, now);
|
|
5909
|
-
}
|
|
5910
|
-
if (platform2 === "linux") return resolveTokenLinux(mcpName);
|
|
5911
|
-
return null;
|
|
6019
|
+
return stored && (opts.now ?? Date.now)() < stored.expiresAt ? stored.accessToken : null;
|
|
5912
6020
|
}
|
|
5913
|
-
function
|
|
5914
|
-
const digest = createHash("sha256").update(JSON.stringify({ type: "http", url: mcpUrl, headers: {} })).digest("hex");
|
|
5915
|
-
return `${mcpName}|${digest.slice(0, 16)}`;
|
|
5916
|
-
}
|
|
5917
|
-
function isExpired(expiresAt, now) {
|
|
5918
|
-
if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt) || expiresAt <= 0) {
|
|
5919
|
-
return false;
|
|
5920
|
-
}
|
|
5921
|
-
const expiresAtMs = expiresAt < 1e11 ? expiresAt * 1e3 : expiresAt;
|
|
5922
|
-
return now >= expiresAtMs;
|
|
5923
|
-
}
|
|
5924
|
-
function readMacOSKeychain2(service, account) {
|
|
5925
|
-
try {
|
|
5926
|
-
const blob = execFileSync2(
|
|
5927
|
-
"security",
|
|
5928
|
-
[
|
|
5929
|
-
"find-generic-password",
|
|
5930
|
-
"-s",
|
|
5931
|
-
service,
|
|
5932
|
-
...account === void 0 ? [] : ["-a", account],
|
|
5933
|
-
"-w"
|
|
5934
|
-
],
|
|
5935
|
-
{
|
|
5936
|
-
encoding: "utf8",
|
|
5937
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
5938
|
-
timeout: 2e3
|
|
5939
|
-
}
|
|
5940
|
-
).trim();
|
|
5941
|
-
return blob.length > 0 ? blob : null;
|
|
5942
|
-
} catch {
|
|
5943
|
-
return null;
|
|
5944
|
-
}
|
|
5945
|
-
}
|
|
5946
|
-
function resolveTokenMacOS(mcpName, mcpUrl, readKeychain, now) {
|
|
5947
|
-
const blob = readKeychain("Claude Code-credentials");
|
|
5948
|
-
if (!blob) return null;
|
|
5949
|
-
try {
|
|
5950
|
-
const data = JSON.parse(blob);
|
|
5951
|
-
const oauth = data.mcpOAuth ?? {};
|
|
5952
|
-
for (const entry of Object.values(oauth)) {
|
|
5953
|
-
if (entry?.serverName !== mcpName || !entry.accessToken) continue;
|
|
5954
|
-
if (mcpUrl && typeof entry.serverUrl === "string" && entry.serverUrl !== mcpUrl) {
|
|
5955
|
-
continue;
|
|
5956
|
-
}
|
|
5957
|
-
if (isExpired(entry.expiresAt, now)) {
|
|
5958
|
-
continue;
|
|
5959
|
-
}
|
|
5960
|
-
return entry.accessToken;
|
|
5961
|
-
}
|
|
5962
|
-
} catch {
|
|
5963
|
-
return blob || null;
|
|
5964
|
-
}
|
|
5965
|
-
return null;
|
|
5966
|
-
}
|
|
5967
|
-
function resolveTokenCodexMacOS(mcpName, mcpUrl, readKeychain, now) {
|
|
5968
|
-
const accounts = mcpUrl ? [codexCredentialAccount(mcpName, mcpUrl), mcpName] : [mcpName];
|
|
5969
|
-
for (const account of accounts) {
|
|
5970
|
-
const blob = readKeychain("Codex MCP Credentials", account);
|
|
5971
|
-
if (!blob) continue;
|
|
5972
|
-
const token = parseCodexCredential(blob, now);
|
|
5973
|
-
if (token) return token;
|
|
5974
|
-
}
|
|
5975
|
-
return null;
|
|
5976
|
-
}
|
|
5977
|
-
function parseCodexCredential(blob, now) {
|
|
5978
|
-
try {
|
|
5979
|
-
const data = JSON.parse(blob);
|
|
5980
|
-
if (isExpired(data.expires_at ?? data.expiresAt, now)) return null;
|
|
5981
|
-
return data.token_response?.access_token ?? data.access_token ?? data.accessToken ?? data.token ?? null;
|
|
5982
|
-
} catch {
|
|
5983
|
-
return blob || null;
|
|
5984
|
-
}
|
|
5985
|
-
}
|
|
5986
|
-
function resolveTokenLinux(mcpName) {
|
|
5987
|
-
try {
|
|
5988
|
-
const token = execFileSync2(
|
|
5989
|
-
"secret-tool",
|
|
5990
|
-
["lookup", "service", "Claude-Code", "account", mcpName],
|
|
5991
|
-
{
|
|
5992
|
-
encoding: "utf8",
|
|
5993
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
5994
|
-
timeout: 2e3
|
|
5995
|
-
}
|
|
5996
|
-
).trim();
|
|
5997
|
-
return token.length > 0 ? token : null;
|
|
5998
|
-
} catch {
|
|
5999
|
-
return null;
|
|
6000
|
-
}
|
|
6001
|
-
}
|
|
6002
|
-
function isExpiredJwt(token) {
|
|
6003
|
-
const payload = token.split(".")[1];
|
|
6004
|
-
if (!payload) return false;
|
|
6005
|
-
try {
|
|
6006
|
-
const json2 = Buffer.from(payload, "base64url").toString("utf8");
|
|
6007
|
-
const exp = JSON.parse(json2).exp;
|
|
6008
|
-
return typeof exp === "number" && exp * 1e3 <= Date.now();
|
|
6009
|
-
} catch {
|
|
6010
|
-
return false;
|
|
6011
|
-
}
|
|
6012
|
-
}
|
|
6013
|
-
async function resolveTokenWithRefresh(mcpName, deps = {}, opts = {}) {
|
|
6021
|
+
async function resolveTokenWithRefresh(mcpName, deps = {}) {
|
|
6014
6022
|
const getValidAccessTokenFn = deps.getValidAccessToken ?? getValidAccessToken;
|
|
6015
6023
|
const resolveTokenFn = deps.resolveTokenFn ?? resolveToken;
|
|
6016
6024
|
const envToken = process.env.CYBEDEFEND_TOKEN;
|
|
@@ -6019,19 +6027,9 @@ async function resolveTokenWithRefresh(mcpName, deps = {}, opts = {}) {
|
|
|
6019
6027
|
const token = await getValidAccessTokenFn(mcpName);
|
|
6020
6028
|
if (token) return token;
|
|
6021
6029
|
} catch (e) {
|
|
6022
|
-
if (e instanceof LoginRequiredError)
|
|
6023
|
-
return resolveTokenFn(mcpName, opts);
|
|
6024
|
-
}
|
|
6025
|
-
}
|
|
6026
|
-
const legacy = resolveTokenFn(mcpName, opts);
|
|
6027
|
-
if (legacy && isExpiredJwt(legacy)) {
|
|
6028
|
-
process.stderr.write(
|
|
6029
|
-
`[vibedefend] the stored credential for "${mcpName}" has expired and cannot be refreshed (no refresh token in the legacy store). Run \`vibedefend login\`.
|
|
6030
|
-
`
|
|
6031
|
-
);
|
|
6032
|
-
return null;
|
|
6030
|
+
if (e instanceof LoginRequiredError) return null;
|
|
6033
6031
|
}
|
|
6034
|
-
return
|
|
6032
|
+
return resolveTokenFn(mcpName);
|
|
6035
6033
|
}
|
|
6036
6034
|
var RESOLVE_API_TIMEOUT_MS = 4e3;
|
|
6037
6035
|
function resolveActivationMode(config2) {
|
|
@@ -6100,9 +6098,9 @@ async function resolveProjectIdWithApi(cwd = process.cwd(), deps = {}) {
|
|
|
6100
6098
|
}
|
|
6101
6099
|
|
|
6102
6100
|
// src/hooks/runtime/usage-block.ts
|
|
6103
|
-
import { existsSync as existsSync7, mkdirSync as
|
|
6104
|
-
import { homedir as
|
|
6105
|
-
import { dirname as
|
|
6101
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "node:fs";
|
|
6102
|
+
import { homedir as homedir7 } from "node:os";
|
|
6103
|
+
import { dirname as dirname4, join as join6 } from "node:path";
|
|
6106
6104
|
var BLOCKED_CODE = "VIBEDEFEND_BLOCKED";
|
|
6107
6105
|
var USAGE_WARNING_HEADER = "x-vibedefend-usage-warning";
|
|
6108
6106
|
var UNITS = ["injection", "judgment", "diff_scan"];
|
|
@@ -6199,8 +6197,8 @@ function blockKey(block) {
|
|
|
6199
6197
|
}
|
|
6200
6198
|
var NOTICES_CAP = 300;
|
|
6201
6199
|
function defaultUsageNoticesFile() {
|
|
6202
|
-
const dir = process.env.CYBEDEFEND_BASELINE_DIR ??
|
|
6203
|
-
return
|
|
6200
|
+
const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join6(homedir7(), ".cybedefend");
|
|
6201
|
+
return join6(dir, "usage-notices-sessions.json");
|
|
6204
6202
|
}
|
|
6205
6203
|
function makeUsageNotifier(opts = {}) {
|
|
6206
6204
|
const file2 = opts.file ?? defaultUsageNoticesFile();
|
|
@@ -6213,7 +6211,7 @@ function makeUsageNotifier(opts = {}) {
|
|
|
6213
6211
|
function load2() {
|
|
6214
6212
|
try {
|
|
6215
6213
|
if (!existsSync7(file2)) return [];
|
|
6216
|
-
const data = JSON.parse(
|
|
6214
|
+
const data = JSON.parse(readFileSync8(file2, "utf8"));
|
|
6217
6215
|
return Array.isArray(data.seen) ? data.seen.filter((s) => typeof s === "string") : [];
|
|
6218
6216
|
} catch {
|
|
6219
6217
|
return [];
|
|
@@ -6225,7 +6223,7 @@ function makeUsageNotifier(opts = {}) {
|
|
|
6225
6223
|
const seen = load2();
|
|
6226
6224
|
if (seen.includes(marker)) return null;
|
|
6227
6225
|
try {
|
|
6228
|
-
|
|
6226
|
+
mkdirSync5(dirname4(file2), { recursive: true });
|
|
6229
6227
|
writeFileSync4(
|
|
6230
6228
|
file2,
|
|
6231
6229
|
JSON.stringify({ seen: [...seen, marker].slice(-NOTICES_CAP) }),
|
|
@@ -6359,13 +6357,13 @@ async function fetchProposalsCount(opts) {
|
|
|
6359
6357
|
}
|
|
6360
6358
|
|
|
6361
6359
|
// src/hooks/runtime/session-activation.ts
|
|
6362
|
-
import { existsSync as existsSync8, mkdirSync as
|
|
6363
|
-
import { homedir as
|
|
6364
|
-
import { dirname as
|
|
6360
|
+
import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "node:fs";
|
|
6361
|
+
import { homedir as homedir8 } from "node:os";
|
|
6362
|
+
import { dirname as dirname5, isAbsolute as isAbsolute2, join as join7, resolve as resolvePath2 } from "node:path";
|
|
6365
6363
|
import { fileURLToPath } from "node:url";
|
|
6366
6364
|
|
|
6367
6365
|
// src/hooks/runtime/emit.ts
|
|
6368
|
-
import { writeSync } from "node:fs";
|
|
6366
|
+
import { writeSync as writeSync2 } from "node:fs";
|
|
6369
6367
|
var ENVELOPE_CLIENTS = {
|
|
6370
6368
|
SessionStart: /* @__PURE__ */ new Set(["codex"]),
|
|
6371
6369
|
PreToolUse: /* @__PURE__ */ new Set(["claude-code", "codex", "vscode"]),
|
|
@@ -6391,7 +6389,7 @@ function writeStdoutSync(text) {
|
|
|
6391
6389
|
while (offset < buf.length) {
|
|
6392
6390
|
let written = 0;
|
|
6393
6391
|
try {
|
|
6394
|
-
written =
|
|
6392
|
+
written = writeSync2(1, buf, offset, buf.length - offset);
|
|
6395
6393
|
} catch (e) {
|
|
6396
6394
|
if (e?.code !== "EAGAIN") return;
|
|
6397
6395
|
}
|
|
@@ -6529,14 +6527,14 @@ function isSettledReason(reason) {
|
|
|
6529
6527
|
}
|
|
6530
6528
|
var SESSIONS_CAP = 200;
|
|
6531
6529
|
function defaultStoreFile() {
|
|
6532
|
-
const dir = process.env.CYBEDEFEND_BASELINE_DIR ??
|
|
6533
|
-
return
|
|
6530
|
+
const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join7(homedir8(), ".cybedefend");
|
|
6531
|
+
return join7(dir, "inactive-sessions.json");
|
|
6534
6532
|
}
|
|
6535
6533
|
function defaultInactiveSessionStore(file2 = defaultStoreFile(), now = Date.now) {
|
|
6536
6534
|
function load2() {
|
|
6537
6535
|
if (!existsSync8(file2)) return {};
|
|
6538
6536
|
try {
|
|
6539
|
-
const parsed = JSON.parse(
|
|
6537
|
+
const parsed = JSON.parse(readFileSync9(file2, "utf8"));
|
|
6540
6538
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
6541
6539
|
} catch {
|
|
6542
6540
|
return {};
|
|
@@ -6544,7 +6542,7 @@ function defaultInactiveSessionStore(file2 = defaultStoreFile(), now = Date.now)
|
|
|
6544
6542
|
}
|
|
6545
6543
|
function save(map2) {
|
|
6546
6544
|
try {
|
|
6547
|
-
|
|
6545
|
+
mkdirSync6(dirname5(file2), { recursive: true });
|
|
6548
6546
|
writeFileSync5(file2, JSON.stringify(map2) + "\n", "utf8");
|
|
6549
6547
|
} catch {
|
|
6550
6548
|
}
|
|
@@ -6661,13 +6659,13 @@ function composeInactiveNotice(reason, repository, client) {
|
|
|
6661
6659
|
}
|
|
6662
6660
|
|
|
6663
6661
|
// src/hooks/runtime/work-dir.ts
|
|
6664
|
-
import { existsSync as existsSync9, realpathSync, statSync } from "node:fs";
|
|
6665
|
-
import { dirname as
|
|
6662
|
+
import { existsSync as existsSync9, realpathSync, statSync as statSync2 } from "node:fs";
|
|
6663
|
+
import { dirname as dirname6, isAbsolute as isAbsolute3, join as join8, resolve } from "node:path";
|
|
6666
6664
|
function findRepoRoot(dir) {
|
|
6667
6665
|
let current = resolve(dir);
|
|
6668
6666
|
for (; ; ) {
|
|
6669
|
-
if (existsSync9(
|
|
6670
|
-
const parent =
|
|
6667
|
+
if (existsSync9(join8(current, ".git"))) return current;
|
|
6668
|
+
const parent = dirname6(current);
|
|
6671
6669
|
if (parent === current) return null;
|
|
6672
6670
|
current = parent;
|
|
6673
6671
|
}
|
|
@@ -6676,10 +6674,10 @@ function nearestExistingDir(path) {
|
|
|
6676
6674
|
let current = resolve(path);
|
|
6677
6675
|
for (; ; ) {
|
|
6678
6676
|
try {
|
|
6679
|
-
if (
|
|
6677
|
+
if (statSync2(current).isDirectory()) return current;
|
|
6680
6678
|
} catch {
|
|
6681
6679
|
}
|
|
6682
|
-
const parent =
|
|
6680
|
+
const parent = dirname6(current);
|
|
6683
6681
|
if (parent === current) return current;
|
|
6684
6682
|
current = parent;
|
|
6685
6683
|
}
|
|
@@ -6694,7 +6692,7 @@ function realPath(p) {
|
|
|
6694
6692
|
function projectDirForFile(file2, workDir) {
|
|
6695
6693
|
if (file2.length === 0 || file2.includes("$")) return workDir;
|
|
6696
6694
|
const absolute = isAbsolute3(file2) ? file2 : resolve(workDir, file2);
|
|
6697
|
-
const fileRoot = findRepoRoot(nearestExistingDir(
|
|
6695
|
+
const fileRoot = findRepoRoot(nearestExistingDir(dirname6(absolute)));
|
|
6698
6696
|
if (fileRoot === null) return workDir;
|
|
6699
6697
|
const workRoot = findRepoRoot(nearestExistingDir(workDir));
|
|
6700
6698
|
if (workRoot !== null && realPath(workRoot) === realPath(fileRoot)) {
|
|
@@ -6706,23 +6704,23 @@ function projectDirForFile(file2, workDir) {
|
|
|
6706
6704
|
// src/hooks/runtime/antigravity-session.ts
|
|
6707
6705
|
import {
|
|
6708
6706
|
appendFileSync,
|
|
6709
|
-
closeSync,
|
|
6707
|
+
closeSync as closeSync2,
|
|
6710
6708
|
constants,
|
|
6711
6709
|
lstatSync,
|
|
6712
|
-
mkdirSync as
|
|
6713
|
-
openSync,
|
|
6710
|
+
mkdirSync as mkdirSync7,
|
|
6711
|
+
openSync as openSync2,
|
|
6714
6712
|
readdirSync,
|
|
6715
|
-
readFileSync as
|
|
6713
|
+
readFileSync as readFileSync10,
|
|
6716
6714
|
renameSync,
|
|
6717
6715
|
rmSync,
|
|
6718
|
-
unlinkSync,
|
|
6716
|
+
unlinkSync as unlinkSync2,
|
|
6719
6717
|
utimesSync,
|
|
6720
6718
|
writeFileSync as writeFileSync6,
|
|
6721
|
-
writeSync as
|
|
6719
|
+
writeSync as writeSync3
|
|
6722
6720
|
} from "node:fs";
|
|
6723
6721
|
import { createHash as createHash2, randomBytes } from "node:crypto";
|
|
6724
|
-
import { homedir as
|
|
6725
|
-
import { join as
|
|
6722
|
+
import { homedir as homedir9 } from "node:os";
|
|
6723
|
+
import { join as join9 } from "node:path";
|
|
6726
6724
|
var MAX_STASHED_CONTEXTS = 20;
|
|
6727
6725
|
var DEFAULT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
6728
6726
|
var STASH_NAME_RE = /^\d+-[0-9a-f]{8}\.md$/;
|
|
@@ -6734,10 +6732,10 @@ function conversationKey(raw) {
|
|
|
6734
6732
|
return createHash2("sha256").update(id).digest("hex").slice(0, 32);
|
|
6735
6733
|
}
|
|
6736
6734
|
function antigravityStateDir() {
|
|
6737
|
-
return
|
|
6735
|
+
return join9(homedir9(), ".cybedefend", "antigravity");
|
|
6738
6736
|
}
|
|
6739
6737
|
function keyDir(key, dir) {
|
|
6740
|
-
return
|
|
6738
|
+
return join9(dir, key);
|
|
6741
6739
|
}
|
|
6742
6740
|
function isFinalStashName(name) {
|
|
6743
6741
|
return STASH_NAME_RE.test(name);
|
|
@@ -6759,15 +6757,15 @@ function isUnsafeFilePath(path) {
|
|
|
6759
6757
|
var NOFOLLOW_SUPPORTED = typeof constants.O_NOFOLLOW === "number";
|
|
6760
6758
|
function appendLedgerLine(path, line) {
|
|
6761
6759
|
if (NOFOLLOW_SUPPORTED) {
|
|
6762
|
-
const fd =
|
|
6760
|
+
const fd = openSync2(
|
|
6763
6761
|
path,
|
|
6764
6762
|
constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW,
|
|
6765
6763
|
FILE_MODE
|
|
6766
6764
|
);
|
|
6767
6765
|
try {
|
|
6768
|
-
|
|
6766
|
+
writeSync3(fd, line, null, "utf8");
|
|
6769
6767
|
} finally {
|
|
6770
|
-
|
|
6768
|
+
closeSync2(fd);
|
|
6771
6769
|
}
|
|
6772
6770
|
return;
|
|
6773
6771
|
}
|
|
@@ -6776,15 +6774,15 @@ function appendLedgerLine(path, line) {
|
|
|
6776
6774
|
}
|
|
6777
6775
|
function writeMarkerFile(path, content) {
|
|
6778
6776
|
if (NOFOLLOW_SUPPORTED) {
|
|
6779
|
-
const fd =
|
|
6777
|
+
const fd = openSync2(
|
|
6780
6778
|
path,
|
|
6781
6779
|
constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW,
|
|
6782
6780
|
FILE_MODE
|
|
6783
6781
|
);
|
|
6784
6782
|
try {
|
|
6785
|
-
|
|
6783
|
+
writeSync3(fd, content, null, "utf8");
|
|
6786
6784
|
} finally {
|
|
6787
|
-
|
|
6785
|
+
closeSync2(fd);
|
|
6788
6786
|
}
|
|
6789
6787
|
return;
|
|
6790
6788
|
}
|
|
@@ -6793,7 +6791,7 @@ function writeMarkerFile(path, content) {
|
|
|
6793
6791
|
}
|
|
6794
6792
|
function ensureRealDir(path) {
|
|
6795
6793
|
if (isUnsafePath(path)) return false;
|
|
6796
|
-
|
|
6794
|
+
mkdirSync7(path, { recursive: true, mode: DIR_MODE });
|
|
6797
6795
|
return true;
|
|
6798
6796
|
}
|
|
6799
6797
|
function ensureLiveKeyDir(key, dir, now) {
|
|
@@ -6812,12 +6810,12 @@ function stashContext(key, body, dir = antigravityStateDir()) {
|
|
|
6812
6810
|
const now = Date.now();
|
|
6813
6811
|
const kd = ensureLiveKeyDir(key, dir, now);
|
|
6814
6812
|
if (!kd) return;
|
|
6815
|
-
const contextDir =
|
|
6813
|
+
const contextDir = join9(kd, "context");
|
|
6816
6814
|
if (!ensureRealDir(contextDir)) return;
|
|
6817
6815
|
const suffix = randomBytes(4).toString("hex");
|
|
6818
|
-
tmpPath =
|
|
6816
|
+
tmpPath = join9(contextDir, `.${now}-${suffix}.tmp`);
|
|
6819
6817
|
writeFileSync6(tmpPath, body, { mode: FILE_MODE, flag: "wx" });
|
|
6820
|
-
const finalPath =
|
|
6818
|
+
const finalPath = join9(contextDir, `${now}-${suffix}.md`);
|
|
6821
6819
|
renameSync(tmpPath, finalPath);
|
|
6822
6820
|
tmpPath = void 0;
|
|
6823
6821
|
const kept = readdirSync(contextDir).filter(isFinalStashName).sort();
|
|
@@ -6825,7 +6823,7 @@ function stashContext(key, body, dir = antigravityStateDir()) {
|
|
|
6825
6823
|
if (excess > 0) {
|
|
6826
6824
|
for (const stale of kept.slice(0, excess)) {
|
|
6827
6825
|
try {
|
|
6828
|
-
|
|
6826
|
+
unlinkSync2(join9(contextDir, stale));
|
|
6829
6827
|
} catch {
|
|
6830
6828
|
}
|
|
6831
6829
|
}
|
|
@@ -6833,7 +6831,7 @@ function stashContext(key, body, dir = antigravityStateDir()) {
|
|
|
6833
6831
|
} catch {
|
|
6834
6832
|
if (tmpPath) {
|
|
6835
6833
|
try {
|
|
6836
|
-
|
|
6834
|
+
unlinkSync2(tmpPath);
|
|
6837
6835
|
} catch {
|
|
6838
6836
|
}
|
|
6839
6837
|
}
|
|
@@ -6843,15 +6841,15 @@ function drainContext(key, dir = antigravityStateDir()) {
|
|
|
6843
6841
|
try {
|
|
6844
6842
|
const kd = keyDir(key, dir);
|
|
6845
6843
|
if (isUnsafePath(kd)) return [];
|
|
6846
|
-
const contextDir =
|
|
6844
|
+
const contextDir = join9(kd, "context");
|
|
6847
6845
|
if (isUnsafePath(contextDir)) return [];
|
|
6848
6846
|
const entries = readdirSync(contextDir).filter(isFinalStashName).sort();
|
|
6849
6847
|
const seen = /* @__PURE__ */ new Set();
|
|
6850
6848
|
const bodies = [];
|
|
6851
6849
|
for (const name of entries) {
|
|
6852
|
-
const filePath =
|
|
6850
|
+
const filePath = join9(contextDir, name);
|
|
6853
6851
|
try {
|
|
6854
|
-
const body =
|
|
6852
|
+
const body = readFileSync10(filePath, "utf8");
|
|
6855
6853
|
if (!seen.has(body)) {
|
|
6856
6854
|
seen.add(body);
|
|
6857
6855
|
bodies.push(body);
|
|
@@ -6859,7 +6857,7 @@ function drainContext(key, dir = antigravityStateDir()) {
|
|
|
6859
6857
|
} catch {
|
|
6860
6858
|
}
|
|
6861
6859
|
try {
|
|
6862
|
-
|
|
6860
|
+
unlinkSync2(filePath);
|
|
6863
6861
|
} catch {
|
|
6864
6862
|
}
|
|
6865
6863
|
}
|
|
@@ -6873,7 +6871,7 @@ function recordEdit(key, file2, dir = antigravityStateDir()) {
|
|
|
6873
6871
|
const now = Date.now();
|
|
6874
6872
|
const kd = ensureLiveKeyDir(key, dir, now);
|
|
6875
6873
|
if (!kd) return;
|
|
6876
|
-
appendLedgerLine(
|
|
6874
|
+
appendLedgerLine(join9(kd, "edits.jsonl"), JSON.stringify({ f: file2 }) + "\n");
|
|
6877
6875
|
} catch {
|
|
6878
6876
|
}
|
|
6879
6877
|
}
|
|
@@ -6881,9 +6879,9 @@ function readEdits(key, dir = antigravityStateDir()) {
|
|
|
6881
6879
|
try {
|
|
6882
6880
|
const kd = keyDir(key, dir);
|
|
6883
6881
|
if (isUnsafePath(kd)) return { count: 0, files: [] };
|
|
6884
|
-
const editsPath =
|
|
6882
|
+
const editsPath = join9(kd, "edits.jsonl");
|
|
6885
6883
|
if (isUnsafeFilePath(editsPath)) return { count: 0, files: [] };
|
|
6886
|
-
const content =
|
|
6884
|
+
const content = readFileSync10(editsPath, "utf8");
|
|
6887
6885
|
let count = 0;
|
|
6888
6886
|
const files = [];
|
|
6889
6887
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -6913,7 +6911,7 @@ function markReviewed(key, dir = antigravityStateDir()) {
|
|
|
6913
6911
|
const now = Date.now();
|
|
6914
6912
|
const kd = ensureLiveKeyDir(key, dir, now);
|
|
6915
6913
|
if (!kd) return;
|
|
6916
|
-
writeMarkerFile(
|
|
6914
|
+
writeMarkerFile(join9(kd, "reviewed"), String(now));
|
|
6917
6915
|
} catch {
|
|
6918
6916
|
}
|
|
6919
6917
|
}
|
|
@@ -6921,7 +6919,7 @@ function isReviewed(key, dir = antigravityStateDir()) {
|
|
|
6921
6919
|
try {
|
|
6922
6920
|
const kd = keyDir(key, dir);
|
|
6923
6921
|
if (isUnsafePath(kd)) return false;
|
|
6924
|
-
return lstatSync(
|
|
6922
|
+
return lstatSync(join9(kd, "reviewed")).isFile();
|
|
6925
6923
|
} catch {
|
|
6926
6924
|
return false;
|
|
6927
6925
|
}
|
|
@@ -6930,7 +6928,7 @@ function pruneStale(dir = antigravityStateDir(), now = Date.now(), maxAgeMs = DE
|
|
|
6930
6928
|
try {
|
|
6931
6929
|
const entries = readdirSync(dir);
|
|
6932
6930
|
for (const name of entries) {
|
|
6933
|
-
const entryPath =
|
|
6931
|
+
const entryPath = join9(dir, name);
|
|
6934
6932
|
try {
|
|
6935
6933
|
const { mtimeMs } = lstatSync(entryPath);
|
|
6936
6934
|
if (now - mtimeMs > maxAgeMs) {
|
|
@@ -6995,9 +6993,7 @@ async function fetchRulesHook(deps = {}) {
|
|
|
6995
6993
|
const { projectId, apiBase: configApiBase } = resolution;
|
|
6996
6994
|
if (!projectId) return;
|
|
6997
6995
|
const apiBase = process.env.CYBEDEFEND_API_BASE ?? configApiBase ?? config2.region.apiBase;
|
|
6998
|
-
const token = resolveTok(config2.region.mcpName
|
|
6999
|
-
mcpUrl: config2.region.mcpUrl
|
|
7000
|
-
});
|
|
6996
|
+
const token = resolveTok(config2.region.mcpName);
|
|
7001
6997
|
if (!token) return;
|
|
7002
6998
|
const intent = buildIntent(event);
|
|
7003
6999
|
const fileLabel = files.join(", ");
|
|
@@ -7104,6 +7100,15 @@ function composeSecurityBody(markdown, total, filePath) {
|
|
|
7104
7100
|
].join("\n");
|
|
7105
7101
|
}
|
|
7106
7102
|
|
|
7103
|
+
// src/hooks/runtime/sign-in-notice.ts
|
|
7104
|
+
import { homedir as homedir11 } from "node:os";
|
|
7105
|
+
import { join as join11 } from "node:path";
|
|
7106
|
+
|
|
7107
|
+
// src/hooks/runtime/user-prompt-submit.ts
|
|
7108
|
+
import { existsSync as existsSync10, mkdirSync as mkdirSync8, readFileSync as readFileSync11, writeFileSync as writeFileSync7 } from "node:fs";
|
|
7109
|
+
import { homedir as homedir10 } from "node:os";
|
|
7110
|
+
import { join as join10 } from "node:path";
|
|
7111
|
+
|
|
7107
7112
|
// src/hooks/runtime/proposal-mode.ts
|
|
7108
7113
|
var TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
|
|
7109
7114
|
var FALSY = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
|
|
@@ -7128,11 +7133,144 @@ var DIRECT_PROPOSE_DIRECTIVES = {
|
|
|
7128
7133
|
"non-blocking": `**Non-blocking mode is ON** (autonomous agent \u2014 nobody is in the chat to answer). Do NOT ask the user (no AskUserQuestion). If \u2014 and ONLY if \u2014 one durable, reusable gap stands out, call ${REPORT_MISSING_CALL} directly for that single rule. It lands as a pending proposal that a human accepts or rejects in the CybeDefend dashboard. Otherwise propose nothing.`
|
|
7129
7134
|
};
|
|
7130
7135
|
|
|
7136
|
+
// src/hooks/runtime/user-prompt-submit.ts
|
|
7137
|
+
var SESSIONS_CAP2 = 100;
|
|
7138
|
+
function defaultSessionsFile() {
|
|
7139
|
+
const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join10(homedir10(), ".cybedefend");
|
|
7140
|
+
return join10(dir, "user-prompt-seen-sessions.json");
|
|
7141
|
+
}
|
|
7142
|
+
function defaultSessionTracker(file2 = defaultSessionsFile()) {
|
|
7143
|
+
function load2() {
|
|
7144
|
+
if (!existsSync10(file2)) return [];
|
|
7145
|
+
try {
|
|
7146
|
+
const raw = readFileSync11(file2, "utf8");
|
|
7147
|
+
const data = JSON.parse(raw);
|
|
7148
|
+
if (!Array.isArray(data.sessions)) return [];
|
|
7149
|
+
return data.sessions.filter((s) => typeof s === "string");
|
|
7150
|
+
} catch {
|
|
7151
|
+
return [];
|
|
7152
|
+
}
|
|
7153
|
+
}
|
|
7154
|
+
return {
|
|
7155
|
+
hasSeen(sessionId) {
|
|
7156
|
+
return load2().includes(sessionId);
|
|
7157
|
+
},
|
|
7158
|
+
async markSeen(sessionId) {
|
|
7159
|
+
const existing = load2();
|
|
7160
|
+
if (existing.includes(sessionId)) return;
|
|
7161
|
+
const next = [...existing, sessionId].slice(-SESSIONS_CAP2);
|
|
7162
|
+
try {
|
|
7163
|
+
mkdirSync8(join10(file2, ".."), { recursive: true });
|
|
7164
|
+
writeFileSync7(file2, JSON.stringify({ sessions: next }), "utf8");
|
|
7165
|
+
} catch {
|
|
7166
|
+
}
|
|
7167
|
+
}
|
|
7168
|
+
};
|
|
7169
|
+
}
|
|
7170
|
+
async function userPromptSubmitHook(deps = {}) {
|
|
7171
|
+
const readStdin = deps.readStdin ?? readStdinJson;
|
|
7172
|
+
const loadConfig = deps.loadConfig ?? loadRuntimeConfig;
|
|
7173
|
+
const resolveProject = deps.resolveProject ?? resolveProjectIdWithApi;
|
|
7174
|
+
const resolveTok = deps.resolveTokenFn ?? resolveToken;
|
|
7175
|
+
const fetchProposals = deps.fetchProposalsFn ?? fetchProposalsCount;
|
|
7176
|
+
const emitFn = deps.emitFn ?? emit;
|
|
7177
|
+
const sessionTracker = deps.sessionTracker ?? defaultSessionTracker();
|
|
7178
|
+
const stdin = await readStdin();
|
|
7179
|
+
const event = sniff(stdin);
|
|
7180
|
+
const sessionId = typeof stdin.session_id === "string" && stdin.session_id.length > 0 ? stdin.session_id : null;
|
|
7181
|
+
if (sessionId !== null && sessionTracker.hasSeen(sessionId)) {
|
|
7182
|
+
return;
|
|
7183
|
+
}
|
|
7184
|
+
const config2 = loadConfig();
|
|
7185
|
+
if (!config2) return;
|
|
7186
|
+
const folder = sessionFolderOf(stdin, event.client);
|
|
7187
|
+
if (isSessionInactive(stdin, { store: deps.sessionStore, cwd: folder })) return;
|
|
7188
|
+
const { projectId, apiBase: configApiBase } = await resolveProject(folder);
|
|
7189
|
+
if (!projectId) return;
|
|
7190
|
+
const apiBase = process.env.CYBEDEFEND_API_BASE ?? configApiBase ?? config2.region.apiBase;
|
|
7191
|
+
const token = resolveTok(config2.region.mcpName);
|
|
7192
|
+
let total = null;
|
|
7193
|
+
if (token) {
|
|
7194
|
+
const result = await fetchProposals({ apiBase, projectId, token });
|
|
7195
|
+
if (result) total = result.total;
|
|
7196
|
+
}
|
|
7197
|
+
const lines = [
|
|
7198
|
+
"## \u26A0\uFE0F CybeDefend doctrine \u2014 execute BEFORE answering this prompt",
|
|
7199
|
+
"",
|
|
7200
|
+
`**Project**: \`${projectId}\``,
|
|
7201
|
+
"",
|
|
7202
|
+
"### Step 0 \u2014 Proposal inbox"
|
|
7203
|
+
];
|
|
7204
|
+
const nonBlocking = isNonBlockingMode(config2);
|
|
7205
|
+
if (nonBlocking) {
|
|
7206
|
+
lines.push(
|
|
7207
|
+
`- CybeDefend: ${total === null ? "proposal inbox not checked" : `**${total}** pending proposals`} \u2014 no action required.`,
|
|
7208
|
+
`- ${NON_BLOCKING_INBOX_DIRECTIVE}`
|
|
7209
|
+
);
|
|
7210
|
+
} else if (total === null) {
|
|
7211
|
+
lines.push(
|
|
7212
|
+
"- CybeDefend: could not fetch proposal-inbox status (token / API unreachable).",
|
|
7213
|
+
'- Call `cybe_rules_list_proposals(projectId, status="proposed")` yourself to verify, then handle each surfaced proposal via AskUserQuestion (Accept / Reject / Skip / Tell me more) before continuing.'
|
|
7214
|
+
);
|
|
7215
|
+
} else if (total > 0) {
|
|
7216
|
+
lines.push(
|
|
7217
|
+
`- CybeDefend: **${total}** pending proposals.`,
|
|
7218
|
+
'- Call `cybe_rules_list_proposals(projectId, status="proposed")` and surface each via AskUserQuestion (Accept / Reject / Skip / Tell me more) BEFORE responding to this prompt.'
|
|
7219
|
+
);
|
|
7220
|
+
} else {
|
|
7221
|
+
lines.push(
|
|
7222
|
+
"- CybeDefend: **0** pending proposals.",
|
|
7223
|
+
'- You MUST still acknowledge step 0 in your reply ("No pending business-rule proposals."). Silently skipping this step is a doctrine violation observed in earlier sessions.'
|
|
7224
|
+
);
|
|
7225
|
+
}
|
|
7226
|
+
lines.push(
|
|
7227
|
+
"",
|
|
7228
|
+
"### Step 1 \u2014 Rules fetch (before any code edit)",
|
|
7229
|
+
"- Even if you plan to brainstorm / explore / ask clarifying questions first, call BOTH:",
|
|
7230
|
+
' - `cybe_rules_fetch(projectId, files=[...], intent="<1-2 sentence narrative>")` for business rules',
|
|
7231
|
+
' - `cybe_secrules_fetch(projectId, files=[...], intent="...", languages=[...])` for security rules',
|
|
7232
|
+
'- Use a rich `intent` \u2014 the retrieval is 60% graph + 40% vector, so a generic placeholder like "Editing file" returns nothing useful.',
|
|
7233
|
+
"- The PreToolUse hook fires automatically as a backstop on Edit/Write/MultiEdit, but your explicit call with a narrative intent gets better matches.",
|
|
7234
|
+
"",
|
|
7235
|
+
"### Order",
|
|
7236
|
+
nonBlocking ? "1. Step 0 needs no action (non-blocking mode)." : "1. Satisfy step 0 (acknowledge / handle the inbox).",
|
|
7237
|
+
"2. Satisfy step 1 (fetch rules with a narrative intent) once you know which files you will touch.",
|
|
7238
|
+
"3. THEN proceed with whatever skill / brainstorm / implementation flow fits the task.",
|
|
7239
|
+
""
|
|
7240
|
+
);
|
|
7241
|
+
emitFn(lines.join("\n"), event.client);
|
|
7242
|
+
if (sessionId !== null) {
|
|
7243
|
+
try {
|
|
7244
|
+
await sessionTracker.markSeen(sessionId);
|
|
7245
|
+
} catch {
|
|
7246
|
+
}
|
|
7247
|
+
}
|
|
7248
|
+
}
|
|
7249
|
+
|
|
7250
|
+
// src/hooks/runtime/sign-in-notice.ts
|
|
7251
|
+
var SIGN_IN_NOTICE = "\u{1F6E1}\uFE0F CybeDefend found no sign-in: Action Guards may not be enforced, and no rules reach your agent. Run `vibedefend login`.";
|
|
7252
|
+
function noticeSessionsFile() {
|
|
7253
|
+
const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join11(homedir11(), ".cybedefend");
|
|
7254
|
+
return join11(dir, "sign-in-notice-sessions.json");
|
|
7255
|
+
}
|
|
7256
|
+
async function claimSignInNotice(mcpName, sessionId, deps = {}) {
|
|
7257
|
+
if (!sessionId) return false;
|
|
7258
|
+
try {
|
|
7259
|
+
const sessions = defaultSessionTracker(noticeSessionsFile());
|
|
7260
|
+
if (sessions.hasSeen(sessionId)) return false;
|
|
7261
|
+
if ((deps.hasUsableSignIn ?? hasUsableStoredAuth)(mcpName)) return false;
|
|
7262
|
+
await sessions.markSeen(sessionId);
|
|
7263
|
+
return true;
|
|
7264
|
+
} catch {
|
|
7265
|
+
return false;
|
|
7266
|
+
}
|
|
7267
|
+
}
|
|
7268
|
+
|
|
7131
7269
|
// src/hooks/runtime/self-update-check.ts
|
|
7132
7270
|
import { spawn } from "node:child_process";
|
|
7133
|
-
import { existsSync as
|
|
7134
|
-
import { homedir as
|
|
7135
|
-
import { join as
|
|
7271
|
+
import { existsSync as existsSync12, readFileSync as readFileSync12, rmSync as rmSync2, writeFileSync as writeFileSync8 } from "node:fs";
|
|
7272
|
+
import { homedir as homedir12 } from "node:os";
|
|
7273
|
+
import { join as join12 } from "node:path";
|
|
7136
7274
|
|
|
7137
7275
|
// src/hooks/runtime/semver.ts
|
|
7138
7276
|
function parseVersion(input2) {
|
|
@@ -7160,7 +7298,7 @@ function isNewer(latest, current) {
|
|
|
7160
7298
|
|
|
7161
7299
|
// src/self-update.ts
|
|
7162
7300
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
7163
|
-
import { existsSync as
|
|
7301
|
+
import { existsSync as existsSync11, realpathSync as realpathSync2 } from "node:fs";
|
|
7164
7302
|
var GLOBAL_MODES = /* @__PURE__ */ new Set([
|
|
7165
7303
|
"npm-global",
|
|
7166
7304
|
"pnpm-global",
|
|
@@ -7188,7 +7326,7 @@ function detectInstallMode(scriptPath) {
|
|
|
7188
7326
|
}
|
|
7189
7327
|
function resolveScriptPath() {
|
|
7190
7328
|
const fromArgv = process.argv[1];
|
|
7191
|
-
if (fromArgv &&
|
|
7329
|
+
if (fromArgv && existsSync11(fromArgv)) {
|
|
7192
7330
|
try {
|
|
7193
7331
|
return realpathSync2(fromArgv);
|
|
7194
7332
|
} catch {
|
|
@@ -7210,9 +7348,9 @@ function isValidRegistryVersion(value) {
|
|
|
7210
7348
|
}
|
|
7211
7349
|
async function selfUpdateCheck(deps) {
|
|
7212
7350
|
const now = deps.now ?? (() => Date.now());
|
|
7213
|
-
const dir = deps.cybeDir ??
|
|
7214
|
-
const throttlePath =
|
|
7215
|
-
const logPath =
|
|
7351
|
+
const dir = deps.cybeDir ?? join12(process.env.CYBEDEFEND_HOME ?? homedir12(), ".cybedefend");
|
|
7352
|
+
const throttlePath = join12(dir, "update-check.json");
|
|
7353
|
+
const logPath = join12(dir, "last-update.log");
|
|
7216
7354
|
const installMode = deps.installMode ?? (deps.runnerSource ? detectInstallMode(deps.runnerSource) : detectInstallMode(resolveScriptPath()));
|
|
7217
7355
|
const priorFailure = takeUpdateLogNotice(logPath);
|
|
7218
7356
|
const throttle = readThrottle(throttlePath);
|
|
@@ -7245,8 +7383,8 @@ function applyOrNotify(deps, installMode, latest, logPath) {
|
|
|
7245
7383
|
}
|
|
7246
7384
|
function readThrottle(path) {
|
|
7247
7385
|
try {
|
|
7248
|
-
if (!
|
|
7249
|
-
const data = JSON.parse(
|
|
7386
|
+
if (!existsSync12(path)) return null;
|
|
7387
|
+
const data = JSON.parse(readFileSync12(path, "utf8"));
|
|
7250
7388
|
if (typeof data.lastCheckedAt !== "number") return null;
|
|
7251
7389
|
return { lastCheckedAt: data.lastCheckedAt };
|
|
7252
7390
|
} catch {
|
|
@@ -7256,16 +7394,16 @@ function readThrottle(path) {
|
|
|
7256
7394
|
function writeThrottle(path, throttle) {
|
|
7257
7395
|
try {
|
|
7258
7396
|
ensureDirFor(path);
|
|
7259
|
-
|
|
7397
|
+
writeFileSync8(path, JSON.stringify(throttle) + "\n");
|
|
7260
7398
|
} catch {
|
|
7261
7399
|
}
|
|
7262
7400
|
}
|
|
7263
7401
|
function takeUpdateLogNotice(logPath) {
|
|
7264
7402
|
try {
|
|
7265
|
-
if (!
|
|
7403
|
+
if (!existsSync12(logPath)) return null;
|
|
7266
7404
|
let parsed = {};
|
|
7267
7405
|
try {
|
|
7268
|
-
parsed = JSON.parse(
|
|
7406
|
+
parsed = JSON.parse(readFileSync12(logPath, "utf8"));
|
|
7269
7407
|
} catch {
|
|
7270
7408
|
parsed = {};
|
|
7271
7409
|
}
|
|
@@ -7340,18 +7478,18 @@ function pmCommand(mode, spec) {
|
|
|
7340
7478
|
|
|
7341
7479
|
// src/hooks/runtime/hook-refresh-trigger.ts
|
|
7342
7480
|
import { spawn as spawn2 } from "node:child_process";
|
|
7343
|
-
import { existsSync as
|
|
7344
|
-
import { homedir as
|
|
7345
|
-
import { dirname as
|
|
7481
|
+
import { existsSync as existsSync13, readFileSync as readFileSync13, writeFileSync as writeFileSync9 } from "node:fs";
|
|
7482
|
+
import { homedir as homedir13 } from "node:os";
|
|
7483
|
+
import { dirname as dirname7, join as join13 } from "node:path";
|
|
7346
7484
|
function maybeRefreshStaleWiring(deps) {
|
|
7347
7485
|
try {
|
|
7348
7486
|
const { config: config2, runnerVersion } = deps;
|
|
7349
7487
|
if (!config2.runnerSource || config2.installedVersion === runnerVersion) {
|
|
7350
7488
|
return false;
|
|
7351
7489
|
}
|
|
7352
|
-
const cliEntry =
|
|
7353
|
-
if (!(deps.exists ??
|
|
7354
|
-
const markerPath = deps.markerPath ??
|
|
7490
|
+
const cliEntry = join13(dirname7(dirname7(config2.runnerSource)), "bin", "vibedefend.js");
|
|
7491
|
+
if (!(deps.exists ?? existsSync13)(cliEntry)) return false;
|
|
7492
|
+
const markerPath = deps.markerPath ?? join13(process.env.CYBEDEFEND_HOME ?? homedir13(), ".cybedefend", "hook-refresh.json");
|
|
7355
7493
|
if (readMarkerVersion(markerPath) === runnerVersion) return false;
|
|
7356
7494
|
(deps.spawnRefresh ?? defaultSpawnRefresh)(cliEntry);
|
|
7357
7495
|
writeMarker(markerPath, runnerVersion);
|
|
@@ -7362,8 +7500,8 @@ function maybeRefreshStaleWiring(deps) {
|
|
|
7362
7500
|
}
|
|
7363
7501
|
function readMarkerVersion(path) {
|
|
7364
7502
|
try {
|
|
7365
|
-
if (!
|
|
7366
|
-
const data = JSON.parse(
|
|
7503
|
+
if (!existsSync13(path)) return null;
|
|
7504
|
+
const data = JSON.parse(readFileSync13(path, "utf8"));
|
|
7367
7505
|
return typeof data.version === "string" ? data.version : null;
|
|
7368
7506
|
} catch {
|
|
7369
7507
|
return null;
|
|
@@ -7372,7 +7510,7 @@ function readMarkerVersion(path) {
|
|
|
7372
7510
|
function writeMarker(path, version2) {
|
|
7373
7511
|
try {
|
|
7374
7512
|
ensureDirFor(path);
|
|
7375
|
-
|
|
7513
|
+
writeFileSync9(path, JSON.stringify({ version: version2, spawnedAt: Date.now() }) + "\n");
|
|
7376
7514
|
} catch {
|
|
7377
7515
|
}
|
|
7378
7516
|
}
|
|
@@ -7386,18 +7524,18 @@ function defaultSpawnRefresh(cliEntry) {
|
|
|
7386
7524
|
}
|
|
7387
7525
|
|
|
7388
7526
|
// src/version.ts
|
|
7389
|
-
import { readFileSync as
|
|
7527
|
+
import { readFileSync as readFileSync14 } from "node:fs";
|
|
7390
7528
|
import { fileURLToPath as fileURLToPath3 } from "node:url";
|
|
7391
|
-
import { dirname as
|
|
7529
|
+
import { dirname as dirname8, join as join14 } from "node:path";
|
|
7392
7530
|
var PKG_NAME = "@cybedefend/vibedefend";
|
|
7393
7531
|
function defaultPkgPath() {
|
|
7394
|
-
return
|
|
7532
|
+
return join14(dirname8(fileURLToPath3(import.meta.url)), "..", "package.json");
|
|
7395
7533
|
}
|
|
7396
7534
|
function readPackageMeta(opts = {}) {
|
|
7397
7535
|
if (typeof opts.bakedVersion === "string" && opts.bakedVersion.length > 0) {
|
|
7398
7536
|
return { name: PKG_NAME, version: opts.bakedVersion };
|
|
7399
7537
|
}
|
|
7400
|
-
const readFile = opts.readFile ?? ((p) =>
|
|
7538
|
+
const readFile = opts.readFile ?? ((p) => readFileSync14(p, "utf8"));
|
|
7401
7539
|
const pkgPath = opts.pkgPath ?? defaultPkgPath();
|
|
7402
7540
|
try {
|
|
7403
7541
|
return JSON.parse(readFile(pkgPath));
|
|
@@ -7406,7 +7544,7 @@ function readPackageMeta(opts = {}) {
|
|
|
7406
7544
|
}
|
|
7407
7545
|
}
|
|
7408
7546
|
var pkg = readPackageMeta({
|
|
7409
|
-
bakedVersion: true ? "1.8.
|
|
7547
|
+
bakedVersion: true ? "1.8.2" : void 0
|
|
7410
7548
|
});
|
|
7411
7549
|
|
|
7412
7550
|
// src/hooks/runtime/session-start.ts
|
|
@@ -7462,9 +7600,7 @@ async function sessionStartHook(deps = {}) {
|
|
|
7462
7600
|
);
|
|
7463
7601
|
return;
|
|
7464
7602
|
}
|
|
7465
|
-
const token = resolveTok(config2.region.mcpName
|
|
7466
|
-
mcpUrl: config2.region.mcpUrl
|
|
7467
|
-
});
|
|
7603
|
+
const token = resolveTok(config2.region.mcpName);
|
|
7468
7604
|
let total = null;
|
|
7469
7605
|
if (token) {
|
|
7470
7606
|
const result = await fetchProposals({ apiBase, projectId, token });
|
|
@@ -7544,27 +7680,41 @@ async function sessionStartHook(deps = {}) {
|
|
|
7544
7680
|
if (notice) lines.push("", notice);
|
|
7545
7681
|
} catch {
|
|
7546
7682
|
}
|
|
7547
|
-
|
|
7683
|
+
const body = lines.join("\n") + "\n";
|
|
7684
|
+
const claimNotice = deps.claimSignInNoticeFn ?? claimSignInNotice;
|
|
7685
|
+
if (!token && await claimNotice(config2.region.mcpName, sessionId)) {
|
|
7686
|
+
emitNoticeFn(
|
|
7687
|
+
{
|
|
7688
|
+
userMessage: SIGN_IN_NOTICE,
|
|
7689
|
+
modelContext: body + (SYSTEM_MESSAGE_CLIENTS.has(event.client) ? "\n- **No sign-in**: the user has been told to run `vibedefend login`; do not repeat it.\n" : `
|
|
7690
|
+
- **No sign-in**: Tell the user once, in one short line: ${SIGN_IN_NOTICE}
|
|
7691
|
+
`)
|
|
7692
|
+
},
|
|
7693
|
+
event.client
|
|
7694
|
+
);
|
|
7695
|
+
return;
|
|
7696
|
+
}
|
|
7697
|
+
emitFn(body, event.client);
|
|
7548
7698
|
}
|
|
7549
7699
|
|
|
7550
7700
|
// src/hooks/runtime/session-review.ts
|
|
7551
|
-
import { existsSync as
|
|
7701
|
+
import { existsSync as existsSync15, readFileSync as readFileSync16 } from "node:fs";
|
|
7552
7702
|
|
|
7553
7703
|
// src/hooks/runtime/review-sessions.ts
|
|
7554
|
-
import { existsSync as
|
|
7555
|
-
import { homedir as
|
|
7556
|
-
import { dirname as
|
|
7557
|
-
var
|
|
7704
|
+
import { existsSync as existsSync14, mkdirSync as mkdirSync9, readFileSync as readFileSync15, writeFileSync as writeFileSync10 } from "node:fs";
|
|
7705
|
+
import { homedir as homedir14 } from "node:os";
|
|
7706
|
+
import { dirname as dirname9, join as join15 } from "node:path";
|
|
7707
|
+
var SESSIONS_CAP3 = 200;
|
|
7558
7708
|
function defaultStoreFile2() {
|
|
7559
|
-
const dir = process.env.CYBEDEFEND_BASELINE_DIR ??
|
|
7560
|
-
return
|
|
7709
|
+
const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join15(homedir14(), ".cybedefend");
|
|
7710
|
+
return join15(dir, "review-sessions.json");
|
|
7561
7711
|
}
|
|
7562
7712
|
var isCount = (n) => typeof n === "number" && Number.isInteger(n) && n >= 0;
|
|
7563
7713
|
function defaultReviewSessionStore(file2 = defaultStoreFile2(), now = Date.now) {
|
|
7564
7714
|
function load2() {
|
|
7565
|
-
if (!
|
|
7715
|
+
if (!existsSync14(file2)) return {};
|
|
7566
7716
|
try {
|
|
7567
|
-
const parsed = JSON.parse(
|
|
7717
|
+
const parsed = JSON.parse(readFileSync15(file2, "utf8"));
|
|
7568
7718
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
7569
7719
|
} catch {
|
|
7570
7720
|
return {};
|
|
@@ -7572,8 +7722,8 @@ function defaultReviewSessionStore(file2 = defaultStoreFile2(), now = Date.now)
|
|
|
7572
7722
|
}
|
|
7573
7723
|
function save(map2) {
|
|
7574
7724
|
try {
|
|
7575
|
-
|
|
7576
|
-
|
|
7725
|
+
mkdirSync9(dirname9(file2), { recursive: true });
|
|
7726
|
+
writeFileSync10(file2, JSON.stringify(map2) + "\n", "utf8");
|
|
7577
7727
|
} catch {
|
|
7578
7728
|
}
|
|
7579
7729
|
}
|
|
@@ -7588,9 +7738,9 @@ function defaultReviewSessionStore(file2 = defaultStoreFile2(), now = Date.now)
|
|
|
7588
7738
|
const map2 = load2();
|
|
7589
7739
|
map2[sessionId] = { ...record2, at: now() };
|
|
7590
7740
|
const entries = Object.entries(map2);
|
|
7591
|
-
if (entries.length >
|
|
7741
|
+
if (entries.length > SESSIONS_CAP3) {
|
|
7592
7742
|
entries.sort(([, a], [, b]) => (a.at ?? 0) - (b.at ?? 0));
|
|
7593
|
-
save(Object.fromEntries(entries.slice(-
|
|
7743
|
+
save(Object.fromEntries(entries.slice(-SESSIONS_CAP3)));
|
|
7594
7744
|
return;
|
|
7595
7745
|
}
|
|
7596
7746
|
save(map2);
|
|
@@ -7783,9 +7933,9 @@ function loadTranscript(stdin, readFile) {
|
|
|
7783
7933
|
return out;
|
|
7784
7934
|
}
|
|
7785
7935
|
function defaultReadTranscript(path) {
|
|
7786
|
-
if (!
|
|
7936
|
+
if (!existsSync15(path)) return null;
|
|
7787
7937
|
try {
|
|
7788
|
-
return
|
|
7938
|
+
return readFileSync16(path, "utf8");
|
|
7789
7939
|
} catch {
|
|
7790
7940
|
return null;
|
|
7791
7941
|
}
|
|
@@ -8052,125 +8202,6 @@ async function preCompactHook(deps = {}) {
|
|
|
8052
8202
|
emitFn(body, event.client);
|
|
8053
8203
|
}
|
|
8054
8204
|
|
|
8055
|
-
// src/hooks/runtime/user-prompt-submit.ts
|
|
8056
|
-
import { existsSync as existsSync15, mkdirSync as mkdirSync8, readFileSync as readFileSync15, writeFileSync as writeFileSync10 } from "node:fs";
|
|
8057
|
-
import { homedir as homedir12 } from "node:os";
|
|
8058
|
-
import { join as join13 } from "node:path";
|
|
8059
|
-
var SESSIONS_CAP3 = 100;
|
|
8060
|
-
function defaultSessionsFile() {
|
|
8061
|
-
const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join13(homedir12(), ".cybedefend");
|
|
8062
|
-
return join13(dir, "user-prompt-seen-sessions.json");
|
|
8063
|
-
}
|
|
8064
|
-
function defaultSessionTracker(file2 = defaultSessionsFile()) {
|
|
8065
|
-
function load2() {
|
|
8066
|
-
if (!existsSync15(file2)) return [];
|
|
8067
|
-
try {
|
|
8068
|
-
const raw = readFileSync15(file2, "utf8");
|
|
8069
|
-
const data = JSON.parse(raw);
|
|
8070
|
-
if (!Array.isArray(data.sessions)) return [];
|
|
8071
|
-
return data.sessions.filter((s) => typeof s === "string");
|
|
8072
|
-
} catch {
|
|
8073
|
-
return [];
|
|
8074
|
-
}
|
|
8075
|
-
}
|
|
8076
|
-
return {
|
|
8077
|
-
hasSeen(sessionId) {
|
|
8078
|
-
return load2().includes(sessionId);
|
|
8079
|
-
},
|
|
8080
|
-
async markSeen(sessionId) {
|
|
8081
|
-
const existing = load2();
|
|
8082
|
-
if (existing.includes(sessionId)) return;
|
|
8083
|
-
const next = [...existing, sessionId].slice(-SESSIONS_CAP3);
|
|
8084
|
-
try {
|
|
8085
|
-
mkdirSync8(join13(file2, ".."), { recursive: true });
|
|
8086
|
-
writeFileSync10(file2, JSON.stringify({ sessions: next }), "utf8");
|
|
8087
|
-
} catch {
|
|
8088
|
-
}
|
|
8089
|
-
}
|
|
8090
|
-
};
|
|
8091
|
-
}
|
|
8092
|
-
async function userPromptSubmitHook(deps = {}) {
|
|
8093
|
-
const readStdin = deps.readStdin ?? readStdinJson;
|
|
8094
|
-
const loadConfig = deps.loadConfig ?? loadRuntimeConfig;
|
|
8095
|
-
const resolveProject = deps.resolveProject ?? resolveProjectIdWithApi;
|
|
8096
|
-
const resolveTok = deps.resolveTokenFn ?? resolveToken;
|
|
8097
|
-
const fetchProposals = deps.fetchProposalsFn ?? fetchProposalsCount;
|
|
8098
|
-
const emitFn = deps.emitFn ?? emit;
|
|
8099
|
-
const sessionTracker = deps.sessionTracker ?? defaultSessionTracker();
|
|
8100
|
-
const stdin = await readStdin();
|
|
8101
|
-
const event = sniff(stdin);
|
|
8102
|
-
const sessionId = typeof stdin.session_id === "string" && stdin.session_id.length > 0 ? stdin.session_id : null;
|
|
8103
|
-
if (sessionId !== null && sessionTracker.hasSeen(sessionId)) {
|
|
8104
|
-
return;
|
|
8105
|
-
}
|
|
8106
|
-
const config2 = loadConfig();
|
|
8107
|
-
if (!config2) return;
|
|
8108
|
-
const folder = sessionFolderOf(stdin, event.client);
|
|
8109
|
-
if (isSessionInactive(stdin, { store: deps.sessionStore, cwd: folder })) return;
|
|
8110
|
-
const { projectId, apiBase: configApiBase } = await resolveProject(folder);
|
|
8111
|
-
if (!projectId) return;
|
|
8112
|
-
const apiBase = process.env.CYBEDEFEND_API_BASE ?? configApiBase ?? config2.region.apiBase;
|
|
8113
|
-
const token = resolveTok(config2.region.mcpName, {
|
|
8114
|
-
mcpUrl: config2.region.mcpUrl
|
|
8115
|
-
});
|
|
8116
|
-
let total = null;
|
|
8117
|
-
if (token) {
|
|
8118
|
-
const result = await fetchProposals({ apiBase, projectId, token });
|
|
8119
|
-
if (result) total = result.total;
|
|
8120
|
-
}
|
|
8121
|
-
const lines = [
|
|
8122
|
-
"## \u26A0\uFE0F CybeDefend doctrine \u2014 execute BEFORE answering this prompt",
|
|
8123
|
-
"",
|
|
8124
|
-
`**Project**: \`${projectId}\``,
|
|
8125
|
-
"",
|
|
8126
|
-
"### Step 0 \u2014 Proposal inbox"
|
|
8127
|
-
];
|
|
8128
|
-
const nonBlocking = isNonBlockingMode(config2);
|
|
8129
|
-
if (nonBlocking) {
|
|
8130
|
-
lines.push(
|
|
8131
|
-
`- CybeDefend: ${total === null ? "proposal inbox not checked" : `**${total}** pending proposals`} \u2014 no action required.`,
|
|
8132
|
-
`- ${NON_BLOCKING_INBOX_DIRECTIVE}`
|
|
8133
|
-
);
|
|
8134
|
-
} else if (total === null) {
|
|
8135
|
-
lines.push(
|
|
8136
|
-
"- CybeDefend: could not fetch proposal-inbox status (token / API unreachable).",
|
|
8137
|
-
'- Call `cybe_rules_list_proposals(projectId, status="proposed")` yourself to verify, then handle each surfaced proposal via AskUserQuestion (Accept / Reject / Skip / Tell me more) before continuing.'
|
|
8138
|
-
);
|
|
8139
|
-
} else if (total > 0) {
|
|
8140
|
-
lines.push(
|
|
8141
|
-
`- CybeDefend: **${total}** pending proposals.`,
|
|
8142
|
-
'- Call `cybe_rules_list_proposals(projectId, status="proposed")` and surface each via AskUserQuestion (Accept / Reject / Skip / Tell me more) BEFORE responding to this prompt.'
|
|
8143
|
-
);
|
|
8144
|
-
} else {
|
|
8145
|
-
lines.push(
|
|
8146
|
-
"- CybeDefend: **0** pending proposals.",
|
|
8147
|
-
'- You MUST still acknowledge step 0 in your reply ("No pending business-rule proposals."). Silently skipping this step is a doctrine violation observed in earlier sessions.'
|
|
8148
|
-
);
|
|
8149
|
-
}
|
|
8150
|
-
lines.push(
|
|
8151
|
-
"",
|
|
8152
|
-
"### Step 1 \u2014 Rules fetch (before any code edit)",
|
|
8153
|
-
"- Even if you plan to brainstorm / explore / ask clarifying questions first, call BOTH:",
|
|
8154
|
-
' - `cybe_rules_fetch(projectId, files=[...], intent="<1-2 sentence narrative>")` for business rules',
|
|
8155
|
-
' - `cybe_secrules_fetch(projectId, files=[...], intent="...", languages=[...])` for security rules',
|
|
8156
|
-
'- Use a rich `intent` \u2014 the retrieval is 60% graph + 40% vector, so a generic placeholder like "Editing file" returns nothing useful.',
|
|
8157
|
-
"- The PreToolUse hook fires automatically as a backstop on Edit/Write/MultiEdit, but your explicit call with a narrative intent gets better matches.",
|
|
8158
|
-
"",
|
|
8159
|
-
"### Order",
|
|
8160
|
-
nonBlocking ? "1. Step 0 needs no action (non-blocking mode)." : "1. Satisfy step 0 (acknowledge / handle the inbox).",
|
|
8161
|
-
"2. Satisfy step 1 (fetch rules with a narrative intent) once you know which files you will touch.",
|
|
8162
|
-
"3. THEN proceed with whatever skill / brainstorm / implementation flow fits the task.",
|
|
8163
|
-
""
|
|
8164
|
-
);
|
|
8165
|
-
emitFn(lines.join("\n"), event.client);
|
|
8166
|
-
if (sessionId !== null) {
|
|
8167
|
-
try {
|
|
8168
|
-
await sessionTracker.markSeen(sessionId);
|
|
8169
|
-
} catch {
|
|
8170
|
-
}
|
|
8171
|
-
}
|
|
8172
|
-
}
|
|
8173
|
-
|
|
8174
8205
|
// src/hooks/runtime/pre-invocation.ts
|
|
8175
8206
|
var STASH_SEPARATOR = "\n\n---\n\n";
|
|
8176
8207
|
async function preInvocationHook(deps = {}) {
|
|
@@ -11645,15 +11676,15 @@ function resolveCandidatePaths(rawPath, opts) {
|
|
|
11645
11676
|
// src/hooks/runtime/session-writes.ts
|
|
11646
11677
|
import {
|
|
11647
11678
|
existsSync as existsSync17,
|
|
11648
|
-
mkdirSync as
|
|
11649
|
-
readFileSync as
|
|
11679
|
+
mkdirSync as mkdirSync10,
|
|
11680
|
+
readFileSync as readFileSync18,
|
|
11650
11681
|
renameSync as renameSync2,
|
|
11651
11682
|
rmdirSync,
|
|
11652
|
-
statSync as
|
|
11683
|
+
statSync as statSync4,
|
|
11653
11684
|
writeFileSync as writeFileSync11
|
|
11654
11685
|
} from "node:fs";
|
|
11655
|
-
import { homedir as
|
|
11656
|
-
import { join as
|
|
11686
|
+
import { homedir as homedir15 } from "node:os";
|
|
11687
|
+
import { join as join16, posix } from "node:path";
|
|
11657
11688
|
var DEFAULT_MAX_PATHS = 500;
|
|
11658
11689
|
var DEFAULT_SESSION_WRITES_TTL_MS = 4 * 60 * 60 * 1e3;
|
|
11659
11690
|
var SESSION_WRITES_FILE = "guards-session-writes.json";
|
|
@@ -11667,11 +11698,11 @@ function withLock(lockDir, fn) {
|
|
|
11667
11698
|
let held = false;
|
|
11668
11699
|
while (!held) {
|
|
11669
11700
|
try {
|
|
11670
|
-
|
|
11701
|
+
mkdirSync10(lockDir);
|
|
11671
11702
|
held = true;
|
|
11672
11703
|
} catch {
|
|
11673
11704
|
try {
|
|
11674
|
-
if (Date.now() -
|
|
11705
|
+
if (Date.now() - statSync4(lockDir).mtimeMs > LOCK_STALE_MS) {
|
|
11675
11706
|
rmdirSync(lockDir);
|
|
11676
11707
|
continue;
|
|
11677
11708
|
}
|
|
@@ -11694,7 +11725,7 @@ function withLock(lockDir, fn) {
|
|
|
11694
11725
|
}
|
|
11695
11726
|
}
|
|
11696
11727
|
function defaultDir() {
|
|
11697
|
-
return process.env.CYBEDEFEND_BASELINE_DIR ??
|
|
11728
|
+
return process.env.CYBEDEFEND_BASELINE_DIR ?? join16(homedir15(), ".cybedefend");
|
|
11698
11729
|
}
|
|
11699
11730
|
function normalizePath(p) {
|
|
11700
11731
|
if (typeof p !== "string") return "";
|
|
@@ -11729,14 +11760,14 @@ function coerce(raw) {
|
|
|
11729
11760
|
}
|
|
11730
11761
|
function makeSessionWritesStore(opts = {}) {
|
|
11731
11762
|
const dir = opts.dir ?? defaultDir();
|
|
11732
|
-
const file2 =
|
|
11763
|
+
const file2 = join16(dir, SESSION_WRITES_FILE);
|
|
11733
11764
|
const now = opts.now ?? (() => Date.now());
|
|
11734
11765
|
const maxPaths = typeof opts.maxPaths === "number" && opts.maxPaths > 0 ? Math.floor(opts.maxPaths) : DEFAULT_MAX_PATHS;
|
|
11735
11766
|
const ttlMs = typeof opts.ttlMs === "number" && opts.ttlMs > 0 ? opts.ttlMs : DEFAULT_SESSION_WRITES_TTL_MS;
|
|
11736
11767
|
function readAll() {
|
|
11737
11768
|
if (!existsSync17(file2)) return {};
|
|
11738
11769
|
try {
|
|
11739
|
-
return coerce(JSON.parse(
|
|
11770
|
+
return coerce(JSON.parse(readFileSync18(file2, "utf8")));
|
|
11740
11771
|
} catch {
|
|
11741
11772
|
return {};
|
|
11742
11773
|
}
|
|
@@ -11751,7 +11782,7 @@ function makeSessionWritesStore(opts = {}) {
|
|
|
11751
11782
|
}
|
|
11752
11783
|
function writeAll(all) {
|
|
11753
11784
|
try {
|
|
11754
|
-
if (!existsSync17(dir))
|
|
11785
|
+
if (!existsSync17(dir)) mkdirSync10(dir, { recursive: true });
|
|
11755
11786
|
const tmp = `${file2}.${process.pid}.tmp`;
|
|
11756
11787
|
writeFileSync11(tmp, JSON.stringify(all), "utf8");
|
|
11757
11788
|
renameSync2(tmp, file2);
|
|
@@ -11764,7 +11795,7 @@ function makeSessionWritesStore(opts = {}) {
|
|
|
11764
11795
|
const usable = paths.filter(isUsable);
|
|
11765
11796
|
if (usable.length === 0) return;
|
|
11766
11797
|
try {
|
|
11767
|
-
if (!existsSync17(dir))
|
|
11798
|
+
if (!existsSync17(dir)) mkdirSync10(dir, { recursive: true });
|
|
11768
11799
|
withLock(`${file2}.lock`, () => {
|
|
11769
11800
|
const t = now();
|
|
11770
11801
|
const all = pruneExpired(readAll(), t);
|
|
@@ -12080,10 +12111,10 @@ function nearMiss(req, rule) {
|
|
|
12080
12111
|
import { isAbsolute as isAbsolute6, resolve as resolvePath4 } from "node:path";
|
|
12081
12112
|
|
|
12082
12113
|
// src/hooks/runtime/guard-rules-cache.ts
|
|
12083
|
-
import { readFileSync as
|
|
12084
|
-
import { dirname as
|
|
12085
|
-
import { homedir as
|
|
12086
|
-
import { join as
|
|
12114
|
+
import { readFileSync as readFileSync19, writeFileSync as writeFileSync12, existsSync as existsSync18, mkdirSync as mkdirSync11 } from "node:fs";
|
|
12115
|
+
import { dirname as dirname10 } from "node:path";
|
|
12116
|
+
import { homedir as homedir16 } from "node:os";
|
|
12117
|
+
import { join as join17 } from "node:path";
|
|
12087
12118
|
|
|
12088
12119
|
// node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/external.js
|
|
12089
12120
|
var external_exports = {};
|
|
@@ -31920,8 +31951,8 @@ function tokenFingerprint(token) {
|
|
|
31920
31951
|
}
|
|
31921
31952
|
|
|
31922
31953
|
// src/hooks/runtime/guard-rules-cache.ts
|
|
31923
|
-
var DEFAULT_CACHE_FILE =
|
|
31924
|
-
|
|
31954
|
+
var DEFAULT_CACHE_FILE = join17(
|
|
31955
|
+
homedir16(),
|
|
31925
31956
|
".cybedefend",
|
|
31926
31957
|
"guards-cache.json"
|
|
31927
31958
|
);
|
|
@@ -31996,7 +32027,7 @@ function reportDroppedRules(dropped) {
|
|
|
31996
32027
|
}
|
|
31997
32028
|
function makeGuardRulesCache(opts) {
|
|
31998
32029
|
const cacheFile = opts.cacheFile ?? DEFAULT_CACHE_FILE;
|
|
31999
|
-
const failuresFile = opts.failuresFile ??
|
|
32030
|
+
const failuresFile = opts.failuresFile ?? join17(dirname10(cacheFile), "guards-cache-failures.json");
|
|
32000
32031
|
const staleSec = opts.staleSec ?? DEFAULT_STALE_SEC;
|
|
32001
32032
|
const fetchFn = opts.fetchFn;
|
|
32002
32033
|
const clock = opts.now ?? Date.now;
|
|
@@ -32101,7 +32132,7 @@ function makeGuardRulesCache(opts) {
|
|
|
32101
32132
|
function readCache(projectId) {
|
|
32102
32133
|
if (!existsSync18(cacheFile)) return null;
|
|
32103
32134
|
try {
|
|
32104
|
-
const raw =
|
|
32135
|
+
const raw = readFileSync19(cacheFile, "utf8");
|
|
32105
32136
|
const data = JSON.parse(raw);
|
|
32106
32137
|
if (data.projectId !== projectId) return null;
|
|
32107
32138
|
return data;
|
|
@@ -32112,7 +32143,7 @@ function makeGuardRulesCache(opts) {
|
|
|
32112
32143
|
function readFailures() {
|
|
32113
32144
|
try {
|
|
32114
32145
|
if (!existsSync18(failuresFile)) return {};
|
|
32115
|
-
const parsed = JSON.parse(
|
|
32146
|
+
const parsed = JSON.parse(readFileSync19(failuresFile, "utf8"));
|
|
32116
32147
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
32117
32148
|
return {};
|
|
32118
32149
|
}
|
|
@@ -32152,9 +32183,9 @@ function makeGuardRulesCache(opts) {
|
|
|
32152
32183
|
return { refreshIfStale };
|
|
32153
32184
|
}
|
|
32154
32185
|
function ensureDirFor2(filePath) {
|
|
32155
|
-
const dir =
|
|
32186
|
+
const dir = dirname10(filePath);
|
|
32156
32187
|
if (!existsSync18(dir)) {
|
|
32157
|
-
|
|
32188
|
+
mkdirSync11(dir, { recursive: true });
|
|
32158
32189
|
}
|
|
32159
32190
|
}
|
|
32160
32191
|
var DEFAULT_TIMEOUT_MS2 = 8e3;
|
|
@@ -32294,11 +32325,11 @@ function detectPromptInjection(text) {
|
|
|
32294
32325
|
}
|
|
32295
32326
|
|
|
32296
32327
|
// src/hooks/runtime/judge-cache.ts
|
|
32297
|
-
import { readFileSync as
|
|
32298
|
-
import { dirname as
|
|
32299
|
-
import { homedir as
|
|
32300
|
-
var DEFAULT_JUDGE_CACHE_FILE =
|
|
32301
|
-
|
|
32328
|
+
import { readFileSync as readFileSync20, writeFileSync as writeFileSync13, existsSync as existsSync19, mkdirSync as mkdirSync12 } from "node:fs";
|
|
32329
|
+
import { dirname as dirname11, join as join18 } from "node:path";
|
|
32330
|
+
import { homedir as homedir17 } from "node:os";
|
|
32331
|
+
var DEFAULT_JUDGE_CACHE_FILE = join18(
|
|
32332
|
+
homedir17(),
|
|
32302
32333
|
".cybedefend",
|
|
32303
32334
|
"guards-judge-cache.json"
|
|
32304
32335
|
);
|
|
@@ -32311,7 +32342,7 @@ function makeJudgeCache(opts = {}) {
|
|
|
32311
32342
|
function readAll() {
|
|
32312
32343
|
if (!existsSync19(cacheFile)) return {};
|
|
32313
32344
|
try {
|
|
32314
|
-
return JSON.parse(
|
|
32345
|
+
return JSON.parse(readFileSync20(cacheFile, "utf8"));
|
|
32315
32346
|
} catch {
|
|
32316
32347
|
return {};
|
|
32317
32348
|
}
|
|
@@ -32342,36 +32373,36 @@ function makeJudgeCache(opts = {}) {
|
|
|
32342
32373
|
return { get, set: set2 };
|
|
32343
32374
|
}
|
|
32344
32375
|
function ensureDirFor3(filePath) {
|
|
32345
|
-
const dir =
|
|
32376
|
+
const dir = dirname11(filePath);
|
|
32346
32377
|
if (!existsSync19(dir)) {
|
|
32347
|
-
|
|
32378
|
+
mkdirSync12(dir, { recursive: true });
|
|
32348
32379
|
}
|
|
32349
32380
|
}
|
|
32350
32381
|
|
|
32351
32382
|
// src/hooks/runtime/guard-check.ts
|
|
32352
32383
|
import { spawn as spawn3 } from "node:child_process";
|
|
32353
|
-
import { homedir as
|
|
32354
|
-
import { join as
|
|
32384
|
+
import { homedir as homedir20 } from "node:os";
|
|
32385
|
+
import { join as join21 } from "node:path";
|
|
32355
32386
|
|
|
32356
32387
|
// src/hooks/runtime/guard-violations-buffer.ts
|
|
32357
32388
|
import {
|
|
32358
32389
|
appendFileSync as appendFileSync2,
|
|
32359
|
-
closeSync as
|
|
32390
|
+
closeSync as closeSync4,
|
|
32360
32391
|
existsSync as existsSync20,
|
|
32361
|
-
openSync as
|
|
32362
|
-
readFileSync as
|
|
32392
|
+
openSync as openSync4,
|
|
32393
|
+
readFileSync as readFileSync21,
|
|
32363
32394
|
writeFileSync as writeFileSync14,
|
|
32364
|
-
writeSync as
|
|
32365
|
-
mkdirSync as
|
|
32395
|
+
writeSync as writeSync4,
|
|
32396
|
+
mkdirSync as mkdirSync13,
|
|
32366
32397
|
rmSync as rmSync3,
|
|
32367
|
-
statSync as
|
|
32398
|
+
statSync as statSync5,
|
|
32368
32399
|
utimesSync as utimesSync2
|
|
32369
32400
|
} from "node:fs";
|
|
32370
|
-
import { dirname as
|
|
32371
|
-
import { homedir as
|
|
32372
|
-
import { join as
|
|
32373
|
-
var DEFAULT_BUFFER_FILE =
|
|
32374
|
-
|
|
32401
|
+
import { dirname as dirname12 } from "node:path";
|
|
32402
|
+
import { homedir as homedir18 } from "node:os";
|
|
32403
|
+
import { join as join19 } from "node:path";
|
|
32404
|
+
var DEFAULT_BUFFER_FILE = join19(
|
|
32405
|
+
homedir18(),
|
|
32375
32406
|
".cybedefend",
|
|
32376
32407
|
"guards-violations-buffer.jsonl"
|
|
32377
32408
|
);
|
|
@@ -32382,8 +32413,8 @@ var MAX_RECORD_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
|
32382
32413
|
var FLUSH_LOCK_STALE_MS = 6e4;
|
|
32383
32414
|
function makeViolationsBuffer(opts = {}) {
|
|
32384
32415
|
const bufferFile = opts.bufferFile ?? DEFAULT_BUFFER_FILE;
|
|
32385
|
-
const holdsFile = opts.holdsFile ??
|
|
32386
|
-
const lockFile = opts.lockFile ??
|
|
32416
|
+
const holdsFile = opts.holdsFile ?? join19(dirname12(bufferFile), "guards-violations-holds.json");
|
|
32417
|
+
const lockFile = opts.lockFile ?? join19(dirname12(bufferFile), "guards-violations-flush.lock");
|
|
32387
32418
|
const now = opts.now ?? Date.now;
|
|
32388
32419
|
function bufferViolation2(ctx, v) {
|
|
32389
32420
|
const record2 = {
|
|
@@ -32497,7 +32528,7 @@ function makeViolationsBuffer(opts = {}) {
|
|
|
32497
32528
|
}
|
|
32498
32529
|
function readBuffer() {
|
|
32499
32530
|
try {
|
|
32500
|
-
const raw =
|
|
32531
|
+
const raw = readFileSync21(bufferFile);
|
|
32501
32532
|
return { content: raw.toString("utf8"), bytes: raw.length };
|
|
32502
32533
|
} catch {
|
|
32503
32534
|
return null;
|
|
@@ -32505,7 +32536,7 @@ function makeViolationsBuffer(opts = {}) {
|
|
|
32505
32536
|
}
|
|
32506
32537
|
function appendedSince(bytes) {
|
|
32507
32538
|
try {
|
|
32508
|
-
const raw =
|
|
32539
|
+
const raw = readFileSync21(bufferFile);
|
|
32509
32540
|
return raw.length > bytes ? raw.subarray(bytes).toString("utf8") : "";
|
|
32510
32541
|
} catch {
|
|
32511
32542
|
return "";
|
|
@@ -32519,11 +32550,11 @@ function makeViolationsBuffer(opts = {}) {
|
|
|
32519
32550
|
}
|
|
32520
32551
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
32521
32552
|
try {
|
|
32522
|
-
const fd =
|
|
32553
|
+
const fd = openSync4(lockFile, "wx");
|
|
32523
32554
|
try {
|
|
32524
|
-
|
|
32555
|
+
writeSync4(fd, String(process.pid));
|
|
32525
32556
|
} finally {
|
|
32526
|
-
|
|
32557
|
+
closeSync4(fd);
|
|
32527
32558
|
}
|
|
32528
32559
|
return true;
|
|
32529
32560
|
} catch (e) {
|
|
@@ -32540,7 +32571,7 @@ function makeViolationsBuffer(opts = {}) {
|
|
|
32540
32571
|
}
|
|
32541
32572
|
function lockIsStale() {
|
|
32542
32573
|
try {
|
|
32543
|
-
return Date.now() -
|
|
32574
|
+
return Date.now() - statSync5(lockFile).mtimeMs > FLUSH_LOCK_STALE_MS;
|
|
32544
32575
|
} catch {
|
|
32545
32576
|
return true;
|
|
32546
32577
|
}
|
|
@@ -32567,7 +32598,7 @@ function makeViolationsBuffer(opts = {}) {
|
|
|
32567
32598
|
function readHolds() {
|
|
32568
32599
|
try {
|
|
32569
32600
|
if (!existsSync20(holdsFile)) return {};
|
|
32570
|
-
const parsed = JSON.parse(
|
|
32601
|
+
const parsed = JSON.parse(readFileSync21(holdsFile, "utf8"));
|
|
32571
32602
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
32572
32603
|
return {};
|
|
32573
32604
|
}
|
|
@@ -32627,9 +32658,9 @@ function capRecords(records, now) {
|
|
|
32627
32658
|
return dated.slice(-MAX_BUFFERED_RECORDS).map(({ record: record2 }) => record2);
|
|
32628
32659
|
}
|
|
32629
32660
|
function ensureDirFor4(filePath) {
|
|
32630
|
-
const dir =
|
|
32661
|
+
const dir = dirname12(filePath);
|
|
32631
32662
|
if (!existsSync20(dir)) {
|
|
32632
|
-
|
|
32663
|
+
mkdirSync13(dir, { recursive: true });
|
|
32633
32664
|
}
|
|
32634
32665
|
}
|
|
32635
32666
|
var _defaultBuffer = makeViolationsBuffer();
|
|
@@ -32638,9 +32669,9 @@ var flushViolations = _defaultBuffer.flushViolations.bind(_defaultBuffer);
|
|
|
32638
32669
|
var liftViolationHolds = _defaultBuffer.liftHolds.bind(_defaultBuffer);
|
|
32639
32670
|
|
|
32640
32671
|
// src/hooks/runtime/unmapped-tools.ts
|
|
32641
|
-
import { existsSync as existsSync21, mkdirSync as
|
|
32642
|
-
import { dirname as
|
|
32643
|
-
import { homedir as
|
|
32672
|
+
import { existsSync as existsSync21, mkdirSync as mkdirSync14, readFileSync as readFileSync22, writeFileSync as writeFileSync15 } from "node:fs";
|
|
32673
|
+
import { dirname as dirname13, join as join20 } from "node:path";
|
|
32674
|
+
import { homedir as homedir19 } from "node:os";
|
|
32644
32675
|
var TARGETLESS_TOOL_RE = /^(?:ToolSearch|TodoRead|TodoWrite|Task|Agent|AskUserQuestion|Skill|SlashCommand|EnterPlanMode|ExitPlanMode|EnterWorktree|ExitWorktree|BashOutput|KillShell|KillBash|Monitor|ListMcpResourcesTool|ReadMcpResourceTool|ReadMcpResourceDirTool|ScheduleWakeup|PushNotification|CronCreate|CronDelete|CronList|SendMessage|ListAgents|TaskOutput|TaskStop|ReportFindings|Workflow)$/;
|
|
32645
32676
|
var OWN_MCP_TOOL_RE = /^mcp__cybedefend(?:-[A-Za-z0-9_-]+)?__/;
|
|
32646
32677
|
function isTargetlessTool(tool) {
|
|
@@ -32652,13 +32683,13 @@ function strictUnmappedPolicy() {
|
|
|
32652
32683
|
}
|
|
32653
32684
|
var MAX_TOOLS = 200;
|
|
32654
32685
|
function defaultUnmappedToolsFile() {
|
|
32655
|
-
const dir = process.env.CYBEDEFEND_BASELINE_DIR ??
|
|
32656
|
-
return
|
|
32686
|
+
const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join20(homedir19(), ".cybedefend");
|
|
32687
|
+
return join20(dir, "guards-unmapped-tools.json");
|
|
32657
32688
|
}
|
|
32658
32689
|
function load(file2) {
|
|
32659
32690
|
try {
|
|
32660
32691
|
if (!existsSync21(file2)) return { tools: {} };
|
|
32661
|
-
const parsed = JSON.parse(
|
|
32692
|
+
const parsed = JSON.parse(readFileSync22(file2, "utf8"));
|
|
32662
32693
|
if (!parsed || typeof parsed !== "object" || typeof parsed.tools !== "object" || !parsed.tools) {
|
|
32663
32694
|
return { tools: {} };
|
|
32664
32695
|
}
|
|
@@ -32682,7 +32713,7 @@ function makeUnmappedToolTelemetry(file2 = defaultUnmappedToolsFile()) {
|
|
|
32682
32713
|
if (names.length > MAX_TOOLS) {
|
|
32683
32714
|
names.sort((a, b) => data.tools[a].lastSeen.localeCompare(data.tools[b].lastSeen)).slice(0, names.length - MAX_TOOLS).forEach((n) => delete data.tools[n]);
|
|
32684
32715
|
}
|
|
32685
|
-
|
|
32716
|
+
mkdirSync14(dirname13(file2), { recursive: true });
|
|
32686
32717
|
writeFileSync15(file2, JSON.stringify(data, null, 2) + "\n", "utf8");
|
|
32687
32718
|
} catch {
|
|
32688
32719
|
}
|
|
@@ -32748,11 +32779,11 @@ function appendDebugLog(entry) {
|
|
|
32748
32779
|
try {
|
|
32749
32780
|
const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "";
|
|
32750
32781
|
if (!homeDir) return;
|
|
32751
|
-
const { mkdirSync:
|
|
32752
|
-
const { join:
|
|
32753
|
-
const dir =
|
|
32754
|
-
|
|
32755
|
-
appendFileSync3(
|
|
32782
|
+
const { mkdirSync: mkdirSync15, appendFileSync: appendFileSync3 } = __require("node:fs");
|
|
32783
|
+
const { join: join22 } = __require("node:path");
|
|
32784
|
+
const dir = join22(homeDir, ".cybedefend");
|
|
32785
|
+
mkdirSync15(dir, { recursive: true });
|
|
32786
|
+
appendFileSync3(join22(dir, "hook-debug.log"), entry + "\n", "utf8");
|
|
32756
32787
|
} catch {
|
|
32757
32788
|
}
|
|
32758
32789
|
}
|
|
@@ -33311,7 +33342,7 @@ async function runCatchJudgeStep(args) {
|
|
|
33311
33342
|
message
|
|
33312
33343
|
};
|
|
33313
33344
|
}
|
|
33314
|
-
function emitUnverifiedBanner(reason, client) {
|
|
33345
|
+
function emitUnverifiedBanner(reason, client, userNotice) {
|
|
33315
33346
|
const banner = [
|
|
33316
33347
|
"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
|
|
33317
33348
|
"\u2588 VibeDefend Action Guards \u2014 UNVERIFIED \u2588",
|
|
@@ -33329,16 +33360,24 @@ function emitUnverifiedBanner(reason, client) {
|
|
|
33329
33360
|
].join("\n") + "\n";
|
|
33330
33361
|
process.stderr.write(banner);
|
|
33331
33362
|
const isCodex = typeof process.env.CODEX_SANDBOX !== "undefined" || typeof process.env.CODEX_AGENT !== "undefined";
|
|
33332
|
-
|
|
33333
|
-
|
|
33334
|
-
|
|
33363
|
+
const withContext = isCodex && client !== "antigravity";
|
|
33364
|
+
if (!withContext && !userNotice) return;
|
|
33365
|
+
try {
|
|
33366
|
+
const ctx = JSON.stringify({
|
|
33367
|
+
...userNotice ? { systemMessage: userNotice } : {},
|
|
33368
|
+
...withContext ? {
|
|
33335
33369
|
additionalContext: `VibeDefend Action Guards UNVERIFIED \u2014 ${reason} Tool call allowed WITHOUT enforcement. Run \`vibedefend login\` to restore protection.`
|
|
33336
|
-
}
|
|
33337
|
-
|
|
33338
|
-
|
|
33339
|
-
|
|
33370
|
+
} : {}
|
|
33371
|
+
});
|
|
33372
|
+
process.stdout.write(ctx + "\n");
|
|
33373
|
+
} catch {
|
|
33340
33374
|
}
|
|
33341
33375
|
}
|
|
33376
|
+
async function claimUserNotice(mcpName, envelope, client) {
|
|
33377
|
+
if (!SYSTEM_MESSAGE_CLIENTS.has(client)) return void 0;
|
|
33378
|
+
return await claimSignInNotice(mcpName, sessionIdOf3(envelope, client)) ? SIGN_IN_NOTICE : void 0;
|
|
33379
|
+
}
|
|
33380
|
+
var agentMessageWritten = false;
|
|
33342
33381
|
function sessionIdOf3(envelope, client) {
|
|
33343
33382
|
if (typeof envelope.session_id === "string") return envelope.session_id;
|
|
33344
33383
|
if (typeof envelope.sessionId === "string") return envelope.sessionId;
|
|
@@ -33619,23 +33658,24 @@ function emitAgentMessage(verdict, message, client) {
|
|
|
33619
33658
|
// Codex
|
|
33620
33659
|
additionalContext: fullMessage
|
|
33621
33660
|
};
|
|
33661
|
+
agentMessageWritten = true;
|
|
33622
33662
|
process.stdout.write(JSON.stringify(payload) + "\n");
|
|
33623
33663
|
} catch {
|
|
33624
33664
|
}
|
|
33625
33665
|
}
|
|
33626
33666
|
function makeProductionJudgeDeps() {
|
|
33627
33667
|
const cache = makeJudgeCache();
|
|
33628
|
-
const warnDir = process.env.CYBEDEFEND_BASELINE_DIR ??
|
|
33668
|
+
const warnDir = process.env.CYBEDEFEND_BASELINE_DIR ?? join21(homedir20(), ".cybedefend");
|
|
33629
33669
|
const scriptCache = makeJudgeCache({
|
|
33630
|
-
cacheFile:
|
|
33670
|
+
cacheFile: join21(warnDir, "guards-judge-script-cache.json"),
|
|
33631
33671
|
ttlMs: SCRIPT_VERDICT_TTL_MS,
|
|
33632
33672
|
maxEntries: SCRIPT_VERDICT_MAX_ENTRIES
|
|
33633
33673
|
});
|
|
33634
33674
|
const warnTracker = defaultSessionTracker(
|
|
33635
|
-
|
|
33675
|
+
join21(warnDir, "guards-judge-warned-sessions.json")
|
|
33636
33676
|
);
|
|
33637
33677
|
const blockedTracker = defaultSessionTracker(
|
|
33638
|
-
|
|
33678
|
+
join21(warnDir, "guards-judge-blocked-sessions.json")
|
|
33639
33679
|
);
|
|
33640
33680
|
return {
|
|
33641
33681
|
usage: {
|
|
@@ -33663,8 +33703,8 @@ function makeProductionJudgeDeps() {
|
|
|
33663
33703
|
}
|
|
33664
33704
|
function makeProductionUnmappedDeps() {
|
|
33665
33705
|
const telemetry = makeUnmappedToolTelemetry();
|
|
33666
|
-
const dir = process.env.CYBEDEFEND_BASELINE_DIR ??
|
|
33667
|
-
const tracker = defaultSessionTracker(
|
|
33706
|
+
const dir = process.env.CYBEDEFEND_BASELINE_DIR ?? join21(homedir20(), ".cybedefend");
|
|
33707
|
+
const tracker = defaultSessionTracker(join21(dir, "guards-unmapped-notified.json"));
|
|
33668
33708
|
return {
|
|
33669
33709
|
record: telemetry.record,
|
|
33670
33710
|
noticeOnce: (sessionId, tool) => {
|
|
@@ -33692,6 +33732,7 @@ function makeSessionWritesPort(sessionId) {
|
|
|
33692
33732
|
}
|
|
33693
33733
|
async function runPreToolUseGuard() {
|
|
33694
33734
|
try {
|
|
33735
|
+
agentMessageWritten = false;
|
|
33695
33736
|
const envelope = await readStdinJson();
|
|
33696
33737
|
const config2 = loadRuntimeConfig();
|
|
33697
33738
|
if (!config2) return 0;
|
|
@@ -33703,11 +33744,7 @@ async function runPreToolUseGuard() {
|
|
|
33703
33744
|
);
|
|
33704
33745
|
if (!projectId) return 0;
|
|
33705
33746
|
const apiBaseResolved = process.env.CYBEDEFEND_API_BASE ?? configApiBase ?? config2.region.apiBase;
|
|
33706
|
-
const token = await resolveTokenWithRefresh(
|
|
33707
|
-
config2.region.mcpName,
|
|
33708
|
-
{},
|
|
33709
|
-
{ mcpUrl: config2.region.mcpUrl }
|
|
33710
|
-
);
|
|
33747
|
+
const token = await resolveTokenWithRefresh(config2.region.mcpName);
|
|
33711
33748
|
const cache = makeGuardRulesCache({
|
|
33712
33749
|
fetchFn: (ctx) => fetchEffectiveRulesFromGateway(ctx)
|
|
33713
33750
|
});
|
|
@@ -33717,9 +33754,11 @@ async function runPreToolUseGuard() {
|
|
|
33717
33754
|
apiBaseResolved
|
|
33718
33755
|
});
|
|
33719
33756
|
if (!token && rulesOutcome.kind === "unavailable") {
|
|
33757
|
+
const client = sniffCaller(envelope).client;
|
|
33720
33758
|
emitUnverifiedBanner(
|
|
33721
33759
|
"Not authenticated \u2014 run `vibedefend login` to restore Action Guards.",
|
|
33722
|
-
|
|
33760
|
+
client,
|
|
33761
|
+
await claimUserNotice(config2.region.mcpName, envelope, client)
|
|
33723
33762
|
);
|
|
33724
33763
|
return 0;
|
|
33725
33764
|
}
|
|
@@ -33763,6 +33802,10 @@ async function runPreToolUseGuard() {
|
|
|
33763
33802
|
usageNotifier: makeUsageNotifier({ write: () => void 0 })
|
|
33764
33803
|
});
|
|
33765
33804
|
if (token) scheduleViolationsFlush({ buffer, token, apiBaseResolved });
|
|
33805
|
+
if (!token && exitCode === 0 && !agentMessageWritten) {
|
|
33806
|
+
const notice = await claimUserNotice(config2.region.mcpName, envelope, sniffCaller(envelope).client);
|
|
33807
|
+
if (notice) process.stdout.write(JSON.stringify({ systemMessage: notice }) + "\n");
|
|
33808
|
+
}
|
|
33766
33809
|
return exitCode;
|
|
33767
33810
|
} catch {
|
|
33768
33811
|
return 0;
|
|
@@ -33794,9 +33837,7 @@ async function runViolationsFlush(deps = {}) {
|
|
|
33794
33837
|
try {
|
|
33795
33838
|
const config2 = (deps.loadConfig ?? loadRuntimeConfig)();
|
|
33796
33839
|
if (!config2) return;
|
|
33797
|
-
const token = (deps.resolveTokenFn ?? resolveToken)(config2.region.mcpName
|
|
33798
|
-
mcpUrl: config2.region.mcpUrl
|
|
33799
|
-
});
|
|
33840
|
+
const token = (deps.resolveTokenFn ?? resolveToken)(config2.region.mcpName);
|
|
33800
33841
|
if (!token) return;
|
|
33801
33842
|
const apiBaseResolved = process.env.CYBEDEFEND_API_BASE ?? config2.region.apiBase;
|
|
33802
33843
|
await (deps.buffer ?? makeViolationsBuffer()).flushViolations(
|