@hasna/hooks 0.12.22 → 0.13.0
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/README.md +36 -0
- package/bin/hooks/scratch-lifecycle.js +5 -5
- package/bin/hooks/stop-review.js +23 -8
- package/bin/hooks-mcp.js +1901 -1213
- package/bin/index.js +3355 -1978
- package/bin/native-safety-entry.js +37 -37
- package/bin/native-safety-worker.cjs +37 -37
- package/bin/serve.js +125 -121
- package/dist/index.js +2304 -1548
- package/dist/lib/claude-skills-coordination.d.ts +1 -1
- package/dist/lib/installer.d.ts +44 -5
- package/dist/lib/manifest.d.ts +21 -0
- package/dist/lib/native-safety.d.ts +24 -0
- package/dist/lib/native-target.d.ts +11 -2
- package/dist/lib/registry.d.ts +12 -0
- package/dist/lib/sumi-stop-plugin.d.ts +4 -0
- package/dist/lib/target-adapters.d.ts +151 -0
- package/dist/lib/targets.d.ts +99 -0
- package/dist/native-readiness.js +11 -11
- package/dist/native-safety.js +183 -24
- package/dist/opencode-stop-plugin.js +17 -7
- package/dist/sdk/index.js +60 -16
- package/dist/storage.js +34 -34
- package/dist/sumi-stop-plugin.js +29 -10
- package/hooks/hook-announce-stop/src/hook.ts +91 -15
- package/hooks/hook-stop-review/README.md +7 -0
- package/hooks/hook-stop-review/src/policy.ts +21 -4
- package/hooks/hook-stop-review/src/runtime.ts +4 -3
- package/hooks/hook-stop-review/src/types.ts +6 -0
- package/hooks/hook-trash-guard/src/hook.ts +108 -12
- package/package.json +2 -2
package/bin/hooks-mcp.js
CHANGED
|
@@ -891,6 +891,8 @@ var init_manifest = __esm(() => {
|
|
|
891
891
|
script_kind: z.enum(["inline", "file"]).optional(),
|
|
892
892
|
args: z.array(z.string()).optional(),
|
|
893
893
|
nativeTargetDispatch: z.boolean().optional(),
|
|
894
|
+
requires_final_message: z.boolean().optional(),
|
|
895
|
+
requires_block: z.boolean().optional(),
|
|
894
896
|
timeout_ms: z.number().int().positive().optional(),
|
|
895
897
|
env: z.record(z.string(), z.string()).optional()
|
|
896
898
|
});
|
|
@@ -910,11 +912,11 @@ var init_manifest = __esm(() => {
|
|
|
910
912
|
// src/lib/resolve.ts
|
|
911
913
|
var exports_resolve = {};
|
|
912
914
|
__export(exports_resolve, {
|
|
913
|
-
|
|
914
|
-
resolveHookMeta: () => resolveHookMeta,
|
|
915
|
-
resolveHookDir: () => resolveHookDir,
|
|
915
|
+
resolveBundledHooksDir: () => resolveBundledHooksDir,
|
|
916
916
|
resolveHook: () => resolveHook,
|
|
917
|
-
|
|
917
|
+
resolveHookDir: () => resolveHookDir,
|
|
918
|
+
resolveHookMeta: () => resolveHookMeta,
|
|
919
|
+
resolveScriptPath: () => resolveScriptPath
|
|
918
920
|
});
|
|
919
921
|
import { dirname as dirname2, join as join4 } from "path";
|
|
920
922
|
import { existsSync as existsSync3 } from "fs";
|
|
@@ -972,6 +974,8 @@ function resolveHookMeta(name) {
|
|
|
972
974
|
matcher: "",
|
|
973
975
|
tags: ["custom"],
|
|
974
976
|
nativeTargetDispatch: manifest.nativeTargetDispatch,
|
|
977
|
+
requiresFinalMessage: manifest.requires_final_message,
|
|
978
|
+
requiresBlock: manifest.requires_block,
|
|
975
979
|
timeoutSeconds: manifest.timeout_ms === undefined ? undefined : Math.ceil(manifest.timeout_ms / 1000)
|
|
976
980
|
};
|
|
977
981
|
}
|
|
@@ -1046,7 +1050,7 @@ function up(db) {
|
|
|
1046
1050
|
db.exec(idx);
|
|
1047
1051
|
}
|
|
1048
1052
|
}
|
|
1049
|
-
var
|
|
1053
|
+
var init__001_initial = __esm(() => {
|
|
1050
1054
|
init_schema();
|
|
1051
1055
|
});
|
|
1052
1056
|
|
|
@@ -1075,7 +1079,7 @@ function up2(db) {
|
|
|
1075
1079
|
throw err;
|
|
1076
1080
|
}
|
|
1077
1081
|
}
|
|
1078
|
-
var
|
|
1082
|
+
var init__002_session_events = __esm(() => {
|
|
1079
1083
|
init_schema();
|
|
1080
1084
|
});
|
|
1081
1085
|
|
|
@@ -1104,7 +1108,7 @@ function up3(db) {
|
|
|
1104
1108
|
throw err;
|
|
1105
1109
|
}
|
|
1106
1110
|
}
|
|
1107
|
-
var
|
|
1111
|
+
var init__003_user_prompt_submit_event = __esm(() => {
|
|
1108
1112
|
init_schema();
|
|
1109
1113
|
});
|
|
1110
1114
|
|
|
@@ -1128,7 +1132,7 @@ var CREATE_HOOKS_TABLE = `
|
|
|
1128
1132
|
last_verified_at TEXT
|
|
1129
1133
|
)
|
|
1130
1134
|
`, CREATE_HOOKS_INDEXES;
|
|
1131
|
-
var
|
|
1135
|
+
var init__004_hooks_table = __esm(() => {
|
|
1132
1136
|
CREATE_HOOKS_INDEXES = [
|
|
1133
1137
|
`CREATE INDEX IF NOT EXISTS idx_hooks_name ON hooks (name)`
|
|
1134
1138
|
];
|
|
@@ -1159,7 +1163,7 @@ function up5(db) {
|
|
|
1159
1163
|
throw err;
|
|
1160
1164
|
}
|
|
1161
1165
|
}
|
|
1162
|
-
var
|
|
1166
|
+
var init__005_subagent_start_event = __esm(() => {
|
|
1163
1167
|
init_schema();
|
|
1164
1168
|
});
|
|
1165
1169
|
|
|
@@ -1191,11 +1195,11 @@ function runMigrations(db) {
|
|
|
1191
1195
|
}
|
|
1192
1196
|
var MIGRATIONS;
|
|
1193
1197
|
var init_migrations = __esm(() => {
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1198
|
+
init__001_initial();
|
|
1199
|
+
init__002_session_events();
|
|
1200
|
+
init__003_user_prompt_submit_event();
|
|
1201
|
+
init__004_hooks_table();
|
|
1202
|
+
init__005_subagent_start_event();
|
|
1199
1203
|
MIGRATIONS = [
|
|
1200
1204
|
{ version: "001_initial", up },
|
|
1201
1205
|
{ version: "002_session_events", up: up2 },
|
|
@@ -1207,8 +1211,8 @@ var init_migrations = __esm(() => {
|
|
|
1207
1211
|
|
|
1208
1212
|
// src/db/legacy-import.ts
|
|
1209
1213
|
import { existsSync as existsSync6, readdirSync as readdirSync2, readFileSync as readFileSync4 } from "fs";
|
|
1210
|
-
import { join as
|
|
1211
|
-
import { homedir as
|
|
1214
|
+
import { join as join8 } from "path";
|
|
1215
|
+
import { homedir as homedir5 } from "os";
|
|
1212
1216
|
function ensureMetaTable(db) {
|
|
1213
1217
|
db.exec(`
|
|
1214
1218
|
CREATE TABLE IF NOT EXISTS _meta (
|
|
@@ -1282,25 +1286,25 @@ function importErrorsLog(db, filePath) {
|
|
|
1282
1286
|
} catch {}
|
|
1283
1287
|
return count;
|
|
1284
1288
|
}
|
|
1285
|
-
function runLegacyImport(db, homeDir =
|
|
1289
|
+
function runLegacyImport(db, homeDir = homedir5()) {
|
|
1286
1290
|
try {
|
|
1287
1291
|
if (isAlreadyDone(db))
|
|
1288
1292
|
return;
|
|
1289
1293
|
let total = 0;
|
|
1290
|
-
const claudeProjectsDir =
|
|
1294
|
+
const claudeProjectsDir = join8(homeDir, ".claude", "projects");
|
|
1291
1295
|
if (existsSync6(claudeProjectsDir)) {
|
|
1292
1296
|
try {
|
|
1293
1297
|
const projectDirs = readdirSync2(claudeProjectsDir);
|
|
1294
1298
|
for (const dir of projectDirs) {
|
|
1295
|
-
const projectDir =
|
|
1299
|
+
const projectDir = join8(claudeProjectsDir, dir);
|
|
1296
1300
|
try {
|
|
1297
1301
|
const files = readdirSync2(projectDir);
|
|
1298
1302
|
for (const file of files) {
|
|
1299
1303
|
if (file.match(/^session-log-\d{4}-\d{2}-\d{2}\.jsonl$/)) {
|
|
1300
|
-
total += importJsonlFile(db,
|
|
1304
|
+
total += importJsonlFile(db, join8(projectDir, file));
|
|
1301
1305
|
}
|
|
1302
1306
|
if (file === "errors.log") {
|
|
1303
|
-
total += importErrorsLog(db,
|
|
1307
|
+
total += importErrorsLog(db, join8(projectDir, file));
|
|
1304
1308
|
}
|
|
1305
1309
|
}
|
|
1306
1310
|
} catch {}
|
|
@@ -1337,18 +1341,18 @@ function runRetention(db, days) {
|
|
|
1337
1341
|
// src/db/index.ts
|
|
1338
1342
|
var exports_db = {};
|
|
1339
1343
|
__export(exports_db, {
|
|
1340
|
-
|
|
1341
|
-
localStoreRefusalMessage: () => localStoreRefusalMessage,
|
|
1342
|
-
isLocalStoreRefused: () => isLocalStoreRefused,
|
|
1343
|
-
getDbPath: () => getDbPath,
|
|
1344
|
-
getDb: () => getDb,
|
|
1345
|
-
createTestDb: () => createTestDb,
|
|
1344
|
+
allowLocalStore: () => allowLocalStore,
|
|
1346
1345
|
closeDb: () => closeDb,
|
|
1347
|
-
|
|
1346
|
+
createTestDb: () => createTestDb,
|
|
1347
|
+
getDb: () => getDb,
|
|
1348
|
+
getDbPath: () => getDbPath,
|
|
1349
|
+
isLocalStoreRefused: () => isLocalStoreRefused,
|
|
1350
|
+
localStoreRefusalMessage: () => localStoreRefusalMessage,
|
|
1351
|
+
refuseLocalStore: () => refuseLocalStore
|
|
1348
1352
|
});
|
|
1349
1353
|
import { Database } from "bun:sqlite";
|
|
1350
1354
|
import { existsSync as existsSync7, mkdirSync as mkdirSync2, cpSync } from "fs";
|
|
1351
|
-
import { join as
|
|
1355
|
+
import { join as join9 } from "path";
|
|
1352
1356
|
function refuseLocalStore(message) {
|
|
1353
1357
|
localStoreRefusal = message;
|
|
1354
1358
|
}
|
|
@@ -1363,7 +1367,7 @@ function localStoreRefusalMessage() {
|
|
|
1363
1367
|
}
|
|
1364
1368
|
function resolveDataDir() {
|
|
1365
1369
|
const effective = getEffectiveDataRoot();
|
|
1366
|
-
const oldDir =
|
|
1370
|
+
const oldDir = join9(getHomeDir(), ".hooks");
|
|
1367
1371
|
if (!existsSync7(effective) && existsSync7(oldDir)) {
|
|
1368
1372
|
mkdirSync2(effective, { recursive: true });
|
|
1369
1373
|
cpSync(oldDir, effective, { recursive: true });
|
|
@@ -1375,7 +1379,7 @@ function getDbPath() {
|
|
|
1375
1379
|
if (explicitDb)
|
|
1376
1380
|
return explicitDb;
|
|
1377
1381
|
const dataDir2 = resolveDataDir();
|
|
1378
|
-
return
|
|
1382
|
+
return join9(dataDir2, "hooks.db");
|
|
1379
1383
|
}
|
|
1380
1384
|
function ensureDir(dbPath) {
|
|
1381
1385
|
const dir = dbPath.substring(0, dbPath.lastIndexOf("/"));
|
|
@@ -1452,14 +1456,14 @@ function redactValue(value) {
|
|
|
1452
1456
|
}
|
|
1453
1457
|
return value;
|
|
1454
1458
|
}
|
|
1455
|
-
function redactEventPayload(
|
|
1456
|
-
if (
|
|
1459
|
+
function redactEventPayload(text2) {
|
|
1460
|
+
if (text2 === null || text2 === undefined)
|
|
1457
1461
|
return null;
|
|
1458
1462
|
try {
|
|
1459
|
-
const parsed = JSON.parse(
|
|
1463
|
+
const parsed = JSON.parse(text2);
|
|
1460
1464
|
return redactText(JSON.stringify(redactValue(parsed)));
|
|
1461
1465
|
} catch {
|
|
1462
|
-
return redactText(
|
|
1466
|
+
return redactText(text2);
|
|
1463
1467
|
}
|
|
1464
1468
|
}
|
|
1465
1469
|
function projectEventRowForRead(row) {
|
|
@@ -1495,13 +1499,13 @@ var init_redact = __esm(() => {
|
|
|
1495
1499
|
];
|
|
1496
1500
|
});
|
|
1497
1501
|
|
|
1498
|
-
//
|
|
1502
|
+
// ../contracts/dist/client/transport.js
|
|
1499
1503
|
import { isIP } from "net";
|
|
1500
|
-
import { spawnSync } from "child_process";
|
|
1504
|
+
import { spawnSync as spawnSync4 } from "child_process";
|
|
1501
1505
|
import { closeSync as closeSync23, fstatSync as fstatSync23, openSync as openSync23, readFileSync as readFileSync22 } from "fs";
|
|
1502
1506
|
import { O_NOFOLLOW as O_NOFOLLOW2, O_NONBLOCK as O_NONBLOCK2, O_RDONLY as O_RDONLY2 } from "constants";
|
|
1503
1507
|
import { hostname as osHostname } from "os";
|
|
1504
|
-
import { isAbsolute as isAbsolute9, join as
|
|
1508
|
+
import { isAbsolute as isAbsolute9, join as join210 } from "path";
|
|
1505
1509
|
import { createRequire as createRequire2 } from "module";
|
|
1506
1510
|
function envToken2(name) {
|
|
1507
1511
|
return name.toUpperCase().replace(/-/g, "_");
|
|
@@ -1532,14 +1536,14 @@ function hasnaHomeDir(env) {
|
|
|
1532
1536
|
if (override)
|
|
1533
1537
|
return override;
|
|
1534
1538
|
const home = homeDir(env);
|
|
1535
|
-
return home ?
|
|
1539
|
+
return home ? join210(home, HASNA_HOME_DIR) : null;
|
|
1536
1540
|
}
|
|
1537
1541
|
function appConfigDir(name, env) {
|
|
1538
1542
|
const configRoot = absoluteOverride(env, HASNA_CONFIG_HOME_ENV_KEY);
|
|
1539
1543
|
if (configRoot)
|
|
1540
|
-
return
|
|
1544
|
+
return join210(configRoot, name);
|
|
1541
1545
|
const root = hasnaHomeDir(env);
|
|
1542
|
-
return root ?
|
|
1546
|
+
return root ? join210(root, name, CONFIG_SUBDIR) : null;
|
|
1543
1547
|
}
|
|
1544
1548
|
function credentialDiskSourceList(name, env, profile = null) {
|
|
1545
1549
|
if (!SAFE_APP_SLUG.test(name))
|
|
@@ -1548,7 +1552,7 @@ function credentialDiskSourceList(name, env, profile = null) {
|
|
|
1548
1552
|
if (!directory3)
|
|
1549
1553
|
return [];
|
|
1550
1554
|
const file2 = profile ? `${CREDENTIALS_FILE}-${profile}` : CREDENTIALS_FILE;
|
|
1551
|
-
return [{ path:
|
|
1555
|
+
return [{ path: join210(directory3, file2), tier: "disk" }];
|
|
1552
1556
|
}
|
|
1553
1557
|
function credentialDiskSources(name, env) {
|
|
1554
1558
|
return credentialDiskSourceList(name, env, null).map((s) => s.path);
|
|
@@ -1556,10 +1560,10 @@ function credentialDiskSources(name, env) {
|
|
|
1556
1560
|
function profileDiskSources(name, env, profile) {
|
|
1557
1561
|
return credentialDiskSourceList(name, env, profile).map((s) => s.path);
|
|
1558
1562
|
}
|
|
1559
|
-
function parseEnvFile(
|
|
1563
|
+
function parseEnvFile(text2) {
|
|
1560
1564
|
const values = new Map;
|
|
1561
1565
|
const unusable = new Set;
|
|
1562
|
-
for (const rawLine of
|
|
1566
|
+
for (const rawLine of text2.split(/\r?\n/)) {
|
|
1563
1567
|
const line = rawLine.trim();
|
|
1564
1568
|
if (line.length === 0 || line.startsWith("#"))
|
|
1565
1569
|
continue;
|
|
@@ -1657,11 +1661,14 @@ function readCredentialFile(path, apiKeyKeys, pointerKey) {
|
|
|
1657
1661
|
}
|
|
1658
1662
|
return values[0] === undefined ? null : { apiKey: values[0] };
|
|
1659
1663
|
}
|
|
1660
|
-
function appConfigDiskValue(name, env, keys2) {
|
|
1664
|
+
function appConfigDiskValue(name, env, keys2, profile = null) {
|
|
1665
|
+
if (profile !== null && !SAFE_PROFILE.test(profile)) {
|
|
1666
|
+
throw new CredentialResolutionError(name, "The selected configuration profile is invalid.", ["profile"]);
|
|
1667
|
+
}
|
|
1661
1668
|
const wanted = keys2.filter((key2) => !CREDENTIAL_SHAPED_KEY.test(key2));
|
|
1662
1669
|
if (wanted.length === 0)
|
|
1663
1670
|
return null;
|
|
1664
|
-
for (const path of
|
|
1671
|
+
for (const path of profileDiskSources(name, env, profile)) {
|
|
1665
1672
|
const parsed = readAppConfigFile(path);
|
|
1666
1673
|
if (!parsed)
|
|
1667
1674
|
continue;
|
|
@@ -1741,7 +1748,7 @@ function isAmbientEnvironment(env) {
|
|
|
1741
1748
|
return env === process.env || env[AMBIENT_ENVIRONMENT2] === true;
|
|
1742
1749
|
}
|
|
1743
1750
|
function defaultKeychainRunner(argv) {
|
|
1744
|
-
const result =
|
|
1751
|
+
const result = spawnSync4(KEYCHAIN_SECURITY_BIN, [...argv], {
|
|
1745
1752
|
encoding: "utf8",
|
|
1746
1753
|
stdio: ["ignore", "pipe", "pipe"],
|
|
1747
1754
|
timeout: KEYCHAIN_SPAWN_TIMEOUT_MS
|
|
@@ -1769,8 +1776,8 @@ function keychainAccount(env, options) {
|
|
|
1769
1776
|
const user = env.USER?.trim();
|
|
1770
1777
|
return user || null;
|
|
1771
1778
|
}
|
|
1772
|
-
function keychainFailureHint(
|
|
1773
|
-
const line =
|
|
1779
|
+
function keychainFailureHint(text2) {
|
|
1780
|
+
const line = text2.split(/\r?\n/).find((entry) => entry.trim().length > 0)?.trim() ?? "";
|
|
1774
1781
|
const clean = line.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 200);
|
|
1775
1782
|
return clean ? `: ${clean}` : "";
|
|
1776
1783
|
}
|
|
@@ -2108,7 +2115,7 @@ function toV1BaseUrl(apiUrl) {
|
|
|
2108
2115
|
url2.pathname = `${path}/v1`;
|
|
2109
2116
|
return url2.toString().replace(/\/+$/, "");
|
|
2110
2117
|
}
|
|
2111
|
-
function
|
|
2118
|
+
function resolveClientAuthoritySnapshot(name, env = process.env, options = {}) {
|
|
2112
2119
|
env = snapshotClientEnvironment(name, env);
|
|
2113
2120
|
const keys2 = clientTransportEnvKeys2(name);
|
|
2114
2121
|
const definedUrlEntries = keys2.apiUrlKeys.filter((key2) => Object.prototype.hasOwnProperty.call(env, key2) && env[key2] !== undefined).map((key2) => ({ key: key2, raw: String(env[key2]) }));
|
|
@@ -2121,12 +2128,20 @@ function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
|
|
|
2121
2128
|
throw new ClientTransportConfigurationError(name, `${controlledUrl.key} contains ASCII control characters.`, [controlledUrl.key]);
|
|
2122
2129
|
}
|
|
2123
2130
|
const usableUrlEntries = definedUrlEntries.map((entry) => ({ key: entry.key, value: entry.raw.trim() }));
|
|
2124
|
-
|
|
2125
|
-
|
|
2131
|
+
const normalizedAuthority = (entry) => {
|
|
2132
|
+
try {
|
|
2133
|
+
return toV1BaseUrl(entry.value);
|
|
2134
|
+
} catch {
|
|
2135
|
+
throw new ClientTransportConfigurationError(name, `Invalid API URL from ${entry.key}; use an absolute HTTPS URL or exact loopback HTTP authority without credentials, query or fragment.`, [entry.key]);
|
|
2136
|
+
}
|
|
2137
|
+
};
|
|
2138
|
+
if (usableUrlEntries.length > 1 && new Set(usableUrlEntries.map(normalizedAuthority)).size > 1) {
|
|
2139
|
+
throw new ClientTransportConfigurationError(name, `${usableUrlEntries.map((entry) => entry.key).join(" and ")} disagree; client authority aliases must select the same versioned API authority or only one may be set.`, usableUrlEntries.map((entry) => entry.key));
|
|
2126
2140
|
}
|
|
2127
2141
|
const envUrlHit = usableUrlEntries[0] ?? null;
|
|
2128
2142
|
const keychainUrlHit = keychainConfigValue(name, env, options.credentials?.keychain);
|
|
2129
|
-
const
|
|
2143
|
+
const profile = options.bindUnpairedCredentialsToFleet ? options.credentials?.profile?.trim() || env.HASNA_PROFILE?.trim() || null : null;
|
|
2144
|
+
const diskConfigUrlHit = appConfigDiskValue(name, env, keys2.apiUrlKeys, profile);
|
|
2130
2145
|
if (diskConfigUrlHit?.unusable) {
|
|
2131
2146
|
throw new ClientTransportConfigurationError(name, `${diskConfigUrlHit.key} in ${diskConfigUrlHit.path} is declared but blank or malformed; public clients require a valid HTTPS service authority.`, [diskConfigUrlHit.path]);
|
|
2132
2147
|
}
|
|
@@ -2136,10 +2151,23 @@ function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
|
|
|
2136
2151
|
...diskConfigUrlHit ? [{ key: diskConfigUrlHit.path, value: diskConfigUrlHit.value.trim() }] : []
|
|
2137
2152
|
];
|
|
2138
2153
|
const configuredUrl = urlCandidates[0] ?? null;
|
|
2139
|
-
const
|
|
2154
|
+
const normalizedUrls = urlCandidates.map(normalizedAuthority);
|
|
2155
|
+
const divergentUrls = urlCandidates.filter((_, index) => normalizedUrls[index] !== normalizedUrls[0]);
|
|
2140
2156
|
if (configuredUrl && divergentUrls.length > 0) {
|
|
2141
2157
|
throw new ClientTransportConfigurationError(name, `${configuredUrl.key} and ${divergentUrls.map((candidate) => candidate.key).join(" and ")} select different service authorities; refusing to send a credential written for one authority to the other.`, urlCandidates.map((candidate) => candidate.key));
|
|
2142
2158
|
}
|
|
2159
|
+
if (configuredUrl && options.bindUnpairedCredentialsToFleet) {
|
|
2160
|
+
try {
|
|
2161
|
+
toV1BaseUrl(configuredUrl.value);
|
|
2162
|
+
} catch (error61) {
|
|
2163
|
+
throw new ClientTransportConfigurationError(name, `Invalid API URL from ${configuredUrl.key}: ${error61 instanceof Error ? error61.message : String(error61)}`, [configuredUrl.key]);
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
return { keys: keys2, configuredUrl, envUrlHit, keychainUrlHit, diskConfigUrlHit };
|
|
2167
|
+
}
|
|
2168
|
+
function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
|
|
2169
|
+
env = snapshotClientEnvironment(name, env);
|
|
2170
|
+
const { keys: keys2, configuredUrl, envUrlHit, keychainUrlHit, diskConfigUrlHit } = resolveClientAuthoritySnapshot(name, env, options);
|
|
2143
2171
|
const warnings = [];
|
|
2144
2172
|
if (configuredUrl && !envUrlHit) {
|
|
2145
2173
|
warnings.push(`No ${keys2.apiUrlKeys[0]} in the environment; the server URL in ${configuredUrl.key} was used, so this client connects to the server. ` + `Keep that entry aligned with the intended service authority.`);
|
|
@@ -2149,7 +2177,10 @@ function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
|
|
|
2149
2177
|
const diskHint = credentialDiskSourcesForMessage(name, env);
|
|
2150
2178
|
const lead = configuredUrl ? `${configuredUrl.key} selects the HTTP server for '${name}', but no API key could be resolved` : `${keys2.apiUrlKeys[0]} is not set and no API key could be resolved for '${name}'; a credential is required before the default fleet gateway authority applies`;
|
|
2151
2179
|
warnings.push(`${lead}; refusing to create an unauthenticated client \u2014 public clients never fall back to SQLite or another local store. ` + `Looked in the Keychain (macOS only), then for a credential file at ${diskHint}, then for ${keys2.apiKeyKeys[0]} in the environment.`);
|
|
2152
|
-
|
|
2180
|
+
const sources = [configuredUrl?.key ?? keys2.apiUrlKeys[0]];
|
|
2181
|
+
if (options.bindUnpairedCredentialsToFleet)
|
|
2182
|
+
throw new ClientCredentialMissingError(name, warnings.join(" "), sources, configuredUrl !== null);
|
|
2183
|
+
throw new ClientTransportConfigurationError(name, warnings.join(" "), sources);
|
|
2153
2184
|
}
|
|
2154
2185
|
if (credential.warning)
|
|
2155
2186
|
warnings.push(credential.warning);
|
|
@@ -2172,6 +2203,14 @@ function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
|
|
|
2172
2203
|
const message = error61 instanceof Error ? error61.message : String(error61);
|
|
2173
2204
|
throw new ClientTransportConfigurationError(name, `Invalid API URL from ${apiUrlSource}: ${message}`, [apiUrlSource]);
|
|
2174
2205
|
}
|
|
2206
|
+
if (options.bindUnpairedCredentialsToFleet && baseUrl !== toV1BaseUrl(defaultFleetGatewayBaseUrl(name))) {
|
|
2207
|
+
const pairedDisk = diskConfigUrlHit?.path === credential.source && (credential.tier === "disk" || credential.tier === "profile" || credential.tier === "pointer");
|
|
2208
|
+
const pairedKeychain = credential.tier === "keychain" && keychainUrlHit?.source === credential.source.replace(".api-key@", ".api-url@");
|
|
2209
|
+
const deliberatePair = envUrlHit !== null && (credential.tier === "argument" || credential.tier === "override");
|
|
2210
|
+
if (!pairedDisk && !pairedKeychain && !deliberatePair) {
|
|
2211
|
+
throw new ClientTransportConfigurationError(name, "An unpaired legacy credential is bound to the fleet gateway. Configure a stored authority/credential pair or an explicit API key override for the intended authority; no credential was sent.");
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2175
2214
|
return {
|
|
2176
2215
|
resolution: {
|
|
2177
2216
|
transport: "http",
|
|
@@ -2194,7 +2233,7 @@ function credentialDiskSourcesForMessage(name, env) {
|
|
|
2194
2233
|
const paths = credentialDiskSources(name, env);
|
|
2195
2234
|
return paths.length > 0 ? paths.join(" or ") : "<no HOME or HASNA_HOME set in this environment, so no credential file was consulted>";
|
|
2196
2235
|
}
|
|
2197
|
-
var CREDENTIAL_PROFILE_ENV_KEY = "HASNA_PROFILE", MAX_PACKAGE_BYTES2, CredentialResolutionError, CredentialFileUnsafeError, HASNA_HOME_ENV_KEY = "HASNA_HOME", HASNA_CONFIG_HOME_ENV_KEY = "HASNA_CONFIG_HOME", KEYCHAIN_STATION_ENV_KEY = "HASNA_STATION", HASNA_HOME_DIR = ".hasna", CONFIG_SUBDIR = "config", CREDENTIALS_FILE = "credentials", KEYCHAIN_SECURITY_BIN = "/usr/bin/security", KEYCHAIN_SERVICE_PREFIX = "hasna.credentials", KEYCHAIN_ITEM_NOT_FOUND_STATUS = 44, KEYCHAIN_SPAWN_TIMEOUT_MS = 1e4, MAX_CREDENTIAL_FILE_BYTES2, SAFE_APP_SLUG, SAFE_PROFILE, ILLEGAL_IN_HEADER_VALUE, VAULT_POINTER_SHAPE, CREDENTIAL_SHAPED_KEY, INSPECT_CUSTOM2, CREDENTIAL_SEAL2, AMBIENT_ENVIRONMENT2, requireSecretsSdk2, DEFAULT_FLEET_GATEWAY_ORIGIN = "https://api.hasna.com", DEFAULT_AUTHORITY_SOURCE = "default", ASCII_CONTROL_PATTERN, DNS_LABEL_PATTERN, ClientTransportConfigurationError, IDEMPOTENT_METHODS2, AUTHORITY_OVERRIDE_HEADERS2;
|
|
2236
|
+
var CREDENTIAL_PROFILE_ENV_KEY = "HASNA_PROFILE", MAX_PACKAGE_BYTES2, CredentialResolutionError, CredentialFileUnsafeError, HASNA_HOME_ENV_KEY = "HASNA_HOME", HASNA_CONFIG_HOME_ENV_KEY = "HASNA_CONFIG_HOME", KEYCHAIN_STATION_ENV_KEY = "HASNA_STATION", HASNA_HOME_DIR = ".hasna", CONFIG_SUBDIR = "config", CREDENTIALS_FILE = "credentials", KEYCHAIN_SECURITY_BIN = "/usr/bin/security", KEYCHAIN_SERVICE_PREFIX = "hasna.credentials", KEYCHAIN_ITEM_NOT_FOUND_STATUS = 44, KEYCHAIN_SPAWN_TIMEOUT_MS = 1e4, MAX_CREDENTIAL_FILE_BYTES2, SAFE_APP_SLUG, SAFE_PROFILE, ILLEGAL_IN_HEADER_VALUE, VAULT_POINTER_SHAPE, CREDENTIAL_SHAPED_KEY, INSPECT_CUSTOM2, CREDENTIAL_SEAL2, AMBIENT_ENVIRONMENT2, requireSecretsSdk2, DEFAULT_FLEET_GATEWAY_ORIGIN = "https://api.hasna.com", DEFAULT_AUTHORITY_SOURCE = "default", ASCII_CONTROL_PATTERN, DNS_LABEL_PATTERN, ClientTransportConfigurationError, ClientCredentialMissingError, IDEMPOTENT_METHODS2, AUTHORITY_OVERRIDE_HEADERS2;
|
|
2198
2237
|
var init_transport = __esm(() => {
|
|
2199
2238
|
MAX_PACKAGE_BYTES2 = 1024 * 1024;
|
|
2200
2239
|
CredentialResolutionError = class CredentialResolutionError extends Error {
|
|
@@ -2237,6 +2276,14 @@ var init_transport = __esm(() => {
|
|
|
2237
2276
|
this.sources = Object.freeze([...sources]);
|
|
2238
2277
|
}
|
|
2239
2278
|
};
|
|
2279
|
+
ClientCredentialMissingError = class ClientCredentialMissingError extends ClientTransportConfigurationError {
|
|
2280
|
+
authorityConfigured;
|
|
2281
|
+
constructor(name, message, sources, authorityConfigured) {
|
|
2282
|
+
super(name, message, sources);
|
|
2283
|
+
this.authorityConfigured = authorityConfigured;
|
|
2284
|
+
this.name = "ClientCredentialMissingError";
|
|
2285
|
+
}
|
|
2286
|
+
};
|
|
2240
2287
|
IDEMPOTENT_METHODS2 = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
|
|
2241
2288
|
AUTHORITY_OVERRIDE_HEADERS2 = new Set([
|
|
2242
2289
|
"host",
|
|
@@ -2375,9 +2422,9 @@ var init_stop_review_context = __esm(() => {
|
|
|
2375
2422
|
});
|
|
2376
2423
|
|
|
2377
2424
|
// src/lib/hook-env.ts
|
|
2378
|
-
import { dirname as
|
|
2379
|
-
import { existsSync as
|
|
2380
|
-
import { tmpdir } from "os";
|
|
2425
|
+
import { dirname as dirname23, isAbsolute as isAbsolute14 } from "path";
|
|
2426
|
+
import { existsSync as existsSync15, realpathSync as realpathSync7, statSync as statSync2 } from "fs";
|
|
2427
|
+
import { tmpdir as tmpdir2 } from "os";
|
|
2381
2428
|
function isDeniedEnvName(name) {
|
|
2382
2429
|
const upper = name.toUpperCase();
|
|
2383
2430
|
if (DENY_PREFIXES.some((prefix3) => upper.startsWith(prefix3)))
|
|
@@ -2411,22 +2458,22 @@ function isUnsafePathEntry(entry, home) {
|
|
|
2411
2458
|
}
|
|
2412
2459
|
};
|
|
2413
2460
|
const resolved = canonical9(entry);
|
|
2414
|
-
for (const root of [home,
|
|
2461
|
+
for (const root of [home, tmpdir2(), "/tmp", "/var/tmp"].filter((value) => Boolean(value))) {
|
|
2415
2462
|
const blocked = canonical9(root);
|
|
2416
2463
|
if (resolved === blocked || resolved.startsWith(blocked + "/"))
|
|
2417
2464
|
return true;
|
|
2418
2465
|
}
|
|
2419
2466
|
try {
|
|
2420
|
-
if ((
|
|
2467
|
+
if ((statSync2(entry).mode & 2) !== 0)
|
|
2421
2468
|
return true;
|
|
2422
2469
|
} catch {}
|
|
2423
2470
|
return false;
|
|
2424
2471
|
}
|
|
2425
2472
|
function sanitizeHookPath(pathValue, home) {
|
|
2426
2473
|
const baseline = PATH_BASELINE.slice();
|
|
2427
|
-
if (process.platform === "darwin" &&
|
|
2474
|
+
if (process.platform === "darwin" && existsSync15("/opt/homebrew/bin"))
|
|
2428
2475
|
baseline.push("/opt/homebrew/bin");
|
|
2429
|
-
const bunDir =
|
|
2476
|
+
const bunDir = dirname23(process.execPath);
|
|
2430
2477
|
const seen = new Set;
|
|
2431
2478
|
const out = [];
|
|
2432
2479
|
for (const dir of baseline) {
|
|
@@ -2554,15 +2601,15 @@ var init_hook_env = __esm(() => {
|
|
|
2554
2601
|
// src/lib/run.ts
|
|
2555
2602
|
var exports_run = {};
|
|
2556
2603
|
__export(exports_run, {
|
|
2557
|
-
|
|
2604
|
+
BUN_ISOLATION_FLAGS: () => BUN_ISOLATION_FLAGS,
|
|
2558
2605
|
HookTimeoutError: () => HookTimeoutError,
|
|
2559
|
-
|
|
2606
|
+
executeVerifiedScript: () => executeVerifiedScript
|
|
2560
2607
|
});
|
|
2561
2608
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
2562
|
-
import { rmSync as
|
|
2563
|
-
import { basename as
|
|
2609
|
+
import { rmSync as rmSync5, writeFileSync as writeFileSync11 } from "fs";
|
|
2610
|
+
import { basename as basename16, dirname as dirname27, isAbsolute as isAbsolute17, join as join32 } from "path";
|
|
2564
2611
|
function extensionOf(scriptPath) {
|
|
2565
|
-
const base =
|
|
2612
|
+
const base = basename16(scriptPath);
|
|
2566
2613
|
const dot = base.lastIndexOf(".");
|
|
2567
2614
|
return dot > 0 ? base.slice(dot + 1) : "ts";
|
|
2568
2615
|
}
|
|
@@ -2574,9 +2621,9 @@ function shebangInterpreter(firstLine) {
|
|
|
2574
2621
|
return null;
|
|
2575
2622
|
const parts = rest.split(/\s+/);
|
|
2576
2623
|
if (parts[0] === "env" || parts[0] === "/usr/bin/env") {
|
|
2577
|
-
return parts[1] && parts[1] !== "-S" ?
|
|
2624
|
+
return parts[1] && parts[1] !== "-S" ? basename16(parts[1]) : parts[2] ? basename16(parts[2]) : null;
|
|
2578
2625
|
}
|
|
2579
|
-
return
|
|
2626
|
+
return basename16(parts[0]);
|
|
2580
2627
|
}
|
|
2581
2628
|
function interpreterFor(name, scriptPath, content) {
|
|
2582
2629
|
const ext = extensionOf(scriptPath);
|
|
@@ -2629,9 +2676,9 @@ async function readPipeWithDeadline(stream, deadlineMs) {
|
|
|
2629
2676
|
return chunks.join("");
|
|
2630
2677
|
}
|
|
2631
2678
|
async function executeVerifiedScript(options) {
|
|
2632
|
-
const scriptDir =
|
|
2679
|
+
const scriptDir = dirname27(options.scriptPath);
|
|
2633
2680
|
const interpreter = interpreterFor(options.name, options.scriptPath, options.content);
|
|
2634
|
-
const tempPath =
|
|
2681
|
+
const tempPath = join32(scriptDir, `.hooks-verified-${randomBytes2(12).toString("hex")}.${interpreter.tempExt}`);
|
|
2635
2682
|
let proc = null;
|
|
2636
2683
|
let timedOut = false;
|
|
2637
2684
|
const timeoutTimer = options.timeout ? setTimeout(() => {
|
|
@@ -2639,7 +2686,7 @@ async function executeVerifiedScript(options) {
|
|
|
2639
2686
|
killGroup(proc, { leaderAlive: proc !== null && proc.exitCode === null });
|
|
2640
2687
|
}, options.timeout) : null;
|
|
2641
2688
|
try {
|
|
2642
|
-
|
|
2689
|
+
writeFileSync11(tempPath, options.content, { flag: "wx", mode: 384 });
|
|
2643
2690
|
proc = Bun.spawn([...interpreter.command, isAbsolute17(tempPath) ? tempPath : `./${tempPath}`, ...options.args ?? []], {
|
|
2644
2691
|
stdin: new Response(options.stdin),
|
|
2645
2692
|
stdout: "pipe",
|
|
@@ -2661,7 +2708,7 @@ async function executeVerifiedScript(options) {
|
|
|
2661
2708
|
if (timeoutTimer)
|
|
2662
2709
|
clearTimeout(timeoutTimer);
|
|
2663
2710
|
try {
|
|
2664
|
-
|
|
2711
|
+
rmSync5(tempPath, { force: true });
|
|
2665
2712
|
} catch {}
|
|
2666
2713
|
}
|
|
2667
2714
|
}
|
|
@@ -2683,8 +2730,8 @@ function killGroup(proc, options) {
|
|
|
2683
2730
|
let killed = 0;
|
|
2684
2731
|
for (const pid of members2) {
|
|
2685
2732
|
try {
|
|
2686
|
-
const
|
|
2687
|
-
const cols =
|
|
2733
|
+
const probe2 = Bun.spawnSync(["ps", "-o", "pid=,pgid=", "-p", String(pid)], { stdout: "pipe", stderr: "pipe" });
|
|
2734
|
+
const cols = probe2.stdout.toString().trim().split(/\s+/);
|
|
2688
2735
|
if (cols.length === 2 && cols[1] === String(pgid)) {
|
|
2689
2736
|
process.kill(pid, "SIGKILL");
|
|
2690
2737
|
killed++;
|
|
@@ -2720,12 +2767,12 @@ var init_run = __esm(() => {
|
|
|
2720
2767
|
// src/lib/db-writer.ts
|
|
2721
2768
|
var exports_db_writer = {};
|
|
2722
2769
|
__export(exports_db_writer, {
|
|
2723
|
-
|
|
2724
|
-
resolveHookEventSink: () => resolveHookEventSink,
|
|
2725
|
-
resolveEventType: () => resolveEventType,
|
|
2726
|
-
recordHookRun: () => recordHookRun,
|
|
2770
|
+
__resetHookEventSinkNotice: () => __resetHookEventSinkNotice,
|
|
2727
2771
|
normalizeEventType: () => normalizeEventType,
|
|
2728
|
-
|
|
2772
|
+
recordHookRun: () => recordHookRun,
|
|
2773
|
+
resolveEventType: () => resolveEventType,
|
|
2774
|
+
resolveHookEventSink: () => resolveHookEventSink,
|
|
2775
|
+
writeHookEvent: () => writeHookEvent
|
|
2729
2776
|
});
|
|
2730
2777
|
function resolveHookEventSink(env = process.env) {
|
|
2731
2778
|
if (isLocalStoreRefused())
|
|
@@ -2841,15 +2888,15 @@ import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
|
|
2841
2888
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
2842
2889
|
import { z as z3 } from "zod";
|
|
2843
2890
|
init_registry();
|
|
2844
|
-
import { existsSync as
|
|
2845
|
-
import { join as
|
|
2891
|
+
import { existsSync as existsSync16, readFileSync as readFileSync18 } from "fs";
|
|
2892
|
+
import { join as join34, dirname as dirname29 } from "path";
|
|
2846
2893
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
2847
2894
|
|
|
2848
2895
|
// src/lib/installer.ts
|
|
2849
2896
|
init_registry();
|
|
2850
|
-
import { existsSync as
|
|
2851
|
-
import { join as
|
|
2852
|
-
import { homedir as
|
|
2897
|
+
import { existsSync as existsSync14, mkdirSync as mkdirSync12, readFileSync as readFileSync13, readdirSync as readdirSync8, realpathSync as realpathSync4, rmdirSync as rmdirSync4, unlinkSync as unlinkSync6, writeFileSync as writeFileSync10 } from "fs";
|
|
2898
|
+
import { join as join24, dirname as dirname16, basename as basename12, resolve as resolve28 } from "path";
|
|
2899
|
+
import { homedir as homedir8 } from "os";
|
|
2853
2900
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
2854
2901
|
|
|
2855
2902
|
// src/lib/readiness-process.ts
|
|
@@ -2928,7 +2975,144 @@ import { homedir as homedir2 } from "os";
|
|
|
2928
2975
|
function isNativeSafetyName(name) {
|
|
2929
2976
|
return name === "trash-guard" || name === "workspace-repos-guard";
|
|
2930
2977
|
}
|
|
2978
|
+
var NATIVE_SAFETY_RUNTIME_KEY_SOURCE = String.raw`((s) => {
|
|
2979
|
+
const parts = [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs, s.birthtimeNs];
|
|
2980
|
+
return parts.every((part) => typeof part === "bigint") && parts.slice(1).every((part) => part > 0n) ? parts.join(":") : null;
|
|
2981
|
+
})`;
|
|
2982
|
+
var NATIVE_SAFETY_TIMEOUT_STATUS = 93;
|
|
2983
|
+
var NATIVE_SAFETY_TIMEOUT_MESSAGE = "Native safety guard refused (guard_timeout): verification did not finish within its time budget, so the command did not run. This is a timeout, not a policy decision; one retry is safe. If it repeats, report it and do not bypass the guard.";
|
|
2984
|
+
var NATIVE_SAFETY_FAILURE_MESSAGE = "Native safety guard refused: verification or execution failed.";
|
|
2985
|
+
var NATIVE_SAFETY_DIGEST_DIR = ".hasna/hooks/native/runtime-digests";
|
|
2931
2986
|
var supervisorSource = String.raw`async function supervise(encoded) {
|
|
2987
|
+
const fs = require("node:fs");
|
|
2988
|
+
const path = require("node:path");
|
|
2989
|
+
const crypto = require("node:crypto");
|
|
2990
|
+
const cp = require("node:child_process");
|
|
2991
|
+
const fail = () => { process.stderr.write("Native safety guard refused: verification or execution failed.\n"); process.exit(2); };
|
|
2992
|
+
const timedOut = () => process.exit(${NATIVE_SAFETY_TIMEOUT_STATUS});
|
|
2993
|
+
try {
|
|
2994
|
+
const b = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
|
|
2995
|
+
const uid = process.getuid();
|
|
2996
|
+
const ancestry = (directory) => {
|
|
2997
|
+
for (let parent = directory;;) {
|
|
2998
|
+
const s = fs.lstatSync(parent);
|
|
2999
|
+
if (!s.isDirectory() || ![0, uid].includes(s.uid) || (s.mode & 0o022)) throw Error();
|
|
3000
|
+
if (parent === path.dirname(parent)) break;
|
|
3001
|
+
parent = path.dirname(parent);
|
|
3002
|
+
}
|
|
3003
|
+
};
|
|
3004
|
+
const open = (file, maximum) => {
|
|
3005
|
+
if (!path.isAbsolute(file) || fs.realpathSync(file) !== file) throw Error();
|
|
3006
|
+
ancestry(path.dirname(file));
|
|
3007
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
3008
|
+
const s = fs.fstatSync(fd);
|
|
3009
|
+
if (!s.isFile() || ![0, uid].includes(s.uid) || (s.mode & 0o022) || s.size > maximum) { fs.closeSync(fd); throw Error(); }
|
|
3010
|
+
return fd;
|
|
3011
|
+
};
|
|
3012
|
+
const check = (file, hash, maximum) => {
|
|
3013
|
+
const fd = open(file, maximum);
|
|
3014
|
+
try {
|
|
3015
|
+
const bytes = fs.readFileSync(fd);
|
|
3016
|
+
if (crypto.createHash("sha256").update(bytes).digest("hex") !== hash) throw Error();
|
|
3017
|
+
return bytes;
|
|
3018
|
+
} finally { fs.closeSync(fd); }
|
|
3019
|
+
};
|
|
3020
|
+
const keyOf = ${NATIVE_SAFETY_RUNTIME_KEY_SOURCE};
|
|
3021
|
+
const schema = "hasna.hooks.native-safety-runtime-digest/v1";
|
|
3022
|
+
const digests = path.join(b.home, "${NATIVE_SAFETY_DIGEST_DIR}");
|
|
3023
|
+
const entry = path.join(digests, crypto.createHash("sha256").update(b.runtime).digest("hex") + ".json");
|
|
3024
|
+
const privateDirectory = () => {
|
|
3025
|
+
ancestry(path.dirname(digests));
|
|
3026
|
+
const s = fs.lstatSync(digests);
|
|
3027
|
+
if (!s.isDirectory() || s.uid !== uid || (s.mode & 0o077)) throw Error();
|
|
3028
|
+
};
|
|
3029
|
+
const remembered = (key) => {
|
|
3030
|
+
try {
|
|
3031
|
+
privateDirectory();
|
|
3032
|
+
const fd = fs.openSync(entry, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
3033
|
+
try {
|
|
3034
|
+
const s = fs.fstatSync(fd);
|
|
3035
|
+
if (!s.isFile() || s.uid !== uid || (s.mode & 0o077) || s.nlink !== 1 || s.size > 4096) return false;
|
|
3036
|
+
const e = JSON.parse(fs.readFileSync(fd, "utf8"));
|
|
3037
|
+
return !!e && Object.keys(e).sort().join() === "key,path,schema,sha256" && e.schema === schema
|
|
3038
|
+
&& e.path === b.runtime && e.sha256 === b.runtimeSHA256 && e.key === key;
|
|
3039
|
+
} finally { fs.closeSync(fd); }
|
|
3040
|
+
} catch { return false; }
|
|
3041
|
+
};
|
|
3042
|
+
const remember = (key) => {
|
|
3043
|
+
let temporary;
|
|
3044
|
+
try {
|
|
3045
|
+
ancestry(path.dirname(digests));
|
|
3046
|
+
try { fs.mkdirSync(digests, { mode: 0o700 }); } catch (error) { if (error.code !== "EEXIST") return; }
|
|
3047
|
+
privateDirectory();
|
|
3048
|
+
temporary = path.join(digests, "." + process.pid + "." + crypto.randomBytes(8).toString("hex") + ".tmp");
|
|
3049
|
+
const fd = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
|
|
3050
|
+
try { fs.writeFileSync(fd, JSON.stringify({ schema, path: b.runtime, sha256: b.runtimeSHA256, key })); } finally { fs.closeSync(fd); }
|
|
3051
|
+
fs.renameSync(temporary, entry);
|
|
3052
|
+
temporary = undefined;
|
|
3053
|
+
} catch {} finally { if (temporary) try { fs.unlinkSync(temporary); } catch {} }
|
|
3054
|
+
};
|
|
3055
|
+
const verifyRuntime = () => {
|
|
3056
|
+
const fd = open(b.runtime, 200_000_000);
|
|
3057
|
+
try {
|
|
3058
|
+
const key = keyOf(fs.fstatSync(fd, { bigint: true }));
|
|
3059
|
+
if (key !== null && remembered(key)) return;
|
|
3060
|
+
const hash = crypto.createHash("sha256"), chunk = Buffer.allocUnsafe(1_048_576);
|
|
3061
|
+
for (let total = 0, n; (n = fs.readSync(fd, chunk, 0, chunk.length, null)) > 0;) {
|
|
3062
|
+
total += n;
|
|
3063
|
+
if (total > 200_000_000) throw Error();
|
|
3064
|
+
hash.update(chunk.subarray(0, n));
|
|
3065
|
+
}
|
|
3066
|
+
if (hash.digest("hex") !== b.runtimeSHA256) throw Error();
|
|
3067
|
+
if (key !== null && keyOf(fs.fstatSync(fd, { bigint: true })) === key) remember(key);
|
|
3068
|
+
} finally { fs.closeSync(fd); }
|
|
3069
|
+
};
|
|
3070
|
+
verifyRuntime();
|
|
3071
|
+
const bytes = check(b.worker, b.workerSHA256, 256_000);
|
|
3072
|
+
const deadline = setTimeout(timedOut, 1500);
|
|
3073
|
+
const chunks = []; let size = 0;
|
|
3074
|
+
for await (const chunk of process.stdin) {
|
|
3075
|
+
size += chunk.length;
|
|
3076
|
+
if (size > 1_048_576) throw Error();
|
|
3077
|
+
chunks.push(chunk);
|
|
3078
|
+
}
|
|
3079
|
+
clearTimeout(deadline);
|
|
3080
|
+
const input = Buffer.concat(chunks);
|
|
3081
|
+
const child = cp.spawnSync(b.runtime, ["--config=/dev/null", "--no-env-file", "--no-macros", "--no-install", "--eval", bytes.toString("utf8"), b.name], {
|
|
3082
|
+
input, env: { HOME: b.home, PATH: b.path }, cwd: "/", timeout: 2500, killSignal: "SIGKILL", maxBuffer: 1_048_576,
|
|
3083
|
+
});
|
|
3084
|
+
if (child.error?.code === "ETIMEDOUT") timedOut();
|
|
3085
|
+
if (child.error || child.status !== 0 || child.signal || child.stderr.length) throw Error();
|
|
3086
|
+
const result = JSON.parse(child.stdout.toString("utf8"));
|
|
3087
|
+
if (!result || Array.isArray(result) || Object.keys(result).length !== 1) throw Error();
|
|
3088
|
+
if (result.verdict === null) return;
|
|
3089
|
+
const output = result.verdict?.hookSpecificOutput;
|
|
3090
|
+
if (!output || Object.keys(result.verdict).length !== 1 || output.hookEventName !== "PreToolUse") throw Error();
|
|
3091
|
+
if (output.permissionDecision === "deny") {
|
|
3092
|
+
if (Object.keys(output).sort().join() !== "hookEventName,permissionDecision,permissionDecisionReason" || typeof output.permissionDecisionReason !== "string" || !output.permissionDecisionReason.trim()) throw Error();
|
|
3093
|
+
} else if (output.permissionDecision === "allow") {
|
|
3094
|
+
if (b.name !== "trash-guard" || Object.keys(output).sort().join() !== "hookEventName,permissionDecision,updatedInput" || !output.updatedInput || typeof output.updatedInput.command !== "string" || !output.updatedInput.command.trim()) throw Error();
|
|
3095
|
+
} else throw Error();
|
|
3096
|
+
process.stdout.write(JSON.stringify(result.verdict));
|
|
3097
|
+
} catch { fail(); }
|
|
3098
|
+
}`;
|
|
3099
|
+
var quote = (value) => "'" + value.replaceAll("'", "'\\''") + "'";
|
|
3100
|
+
var program = `(${supervisorSource})(process.argv[1]);`;
|
|
3101
|
+
var shell = `cd / || exit 2
|
|
3102
|
+
exec 3<&0 || exit 2
|
|
3103
|
+
/usr/bin/env -i HOME="$3" PATH="$4" "$2" --config=/dev/null --no-env-file --no-macros --no-install --eval ${quote(program)} "$1" <&3 3<&- 2>/dev/null &
|
|
3104
|
+
runner=$!
|
|
3105
|
+
exec 3<&-
|
|
3106
|
+
(fired=0; trap 'kill "$sleeper" 2>/dev/null; exit "$fired"' TERM; /bin/sleep 6 & sleeper=$!; wait "$sleeper"; fired=3; kill -KILL "$runner" 2>/dev/null; exit 3) &
|
|
3107
|
+
watchdog=$!
|
|
3108
|
+
wait "$runner" 2>/dev/null; result=$?
|
|
3109
|
+
kill "$watchdog" 2>/dev/null; wait "$watchdog" 2>/dev/null; fired=$?
|
|
3110
|
+
if [ "$result" -eq 0 ]; then exit 0; fi
|
|
3111
|
+
if [ "$result" -eq ${NATIVE_SAFETY_TIMEOUT_STATUS} ] || { [ "$fired" -eq 3 ] && [ "$result" -gt 128 ]; }; then printf '%s\\n' ${quote(NATIVE_SAFETY_TIMEOUT_MESSAGE)} >&2; exit 2; fi
|
|
3112
|
+
printf '%s\\n' ${quote(NATIVE_SAFETY_FAILURE_MESSAGE)} >&2; exit 2`;
|
|
3113
|
+
var marker = " hasna-native-safety-v1 ";
|
|
3114
|
+
var prefix = `/usr/bin/env -i /bin/sh -c ${quote(shell)}${marker}`;
|
|
3115
|
+
var previousSupervisorSource = String.raw`async function supervise(encoded) {
|
|
2932
3116
|
const fs = require("node:fs");
|
|
2933
3117
|
const path = require("node:path");
|
|
2934
3118
|
const crypto = require("node:crypto");
|
|
@@ -2981,11 +3165,10 @@ var supervisorSource = String.raw`async function supervise(encoded) {
|
|
|
2981
3165
|
process.stdout.write(JSON.stringify(result.verdict));
|
|
2982
3166
|
} catch { fail(); }
|
|
2983
3167
|
}`;
|
|
2984
|
-
var
|
|
2985
|
-
var
|
|
2986
|
-
var shell = `cd / || exit 2
|
|
3168
|
+
var previousProgram = `(${previousSupervisorSource})(process.argv[1]);`;
|
|
3169
|
+
var previousShell = `cd / || exit 2
|
|
2987
3170
|
exec 3<&0 || exit 2
|
|
2988
|
-
/usr/bin/env -i HOME="$3" PATH="$4" "$2" --config=/dev/null --no-env-file --no-macros --no-install --eval ${quote(
|
|
3171
|
+
/usr/bin/env -i HOME="$3" PATH="$4" "$2" --config=/dev/null --no-env-file --no-macros --no-install --eval ${quote(previousProgram)} "$1" <&3 3<&- 2>/dev/null &
|
|
2989
3172
|
runner=$!
|
|
2990
3173
|
exec 3<&-
|
|
2991
3174
|
(trap 'kill "$sleeper" 2>/dev/null; exit 0' TERM; /bin/sleep 6 & sleeper=$!; wait "$sleeper"; kill -KILL "$runner" 2>/dev/null) &
|
|
@@ -2993,28 +3176,39 @@ watchdog=$!
|
|
|
2993
3176
|
wait "$runner"; result=$?
|
|
2994
3177
|
kill "$watchdog" 2>/dev/null; wait "$watchdog" 2>/dev/null
|
|
2995
3178
|
if [ "$result" -ne 0 ]; then printf '%s\\n' 'Native safety guard refused: verification or execution failed.' >&2; exit 2; fi`;
|
|
2996
|
-
var
|
|
3179
|
+
var previousPrefix = `/usr/bin/env -i /bin/sh -c ${quote(previousShell)}${marker}`;
|
|
2997
3180
|
function validateBinding(b) {
|
|
2998
3181
|
if (!b || !isNativeSafetyName(b.name) || ![b.runtime, b.worker, b.home].every((p) => typeof p === "string" && isAbsolute2(p) && !/[\0\r\n]/.test(p)) || ![b.runtimeSHA256, b.workerSHA256].every((h) => /^[0-9a-f]{64}$/.test(h)) || typeof b.path !== "string" || b.path.split(":").some((p) => !isAbsolute2(p) || /[\0\r\n]/.test(p)))
|
|
2999
3182
|
throw new Error("Invalid native safety binding");
|
|
3000
3183
|
}
|
|
3001
|
-
function
|
|
3184
|
+
function commandWith(head, binding) {
|
|
3002
3185
|
validateBinding(binding);
|
|
3003
3186
|
const encoded = Buffer.from(JSON.stringify(binding)).toString("base64url");
|
|
3004
|
-
return
|
|
3187
|
+
return head + [encoded, binding.runtime, binding.home, binding.path].map(quote).join(" ");
|
|
3188
|
+
}
|
|
3189
|
+
function buildNativeSafetyCommand(binding) {
|
|
3190
|
+
return commandWith(prefix, binding);
|
|
3191
|
+
}
|
|
3192
|
+
function managedPrefix(command) {
|
|
3193
|
+
if (command.startsWith(prefix))
|
|
3194
|
+
return prefix;
|
|
3195
|
+
if (command.startsWith(previousPrefix))
|
|
3196
|
+
return previousPrefix;
|
|
3197
|
+
return;
|
|
3005
3198
|
}
|
|
3006
3199
|
function nativeSafetyRegistration(command) {
|
|
3007
3200
|
return nativeSafetyCommandBinding(command)?.name;
|
|
3008
3201
|
}
|
|
3009
3202
|
function nativeSafetyCommandBinding(command) {
|
|
3010
|
-
|
|
3203
|
+
const head = managedPrefix(command);
|
|
3204
|
+
if (!head)
|
|
3011
3205
|
return;
|
|
3012
|
-
const encoded = command.slice(
|
|
3206
|
+
const encoded = command.slice(head.length).match(/^'([A-Za-z0-9_-]+)' /)?.[1];
|
|
3013
3207
|
if (!encoded || encoded.length > 16384)
|
|
3014
3208
|
return;
|
|
3015
3209
|
try {
|
|
3016
3210
|
const binding = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
|
|
3017
|
-
return
|
|
3211
|
+
return commandWith(head, binding) === command ? binding : undefined;
|
|
3018
3212
|
} catch {
|
|
3019
3213
|
return;
|
|
3020
3214
|
}
|
|
@@ -3043,7 +3237,7 @@ function pinEligibleFile(file, maximum, executable = false) {
|
|
|
3043
3237
|
closeSync(fd);
|
|
3044
3238
|
}
|
|
3045
3239
|
}
|
|
3046
|
-
function
|
|
3240
|
+
function installedNativeSafetyBinding(name) {
|
|
3047
3241
|
const home = realpathSync2(homedir2());
|
|
3048
3242
|
const runtime = realpathSync2(process.execPath);
|
|
3049
3243
|
const candidates = [join5(import.meta.dir, "../../bin/native-safety-entry.js"), join5(import.meta.dir, "../bin/native-safety-entry.js"), join5(import.meta.dir, "native-safety-entry.js")];
|
|
@@ -3051,7 +3245,10 @@ function installedNativeSafetyCommand(name) {
|
|
|
3051
3245
|
if (!worker)
|
|
3052
3246
|
throw new Error("Bundled native safety runner is missing; build or reinstall @hasna/hooks before installing its guards.");
|
|
3053
3247
|
const canonicalWorker = realpathSync2(worker);
|
|
3054
|
-
return
|
|
3248
|
+
return { name, runtime, runtimeSHA256: pinEligibleFile(runtime, 200000000, true), worker: canonicalWorker, workerSHA256: pinEligibleFile(canonicalWorker, 256000), home, path: `${dirname3(runtime)}:${join5(home, ".bun/bin")}:/usr/local/bin:/usr/bin:/bin` };
|
|
3249
|
+
}
|
|
3250
|
+
function installedNativeSafetyCommand(name) {
|
|
3251
|
+
return buildNativeSafetyCommand(installedNativeSafetyBinding(name));
|
|
3055
3252
|
}
|
|
3056
3253
|
|
|
3057
3254
|
// src/lib/native-readiness-command.ts
|
|
@@ -3206,8 +3403,232 @@ function retainedMementosRegistration(commands) {
|
|
|
3206
3403
|
return values[0];
|
|
3207
3404
|
}
|
|
3208
3405
|
|
|
3406
|
+
// src/lib/targets.ts
|
|
3407
|
+
import { homedir as homedir4 } from "os";
|
|
3408
|
+
import { dirname as dirname5, join as join7, resolve as resolve3 } from "path";
|
|
3409
|
+
var TARGET_NAMES = [
|
|
3410
|
+
"claude",
|
|
3411
|
+
"codex",
|
|
3412
|
+
"gemini",
|
|
3413
|
+
"codewith",
|
|
3414
|
+
"qwen",
|
|
3415
|
+
"muse",
|
|
3416
|
+
"kimi",
|
|
3417
|
+
"pi",
|
|
3418
|
+
"cursor",
|
|
3419
|
+
"opencode",
|
|
3420
|
+
"sumi"
|
|
3421
|
+
];
|
|
3422
|
+
var INSTALL_TARGET_NAMES = [
|
|
3423
|
+
"claude",
|
|
3424
|
+
"codex",
|
|
3425
|
+
"gemini",
|
|
3426
|
+
"codewith",
|
|
3427
|
+
"qwen",
|
|
3428
|
+
"muse",
|
|
3429
|
+
"kimi",
|
|
3430
|
+
"pi",
|
|
3431
|
+
"cursor"
|
|
3432
|
+
];
|
|
3433
|
+
function isTargetName(value) {
|
|
3434
|
+
return typeof value === "string" && TARGET_NAMES.includes(value);
|
|
3435
|
+
}
|
|
3436
|
+
var settingsJson = (dir) => (o) => o.scope === "project" ? join7(resolve3(o.cwd), dir, "settings.json") : join7(o.home, dir, "settings.json");
|
|
3437
|
+
var DEFINITIONS = {
|
|
3438
|
+
claude: {
|
|
3439
|
+
install: true,
|
|
3440
|
+
run: true,
|
|
3441
|
+
stopEvent: "Stop",
|
|
3442
|
+
canBlock: true,
|
|
3443
|
+
deliversFinalMessage: true,
|
|
3444
|
+
finalMessageField: "last_assistant_message",
|
|
3445
|
+
path: settingsJson(".claude")
|
|
3446
|
+
},
|
|
3447
|
+
codex: {
|
|
3448
|
+
install: true,
|
|
3449
|
+
run: true,
|
|
3450
|
+
stopEvent: "Stop",
|
|
3451
|
+
canBlock: true,
|
|
3452
|
+
deliversFinalMessage: true,
|
|
3453
|
+
finalMessageField: "last_assistant_message",
|
|
3454
|
+
path: (o) => o.scope === "project" ? join7(resolve3(o.cwd), ".codex", "hooks.json") : join7(o.home, ".codex", "hooks.json")
|
|
3455
|
+
},
|
|
3456
|
+
gemini: {
|
|
3457
|
+
install: true,
|
|
3458
|
+
run: true,
|
|
3459
|
+
stopEvent: "AfterAgent",
|
|
3460
|
+
canBlock: true,
|
|
3461
|
+
deliversFinalMessage: true,
|
|
3462
|
+
finalMessageField: "prompt_response",
|
|
3463
|
+
path: settingsJson(".gemini")
|
|
3464
|
+
},
|
|
3465
|
+
codewith: {
|
|
3466
|
+
install: true,
|
|
3467
|
+
run: true,
|
|
3468
|
+
stopEvent: "Stop",
|
|
3469
|
+
canBlock: true,
|
|
3470
|
+
deliversFinalMessage: true,
|
|
3471
|
+
finalMessageField: "last_assistant_message",
|
|
3472
|
+
path: (o) => o.scope === "project" ? join7(resolve3(o.cwd), ".codewith", "config.toml") : join7(o.home, ".codewith", "config.toml")
|
|
3473
|
+
},
|
|
3474
|
+
qwen: {
|
|
3475
|
+
install: true,
|
|
3476
|
+
run: true,
|
|
3477
|
+
stopEvent: "Stop",
|
|
3478
|
+
canBlock: true,
|
|
3479
|
+
deliversFinalMessage: true,
|
|
3480
|
+
finalMessageField: "last_assistant_message",
|
|
3481
|
+
path: settingsJson(".qwen")
|
|
3482
|
+
},
|
|
3483
|
+
muse: {
|
|
3484
|
+
install: true,
|
|
3485
|
+
run: true,
|
|
3486
|
+
stopEvent: "Stop",
|
|
3487
|
+
canBlock: true,
|
|
3488
|
+
deliversFinalMessage: true,
|
|
3489
|
+
finalMessageField: "last_assistant_message",
|
|
3490
|
+
installNote: "Muse receives the final message as a quoted JSON string; `hooks run --target muse` parses it once before the hook sees it.",
|
|
3491
|
+
path: (o) => join7(o.home, ".hasna", "hooks", "muse-plugins", o.hook ?? "")
|
|
3492
|
+
},
|
|
3493
|
+
kimi: {
|
|
3494
|
+
install: true,
|
|
3495
|
+
run: true,
|
|
3496
|
+
stopEvent: "Stop",
|
|
3497
|
+
canBlock: true,
|
|
3498
|
+
deliversFinalMessage: false,
|
|
3499
|
+
finalMessageNote: "Kimi's Stop payload carries only hook_event_name, session_id, cwd, client_type, session_title and stop_hook_active",
|
|
3500
|
+
path: (o) => join7(o.home, ".kimi-code", "config.toml")
|
|
3501
|
+
},
|
|
3502
|
+
pi: {
|
|
3503
|
+
install: true,
|
|
3504
|
+
run: true,
|
|
3505
|
+
stopEvent: "turn_end",
|
|
3506
|
+
canBlock: true,
|
|
3507
|
+
deliversFinalMessage: false,
|
|
3508
|
+
finalMessageNote: "the pi-hooks bridge sends only hook_event_name, session_id, cwd and stop_hook_active (transcript_path is declared but never populated)",
|
|
3509
|
+
installNote: "Pi runs hooks through the hasna-pi-hooks bridge: the config points at a Hooks profile, so registration is not by itself proof that a turn was held.",
|
|
3510
|
+
path: (o) => join7(o.home, ".pi", "agent", "state", "hasna-pi-hooks.config.json")
|
|
3511
|
+
},
|
|
3512
|
+
cursor: {
|
|
3513
|
+
install: true,
|
|
3514
|
+
run: true,
|
|
3515
|
+
stopEvent: "stop",
|
|
3516
|
+
canBlock: false,
|
|
3517
|
+
deliversFinalMessage: false,
|
|
3518
|
+
finalMessageNote: "Cursor's stop hook carries no assistant text",
|
|
3519
|
+
blockNote: "a block verdict is ignored, and only followup_message continues a turn (loop_limit 5)",
|
|
3520
|
+
installNote: "Cursor's stop hook cannot block the turn: a block verdict is ignored, and only followup_message continues a turn (loop_limit 5). The registration alone does not hold anything.",
|
|
3521
|
+
path: (o) => o.scope === "project" ? join7(resolve3(o.cwd), ".cursor", "hooks.json") : join7(o.home, ".cursor", "hooks.json")
|
|
3522
|
+
},
|
|
3523
|
+
opencode: {
|
|
3524
|
+
install: false,
|
|
3525
|
+
run: true,
|
|
3526
|
+
stopEvent: null,
|
|
3527
|
+
canBlock: false,
|
|
3528
|
+
deliversFinalMessage: false,
|
|
3529
|
+
blockNote: "opencode has no turn-end event to hold: session.prompt schedules a new agent-loop run instead of continuing the current turn",
|
|
3530
|
+
stopEventSubstitute: "opencode has only the session.idle bus event, which is observe-only and cannot hold the turn; `hooks install stop-review --target opencode` registers the managed observe-and-re-prompt plugin",
|
|
3531
|
+
path: (o) => {
|
|
3532
|
+
const xdg = o.env.XDG_CONFIG_HOME;
|
|
3533
|
+
const base = xdg && xdg.startsWith("/") ? xdg : join7(o.home, ".config");
|
|
3534
|
+
return join7(resolve3(base), "opencode", "opencode.json");
|
|
3535
|
+
}
|
|
3536
|
+
},
|
|
3537
|
+
sumi: {
|
|
3538
|
+
install: false,
|
|
3539
|
+
run: true,
|
|
3540
|
+
stopEvent: "Stop",
|
|
3541
|
+
canBlock: true,
|
|
3542
|
+
deliversFinalMessage: true,
|
|
3543
|
+
finalMessageField: "last_assistant_message",
|
|
3544
|
+
stopEventSubstitute: "Sumi stop review is registered through the managed path: `hooks install stop-review --target sumi`",
|
|
3545
|
+
path: (o) => join7(o.home, ".sumi", "plugins")
|
|
3546
|
+
}
|
|
3547
|
+
};
|
|
3548
|
+
function getTargetCapabilities(target, options = {}) {
|
|
3549
|
+
if (!isTargetName(target))
|
|
3550
|
+
return;
|
|
3551
|
+
const definition = DEFINITIONS[target];
|
|
3552
|
+
const resolved = {
|
|
3553
|
+
scope: options.scope ?? "global",
|
|
3554
|
+
home: options.home ?? homedir4(),
|
|
3555
|
+
cwd: options.cwd ?? process.cwd(),
|
|
3556
|
+
env: options.env ?? process.env,
|
|
3557
|
+
hook: options.hook
|
|
3558
|
+
};
|
|
3559
|
+
return {
|
|
3560
|
+
install: definition.install,
|
|
3561
|
+
run: definition.run,
|
|
3562
|
+
stopEvent: definition.stopEvent,
|
|
3563
|
+
canBlock: definition.canBlock,
|
|
3564
|
+
deliversFinalMessage: definition.deliversFinalMessage,
|
|
3565
|
+
configPath: definition.path(resolved)
|
|
3566
|
+
};
|
|
3567
|
+
}
|
|
3568
|
+
function musePluginRoot(options = {}) {
|
|
3569
|
+
return dirname5(getTargetCapabilities("muse", { ...options, hook: "bundle" }).configPath);
|
|
3570
|
+
}
|
|
3571
|
+
function targetInstallNote(target) {
|
|
3572
|
+
return isTargetName(target) ? DEFINITIONS[target].installNote : undefined;
|
|
3573
|
+
}
|
|
3574
|
+
function runTargetHelp() {
|
|
3575
|
+
return TARGET_NAMES.join(", ");
|
|
3576
|
+
}
|
|
3577
|
+
function blockingInstallTargets() {
|
|
3578
|
+
return INSTALL_TARGET_NAMES.filter((name) => DEFINITIONS[name].canBlock);
|
|
3579
|
+
}
|
|
3580
|
+
function installCapabilityRefusal(hook, target, requirement, options = {}) {
|
|
3581
|
+
const definition = isTargetName(target) ? DEFINITIONS[target] : undefined;
|
|
3582
|
+
if (!definition) {
|
|
3583
|
+
return `Refused: Unknown target '${target}'. Known targets: ${runTargetHelp()}.`;
|
|
3584
|
+
}
|
|
3585
|
+
const capabilities = getTargetCapabilities(target, options);
|
|
3586
|
+
if (requirement.requiresBlock && !capabilities.canBlock) {
|
|
3587
|
+
const others = [];
|
|
3588
|
+
if (!capabilities.install)
|
|
3589
|
+
others.push("no generic install path (install: false)");
|
|
3590
|
+
if (requirement.requiresFinalMessage && !capabilities.deliversFinalMessage)
|
|
3591
|
+
others.push("no final assistant message (deliversFinalMessage: false)");
|
|
3592
|
+
if (requirement.events.includes("Stop") && capabilities.stopEvent === null)
|
|
3593
|
+
others.push("no turn-end event (stopEvent: null)");
|
|
3594
|
+
const also = others.length === 0 ? "" : ` It also has ${others.join(" and ")}.`;
|
|
3595
|
+
return `Refused: '${hook}' declares requires_block, and target '${target}' cannot hold the turn (canBlock: false) \u2014 ${definition.blockNote ?? "a block verdict is ignored there"}.${also} ` + `Unblock it by installing on a target that can block (${blockingInstallTargets().join(", ")}), or by clearing requires_block in the hook's manifest.`;
|
|
3596
|
+
}
|
|
3597
|
+
if (requirement.requiresFinalMessage && !capabilities.deliversFinalMessage) {
|
|
3598
|
+
const others = [];
|
|
3599
|
+
if (!capabilities.install)
|
|
3600
|
+
others.push("no generic install path (install: false)");
|
|
3601
|
+
if (requirement.requiresBlock && !capabilities.canBlock)
|
|
3602
|
+
others.push("no turn-holding verdict (canBlock: false)");
|
|
3603
|
+
if (requirement.events.includes("Stop") && capabilities.stopEvent === null)
|
|
3604
|
+
others.push("no turn-end event (stopEvent: null)");
|
|
3605
|
+
const also = others.length === 0 ? "" : ` It also has ${others.join(" and ")}.`;
|
|
3606
|
+
return `Refused: '${hook}' declares requires_final_message, and target '${target}' does not deliver the assistant's final message (deliversFinalMessage: false) \u2014 ${definition.finalMessageNote ?? "its payload carries no assistant text"}.${also} ` + `Unblock it by installing on a target that delivers the message (${INSTALL_TARGET_NAMES.filter((name) => DEFINITIONS[name].deliversFinalMessage).join(", ")}), or by clearing requires_final_message in the hook's manifest.`;
|
|
3607
|
+
}
|
|
3608
|
+
if (!capabilities.install) {
|
|
3609
|
+
return `Refused: Hooks has no generic install path for target '${target}' (install: false). ${definition.stopEventSubstitute ?? `Supported install targets: ${INSTALL_TARGET_NAMES.join(", ")}.`}`;
|
|
3610
|
+
}
|
|
3611
|
+
if (requirement.events.includes("Stop") && capabilities.stopEvent === null) {
|
|
3612
|
+
return `Refused: '${hook}' runs on the Stop event, and target '${target}' has no turn-end event (stopEvent: null), so nothing would ever run it. ${definition.stopEventSubstitute ?? ""}`.trim();
|
|
3613
|
+
}
|
|
3614
|
+
return;
|
|
3615
|
+
}
|
|
3616
|
+
|
|
3617
|
+
// src/lib/native-target.ts
|
|
3618
|
+
var HOOK_RUN_TARGETS = TARGET_NAMES;
|
|
3619
|
+
function isHookRunTarget(value) {
|
|
3620
|
+
return typeof value === "string" && HOOK_RUN_TARGETS.includes(value);
|
|
3621
|
+
}
|
|
3622
|
+
function nativeTargetCommandSuffix(dispatch, target) {
|
|
3623
|
+
if (!dispatch)
|
|
3624
|
+
return "";
|
|
3625
|
+
if (!isHookRunTarget(target))
|
|
3626
|
+
throw new Error("Native registration requires a supported target");
|
|
3627
|
+
return ` --target ${target}`;
|
|
3628
|
+
}
|
|
3629
|
+
|
|
3209
3630
|
// src/lib/registration.ts
|
|
3210
|
-
var REGISTRATION_COMMAND_RE =
|
|
3631
|
+
var REGISTRATION_COMMAND_RE = new RegExp(`^(?:hooks run ([\\w-]+)(?:\\s+--profile\\s+[\\w-]+)?(?:\\s+--target\\s+(?:${HOOK_RUN_TARGETS.join("|")}))?|hook-([\\w-]+))$`);
|
|
3211
3632
|
function registrationName(command) {
|
|
3212
3633
|
if (typeof command !== "string")
|
|
3213
3634
|
return;
|
|
@@ -3284,7 +3705,7 @@ function hookRegisteredInSettings(settings, name, eventSpec, hookMatcher) {
|
|
|
3284
3705
|
// src/lib/store.ts
|
|
3285
3706
|
import { createHash as createHash4 } from "crypto";
|
|
3286
3707
|
import { existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync2, renameSync, lstatSync as lstatSync3 } from "fs";
|
|
3287
|
-
import { join as
|
|
3708
|
+
import { join as join10 } from "path";
|
|
3288
3709
|
init_db();
|
|
3289
3710
|
init_config();
|
|
3290
3711
|
init_manifest();
|
|
@@ -3402,7 +3823,7 @@ function getPinnedHook(name) {
|
|
|
3402
3823
|
return readLock().hooks[name];
|
|
3403
3824
|
}
|
|
3404
3825
|
function registryManagedMarker(name) {
|
|
3405
|
-
return
|
|
3826
|
+
return join10(getHooksDataDir(), "registry-managed", sha256Of(name) + ".json");
|
|
3406
3827
|
}
|
|
3407
3828
|
function isRegistryManaged(name) {
|
|
3408
3829
|
try {
|
|
@@ -3476,7 +3897,7 @@ function checkScriptHash(name, actual) {
|
|
|
3476
3897
|
|
|
3477
3898
|
// src/lib/codex-settings.ts
|
|
3478
3899
|
import { closeSync as closeSync3, existsSync as existsSync9, lstatSync as lstatSync4, mkdirSync as mkdirSync4, openSync as openSync3, readFileSync as readFileSync6, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
|
|
3479
|
-
import { dirname as
|
|
3900
|
+
import { dirname as dirname6 } from "path";
|
|
3480
3901
|
import { createHash as createHash5, randomUUID } from "crypto";
|
|
3481
3902
|
var snapshots = new WeakMap;
|
|
3482
3903
|
function current(path) {
|
|
@@ -3529,7 +3950,7 @@ function writeCodexSettings(path, settings, expectedSha256, beforeWrite) {
|
|
|
3529
3950
|
` });
|
|
3530
3951
|
}
|
|
3531
3952
|
function writeHookSettingsPreimage(path, settings, before, beforeWrite) {
|
|
3532
|
-
mkdirSync4(
|
|
3953
|
+
mkdirSync4(dirname6(path), { recursive: true, mode: 448 });
|
|
3533
3954
|
const lock = `${path}.hooks-write.lock`;
|
|
3534
3955
|
let fd;
|
|
3535
3956
|
try {
|
|
@@ -3559,18 +3980,15 @@ function writeHookSettingsPreimage(path, settings, before, beforeWrite) {
|
|
|
3559
3980
|
// src/lib/claude-skills-coordination.ts
|
|
3560
3981
|
import { createHash as createHash8 } from "crypto";
|
|
3561
3982
|
import { existsSync as existsSync11, lstatSync as lstatSync9 } from "fs";
|
|
3562
|
-
import { homedir as
|
|
3563
|
-
import { join as
|
|
3983
|
+
import { homedir as homedir7 } from "os";
|
|
3984
|
+
import { join as join17, resolve as resolve9 } from "path";
|
|
3564
3985
|
|
|
3565
|
-
// node_modules/@hasna/skills/dist/index.js
|
|
3986
|
+
// ../../node_modules/.bun/@hasna+skills@0.10.78+a00d3064559565bb/node_modules/@hasna/skills/dist/index.js
|
|
3566
3987
|
import { existsSync as existsSync10 } from "fs";
|
|
3567
|
-
import { homedir as
|
|
3568
|
-
import { join as
|
|
3988
|
+
import { homedir as homedir6 } from "os";
|
|
3989
|
+
import { join as join11, resolve as resolve4 } from "path";
|
|
3569
3990
|
import { homedir as pathsResolverHomedir2 } from "os";
|
|
3570
3991
|
import { join as pathsResolverJoin2 } from "path";
|
|
3571
|
-
import { createHash as createHash6 } from "crypto";
|
|
3572
|
-
import { existsSync as existsSync52, readdirSync as readdirSync3, readFileSync as readFileSync42, statSync as statSync4 } from "fs";
|
|
3573
|
-
import { join as join52, sep as sep2 } from "path";
|
|
3574
3992
|
import { createHash as createHash32 } from "crypto";
|
|
3575
3993
|
import { createHash as createHash22 } from "crypto";
|
|
3576
3994
|
import { closeSync as closeSync22, constants as constants22, fstatSync as fstatSync22, lstatSync as lstatSync42, openSync as openSync22, readSync } from "fs";
|
|
@@ -3580,14 +3998,14 @@ import { createHash as createHash42 } from "crypto";
|
|
|
3580
3998
|
import { basename as basename3, dirname as dirname42, isAbsolute as isAbsolute32, resolve as resolve32 } from "path";
|
|
3581
3999
|
import { createHash as createHash52 } from "crypto";
|
|
3582
4000
|
import { closeSync as closeSync32, constants as constants3, fstatSync as fstatSync3, lstatSync as lstatSync5, openSync as openSync32, readSync as readSync2 } from "fs";
|
|
3583
|
-
import { basename as basename4, dirname as dirname52, isAbsolute as isAbsolute4, resolve as
|
|
4001
|
+
import { basename as basename4, dirname as dirname52, isAbsolute as isAbsolute4, resolve as resolve42, sep as sep2 } from "path";
|
|
3584
4002
|
import { createHash as createHash30 } from "crypto";
|
|
3585
|
-
import { lstatSync as lstatSync32, readFileSync as readFileSync26, readdirSync as
|
|
4003
|
+
import { lstatSync as lstatSync32, readFileSync as readFileSync26, readdirSync as readdirSync13, realpathSync as realpathSync13 } from "fs";
|
|
3586
4004
|
import { basename as basename15, dirname as dirname26, isAbsolute as isAbsolute28, join as join38, relative as relative10, resolve as resolve27, sep as sep15 } from "path";
|
|
3587
4005
|
import { isDeepStrictEqual as isDeepStrictEqual9 } from "util";
|
|
3588
|
-
import { dirname as
|
|
4006
|
+
import { dirname as dirname62, isAbsolute as isAbsolute6, join as join82, resolve as resolve6 } from "path";
|
|
3589
4007
|
import { lstatSync as lstatSync6, readFileSync as readFileSync62, opendirSync } from "fs";
|
|
3590
|
-
import { createHash as
|
|
4008
|
+
import { createHash as createHash6 } from "crypto";
|
|
3591
4009
|
import { lstatSync as lstatSync7, opendirSync as opendirSync2 } from "fs";
|
|
3592
4010
|
import { dirname as dirname7, isAbsolute as isAbsolute7, join as join92, resolve as resolve7 } from "path";
|
|
3593
4011
|
import { createHash as createHash7 } from "crypto";
|
|
@@ -3607,11 +4025,11 @@ import { isDeepStrictEqual as isDeepStrictEqual4 } from "util";
|
|
|
3607
4025
|
import { createHash as createHash15 } from "crypto";
|
|
3608
4026
|
import { lstatSync as lstatSync11, readlinkSync as readlinkSync2 } from "fs";
|
|
3609
4027
|
import { dirname as dirname12, isAbsolute as isAbsolute12, join as join14, parse as parse5, resolve as resolve12, sep as sep5 } from "path";
|
|
3610
|
-
import { lstatSync as lstatSync15, readdirSync as
|
|
4028
|
+
import { lstatSync as lstatSync15, readdirSync as readdirSync7, readFileSync as readFileSync12 } from "fs";
|
|
3611
4029
|
import { isAbsolute as isAbsolute16, join as join19, relative as relative6, resolve as resolve16, sep as sep9 } from "path";
|
|
3612
4030
|
import { isDeepStrictEqual as isDeepStrictEqual5 } from "util";
|
|
3613
4031
|
import { basename as basename8, dirname as dirname15, join as join18, relative as relative5, resolve as resolve15, sep as sep8 } from "path";
|
|
3614
|
-
import { lstatSync as lstatSync14, readdirSync as
|
|
4032
|
+
import { lstatSync as lstatSync14, readdirSync as readdirSync6, readFileSync as readFileSync11, readlinkSync as readlinkSync3, realpathSync as realpathSync6 } from "fs";
|
|
3615
4033
|
import { realpathSync as realpathSync5 } from "fs";
|
|
3616
4034
|
import { isAbsolute as isAbsolute15, normalize as normalize3 } from "path";
|
|
3617
4035
|
import { createHash as createHash16 } from "crypto";
|
|
@@ -3619,9 +4037,10 @@ import { fileURLToPath as fileURLToPath2 } from "url";
|
|
|
3619
4037
|
import { spawn, spawnSync as spawnSync2 } from "child_process";
|
|
3620
4038
|
import { closeSync as closeSync7, constants as constants7, fstatSync as fstatSync7, lstatSync as lstatSync12, openSync as openSync7, readFileSync as readFileSync9, realpathSync as realpathSync22 } from "fs";
|
|
3621
4039
|
import { dirname as dirname13, join as join15, parse as parse6, relative as relative3, resolve as resolve13, sep as sep6 } from "path";
|
|
3622
|
-
import {
|
|
4040
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
4041
|
+
import { execFileSync, spawnSync as spawnSync3 } from "child_process";
|
|
3623
4042
|
import { createHash as createHash17 } from "crypto";
|
|
3624
|
-
import { accessSync, constants as constants8, lstatSync as lstatSync13, readFileSync as readFileSync10, realpathSync as realpathSync32, statSync as statSync7 } from "fs";
|
|
4043
|
+
import { accessSync, constants as constants8, lstatSync as lstatSync13, mkdirSync as mkdirSync5, mkdtempSync, readdirSync as readdirSync5, readFileSync as readFileSync10, realpathSync as realpathSync32, rmSync as rmSync2, statSync as statSync7 } from "fs";
|
|
3625
4044
|
import { basename as basename7, delimiter, dirname as dirname14, isAbsolute as isAbsolute13, join as join16, relative as relative4, resolve as resolve14, sep as sep7 } from "path";
|
|
3626
4045
|
import { createHash as createHash19 } from "crypto";
|
|
3627
4046
|
import { closeSync as closeSync18, constants as constants19, fstatSync as fstatSync18, lstatSync as lstatSync30, openSync as openSync18, opendirSync as opendirSync5, readSync as readSync13 } from "fs";
|
|
@@ -3629,39 +4048,38 @@ import { basename as basename13, dirname as dirname24, isAbsolute as isAbsolute2
|
|
|
3629
4048
|
import { isAbsolute as isAbsolute25, join as join36, resolve as resolve24 } from "path";
|
|
3630
4049
|
import { createRequire } from "module";
|
|
3631
4050
|
import { createHash as createHash21, randomUUID as randomUUID3 } from "crypto";
|
|
3632
|
-
import { closeSync as closeSync11, constants as constants11, fstatSync as fstatSync11, fsyncSync as fsyncSync3, lstatSync as lstatSync19, mkdirSync as
|
|
4051
|
+
import { closeSync as closeSync11, constants as constants11, fstatSync as fstatSync11, fsyncSync as fsyncSync3, lstatSync as lstatSync19, mkdirSync as mkdirSync7, openSync as openSync11, readFileSync as readFileSync15, readSync as readSync7, readlinkSync as readlinkSync4, realpathSync as realpathSync8, renameSync as renameSync3, unlinkSync as unlinkSync4, writeFileSync as writeFileSync4 } from "fs";
|
|
3633
4052
|
import { dirname as dirname17, isAbsolute as isAbsolute18, join as join23, resolve as resolve17 } from "path";
|
|
3634
4053
|
import { isDeepStrictEqual as isDeepStrictEqual6 } from "util";
|
|
3635
4054
|
import { createHash as createHash222 } from "crypto";
|
|
3636
|
-
import { constants as constants12, closeSync as closeSync12, fstatSync as fstatSync12, lstatSync as lstatSync20, openSync as openSync12, readSync as readSync8, readdirSync as
|
|
4055
|
+
import { constants as constants12, closeSync as closeSync12, fstatSync as fstatSync12, lstatSync as lstatSync20, openSync as openSync12, readSync as readSync8, readdirSync as readdirSync9, realpathSync as realpathSync9 } from "fs";
|
|
3637
4056
|
import { basename as basename10, dirname as dirname18, isAbsolute as isAbsolute19, join as join25, relative as relative8, resolve as resolve18, sep as sep11 } from "path";
|
|
3638
4057
|
import { lstatSync as lstatSync21, readFileSync as readFileSync16 } from "fs";
|
|
3639
4058
|
import { dirname as dirname19, join as join26, resolve as resolve19, sep as sep12 } from "path";
|
|
3640
4059
|
import { createHash as createHash27, randomUUID as randomUUID4 } from "crypto";
|
|
3641
4060
|
import { isDeepStrictEqual as isDeepStrictEqual8 } from "util";
|
|
3642
|
-
import { existsSync as existsSync92, lstatSync as lstatSync28, statSync as statSync11, mkdirSync as
|
|
4061
|
+
import { existsSync as existsSync92, lstatSync as lstatSync28, statSync as statSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync19, readdirSync as readdirSync11, opendirSync as opendirSync4, readlinkSync as readlinkSync7, realpathSync as realpathSync12, renameSync as renameSync4, rmdirSync as rmdirSync3, writeFileSync as writeFileSync6, unlinkSync as unlinkSync5, chmodSync, openSync as openSync17, closeSync as closeSync17, fsyncSync as fsyncSync7, fstatSync as fstatSync17, readSync as readSync12, constants as constants18, linkSync as linkSync3 } from "fs";
|
|
3643
4062
|
import { basename as basename11, dirname as dirname22, join as join31, resolve as resolve23, relative as relative9, isAbsolute as isAbsolute24, sep as sep14 } from "path";
|
|
3644
4063
|
import { homedir as homedir22 } from "os";
|
|
3645
4064
|
import { closeSync as closeSync13, constants as constants13, fstatSync as fstatSync13, lstatSync as lstatSync22, openSync as openSync13, readSync as readSync9 } from "fs";
|
|
3646
4065
|
import { join as join27 } from "path";
|
|
3647
4066
|
import { createHash as createHash23 } from "crypto";
|
|
3648
|
-
import { lstatSync as lstatSync23, readFileSync as readFileSync17, readdirSync as
|
|
4067
|
+
import { lstatSync as lstatSync23, readFileSync as readFileSync17, readdirSync as readdirSync10 } from "fs";
|
|
3649
4068
|
import { join as join28 } from "path";
|
|
3650
|
-
import { spawnSync as
|
|
4069
|
+
import { spawnSync as spawnSync5 } from "child_process";
|
|
3651
4070
|
import { accessSync as accessSync2, constants as constants14, existsSync as existsSync82, lstatSync as lstatSync24, realpathSync as realpathSync10, statSync as statSync10 } from "fs";
|
|
3652
4071
|
import { delimiter as delimiter2, isAbsolute as isAbsolute20, join as join29, resolve as resolve20 } from "path";
|
|
3653
4072
|
import { closeSync as closeSync14, constants as constants15, fstatSync as fstatSync14, fsyncSync as fsyncSync4, lstatSync as lstatSync25, openSync as openSync14, readlinkSync as readlinkSync5, readSync as readSync10, writeFileSync as writeFileSync5 } from "fs";
|
|
3654
4073
|
import { createHash as createHash24 } from "crypto";
|
|
3655
4074
|
import { dirname as dirname20, isAbsolute as isAbsolute21, resolve as resolve21 } from "path";
|
|
3656
4075
|
import { createHash as createHash26 } from "crypto";
|
|
3657
|
-
import { constants as constants17, closeSync as closeSync16, fstatSync as fstatSync16, fsyncSync as fsyncSync6, lstatSync as lstatSync27, mkdirSync as
|
|
4076
|
+
import { constants as constants17, closeSync as closeSync16, fstatSync as fstatSync16, fsyncSync as fsyncSync6, lstatSync as lstatSync27, mkdirSync as mkdirSync8, openSync as openSync16, readSync as readSync11, writeSync as writeSync4 } from "fs";
|
|
3658
4077
|
import { dirname as dirname21, isAbsolute as isAbsolute23, join as join30, resolve as resolve222, sep as sep13 } from "path";
|
|
3659
4078
|
import { createHash as createHash28 } from "crypto";
|
|
3660
4079
|
import { closeSync as closeSync19, constants as constants20, fstatSync as fstatSync19, lstatSync as lstatSync31, openSync as openSync19, readSync as readSync14 } from "fs";
|
|
3661
4080
|
import { basename as basename14, dirname as dirname25, isAbsolute as isAbsolute27, resolve as resolve26 } from "path";
|
|
3662
4081
|
import { createHash as createHash29 } from "crypto";
|
|
3663
4082
|
import { isAbsolute as isAbsolute30 } from "path";
|
|
3664
|
-
import { createHash as createHash34 } from "crypto";
|
|
3665
4083
|
var __defProp2 = Object.defineProperty;
|
|
3666
4084
|
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
3667
4085
|
var __returnValue2 = (v) => v;
|
|
@@ -10513,10 +10931,10 @@ var SKILLS_HOME_ENV = "SKILLS_HOME";
|
|
|
10513
10931
|
var DEFAULT_SQLITE_FILENAME = "server.db";
|
|
10514
10932
|
var GLOBAL_CONFIG_FILENAME = "config.json";
|
|
10515
10933
|
function effectiveHome() {
|
|
10516
|
-
return process.env["HOME"] || process.env["USERPROFILE"] ||
|
|
10934
|
+
return process.env["HOME"] || process.env["USERPROFILE"] || homedir6() || "/tmp";
|
|
10517
10935
|
}
|
|
10518
10936
|
function legacyDataRoot() {
|
|
10519
|
-
return
|
|
10937
|
+
return join11(effectiveHome(), ".hasna", "skills");
|
|
10520
10938
|
}
|
|
10521
10939
|
function resolverDataRoot(home = effectiveHome(), env) {
|
|
10522
10940
|
return dataDir2({ app: "skills", home, env });
|
|
@@ -10525,13 +10943,13 @@ function adoptResolverDataRoot2(resolved, env = process.env) {
|
|
|
10525
10943
|
const dataOverride = env.HASNA_DATA_HOME;
|
|
10526
10944
|
if (typeof dataOverride === "string" && dataOverride.trim().length > 0)
|
|
10527
10945
|
return true;
|
|
10528
|
-
return existsSync10(
|
|
10946
|
+
return existsSync10(join11(resolved, DEFAULT_SQLITE_FILENAME)) || existsSync10(join11(resolved, GLOBAL_CONFIG_FILENAME));
|
|
10529
10947
|
}
|
|
10530
10948
|
function exactDataRoot() {
|
|
10531
10949
|
for (const key of [DATA_DIR_ENV, HASNA_SKILLS_HOME_ENV, SKILLS_HOME_ENV]) {
|
|
10532
10950
|
const dir = process.env[key]?.trim();
|
|
10533
10951
|
if (dir)
|
|
10534
|
-
return
|
|
10952
|
+
return resolve4(dir);
|
|
10535
10953
|
}
|
|
10536
10954
|
return;
|
|
10537
10955
|
}
|
|
@@ -10540,7 +10958,7 @@ function getDataRoot() {
|
|
|
10540
10958
|
if (exact)
|
|
10541
10959
|
return exact;
|
|
10542
10960
|
const resolved = resolverDataRoot();
|
|
10543
|
-
return adoptResolverDataRoot2(resolved) ?
|
|
10961
|
+
return adoptResolverDataRoot2(resolved) ? resolve4(resolved) : resolve4(legacyDataRoot());
|
|
10544
10962
|
}
|
|
10545
10963
|
function getDataDirReadOnly() {
|
|
10546
10964
|
return getDataRoot();
|
|
@@ -10638,132 +11056,7 @@ class SkillEntryPaths {
|
|
|
10638
11056
|
this.files.add(key);
|
|
10639
11057
|
}
|
|
10640
11058
|
}
|
|
10641
|
-
var CONTENT_HASH_ALGORITHM = "sha256";
|
|
10642
11059
|
var HASH_EXCLUDE_DIRS = new Set([".git", "node_modules", "dist", "build", ".turbo"]);
|
|
10643
|
-
function excludedHashEntry(name, directory) {
|
|
10644
|
-
return name.startsWith(".") || directory && HASH_EXCLUDE_DIRS.has(name);
|
|
10645
|
-
}
|
|
10646
|
-
var HASH_COVERAGE = [
|
|
10647
|
-
"SKILL.md",
|
|
10648
|
-
"skill.json",
|
|
10649
|
-
"AGENTS.md",
|
|
10650
|
-
"package.json",
|
|
10651
|
-
"tsconfig.json",
|
|
10652
|
-
"src",
|
|
10653
|
-
"scripts",
|
|
10654
|
-
"assets",
|
|
10655
|
-
"references"
|
|
10656
|
-
];
|
|
10657
|
-
function normalizeLineEndings(content) {
|
|
10658
|
-
return content.replace(/\r\n/g, `
|
|
10659
|
-
`).replace(/\r/g, `
|
|
10660
|
-
`);
|
|
10661
|
-
}
|
|
10662
|
-
function canonicalizeManifest(raw) {
|
|
10663
|
-
let parsed;
|
|
10664
|
-
try {
|
|
10665
|
-
parsed = JSON.parse(raw);
|
|
10666
|
-
} catch {
|
|
10667
|
-
return normalizeLineEndings(raw);
|
|
10668
|
-
}
|
|
10669
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
10670
|
-
return normalizeLineEndings(raw);
|
|
10671
|
-
}
|
|
10672
|
-
const record = parsed;
|
|
10673
|
-
delete record.content_hash;
|
|
10674
|
-
if (record.provenance && typeof record.provenance === "object" && !Array.isArray(record.provenance)) {
|
|
10675
|
-
delete record.provenance.content_hash;
|
|
10676
|
-
}
|
|
10677
|
-
return `${JSON.stringify(sortObjectKeys(record), null, 2)}
|
|
10678
|
-
`;
|
|
10679
|
-
}
|
|
10680
|
-
function sortObjectKeys(value) {
|
|
10681
|
-
if (Array.isArray(value))
|
|
10682
|
-
return value.map((item) => sortObjectKeys(item));
|
|
10683
|
-
if (typeof value === "object" && value !== null) {
|
|
10684
|
-
const record = value;
|
|
10685
|
-
const sorted = Object.create(null);
|
|
10686
|
-
for (const key of Object.keys(record).sort())
|
|
10687
|
-
sorted[key] = sortObjectKeys(record[key]);
|
|
10688
|
-
return sorted;
|
|
10689
|
-
}
|
|
10690
|
-
return value;
|
|
10691
|
-
}
|
|
10692
|
-
function looksLikeText(buffer) {
|
|
10693
|
-
return !buffer.includes(0);
|
|
10694
|
-
}
|
|
10695
|
-
function collectBundleFiles(skillPath) {
|
|
10696
|
-
const files = [];
|
|
10697
|
-
const seen = new Set;
|
|
10698
|
-
for (const entry of HASH_COVERAGE) {
|
|
10699
|
-
if (seen.has(entry))
|
|
10700
|
-
continue;
|
|
10701
|
-
seen.add(entry);
|
|
10702
|
-
const absolute = join52(skillPath, entry);
|
|
10703
|
-
if (!existsSync52(absolute))
|
|
10704
|
-
continue;
|
|
10705
|
-
if (statSync4(absolute).isDirectory())
|
|
10706
|
-
collectDirectory(files, absolute, entry);
|
|
10707
|
-
else
|
|
10708
|
-
collectFile(files, absolute, entry);
|
|
10709
|
-
}
|
|
10710
|
-
return files.sort((a, b) => a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0);
|
|
10711
|
-
}
|
|
10712
|
-
function collectDirectory(files, dir, rel) {
|
|
10713
|
-
for (const entry of readdirSync3(dir).sort()) {
|
|
10714
|
-
if (entry.startsWith("."))
|
|
10715
|
-
continue;
|
|
10716
|
-
const absolute = join52(dir, entry);
|
|
10717
|
-
const childRel = `${rel}/${entry}`;
|
|
10718
|
-
let stats;
|
|
10719
|
-
try {
|
|
10720
|
-
stats = statSync4(absolute);
|
|
10721
|
-
} catch {
|
|
10722
|
-
continue;
|
|
10723
|
-
}
|
|
10724
|
-
if (stats.isSymbolicLink())
|
|
10725
|
-
continue;
|
|
10726
|
-
if (stats.isDirectory()) {
|
|
10727
|
-
if (excludedHashEntry(entry, true))
|
|
10728
|
-
continue;
|
|
10729
|
-
collectDirectory(files, absolute, childRel);
|
|
10730
|
-
} else if (stats.isFile()) {
|
|
10731
|
-
collectFile(files, absolute, childRel);
|
|
10732
|
-
}
|
|
10733
|
-
}
|
|
10734
|
-
}
|
|
10735
|
-
function collectFile(files, absolute, rel) {
|
|
10736
|
-
const buffer = readFileSync42(absolute);
|
|
10737
|
-
files.push(normalizeBundleFile(rel.split(sep2).join("/"), buffer));
|
|
10738
|
-
}
|
|
10739
|
-
function normalizeBundleFile(rel, buffer) {
|
|
10740
|
-
if (rel === "skill.json") {
|
|
10741
|
-
return { rel, content: new TextEncoder().encode(canonicalizeManifest(new TextDecoder().decode(buffer))) };
|
|
10742
|
-
}
|
|
10743
|
-
if (looksLikeText(buffer)) {
|
|
10744
|
-
const normalized = normalizeLineEndings(new TextDecoder().decode(buffer));
|
|
10745
|
-
return { rel, content: new TextEncoder().encode(normalized) };
|
|
10746
|
-
}
|
|
10747
|
-
return { rel, content: buffer };
|
|
10748
|
-
}
|
|
10749
|
-
function computeContentHash(skillPath) {
|
|
10750
|
-
return hashBundleFiles(collectBundleFiles(skillPath));
|
|
10751
|
-
}
|
|
10752
|
-
function* bundleHashParts(files) {
|
|
10753
|
-
for (const file of files) {
|
|
10754
|
-
yield new TextEncoder().encode(file.rel);
|
|
10755
|
-
yield new TextEncoder().encode(`\x00${file.content.length}\x00`);
|
|
10756
|
-
yield file.content;
|
|
10757
|
-
yield new TextEncoder().encode("\x00");
|
|
10758
|
-
}
|
|
10759
|
-
yield new TextEncoder().encode("\x00");
|
|
10760
|
-
}
|
|
10761
|
-
function hashBundleFiles(files) {
|
|
10762
|
-
const hash = createHash6(CONTENT_HASH_ALGORITHM);
|
|
10763
|
-
for (const part of bundleHashParts(files))
|
|
10764
|
-
hash.update(part);
|
|
10765
|
-
return hash.digest("hex");
|
|
10766
|
-
}
|
|
10767
11060
|
var CONTENT_HASH_LIMITS = Object.freeze({
|
|
10768
11061
|
entries: 1024,
|
|
10769
11062
|
rawBytes: 64 * 1024 * 1024,
|
|
@@ -10778,173 +11071,6 @@ var CONTENT_HASH_LIMITS = Object.freeze({
|
|
|
10778
11071
|
var typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
10779
11072
|
var byteLengthOf = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength").get;
|
|
10780
11073
|
var bufferOf = Object.getOwnPropertyDescriptor(typedArrayPrototype, "buffer").get;
|
|
10781
|
-
function verifyContentHash(skillPath, manifest) {
|
|
10782
|
-
const declaredHash = manifest?.provenance?.content_hash?.trim() || undefined;
|
|
10783
|
-
if (!declaredHash)
|
|
10784
|
-
return { declared: false, valid: false };
|
|
10785
|
-
if (!/^[a-f0-9]{64}$/.test(declaredHash)) {
|
|
10786
|
-
return { declared: true, valid: false, declaredHash };
|
|
10787
|
-
}
|
|
10788
|
-
const computedHash = computeContentHash(skillPath);
|
|
10789
|
-
return {
|
|
10790
|
-
declared: true,
|
|
10791
|
-
valid: computedHash === declaredHash,
|
|
10792
|
-
declaredHash,
|
|
10793
|
-
computedHash
|
|
10794
|
-
};
|
|
10795
|
-
}
|
|
10796
|
-
var PORTABLE_SKILL_STANDARD = "hasna.skill.v1";
|
|
10797
|
-
var SKILL_RUNTIMES = ["bun", "node", "python3"];
|
|
10798
|
-
var SKILL_SANDBOX_MODES = ["readonly-fs", "workspace-write", "full"];
|
|
10799
|
-
var SKILL_SYSTEM_DEPS_ALLOWLIST = [
|
|
10800
|
-
"ffmpeg",
|
|
10801
|
-
"ffprobe",
|
|
10802
|
-
"imagemagick",
|
|
10803
|
-
"convert",
|
|
10804
|
-
"curl",
|
|
10805
|
-
"wget",
|
|
10806
|
-
"git",
|
|
10807
|
-
"gh",
|
|
10808
|
-
"jq",
|
|
10809
|
-
"python3",
|
|
10810
|
-
"pip3",
|
|
10811
|
-
"node",
|
|
10812
|
-
"bun",
|
|
10813
|
-
"npm",
|
|
10814
|
-
"rsync",
|
|
10815
|
-
"pdftotext",
|
|
10816
|
-
"tesseract",
|
|
10817
|
-
"7z",
|
|
10818
|
-
"unzip",
|
|
10819
|
-
"zip"
|
|
10820
|
-
];
|
|
10821
|
-
var SEMVER_PATTERN2 = "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$";
|
|
10822
|
-
var CONTENT_HASH_PATTERN = "^[a-f0-9]{64}$";
|
|
10823
|
-
var ENV_REFERENCE_PATTERN = "^[A-Z0-9_]+$";
|
|
10824
|
-
var MAX_RUNTIME_TIMEOUT_SECONDS = 900;
|
|
10825
|
-
function add2(target, code, message) {
|
|
10826
|
-
target.push({ code, message });
|
|
10827
|
-
}
|
|
10828
|
-
function isRecord(value) {
|
|
10829
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10830
|
-
}
|
|
10831
|
-
function isNonEmptyString(value) {
|
|
10832
|
-
return typeof value === "string" && value.trim().length > 0;
|
|
10833
|
-
}
|
|
10834
|
-
function validatePortableManifestContract(manifest, options = {}) {
|
|
10835
|
-
const issues = [];
|
|
10836
|
-
if (!manifest) {
|
|
10837
|
-
add2(issues, "contract.manifest_missing", "No portable manifest to validate");
|
|
10838
|
-
return issues;
|
|
10839
|
-
}
|
|
10840
|
-
if (manifest.standard !== PORTABLE_SKILL_STANDARD) {
|
|
10841
|
-
add2(issues, "contract.standard_invalid", `standard must be '${PORTABLE_SKILL_STANDARD}'`);
|
|
10842
|
-
}
|
|
10843
|
-
if (!/^[a-z0-9][a-z0-9._-]*$/.test(manifest.name)) {
|
|
10844
|
-
add2(issues, "contract.name_invalid", `name '${manifest.name}' must be a lowercase slug (letters, numbers, dots, underscores, hyphens)`);
|
|
10845
|
-
}
|
|
10846
|
-
if (!isNonEmptyString(manifest.description)) {
|
|
10847
|
-
add2(issues, "contract.description_missing", "description is required");
|
|
10848
|
-
}
|
|
10849
|
-
if (!isNonEmptyString(manifest.version)) {
|
|
10850
|
-
add2(issues, "contract.version_missing", "version is required");
|
|
10851
|
-
} else if (!new RegExp(SEMVER_PATTERN2).test(manifest.version)) {
|
|
10852
|
-
add2(issues, "contract.version_invalid", `version '${manifest.version}' is not valid semver`);
|
|
10853
|
-
}
|
|
10854
|
-
validateRuntimeContract(manifest, issues, options.strict === true);
|
|
10855
|
-
const provenance = manifest.provenance;
|
|
10856
|
-
if (provenance && !isRecord(provenance)) {
|
|
10857
|
-
add2(issues, "contract.provenance_invalid", "provenance must be an object");
|
|
10858
|
-
} else {
|
|
10859
|
-
const sourceCommit = provenance?.source_commit;
|
|
10860
|
-
if (sourceCommit !== undefined && sourceCommit !== null && !isNonEmptyString(sourceCommit)) {
|
|
10861
|
-
add2(issues, "contract.source_commit_invalid", "provenance.source_commit must be a string");
|
|
10862
|
-
}
|
|
10863
|
-
const changelog = provenance?.changelog;
|
|
10864
|
-
if (changelog !== undefined && changelog !== null && !isNonEmptyString(changelog)) {
|
|
10865
|
-
add2(issues, "contract.changelog_invalid", "provenance.changelog must be a string");
|
|
10866
|
-
}
|
|
10867
|
-
const declaredHash = provenance?.content_hash;
|
|
10868
|
-
if (options.strict && !isNonEmptyString(declaredHash)) {
|
|
10869
|
-
add2(issues, "contract.content_hash_missing", "provenance.content_hash is required: a portable manifest must carry its canonical content hash");
|
|
10870
|
-
} else if (isNonEmptyString(declaredHash) && !new RegExp(CONTENT_HASH_PATTERN).test(declaredHash)) {
|
|
10871
|
-
add2(issues, "contract.content_hash_invalid", "provenance.content_hash must be a 64-character lowercase hex SHA-256");
|
|
10872
|
-
} else if (options.skillPath && isNonEmptyString(declaredHash)) {
|
|
10873
|
-
const verification = verifyContentHash(options.skillPath, manifest);
|
|
10874
|
-
if (!verification.valid) {
|
|
10875
|
-
add2(issues, "contract.content_hash_mismatch", `provenance.content_hash does not match the bundle: declared ${verification.declaredHash}, computed ${verification.computedHash}. Content changed without re-hashing (a content change requires a version bump too).`);
|
|
10876
|
-
}
|
|
10877
|
-
}
|
|
10878
|
-
}
|
|
10879
|
-
return issues;
|
|
10880
|
-
}
|
|
10881
|
-
function validateRuntimeContract(manifest, issues, strict) {
|
|
10882
|
-
const runtime = manifest.runtime;
|
|
10883
|
-
if (runtime === undefined) {
|
|
10884
|
-
if (strict && manifest.kind !== "instruction") {
|
|
10885
|
-
add2(issues, "contract.runtime_missing", "runtime contract is required: { runtime, entrypoint?, timeout?, needs_network?, env?, sandbox?, system_deps?, artifacts? }");
|
|
10886
|
-
}
|
|
10887
|
-
return;
|
|
10888
|
-
}
|
|
10889
|
-
if (!isRecord(runtime)) {
|
|
10890
|
-
add2(issues, "contract.runtime_invalid", "runtime must be an object");
|
|
10891
|
-
return;
|
|
10892
|
-
}
|
|
10893
|
-
const runtimeName = runtime.runtime;
|
|
10894
|
-
if (!SKILL_RUNTIMES.includes(runtimeName)) {
|
|
10895
|
-
add2(issues, "contract.runtime_invalid", `runtime.runtime must be one of: ${SKILL_RUNTIMES.join(", ")}`);
|
|
10896
|
-
}
|
|
10897
|
-
if (runtime.version !== undefined && runtime.version !== null && !isNonEmptyString(runtime.version)) {
|
|
10898
|
-
add2(issues, "contract.runtime_version_invalid", "runtime.version must be a string");
|
|
10899
|
-
}
|
|
10900
|
-
if (runtime.entrypoint !== undefined && runtime.entrypoint !== null && !isNonEmptyString(runtime.entrypoint)) {
|
|
10901
|
-
add2(issues, "contract.entrypoint_invalid", "runtime.entrypoint must be a relative path string");
|
|
10902
|
-
}
|
|
10903
|
-
if (runtime.timeout !== undefined && runtime.timeout !== null) {
|
|
10904
|
-
if (typeof runtime.timeout !== "number" || !Number.isInteger(runtime.timeout) || runtime.timeout < 1 || runtime.timeout > MAX_RUNTIME_TIMEOUT_SECONDS) {
|
|
10905
|
-
add2(issues, "contract.timeout_invalid", `runtime.timeout must be an integer between 1 and ${MAX_RUNTIME_TIMEOUT_SECONDS} seconds`);
|
|
10906
|
-
}
|
|
10907
|
-
}
|
|
10908
|
-
if (runtime.needs_network !== undefined && runtime.needs_network !== null && typeof runtime.needs_network !== "boolean") {
|
|
10909
|
-
add2(issues, "contract.needs_network_invalid", "runtime.needs_network must be a boolean");
|
|
10910
|
-
}
|
|
10911
|
-
if (runtime.env !== undefined && runtime.env !== null) {
|
|
10912
|
-
if (!Array.isArray(runtime.env)) {
|
|
10913
|
-
add2(issues, "contract.env_invalid", "runtime.env must be an array of secret REFERENCE names");
|
|
10914
|
-
} else {
|
|
10915
|
-
for (const reference of runtime.env) {
|
|
10916
|
-
if (typeof reference !== "string" || !new RegExp(ENV_REFERENCE_PATTERN).test(reference)) {
|
|
10917
|
-
add2(issues, "contract.env_invalid", `runtime.env entry '${String(reference)}' must be an uppercase identifier (e.g. OPENAI_API_KEY) \u2014 names only, never values`);
|
|
10918
|
-
}
|
|
10919
|
-
}
|
|
10920
|
-
}
|
|
10921
|
-
}
|
|
10922
|
-
if (runtime.sandbox !== undefined && runtime.sandbox !== null && !SKILL_SANDBOX_MODES.includes(runtime.sandbox)) {
|
|
10923
|
-
add2(issues, "contract.sandbox_invalid", `runtime.sandbox must be one of: ${SKILL_SANDBOX_MODES.join(", ")}`);
|
|
10924
|
-
}
|
|
10925
|
-
if (runtime.system_deps !== undefined && runtime.system_deps !== null) {
|
|
10926
|
-
if (!Array.isArray(runtime.system_deps)) {
|
|
10927
|
-
add2(issues, "contract.system_deps_invalid", "runtime.system_deps must be an array");
|
|
10928
|
-
} else {
|
|
10929
|
-
for (const dep of runtime.system_deps) {
|
|
10930
|
-
if (!SKILL_SYSTEM_DEPS_ALLOWLIST.includes(dep)) {
|
|
10931
|
-
add2(issues, "contract.system_dep_not_allowed", `runtime.system_deps entry '${dep}' is not on the allowlist: ${SKILL_SYSTEM_DEPS_ALLOWLIST.join(", ")}`);
|
|
10932
|
-
}
|
|
10933
|
-
}
|
|
10934
|
-
}
|
|
10935
|
-
}
|
|
10936
|
-
if (runtime.artifacts !== undefined && runtime.artifacts !== null) {
|
|
10937
|
-
if (!Array.isArray(runtime.artifacts)) {
|
|
10938
|
-
add2(issues, "contract.artifacts_invalid", "runtime.artifacts must be an array of glob patterns");
|
|
10939
|
-
} else {
|
|
10940
|
-
for (const glob of runtime.artifacts) {
|
|
10941
|
-
if (!isNonEmptyString(glob)) {
|
|
10942
|
-
add2(issues, "contract.artifacts_invalid", "runtime.artifacts entries must be non-empty glob strings");
|
|
10943
|
-
}
|
|
10944
|
-
}
|
|
10945
|
-
}
|
|
10946
|
-
}
|
|
10947
|
-
}
|
|
10948
11074
|
var ANY_SEGMENT_COPY_EXCLUDES = new Set([
|
|
10949
11075
|
".git",
|
|
10950
11076
|
".DS_Store",
|
|
@@ -11437,7 +11563,8 @@ var MEASURED_CODEX_CAPABILITIES = {
|
|
|
11437
11563
|
"codex-cli 0.160.1": ["hooks", "qualified-skill-catalog", "installed-plugin-review"],
|
|
11438
11564
|
"codex-cli 0.161.0": ["hooks", "qualified-skill-catalog", "installed-plugin-review"],
|
|
11439
11565
|
"codex-cli 0.162.0": ["hooks", "qualified-skill-catalog", "installed-plugin-review"],
|
|
11440
|
-
"codex-cli 0.162.1": ["hooks", "qualified-skill-catalog", "installed-plugin-review"]
|
|
11566
|
+
"codex-cli 0.162.1": ["hooks", "qualified-skill-catalog", "installed-plugin-review"],
|
|
11567
|
+
"codex-cli 0.163.0": ["hooks", "qualified-skill-catalog", "installed-plugin-review"]
|
|
11441
11568
|
};
|
|
11442
11569
|
function supportsCodexNativeCapability(version, capability) {
|
|
11443
11570
|
return typeof version === "string" && Object.hasOwn(MEASURED_CODEX_CAPABILITIES, version) && MEASURED_CODEX_CAPABILITIES[version].includes(capability);
|
|
@@ -11633,14 +11760,14 @@ function captureClaudeMarketplaceEntry(path, marketplace, plugin, budget2 = { re
|
|
|
11633
11760
|
return { path, hashMode: CLAUDE_MARKETPLACE_ENTRY_HASH_MODE, marketplace, plugin, sha256: hashClaudeMarketplaceEntry(text, { marketplace, plugin }) };
|
|
11634
11761
|
}
|
|
11635
11762
|
var CLAUDE_ORPHAN_MARKER_MODE = "claude-plugin-orphaned-at-v1";
|
|
11636
|
-
var CACHE = `${
|
|
11763
|
+
var CACHE = `${sep2}.claude${sep2}plugins${sep2}cache${sep2}`;
|
|
11637
11764
|
function isClaudePluginCacheOrphanMarker(path) {
|
|
11638
|
-
if (typeof path !== "string" || basename4(path) !== ".orphaned_at" || !isAbsolute4(path) ||
|
|
11765
|
+
if (typeof path !== "string" || basename4(path) !== ".orphaned_at" || !isAbsolute4(path) || resolve42(path) !== path || path.includes("\x00"))
|
|
11639
11766
|
return false;
|
|
11640
11767
|
const at = path.indexOf(CACHE);
|
|
11641
11768
|
if (at < 0 || path.indexOf(CACHE, at + 1) >= 0)
|
|
11642
11769
|
return false;
|
|
11643
|
-
const parts = path.slice(at + CACHE.length).split(
|
|
11770
|
+
const parts = path.slice(at + CACHE.length).split(sep2);
|
|
11644
11771
|
return parts.length === 4 && parts.every((part) => part && part !== "." && part !== "..");
|
|
11645
11772
|
}
|
|
11646
11773
|
function same(left, right) {
|
|
@@ -12089,10 +12216,10 @@ function assertHermesEnvironment(home) {
|
|
|
12089
12216
|
throw new Error("NATIVE_SKILL_DRIFT: Hermes project plugins require a dedicated discovery review");
|
|
12090
12217
|
}
|
|
12091
12218
|
function read(path) {
|
|
12092
|
-
for (let current2 = path;; current2 =
|
|
12219
|
+
for (let current2 = path;; current2 = dirname62(current2)) {
|
|
12093
12220
|
if (lstatSync6(current2, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
12094
12221
|
throw new Error("NATIVE_SKILL_DRIFT: symlink Hermes protection input");
|
|
12095
|
-
if (
|
|
12222
|
+
if (dirname62(current2) === current2)
|
|
12096
12223
|
break;
|
|
12097
12224
|
}
|
|
12098
12225
|
const stat = lstatSync6(path, { throwIfNoEntry: false });
|
|
@@ -12132,10 +12259,10 @@ function assertHermesProtection(home, config, command, profile, supervisor2) {
|
|
|
12132
12259
|
}
|
|
12133
12260
|
function assertNoHermesLegacyShadow(root) {
|
|
12134
12261
|
let entries = 0;
|
|
12135
|
-
for (let cursor = resolve6(root);; cursor =
|
|
12262
|
+
for (let cursor = resolve6(root);; cursor = dirname62(cursor)) {
|
|
12136
12263
|
if (lstatSync6(cursor, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
12137
12264
|
throw new Error("NATIVE_SKILL_DRIFT: symlink Hermes legacy discovery root");
|
|
12138
|
-
if (
|
|
12265
|
+
if (dirname62(cursor) === cursor)
|
|
12139
12266
|
break;
|
|
12140
12267
|
}
|
|
12141
12268
|
function scan(path, depth) {
|
|
@@ -12252,7 +12379,7 @@ function capture(path, budget2, excludedRoots, omittedRoots = [], rows) {
|
|
|
12252
12379
|
if (!root)
|
|
12253
12380
|
return { path, sha256: null };
|
|
12254
12381
|
need3(root.isDirectory(), "Unsupported native discovery directory input");
|
|
12255
|
-
const hash =
|
|
12382
|
+
const hash = createHash6("sha256");
|
|
12256
12383
|
function walk(current2, relative2, before, depth) {
|
|
12257
12384
|
need3(depth <= 64, "Native discovery directory depth limit exceeded");
|
|
12258
12385
|
const names = [], directory = opendirSync2(current2);
|
|
@@ -12304,7 +12431,7 @@ function verifyDiscoveryDirectoryProjection(directories, omittedRoots, tolerance
|
|
|
12304
12431
|
const expected = directories.map((directory) => {
|
|
12305
12432
|
safe2(directory.path);
|
|
12306
12433
|
need3(Array.isArray(directory.entries), "Missing reviewed directory membership inventory");
|
|
12307
|
-
const hash =
|
|
12434
|
+
const hash = createHash6("sha256");
|
|
12308
12435
|
const kept = [];
|
|
12309
12436
|
for (const row of directory.entries) {
|
|
12310
12437
|
need3(typeof row === "string" && ++count <= AGENT_POLICY_LIMITS.discoveryDirectoryEntries, "Invalid reviewed directory membership rows");
|
|
@@ -12320,7 +12447,7 @@ function verifyDiscoveryDirectoryProjection(directories, omittedRoots, tolerance
|
|
|
12320
12447
|
}
|
|
12321
12448
|
need3(directory.sha256 === null ? directory.entries.length === 0 : hash.digest("hex") === directory.sha256, "Reviewed directory inventory does not match its fingerprint");
|
|
12322
12449
|
const absent = omittedRoots.some((root) => directory.path === root || directory.path.startsWith(root + "/"));
|
|
12323
|
-
return { path: directory.path, sha256: absent || directory.sha256 === null ? null :
|
|
12450
|
+
return { path: directory.path, sha256: absent || directory.sha256 === null ? null : createHash6("sha256").update(kept.join("")).digest("hex") };
|
|
12324
12451
|
});
|
|
12325
12452
|
const current2 = captureDiscoveryDirectoryProjection(directories.map((item) => item.path), omittedRoots);
|
|
12326
12453
|
for (let i = 0;i < current2.length; i++)
|
|
@@ -12408,7 +12535,6 @@ function hashRawDiscoveryFile(path, budget2, changes) {
|
|
|
12408
12535
|
closeSync4(fd);
|
|
12409
12536
|
}
|
|
12410
12537
|
}
|
|
12411
|
-
var BLOCK = 512;
|
|
12412
12538
|
var ANY_SEGMENT_EXCLUDES = new Set([
|
|
12413
12539
|
".git",
|
|
12414
12540
|
".ds_store",
|
|
@@ -12538,136 +12664,6 @@ var SKILL_BUNDLE_INSPECTION_LIMITS = Object.freeze({
|
|
|
12538
12664
|
pathBytes: 100,
|
|
12539
12665
|
timeoutMs: 5000
|
|
12540
12666
|
});
|
|
12541
|
-
|
|
12542
|
-
class SkillBundleInspectionError extends Error {
|
|
12543
|
-
code;
|
|
12544
|
-
constructor(code, message) {
|
|
12545
|
-
super(message);
|
|
12546
|
-
this.code = code;
|
|
12547
|
-
this.name = "SkillBundleInspectionError";
|
|
12548
|
-
}
|
|
12549
|
-
}
|
|
12550
|
-
function invalidBundle(message) {
|
|
12551
|
-
throw new SkillBundleInspectionError("BUNDLE_INVALID", message);
|
|
12552
|
-
}
|
|
12553
|
-
class BoundedTarReader {
|
|
12554
|
-
limits;
|
|
12555
|
-
check;
|
|
12556
|
-
header = new Uint8Array(BLOCK);
|
|
12557
|
-
headerOffset = 0;
|
|
12558
|
-
pending;
|
|
12559
|
-
bodyOffset = 0;
|
|
12560
|
-
padding = 0;
|
|
12561
|
-
zeroBlocks = 0;
|
|
12562
|
-
entries = [];
|
|
12563
|
-
paths = new SkillEntryPaths;
|
|
12564
|
-
fileBytes = 0;
|
|
12565
|
-
constructor(limits, check) {
|
|
12566
|
-
this.limits = limits;
|
|
12567
|
-
this.check = check;
|
|
12568
|
-
}
|
|
12569
|
-
push(chunk) {
|
|
12570
|
-
let offset = 0;
|
|
12571
|
-
while (offset < chunk.byteLength) {
|
|
12572
|
-
this.check();
|
|
12573
|
-
if (this.pending) {
|
|
12574
|
-
const count = Math.min(this.pending.bytes.byteLength - this.bodyOffset, chunk.byteLength - offset);
|
|
12575
|
-
this.pending.bytes.set(chunk.subarray(offset, offset + count), this.bodyOffset);
|
|
12576
|
-
offset += count;
|
|
12577
|
-
this.bodyOffset += count;
|
|
12578
|
-
if (this.bodyOffset === this.pending.bytes.byteLength) {
|
|
12579
|
-
this.entries.push(this.pending);
|
|
12580
|
-
this.pending = undefined;
|
|
12581
|
-
}
|
|
12582
|
-
} else if (this.padding) {
|
|
12583
|
-
const count = Math.min(this.padding, chunk.byteLength - offset);
|
|
12584
|
-
if (chunk.subarray(offset, offset + count).some((byte) => byte !== 0))
|
|
12585
|
-
invalidBundle("Nonzero tar body padding");
|
|
12586
|
-
offset += count;
|
|
12587
|
-
this.padding -= count;
|
|
12588
|
-
} else {
|
|
12589
|
-
const count = Math.min(BLOCK - this.headerOffset, chunk.byteLength - offset);
|
|
12590
|
-
this.header.set(chunk.subarray(offset, offset + count), this.headerOffset);
|
|
12591
|
-
offset += count;
|
|
12592
|
-
this.headerOffset += count;
|
|
12593
|
-
if (this.headerOffset === BLOCK) {
|
|
12594
|
-
this.readHeader();
|
|
12595
|
-
this.headerOffset = 0;
|
|
12596
|
-
}
|
|
12597
|
-
}
|
|
12598
|
-
}
|
|
12599
|
-
}
|
|
12600
|
-
finish() {
|
|
12601
|
-
this.check();
|
|
12602
|
-
if (this.pending || this.padding || this.headerOffset || this.zeroBlocks < 2)
|
|
12603
|
-
invalidBundle("Truncated tar bundle");
|
|
12604
|
-
return this.entries;
|
|
12605
|
-
}
|
|
12606
|
-
readHeader() {
|
|
12607
|
-
this.check();
|
|
12608
|
-
const h = this.header;
|
|
12609
|
-
if (h.every((byte) => byte === 0)) {
|
|
12610
|
-
this.zeroBlocks++;
|
|
12611
|
-
return;
|
|
12612
|
-
}
|
|
12613
|
-
if (this.zeroBlocks)
|
|
12614
|
-
invalidBundle("Nonzero tar data after terminator");
|
|
12615
|
-
if (this.entries.length >= this.limits.entries)
|
|
12616
|
-
throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle entry limit exceeded");
|
|
12617
|
-
let checksum = 0;
|
|
12618
|
-
for (let i = 0;i < BLOCK; i++)
|
|
12619
|
-
checksum += i >= 148 && i < 156 ? 32 : h[i];
|
|
12620
|
-
if (tarOctal(h.subarray(148, 156)) !== checksum)
|
|
12621
|
-
invalidBundle("Invalid tar header checksum");
|
|
12622
|
-
if (new TextDecoder().decode(h.subarray(257, 265)) !== "ustar\x00" + "00")
|
|
12623
|
-
invalidBundle("Unsupported tar format");
|
|
12624
|
-
if (h[156] !== 48 && h[156] !== 0 || h.subarray(157, 257).some((b) => b !== 0) || h.subarray(345).some((b) => b !== 0))
|
|
12625
|
-
invalidBundle("Unsupported tar entry or path prefix");
|
|
12626
|
-
const mode = tarOctal(h.subarray(100, 108));
|
|
12627
|
-
if (mode > 511)
|
|
12628
|
-
invalidBundle("Unsupported tar permission bits");
|
|
12629
|
-
tarOctal(h.subarray(108, 116));
|
|
12630
|
-
tarOctal(h.subarray(116, 124));
|
|
12631
|
-
tarOctal(h.subarray(136, 148));
|
|
12632
|
-
const size = tarOctal(h.subarray(124, 136));
|
|
12633
|
-
if (size > this.limits.fileBytes || this.fileBytes + size > this.limits.decompressedBytes) {
|
|
12634
|
-
throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle file byte limit exceeded");
|
|
12635
|
-
}
|
|
12636
|
-
const name = h.subarray(0, 100);
|
|
12637
|
-
const end = name.indexOf(0);
|
|
12638
|
-
if (end !== -1 && name.subarray(end).some((b) => b !== 0))
|
|
12639
|
-
invalidBundle("Invalid tar path padding");
|
|
12640
|
-
const raw = end === -1 ? name : name.subarray(0, end);
|
|
12641
|
-
if (raw.byteLength > this.limits.pathBytes)
|
|
12642
|
-
throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle path byte limit exceeded");
|
|
12643
|
-
let path;
|
|
12644
|
-
try {
|
|
12645
|
-
path = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(raw);
|
|
12646
|
-
} catch {
|
|
12647
|
-
return invalidBundle("Invalid UTF-8 bundle path");
|
|
12648
|
-
}
|
|
12649
|
-
this.paths.add(path, this.limits.pathBytes, invalidBundle, () => {
|
|
12650
|
-
throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle path byte limit exceeded");
|
|
12651
|
-
});
|
|
12652
|
-
this.fileBytes += size;
|
|
12653
|
-
this.pending = { path, mode, bytes: new Uint8Array(new ArrayBuffer(size)) };
|
|
12654
|
-
this.bodyOffset = 0;
|
|
12655
|
-
this.padding = (BLOCK - size % BLOCK) % BLOCK;
|
|
12656
|
-
if (!size) {
|
|
12657
|
-
this.entries.push(this.pending);
|
|
12658
|
-
this.pending = undefined;
|
|
12659
|
-
}
|
|
12660
|
-
}
|
|
12661
|
-
}
|
|
12662
|
-
function tarOctal(field2) {
|
|
12663
|
-
const text2 = new TextDecoder().decode(field2);
|
|
12664
|
-
if (!/^[0-7]+[\0 ]*$/.test(text2))
|
|
12665
|
-
invalidBundle("Invalid tar octal field");
|
|
12666
|
-
const value = Number.parseInt(text2, 8);
|
|
12667
|
-
if (!Number.isSafeInteger(value))
|
|
12668
|
-
invalidBundle("Tar integer is out of range");
|
|
12669
|
-
return value;
|
|
12670
|
-
}
|
|
12671
12667
|
var SKILL_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
|
|
12672
12668
|
function isValidSkillVersion(value) {
|
|
12673
12669
|
return typeof value === "string" && SKILL_VERSION_PATTERN.test(value) && !/^\.+$/.test(value) && !value.includes("..");
|
|
@@ -13161,6 +13157,35 @@ function finishCodexSettingsV1(config, tokens) {
|
|
|
13161
13157
|
}
|
|
13162
13158
|
return sha(`hasna.skills.codex-settings.v1\x00${JSON.stringify([canonical4(config), tokens])}`);
|
|
13163
13159
|
}
|
|
13160
|
+
var CODEX_PLUGIN_MANIFEST_LOCATIONS = Object.freeze([
|
|
13161
|
+
"plugin.json",
|
|
13162
|
+
".codex-plugin/plugin.json",
|
|
13163
|
+
".claude-plugin/plugin.json",
|
|
13164
|
+
".cursor-plugin/plugin.json"
|
|
13165
|
+
]);
|
|
13166
|
+
var CODEX_PLUGIN_MANIFEST_DIRECTORIES = Object.freeze([".codex-plugin", ".claude-plugin", ".cursor-plugin"]);
|
|
13167
|
+
var CODEX_PLUGIN_ROOT_CAPABILITY_ENTRIES = Object.freeze([
|
|
13168
|
+
"plugin.json",
|
|
13169
|
+
".codex-plugin",
|
|
13170
|
+
".claude-plugin",
|
|
13171
|
+
".cursor-plugin",
|
|
13172
|
+
"hooks",
|
|
13173
|
+
"hooks.json",
|
|
13174
|
+
".mcp.json",
|
|
13175
|
+
".app.json",
|
|
13176
|
+
"commands",
|
|
13177
|
+
"agents"
|
|
13178
|
+
]);
|
|
13179
|
+
function foldCodexPluginEntryName(name) {
|
|
13180
|
+
return name.toUpperCase().toLowerCase();
|
|
13181
|
+
}
|
|
13182
|
+
function codexPluginRootCapabilityEntry(name) {
|
|
13183
|
+
const folded = foldCodexPluginEntryName(name);
|
|
13184
|
+
return CODEX_PLUGIN_ROOT_CAPABILITY_ENTRIES.includes(folded) ? folded : null;
|
|
13185
|
+
}
|
|
13186
|
+
function isCodexSkillDocumentName(name) {
|
|
13187
|
+
return foldCodexPluginEntryName(name) === "skill.md";
|
|
13188
|
+
}
|
|
13164
13189
|
var need5 = (value) => {
|
|
13165
13190
|
if (!value)
|
|
13166
13191
|
throw new Error("Incomplete or unsupported reviewed Codex hook dependency");
|
|
@@ -13309,15 +13334,13 @@ function captureCodexHookMcpDependencies(configPath, reviewed, configText, chang
|
|
|
13309
13334
|
}
|
|
13310
13335
|
};
|
|
13311
13336
|
const root = join13(cacheRoot, identity2, selectCodexPluginVersion(versions, selectionBudget));
|
|
13312
|
-
const
|
|
13337
|
+
const [agentPluginManifest, ...legacyManifests] = CODEX_PLUGIN_MANIFEST_LOCATIONS;
|
|
13338
|
+
const agent = read2(join13(root, agentPluginManifest));
|
|
13313
13339
|
if (agent !== null) {
|
|
13314
13340
|
const schema = JSON.parse(agent).$schema;
|
|
13315
13341
|
need5(typeof schema !== "string" || !schema.startsWith("https://agent-plugins.org/schemas/"));
|
|
13316
13342
|
}
|
|
13317
|
-
const
|
|
13318
|
-
const claude = read2(join13(root, ".claude-plugin/plugin.json"));
|
|
13319
|
-
const cursor = read2(join13(root, ".cursor-plugin/plugin.json"));
|
|
13320
|
-
const text2 = codex ?? claude ?? cursor;
|
|
13343
|
+
const text2 = legacyManifests.map((location) => read2(join13(root, location))).find((value) => value !== null) ?? null;
|
|
13321
13344
|
if (text2 === null)
|
|
13322
13345
|
continue;
|
|
13323
13346
|
const manifest = JSON.parse(text2);
|
|
@@ -13535,27 +13558,27 @@ function spans(text2) {
|
|
|
13535
13558
|
}
|
|
13536
13559
|
function codexNumericProvenance(text2, original) {
|
|
13537
13560
|
need6(Buffer.byteLength(text2) <= 1024 * 1024);
|
|
13538
|
-
const
|
|
13561
|
+
const marker2 = "__hasna_v6_numeric_attribution__";
|
|
13539
13562
|
const leaves = new Map, tokens = new Map;
|
|
13540
13563
|
let nodes = 0;
|
|
13541
13564
|
function visit2(value, path) {
|
|
13542
13565
|
need6(++nodes <= 65536 && path.length <= 32);
|
|
13543
|
-
need6(value !==
|
|
13566
|
+
need6(value !== marker2);
|
|
13544
13567
|
if (typeof value === "number" || value instanceof Date) {
|
|
13545
13568
|
need6(value instanceof Date ? Number.isFinite(value.getTime()) : Number.isFinite(value) && (!Number.isInteger(value) || Number.isSafeInteger(value)));
|
|
13546
13569
|
leaves.set(key(path), value);
|
|
13547
13570
|
} else if (value && typeof value === "object")
|
|
13548
13571
|
for (const [name, child2] of Object.entries(value)) {
|
|
13549
|
-
need6(name !==
|
|
13572
|
+
need6(name !== marker2);
|
|
13550
13573
|
visit2(child2, [...path, Array.isArray(value) ? Number(name) : name]);
|
|
13551
13574
|
}
|
|
13552
13575
|
}
|
|
13553
13576
|
visit2(original, []);
|
|
13554
|
-
need6(!text2.includes(
|
|
13577
|
+
need6(!text2.includes(marker2));
|
|
13555
13578
|
let work = 0;
|
|
13556
13579
|
for (const { start, end } of spans(text2)) {
|
|
13557
13580
|
let compare = function(before, after, path2) {
|
|
13558
|
-
if (after ===
|
|
13581
|
+
if (after === marker2 && (typeof before === "number" || before instanceof Date || nonfinite && typeof before === "string")) {
|
|
13559
13582
|
changed.push(path2);
|
|
13560
13583
|
return true;
|
|
13561
13584
|
}
|
|
@@ -13567,7 +13590,7 @@ function codexNumericProvenance(text2, original) {
|
|
|
13567
13590
|
return names.length === Object.keys(after).length && names.every((name) => Object.hasOwn(after, name) && compare(before[name], after[name], [...path2, Array.isArray(before) ? Number(name) : name]));
|
|
13568
13591
|
};
|
|
13569
13592
|
const literal = text2.slice(start, end), nonfinite = /^[+-]?(?:inf|nan)$/.test(literal);
|
|
13570
|
-
const replacement = text2.slice(0, start) + JSON.stringify(
|
|
13593
|
+
const replacement = text2.slice(0, start) + JSON.stringify(marker2) + text2.slice(end);
|
|
13571
13594
|
work += Buffer.byteLength(replacement);
|
|
13572
13595
|
need6(work <= 16 * 1024 * 1024);
|
|
13573
13596
|
let parsed;
|
|
@@ -14482,9 +14505,12 @@ class KernelLock {
|
|
|
14482
14505
|
}
|
|
14483
14506
|
}
|
|
14484
14507
|
var KEY = ".native-corpus-admission";
|
|
14485
|
-
var fail = () => {
|
|
14486
|
-
throw new Error(
|
|
14508
|
+
var fail = (reason2) => {
|
|
14509
|
+
throw new Error(`CODEX_CORPUS_ADMISSION_REQUIRED: verified native admission and its existing shared lock are required${reason2 ? ` (${reason2})` : ""}`);
|
|
14487
14510
|
};
|
|
14511
|
+
function codexAdmissionReceipt(admission) {
|
|
14512
|
+
return admission?.nativeAdmission === "unavailable" && admission.probe ? { nativeAdmission: "unavailable", nativeAdmissionProbe: { ...admission.probe } } : {};
|
|
14513
|
+
}
|
|
14488
14514
|
function physicalTarget(path) {
|
|
14489
14515
|
const suffix = [];
|
|
14490
14516
|
for (let cursor = path;; cursor = dirname14(cursor)) {
|
|
@@ -14566,13 +14592,246 @@ function executable(options) {
|
|
|
14566
14592
|
const digest = hash2();
|
|
14567
14593
|
if (options.codexSha256 && digest !== options.codexSha256)
|
|
14568
14594
|
return fail();
|
|
14569
|
-
return { path, assertCurrent() {
|
|
14595
|
+
return { path, sha256: digest, size: Number(initial.size), assertCurrent() {
|
|
14570
14596
|
const current2 = statSync7(path, { bigint: true });
|
|
14571
14597
|
if (realpathSync32(found) !== path || ["dev", "ino", "size", "mtimeNs", "ctimeNs", "mode"].some((key2) => initial[key2] !== current2[key2]) || hash2() !== digest)
|
|
14572
14598
|
fail();
|
|
14573
14599
|
} };
|
|
14574
14600
|
}
|
|
14575
|
-
|
|
14601
|
+
var PROBE = { timeout: 5000, maxBuffer: 4096, killSignal: "SIGKILL", encoding: "utf8" };
|
|
14602
|
+
var UNRECOGNIZED = /^error: unrecognized subcommand 'corpus-admission-inspect'(?:\r?\n|$)/;
|
|
14603
|
+
var VERSION = /^codex-cli (?:0|[1-9][0-9]{0,5})\.(?:0|[1-9][0-9]{0,5})\.(?:0|[1-9][0-9]{0,5})(?:-[0-9A-Za-z-]{1,32}(?:\.[0-9A-Za-z-]{1,32}){0,7})?$/;
|
|
14604
|
+
var LOCK_DIRECTORY = "codex-corpus-locks";
|
|
14605
|
+
var PROBE_PARENT = "codex-probe-homes";
|
|
14606
|
+
var retain = (hold) => {
|
|
14607
|
+
hold.refs++;
|
|
14608
|
+
return { hold, released: false };
|
|
14609
|
+
};
|
|
14610
|
+
var release = (ref) => {
|
|
14611
|
+
if (ref.released)
|
|
14612
|
+
return;
|
|
14613
|
+
ref.released = true;
|
|
14614
|
+
if (--ref.hold.refs === 0)
|
|
14615
|
+
ref.hold.lock.close();
|
|
14616
|
+
};
|
|
14617
|
+
var enclosing = new AsyncLocalStorage;
|
|
14618
|
+
var leaseHolds = new WeakMap;
|
|
14619
|
+
var contains = (base, path) => {
|
|
14620
|
+
const distance = relative4(base, path);
|
|
14621
|
+
return distance === "" || !distance.startsWith(`..${sep7}`) && distance !== ".." && !isAbsolute13(distance);
|
|
14622
|
+
};
|
|
14623
|
+
function nativeLockAbsent(root) {
|
|
14624
|
+
for (const name of [`${KEY}.flock-v1`, `${KEY}.lock`]) {
|
|
14625
|
+
try {
|
|
14626
|
+
lstatSync13(join16(root, name));
|
|
14627
|
+
return false;
|
|
14628
|
+
} catch (error) {
|
|
14629
|
+
if (error.code !== "ENOENT")
|
|
14630
|
+
throw error;
|
|
14631
|
+
}
|
|
14632
|
+
}
|
|
14633
|
+
return true;
|
|
14634
|
+
}
|
|
14635
|
+
function skillsState(root, leaf, roots) {
|
|
14636
|
+
const chain = [realpathSync32(dirname14(root))];
|
|
14637
|
+
for (const part of [".hasna", "skills", leaf])
|
|
14638
|
+
chain.push(join16(chain.at(-1), part));
|
|
14639
|
+
const path = chain.at(-1);
|
|
14640
|
+
const uid2 = process.getuid();
|
|
14641
|
+
const verify = () => {
|
|
14642
|
+
if (roots.some((item) => contains(item, path)) || codexCorpusRootForPath(path) !== undefined)
|
|
14643
|
+
fail();
|
|
14644
|
+
for (let ancestor = dirname14(chain[0]);; ancestor = dirname14(ancestor)) {
|
|
14645
|
+
const stat2 = lstatSync13(ancestor), sticky = stat2.uid === 0 && (stat2.mode & 512) !== 0;
|
|
14646
|
+
if (!stat2.isDirectory() || stat2.uid !== uid2 && stat2.uid !== 0 || (stat2.mode & 18) !== 0 && !sticky)
|
|
14647
|
+
fail();
|
|
14648
|
+
if (dirname14(ancestor) === ancestor)
|
|
14649
|
+
break;
|
|
14650
|
+
}
|
|
14651
|
+
for (const component of chain) {
|
|
14652
|
+
const stat2 = lstatSync13(component, { throwIfNoEntry: false });
|
|
14653
|
+
if (!stat2)
|
|
14654
|
+
return;
|
|
14655
|
+
if (!stat2.isDirectory() || stat2.uid !== uid2 && stat2.uid !== 0 || (stat2.mode & 18) !== 0 || component === path && stat2.uid !== uid2)
|
|
14656
|
+
fail();
|
|
14657
|
+
}
|
|
14658
|
+
};
|
|
14659
|
+
verify();
|
|
14660
|
+
return { path, ensure() {
|
|
14661
|
+
verify();
|
|
14662
|
+
for (const component of chain.slice(1)) {
|
|
14663
|
+
try {
|
|
14664
|
+
mkdirSync5(component, { mode: 448 });
|
|
14665
|
+
} catch (error) {
|
|
14666
|
+
if (error.code !== "EEXIST")
|
|
14667
|
+
throw error;
|
|
14668
|
+
}
|
|
14669
|
+
}
|
|
14670
|
+
verify();
|
|
14671
|
+
if (realpathSync32(path) !== path)
|
|
14672
|
+
fail();
|
|
14673
|
+
return path;
|
|
14674
|
+
} };
|
|
14675
|
+
}
|
|
14676
|
+
function probeParent(roots) {
|
|
14677
|
+
const dataRoot = resolve14(getDataDirReadOnly()), path = join16(dataRoot, PROBE_PARENT), uid2 = process.getuid();
|
|
14678
|
+
const chain = [];
|
|
14679
|
+
for (let component = path;; component = dirname14(component)) {
|
|
14680
|
+
chain.unshift(component);
|
|
14681
|
+
if (dirname14(component) === component)
|
|
14682
|
+
break;
|
|
14683
|
+
}
|
|
14684
|
+
const verify = () => {
|
|
14685
|
+
if (roots.some((item) => contains(item, path)) || codexCorpusRootForPath(path) !== undefined)
|
|
14686
|
+
fail();
|
|
14687
|
+
for (const component of chain) {
|
|
14688
|
+
const stat2 = lstatSync13(component, { throwIfNoEntry: false });
|
|
14689
|
+
if (!stat2)
|
|
14690
|
+
return;
|
|
14691
|
+
const skills = contains(dataRoot, component), sticky = !skills && stat2.uid === 0 && (stat2.mode & 512) !== 0;
|
|
14692
|
+
if (!stat2.isDirectory() || stat2.uid !== uid2 && (skills || stat2.uid !== 0) || (stat2.mode & 18) !== 0 && !sticky)
|
|
14693
|
+
fail();
|
|
14694
|
+
}
|
|
14695
|
+
};
|
|
14696
|
+
verify();
|
|
14697
|
+
for (const component of chain) {
|
|
14698
|
+
if (lstatSync13(component, { throwIfNoEntry: false }))
|
|
14699
|
+
continue;
|
|
14700
|
+
try {
|
|
14701
|
+
mkdirSync5(component, { mode: 448 });
|
|
14702
|
+
} catch (error) {
|
|
14703
|
+
if (error.code !== "EEXIST")
|
|
14704
|
+
throw error;
|
|
14705
|
+
}
|
|
14706
|
+
}
|
|
14707
|
+
verify();
|
|
14708
|
+
if (realpathSync32(path) !== path)
|
|
14709
|
+
fail();
|
|
14710
|
+
return path;
|
|
14711
|
+
}
|
|
14712
|
+
function probeHomeIntact(home, empty) {
|
|
14713
|
+
const stat2 = lstatSync13(home.path, { bigint: true, throwIfNoEntry: false });
|
|
14714
|
+
return !!stat2 && stat2.isDirectory() && stat2.dev === home.dev && stat2.ino === home.ino && stat2.uid === BigInt(process.getuid()) && (stat2.mode & 0o777n) === 0o700n && realpathSync32(home.path) === home.path && (!empty || readdirSync5(home.path).length === 0);
|
|
14715
|
+
}
|
|
14716
|
+
function removeProbeHome(home) {
|
|
14717
|
+
try {
|
|
14718
|
+
const stat2 = lstatSync13(home.path, { bigint: true });
|
|
14719
|
+
if (stat2.isDirectory() && stat2.dev === home.dev && stat2.ino === home.ino)
|
|
14720
|
+
rmSync2(home.path, { recursive: true, force: true });
|
|
14721
|
+
} catch {}
|
|
14722
|
+
}
|
|
14723
|
+
function probe(path, args, parent, stdio) {
|
|
14724
|
+
const created = mkdtempSync(join16(parent, "probe-")), stat2 = lstatSync13(created, { bigint: true });
|
|
14725
|
+
const home = { path: created, dev: stat2.dev, ino: stat2.ino };
|
|
14726
|
+
try {
|
|
14727
|
+
if (!probeHomeIntact(home, true))
|
|
14728
|
+
return;
|
|
14729
|
+
const env = { CODEX_HOME: home.path };
|
|
14730
|
+
for (const key2 of ["PATH", "HOME"])
|
|
14731
|
+
if (process.env[key2] !== undefined)
|
|
14732
|
+
env[key2] = process.env[key2];
|
|
14733
|
+
const result = spawnSync3(path, args, { ...PROBE, cwd: home.path, env, stdio: ["ignore", stdio, stdio] });
|
|
14734
|
+
return probeHomeIntact(home, false) ? result : undefined;
|
|
14735
|
+
} finally {
|
|
14736
|
+
removeProbeHome(home);
|
|
14737
|
+
}
|
|
14738
|
+
}
|
|
14739
|
+
function probeAdmissionCommand(path, parent) {
|
|
14740
|
+
const help = probe(path, ["help", "corpus-admission-inspect"], parent, "pipe");
|
|
14741
|
+
if (!help || help.error || help.signal !== null)
|
|
14742
|
+
return "inconclusive";
|
|
14743
|
+
if (help.status === 0)
|
|
14744
|
+
return "present";
|
|
14745
|
+
if (help.status !== 2 || help.stdout !== "" || typeof help.stderr !== "string" || !UNRECOGNIZED.test(help.stderr))
|
|
14746
|
+
return "inconclusive";
|
|
14747
|
+
const control = probe(path, ["help", "exec"], parent, "ignore");
|
|
14748
|
+
return control && !control.error && control.signal === null && control.status === 0 ? "absent" : "inconclusive";
|
|
14749
|
+
}
|
|
14750
|
+
function strictVersion(path, parent) {
|
|
14751
|
+
const result = probe(path, ["--version"], parent, "pipe");
|
|
14752
|
+
if (!result || result.error || result.signal !== null || result.status !== 0 || typeof result.stdout !== "string")
|
|
14753
|
+
return;
|
|
14754
|
+
const line = result.stdout.replace(/\r?\n$/, "");
|
|
14755
|
+
return VERSION.test(line) ? line : undefined;
|
|
14756
|
+
}
|
|
14757
|
+
function rootLockKey(root, id) {
|
|
14758
|
+
return `codex-corpus-${createHash17("sha256").update(`${root}\x00${id.device}\x00${id.inode}`).digest("hex")}`;
|
|
14759
|
+
}
|
|
14760
|
+
function acquireFallback(inputs, options) {
|
|
14761
|
+
let reason2 = "executable-unverified";
|
|
14762
|
+
const refs = new Map, held = [];
|
|
14763
|
+
const close = () => {
|
|
14764
|
+
for (const ref of [...refs.values()].reverse())
|
|
14765
|
+
release(ref);
|
|
14766
|
+
};
|
|
14767
|
+
try {
|
|
14768
|
+
const native = executable(options);
|
|
14769
|
+
reason2 = "skills-lock-unavailable";
|
|
14770
|
+
const roots = inputs.map((item) => item.root);
|
|
14771
|
+
const locks = new Map(roots.map((root) => [root, skillsState(root, LOCK_DIRECTORY, roots)]));
|
|
14772
|
+
const parent = probeParent(roots);
|
|
14773
|
+
reason2 = "probe-inconclusive";
|
|
14774
|
+
const state = probeAdmissionCommand(native.path, parent);
|
|
14775
|
+
if (state === "present")
|
|
14776
|
+
reason2 = "command-present";
|
|
14777
|
+
if (state !== "absent")
|
|
14778
|
+
fail();
|
|
14779
|
+
const version = strictVersion(native.path, parent);
|
|
14780
|
+
if (version === undefined)
|
|
14781
|
+
fail();
|
|
14782
|
+
reason2 = "executable-unverified";
|
|
14783
|
+
native.assertCurrent();
|
|
14784
|
+
reason2 = "skills-lock-unavailable";
|
|
14785
|
+
for (const { input, root } of inputs) {
|
|
14786
|
+
const id = identity3(root), key2 = rootLockKey(root, id);
|
|
14787
|
+
if (!refs.has(key2)) {
|
|
14788
|
+
const owner2 = enclosing.getStore()?.get(key2);
|
|
14789
|
+
if (owner2 && !owner2.released)
|
|
14790
|
+
refs.set(key2, retain(owner2.hold));
|
|
14791
|
+
else {
|
|
14792
|
+
const lock = new KernelLock(locks.get(root).ensure(), key2, { mode: "exclusive" });
|
|
14793
|
+
refs.set(key2, retain({ lock, refs: 0 }));
|
|
14794
|
+
if (!lock.trySync(1000)) {
|
|
14795
|
+
reason2 = "writer-busy";
|
|
14796
|
+
fail();
|
|
14797
|
+
}
|
|
14798
|
+
}
|
|
14799
|
+
}
|
|
14800
|
+
held.push({ input, root, id, ref: refs.get(key2) });
|
|
14801
|
+
}
|
|
14802
|
+
const assertCurrent = () => {
|
|
14803
|
+
try {
|
|
14804
|
+
for (const item of held) {
|
|
14805
|
+
if (item.ref.released)
|
|
14806
|
+
fail();
|
|
14807
|
+
item.ref.hold.lock.assertUnchanged();
|
|
14808
|
+
if (realpathSync32(item.input) !== item.root || !sameIdentity(identity3(item.root), item.id) || !nativeLockAbsent(item.root))
|
|
14809
|
+
fail();
|
|
14810
|
+
}
|
|
14811
|
+
native.assertCurrent();
|
|
14812
|
+
} catch {
|
|
14813
|
+
fail("lease-changed");
|
|
14814
|
+
}
|
|
14815
|
+
};
|
|
14816
|
+
reason2 = "lease-changed";
|
|
14817
|
+
assertCurrent();
|
|
14818
|
+
const lease = { assertCurrent, close, admission: { nativeAdmission: "unavailable", probe: {
|
|
14819
|
+
kind: "help-unrecognized-subcommand",
|
|
14820
|
+
executable: native.path,
|
|
14821
|
+
sha256: native.sha256,
|
|
14822
|
+
size: native.size,
|
|
14823
|
+
version,
|
|
14824
|
+
probeExitCode: 2,
|
|
14825
|
+
controlExitCode: 0
|
|
14826
|
+
} } };
|
|
14827
|
+
leaseHolds.set(lease, refs);
|
|
14828
|
+
return lease;
|
|
14829
|
+
} catch {
|
|
14830
|
+
close();
|
|
14831
|
+
return fail(reason2);
|
|
14832
|
+
}
|
|
14833
|
+
}
|
|
14834
|
+
function acquireCodexCorpusWrite(roots, options, policy = {}) {
|
|
14576
14835
|
const held = [];
|
|
14577
14836
|
const close = () => {
|
|
14578
14837
|
for (const item of held.reverse())
|
|
@@ -14585,10 +14844,20 @@ function acquireCodexCorpusWrite(roots, options) {
|
|
|
14585
14844
|
fail();
|
|
14586
14845
|
}
|
|
14587
14846
|
};
|
|
14847
|
+
let fallback = false, refusal;
|
|
14588
14848
|
try {
|
|
14589
14849
|
if (roots.some((root) => typeof root !== "string" || !isAbsolute13(root) || root.includes("\x00")))
|
|
14590
14850
|
fail();
|
|
14591
14851
|
const inputs = [...new Set(roots)].map((input) => ({ input, root: realpathSync32(input) })).sort((a, b) => a.root.localeCompare(b.root));
|
|
14852
|
+
const absent = inputs.filter(({ root }) => nativeLockAbsent(root));
|
|
14853
|
+
if (absent.length && absent.length !== inputs.length) {
|
|
14854
|
+
refusal = "native-lock-present";
|
|
14855
|
+
fail();
|
|
14856
|
+
}
|
|
14857
|
+
if (absent.length && policy.fallback !== false) {
|
|
14858
|
+
fallback = true;
|
|
14859
|
+
return acquireFallback(inputs, options);
|
|
14860
|
+
}
|
|
14592
14861
|
for (const { input, root } of inputs) {
|
|
14593
14862
|
const lock = new KernelLock(root, KEY, { mode: "shared", existingOnly: true });
|
|
14594
14863
|
held.push({ input, root, lock });
|
|
@@ -14616,19 +14885,25 @@ function acquireCodexCorpusWrite(roots, options) {
|
|
|
14616
14885
|
if (Object.keys(row).sort().join(",") !== "lock,root,schema,state" || row.schema !== "codex-corpus-admission-status/v1" || row.state !== "committed-v1" && row.state !== "committed-v2" || !sameIdentity(row.root, rootIdentity) || !sameIdentity(row.lock, lockIdentity))
|
|
14617
14886
|
fail();
|
|
14618
14887
|
}
|
|
14619
|
-
return { assertCurrent, close };
|
|
14620
|
-
} catch {
|
|
14888
|
+
return { assertCurrent, close, admission: { nativeAdmission: "verified" } };
|
|
14889
|
+
} catch (error) {
|
|
14890
|
+
if (fallback)
|
|
14891
|
+
throw error;
|
|
14621
14892
|
close();
|
|
14622
|
-
return fail();
|
|
14893
|
+
return fail(refusal);
|
|
14623
14894
|
}
|
|
14624
14895
|
}
|
|
14625
|
-
function
|
|
14896
|
+
function scoped(lease, run) {
|
|
14897
|
+
const holds = leaseHolds.get(lease);
|
|
14898
|
+
return holds?.size ? enclosing.run(new Map([...enclosing.getStore() ?? [], ...holds]), run) : run();
|
|
14899
|
+
}
|
|
14900
|
+
function withCodexCorpusWrite(roots, run, options = {}, policy = {}) {
|
|
14626
14901
|
if (!roots.length)
|
|
14627
14902
|
return run(() => {});
|
|
14628
|
-
const lease = acquireCodexCorpusWrite(roots, options);
|
|
14903
|
+
const lease = acquireCodexCorpusWrite(roots, options, policy);
|
|
14629
14904
|
try {
|
|
14630
14905
|
lease.assertCurrent();
|
|
14631
|
-
const result = run(lease.assertCurrent);
|
|
14906
|
+
const result = scoped(lease, () => run(lease.assertCurrent, lease.admission));
|
|
14632
14907
|
lease.assertCurrent();
|
|
14633
14908
|
return result;
|
|
14634
14909
|
} finally {
|
|
@@ -14981,7 +15256,7 @@ function reviewedRetiredCodexRoot(cache, root, controls, rules, read2, allowAbse
|
|
|
14981
15256
|
if (!enrolled.some((control) => control.namespace === parsed.namespace && control.manifestSha256 === parsed.manifestSha256 && !parsed.appSha256 && !parsed.mcpSha256))
|
|
14982
15257
|
return false;
|
|
14983
15258
|
let entries = 0;
|
|
14984
|
-
const emptySkills = (directory, depth) => depth <= 64 &&
|
|
15259
|
+
const emptySkills = (directory, depth) => depth <= 64 && readdirSync6(directory).every((name) => {
|
|
14985
15260
|
if (++entries > 4096 || name === "SKILL.md")
|
|
14986
15261
|
return false;
|
|
14987
15262
|
const path = join18(directory, name), stat2 = lstatSync14(path);
|
|
@@ -15006,7 +15281,7 @@ function reviewedCodexPluginCapabilitiesUnchanged(cache, controls, read2, rules)
|
|
|
15006
15281
|
if (control.remotePluginId !== undefined && !remoteInstallationMatches(parent, control.remotePluginId, read2))
|
|
15007
15282
|
return false;
|
|
15008
15283
|
}
|
|
15009
|
-
const names =
|
|
15284
|
+
const names = readdirSync6(parent);
|
|
15010
15285
|
entries += names.length;
|
|
15011
15286
|
if (entries > 4096)
|
|
15012
15287
|
return false;
|
|
@@ -15103,20 +15378,20 @@ function codexVendorMarketplace(cache, path) {
|
|
|
15103
15378
|
return null;
|
|
15104
15379
|
return CODEX_VENDOR_MARKETPLACES.includes(parts[0]) ? parts[0] : null;
|
|
15105
15380
|
}
|
|
15106
|
-
var OTHER_PLUGIN_CONTROLS = Object.freeze(
|
|
15381
|
+
var OTHER_PLUGIN_CONTROLS = Object.freeze(CODEX_PLUGIN_ROOT_CAPABILITY_ENTRIES.filter((entry) => entry !== ".codex-plugin" && entry !== ".app.json"));
|
|
15107
15382
|
var VENDOR_MANIFEST_KEYS = Object.freeze(["name", "version", "description", "author", "homepage", "repository", "license", "keywords", "interface", "skills", "apps"]);
|
|
15108
15383
|
var DEFAULT_SKILLS_PATHS = Object.freeze(["./skills", "./skills/"]);
|
|
15109
15384
|
var VENDOR_APP_DECLARATION = "./.app.json";
|
|
15110
15385
|
var MAX_SUBTREE_ENTRIES = 20000;
|
|
15111
15386
|
var MAX_SUBTREE_DEPTH = 32;
|
|
15112
15387
|
var hiddenName = (name) => name.startsWith(".") || name === "node_modules";
|
|
15113
|
-
var isSkillDocument =
|
|
15388
|
+
var isSkillDocument = isCodexSkillDocumentName;
|
|
15114
15389
|
var present = (path) => lstatSync15(path, { throwIfNoEntry: false }) !== undefined;
|
|
15115
|
-
var holdsOtherControl = (path) =>
|
|
15390
|
+
var holdsOtherControl = (path) => readdirSync7(path).some((name) => OTHER_PLUGIN_CONTROLS.includes(codexPluginRootCapabilityEntry(name) ?? ""));
|
|
15116
15391
|
function pluginTreeVisible(path, hidden, insideSkill, depth, budget2) {
|
|
15117
15392
|
if (depth > MAX_SUBTREE_DEPTH)
|
|
15118
15393
|
return false;
|
|
15119
|
-
const names =
|
|
15394
|
+
const names = readdirSync7(path);
|
|
15120
15395
|
const skill = names.some(isSkillDocument);
|
|
15121
15396
|
if (skill && (hidden || insideSkill))
|
|
15122
15397
|
return false;
|
|
@@ -15140,7 +15415,7 @@ function codexVendorPluginRootRefreshSafe(root, budget2 = { remaining: MAX_SUBTR
|
|
|
15140
15415
|
return false;
|
|
15141
15416
|
if (!directory(join19(root, ".codex-plugin")))
|
|
15142
15417
|
return false;
|
|
15143
|
-
const controls =
|
|
15418
|
+
const controls = readdirSync7(join19(root, ".codex-plugin"));
|
|
15144
15419
|
if (controls.length !== 1 || controls[0] !== "plugin.json")
|
|
15145
15420
|
return false;
|
|
15146
15421
|
const manifest = join19(root, ".codex-plugin", "plugin.json"), stat2 = lstatSync15(manifest, { throwIfNoEntry: false });
|
|
@@ -15163,7 +15438,7 @@ function codexVendorPluginRootRefreshSafe(root, budget2 = { remaining: MAX_SUBTR
|
|
|
15163
15438
|
}
|
|
15164
15439
|
function vendorMembers(path, budget2) {
|
|
15165
15440
|
const directories = [];
|
|
15166
|
-
for (const name of
|
|
15441
|
+
for (const name of readdirSync7(path)) {
|
|
15167
15442
|
if (--budget2.remaining < 0)
|
|
15168
15443
|
return null;
|
|
15169
15444
|
const stat2 = lstatSync15(join19(path, name));
|
|
@@ -15441,7 +15716,7 @@ function projectReviewedClaudePluginManifest(text2, reviewedSha256) {
|
|
|
15441
15716
|
}
|
|
15442
15717
|
return hashClaudePluginManifest(text2);
|
|
15443
15718
|
}
|
|
15444
|
-
var version = "0.10.
|
|
15719
|
+
var version = "0.10.78";
|
|
15445
15720
|
var package_default = {
|
|
15446
15721
|
name: "@hasna/skills",
|
|
15447
15722
|
version,
|
|
@@ -15608,56 +15883,13 @@ var AUTHORITY_OVERRIDE_HEADERS = new Set([
|
|
|
15608
15883
|
"x-forwarded-host",
|
|
15609
15884
|
"x-original-host"
|
|
15610
15885
|
]);
|
|
15886
|
+
var urlKeys = clientTransportEnvKeys("skills").apiUrlKeys;
|
|
15611
15887
|
var SKILLS_APP = "skills";
|
|
15612
15888
|
var ENV_KEYS = clientTransportEnvKeys(SKILLS_APP);
|
|
15613
15889
|
var SKILLS_API_URL_ENV_KEYS = ENV_KEYS.apiUrlKeys;
|
|
15614
15890
|
var SKILLS_API_KEY_ENV_KEYS = ENV_KEYS.apiKeyKeys;
|
|
15615
15891
|
var SKILLS_API_URL_ENV = SKILLS_API_URL_ENV_KEYS[0];
|
|
15616
15892
|
var SKILLS_API_KEY_ENV = SKILLS_API_KEY_ENV_KEYS[0];
|
|
15617
|
-
|
|
15618
|
-
class SkillsFleetCredentialError extends Error {
|
|
15619
|
-
code;
|
|
15620
|
-
next;
|
|
15621
|
-
constructor(message, code = "MISSING_API_CREDENTIAL", next) {
|
|
15622
|
-
super(message);
|
|
15623
|
-
this.name = "SkillsFleetCredentialError";
|
|
15624
|
-
this.code = code;
|
|
15625
|
-
if (next)
|
|
15626
|
-
this.next = next;
|
|
15627
|
-
}
|
|
15628
|
-
}
|
|
15629
|
-
function normalizeSkillsApiOrigin(apiUrl) {
|
|
15630
|
-
const url = new URL(apiUrl);
|
|
15631
|
-
if (url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
|
|
15632
|
-
throw new SkillsFleetCredentialError("A Skills API URL must use HTTPS (or loopback HTTP), without credentials, query or fragment", "INVALID_API_URL");
|
|
15633
|
-
}
|
|
15634
|
-
const pathname = url.pathname.replace(/\/+$/, "");
|
|
15635
|
-
if (url.origin === "https://api.hasna.com" && pathname === "/skills/v1") {
|
|
15636
|
-
url.pathname = "/skills";
|
|
15637
|
-
} else if (pathname === "/api" || pathname === "/api/v1") {
|
|
15638
|
-
url.pathname = "/";
|
|
15639
|
-
} else if (pathname.endsWith("/api/v1")) {
|
|
15640
|
-
url.pathname = pathname.slice(0, -"/api/v1".length) || "/";
|
|
15641
|
-
} else if (pathname.endsWith("/api")) {
|
|
15642
|
-
url.pathname = pathname.slice(0, -"/api".length) || "/";
|
|
15643
|
-
}
|
|
15644
|
-
return url.toString().replace(/\/+$/, "");
|
|
15645
|
-
}
|
|
15646
|
-
function skillsApiRequestUrl(apiUrl, route) {
|
|
15647
|
-
const origin = normalizeSkillsApiOrigin(apiUrl);
|
|
15648
|
-
if (!route.startsWith("/api/") || route.includes("#") || route.includes("\\")) {
|
|
15649
|
-
throw new SkillsFleetCredentialError("Invalid Skills API route", "INVALID_API_URL");
|
|
15650
|
-
}
|
|
15651
|
-
if (origin === "https://api.hasna.com/skills") {
|
|
15652
|
-
if (route === "/api/auth/whoami")
|
|
15653
|
-
return `${origin}/v1/auth/whoami`;
|
|
15654
|
-
if (!route.startsWith("/api/v1/")) {
|
|
15655
|
-
throw new SkillsFleetCredentialError("The internal Skills gateway has no established login contract yet. Select an explicitly configured instance with supported authentication.", "GATEWAY_AUTH_UNAVAILABLE");
|
|
15656
|
-
}
|
|
15657
|
-
return `${origin}${route.slice("/api".length)}`;
|
|
15658
|
-
}
|
|
15659
|
-
return `${origin}${route}`;
|
|
15660
|
-
}
|
|
15661
15893
|
var MAX_REMOTE_FILE_BYTES = 64 * 1024 * 1024;
|
|
15662
15894
|
var CODEX_NATIVE_POLICY_CAPABILITY = "host-path-allowlist-v1";
|
|
15663
15895
|
var CODEX_NATIVE_POLICY_RECEIPT_SCHEMA = "skills.codex-native-policy-acceptance/v1";
|
|
@@ -15925,7 +16157,7 @@ function writeExecutableCache(dataDir22, entries) {
|
|
|
15925
16157
|
return;
|
|
15926
16158
|
const existing = lstatSync19(directory2, { throwIfNoEntry: false });
|
|
15927
16159
|
if (!existing)
|
|
15928
|
-
|
|
16160
|
+
mkdirSync7(directory2, { mode: 448 });
|
|
15929
16161
|
else if (existing.isSymbolicLink() || !existing.isDirectory())
|
|
15930
16162
|
return;
|
|
15931
16163
|
const holder = lstatSync19(directory2, { throwIfNoEntry: false, bigint: true });
|
|
@@ -16220,7 +16452,7 @@ function recordCodexNativePolicyAcceptance(dataDir22, verification, accepted) {
|
|
|
16220
16452
|
...verification.attestation ? { attestation: { schema: verification.attestation.schema, peerProcessId: verification.attestation.peerProcessId } } : {}
|
|
16221
16453
|
};
|
|
16222
16454
|
try {
|
|
16223
|
-
|
|
16455
|
+
mkdirSync7(directory2, { recursive: true, mode: 448 });
|
|
16224
16456
|
const stat2 = lstatSync19(directory2);
|
|
16225
16457
|
if (stat2.isSymbolicLink() || !stat2.isDirectory())
|
|
16226
16458
|
throw new Error(`the receipt directory is not a real directory: ${directory2}`);
|
|
@@ -16250,6 +16482,7 @@ function recordCodexNativePolicyAcceptance(dataDir22, verification, accepted) {
|
|
|
16250
16482
|
return path;
|
|
16251
16483
|
}
|
|
16252
16484
|
var CODEX_SEMANTIC_CACHE_WITNESS_SCHEMA = "hasna.codex-semantic-cache-witness.v1";
|
|
16485
|
+
var SEMANTIC_BOUND_ROOT_ENTRIES = Object.freeze([".codex-plugin", ".app.json", ".mcp.json", "hooks"]);
|
|
16253
16486
|
var identifier5 = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value);
|
|
16254
16487
|
var digest = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
|
|
16255
16488
|
var refuse4 = () => {
|
|
@@ -16412,7 +16645,7 @@ function assertCanonicalDirectory(path) {
|
|
|
16412
16645
|
function walkSafeTree(path, state, depth = 0, root = path) {
|
|
16413
16646
|
if (depth > 64 || ++state.entries > 16384)
|
|
16414
16647
|
refuse4();
|
|
16415
|
-
const names =
|
|
16648
|
+
const names = readdirSync9(path).sort();
|
|
16416
16649
|
const files = [];
|
|
16417
16650
|
for (const name of names) {
|
|
16418
16651
|
if (!name || name === "." || name === ".." || name.includes(sep11) || ++state.entries > 16384)
|
|
@@ -16558,7 +16791,7 @@ function appOnlyParentProjection(cacheRoot, parents2, read2) {
|
|
|
16558
16791
|
} catch {
|
|
16559
16792
|
refuse4();
|
|
16560
16793
|
}
|
|
16561
|
-
const versions =
|
|
16794
|
+
const versions = readdirSync9(parent.pluginParent).filter((name) => name !== ".codex-remote-plugin-install.json");
|
|
16562
16795
|
if (!versions.length || versions.length > 4096)
|
|
16563
16796
|
refuse4();
|
|
16564
16797
|
const materializations = versions.map((version2) => {
|
|
@@ -16703,7 +16936,7 @@ function reviewedHookParentProjection(cacheRoot, parents2, read2) {
|
|
|
16703
16936
|
if (createHash222("sha256").update(marketplaceText).digest("hex") !== parent.marketplaceSha256 || !codexLocalMarketplaceMapsPlugin(marketplaceText, parts[0], parent.namespace))
|
|
16704
16937
|
refuse4();
|
|
16705
16938
|
}
|
|
16706
|
-
const materializations =
|
|
16939
|
+
const materializations = readdirSync9(parent.pluginParent).filter((name) => name !== ".codex-remote-plugin-install.json").map((version2) => {
|
|
16707
16940
|
if (!/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/.test(version2))
|
|
16708
16941
|
refuse4();
|
|
16709
16942
|
const root = join25(parent.pluginParent, version2), stat2 = lstatSync20(root, { throwIfNoEntry: false });
|
|
@@ -16737,14 +16970,14 @@ function assertParents(cacheRoot, controls, appOnlyParents, hookParents, files,
|
|
|
16737
16970
|
refuse4();
|
|
16738
16971
|
actual.add(join25(cacheRoot, parts[0], parts[1]));
|
|
16739
16972
|
}
|
|
16740
|
-
const actualMarkets =
|
|
16973
|
+
const actualMarkets = readdirSync9(cacheRoot);
|
|
16741
16974
|
if (actualMarkets.length !== expectedMarkets.size || actualMarkets.some((market) => !expectedMarkets.has(market)))
|
|
16742
16975
|
refuse4();
|
|
16743
16976
|
for (const market of actualMarkets) {
|
|
16744
16977
|
const marketPath = join25(cacheRoot, market), marketStat = lstatSync20(marketPath);
|
|
16745
16978
|
if (!identifier5(market) || !marketStat.isDirectory() || marketStat.isSymbolicLink())
|
|
16746
16979
|
refuse4();
|
|
16747
|
-
for (const plugin of
|
|
16980
|
+
for (const plugin of readdirSync9(marketPath)) {
|
|
16748
16981
|
const parent = join25(marketPath, plugin), stat2 = lstatSync20(parent);
|
|
16749
16982
|
if (!identifier5(plugin) || !stat2.isDirectory() || stat2.isSymbolicLink())
|
|
16750
16983
|
refuse4();
|
|
@@ -16759,14 +16992,23 @@ function assertParents(cacheRoot, controls, appOnlyParents, hookParents, files,
|
|
|
16759
16992
|
continue;
|
|
16760
16993
|
const parent = join25(cacheRoot, parts[0], parts[1]);
|
|
16761
16994
|
const root = join25(parent, parts[2]);
|
|
16762
|
-
const base = parts[parts.length - 1];
|
|
16763
|
-
if (parts.
|
|
16995
|
+
const base = parts[parts.length - 1], folded = foldCodexPluginEntryName(base);
|
|
16996
|
+
if (parts.length === 3 && (codexPluginRootCapabilityEntry(base) !== null || isCodexSkillDocumentName(base)))
|
|
16997
|
+
refuse4();
|
|
16998
|
+
const rootEntry = parts.length >= 4 ? codexPluginRootCapabilityEntry(parts[3]) : null;
|
|
16999
|
+
if (rootEntry !== null && rootEntry !== parts[3])
|
|
17000
|
+
refuse4();
|
|
17001
|
+
if (rootEntry !== null && !SEMANTIC_BOUND_ROOT_ENTRIES.includes(rootEntry))
|
|
17002
|
+
refuse4();
|
|
17003
|
+
if (isCodexSkillDocumentName(base) && base !== "SKILL.md")
|
|
17004
|
+
refuse4();
|
|
17005
|
+
if (parts.some((part) => CODEX_PLUGIN_MANIFEST_DIRECTORIES.includes(foldCodexPluginEntryName(part))) && (parts.length < 4 || parts[3] !== ".codex-plugin" || (parts.length === 4 ? base !== ".codex-plugin" : parts.length !== 5 || base !== "plugin.json")))
|
|
16764
17006
|
refuse4();
|
|
16765
|
-
if ([".app.json", ".mcp.json"].includes(
|
|
17007
|
+
if ([".app.json", ".mcp.json"].includes(folded) && (parts.length !== 4 || dirname18(member) !== root))
|
|
16766
17008
|
refuse4();
|
|
16767
|
-
if ([".app.json", ".mcp.json"].includes(
|
|
17009
|
+
if ([".app.json", ".mcp.json"].includes(folded) && hookParents.some((reviewed) => reviewed.pluginParent === parent))
|
|
16768
17010
|
refuse4();
|
|
16769
|
-
if ((
|
|
17011
|
+
if ((rootEntry === "hooks" || folded === "hooks.json") && (![4, 5].includes(parts.length) || parts[3] !== "hooks" || (parts.length === 4 ? base !== "hooks" : base !== "hooks.json") || !hookParents.some((reviewed) => reviewed.pluginParent === join25(cacheRoot, parts[0], parts[1]))))
|
|
16770
17012
|
refuse4();
|
|
16771
17013
|
}
|
|
16772
17014
|
}
|
|
@@ -16796,7 +17038,7 @@ function assertSkillMaterializations(cacheRoot, controls, files, read2) {
|
|
|
16796
17038
|
const expectedNames = new Set(rows.map((row) => row.name));
|
|
16797
17039
|
if (expectedNames.size !== rows.length)
|
|
16798
17040
|
refuse4();
|
|
16799
|
-
const entries =
|
|
17041
|
+
const entries = readdirSync9(parent);
|
|
16800
17042
|
let roots = 0;
|
|
16801
17043
|
for (const entry of entries) {
|
|
16802
17044
|
if (entry === ".codex-remote-plugin-install.json")
|
|
@@ -17125,7 +17367,7 @@ function isOwnedCliBridge(path, expectedPaths) {
|
|
|
17125
17367
|
try {
|
|
17126
17368
|
if (!lstatSync23(path).isDirectory())
|
|
17127
17369
|
return false;
|
|
17128
|
-
if (JSON.stringify(
|
|
17370
|
+
if (JSON.stringify(readdirSync10(path).sort()) !== JSON.stringify(Object.keys(CLI_BRIDGE_FILES).sort()))
|
|
17129
17371
|
return false;
|
|
17130
17372
|
return Object.entries(CLI_BRIDGE_FILES).every(([name, content]) => {
|
|
17131
17373
|
const file = join28(path, name), stat2 = lstatSync23(file);
|
|
@@ -17286,7 +17528,7 @@ function sumiPathPlan(home, cwd = process.cwd(), env = process.env) {
|
|
|
17286
17528
|
childEnv[key2] = env[key2];
|
|
17287
17529
|
let child2;
|
|
17288
17530
|
try {
|
|
17289
|
-
child2 =
|
|
17531
|
+
child2 = spawnSync5(executable2, ["--json", "--home", resolve20(home), "--cwd", resolve20(cwd)], {
|
|
17290
17532
|
cwd: resolve20(cwd),
|
|
17291
17533
|
env: childEnv,
|
|
17292
17534
|
encoding: "buffer",
|
|
@@ -17658,7 +17900,7 @@ function writeReviewArtifactExclusive(change) {
|
|
|
17658
17900
|
for (let parent = dirname21(change.path);!lstatSync27(parent, { throwIfNoEntry: false }); parent = dirname21(parent))
|
|
17659
17901
|
missing2.push(parent);
|
|
17660
17902
|
for (const parent of missing2.reverse())
|
|
17661
|
-
|
|
17903
|
+
mkdirSync8(parent, { mode: 448 });
|
|
17662
17904
|
safe4(change.path);
|
|
17663
17905
|
privateStore(change.artifact.storeRoot);
|
|
17664
17906
|
for (let parent = dirname21(change.path);parent !== change.artifact.storeRoot; parent = dirname21(parent)) {
|
|
@@ -17906,7 +18148,7 @@ function treeHash(root) {
|
|
|
17906
18148
|
const rel = relative9(root, path);
|
|
17907
18149
|
if (stat2.isDirectory()) {
|
|
17908
18150
|
hash3.update(`d\x00${rel}\x00`);
|
|
17909
|
-
for (const name of
|
|
18151
|
+
for (const name of readdirSync11(path).sort())
|
|
17910
18152
|
visit2(join31(path, name));
|
|
17911
18153
|
return;
|
|
17912
18154
|
}
|
|
@@ -18034,10 +18276,10 @@ function inventoryNativeSkills(home = homedir22(), options = {}) {
|
|
|
18034
18276
|
return scan;
|
|
18035
18277
|
seen.add(path);
|
|
18036
18278
|
let managed = false;
|
|
18037
|
-
const
|
|
18038
|
-
if (existsSync92(
|
|
18279
|
+
const marker2 = join31(path, ".hasna-skills.json");
|
|
18280
|
+
if (existsSync92(marker2)) {
|
|
18039
18281
|
try {
|
|
18040
|
-
managed = JSON.parse(readFileSync19(
|
|
18282
|
+
managed = JSON.parse(readFileSync19(marker2, "utf8")).managedBy === "@hasna/skills";
|
|
18041
18283
|
} catch {}
|
|
18042
18284
|
}
|
|
18043
18285
|
const bridge = (!vendor || agent === "sumi") && isOwnedCliBridge(path, bridgePaths);
|
|
@@ -18301,7 +18543,7 @@ function planClaudeHookEventsUpdate(options) {
|
|
|
18301
18543
|
}
|
|
18302
18544
|
function atomicWrite2(path, content) {
|
|
18303
18545
|
assertSafePath(path);
|
|
18304
|
-
|
|
18546
|
+
mkdirSync9(dirname22(path), { recursive: true, mode: 448 });
|
|
18305
18547
|
const temporary = `${path}.skills-${randomUUID4()}`;
|
|
18306
18548
|
try {
|
|
18307
18549
|
writeFileSync6(temporary, content, { mode: 384, flag: "wx" });
|
|
@@ -18469,7 +18711,7 @@ function planCodexSemanticCacheWitnessUpgrade(options) {
|
|
|
18469
18711
|
throw new Error("Local marketplace hook parent is not enabled in the unchanged Codex settings");
|
|
18470
18712
|
identity5 = { role: "reviewed-hook", pluginId: pluginId2, namespace: parts[1], pluginParent: parent, installation: "local-marketplace", marketplaceSourcePath: source.path, marketplaceSha256: source.sha256 };
|
|
18471
18713
|
}
|
|
18472
|
-
const versions =
|
|
18714
|
+
const versions = readdirSync11(parent).filter((name) => name !== ".codex-remote-plugin-install.json");
|
|
18473
18715
|
if (!versions.length || versions.length > 4096)
|
|
18474
18716
|
throw new Error("Reviewed native-hook parent has no bounded materializations");
|
|
18475
18717
|
for (const version2 of versions) {
|
|
@@ -18563,9 +18805,10 @@ function applyAgentIntegration(plan, options = {}) {
|
|
|
18563
18805
|
const alias = plan.rootAliases?.find((item) => item.agent === "codex" && (change.path === item.target || change.path.startsWith(item.target + "/")));
|
|
18564
18806
|
return lexical ? [lexical] : alias ? [alias.alias] : [];
|
|
18565
18807
|
});
|
|
18566
|
-
return withCodexCorpusWrite(roots, (assertCurrent) => applyAgentIntegrationUnlocked(plan, options, assertCurrent), options);
|
|
18808
|
+
return withCodexCorpusWrite(roots, (assertCurrent, admission) => applyAgentIntegrationUnlocked(plan, options, assertCurrent, admission), options);
|
|
18567
18809
|
}
|
|
18568
|
-
function applyAgentIntegrationUnlocked(plan, options = {}, assertCurrent) {
|
|
18810
|
+
function applyAgentIntegrationUnlocked(plan, options = {}, assertCurrent, admission) {
|
|
18811
|
+
const fallback = codexAdmissionReceipt(admission);
|
|
18569
18812
|
for (const source of plan.reviewArtifactSources ?? [])
|
|
18570
18813
|
verifyReviewArtifactOriginal(source.path, source.sha256);
|
|
18571
18814
|
for (const source of plan.observedNativeSources ?? [])
|
|
@@ -18584,7 +18827,7 @@ function applyAgentIntegrationUnlocked(plan, options = {}, assertCurrent) {
|
|
|
18584
18827
|
assertCurrent();
|
|
18585
18828
|
recheckRootAliases(aliases);
|
|
18586
18829
|
for (const agent of plan.retainedReviewChecks?.agents ?? [])
|
|
18587
|
-
|
|
18830
|
+
assertRetainedReviewState(agent, { ...plan.retainedReviewChecks, dataDir: plan.dataDir });
|
|
18588
18831
|
if (plan.reviewArtifactMigration) {
|
|
18589
18832
|
const verified = planReviewedArtifactMigration(plan.reviewArtifactMigration);
|
|
18590
18833
|
if (JSON.stringify(verified.changes) !== JSON.stringify(plan.changes) || JSON.stringify(verified.discoveryAfter) !== JSON.stringify(plan.discoveryAfter))
|
|
@@ -18627,10 +18870,12 @@ function applyAgentIntegrationUnlocked(plan, options = {}, assertCurrent) {
|
|
|
18627
18870
|
if (!plan.changes.length) {
|
|
18628
18871
|
assertCurrent();
|
|
18629
18872
|
recheckRootAliases(aliases);
|
|
18630
|
-
|
|
18873
|
+
for (const agent of plan.retainedReviewChecks?.agents ?? [])
|
|
18874
|
+
assertManagedAgentBridge(agent, { ...plan.retainedReviewChecks, dataDir: plan.dataDir });
|
|
18875
|
+
return { changed: [], backups, ...aliases.length ? { rootAliases: aliases } : {}, ...fallback };
|
|
18631
18876
|
}
|
|
18632
18877
|
assertSafePath(backupRoot);
|
|
18633
|
-
|
|
18878
|
+
mkdirSync9(backupRoot, { recursive: true, mode: 448 });
|
|
18634
18879
|
chmodSync(backupRoot, 448);
|
|
18635
18880
|
for (const [index, change] of plan.changes.entries())
|
|
18636
18881
|
if (change.before !== null) {
|
|
@@ -18676,7 +18921,9 @@ function applyAgentIntegrationUnlocked(plan, options = {}, assertCurrent) {
|
|
|
18676
18921
|
}
|
|
18677
18922
|
for (const agent of plan.managedAgentChecks?.agents ?? [])
|
|
18678
18923
|
assertManagedAgentBridge(agent, { home: plan.managedAgentChecks.home, dataDir: plan.dataDir, projectDir: plan.managedAgentChecks.projectDir ?? plan.managedAgentChecks.home });
|
|
18679
|
-
|
|
18924
|
+
for (const agent of plan.retainedReviewChecks?.agents ?? [])
|
|
18925
|
+
assertManagedAgentBridge(agent, { ...plan.retainedReviewChecks, dataDir: plan.dataDir });
|
|
18926
|
+
atomicWrite2(join31(backupRoot, "receipt.json"), JSON.stringify({ version: 1, changes: written.map((change) => ({ path: change.path, beforeHash: change.before === null ? null : sha4(change.before), afterHash: sha4(change.after) })), backups, ...plan.cacheWitnessUpgrade ? { cacheWitnessUpgrade: plan.cacheWitnessUpgrade } : {}, ...plan.retainedReviewArtifacts?.length ? { retainedReviewArtifacts: plan.retainedReviewArtifacts.map((item) => ({ path: item.path, ...item.artifact })) } : {}, ...aliases.length ? { rootAliases: aliases } : {}, ...fallback }) + `
|
|
18680
18927
|
`);
|
|
18681
18928
|
} catch (error) {
|
|
18682
18929
|
assertCurrent();
|
|
@@ -18704,7 +18951,7 @@ function applyAgentIntegrationUnlocked(plan, options = {}, assertCurrent) {
|
|
|
18704
18951
|
}
|
|
18705
18952
|
throw error;
|
|
18706
18953
|
}
|
|
18707
|
-
return { changed: plan.changes.map((change) => change.path), backups, ...aliases.length ? { rootAliases: aliases } : {} };
|
|
18954
|
+
return { changed: plan.changes.map((change) => change.path), backups, ...aliases.length ? { rootAliases: aliases } : {}, ...fallback };
|
|
18708
18955
|
}
|
|
18709
18956
|
function classifiedCodexPluginCacheCopy(entry, cache, read2, admit) {
|
|
18710
18957
|
try {
|
|
@@ -18841,7 +19088,7 @@ enabled = false
|
|
|
18841
19088
|
function assertManagedAgentBridge(agent, options = {}) {
|
|
18842
19089
|
return assertManagedAgentBridgeWithDiscovery(agent, options);
|
|
18843
19090
|
}
|
|
18844
|
-
function
|
|
19091
|
+
function assertManagedBridgeCustody(agent, options = {}, provenDiscovery) {
|
|
18845
19092
|
const home = resolve23(options.home ?? homedir22()), dataDir22 = options.dataDir ?? getDataDirReadOnly();
|
|
18846
19093
|
assertSafePath(join31(dataDir22, "agent-policy.json"));
|
|
18847
19094
|
const snapshot2 = readManagedSkillPolicySnapshot(dataDir22);
|
|
@@ -18858,7 +19105,6 @@ function assertManagedAgentBridgeWithDiscovery(agent, options = {}, provenDiscov
|
|
|
18858
19105
|
if (!isOwnedCliBridge(expected, [expected]))
|
|
18859
19106
|
throw new Error("NATIVE_SKILL_DRIFT: the native Skills bridge is missing or modified; repair it before continuing");
|
|
18860
19107
|
const roots = projectAncestorDirectories([options.projectDir ?? process.cwd(), ...options.projectDirs ?? [], ...agent === "hermes" && process.env.TERMINAL_CWD ? [process.cwd()] : []]);
|
|
18861
|
-
const visible = (entry) => entry.agent === agent || ["codex", "gemini", "opencode", "hermes", "sumi"].includes(agent) && entry.path.includes(`${sep14}.agents${sep14}skills${sep14}`) || ["opencode", "sumi"].includes(agent) && entry.agent === "claude";
|
|
18862
19108
|
const discovery = provenDiscovery ?? binding.discovery?.[agent];
|
|
18863
19109
|
assertProjectDiscovery(agent, [...roots], home, (path) => canonicalAgentPath(path, aliases), discovery);
|
|
18864
19110
|
for (const source of discovery?.sources ?? [])
|
|
@@ -18873,11 +19119,30 @@ function assertManagedAgentBridgeWithDiscovery(agent, options = {}, provenDiscov
|
|
|
18873
19119
|
throw new Error("NATIVE_SKILL_DRIFT: the native hook command/profile binding is missing");
|
|
18874
19120
|
if (options.profileId !== undefined && options.profileId !== profile)
|
|
18875
19121
|
throw new Error("NATIVE_SKILL_DRIFT: the hook selection profile differs from its managed binding; restart the native client after reviewing skills hook install");
|
|
19122
|
+
return { home, dataDir: dataDir22, binding, aliases, expected, roots, discovery, configPath, config, command, profile };
|
|
19123
|
+
}
|
|
19124
|
+
function assertUnrepairableBridgeProtection(custody, agent) {
|
|
19125
|
+
if (agent !== "hermes")
|
|
19126
|
+
return;
|
|
19127
|
+
const { home, dataDir: dataDir22, binding, config, command, profile } = custody;
|
|
19128
|
+
const supervisor2 = binding.supervisors?.hermes;
|
|
19129
|
+
if (supervisor2?.path !== join31(dataDir22, "agent-hooks", "hermes.js") || supervisor2?.sha256 !== sha4(renderHermesSupervisor(command, profile)))
|
|
19130
|
+
throw new Error("NATIVE_SKILL_DRIFT: Hermes supervisor binding changed; run skills hook install");
|
|
19131
|
+
assertHermesProtection(home, config, command, profile, supervisor2);
|
|
19132
|
+
}
|
|
19133
|
+
function assertRetainedReviewState(agent, options) {
|
|
19134
|
+
const custody = assertManagedBridgeCustody(agent, options);
|
|
19135
|
+
assertUnrepairableBridgeProtection(custody, agent);
|
|
19136
|
+
assertManagedNativeDiscovery(custody, agent, options);
|
|
19137
|
+
}
|
|
19138
|
+
|
|
19139
|
+
class NativeSkillCopiesDriftError extends Error {
|
|
19140
|
+
}
|
|
19141
|
+
function assertManagedAgentBridgeWithDiscovery(agent, options = {}, provenDiscovery) {
|
|
19142
|
+
const custody = assertManagedBridgeCustody(agent, options, provenDiscovery);
|
|
19143
|
+
const { home, aliases, expected, discovery, config, command, profile } = custody;
|
|
18876
19144
|
if (agent === "hermes") {
|
|
18877
|
-
|
|
18878
|
-
if (supervisor2?.path !== join31(dataDir22, "agent-hooks", "hermes.js") || supervisor2?.sha256 !== sha4(renderHermesSupervisor(command, profile)))
|
|
18879
|
-
throw new Error("NATIVE_SKILL_DRIFT: Hermes supervisor binding changed; run skills hook install");
|
|
18880
|
-
assertHermesProtection(home, config, command, profile, supervisor2);
|
|
19145
|
+
assertUnrepairableBridgeProtection(custody, agent);
|
|
18881
19146
|
} else if (agent === "sumi") {
|
|
18882
19147
|
if (JSON.stringify(config.permissions?.filter((rule) => rule.action === "skill")) !== JSON.stringify(SUMI_SKILL_PERMISSIONS) || !isManagedSumiPlugin(readOptional(join31(sumiConfigDirectory(home, process.env, options.projectDir ?? process.cwd()), "plugins", "skills-cli.js")), command, profile))
|
|
18883
19148
|
throw new Error("NATIVE_SKILL_DRIFT: Sumi bridge protection changed; run skills hook install");
|
|
@@ -18899,6 +19164,21 @@ function assertManagedAgentBridgeWithDiscovery(agent, options = {}, provenDiscov
|
|
|
18899
19164
|
if (agent === "gemini" && (config.hooksConfig?.enabled === false || config.skills?.enabled !== true || !["antigravity-support", "skill-creator"].every((name) => config.skills?.disabled?.includes(name)) || config.skills?.disabled?.includes(CLI_BRIDGE_NAME)))
|
|
18900
19165
|
throw new Error("NATIVE_SKILL_DRIFT: Gemini bridge or bundled-skill protection changed; run skills hook install");
|
|
18901
19166
|
}
|
|
19167
|
+
if (agent === "codex") {
|
|
19168
|
+
const codexConfig = Bun.TOML.parse(readOptional(canonicalAgentPath(join31(home, ".codex", "config.toml"), aliases)) ?? "");
|
|
19169
|
+
if (codexConfig.skills?.bundled?.enabled !== false)
|
|
19170
|
+
throw new Error("NATIVE_SKILL_DRIFT: Codex bundled skill reseeding is not disabled (skills.bundled.enabled); run skills hook install");
|
|
19171
|
+
const setting = (path) => (codexConfig.skills?.config ?? []).filter((entry) => typeof entry.path === "string" && [path, join31(path, "SKILL.md")].includes(canonicalAgentPath(entry.path, aliases)));
|
|
19172
|
+
if ([...setting(expected), ...(codexConfig.skills?.config ?? []).filter((entry) => typeof entry.name === "string" && entry.name.trim() === CLI_BRIDGE_NAME)].some((entry) => entry.enabled === false))
|
|
19173
|
+
throw new Error("NATIVE_SKILL_DRIFT: the Codex CLI bridge is disabled; run skills hook install");
|
|
19174
|
+
}
|
|
19175
|
+
if (agent === "gemini" && discovery && !discovery.builtinNames?.every((name) => config.skills.disabled.includes(name)))
|
|
19176
|
+
throw new Error("NATIVE_SKILL_DRIFT: an installed Gemini builtin is not disabled");
|
|
19177
|
+
return assertManagedNativeDiscovery(custody, agent, options);
|
|
19178
|
+
}
|
|
19179
|
+
function assertManagedNativeDiscovery(custody, agent, options) {
|
|
19180
|
+
const { home, dataDir: dataDir22, binding, aliases, expected, roots, discovery } = custody;
|
|
19181
|
+
const visible = (entry) => entry.agent === agent || ["codex", "gemini", "opencode", "hermes", "sumi"].includes(agent) && entry.path.includes(`${sep14}.agents${sep14}skills${sep14}`) || ["opencode", "sumi"].includes(agent) && entry.agent === "claude";
|
|
18902
19182
|
const codexPath = canonicalAgentPath(join31(home, ".codex", "config.toml"), aliases);
|
|
18903
19183
|
const vendorCache = canonicalAgentPath(join31(home, ".codex", "plugins", "cache"), aliases);
|
|
18904
19184
|
const witnessTolerance = agent === "codex" && options.codexPromptHook === true ? {
|
|
@@ -18909,11 +19189,6 @@ function assertManagedAgentBridgeWithDiscovery(agent, options = {}, provenDiscov
|
|
|
18909
19189
|
if (options.codexDiscoveryRecovery && (agent !== "codex" || options.codexDiscoveryRecovery.configPath !== codexPath))
|
|
18910
19190
|
throw new Error("NATIVE_SKILL_DRIFT: Codex trust recovery names a different configuration root");
|
|
18911
19191
|
const codexConfig = agent === "codex" ? Bun.TOML.parse(readOptional(codexPath) ?? "") : {};
|
|
18912
|
-
if (agent === "codex" && codexConfig.skills?.bundled?.enabled !== false)
|
|
18913
|
-
throw new Error("NATIVE_SKILL_DRIFT: Codex bundled skill reseeding is not disabled (skills.bundled.enabled); run skills hook install");
|
|
18914
|
-
const setting = (path) => (codexConfig.skills?.config ?? []).filter((entry) => typeof entry.path === "string" && [path, join31(path, "SKILL.md")].includes(canonicalAgentPath(entry.path, aliases)));
|
|
18915
|
-
if (agent === "codex" && [...setting(expected), ...(codexConfig.skills?.config ?? []).filter((entry) => typeof entry.name === "string" && entry.name.trim() === CLI_BRIDGE_NAME)].some((entry) => entry.enabled === false))
|
|
18916
|
-
throw new Error("NATIVE_SKILL_DRIFT: the Codex CLI bridge is disabled; run skills hook install");
|
|
18917
19192
|
if (agent === "codex" && !reviewedCodexPluginCapabilitiesUnchanged(canonicalAgentPath(join31(home, ".codex/plugins/cache"), aliases), binding.codexPluginSkills ?? [], (path) => new TextDecoder("utf-8", { fatal: true }).decode(readNativeBytes(path, 1024 * 1024)), codexConfig.skills?.config ?? []))
|
|
18918
19193
|
throw new Error("NATIVE_SKILL_DRIFT: reviewed native plugin capability controls changed; run skills hook install with a fresh discovery review");
|
|
18919
19194
|
const disabledPlugin = (entry) => {
|
|
@@ -18950,8 +19225,6 @@ function assertManagedAgentBridgeWithDiscovery(agent, options = {}, provenDiscov
|
|
|
18950
19225
|
};
|
|
18951
19226
|
if (!discovery || discovery.agent !== agent)
|
|
18952
19227
|
throw new Error("NATIVE_SKILL_DRIFT: native discovery coverage is missing; run skills hook install");
|
|
18953
|
-
if (agent === "gemini" && !discovery.builtinNames?.every((name) => config.skills.disabled.includes(name)))
|
|
18954
|
-
throw new Error("NATIVE_SKILL_DRIFT: an installed Gemini builtin is not disabled");
|
|
18955
19228
|
try {
|
|
18956
19229
|
verifyAgentDiscovery(agent === "codex" ? { ...discovery, codexDisabledPluginSkills: binding.codexPluginSkills ?? [] } : discovery, options.codexDiscoveryRecovery, aliases, witnessTolerance);
|
|
18957
19230
|
if (agent === "sumi" && discovery.method === "reviewed")
|
|
@@ -19006,7 +19279,7 @@ function assertManagedAgentBridgeWithDiscovery(agent, options = {}, provenDiscov
|
|
|
19006
19279
|
return false;
|
|
19007
19280
|
}
|
|
19008
19281
|
}, read: (path) => new TextDecoder("utf-8", { fatal: true }).decode(readNativeBytes(path, 1024 * 1024)) });
|
|
19009
|
-
throw new
|
|
19282
|
+
throw new NativeSkillCopiesDriftError(`NATIVE_SKILL_DRIFT: ${blocking.length} unexpected native skill copies were found: ${nativeSkillPathList(blocking.map((entry) => entry.path))}. ${remediation}${adapterRefusal ? ` Native policy adapter refused: ${adapterRefusal}` : ""}`);
|
|
19010
19283
|
}
|
|
19011
19284
|
recheckRootAliases(aliases);
|
|
19012
19285
|
const discoveryChanges = (witnessTolerance?.changes ?? []).filter((change, index, all) => all.findIndex((other) => other.kind === change.kind && other.path === change.path) === index);
|
|
@@ -19891,10 +20164,10 @@ function absentRetiredClaudeRoots(binding) {
|
|
|
19891
20164
|
for (const source of binding.sources) {
|
|
19892
20165
|
if (!retainableAbsentSource(source) || source.sha256 === null)
|
|
19893
20166
|
continue;
|
|
19894
|
-
const
|
|
19895
|
-
if (at < 0 || source.path.indexOf(
|
|
20167
|
+
const marker2 = sep15 + ".claude" + sep15 + "plugins" + sep15 + "cache" + sep15, at = source.path.indexOf(marker2);
|
|
20168
|
+
if (at < 0 || source.path.indexOf(marker2, at + 1) >= 0)
|
|
19896
20169
|
continue;
|
|
19897
|
-
const cache = source.path.slice(0, at +
|
|
20170
|
+
const cache = source.path.slice(0, at + marker2.length - 1), parts = source.path.slice(at + marker2.length).split(sep15);
|
|
19898
20171
|
if (parts.length < 4 || parts.slice(0, 3).some((part) => !part || part === "." || part === ".."))
|
|
19899
20172
|
continue;
|
|
19900
20173
|
const root2 = join38(cache, ...parts.slice(0, 3));
|
|
@@ -20101,6 +20374,12 @@ function verifyAgentDiscovery(binding, codexRecovery, reviewedRootAliases, witne
|
|
|
20101
20374
|
}
|
|
20102
20375
|
var CLAUDE_CONTROL_WITNESS_MODES = new Set(["claude-settings-v1", "claude-settings-v2", "claude-settings-v3", "claude-settings-v4", "claude-marketplace-registry", "claude-marketplace-registry-v2", "claude-marketplace-entry-v1", "claude-plugin-registry"]);
|
|
20103
20376
|
var CLAUDE_CONTROL_FILES = new Set(["settings.json", "settings.local.json", "installed_plugins.json", "known_marketplaces.json"]);
|
|
20377
|
+
function claudeControlSource(source) {
|
|
20378
|
+
return CLAUDE_CONTROL_WITNESS_MODES.has(source.hashMode ?? "") || CLAUDE_CONTROL_FILES.has(basename15(source.path)) && !source.path.includes(`${sep15}.claude${sep15}plugins${sep15}cache${sep15}`);
|
|
20379
|
+
}
|
|
20380
|
+
function retainedAbsentClaudeRoot(absentRoots, source) {
|
|
20381
|
+
return claudeControlSource(source) ? undefined : retainedAbsentRoot(absentRoots, source);
|
|
20382
|
+
}
|
|
20104
20383
|
function codexInstallationRoots(binding) {
|
|
20105
20384
|
const proof = binding.codexInstallationInputs;
|
|
20106
20385
|
if (proof === undefined)
|
|
@@ -20242,13 +20521,13 @@ function assertProjectDiscovery(agent, directories, home, canonical9 = resolve27
|
|
|
20242
20521
|
for (const name of ["plugin", "plugins"]) {
|
|
20243
20522
|
const path = canonical9(join38(directory2, ".sumi", name));
|
|
20244
20523
|
safe6(path);
|
|
20245
|
-
if (lstatSync32(path, { throwIfNoEntry: false })?.isDirectory() &&
|
|
20524
|
+
if (lstatSync32(path, { throwIfNoEntry: false })?.isDirectory() && readdirSync13(path).length)
|
|
20246
20525
|
throw new Error(`NATIVE_SKILL_DRIFT: project Sumi plugins require a dedicated discovery review: ${path}`);
|
|
20247
20526
|
}
|
|
20248
20527
|
if (agent === "claude") {
|
|
20249
20528
|
const commands = canonical9(join38(directory2, ".claude/commands"));
|
|
20250
20529
|
safe6(commands);
|
|
20251
|
-
if (lstatSync32(commands, { throwIfNoEntry: false })?.isDirectory() &&
|
|
20530
|
+
if (lstatSync32(commands, { throwIfNoEntry: false })?.isDirectory() && readdirSync13(commands).length)
|
|
20252
20531
|
throw new Error("NATIVE_SKILL_DRIFT: legacy project command discovery requires a dedicated format adapter");
|
|
20253
20532
|
}
|
|
20254
20533
|
}
|
|
@@ -20397,7 +20676,7 @@ function resolveAgentDiscovery(options) {
|
|
|
20397
20676
|
for (const path of plugins) {
|
|
20398
20677
|
safe6(path);
|
|
20399
20678
|
if (lstatSync32(path, { throwIfNoEntry: false })?.isDirectory())
|
|
20400
|
-
for (const name of
|
|
20679
|
+
for (const name of readdirSync13(path).sort()) {
|
|
20401
20680
|
if (name === "skills-cli.js" && path === plugins[1])
|
|
20402
20681
|
continue;
|
|
20403
20682
|
const target = join38(path, name);
|
|
@@ -20408,7 +20687,7 @@ function resolveAgentDiscovery(options) {
|
|
|
20408
20687
|
}
|
|
20409
20688
|
for (const root2 of roots) {
|
|
20410
20689
|
safe6(root2);
|
|
20411
|
-
if (lstatSync32(root2, { throwIfNoEntry: false })?.isDirectory() &&
|
|
20690
|
+
if (lstatSync32(root2, { throwIfNoEntry: false })?.isDirectory() && readdirSync13(root2).some((name) => name.endsWith(".md")))
|
|
20412
20691
|
unresolved("flat markdown skills require a dedicated native migration adapter");
|
|
20413
20692
|
}
|
|
20414
20693
|
}
|
|
@@ -20452,7 +20731,7 @@ function resolveAgentDiscovery(options) {
|
|
|
20452
20731
|
safe6(builtinRoot);
|
|
20453
20732
|
if (!lstatSync32(builtinRoot, { throwIfNoEntry: false })?.isDirectory())
|
|
20454
20733
|
unresolved("installed Gemini builtin root is missing");
|
|
20455
|
-
for (const name of
|
|
20734
|
+
for (const name of readdirSync13(builtinRoot).sort()) {
|
|
20456
20735
|
const text2 = witness(join38(builtinRoot, name, "SKILL.md"));
|
|
20457
20736
|
const match = text2?.match(/^---\r?\n[\s\S]*?^name:\s*([a-z0-9][a-z0-9-]*)\s*$/m);
|
|
20458
20737
|
if (!match?.[1] || builtinNames.includes(match[1]))
|
|
@@ -20492,7 +20771,10 @@ function resolveAgentDiscovery(options) {
|
|
|
20492
20771
|
if (!review.sources.some((source) => source.path === canonical9(configPath)))
|
|
20493
20772
|
throw new Error("Discovery review must include the agent configuration source");
|
|
20494
20773
|
const reviewedSources = supersedesSettingsProjection(agent, review.sources, canonical9(configPath)) ? sources.filter((source) => !isSupersededSettingsProjection(agent, canonical9(configPath), source)) : sources;
|
|
20774
|
+
const absentRoots = absentRetiredClaudeRoots(supplied);
|
|
20495
20775
|
const reviewedSourcesWithManifestProjection = review.sources.map((source) => {
|
|
20776
|
+
if (retainedAbsentClaudeRoot(absentRoots, source) !== undefined)
|
|
20777
|
+
return source;
|
|
20496
20778
|
if (agent === "claude" && source.format === undefined && source.fields === undefined && source.managedPlugins === undefined && source.reviewArtifact === undefined && [undefined, "bytes", "path-bytes"].includes(source.hashMode) && isClaudePluginCacheOrphanMarker(source.path)) {
|
|
20497
20779
|
return { path: source.path, hashMode: CLAUDE_ORPHAN_MARKER_MODE, sha256: hashClaudePluginCacheOrphanMarker(source.path) };
|
|
20498
20780
|
}
|
|
@@ -20525,6 +20807,11 @@ function resolveAgentDiscovery(options) {
|
|
|
20525
20807
|
});
|
|
20526
20808
|
if (agent === "claude")
|
|
20527
20809
|
assertReviewedClaudeCacheClosures(home, config, review, canonical9);
|
|
20810
|
+
for (const root2 of absentRoots) {
|
|
20811
|
+
safe6(root2);
|
|
20812
|
+
if (lstatSync32(root2, { throwIfNoEntry: false }))
|
|
20813
|
+
throw new Error("Retired native materialization changed during discovery review");
|
|
20814
|
+
}
|
|
20528
20815
|
const combined = [...reviewedSources, ...reviewedSourcesWithManifestProjection];
|
|
20529
20816
|
const unique = combined.filter((source, index) => combined.findIndex((candidate2) => isDeepStrictEqual9(candidate2, source)) === index);
|
|
20530
20817
|
return { ...supplied, roots: [...new Set([...roots, ...supplied.roots])].sort(), sources: unique, ...agent === "gemini" ? { builtinNames } : {} };
|
|
@@ -20542,7 +20829,7 @@ function resolveAgentDiscovery(options) {
|
|
|
20542
20829
|
unresolved("plugin hooks require a separate no-skill-injection review");
|
|
20543
20830
|
const commands = join38(root2, "commands");
|
|
20544
20831
|
safe6(commands);
|
|
20545
|
-
if (agent === "claude" && (manifest.commands !== undefined || lstatSync32(commands, { throwIfNoEntry: false })?.isDirectory() &&
|
|
20832
|
+
if (agent === "claude" && (manifest.commands !== undefined || lstatSync32(commands, { throwIfNoEntry: false })?.isDirectory() && readdirSync13(commands).length))
|
|
20546
20833
|
unresolved("legacy command discovery requires retirement or a dedicated format adapter");
|
|
20547
20834
|
const rootSkill = witness(join38(root2, "SKILL.md"));
|
|
20548
20835
|
if (rootSkill !== null)
|
|
@@ -20564,7 +20851,7 @@ function resolveAgentDiscovery(options) {
|
|
|
20564
20851
|
const installed = registrations === null ? {} : parseConfig(registrations, join38(home, ".claude/plugins/installed_plugins.json")).plugins;
|
|
20565
20852
|
const commands = canonical9(join38(home, ".claude/commands"));
|
|
20566
20853
|
safe6(commands);
|
|
20567
|
-
if (lstatSync32(commands, { throwIfNoEntry: false })?.isDirectory() &&
|
|
20854
|
+
if (lstatSync32(commands, { throwIfNoEntry: false })?.isDirectory() && readdirSync13(commands).length)
|
|
20568
20855
|
unresolved("legacy home command discovery requires a dedicated format adapter");
|
|
20569
20856
|
for (const [id, enabled] of Object.entries(config.enabledPlugins ?? {})) {
|
|
20570
20857
|
if (enabled === false)
|
|
@@ -20606,7 +20893,7 @@ function resolveAgentDiscovery(options) {
|
|
|
20606
20893
|
}
|
|
20607
20894
|
const localPlugins = join38(home, ".config/opencode/plugins");
|
|
20608
20895
|
safe6(localPlugins);
|
|
20609
|
-
if (lstatSync32(localPlugins, { throwIfNoEntry: false }) &&
|
|
20896
|
+
if (lstatSync32(localPlugins, { throwIfNoEntry: false }) && readdirSync13(localPlugins).some((name) => name !== "skills-cli.js"))
|
|
20610
20897
|
unresolved("additional local plugin hooks require review");
|
|
20611
20898
|
} else if (agent === "sumi") {
|
|
20612
20899
|
if ((config.plugin?.length ?? 0) > 0 || (config.plugins?.length ?? 0) > 0 || sources.some((source) => source.path !== canonical9(configPath) && source.path !== canonical9(join38(sumiConfigDirectory(home), "sumi.jsonc")) && source.sha256 !== null))
|
|
@@ -20625,7 +20912,7 @@ function resolveAgentDiscovery(options) {
|
|
|
20625
20912
|
const directory2 = join38(home, ".gemini/extensions");
|
|
20626
20913
|
safe6(directory2);
|
|
20627
20914
|
if (lstatSync32(directory2, { throwIfNoEntry: false }))
|
|
20628
|
-
for (const name of
|
|
20915
|
+
for (const name of readdirSync13(directory2)) {
|
|
20629
20916
|
const root2 = join38(directory2, name);
|
|
20630
20917
|
safe6(root2);
|
|
20631
20918
|
if (!lstatSync32(root2)?.isDirectory())
|
|
@@ -39180,11 +39467,12 @@ var remoteAvailabilitySchema = exports_external.object({
|
|
|
39180
39467
|
details: exports_external.array(exports_external.string()).optional()
|
|
39181
39468
|
}).passthrough();
|
|
39182
39469
|
var remoteSkillSchema = exports_external.object({
|
|
39470
|
+
id: exports_external.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/).optional(),
|
|
39183
39471
|
name: exports_external.string().min(1).optional(),
|
|
39184
39472
|
slug: exports_external.string().min(1).optional(),
|
|
39185
39473
|
displayName: exports_external.string().optional(),
|
|
39186
39474
|
description: exports_external.string().optional(),
|
|
39187
|
-
category: exports_external.string().optional(),
|
|
39475
|
+
category: exports_external.string().nullable().optional(),
|
|
39188
39476
|
tags: exports_external.array(exports_external.string()).optional(),
|
|
39189
39477
|
dependencies: exports_external.array(exports_external.string()).optional(),
|
|
39190
39478
|
version: exports_external.string().optional(),
|
|
@@ -39521,46 +39809,6 @@ var revocation = exports_external.object({
|
|
|
39521
39809
|
});
|
|
39522
39810
|
var page = (item) => exports_external.object({ contractVersion: exports_external.literal(1), items: exports_external.array(item).max(100), nextCursor: exports_external.string().min(1).max(2048).nullable() });
|
|
39523
39811
|
var results = { preview, draft: preview.nullable(), activate: exports_external.object({ replayed: exports_external.boolean(), consent }), list: page(consent), get: consent.nullable(), occurrences: page(occurrence), revoke: revocation };
|
|
39524
|
-
var record7 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
39525
|
-
var uuid8 = (v) => typeof v === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(v);
|
|
39526
|
-
var text2 = (v, max = 1024) => typeof v === "string" && !!v.trim() && v.length <= max && !/[\p{Cc}\p{Cs}\u2028\u2029]/u.test(v);
|
|
39527
|
-
var role2 = (v) => typeof v === "string" && ["owner", "admin", "member", "viewer"].includes(v);
|
|
39528
|
-
var invalidWorkspaceResult = "The server returned an invalid workspace selection result.";
|
|
39529
|
-
class WorkspaceIdentityMismatchError extends Error {
|
|
39530
|
-
constructor() {
|
|
39531
|
-
super("The verified account does not match the requested workspace context.");
|
|
39532
|
-
this.name = "WorkspaceIdentityMismatchError";
|
|
39533
|
-
}
|
|
39534
|
-
}
|
|
39535
|
-
function invalid3() {
|
|
39536
|
-
throw new Error(invalidWorkspaceResult);
|
|
39537
|
-
}
|
|
39538
|
-
function organization(v) {
|
|
39539
|
-
if (!record7(v) || !uuid8(v.id) || !text2(v.slug) || !text2(v.name))
|
|
39540
|
-
return invalid3();
|
|
39541
|
-
return { id: v.id, slug: v.slug, name: v.name };
|
|
39542
|
-
}
|
|
39543
|
-
function parseWorkspaceIdentity(value, expectedUserId) {
|
|
39544
|
-
if (!record7(value))
|
|
39545
|
-
return invalid3();
|
|
39546
|
-
const user = value.user;
|
|
39547
|
-
if (!record7(user) || !uuid8(user.id) || !uuid8(user.membershipId) || !text2(user.email, 320) || !(user.displayName === null || text2(user.displayName)) || !role2(user.role))
|
|
39548
|
-
return invalid3();
|
|
39549
|
-
if (user.id !== expectedUserId)
|
|
39550
|
-
throw new WorkspaceIdentityMismatchError;
|
|
39551
|
-
return { user: { id: user.id, membershipId: user.membershipId, email: user.email, displayName: user.displayName, role: user.role }, organization: organization(value.organization) };
|
|
39552
|
-
}
|
|
39553
|
-
function sessionToken(value) {
|
|
39554
|
-
if (typeof value !== "string" || !value || value.length > 8192 || /[^\x21-\x7e]/.test(value) || value.startsWith("sk_"))
|
|
39555
|
-
return invalid3();
|
|
39556
|
-
return value;
|
|
39557
|
-
}
|
|
39558
|
-
function parseWorkspaceSession(value, expected) {
|
|
39559
|
-
const identity5 = parseWorkspaceIdentity(value, expected.userId);
|
|
39560
|
-
if (identity5.user.membershipId !== expected.membershipId)
|
|
39561
|
-
throw new WorkspaceIdentityMismatchError;
|
|
39562
|
-
return { token: sessionToken(value.token), ...identity5 };
|
|
39563
|
-
}
|
|
39564
39812
|
var SKILLS_API_KEY_REF = credentialPointerEnvKey("skills");
|
|
39565
39813
|
var quoteUnavailableMessages = Object.freeze({
|
|
39566
39814
|
HOSTED_PROVIDER_UNAVAILABLE: "Hosted execution is temporarily unavailable on this Skills instance.",
|
|
@@ -39572,308 +39820,6 @@ var quoteUnavailableMessages = Object.freeze({
|
|
|
39572
39820
|
});
|
|
39573
39821
|
var KNOWN_SKILL_LIFECYCLE_CODES = new Set(["SKILL_ARCHIVE_PROFILE_CONFLICT", "LIFECYCLE_ROLE_REQUIRED"]);
|
|
39574
39822
|
var PRIVATE_PUBLICATION_MAX_BYTES = 16 * 1024 * 1024;
|
|
39575
|
-
var failures2 = {
|
|
39576
|
-
INVALID_REQUEST: [400, "The publication request is invalid."],
|
|
39577
|
-
SESSION_EXPIRED: [401, "Sign in again to manage this publication."],
|
|
39578
|
-
ACCOUNT_UNAVAILABLE: [403, "The account is unavailable."],
|
|
39579
|
-
INTERACTIVE_SESSION_REQUIRED: [403, "An interactive account session is required."],
|
|
39580
|
-
PUBLICATION_FORBIDDEN: [403, "This session cannot manage the publication."],
|
|
39581
|
-
PUBLICATION_ENTITLEMENT_REQUIRED: [403, "The workspace is not entitled to publish private skills."],
|
|
39582
|
-
PUBLICATION_UNAVAILABLE: [404, "The publication is unavailable to this session."],
|
|
39583
|
-
MANIFEST_NAME_MISMATCH: [409, "The manifest name does not match the selected skill."],
|
|
39584
|
-
IDEMPOTENCY_CONFLICT: [409, "This request key already identifies different publication bytes. Use the saved recovery directory."],
|
|
39585
|
-
CURRENT_VERSION_CHANGED: [409, "The current version changed. Inspect it before explicitly starting another publication."],
|
|
39586
|
-
VERSION_EXISTS: [409, "This version already exists."],
|
|
39587
|
-
VERSION_RESERVED: [409, "This version is reserved by another publication."],
|
|
39588
|
-
PUBLICATION_COMMITTED: [409, "The publication is already committed."],
|
|
39589
|
-
PUBLICATION_UPLOAD_UNAVAILABLE: [409, "This publication cannot receive another upload."],
|
|
39590
|
-
PUBLICATION_LIMIT: [429, "The workspace publication limit has been reached."],
|
|
39591
|
-
PUBLICATION_BUSY: [503, "The publication is busy. Reconcile the saved intent before retrying."],
|
|
39592
|
-
PUBLICATION_UNCERTAIN: [503, "The publication outcome is uncertain. Reconcile the saved intent."],
|
|
39593
|
-
PUBLICATION_CAPABILITY_UNAVAILABLE: [503, "Private publishing is not enabled on this server."],
|
|
39594
|
-
PUBLICATION_SIGNING_UNAVAILABLE: [503, "Upload authorization is temporarily unavailable. Keep the same intent."]
|
|
39595
|
-
};
|
|
39596
|
-
|
|
39597
|
-
class PrivatePublicationError extends Error {
|
|
39598
|
-
code;
|
|
39599
|
-
uncertain;
|
|
39600
|
-
status;
|
|
39601
|
-
constructor(code, message, uncertain = false, status) {
|
|
39602
|
-
super(message);
|
|
39603
|
-
this.code = code;
|
|
39604
|
-
this.uncertain = uncertain;
|
|
39605
|
-
this.status = status;
|
|
39606
|
-
this.name = "PrivatePublicationError";
|
|
39607
|
-
}
|
|
39608
|
-
}
|
|
39609
|
-
var bad = () => {
|
|
39610
|
-
throw new PrivatePublicationError("INVALID_PUBLICATION_INPUT", "Invalid publication input or recovery data.");
|
|
39611
|
-
};
|
|
39612
|
-
var invalid4 = () => {
|
|
39613
|
-
throw new PrivatePublicationError("INVALID_PUBLICATION_RESPONSE", "The server returned an invalid publication result.");
|
|
39614
|
-
};
|
|
39615
|
-
var publicationUuid = (v) => typeof v === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(v);
|
|
39616
|
-
var hash4 = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
|
|
39617
|
-
var record11 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
39618
|
-
var exact = (v, keys2) => record11(v) && Object.keys(v).sort().join(",") === keys2.sort().join(",");
|
|
39619
|
-
var date5 = (v) => typeof v === "string" && /^\d{4}-\d\d-\d\dT[0-9:.]+(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(v) && Number.isFinite(Date.parse(v));
|
|
39620
|
-
var publicationSha256 = (bytes) => createHash34("sha256").update(bytes).digest("hex");
|
|
39621
|
-
function checkedPublicationDeclaration(value) {
|
|
39622
|
-
if (!exact(value, ["idempotencyKey", "version", "expectedCurrentVersionId", "manifestText", "archiveSha256", "archiveByteSize"]) || !publicationUuid(value.idempotencyKey) || !(value.expectedCurrentVersionId === null || publicationUuid(value.expectedCurrentVersionId)) || typeof value.version !== "string" || !value.version || value.version.length > 128 || /[\p{Cc}\p{Cs}]/u.test(value.version) || typeof value.manifestText !== "string" || Buffer.byteLength(value.manifestText) > 16384 || !hash4(value.archiveSha256) || !Number.isSafeInteger(value.archiveByteSize) || Number(value.archiveByteSize) < 1 || Number(value.archiveByteSize) > PRIVATE_PUBLICATION_MAX_BYTES)
|
|
39623
|
-
return bad();
|
|
39624
|
-
try {
|
|
39625
|
-
const manifest = JSON.parse(value.manifestText);
|
|
39626
|
-
if (!record11(manifest) || manifest.version !== value.version || validatePortableManifestContract(manifest, { strict: true }).length || !hash4(manifest.provenance?.content_hash))
|
|
39627
|
-
return bad();
|
|
39628
|
-
} catch {
|
|
39629
|
-
return bad();
|
|
39630
|
-
}
|
|
39631
|
-
return Object.freeze({ ...value });
|
|
39632
|
-
}
|
|
39633
|
-
function checkedPublicationView(value, skillId, intentId, declaration) {
|
|
39634
|
-
if (!exact(value, ["id", "skillId", "version", "expectedCurrentVersionId", "archiveSha256", "archiveByteSize", "state", "expiresAt", "createdAt", "versionId"]) || !publicationUuid(value.id) || value.skillId !== skillId || intentId !== undefined && value.id !== intentId || typeof value.version !== "string" || !value.version || value.version.length > 128 || /[\p{Cc}\p{Cs}]/u.test(value.version) || !(value.expectedCurrentVersionId === null || publicationUuid(value.expectedCurrentVersionId)) || !hash4(value.archiveSha256) || !Number.isSafeInteger(value.archiveByteSize) || Number(value.archiveByteSize) < 1 || Number(value.archiveByteSize) > PRIVATE_PUBLICATION_MAX_BYTES || typeof value.state !== "string" || !["awaiting_upload", "queued", "verifying", "needs_attention", "committed", "rejected", "cancelled", "expired"].includes(value.state) || !date5(value.expiresAt) || !date5(value.createdAt) || !(value.versionId === null || publicationUuid(value.versionId)) || value.state === "committed" && value.versionId === null)
|
|
39635
|
-
return invalid4();
|
|
39636
|
-
if (declaration && ["version", "expectedCurrentVersionId", "archiveSha256", "archiveByteSize"].some((k) => value[k] !== declaration[k]))
|
|
39637
|
-
return invalid4();
|
|
39638
|
-
return Object.freeze({ ...value });
|
|
39639
|
-
}
|
|
39640
|
-
async function boundedJson(url2, init, token, mutation, budget3 = 15000, signal) {
|
|
39641
|
-
const controller = new AbortController;
|
|
39642
|
-
let reader;
|
|
39643
|
-
let response;
|
|
39644
|
-
const timeout2 = new PrivatePublicationError("PUBLICATION_UNCONFIRMED", "No confirmed publication result. Inspect the saved intent before retrying.", mutation);
|
|
39645
|
-
let timer;
|
|
39646
|
-
let abort;
|
|
39647
|
-
try {
|
|
39648
|
-
return await Promise.race([(async () => {
|
|
39649
|
-
if (signal?.aborted)
|
|
39650
|
-
throw timeout2;
|
|
39651
|
-
response = await fetch(url2, {
|
|
39652
|
-
...init,
|
|
39653
|
-
redirect: "error",
|
|
39654
|
-
credentials: "omit",
|
|
39655
|
-
signal: controller.signal,
|
|
39656
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }
|
|
39657
|
-
});
|
|
39658
|
-
const length = response.headers.get("content-length");
|
|
39659
|
-
if (length !== null && (!/^\d+$/.test(length) || Number(length) > 65536))
|
|
39660
|
-
return invalid4();
|
|
39661
|
-
reader = response.body?.getReader();
|
|
39662
|
-
const chunks = [];
|
|
39663
|
-
let size = 0;
|
|
39664
|
-
if (reader)
|
|
39665
|
-
while (true) {
|
|
39666
|
-
const part = await reader.read();
|
|
39667
|
-
if (part.done)
|
|
39668
|
-
break;
|
|
39669
|
-
size += part.value.byteLength;
|
|
39670
|
-
if (size > 65536)
|
|
39671
|
-
return invalid4();
|
|
39672
|
-
chunks.push(part.value);
|
|
39673
|
-
}
|
|
39674
|
-
if (controller.signal.aborted)
|
|
39675
|
-
throw timeout2;
|
|
39676
|
-
const bytes = Buffer.concat(chunks);
|
|
39677
|
-
let body;
|
|
39678
|
-
try {
|
|
39679
|
-
body = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
39680
|
-
} catch {
|
|
39681
|
-
return invalid4();
|
|
39682
|
-
}
|
|
39683
|
-
if (!response.ok) {
|
|
39684
|
-
const code = record11(body) && typeof body.code === "string" && Object.hasOwn(failures2, body.code) ? body.code : null;
|
|
39685
|
-
if (code && failures2[code][0] === response.status)
|
|
39686
|
-
throw new PrivatePublicationError(code, failures2[code][1], mutation && code === "PUBLICATION_UNCERTAIN", response.status);
|
|
39687
|
-
throw new PrivatePublicationError("PUBLICATION_REQUEST_FAILED", "The publication request was refused. Inspect its status before retrying.", mutation && response.status >= 500, response.status);
|
|
39688
|
-
}
|
|
39689
|
-
return body;
|
|
39690
|
-
})(), new Promise((_, reject) => {
|
|
39691
|
-
abort = () => {
|
|
39692
|
-
controller.abort();
|
|
39693
|
-
reject(timeout2);
|
|
39694
|
-
};
|
|
39695
|
-
timer = setTimeout(abort, Math.max(1, Math.min(15000, budget3)));
|
|
39696
|
-
signal?.addEventListener("abort", abort, { once: true });
|
|
39697
|
-
})]);
|
|
39698
|
-
} catch (error61) {
|
|
39699
|
-
if (error61 instanceof PrivatePublicationError) {
|
|
39700
|
-
if (mutation && error61.code === "INVALID_PUBLICATION_RESPONSE")
|
|
39701
|
-
throw timeout2;
|
|
39702
|
-
throw error61;
|
|
39703
|
-
}
|
|
39704
|
-
throw timeout2;
|
|
39705
|
-
} finally {
|
|
39706
|
-
if (timer)
|
|
39707
|
-
clearTimeout(timer);
|
|
39708
|
-
if (abort)
|
|
39709
|
-
signal?.removeEventListener("abort", abort);
|
|
39710
|
-
controller.abort();
|
|
39711
|
-
if (reader)
|
|
39712
|
-
reader.cancel().catch(() => {});
|
|
39713
|
-
else
|
|
39714
|
-
response?.body?.cancel().catch(() => {});
|
|
39715
|
-
}
|
|
39716
|
-
}
|
|
39717
|
-
|
|
39718
|
-
class RemotePrivatePublicationsClient {
|
|
39719
|
-
apiOrigin;
|
|
39720
|
-
organizationId;
|
|
39721
|
-
userId;
|
|
39722
|
-
membershipId;
|
|
39723
|
-
#token;
|
|
39724
|
-
constructor(apiUrl, session) {
|
|
39725
|
-
const checked = parseWorkspaceSession(session, { userId: session?.user?.id, membershipId: session?.user?.membershipId });
|
|
39726
|
-
if (checked.user.role === "viewer")
|
|
39727
|
-
throw new PrivatePublicationError("PUBLICATION_FORBIDDEN", failures2.PUBLICATION_FORBIDDEN[1]);
|
|
39728
|
-
this.apiOrigin = normalizeSkillsApiOrigin(apiUrl);
|
|
39729
|
-
this.#token = checked.token;
|
|
39730
|
-
this.organizationId = checked.organization.id;
|
|
39731
|
-
this.userId = checked.user.id;
|
|
39732
|
-
this.membershipId = checked.user.membershipId;
|
|
39733
|
-
Object.freeze(this);
|
|
39734
|
-
}
|
|
39735
|
-
async getCapability(options = {}) {
|
|
39736
|
-
if (options.timeoutMs !== undefined && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 15000))
|
|
39737
|
-
return bad();
|
|
39738
|
-
const response = await boundedJson(skillsApiRequestUrl(this.apiOrigin, "/api/v1/capabilities"), {}, this.#token, false, options.timeoutMs, options.signal);
|
|
39739
|
-
const p = record11(response) && response.privatePublishing;
|
|
39740
|
-
if (!record11(response) || response.contractVersion !== 1 || response.apiVersion !== 1 || !exact(p, ["contractVersion", "enabled", "authentication", "maxArchiveBytes", "uploadMaxTtlSeconds", "executionEnabled"]) || p.contractVersion !== 1 || typeof p.enabled !== "boolean" || p.authentication !== "interactive-session" || p.maxArchiveBytes !== PRIVATE_PUBLICATION_MAX_BYTES || p.uploadMaxTtlSeconds !== 300 || typeof p.executionEnabled !== "boolean")
|
|
39741
|
-
throw new PrivatePublicationError("PUBLICATION_CONTRACT_UNAVAILABLE", "This server does not support the hosted private publication contract.");
|
|
39742
|
-
return Object.freeze({ ...p });
|
|
39743
|
-
}
|
|
39744
|
-
async#gate(enabled, options = {}) {
|
|
39745
|
-
if (!(await this.getCapability(options)).enabled && enabled)
|
|
39746
|
-
throw new PrivatePublicationError("PUBLICATION_CAPABILITY_UNAVAILABLE", failures2.PUBLICATION_CAPABILITY_UNAVAILABLE[1]);
|
|
39747
|
-
}
|
|
39748
|
-
#path(skillId, intentId) {
|
|
39749
|
-
if (!publicationUuid(skillId) || intentId !== undefined && !publicationUuid(intentId))
|
|
39750
|
-
return bad();
|
|
39751
|
-
return skillsApiRequestUrl(this.apiOrigin, `/api/v1/skills/${skillId}/publication-uploads${intentId ? `/${intentId}` : ""}`);
|
|
39752
|
-
}
|
|
39753
|
-
async#view(path, method, skillId, intentId, declaration, options = {}) {
|
|
39754
|
-
const value = await boundedJson(path, { method, ...method === "GET" ? {} : { body: JSON.stringify(declaration ?? {}) } }, this.#token, method !== "GET", options.timeoutMs, options.signal);
|
|
39755
|
-
try {
|
|
39756
|
-
if (!record11(value) || !Object.keys(value).every((k) => k === "upload" || k === "changed") || value.changed !== undefined && typeof value.changed !== "boolean")
|
|
39757
|
-
return invalid4();
|
|
39758
|
-
return checkedPublicationView(value.upload, skillId, intentId, declaration);
|
|
39759
|
-
} catch (error61) {
|
|
39760
|
-
if (method !== "GET")
|
|
39761
|
-
throw new PrivatePublicationError("PUBLICATION_UNCONFIRMED", "The publication result could not be confirmed. Reconcile the saved intent before another action.", true);
|
|
39762
|
-
throw error61;
|
|
39763
|
-
}
|
|
39764
|
-
}
|
|
39765
|
-
async begin(skillId, input2) {
|
|
39766
|
-
const path = this.#path(skillId), declaration = checkedPublicationDeclaration(input2);
|
|
39767
|
-
await this.#gate(true);
|
|
39768
|
-
return this.#view(path, "POST", skillId, undefined, declaration);
|
|
39769
|
-
}
|
|
39770
|
-
async get(skillId, intentId, options = {}) {
|
|
39771
|
-
const path = this.#path(skillId, intentId), until = Date.now() + (options.timeoutMs ?? 15000);
|
|
39772
|
-
await this.#gate(false, options);
|
|
39773
|
-
return this.#view(path, "GET", skillId, intentId, undefined, { ...options, timeoutMs: Math.max(1, until - Date.now()) });
|
|
39774
|
-
}
|
|
39775
|
-
async finalize(skillId, intentId) {
|
|
39776
|
-
const path = this.#path(skillId, intentId);
|
|
39777
|
-
await this.#gate(true);
|
|
39778
|
-
return this.#view(`${path}/finalize`, "POST", skillId, intentId);
|
|
39779
|
-
}
|
|
39780
|
-
async cancel(skillId, intentId) {
|
|
39781
|
-
const path = this.#path(skillId, intentId);
|
|
39782
|
-
await this.#gate(false);
|
|
39783
|
-
return this.#view(path, "DELETE", skillId, intentId);
|
|
39784
|
-
}
|
|
39785
|
-
async upload(skillId, intent, bytes) {
|
|
39786
|
-
const captured = checkedPublicationView(intent, skillId), path = this.#path(skillId, captured.id);
|
|
39787
|
-
if (!(bytes instanceof Uint8Array) || bytes.byteLength !== captured.archiveByteSize)
|
|
39788
|
-
return bad();
|
|
39789
|
-
const owned = Buffer.from(bytes);
|
|
39790
|
-
if (captured.state !== "awaiting_upload" || owned.byteLength !== captured.archiveByteSize || publicationSha256(owned) !== captured.archiveSha256)
|
|
39791
|
-
return bad();
|
|
39792
|
-
await this.#gate(true);
|
|
39793
|
-
const value = await boundedJson(`${path}/upload-url`, { method: "POST", body: "{}" }, this.#token, false);
|
|
39794
|
-
const upload = this.#upload(value, captured);
|
|
39795
|
-
const controller = new AbortController;
|
|
39796
|
-
let timer;
|
|
39797
|
-
const uncertain = () => new PrivatePublicationError("PUBLICATION_UPLOAD_UNCONFIRMED", "Upload acceptance is uncertain. Resume this saved intent to finalize and inspect it; do not upload again.", true);
|
|
39798
|
-
try {
|
|
39799
|
-
await Promise.race([(async () => {
|
|
39800
|
-
const response = await fetch(upload.uploadUrl, { method: "PUT", headers: upload.headers, body: owned, redirect: "error", credentials: "omit", signal: controller.signal });
|
|
39801
|
-
response.body?.cancel().catch(() => {});
|
|
39802
|
-
if (response.status !== 200 || controller.signal.aborted)
|
|
39803
|
-
throw uncertain();
|
|
39804
|
-
})(), new Promise((_, reject) => {
|
|
39805
|
-
timer = setTimeout(() => {
|
|
39806
|
-
controller.abort();
|
|
39807
|
-
reject(uncertain());
|
|
39808
|
-
}, 30000);
|
|
39809
|
-
})]);
|
|
39810
|
-
} catch {
|
|
39811
|
-
throw uncertain();
|
|
39812
|
-
} finally {
|
|
39813
|
-
if (timer)
|
|
39814
|
-
clearTimeout(timer);
|
|
39815
|
-
controller.abort();
|
|
39816
|
-
}
|
|
39817
|
-
}
|
|
39818
|
-
#upload(value, intent) {
|
|
39819
|
-
if (!exact(value, ["upload"]) || !exact(value.upload, ["method", "uploadUrl", "headers", "expiresAt"]))
|
|
39820
|
-
return invalid4();
|
|
39821
|
-
const p = value.upload;
|
|
39822
|
-
if (p.method !== "PUT" || typeof p.uploadUrl !== "string" || p.uploadUrl.length > 8192 || /[\x00-\x20\x7f]/.test(p.uploadUrl) || !date5(p.expiresAt) || Date.parse(p.expiresAt) - Date.now() < 1000 || Date.parse(p.expiresAt) - Date.now() > 300000 || Date.parse(p.expiresAt) > Date.parse(intent.expiresAt) || !exact(p.headers, ["content-type", "content-length", "x-amz-checksum-sha256", "x-amz-expected-bucket-owner"]) || p.headers["content-type"] !== "application/gzip" || p.headers["content-length"] !== String(intent.archiveByteSize) || p.headers["x-amz-checksum-sha256"] !== Buffer.from(intent.archiveSha256, "hex").toString("base64") || typeof p.headers["x-amz-expected-bucket-owner"] !== "string" || !/^\d{12}$/.test(p.headers["x-amz-expected-bucket-owner"]))
|
|
39823
|
-
return invalid4();
|
|
39824
|
-
let url2;
|
|
39825
|
-
try {
|
|
39826
|
-
url2 = new URL(p.uploadUrl);
|
|
39827
|
-
} catch {
|
|
39828
|
-
return invalid4();
|
|
39829
|
-
}
|
|
39830
|
-
if (url2.protocol !== "https:" || url2.port || url2.username || url2.password || url2.hash || !/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]\.s3\.[a-z]{2}(?:-[a-z]+)+-[1-9]\.amazonaws\.com$/.test(url2.hostname) || url2.pathname !== `/private-publication-staging/${this.organizationId}/${intent.id}/bundle.tgz` || !url2.search || url2.searchParams.get("X-Amz-Algorithm") !== "AWS4-HMAC-SHA256" || url2.searchParams.get("X-Amz-SignedHeaders") !== "content-length;content-type;host;x-amz-checksum-sha256;x-amz-expected-bucket-owner" || !/^[a-f0-9]{64}$/.test(url2.searchParams.get("X-Amz-Signature") ?? ""))
|
|
39831
|
-
return invalid4();
|
|
39832
|
-
const queryKeys = ["X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date", "X-Amz-Expires", "X-Amz-Security-Token", "X-Amz-Signature", "X-Amz-SignedHeaders"];
|
|
39833
|
-
if ([...url2.searchParams.keys()].sort().join(",") !== queryKeys.sort().join(","))
|
|
39834
|
-
return invalid4();
|
|
39835
|
-
const issued = url2.searchParams.get("X-Amz-Date"), ttl = url2.searchParams.get("X-Amz-Expires"), credential = url2.searchParams.get("X-Amz-Credential");
|
|
39836
|
-
const timestamp3 = /^(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)Z$/.exec(issued);
|
|
39837
|
-
const region = url2.hostname.split(".s3.")[1].split(".amazonaws.com")[0];
|
|
39838
|
-
if (!timestamp3 || !/^[1-9]\d{0,2}$/.test(ttl) || Number(ttl) > 300 || !/^[A-Z0-9]{16,128}\//.test(credential) || credential.split("/").slice(1).join("/") !== `${issued.slice(0, 8)}/${region}/s3/aws4_request` || !/^[\x21-\x7e]{1,4096}$/.test(url2.searchParams.get("X-Amz-Security-Token")))
|
|
39839
|
-
return invalid4();
|
|
39840
|
-
const issuedAt = Date.parse(`${timestamp3[1]}-${timestamp3[2]}-${timestamp3[3]}T${timestamp3[4]}:${timestamp3[5]}:${timestamp3[6]}Z`);
|
|
39841
|
-
if (!Number.isFinite(issuedAt) || issuedAt > Date.now() + 1000 || issuedAt + Number(ttl) * 1000 !== Date.parse(p.expiresAt))
|
|
39842
|
-
return invalid4();
|
|
39843
|
-
return { method: "PUT", uploadUrl: url2.href, expiresAt: p.expiresAt, headers: Object.freeze({ ...p.headers }) };
|
|
39844
|
-
}
|
|
39845
|
-
async wait(skillId, intentId, options = {}) {
|
|
39846
|
-
const timeout2 = options.timeoutMs ?? 60000;
|
|
39847
|
-
if (!Number.isSafeInteger(timeout2) || timeout2 < 0 || timeout2 > 300000)
|
|
39848
|
-
return bad();
|
|
39849
|
-
const until = Date.now() + timeout2;
|
|
39850
|
-
let previous;
|
|
39851
|
-
while (true) {
|
|
39852
|
-
if (options.signal?.aborted)
|
|
39853
|
-
throw new PrivatePublicationError("PUBLICATION_WAIT_ABORTED", "Stopped waiting. The server publication continues; inspect the saved intent.");
|
|
39854
|
-
let view;
|
|
39855
|
-
try {
|
|
39856
|
-
view = await this.get(skillId, intentId, { timeoutMs: timeout2 === 0 ? 15000 : Math.max(1, Math.min(15000, until - Date.now())), signal: options.signal });
|
|
39857
|
-
} catch (error61) {
|
|
39858
|
-
if (previous && Date.now() >= until && !options.signal?.aborted)
|
|
39859
|
-
return previous;
|
|
39860
|
-
throw error61;
|
|
39861
|
-
}
|
|
39862
|
-
previous = view;
|
|
39863
|
-
if (!["queued", "verifying"].includes(view.state) || Date.now() >= until)
|
|
39864
|
-
return view;
|
|
39865
|
-
await new Promise((resolve30) => {
|
|
39866
|
-
const timer = setTimeout(done, Math.min(1000, until - Date.now()));
|
|
39867
|
-
function done() {
|
|
39868
|
-
clearTimeout(timer);
|
|
39869
|
-
options.signal?.removeEventListener("abort", done);
|
|
39870
|
-
resolve30();
|
|
39871
|
-
}
|
|
39872
|
-
options.signal?.addEventListener("abort", done, { once: true });
|
|
39873
|
-
});
|
|
39874
|
-
}
|
|
39875
|
-
}
|
|
39876
|
-
}
|
|
39877
39823
|
var uuid12 = exports_external.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/);
|
|
39878
39824
|
var sha6 = exports_external.string().regex(/^[a-f0-9]{64}$/);
|
|
39879
39825
|
var common = exports_external.object({
|
|
@@ -41081,7 +41027,7 @@ function claudeSkillsUsage(before, home) {
|
|
|
41081
41027
|
}
|
|
41082
41028
|
if (events3.length)
|
|
41083
41029
|
evidence.push(`Skills-managed hook entries in ${events3.join(", ")}`);
|
|
41084
|
-
const bridge =
|
|
41030
|
+
const bridge = join17(home, ".claude", "skills", "skills-cli", "SKILL.md");
|
|
41085
41031
|
let bridgePresent;
|
|
41086
41032
|
try {
|
|
41087
41033
|
bridgePresent = lstatSync9(bridge, { throwIfNoEntry: false }) !== undefined;
|
|
@@ -41095,8 +41041,8 @@ function claudeSkillsUsage(before, home) {
|
|
|
41095
41041
|
function skillsPolicyLocations(dataDir3) {
|
|
41096
41042
|
const state = (path) => existsSync11(path) ? "present" : "absent";
|
|
41097
41043
|
if (dataDir3 !== undefined)
|
|
41098
|
-
return [`${
|
|
41099
|
-
const env = process.env, home = env.HOME || env.USERPROFILE ||
|
|
41044
|
+
return [`${join17(resolve9(dataDir3), "agent-policy.json")} (explicit data directory, absent)`];
|
|
41045
|
+
const env = process.env, home = env.HOME || env.USERPROFILE || homedir7() || "/tmp", searched = [];
|
|
41100
41046
|
let selected = false;
|
|
41101
41047
|
for (const key2 of ["HASNA_SKILLS_DIR", "HASNA_SKILLS_HOME", "SKILLS_HOME"]) {
|
|
41102
41048
|
const value = env[key2]?.trim();
|
|
@@ -41106,13 +41052,13 @@ function skillsPolicyLocations(dataDir3) {
|
|
|
41106
41052
|
searched.push(`$${key2} (unset)`);
|
|
41107
41053
|
else {
|
|
41108
41054
|
selected = true;
|
|
41109
|
-
searched.push(`$${key2} -> ${
|
|
41055
|
+
searched.push(`$${key2} -> ${join17(resolve9(value), "agent-policy.json")} (selected, absent)`);
|
|
41110
41056
|
}
|
|
41111
41057
|
}
|
|
41112
41058
|
const override = env.HASNA_DATA_HOME;
|
|
41113
|
-
const base = typeof override === "string" && override.length > 0 ? override : process.platform === "darwin" ?
|
|
41114
|
-
const xdg =
|
|
41115
|
-
const adopted = typeof override === "string" && override.trim().length > 0 || existsSync11(
|
|
41059
|
+
const base = typeof override === "string" && override.length > 0 ? override : process.platform === "darwin" ? join17(home, "Library", "Application Support", "Hasna") : join17(home, ".local", "share", "hasna");
|
|
41060
|
+
const xdg = join17(base, "skills"), xdgPolicy = join17(xdg, "agent-policy.json");
|
|
41061
|
+
const adopted = typeof override === "string" && override.trim().length > 0 || existsSync11(join17(xdg, "server.db")) || existsSync11(join17(xdg, "config.json"));
|
|
41116
41062
|
if (selected)
|
|
41117
41063
|
searched.push(`${xdgPolicy} (not consulted, ${state(xdgPolicy)})`);
|
|
41118
41064
|
else if (adopted) {
|
|
@@ -41120,7 +41066,7 @@ function skillsPolicyLocations(dataDir3) {
|
|
|
41120
41066
|
searched.push(`${xdgPolicy} (selected, absent)`);
|
|
41121
41067
|
} else
|
|
41122
41068
|
searched.push(`${xdgPolicy} (not selected: the directory holds no server.db or config.json and HASNA_DATA_HOME is unset; ${state(xdgPolicy)})`);
|
|
41123
|
-
const legacy =
|
|
41069
|
+
const legacy = join17(home, ".hasna", "skills", "agent-policy.json");
|
|
41124
41070
|
searched.push(selected ? `${legacy} (not consulted, ${state(legacy)})` : `${legacy} (selected, absent)`);
|
|
41125
41071
|
return searched;
|
|
41126
41072
|
}
|
|
@@ -41138,7 +41084,7 @@ function planCoordinatedClaudeSettings(before, replacement, options) {
|
|
|
41138
41084
|
if (!plan) {
|
|
41139
41085
|
const usage = claudeSkillsUsage(before, options.home);
|
|
41140
41086
|
if (usage.length)
|
|
41141
|
-
throw new ClaudeSettingsRefusal("skills_policy_unresolved", `Skills manages ${
|
|
41087
|
+
throw new ClaudeSettingsRefusal("skills_policy_unresolved", `Skills manages ${join17(options.home, ".claude", "settings.json")} (${usage.join("; ")}), but no Skills agent policy resolved, ` + "so Hooks cannot coordinate this change and wrote nothing. Locations searched, in Skills resolution order: " + skillsPolicyLocations(options.dataDir).map((location, index) => `${index + 1}) ${location}`).join("; ") + ". Run hooks with the environment that selects the Skills data directory (for example HASNA_SKILLS_DIR), " + "or repair the integration with `skills hook install`.");
|
|
41142
41088
|
}
|
|
41143
41089
|
return plan;
|
|
41144
41090
|
}
|
|
@@ -41151,22 +41097,771 @@ function coordinateClaudeSettings(before, replacement, options, beforeWrite) {
|
|
|
41151
41097
|
return true;
|
|
41152
41098
|
}
|
|
41153
41099
|
|
|
41154
|
-
// src/lib/
|
|
41155
|
-
|
|
41156
|
-
|
|
41157
|
-
|
|
41100
|
+
// src/lib/target-adapters.ts
|
|
41101
|
+
import { spawnSync } from "child_process";
|
|
41102
|
+
import { chmodSync as chmodSync2, existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync8, readdirSync as readdirSync4, rmdirSync as rmdirSync2, statSync, unlinkSync as unlinkSync3, writeFileSync as writeFileSync9, renameSync as renameSync5 } from "fs";
|
|
41103
|
+
import { tmpdir } from "os";
|
|
41104
|
+
import { basename as basename9, dirname as dirname9, join as join22 } from "path";
|
|
41105
|
+
import { randomUUID as randomUUID5 } from "crypto";
|
|
41106
|
+
|
|
41107
|
+
// src/lib/profiles.ts
|
|
41108
|
+
init_app_home();
|
|
41109
|
+
import { existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync7, readdirSync as readdirSync3, rmSync as rmSync3, cpSync as cpSync2 } from "fs";
|
|
41110
|
+
import { join as join20 } from "path";
|
|
41111
|
+
function getProfilesDir() {
|
|
41112
|
+
const newDir = join20(getEffectiveDataRoot(), "profiles");
|
|
41113
|
+
const oldDir = join20(getHomeDir(), ".hooks", "profiles");
|
|
41114
|
+
if (!existsSync12(newDir) && existsSync12(oldDir)) {
|
|
41115
|
+
mkdirSync6(newDir, { recursive: true });
|
|
41116
|
+
cpSync2(oldDir, newDir, { recursive: true });
|
|
41117
|
+
}
|
|
41118
|
+
return newDir;
|
|
41158
41119
|
}
|
|
41159
|
-
function
|
|
41160
|
-
|
|
41161
|
-
|
|
41162
|
-
|
|
41163
|
-
|
|
41164
|
-
|
|
41120
|
+
function ensureProfilesDir() {
|
|
41121
|
+
const dir = getProfilesDir();
|
|
41122
|
+
if (!existsSync12(dir)) {
|
|
41123
|
+
mkdirSync6(dir, { recursive: true });
|
|
41124
|
+
}
|
|
41125
|
+
}
|
|
41126
|
+
function profilePath(id) {
|
|
41127
|
+
return join20(getProfilesDir(), `${id}.json`);
|
|
41128
|
+
}
|
|
41129
|
+
function shortUuid() {
|
|
41130
|
+
return crypto.randomUUID().slice(0, 8);
|
|
41131
|
+
}
|
|
41132
|
+
function createProfile(input2) {
|
|
41133
|
+
ensureProfilesDir();
|
|
41134
|
+
const id = shortUuid();
|
|
41135
|
+
const now = new Date().toISOString();
|
|
41136
|
+
const profile = {
|
|
41137
|
+
agent_id: id,
|
|
41138
|
+
agent_type: input2.agent_type,
|
|
41139
|
+
created_at: now,
|
|
41140
|
+
last_seen_at: now,
|
|
41141
|
+
preferences: {}
|
|
41142
|
+
};
|
|
41143
|
+
if (input2.name) {
|
|
41144
|
+
profile.name = input2.name;
|
|
41145
|
+
}
|
|
41146
|
+
writeFileSync7(profilePath(id), JSON.stringify(profile, null, 2) + `
|
|
41147
|
+
`);
|
|
41148
|
+
return profile;
|
|
41149
|
+
}
|
|
41150
|
+
function getProfile(id) {
|
|
41151
|
+
const path = profilePath(id);
|
|
41152
|
+
try {
|
|
41153
|
+
if (!existsSync12(path))
|
|
41154
|
+
return null;
|
|
41155
|
+
return JSON.parse(readFileSync7(path, "utf-8"));
|
|
41156
|
+
} catch {
|
|
41157
|
+
return null;
|
|
41158
|
+
}
|
|
41159
|
+
}
|
|
41160
|
+
function listProfiles() {
|
|
41161
|
+
const dir = getProfilesDir();
|
|
41162
|
+
if (!existsSync12(dir))
|
|
41163
|
+
return [];
|
|
41164
|
+
try {
|
|
41165
|
+
const files = readdirSync3(dir).filter((f) => f.endsWith(".json"));
|
|
41166
|
+
const profiles = [];
|
|
41167
|
+
for (const file2 of files) {
|
|
41168
|
+
try {
|
|
41169
|
+
const content = readFileSync7(join20(dir, file2), "utf-8");
|
|
41170
|
+
profiles.push(JSON.parse(content));
|
|
41171
|
+
} catch {}
|
|
41172
|
+
}
|
|
41173
|
+
return profiles.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
|
|
41174
|
+
} catch {
|
|
41175
|
+
return [];
|
|
41176
|
+
}
|
|
41177
|
+
}
|
|
41178
|
+
function updateProfile(id, data) {
|
|
41179
|
+
const profile = getProfile(id);
|
|
41180
|
+
if (!profile)
|
|
41181
|
+
return null;
|
|
41182
|
+
if (data.name !== undefined)
|
|
41183
|
+
profile.name = data.name;
|
|
41184
|
+
if (data.preferences !== undefined)
|
|
41185
|
+
profile.preferences = data.preferences;
|
|
41186
|
+
writeFileSync7(profilePath(id), JSON.stringify(profile, null, 2) + `
|
|
41187
|
+
`);
|
|
41188
|
+
return profile;
|
|
41189
|
+
}
|
|
41190
|
+
|
|
41191
|
+
// src/lib/target-adapters.ts
|
|
41192
|
+
var ADAPTER_TARGETS = ["muse", "kimi", "pi", "cursor"];
|
|
41193
|
+
function isAdapterTarget(value) {
|
|
41194
|
+
return typeof value === "string" && ADAPTER_TARGETS.includes(value);
|
|
41195
|
+
}
|
|
41196
|
+
var defaultRunner = (command, args) => {
|
|
41197
|
+
const result = spawnSync(command, args, { encoding: "utf8", maxBuffer: 4 * 1024 * 1024 });
|
|
41198
|
+
return {
|
|
41199
|
+
status: result.status ?? 1,
|
|
41200
|
+
stdout: result.stdout ?? "",
|
|
41201
|
+
stderr: result.stderr ?? "",
|
|
41202
|
+
notFound: result.error?.code === "ENOENT"
|
|
41203
|
+
};
|
|
41204
|
+
};
|
|
41205
|
+
var HOOK_COMMAND_RE = /^hooks run ([\w-]+)(?:\s|$)/;
|
|
41206
|
+
function hookFromCommand(command) {
|
|
41207
|
+
return command.trim().match(HOOK_COMMAND_RE)?.[1];
|
|
41208
|
+
}
|
|
41209
|
+
function homeOf(options) {
|
|
41210
|
+
return options.home ?? process.env.HOME ?? process.env.USERPROFILE ?? "";
|
|
41211
|
+
}
|
|
41212
|
+
function adapterPath(target, options, hook) {
|
|
41213
|
+
const capabilities = getTargetCapabilities(target, {
|
|
41214
|
+
scope: options.scope,
|
|
41215
|
+
home: homeOf(options),
|
|
41216
|
+
cwd: options.cwd ?? process.cwd(),
|
|
41217
|
+
env: options.env ?? process.env,
|
|
41218
|
+
...hook ? { hook } : {}
|
|
41219
|
+
});
|
|
41220
|
+
if (!capabilities)
|
|
41221
|
+
throw new Error(`No capability record for target '${target}'`);
|
|
41222
|
+
return capabilities.configPath;
|
|
41223
|
+
}
|
|
41224
|
+
function redactedDiagnostic(text2) {
|
|
41225
|
+
const line = (text2.split(`
|
|
41226
|
+
`).find((entry) => entry.trim()) ?? "").trim();
|
|
41227
|
+
return line.slice(0, 300).replace(/[A-Za-z0-9_\-]{24,}/g, "<redacted>");
|
|
41228
|
+
}
|
|
41229
|
+
function redactedCode(value) {
|
|
41230
|
+
return typeof value === "string" && value.length <= 64 && /^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$/.test(value) ? value : "<redacted>";
|
|
41231
|
+
}
|
|
41232
|
+
function messageOf(error61) {
|
|
41233
|
+
return error61 instanceof Error ? error61.message : String(error61);
|
|
41234
|
+
}
|
|
41235
|
+
function readJsonObject(path) {
|
|
41236
|
+
let text2;
|
|
41237
|
+
try {
|
|
41238
|
+
text2 = readFileSync8(path, "utf-8");
|
|
41239
|
+
} catch (error61) {
|
|
41240
|
+
if (error61?.code === "ENOENT")
|
|
41241
|
+
return { status: "absent" };
|
|
41242
|
+
return { status: "unreadable", kind: "file", reason: `cannot read ${path} (${redactedDiagnostic(messageOf(error61))})` };
|
|
41243
|
+
}
|
|
41244
|
+
try {
|
|
41245
|
+
const value = JSON.parse(text2);
|
|
41246
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
41247
|
+
return { status: "unreadable", kind: "content", reason: `${path} is not a JSON object` };
|
|
41248
|
+
}
|
|
41249
|
+
return { status: "verified", value };
|
|
41250
|
+
} catch (error61) {
|
|
41251
|
+
return { status: "unreadable", kind: "content", reason: `${path} is not valid JSON (${redactedDiagnostic(messageOf(error61))})` };
|
|
41252
|
+
}
|
|
41253
|
+
}
|
|
41254
|
+
function writeText(path, content) {
|
|
41255
|
+
const dir = dirname9(path);
|
|
41256
|
+
mkdirSync10(dir, { recursive: true });
|
|
41257
|
+
const temp = join22(dir, `.${basename9(path)}.${randomUUID5()}.tmp`);
|
|
41258
|
+
try {
|
|
41259
|
+
writeFileSync9(temp, content);
|
|
41260
|
+
if (existsSync13(path))
|
|
41261
|
+
chmodSync2(temp, statSync(path).mode & 4095);
|
|
41262
|
+
renameSync5(temp, path);
|
|
41263
|
+
} catch (error61) {
|
|
41264
|
+
try {
|
|
41265
|
+
if (existsSync13(temp))
|
|
41266
|
+
unlinkSync3(temp);
|
|
41267
|
+
} catch {}
|
|
41268
|
+
throw error61;
|
|
41269
|
+
}
|
|
41270
|
+
}
|
|
41271
|
+
function tomlString(value) {
|
|
41272
|
+
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
|
|
41273
|
+
}
|
|
41274
|
+
function tomlStringValue(raw) {
|
|
41275
|
+
return raw.replace(/\\"/g, '"').replace(/\\\\/g, "\\");
|
|
41276
|
+
}
|
|
41277
|
+
var TOML_HEADER_RE = /^\s*\[\[?[^\]]/;
|
|
41278
|
+
var KIMI_HOOK_HEADER_RE = /^\s*\[\[hooks\]\]\s*$/;
|
|
41279
|
+
function splitToml(text2) {
|
|
41280
|
+
const preamble = [];
|
|
41281
|
+
const chunks = [];
|
|
41282
|
+
let current2 = null;
|
|
41283
|
+
for (const line of text2.split(`
|
|
41284
|
+
`)) {
|
|
41285
|
+
if (TOML_HEADER_RE.test(line)) {
|
|
41286
|
+
if (current2)
|
|
41287
|
+
chunks.push(current2);
|
|
41288
|
+
current2 = { header: line.trim(), lines: [line] };
|
|
41289
|
+
} else if (current2) {
|
|
41290
|
+
current2.lines.push(line);
|
|
41291
|
+
} else {
|
|
41292
|
+
preamble.push(line);
|
|
41293
|
+
}
|
|
41294
|
+
}
|
|
41295
|
+
if (current2)
|
|
41296
|
+
chunks.push(current2);
|
|
41297
|
+
return { preamble, chunks };
|
|
41298
|
+
}
|
|
41299
|
+
function chunkCommand(chunk) {
|
|
41300
|
+
const text2 = chunk.lines.join(`
|
|
41301
|
+
`);
|
|
41302
|
+
const basic = text2.match(/^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/m);
|
|
41303
|
+
if (basic)
|
|
41304
|
+
return tomlStringValue(basic[1]);
|
|
41305
|
+
const literal2 = text2.match(/^\s*command\s*=\s*'([^']*)'/m);
|
|
41306
|
+
return literal2 ? literal2[1] : undefined;
|
|
41307
|
+
}
|
|
41308
|
+
function isKimiHookChunk(chunk) {
|
|
41309
|
+
return KIMI_HOOK_HEADER_RE.test(chunk.header);
|
|
41310
|
+
}
|
|
41311
|
+
function kimiRegistrations(text2) {
|
|
41312
|
+
const out = [];
|
|
41313
|
+
for (const chunk of splitToml(text2).chunks) {
|
|
41314
|
+
if (!isKimiHookChunk(chunk))
|
|
41315
|
+
continue;
|
|
41316
|
+
const command = chunkCommand(chunk);
|
|
41317
|
+
const hook = command ? hookFromCommand(command) : undefined;
|
|
41318
|
+
if (command && hook)
|
|
41319
|
+
out.push({ hook, command });
|
|
41320
|
+
}
|
|
41321
|
+
return out;
|
|
41322
|
+
}
|
|
41323
|
+
function kimiBlock(command, timeoutSeconds) {
|
|
41324
|
+
return [
|
|
41325
|
+
"[[hooks]]",
|
|
41326
|
+
'event = "Stop"',
|
|
41327
|
+
`command = ${tomlString(command)}`,
|
|
41328
|
+
`timeout = ${Math.max(1, Math.min(600, timeoutSeconds))}`
|
|
41329
|
+
].join(`
|
|
41330
|
+
`);
|
|
41331
|
+
}
|
|
41332
|
+
function removeKimiChunk(text2, hook) {
|
|
41333
|
+
const { preamble, chunks } = splitToml(text2);
|
|
41334
|
+
const kept = [...preamble];
|
|
41335
|
+
let removed = false;
|
|
41336
|
+
for (const chunk of chunks) {
|
|
41337
|
+
const command = isKimiHookChunk(chunk) ? chunkCommand(chunk) : undefined;
|
|
41338
|
+
if (command && hookFromCommand(command) === hook) {
|
|
41339
|
+
removed = true;
|
|
41340
|
+
while (kept.length > 0 && kept[kept.length - 1].trim() === "")
|
|
41341
|
+
kept.pop();
|
|
41342
|
+
continue;
|
|
41343
|
+
}
|
|
41344
|
+
if (TOML_HEADER_RE.test(chunk.header) && kept.length > 0 && kept[kept.length - 1].trim() !== "") {
|
|
41345
|
+
kept.push("");
|
|
41346
|
+
}
|
|
41347
|
+
kept.push(...chunk.lines);
|
|
41348
|
+
}
|
|
41349
|
+
return { text: kept.join(`
|
|
41350
|
+
`), removed };
|
|
41351
|
+
}
|
|
41352
|
+
function installKimi(hook, command, options, timeoutSeconds) {
|
|
41353
|
+
const path = adapterPath("kimi", options);
|
|
41354
|
+
const read3 = readTextState(path);
|
|
41355
|
+
if (read3.status === "unreadable") {
|
|
41356
|
+
return { ok: false, configPath: path, error: `Refused: ${read3.reason}, so Hooks wrote nothing. Repair the file or move it aside, then retry.` };
|
|
41357
|
+
}
|
|
41358
|
+
const existing = read3.status === "verified" ? read3.text : "";
|
|
41359
|
+
if (kimiRegistrations(existing).some((entry) => entry.hook === hook)) {
|
|
41360
|
+
return { ok: true, configPath: path, note: "already registered; nothing was written" };
|
|
41361
|
+
}
|
|
41362
|
+
const next = existing.trim() === "" ? `${kimiBlock(command, timeoutSeconds)}
|
|
41363
|
+
` : `${existing.trimEnd()}
|
|
41364
|
+
|
|
41365
|
+
${kimiBlock(command, timeoutSeconds)}
|
|
41366
|
+
`;
|
|
41367
|
+
const candidate = join22(tmpdir(), `hooks-kimi-config-${randomUUID5()}.toml`);
|
|
41368
|
+
writeFileSync9(candidate, next);
|
|
41369
|
+
let validationNote;
|
|
41370
|
+
try {
|
|
41371
|
+
const result = (options.run ?? defaultRunner)("kimi", ["doctor", "config", candidate]);
|
|
41372
|
+
if (result.notFound) {
|
|
41373
|
+
validationNote = "kimi is not installed here, so `kimi doctor config` did not validate the entry";
|
|
41374
|
+
} else if (result.status !== 0) {
|
|
41375
|
+
const detail = redactedDiagnostic(result.stderr) || redactedDiagnostic(result.stdout) || `exit ${result.status}`;
|
|
41376
|
+
return { ok: false, configPath: path, error: `Refused: \`kimi doctor config\` rejected the candidate config (${detail}). Nothing was written to ${path}.` };
|
|
41377
|
+
} else {
|
|
41378
|
+
validationNote = "validated with `kimi doctor config`";
|
|
41379
|
+
}
|
|
41380
|
+
} finally {
|
|
41381
|
+
try {
|
|
41382
|
+
if (existsSync13(candidate))
|
|
41383
|
+
unlinkSync3(candidate);
|
|
41384
|
+
} catch {}
|
|
41385
|
+
}
|
|
41386
|
+
writeText(path, next);
|
|
41387
|
+
return {
|
|
41388
|
+
ok: true,
|
|
41389
|
+
configPath: path,
|
|
41390
|
+
note: `Kimi blocks with exit 2 + stderr once per turn; ${validationNote}.`
|
|
41391
|
+
};
|
|
41392
|
+
}
|
|
41393
|
+
var PI_PREFERENCE_KEY = "hasna-pi-hooks";
|
|
41394
|
+
function piPointerPath(options) {
|
|
41395
|
+
return adapterPath("pi", options);
|
|
41396
|
+
}
|
|
41397
|
+
function readPiPointer(options) {
|
|
41398
|
+
return readJsonObject(piPointerPath(options));
|
|
41399
|
+
}
|
|
41400
|
+
function piProfile(options, pointer) {
|
|
41401
|
+
const state = pointer === undefined ? readPiPointer(options) : undefined;
|
|
41402
|
+
const config2 = pointer ?? (state?.status === "verified" ? state.value : undefined);
|
|
41403
|
+
if (typeof config2?.profile === "string") {
|
|
41404
|
+
const pointed = getProfile(config2.profile);
|
|
41405
|
+
if (pointed)
|
|
41406
|
+
return pointed;
|
|
41407
|
+
}
|
|
41408
|
+
return listProfiles().find((profile) => profile.agent_type === "custom" && profile.name === "pi");
|
|
41409
|
+
}
|
|
41410
|
+
function piCommands(profile) {
|
|
41411
|
+
const stored = profile?.preferences?.[PI_PREFERENCE_KEY];
|
|
41412
|
+
const hooks = stored?.hooks;
|
|
41413
|
+
return Array.isArray(hooks) ? hooks.filter((entry) => typeof entry === "string") : [];
|
|
41414
|
+
}
|
|
41415
|
+
function writePiCommands(profileId, commands) {
|
|
41416
|
+
const profile = getProfile(profileId);
|
|
41417
|
+
if (!profile)
|
|
41418
|
+
return;
|
|
41419
|
+
updateProfile(profileId, {
|
|
41420
|
+
preferences: {
|
|
41421
|
+
...profile.preferences,
|
|
41422
|
+
[PI_PREFERENCE_KEY]: { hooks: commands, updated_at: new Date().toISOString() }
|
|
41423
|
+
}
|
|
41424
|
+
});
|
|
41425
|
+
}
|
|
41426
|
+
function installPi(hook, command, options) {
|
|
41427
|
+
const path = piPointerPath(options);
|
|
41428
|
+
const pointerRead = readPiPointer(options);
|
|
41429
|
+
if (pointerRead.status === "unreadable") {
|
|
41430
|
+
return { ok: false, configPath: path, error: `Refused: ${pointerRead.reason}, so Hooks wrote nothing. Repair the file or move it aside, then retry.` };
|
|
41431
|
+
}
|
|
41432
|
+
const profile = piProfile(options) ?? createProfile({ agent_type: "custom", name: "pi" });
|
|
41433
|
+
const commands = piCommands(profile);
|
|
41434
|
+
if (commands.some((entry) => hookFromCommand(entry) === hook)) {
|
|
41435
|
+
return { ok: true, configPath: path, note: "already registered; nothing was written" };
|
|
41436
|
+
}
|
|
41437
|
+
const pointer = pointerRead.status === "verified" ? pointerRead.value : {};
|
|
41438
|
+
writeText(path, `${JSON.stringify({ ...pointer, profile: profile.agent_id }, null, 2)}
|
|
41439
|
+
`);
|
|
41440
|
+
writePiCommands(profile.agent_id, [...commands, command]);
|
|
41441
|
+
return {
|
|
41442
|
+
ok: true,
|
|
41443
|
+
configPath: path,
|
|
41444
|
+
note: `registered through Hooks profile ${profile.agent_id}, which the hasna-pi-hooks bridge reads`
|
|
41445
|
+
};
|
|
41446
|
+
}
|
|
41447
|
+
function readCursorFile(path) {
|
|
41448
|
+
return readJsonObject(path);
|
|
41449
|
+
}
|
|
41450
|
+
function cursorRegistrations(config2) {
|
|
41451
|
+
const out = [];
|
|
41452
|
+
const hooks = config2?.hooks;
|
|
41453
|
+
if (!hooks || typeof hooks !== "object")
|
|
41454
|
+
return out;
|
|
41455
|
+
for (const key2 of Object.keys(hooks)) {
|
|
41456
|
+
const entries = hooks[key2];
|
|
41457
|
+
if (!Array.isArray(entries))
|
|
41458
|
+
continue;
|
|
41459
|
+
for (const entry of entries) {
|
|
41460
|
+
const command = typeof entry?.command === "string" ? entry.command : undefined;
|
|
41461
|
+
const hook = command ? hookFromCommand(command) : undefined;
|
|
41462
|
+
if (command && hook)
|
|
41463
|
+
out.push({ hook, command });
|
|
41464
|
+
}
|
|
41465
|
+
}
|
|
41466
|
+
return out;
|
|
41467
|
+
}
|
|
41468
|
+
function installCursor(hook, command, options, timeoutSeconds) {
|
|
41469
|
+
const path = adapterPath("cursor", options);
|
|
41470
|
+
const read3 = readCursorFile(path);
|
|
41471
|
+
if (read3.status === "unreadable") {
|
|
41472
|
+
return {
|
|
41473
|
+
ok: false,
|
|
41474
|
+
configPath: path,
|
|
41475
|
+
error: read3.kind === "file" ? `Refused: ${read3.reason}, so Hooks wrote nothing. Repair the file or move it aside, then retry.` : `Refused: ${path} is not a JSON object, so Hooks wrote nothing. Repair the file or move it aside, then retry.`
|
|
41476
|
+
};
|
|
41477
|
+
}
|
|
41478
|
+
const config2 = read3.status === "verified" ? read3.value : undefined;
|
|
41479
|
+
if (cursorRegistrations(config2).some((entry) => entry.hook === hook)) {
|
|
41480
|
+
return { ok: true, configPath: path, note: "already registered; nothing was written" };
|
|
41481
|
+
}
|
|
41482
|
+
const next = config2 ?? {};
|
|
41483
|
+
const hooks = next.hooks && typeof next.hooks === "object" ? { ...next.hooks } : {};
|
|
41484
|
+
const stop = Array.isArray(hooks.stop) ? [...hooks.stop] : [];
|
|
41485
|
+
stop.push({ command, timeout: Math.max(1, Math.min(600, timeoutSeconds)) });
|
|
41486
|
+
hooks.stop = stop;
|
|
41487
|
+
writeText(path, `${JSON.stringify({ version: 1, ...next, hooks }, null, 2)}
|
|
41488
|
+
`);
|
|
41489
|
+
return { ok: true, configPath: path };
|
|
41490
|
+
}
|
|
41491
|
+
function splitArgv(command) {
|
|
41492
|
+
return command.trim().split(/\s+/).filter(Boolean);
|
|
41493
|
+
}
|
|
41494
|
+
function hookFromMuseCommand(command) {
|
|
41495
|
+
if (!Array.isArray(command))
|
|
41496
|
+
return;
|
|
41497
|
+
const joined = command.filter((part) => typeof part === "string").join(" ");
|
|
41498
|
+
const match = joined.match(/(?:^|\s)\S*hooks run ([\w-]+)(?:\s|$)/);
|
|
41499
|
+
return match?.[1];
|
|
41500
|
+
}
|
|
41501
|
+
function museManifest(hook, command, options, timeoutSeconds) {
|
|
41502
|
+
return {
|
|
41503
|
+
name: `hasna-hook-${hook}`,
|
|
41504
|
+
version: options.version ?? "0.0.0",
|
|
41505
|
+
description: options.description ?? `Hasna hook ${hook}`,
|
|
41506
|
+
schemaVersion: 1,
|
|
41507
|
+
compat: { source: "native", manifestDir: ".muse-plugin" },
|
|
41508
|
+
capabilities: {
|
|
41509
|
+
hooks: [{
|
|
41510
|
+
id: `hasna-${hook}-stop`,
|
|
41511
|
+
event: "Stop",
|
|
41512
|
+
command: splitArgv(command),
|
|
41513
|
+
timeoutMs: timeoutSeconds * 1000,
|
|
41514
|
+
statusMessage: `Running Hasna hook ${hook}`
|
|
41515
|
+
}]
|
|
41516
|
+
}
|
|
41517
|
+
};
|
|
41518
|
+
}
|
|
41519
|
+
function museDiagnostic(outcome) {
|
|
41520
|
+
try {
|
|
41521
|
+
const parsed = JSON.parse(outcome.stdout);
|
|
41522
|
+
const message = parsed?.error?.message;
|
|
41523
|
+
if (typeof message === "string" && message.trim()) {
|
|
41524
|
+
const code2 = parsed.error?.code === undefined ? "" : `${redactedCode(parsed.error.code)}: `;
|
|
41525
|
+
return `${code2}${redactedDiagnostic(message)}`;
|
|
41526
|
+
}
|
|
41527
|
+
} catch {}
|
|
41528
|
+
return redactedDiagnostic(outcome.stderr) || redactedDiagnostic(outcome.stdout) || `exit ${outcome.status}`;
|
|
41529
|
+
}
|
|
41530
|
+
function removeMuseBundle(bundle) {
|
|
41531
|
+
const manifestPath = join22(bundle, ".muse-plugin", "plugin.json");
|
|
41532
|
+
try {
|
|
41533
|
+
if (existsSync13(manifestPath))
|
|
41534
|
+
unlinkSync3(manifestPath);
|
|
41535
|
+
} catch {}
|
|
41536
|
+
for (const dir of [join22(bundle, ".muse-plugin"), bundle]) {
|
|
41537
|
+
try {
|
|
41538
|
+
if (existsSync13(dir))
|
|
41539
|
+
rmdirSync2(dir);
|
|
41540
|
+
} catch {}
|
|
41541
|
+
}
|
|
41542
|
+
}
|
|
41543
|
+
function museBundles(options) {
|
|
41544
|
+
const root = musePluginRoot({ home: homeOf(options), env: options.env ?? process.env });
|
|
41545
|
+
if (!existsSync13(root))
|
|
41546
|
+
return [];
|
|
41547
|
+
const out = [];
|
|
41548
|
+
for (const entry of readdirSync4(root)) {
|
|
41549
|
+
const manifestPath = join22(root, entry, ".muse-plugin", "plugin.json");
|
|
41550
|
+
if (!existsSync13(manifestPath))
|
|
41551
|
+
continue;
|
|
41552
|
+
try {
|
|
41553
|
+
const manifest = JSON.parse(readFileSync8(manifestPath, "utf-8"));
|
|
41554
|
+
for (const capability of manifest.capabilities?.hooks ?? []) {
|
|
41555
|
+
const command = Array.isArray(capability.command) ? capability.command.join(" ") : "";
|
|
41556
|
+
const hook = hookFromCommand(command) ?? hookFromMuseCommand(capability.command);
|
|
41557
|
+
if (hook)
|
|
41558
|
+
out.push({ hook, command });
|
|
41559
|
+
}
|
|
41560
|
+
} catch {}
|
|
41561
|
+
}
|
|
41562
|
+
return out;
|
|
41563
|
+
}
|
|
41564
|
+
function museOwnFiles(options) {
|
|
41565
|
+
const home = homeOf(options);
|
|
41566
|
+
const env = options.env ?? process.env;
|
|
41567
|
+
const configBase = env.XDG_CONFIG_HOME?.startsWith("/") ? env.XDG_CONFIG_HOME : join22(home, ".config");
|
|
41568
|
+
const dataBase = env.XDG_DATA_HOME?.startsWith("/") ? env.XDG_DATA_HOME : join22(home, ".local", "share");
|
|
41569
|
+
const searched = [join22(configBase, "muse", "settings.json"), join22(dataBase, "muse")];
|
|
41570
|
+
const found = searched.filter((path) => existsSync13(path));
|
|
41571
|
+
return { present: found.length > 0, found, searched };
|
|
41572
|
+
}
|
|
41573
|
+
function readMuseState(options, runner = options.run ?? defaultRunner) {
|
|
41574
|
+
const source = "`muse plugins list --json`";
|
|
41575
|
+
const bundleRoot = musePluginRoot({ home: homeOf(options), env: options.env ?? process.env });
|
|
41576
|
+
const unverified = (reason2) => ({ status: "unverified", registrations: [], inactive: [], source, reason: reason2 });
|
|
41577
|
+
const result = runner("muse", ["plugins", "list", "--json"]);
|
|
41578
|
+
if (result.notFound) {
|
|
41579
|
+
const muse = museOwnFiles(options);
|
|
41580
|
+
if (muse.present) {
|
|
41581
|
+
return unverified(`Muse's own store is here (${muse.found.join(", ")}), but the \`muse\` command is not on PATH, so ${source} cannot say what Muse carries \u2014 ` + `a plugin Muse registered may still run, and a bundle under ${bundleRoot} is a file Hooks wrote, not proof either way`);
|
|
41582
|
+
}
|
|
41583
|
+
return {
|
|
41584
|
+
...unverified(`Muse is not installed here: neither its store (${muse.searched.join(" or ")}) nor the \`muse\` command exists, so it carries no registration`),
|
|
41585
|
+
absent: true
|
|
41586
|
+
};
|
|
41587
|
+
}
|
|
41588
|
+
if (result.status !== 0) {
|
|
41589
|
+
return unverified(`${source} failed (${museDiagnostic(result)})`);
|
|
41590
|
+
}
|
|
41591
|
+
let parsed;
|
|
41592
|
+
try {
|
|
41593
|
+
parsed = JSON.parse(result.stdout);
|
|
41594
|
+
} catch {
|
|
41595
|
+
return unverified(`${source} did not return JSON`);
|
|
41596
|
+
}
|
|
41597
|
+
const entries = parsed?.plugins;
|
|
41598
|
+
if (!Array.isArray(entries))
|
|
41599
|
+
return unverified(`${source} returned no plugin list`);
|
|
41600
|
+
const registrations = [];
|
|
41601
|
+
const inactive = [];
|
|
41602
|
+
for (const entry of entries) {
|
|
41603
|
+
const hooks = entry?.plugin?.capabilities?.hooks;
|
|
41604
|
+
if (!Array.isArray(hooks))
|
|
41605
|
+
continue;
|
|
41606
|
+
const enabled = entry?.record?.enabled === true;
|
|
41607
|
+
for (const capability of hooks) {
|
|
41608
|
+
const command = Array.isArray(capability?.command) ? capability.command.filter((part) => typeof part === "string").join(" ") : "";
|
|
41609
|
+
const hook = hookFromMuseCommand(capability?.command);
|
|
41610
|
+
if (!hook)
|
|
41611
|
+
continue;
|
|
41612
|
+
if (enabled) {
|
|
41613
|
+
registrations.push({ hook, command });
|
|
41614
|
+
} else if (!inactive.includes(hook)) {
|
|
41615
|
+
inactive.push(hook);
|
|
41616
|
+
}
|
|
41617
|
+
}
|
|
41618
|
+
}
|
|
41619
|
+
return { status: "verified", registrations, inactive, source };
|
|
41620
|
+
}
|
|
41621
|
+
function installMuse(hook, command, options, timeoutSeconds) {
|
|
41622
|
+
const runner = options.run ?? defaultRunner;
|
|
41623
|
+
const bundle = adapterPath("muse", options, hook);
|
|
41624
|
+
const manifestPath = join22(bundle, ".muse-plugin", "plugin.json");
|
|
41625
|
+
const existedBefore = existsSync13(manifestPath);
|
|
41626
|
+
const manifest = museManifest(hook, command, options, timeoutSeconds);
|
|
41627
|
+
writeText(manifestPath, `${JSON.stringify(manifest, null, 2)}
|
|
41628
|
+
`);
|
|
41629
|
+
const installCommand = `muse plugins install ${bundle} --scope user`;
|
|
41630
|
+
const approveCommand = `muse plugins approve ${manifest.name}`;
|
|
41631
|
+
const cleanup = () => {
|
|
41632
|
+
if (!existedBefore)
|
|
41633
|
+
removeMuseBundle(bundle);
|
|
41634
|
+
};
|
|
41635
|
+
const left = existedBefore ? ` The existing bundle at ${bundle} was left as it was.` : " The bundle was removed again, so nothing is left half-written.";
|
|
41636
|
+
const validated = runner("muse", ["plugins", "validate", bundle, "--json"]);
|
|
41637
|
+
if (validated.notFound) {
|
|
41638
|
+
cleanup();
|
|
41639
|
+
const muse = museOwnFiles(options);
|
|
41640
|
+
return {
|
|
41641
|
+
ok: false,
|
|
41642
|
+
configPath: bundle,
|
|
41643
|
+
error: muse.present ? `Refused: Muse's own store is here (${muse.found.join(", ")}), but the \`muse\` command is not on PATH, so \`muse plugins validate\` could not check the bundle.${left} Run it where the Muse command is available: \`${installCommand}\` then \`${approveCommand}\`.` : `Refused: Muse is not installed here, so \`muse plugins validate\` could not check the bundle.${left} On a station with Muse run \`${installCommand}\` then \`${approveCommand}\`.`
|
|
41644
|
+
};
|
|
41645
|
+
}
|
|
41646
|
+
if (validated.status !== 0) {
|
|
41647
|
+
cleanup();
|
|
41648
|
+
return {
|
|
41649
|
+
ok: false,
|
|
41650
|
+
configPath: bundle,
|
|
41651
|
+
error: `Refused: Muse rejected the plugin manifest (${museDiagnostic(validated)}).${left} Nothing was registered.`
|
|
41652
|
+
};
|
|
41653
|
+
}
|
|
41654
|
+
const installed = runner("muse", ["plugins", "install", bundle, "--scope", "user"]);
|
|
41655
|
+
if (installed.notFound) {
|
|
41656
|
+
cleanup();
|
|
41657
|
+
return {
|
|
41658
|
+
ok: false,
|
|
41659
|
+
configPath: bundle,
|
|
41660
|
+
error: `Refused: Muse disappeared between validation and install, so the plugin was not registered.${left} On a station with Muse run \`${installCommand}\` then \`${approveCommand}\`.`
|
|
41661
|
+
};
|
|
41662
|
+
}
|
|
41663
|
+
if (installed.status !== 0) {
|
|
41664
|
+
cleanup();
|
|
41665
|
+
return {
|
|
41666
|
+
ok: false,
|
|
41667
|
+
configPath: bundle,
|
|
41668
|
+
error: `Refused: \`${installCommand}\` failed (${museDiagnostic(installed)}).${left}`
|
|
41669
|
+
};
|
|
41670
|
+
}
|
|
41671
|
+
const approved = runner("muse", ["plugins", "approve", manifest.name]);
|
|
41672
|
+
if (approved.status !== 0) {
|
|
41673
|
+
const detail = museDiagnostic(approved);
|
|
41674
|
+
return {
|
|
41675
|
+
ok: false,
|
|
41676
|
+
configPath: bundle,
|
|
41677
|
+
error: `Refused: the plugin installed but Muse did not approve it (${detail}); an unapproved plugin does not run. Run \`${approveCommand}\` and retry.`
|
|
41678
|
+
};
|
|
41679
|
+
}
|
|
41680
|
+
return { ok: true, configPath: bundle, note: `installed at user scope and approved as ${manifest.name}` };
|
|
41681
|
+
}
|
|
41682
|
+
function readTextState(path) {
|
|
41683
|
+
try {
|
|
41684
|
+
return { status: "verified", text: readFileSync8(path, "utf-8") };
|
|
41685
|
+
} catch (error61) {
|
|
41686
|
+
if (error61?.code === "ENOENT")
|
|
41687
|
+
return { status: "absent" };
|
|
41688
|
+
return { status: "unreadable", reason: `cannot read ${path} (${redactedDiagnostic(messageOf(error61))})` };
|
|
41689
|
+
}
|
|
41690
|
+
}
|
|
41691
|
+
function readKimiState(options) {
|
|
41692
|
+
const read3 = readTextState(adapterPath("kimi", options));
|
|
41693
|
+
if (read3.status === "unreadable")
|
|
41694
|
+
return { status: "unverified", registrations: [], reason: read3.reason };
|
|
41695
|
+
if (read3.status === "absent")
|
|
41696
|
+
return { status: "verified", registrations: [] };
|
|
41697
|
+
return { status: "verified", registrations: kimiRegistrations(read3.text) };
|
|
41698
|
+
}
|
|
41699
|
+
function readPiState(options) {
|
|
41700
|
+
const read3 = readPiPointer(options);
|
|
41701
|
+
if (read3.status === "unreadable")
|
|
41702
|
+
return { status: "unverified", registrations: [], reason: read3.reason };
|
|
41703
|
+
const profile = piProfile(options, read3.status === "verified" ? read3.value : {});
|
|
41704
|
+
const registrations = piCommands(profile).flatMap((command) => {
|
|
41705
|
+
const hook = hookFromCommand(command);
|
|
41706
|
+
return hook ? [{ hook, command }] : [];
|
|
41707
|
+
});
|
|
41708
|
+
return { status: "verified", registrations };
|
|
41709
|
+
}
|
|
41710
|
+
function readCursorState(options) {
|
|
41711
|
+
const read3 = readCursorFile(adapterPath("cursor", options));
|
|
41712
|
+
if (read3.status === "unreadable")
|
|
41713
|
+
return { status: "unverified", registrations: [], reason: read3.reason };
|
|
41714
|
+
if (read3.status === "absent")
|
|
41715
|
+
return { status: "verified", registrations: [] };
|
|
41716
|
+
return { status: "verified", registrations: cursorRegistrations(read3.value) };
|
|
41717
|
+
}
|
|
41718
|
+
function readAdapterState(target, options, runner) {
|
|
41719
|
+
try {
|
|
41720
|
+
if (target === "kimi")
|
|
41721
|
+
return readKimiState(options);
|
|
41722
|
+
if (target === "pi")
|
|
41723
|
+
return readPiState(options);
|
|
41724
|
+
if (target === "cursor")
|
|
41725
|
+
return readCursorState(options);
|
|
41726
|
+
return readMuseState(options, runner ?? options.run ?? defaultRunner);
|
|
41727
|
+
} catch (error61) {
|
|
41728
|
+
return {
|
|
41729
|
+
status: "unverified",
|
|
41730
|
+
registrations: [],
|
|
41731
|
+
reason: `${target}: cannot read its registration state (${redactedDiagnostic(messageOf(error61))})`
|
|
41732
|
+
};
|
|
41733
|
+
}
|
|
41734
|
+
}
|
|
41735
|
+
function readAdapterRegistrations(target, options) {
|
|
41736
|
+
if (target === "muse") {
|
|
41737
|
+
try {
|
|
41738
|
+
return museBundles(options);
|
|
41739
|
+
} catch {
|
|
41740
|
+
return [];
|
|
41741
|
+
}
|
|
41742
|
+
}
|
|
41743
|
+
return readAdapterState(target, options).registrations;
|
|
41744
|
+
}
|
|
41745
|
+
function adapterStateCarries(state, hook) {
|
|
41746
|
+
if (state.registrations.some((entry) => entry.hook === hook))
|
|
41747
|
+
return true;
|
|
41748
|
+
const inactive = state.inactive;
|
|
41749
|
+
return Array.isArray(inactive) && inactive.includes(hook);
|
|
41750
|
+
}
|
|
41751
|
+
function installInAdapter(target, hook, command, options, timeoutSeconds = 10) {
|
|
41752
|
+
try {
|
|
41753
|
+
if (target === "kimi")
|
|
41754
|
+
return installKimi(hook, command, options, timeoutSeconds);
|
|
41755
|
+
if (target === "pi")
|
|
41756
|
+
return installPi(hook, command, options);
|
|
41757
|
+
if (target === "cursor")
|
|
41758
|
+
return installCursor(hook, command, options, timeoutSeconds);
|
|
41759
|
+
return installMuse(hook, command, options, timeoutSeconds);
|
|
41760
|
+
} catch (error61) {
|
|
41761
|
+
return { ok: false, configPath: "", error: `Refused: ${target}: the install did not complete (${redactedDiagnostic(messageOf(error61))})` };
|
|
41762
|
+
}
|
|
41763
|
+
}
|
|
41764
|
+
function removeFromAdapter(target, hook, options) {
|
|
41765
|
+
try {
|
|
41766
|
+
if (target === "kimi") {
|
|
41767
|
+
const path = adapterPath("kimi", options);
|
|
41768
|
+
const existing = readTextState(path);
|
|
41769
|
+
if (existing.status === "unreadable") {
|
|
41770
|
+
return { removed: false, reason: `${existing.reason}, so Hooks cannot tell whether '${hook}' is registered; nothing was removed` };
|
|
41771
|
+
}
|
|
41772
|
+
const { text: text2, removed } = removeKimiChunk(existing.status === "verified" ? existing.text : "", hook);
|
|
41773
|
+
if (!removed)
|
|
41774
|
+
return { removed: false, reason: `no '${hook}' entry in ${path}` };
|
|
41775
|
+
writeText(path, text2.endsWith(`
|
|
41776
|
+
`) ? text2 : `${text2}
|
|
41777
|
+
`);
|
|
41778
|
+
return { removed: true };
|
|
41779
|
+
}
|
|
41780
|
+
if (target === "pi") {
|
|
41781
|
+
const pointer = readPiPointer(options);
|
|
41782
|
+
if (pointer.status === "unreadable") {
|
|
41783
|
+
return { removed: false, reason: `${pointer.reason}, so Hooks cannot tell whether '${hook}' is registered; nothing was removed` };
|
|
41784
|
+
}
|
|
41785
|
+
const profile = piProfile(options);
|
|
41786
|
+
if (!profile)
|
|
41787
|
+
return { removed: false, reason: `no Hooks profile is registered for Pi; nothing to remove` };
|
|
41788
|
+
const commands = piCommands(profile);
|
|
41789
|
+
const kept = commands.filter((command) => hookFromCommand(command) !== hook);
|
|
41790
|
+
if (kept.length === commands.length)
|
|
41791
|
+
return { removed: false, reason: `no '${hook}' entry in profile ${profile.agent_id}` };
|
|
41792
|
+
writePiCommands(profile.agent_id, kept);
|
|
41793
|
+
return { removed: true };
|
|
41794
|
+
}
|
|
41795
|
+
if (target === "cursor") {
|
|
41796
|
+
const path = adapterPath("cursor", options);
|
|
41797
|
+
const read3 = readCursorFile(path);
|
|
41798
|
+
if (read3.status === "unreadable") {
|
|
41799
|
+
return { removed: false, reason: `${read3.reason}, so Hooks cannot tell whether '${hook}' is registered; nothing was removed` };
|
|
41800
|
+
}
|
|
41801
|
+
const config2 = read3.status === "verified" ? read3.value : undefined;
|
|
41802
|
+
if (!config2?.hooks)
|
|
41803
|
+
return { removed: false, reason: `no '${hook}' entry in ${path}` };
|
|
41804
|
+
let removed = false;
|
|
41805
|
+
const hooks = {};
|
|
41806
|
+
for (const key2 of Object.keys(config2.hooks)) {
|
|
41807
|
+
const entries = config2.hooks[key2];
|
|
41808
|
+
if (!Array.isArray(entries)) {
|
|
41809
|
+
hooks[key2] = entries;
|
|
41810
|
+
continue;
|
|
41811
|
+
}
|
|
41812
|
+
const kept = entries.filter((entry) => {
|
|
41813
|
+
if (typeof entry?.command !== "string" || hookFromCommand(entry.command) !== hook)
|
|
41814
|
+
return true;
|
|
41815
|
+
removed = true;
|
|
41816
|
+
return false;
|
|
41817
|
+
});
|
|
41818
|
+
if (kept.length > 0)
|
|
41819
|
+
hooks[key2] = kept;
|
|
41820
|
+
}
|
|
41821
|
+
if (!removed)
|
|
41822
|
+
return { removed: false, reason: `no '${hook}' entry in ${path}` };
|
|
41823
|
+
const next = { ...config2, hooks };
|
|
41824
|
+
if (Object.keys(hooks).length === 0)
|
|
41825
|
+
delete next.hooks;
|
|
41826
|
+
writeText(path, `${JSON.stringify(next, null, 2)}
|
|
41827
|
+
`);
|
|
41828
|
+
return { removed: true };
|
|
41829
|
+
}
|
|
41830
|
+
const bundle = adapterPath("muse", options, hook);
|
|
41831
|
+
const manifestPath = join22(bundle, ".muse-plugin", "plugin.json");
|
|
41832
|
+
const hadBundle = existsSync13(manifestPath);
|
|
41833
|
+
const bundleNote = hadBundle ? `the bundle at ${bundle} was left in place` : `no bundle was present at ${bundle}`;
|
|
41834
|
+
const pluginId2 = `hasna-hook-${hook}`;
|
|
41835
|
+
const result = (options.run ?? defaultRunner)("muse", ["plugins", "remove", pluginId2, "--json"]);
|
|
41836
|
+
if (result.notFound) {
|
|
41837
|
+
const muse = museOwnFiles(options);
|
|
41838
|
+
return {
|
|
41839
|
+
removed: false,
|
|
41840
|
+
reason: muse.present ? `Refused: Muse's own store is here (${muse.found.join(", ")}), but the \`muse\` command is not on PATH, so '${hook}' cannot be unregistered from it and may still run; ${bundleNote}. Run \`muse plugins remove ${pluginId2}\` where the Muse command is available.` : `Refused: Muse is not installed here, so '${hook}' cannot be unregistered from Muse's own store; ${bundleNote}. Run \`muse plugins remove ${pluginId2}\` on a station with Muse.`
|
|
41841
|
+
};
|
|
41842
|
+
}
|
|
41843
|
+
const refusal3 = result.status === 0 ? undefined : museDiagnostic(result);
|
|
41844
|
+
const alreadyGone = refusal3 !== undefined && /unknown-plugin|not installed/i.test(refusal3);
|
|
41845
|
+
if (refusal3 !== undefined && !alreadyGone) {
|
|
41846
|
+
return {
|
|
41847
|
+
removed: false,
|
|
41848
|
+
reason: `Refused: \`muse plugins remove ${pluginId2}\` failed (${refusal3}); ${bundleNote}.`
|
|
41849
|
+
};
|
|
41850
|
+
}
|
|
41851
|
+
removeMuseBundle(bundle);
|
|
41852
|
+
return {
|
|
41853
|
+
removed: true,
|
|
41854
|
+
bundleRemoved: hadBundle,
|
|
41855
|
+
reason: alreadyGone ? `Muse did not carry ${pluginId2}; ${hadBundle ? `the bundle at ${bundle} was removed` : `no bundle was present at ${bundle}`}` : hadBundle ? `unregistered ${pluginId2} from Muse and removed ${bundle}` : `unregistered ${pluginId2} from Muse; no bundle was present at ${bundle}`
|
|
41856
|
+
};
|
|
41857
|
+
} catch (error61) {
|
|
41858
|
+
return { removed: false, reason: `${target}: the removal failed (${redactedDiagnostic(messageOf(error61))}); nothing was removed` };
|
|
41859
|
+
}
|
|
41165
41860
|
}
|
|
41166
41861
|
|
|
41167
41862
|
// src/lib/installer.ts
|
|
41168
|
-
var __dirname2 =
|
|
41169
|
-
var HOOKS_DIR =
|
|
41863
|
+
var __dirname2 = dirname16(fileURLToPath3(import.meta.url));
|
|
41864
|
+
var HOOKS_DIR = existsSync14(join24(__dirname2, "..", "..", "hooks", "hook-gitguard")) ? join24(__dirname2, "..", "..", "hooks") : join24(__dirname2, "..", "hooks");
|
|
41170
41865
|
function normalizeHookName(name) {
|
|
41171
41866
|
return name.startsWith("hook-") ? name : `hook-${name}`;
|
|
41172
41867
|
}
|
|
@@ -41183,17 +41878,19 @@ function removeHookEntriesByName(entries, hookName) {
|
|
|
41183
41878
|
return kept.length === entry.hooks.length ? [entry] : kept.length ? [{ ...entry, hooks: kept }] : [];
|
|
41184
41879
|
});
|
|
41185
41880
|
}
|
|
41881
|
+
var CLAUDE_EVENT_MAP = {
|
|
41882
|
+
PreToolUse: "PreToolUse",
|
|
41883
|
+
PostToolUse: "PostToolUse",
|
|
41884
|
+
Stop: "Stop",
|
|
41885
|
+
Notification: "Notification",
|
|
41886
|
+
SessionStart: "SessionStart",
|
|
41887
|
+
SessionEnd: "SessionEnd",
|
|
41888
|
+
UserPromptSubmit: "UserPromptSubmit",
|
|
41889
|
+
SubagentStart: null
|
|
41890
|
+
};
|
|
41186
41891
|
var EVENT_MAP = {
|
|
41187
|
-
claude:
|
|
41188
|
-
|
|
41189
|
-
PostToolUse: "PostToolUse",
|
|
41190
|
-
Stop: "Stop",
|
|
41191
|
-
Notification: "Notification",
|
|
41192
|
-
SessionStart: "SessionStart",
|
|
41193
|
-
SessionEnd: "SessionEnd",
|
|
41194
|
-
UserPromptSubmit: "UserPromptSubmit",
|
|
41195
|
-
SubagentStart: null
|
|
41196
|
-
},
|
|
41892
|
+
claude: CLAUDE_EVENT_MAP,
|
|
41893
|
+
qwen: CLAUDE_EVENT_MAP,
|
|
41197
41894
|
gemini: {
|
|
41198
41895
|
PreToolUse: "BeforeTool",
|
|
41199
41896
|
PostToolUse: "AfterTool",
|
|
@@ -41225,15 +41922,6 @@ var EVENT_MAP = {
|
|
|
41225
41922
|
SubagentStart: "SubagentStart"
|
|
41226
41923
|
}
|
|
41227
41924
|
};
|
|
41228
|
-
function getTargetSettingsDir(target) {
|
|
41229
|
-
if (target === "codex")
|
|
41230
|
-
return ".codex";
|
|
41231
|
-
if (target === "codewith")
|
|
41232
|
-
return ".codewith";
|
|
41233
|
-
if (target === "gemini")
|
|
41234
|
-
return ".gemini";
|
|
41235
|
-
return ".claude";
|
|
41236
|
-
}
|
|
41237
41925
|
function getGlobalSettingsPathOverride(target) {
|
|
41238
41926
|
if (target === "codex")
|
|
41239
41927
|
return process.env.HASNA_HOOKS_CODEX_SETTINGS_PATH ?? (process.env.CODEX_HOME ? resolve28(process.env.CODEX_HOME, "hooks.json") : undefined);
|
|
@@ -41241,34 +41929,38 @@ function getGlobalSettingsPathOverride(target) {
|
|
|
41241
41929
|
return process.env.HASNA_HOOKS_CLAUDE_SETTINGS_PATH ?? (process.env.CLAUDE_CONFIG_DIR ? resolve28(process.env.CLAUDE_CONFIG_DIR, "settings.json") : undefined);
|
|
41242
41930
|
if (target === "gemini")
|
|
41243
41931
|
return process.env.HASNA_HOOKS_GEMINI_SETTINGS_PATH;
|
|
41932
|
+
if (target === "qwen")
|
|
41933
|
+
return process.env.HASNA_HOOKS_QWEN_SETTINGS_PATH;
|
|
41934
|
+
if (target === "codewith")
|
|
41935
|
+
return process.env.HASNA_HOOKS_CODEWITH_CONFIG_PATH;
|
|
41244
41936
|
return;
|
|
41245
41937
|
}
|
|
41938
|
+
function capabilityOptions(scope, hook) {
|
|
41939
|
+
return { scope, home: homedir8(), cwd: process.cwd(), env: process.env, ...hook ? { hook } : {} };
|
|
41940
|
+
}
|
|
41941
|
+
function adapterOptions(scope, home, run) {
|
|
41942
|
+
return { scope, home: home ?? process.env.HOME ?? homedir8(), cwd: process.cwd(), env: process.env, ...run ? { run } : {} };
|
|
41943
|
+
}
|
|
41246
41944
|
function getSettingsPath(scope = "global", target = "claude", codewithConfigPath) {
|
|
41247
41945
|
if (target === "codewith" && codewithConfigPath)
|
|
41248
41946
|
return codewithConfigPath;
|
|
41249
|
-
if (target === "codewith" && scope === "global" && process.env.HASNA_HOOKS_CODEWITH_CONFIG_PATH) {
|
|
41250
|
-
return process.env.HASNA_HOOKS_CODEWITH_CONFIG_PATH;
|
|
41251
|
-
}
|
|
41252
41947
|
const globalOverride = scope === "global" ? getGlobalSettingsPathOverride(target) : undefined;
|
|
41253
41948
|
if (globalOverride)
|
|
41254
41949
|
return globalOverride;
|
|
41255
|
-
const
|
|
41256
|
-
if (
|
|
41257
|
-
return
|
|
41258
|
-
|
|
41259
|
-
return target === "codewith" ? join17(process.cwd(), dir, "config.toml") : join17(process.cwd(), dir, "settings.json");
|
|
41260
|
-
}
|
|
41261
|
-
return target === "codewith" ? join17(homedir7(), dir, "config.toml") : join17(homedir7(), dir, "settings.json");
|
|
41950
|
+
const capabilities = getTargetCapabilities(target, capabilityOptions(scope));
|
|
41951
|
+
if (capabilities)
|
|
41952
|
+
return capabilities.configPath;
|
|
41953
|
+
return join24(homedir8(), ".claude", "settings.json");
|
|
41262
41954
|
}
|
|
41263
41955
|
function getHookPath(name) {
|
|
41264
41956
|
const shortName = shortHookName(name);
|
|
41265
41957
|
const resolved = resolveHookDir(shortName);
|
|
41266
41958
|
if (resolved)
|
|
41267
41959
|
return resolved;
|
|
41268
|
-
return
|
|
41960
|
+
return join24(HOOKS_DIR, normalizeHookName(shortName));
|
|
41269
41961
|
}
|
|
41270
41962
|
function hookExists(name) {
|
|
41271
|
-
return
|
|
41963
|
+
return existsSync14(getHookPath(name));
|
|
41272
41964
|
}
|
|
41273
41965
|
var settingsPreimages = new WeakMap;
|
|
41274
41966
|
var unreadableSettings = new WeakMap;
|
|
@@ -41278,14 +41970,14 @@ function readSettings(scope = "global", target = "claude") {
|
|
|
41278
41970
|
return readCodexSettings(path);
|
|
41279
41971
|
let reason2 = "cannot be read";
|
|
41280
41972
|
try {
|
|
41281
|
-
if (
|
|
41282
|
-
const
|
|
41973
|
+
if (existsSync14(path)) {
|
|
41974
|
+
const text2 = readFileSync13(path, "utf-8");
|
|
41283
41975
|
reason2 = "is not valid JSON";
|
|
41284
|
-
const value = JSON.parse(
|
|
41976
|
+
const value = JSON.parse(text2);
|
|
41285
41977
|
reason2 = "does not hold a JSON object";
|
|
41286
41978
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
41287
41979
|
throw new TypeError(reason2);
|
|
41288
|
-
settingsPreimages.set(value, { path, text:
|
|
41980
|
+
settingsPreimages.set(value, { path, text: text2 });
|
|
41289
41981
|
return value;
|
|
41290
41982
|
}
|
|
41291
41983
|
} catch (error61) {
|
|
@@ -41295,7 +41987,7 @@ function readSettings(scope = "global", target = "claude") {
|
|
|
41295
41987
|
console.warn("[hooks] Cannot read hook settings; repair the selected file before installation.");
|
|
41296
41988
|
}
|
|
41297
41989
|
const empty = {};
|
|
41298
|
-
if (!
|
|
41990
|
+
if (!existsSync14(path))
|
|
41299
41991
|
settingsPreimages.set(empty, { path, text: null });
|
|
41300
41992
|
else
|
|
41301
41993
|
unreadableSettings.set(empty, { path, reason: reason2 });
|
|
@@ -41303,19 +41995,19 @@ function readSettings(scope = "global", target = "claude") {
|
|
|
41303
41995
|
}
|
|
41304
41996
|
function unreadableSettingsRefusal(settings, path) {
|
|
41305
41997
|
const captured = settingsPreimages.get(settings);
|
|
41306
|
-
if (captured?.path === path && captured.text !== null || !
|
|
41998
|
+
if (captured?.path === path && captured.text !== null || !existsSync14(path))
|
|
41307
41999
|
return;
|
|
41308
42000
|
const failed = unreadableSettings.get(settings);
|
|
41309
42001
|
const reason2 = captured?.path === path ? "was created after Hooks read the settings" : failed?.path === path ? failed.reason : "was not read as a settings object";
|
|
41310
42002
|
return new ClaudeSettingsRefusal("settings_unreadable", `${path} ${reason2}, so Hooks wrote nothing. Repair the file or move it aside, then retry.`);
|
|
41311
42003
|
}
|
|
41312
42004
|
function settingsIdentity(path) {
|
|
41313
|
-
if (
|
|
42005
|
+
if (existsSync14(path))
|
|
41314
42006
|
return realpathSync4(path);
|
|
41315
|
-
return
|
|
42007
|
+
return existsSync14(dirname16(path)) ? join24(realpathSync4(dirname16(path)), basename12(path)) : resolve28(path);
|
|
41316
42008
|
}
|
|
41317
42009
|
function coordinatesWithSkills(path, target) {
|
|
41318
|
-
return target === "claude" && settingsIdentity(path) === settingsIdentity(
|
|
42010
|
+
return target === "claude" && settingsIdentity(path) === settingsIdentity(join24(homedir8(), ".claude/settings.json"));
|
|
41319
42011
|
}
|
|
41320
42012
|
function writerRefusal(error61) {
|
|
41321
42013
|
return { error: error61 instanceof Error ? error61.message : "Unknown error", ...error61 instanceof ClaudeSettingsRefusal ? { code: error61.code } : {} };
|
|
@@ -41337,21 +42029,21 @@ function writeSettings(settings, scope = "global", target = "claude", expectedSe
|
|
|
41337
42029
|
const before = settingsPreimages.get(settings);
|
|
41338
42030
|
if (!before || before.path !== path)
|
|
41339
42031
|
throw new Error("Claude settings require a valid captured preimage before installation.");
|
|
41340
|
-
const current2 =
|
|
42032
|
+
const current2 = existsSync14(path) ? readFileSync13(path, "utf8") : null;
|
|
41341
42033
|
if (current2 !== before.text)
|
|
41342
42034
|
throw new Error("Claude settings changed during installation; no settings were written.");
|
|
41343
42035
|
if (coordinateClaudeSettings(before.text, JSON.stringify(settings, null, 2) + `
|
|
41344
|
-
`, { home:
|
|
42036
|
+
`, { home: homedir8() }, beforeWrite))
|
|
41345
42037
|
return;
|
|
41346
42038
|
}
|
|
41347
42039
|
if (expectedSettingsSha256 !== undefined)
|
|
41348
42040
|
return writeHookSettingsPreimage(path, settings, captured.text, beforeWrite);
|
|
41349
42041
|
beforeWrite?.();
|
|
41350
|
-
const dir =
|
|
41351
|
-
if (!
|
|
41352
|
-
|
|
42042
|
+
const dir = dirname16(path);
|
|
42043
|
+
if (!existsSync14(dir)) {
|
|
42044
|
+
mkdirSync12(dir, { recursive: true });
|
|
41353
42045
|
}
|
|
41354
|
-
|
|
42046
|
+
writeFileSync10(path, JSON.stringify(settings, null, 2) + `
|
|
41355
42047
|
`);
|
|
41356
42048
|
}
|
|
41357
42049
|
function getTargetEventName(internalEvent, target) {
|
|
@@ -41360,7 +42052,7 @@ function getTargetEventName(internalEvent, target) {
|
|
|
41360
42052
|
function isEventSupported(internalEvent, target) {
|
|
41361
42053
|
return getTargetEventName(internalEvent, target) !== null;
|
|
41362
42054
|
}
|
|
41363
|
-
function
|
|
42055
|
+
function tomlString2(value) {
|
|
41364
42056
|
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
|
|
41365
42057
|
}
|
|
41366
42058
|
function codewithMatcher(matcher) {
|
|
@@ -41434,8 +42126,8 @@ function buildCodewithTomlFragment(name, profile, mementos) {
|
|
|
41434
42126
|
`[[hooks.${eventKey}]]`
|
|
41435
42127
|
];
|
|
41436
42128
|
if (matcher)
|
|
41437
|
-
lines.push(`matcher = ${
|
|
41438
|
-
lines.push("", `[[hooks.${eventKey}.hooks]]`, `type = "command"`, `command = ${
|
|
42129
|
+
lines.push(`matcher = ${tomlString2(matcher)}`);
|
|
42130
|
+
lines.push("", `[[hooks.${eventKey}.hooks]]`, `type = "command"`, `command = ${tomlString2(command)}`, `timeout = ${codewithTimeout(shortName)}`, `statusMessage = ${tomlString2(codewithStatusMessage(shortName))}`);
|
|
41439
42131
|
fragments.push(lines.join(`
|
|
41440
42132
|
`));
|
|
41441
42133
|
}
|
|
@@ -41447,21 +42139,21 @@ function buildCodewithTomlFragment(name, profile, mementos) {
|
|
|
41447
42139
|
function readCodewithConfig(scope, configPath) {
|
|
41448
42140
|
const path = getSettingsPath(scope, "codewith", configPath);
|
|
41449
42141
|
try {
|
|
41450
|
-
return
|
|
42142
|
+
return existsSync14(path) ? readFileSync13(path, "utf-8") : "";
|
|
41451
42143
|
} catch {
|
|
41452
42144
|
return "";
|
|
41453
42145
|
}
|
|
41454
42146
|
}
|
|
41455
42147
|
function appendCodewithFragment(fragment, scope, configPath) {
|
|
41456
42148
|
const path = getSettingsPath(scope, "codewith", configPath);
|
|
41457
|
-
const dir =
|
|
41458
|
-
if (!
|
|
41459
|
-
|
|
41460
|
-
const existing =
|
|
42149
|
+
const dir = dirname16(path);
|
|
42150
|
+
if (!existsSync14(dir))
|
|
42151
|
+
mkdirSync12(dir, { recursive: true });
|
|
42152
|
+
const existing = existsSync14(path) ? readFileSync13(path, "utf-8") : "";
|
|
41461
42153
|
const sep10 = existing.trim() ? `
|
|
41462
42154
|
|
|
41463
42155
|
` : "";
|
|
41464
|
-
|
|
42156
|
+
writeFileSync10(path, `${existing.replace(/\s*$/, "")}${sep10}${fragment}`);
|
|
41465
42157
|
return path;
|
|
41466
42158
|
}
|
|
41467
42159
|
function detectConflict(name, scope, target) {
|
|
@@ -41504,14 +42196,59 @@ function detectRewriteConflict(name, scope, target, lookup = getHook) {
|
|
|
41504
42196
|
}
|
|
41505
42197
|
return;
|
|
41506
42198
|
}
|
|
42199
|
+
function installForAdapter(shortName, scope, overwrite, target, events3, timeoutSeconds, profile, mementos) {
|
|
42200
|
+
const stopEvent = getTargetCapabilities(target, capabilityOptions(scope, shortName))?.stopEvent ?? "turn-end";
|
|
42201
|
+
const unsupported = events3.filter((event) => event !== "Stop");
|
|
42202
|
+
if (events3.length === 0 || unsupported.length > 0) {
|
|
42203
|
+
return {
|
|
42204
|
+
hook: shortName,
|
|
42205
|
+
success: false,
|
|
42206
|
+
scope,
|
|
42207
|
+
target,
|
|
42208
|
+
error: `Refused: '${shortName}' runs on ${events3.length > 0 ? events3.join(", ") : "no event"}, and target '${target}' only has the ${stopEvent} turn-end event. Install it on claude, codex, gemini, codewith or qwen; a harness config is never given an event it does not carry.`
|
|
42209
|
+
};
|
|
42210
|
+
}
|
|
42211
|
+
const options = adapterOptions(scope);
|
|
42212
|
+
const registered = readAdapterRegistrations(target, options).some((entry) => entry.hook === shortName);
|
|
42213
|
+
if (registered && !overwrite) {
|
|
42214
|
+
return { hook: shortName, success: false, error: "Already installed. Use --overwrite to replace.", scope, target };
|
|
42215
|
+
}
|
|
42216
|
+
if (registered)
|
|
42217
|
+
removeFromAdapter(target, shortName, options);
|
|
42218
|
+
const conflict = detectConflict(shortName, scope, target);
|
|
42219
|
+
const command = (profile ? `hooks run ${shortName} --profile ${profile}` : `hooks run ${shortName}`) + ` --target ${target}` + mementosCommandSuffix(mementos);
|
|
42220
|
+
const outcome = installInAdapter(target, shortName, command, options, timeoutSeconds);
|
|
42221
|
+
if (!outcome.ok) {
|
|
42222
|
+
return { hook: shortName, success: false, error: outcome.error, scope, target, ...outcome.configPath ? { configPath: outcome.configPath } : {} };
|
|
42223
|
+
}
|
|
42224
|
+
const note = [outcome.note, targetInstallNote(target)].filter(Boolean).join(" ");
|
|
42225
|
+
return {
|
|
42226
|
+
hook: shortName,
|
|
42227
|
+
success: true,
|
|
42228
|
+
scope,
|
|
42229
|
+
target,
|
|
42230
|
+
applied: true,
|
|
42231
|
+
conflict,
|
|
42232
|
+
configPath: outcome.configPath,
|
|
42233
|
+
...note ? { note } : {}
|
|
42234
|
+
};
|
|
42235
|
+
}
|
|
41507
42236
|
function installForTarget(name, scope, overwrite, target, profile, codewithMode = "fragment", codewithConfigPath, mementos, expectedSettingsSha256, beforeWrite) {
|
|
41508
42237
|
const shortName = shortHookName(name);
|
|
41509
|
-
if (isNativeSafetyName(shortName) && (profile || target === "gemini" || target === "codewith" && codewithMode === "write")) {
|
|
42238
|
+
if (isNativeSafetyName(shortName) && (profile || target === "gemini" || isAdapterTarget(target) || target === "codewith" && codewithMode === "write")) {
|
|
41510
42239
|
return { hook: shortName, success: false, error: "Bundled native safety guards support Claude/Codex and managed Codewith fragments, without registry profiles.", target };
|
|
41511
42240
|
}
|
|
41512
42241
|
if (!isNativeSafetyName(shortName) && !hookExists(shortName)) {
|
|
41513
42242
|
return { hook: shortName, success: false, error: `Hook '${shortName}' not found`, target };
|
|
41514
42243
|
}
|
|
42244
|
+
const meta3 = isNativeSafetyName(shortName) ? getHook(shortName) : resolveHookMeta(shortName);
|
|
42245
|
+
const events3 = meta3 ? getHookEvents(meta3) : [];
|
|
42246
|
+
const capabilityRefusal = installCapabilityRefusal(shortName, target, { events: events3, requiresFinalMessage: meta3?.requiresFinalMessage === true, requiresBlock: meta3?.requiresBlock === true }, capabilityOptions(scope, shortName));
|
|
42247
|
+
if (capabilityRefusal)
|
|
42248
|
+
return { hook: shortName, success: false, error: capabilityRefusal, scope, target };
|
|
42249
|
+
if (isAdapterTarget(target)) {
|
|
42250
|
+
return installForAdapter(shortName, scope, overwrite, target, events3, meta3?.timeoutSeconds ?? 10, profile, mementos);
|
|
42251
|
+
}
|
|
41515
42252
|
if (target === "codewith") {
|
|
41516
42253
|
try {
|
|
41517
42254
|
const fragment = buildCodewithTomlFragment(shortName, profile, mementos);
|
|
@@ -41562,7 +42299,8 @@ function installForTarget(name, scope, overwrite, target, profile, codewithMode
|
|
|
41562
42299
|
}
|
|
41563
42300
|
}
|
|
41564
42301
|
try {
|
|
41565
|
-
const
|
|
42302
|
+
const settingsTarget = target;
|
|
42303
|
+
const registered = getRegisteredHooksForTarget(scope, settingsTarget);
|
|
41566
42304
|
if (registered.includes(shortName) && !overwrite) {
|
|
41567
42305
|
return { hook: shortName, success: false, error: "Already installed. Use --overwrite to replace.", scope, target };
|
|
41568
42306
|
}
|
|
@@ -41571,7 +42309,7 @@ function installForTarget(name, scope, overwrite, target, profile, codewithMode
|
|
|
41571
42309
|
if (rewriteConflict) {
|
|
41572
42310
|
return { hook: shortName, success: false, error: `Refused: ${rewriteConflict}`, scope, target };
|
|
41573
42311
|
}
|
|
41574
|
-
registerHook(shortName, scope,
|
|
42312
|
+
registerHook(shortName, scope, settingsTarget, profile, mementos, (settings, selectedScope, selectedTarget) => writeSettings(settings, selectedScope, selectedTarget, expectedSettingsSha256, beforeWrite));
|
|
41575
42313
|
return {
|
|
41576
42314
|
hook: shortName,
|
|
41577
42315
|
success: true,
|
|
@@ -41754,6 +42492,9 @@ function unregisterHook(name, scope = "global", target = "claude") {
|
|
|
41754
42492
|
writeSettings(settings, scope, target);
|
|
41755
42493
|
}
|
|
41756
42494
|
function getRegisteredHooksForTarget(scope = "global", target = "claude") {
|
|
42495
|
+
if (isAdapterTarget(target)) {
|
|
42496
|
+
return [...new Set(readAdapterRegistrations(target, adapterOptions(scope)).map((entry) => entry.hook))];
|
|
42497
|
+
}
|
|
41757
42498
|
if (target === "codewith") {
|
|
41758
42499
|
const config2 = readCodewithConfig(scope);
|
|
41759
42500
|
const registered2 = [];
|
|
@@ -41792,20 +42533,37 @@ function getRegisteredHooksForTarget(scope = "global", target = "claude") {
|
|
|
41792
42533
|
function getRegisteredHooks(scope = "global") {
|
|
41793
42534
|
return getRegisteredHooksForTarget(scope, "claude");
|
|
41794
42535
|
}
|
|
41795
|
-
function removeHook(name, scope = "global", target = "claude") {
|
|
42536
|
+
function removeHook(name, scope = "global", target = "claude", options = {}) {
|
|
41796
42537
|
const shortName = shortHookName(name);
|
|
41797
42538
|
if (target === "all") {
|
|
41798
|
-
|
|
41799
|
-
const
|
|
41800
|
-
|
|
41801
|
-
|
|
42539
|
+
let removedAny = false;
|
|
42540
|
+
for (const candidate of ALL_REMOVABLE_TARGETS) {
|
|
42541
|
+
if (removeHookForTarget(shortName, scope, candidate, options.run))
|
|
42542
|
+
removedAny = true;
|
|
42543
|
+
}
|
|
42544
|
+
return removedAny;
|
|
41802
42545
|
}
|
|
41803
42546
|
if (target === "codewith") {
|
|
41804
42547
|
return false;
|
|
41805
42548
|
}
|
|
41806
|
-
|
|
42549
|
+
if (isAdapterTarget(target)) {
|
|
42550
|
+
return removeFromAdapter(target, shortName, adapterOptions(scope, undefined, options.run)).removed;
|
|
42551
|
+
}
|
|
42552
|
+
if (target === "opencode" || target === "sumi") {
|
|
42553
|
+
return false;
|
|
42554
|
+
}
|
|
42555
|
+
return removeHookForTarget(shortName, scope, target, options.run);
|
|
41807
42556
|
}
|
|
41808
|
-
function removeHookForTarget(name, scope, target) {
|
|
42557
|
+
function removeHookForTarget(name, scope, target, run) {
|
|
42558
|
+
if (isAdapterTarget(target)) {
|
|
42559
|
+
const options = adapterOptions(scope, undefined, run);
|
|
42560
|
+
const state = readAdapterState(target, options);
|
|
42561
|
+
if (state.status !== "verified")
|
|
42562
|
+
return false;
|
|
42563
|
+
if (!adapterStateCarries(state, name))
|
|
42564
|
+
return false;
|
|
42565
|
+
return removeFromAdapter(target, name, options).removed;
|
|
42566
|
+
}
|
|
41809
42567
|
const registered = getRegisteredHooksForTarget(scope, target);
|
|
41810
42568
|
if (!registered.includes(name)) {
|
|
41811
42569
|
return false;
|
|
@@ -41813,78 +42571,8 @@ function removeHookForTarget(name, scope, target) {
|
|
|
41813
42571
|
unregisterHook(name, scope, target);
|
|
41814
42572
|
return true;
|
|
41815
42573
|
}
|
|
41816
|
-
|
|
41817
|
-
|
|
41818
|
-
init_app_home();
|
|
41819
|
-
import { existsSync as existsSync13, mkdirSync as mkdirSync9, readFileSync as readFileSync8, writeFileSync as writeFileSync9, readdirSync as readdirSync7, rmSync as rmSync2, cpSync as cpSync2 } from "fs";
|
|
41820
|
-
import { join as join20 } from "path";
|
|
41821
|
-
function getProfilesDir() {
|
|
41822
|
-
const newDir = join20(getEffectiveDataRoot(), "profiles");
|
|
41823
|
-
const oldDir = join20(getHomeDir(), ".hooks", "profiles");
|
|
41824
|
-
if (!existsSync13(newDir) && existsSync13(oldDir)) {
|
|
41825
|
-
mkdirSync9(newDir, { recursive: true });
|
|
41826
|
-
cpSync2(oldDir, newDir, { recursive: true });
|
|
41827
|
-
}
|
|
41828
|
-
return newDir;
|
|
41829
|
-
}
|
|
41830
|
-
function ensureProfilesDir() {
|
|
41831
|
-
const dir = getProfilesDir();
|
|
41832
|
-
if (!existsSync13(dir)) {
|
|
41833
|
-
mkdirSync9(dir, { recursive: true });
|
|
41834
|
-
}
|
|
41835
|
-
}
|
|
41836
|
-
function profilePath(id) {
|
|
41837
|
-
return join20(getProfilesDir(), `${id}.json`);
|
|
41838
|
-
}
|
|
41839
|
-
function shortUuid() {
|
|
41840
|
-
return crypto.randomUUID().slice(0, 8);
|
|
41841
|
-
}
|
|
41842
|
-
function createProfile(input2) {
|
|
41843
|
-
ensureProfilesDir();
|
|
41844
|
-
const id = shortUuid();
|
|
41845
|
-
const now = new Date().toISOString();
|
|
41846
|
-
const profile = {
|
|
41847
|
-
agent_id: id,
|
|
41848
|
-
agent_type: input2.agent_type,
|
|
41849
|
-
created_at: now,
|
|
41850
|
-
last_seen_at: now,
|
|
41851
|
-
preferences: {}
|
|
41852
|
-
};
|
|
41853
|
-
if (input2.name) {
|
|
41854
|
-
profile.name = input2.name;
|
|
41855
|
-
}
|
|
41856
|
-
writeFileSync9(profilePath(id), JSON.stringify(profile, null, 2) + `
|
|
41857
|
-
`);
|
|
41858
|
-
return profile;
|
|
41859
|
-
}
|
|
41860
|
-
function getProfile(id) {
|
|
41861
|
-
const path = profilePath(id);
|
|
41862
|
-
try {
|
|
41863
|
-
if (!existsSync13(path))
|
|
41864
|
-
return null;
|
|
41865
|
-
return JSON.parse(readFileSync8(path, "utf-8"));
|
|
41866
|
-
} catch {
|
|
41867
|
-
return null;
|
|
41868
|
-
}
|
|
41869
|
-
}
|
|
41870
|
-
function listProfiles() {
|
|
41871
|
-
const dir = getProfilesDir();
|
|
41872
|
-
if (!existsSync13(dir))
|
|
41873
|
-
return [];
|
|
41874
|
-
try {
|
|
41875
|
-
const files = readdirSync7(dir).filter((f) => f.endsWith(".json"));
|
|
41876
|
-
const profiles = [];
|
|
41877
|
-
for (const file2 of files) {
|
|
41878
|
-
try {
|
|
41879
|
-
const content = readFileSync8(join20(dir, file2), "utf-8");
|
|
41880
|
-
profiles.push(JSON.parse(content));
|
|
41881
|
-
} catch {}
|
|
41882
|
-
}
|
|
41883
|
-
return profiles.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
|
|
41884
|
-
} catch {
|
|
41885
|
-
return [];
|
|
41886
|
-
}
|
|
41887
|
-
}
|
|
42574
|
+
var JSON_SETTINGS_TARGETS = ["claude", "gemini", "codex", "qwen"];
|
|
42575
|
+
var ALL_REMOVABLE_TARGETS = [...JSON_SETTINGS_TARGETS, ...ADAPTER_TARGETS];
|
|
41888
42576
|
|
|
41889
42577
|
// src/mcp/server.ts
|
|
41890
42578
|
init_manifest();
|
|
@@ -42442,13 +43130,13 @@ function coerceForSqlite(value) {
|
|
|
42442
43130
|
return String(value);
|
|
42443
43131
|
}
|
|
42444
43132
|
// src/mcp/server.ts
|
|
42445
|
-
var __dirname3 =
|
|
43133
|
+
var __dirname3 = dirname29(fileURLToPath4(import.meta.url));
|
|
42446
43134
|
var pkg = { name: "@hasna/hooks", version: "0.0.0" };
|
|
42447
43135
|
try {
|
|
42448
43136
|
for (const rel of ["../../package.json", "../package.json", "../../../package.json"]) {
|
|
42449
|
-
const p =
|
|
42450
|
-
if (
|
|
42451
|
-
pkg = JSON.parse(
|
|
43137
|
+
const p = join34(__dirname3, rel);
|
|
43138
|
+
if (existsSync16(p)) {
|
|
43139
|
+
pkg = JSON.parse(readFileSync18(p, "utf-8"));
|
|
42452
43140
|
break;
|
|
42453
43141
|
}
|
|
42454
43142
|
}
|
|
@@ -42457,10 +43145,10 @@ async function runVerifiedHook(name, stdin, timeoutMs) {
|
|
|
42457
43145
|
const { resolveHook: resolveHook2, resolveScriptPath: resolveScriptPath2 } = await Promise.resolve().then(() => (init_resolve(), exports_resolve));
|
|
42458
43146
|
const resolved = resolveHook2(name);
|
|
42459
43147
|
const hookScript = resolveScriptPath2(name);
|
|
42460
|
-
if (!resolved || !hookScript || !
|
|
43148
|
+
if (!resolved || !hookScript || !existsSync16(hookScript)) {
|
|
42461
43149
|
throw new Error(`Hook '${name}' not found`);
|
|
42462
43150
|
}
|
|
42463
|
-
const content =
|
|
43151
|
+
const content = readFileSync18(hookScript);
|
|
42464
43152
|
const sha7 = sha256Of(content);
|
|
42465
43153
|
const check2 = checkScriptHash(name, sha7);
|
|
42466
43154
|
if (!check2.ok) {
|
|
@@ -42542,10 +43230,10 @@ function settingsChangeError(hook, scope, error61, code2) {
|
|
|
42542
43230
|
};
|
|
42543
43231
|
}
|
|
42544
43232
|
function truncateText(value, max = 160) {
|
|
42545
|
-
const
|
|
42546
|
-
if (
|
|
42547
|
-
return
|
|
42548
|
-
return `${
|
|
43233
|
+
const text2 = String(value ?? "").replace(/\s+/g, " ").trim();
|
|
43234
|
+
if (text2.length <= max)
|
|
43235
|
+
return text2;
|
|
43236
|
+
return `${text2.slice(0, Math.max(0, max - 3))}...`;
|
|
42549
43237
|
}
|
|
42550
43238
|
function boundedLimit(value, fallback, max) {
|
|
42551
43239
|
if (!Number.isFinite(value) || !value || value <= 0)
|
|
@@ -42672,7 +43360,7 @@ function createHooksServer() {
|
|
|
42672
43360
|
const settingsPath = getSettingsPath(scope);
|
|
42673
43361
|
const issues = [];
|
|
42674
43362
|
const healthy = [];
|
|
42675
|
-
const settingsExist =
|
|
43363
|
+
const settingsExist = existsSync16(settingsPath);
|
|
42676
43364
|
if (!settingsExist) {
|
|
42677
43365
|
issues.push({ hook: "(settings)", issue: `${settingsPath} not found`, severity: "warning" });
|
|
42678
43366
|
}
|
|
@@ -42682,7 +43370,7 @@ function createHooksServer() {
|
|
|
42682
43370
|
const meta3 = custom2 ? resolveHookMeta(name) : getHook(name);
|
|
42683
43371
|
let hookHealthy = true;
|
|
42684
43372
|
if (custom2) {
|
|
42685
|
-
if (!
|
|
43373
|
+
if (!existsSync16(custom2.scriptPath)) {
|
|
42686
43374
|
issues.push({ hook: name, issue: `Custom hook script missing: ${custom2.scriptPath}`, severity: "error" });
|
|
42687
43375
|
hookHealthy = false;
|
|
42688
43376
|
}
|
|
@@ -42692,14 +43380,14 @@ function createHooksServer() {
|
|
|
42692
43380
|
continue;
|
|
42693
43381
|
}
|
|
42694
43382
|
const hookDir = getHookPath(name);
|
|
42695
|
-
if (!
|
|
43383
|
+
if (!existsSync16(join34(hookDir, "src", "hook.ts"))) {
|
|
42696
43384
|
issues.push({ hook: name, issue: "Missing src/hook.ts in package", severity: "error" });
|
|
42697
43385
|
hookHealthy = false;
|
|
42698
43386
|
}
|
|
42699
43387
|
}
|
|
42700
43388
|
if (meta3 && settingsExist) {
|
|
42701
43389
|
try {
|
|
42702
|
-
const settings = JSON.parse(
|
|
43390
|
+
const settings = JSON.parse(readFileSync18(settingsPath, "utf-8"));
|
|
42703
43391
|
if (!hookRegisteredInSettings(settings, name, meta3.event, matcherFor(meta3, "claude"))) {
|
|
42704
43392
|
const eventName = meta3.event.split(":")[0];
|
|
42705
43393
|
issues.push({ hook: name, issue: `Not registered under correct event (${eventName})`, severity: "error" });
|
|
@@ -42736,10 +43424,10 @@ function createHooksServer() {
|
|
|
42736
43424
|
return { content: [{ type: "text", text: JSON.stringify({ error: `Hook '${name}' not found` }) }] };
|
|
42737
43425
|
}
|
|
42738
43426
|
const hookPath = getHookPath(name);
|
|
42739
|
-
const readmePath =
|
|
43427
|
+
const readmePath = join34(hookPath, "README.md");
|
|
42740
43428
|
let readme = "";
|
|
42741
|
-
if (
|
|
42742
|
-
readme =
|
|
43429
|
+
if (existsSync16(readmePath)) {
|
|
43430
|
+
readme = readFileSync18(readmePath, "utf-8");
|
|
42743
43431
|
}
|
|
42744
43432
|
if (verbose) {
|
|
42745
43433
|
return { content: [{ type: "text", text: JSON.stringify({ ...meta3, readme }) }] };
|
|
@@ -42922,7 +43610,7 @@ function createHooksServer() {
|
|
|
42922
43610
|
const ctx = {
|
|
42923
43611
|
scope,
|
|
42924
43612
|
settings_path: settingsPath,
|
|
42925
|
-
settings_exists:
|
|
43613
|
+
settings_exists: existsSync16(settingsPath),
|
|
42926
43614
|
registered_hooks: hooks,
|
|
42927
43615
|
hook_count: hooks.length,
|
|
42928
43616
|
healthy,
|