@hasna/hooks 0.12.23 → 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 +1 -0
- package/bin/hooks/scratch-lifecycle.js +5 -5
- package/bin/hooks/stop-review.js +2 -2
- package/bin/hooks-mcp.js +1246 -1134
- package/bin/index.js +2160 -1836
- package/bin/native-safety-entry.js +37 -37
- package/bin/native-safety-worker.cjs +37 -37
- package/bin/serve.js +115 -111
- package/dist/index.js +1633 -1453
- package/dist/lib/installer.d.ts +44 -5
- package/dist/lib/manifest.d.ts +21 -0
- package/dist/lib/native-target.d.ts +11 -2
- package/dist/lib/registry.d.ts +12 -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 +9 -9
- package/dist/opencode-stop-plugin.js +5 -5
- package/dist/sdk/index.js +7 -7
- package/dist/storage.js +34 -34
- package/dist/sumi-stop-plugin.js +7 -7
- package/package.json +1 -1
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) {
|
|
@@ -1497,11 +1501,11 @@ var init_redact = __esm(() => {
|
|
|
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;
|
|
@@ -1744,7 +1748,7 @@ function isAmbientEnvironment(env) {
|
|
|
1744
1748
|
return env === process.env || env[AMBIENT_ENVIRONMENT2] === true;
|
|
1745
1749
|
}
|
|
1746
1750
|
function defaultKeychainRunner(argv) {
|
|
1747
|
-
const result =
|
|
1751
|
+
const result = spawnSync4(KEYCHAIN_SECURITY_BIN, [...argv], {
|
|
1748
1752
|
encoding: "utf8",
|
|
1749
1753
|
stdio: ["ignore", "pipe", "pipe"],
|
|
1750
1754
|
timeout: KEYCHAIN_SPAWN_TIMEOUT_MS
|
|
@@ -1772,8 +1776,8 @@ function keychainAccount(env, options) {
|
|
|
1772
1776
|
const user = env.USER?.trim();
|
|
1773
1777
|
return user || null;
|
|
1774
1778
|
}
|
|
1775
|
-
function keychainFailureHint(
|
|
1776
|
-
const line =
|
|
1779
|
+
function keychainFailureHint(text2) {
|
|
1780
|
+
const line = text2.split(/\r?\n/).find((entry) => entry.trim().length > 0)?.trim() ?? "";
|
|
1777
1781
|
const clean = line.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 200);
|
|
1778
1782
|
return clean ? `: ${clean}` : "";
|
|
1779
1783
|
}
|
|
@@ -2418,9 +2422,9 @@ var init_stop_review_context = __esm(() => {
|
|
|
2418
2422
|
});
|
|
2419
2423
|
|
|
2420
2424
|
// src/lib/hook-env.ts
|
|
2421
|
-
import { dirname as
|
|
2422
|
-
import { existsSync as
|
|
2423
|
-
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";
|
|
2424
2428
|
function isDeniedEnvName(name) {
|
|
2425
2429
|
const upper = name.toUpperCase();
|
|
2426
2430
|
if (DENY_PREFIXES.some((prefix3) => upper.startsWith(prefix3)))
|
|
@@ -2454,22 +2458,22 @@ function isUnsafePathEntry(entry, home) {
|
|
|
2454
2458
|
}
|
|
2455
2459
|
};
|
|
2456
2460
|
const resolved = canonical9(entry);
|
|
2457
|
-
for (const root of [home,
|
|
2461
|
+
for (const root of [home, tmpdir2(), "/tmp", "/var/tmp"].filter((value) => Boolean(value))) {
|
|
2458
2462
|
const blocked = canonical9(root);
|
|
2459
2463
|
if (resolved === blocked || resolved.startsWith(blocked + "/"))
|
|
2460
2464
|
return true;
|
|
2461
2465
|
}
|
|
2462
2466
|
try {
|
|
2463
|
-
if ((
|
|
2467
|
+
if ((statSync2(entry).mode & 2) !== 0)
|
|
2464
2468
|
return true;
|
|
2465
2469
|
} catch {}
|
|
2466
2470
|
return false;
|
|
2467
2471
|
}
|
|
2468
2472
|
function sanitizeHookPath(pathValue, home) {
|
|
2469
2473
|
const baseline = PATH_BASELINE.slice();
|
|
2470
|
-
if (process.platform === "darwin" &&
|
|
2474
|
+
if (process.platform === "darwin" && existsSync15("/opt/homebrew/bin"))
|
|
2471
2475
|
baseline.push("/opt/homebrew/bin");
|
|
2472
|
-
const bunDir =
|
|
2476
|
+
const bunDir = dirname23(process.execPath);
|
|
2473
2477
|
const seen = new Set;
|
|
2474
2478
|
const out = [];
|
|
2475
2479
|
for (const dir of baseline) {
|
|
@@ -2597,15 +2601,15 @@ var init_hook_env = __esm(() => {
|
|
|
2597
2601
|
// src/lib/run.ts
|
|
2598
2602
|
var exports_run = {};
|
|
2599
2603
|
__export(exports_run, {
|
|
2600
|
-
|
|
2604
|
+
BUN_ISOLATION_FLAGS: () => BUN_ISOLATION_FLAGS,
|
|
2601
2605
|
HookTimeoutError: () => HookTimeoutError,
|
|
2602
|
-
|
|
2606
|
+
executeVerifiedScript: () => executeVerifiedScript
|
|
2603
2607
|
});
|
|
2604
2608
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
2605
|
-
import { rmSync as rmSync5, writeFileSync as
|
|
2606
|
-
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";
|
|
2607
2611
|
function extensionOf(scriptPath) {
|
|
2608
|
-
const base =
|
|
2612
|
+
const base = basename16(scriptPath);
|
|
2609
2613
|
const dot = base.lastIndexOf(".");
|
|
2610
2614
|
return dot > 0 ? base.slice(dot + 1) : "ts";
|
|
2611
2615
|
}
|
|
@@ -2617,9 +2621,9 @@ function shebangInterpreter(firstLine) {
|
|
|
2617
2621
|
return null;
|
|
2618
2622
|
const parts = rest.split(/\s+/);
|
|
2619
2623
|
if (parts[0] === "env" || parts[0] === "/usr/bin/env") {
|
|
2620
|
-
return parts[1] && parts[1] !== "-S" ?
|
|
2624
|
+
return parts[1] && parts[1] !== "-S" ? basename16(parts[1]) : parts[2] ? basename16(parts[2]) : null;
|
|
2621
2625
|
}
|
|
2622
|
-
return
|
|
2626
|
+
return basename16(parts[0]);
|
|
2623
2627
|
}
|
|
2624
2628
|
function interpreterFor(name, scriptPath, content) {
|
|
2625
2629
|
const ext = extensionOf(scriptPath);
|
|
@@ -2672,9 +2676,9 @@ async function readPipeWithDeadline(stream, deadlineMs) {
|
|
|
2672
2676
|
return chunks.join("");
|
|
2673
2677
|
}
|
|
2674
2678
|
async function executeVerifiedScript(options) {
|
|
2675
|
-
const scriptDir =
|
|
2679
|
+
const scriptDir = dirname27(options.scriptPath);
|
|
2676
2680
|
const interpreter = interpreterFor(options.name, options.scriptPath, options.content);
|
|
2677
|
-
const tempPath =
|
|
2681
|
+
const tempPath = join32(scriptDir, `.hooks-verified-${randomBytes2(12).toString("hex")}.${interpreter.tempExt}`);
|
|
2678
2682
|
let proc = null;
|
|
2679
2683
|
let timedOut = false;
|
|
2680
2684
|
const timeoutTimer = options.timeout ? setTimeout(() => {
|
|
@@ -2682,7 +2686,7 @@ async function executeVerifiedScript(options) {
|
|
|
2682
2686
|
killGroup(proc, { leaderAlive: proc !== null && proc.exitCode === null });
|
|
2683
2687
|
}, options.timeout) : null;
|
|
2684
2688
|
try {
|
|
2685
|
-
|
|
2689
|
+
writeFileSync11(tempPath, options.content, { flag: "wx", mode: 384 });
|
|
2686
2690
|
proc = Bun.spawn([...interpreter.command, isAbsolute17(tempPath) ? tempPath : `./${tempPath}`, ...options.args ?? []], {
|
|
2687
2691
|
stdin: new Response(options.stdin),
|
|
2688
2692
|
stdout: "pipe",
|
|
@@ -2763,12 +2767,12 @@ var init_run = __esm(() => {
|
|
|
2763
2767
|
// src/lib/db-writer.ts
|
|
2764
2768
|
var exports_db_writer = {};
|
|
2765
2769
|
__export(exports_db_writer, {
|
|
2766
|
-
|
|
2767
|
-
resolveHookEventSink: () => resolveHookEventSink,
|
|
2768
|
-
resolveEventType: () => resolveEventType,
|
|
2769
|
-
recordHookRun: () => recordHookRun,
|
|
2770
|
+
__resetHookEventSinkNotice: () => __resetHookEventSinkNotice,
|
|
2770
2771
|
normalizeEventType: () => normalizeEventType,
|
|
2771
|
-
|
|
2772
|
+
recordHookRun: () => recordHookRun,
|
|
2773
|
+
resolveEventType: () => resolveEventType,
|
|
2774
|
+
resolveHookEventSink: () => resolveHookEventSink,
|
|
2775
|
+
writeHookEvent: () => writeHookEvent
|
|
2772
2776
|
});
|
|
2773
2777
|
function resolveHookEventSink(env = process.env) {
|
|
2774
2778
|
if (isLocalStoreRefused())
|
|
@@ -2884,15 +2888,15 @@ import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
|
|
2884
2888
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
2885
2889
|
import { z as z3 } from "zod";
|
|
2886
2890
|
init_registry();
|
|
2887
|
-
import { existsSync as
|
|
2888
|
-
import { join as
|
|
2891
|
+
import { existsSync as existsSync16, readFileSync as readFileSync18 } from "fs";
|
|
2892
|
+
import { join as join34, dirname as dirname29 } from "path";
|
|
2889
2893
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
2890
2894
|
|
|
2891
2895
|
// src/lib/installer.ts
|
|
2892
2896
|
init_registry();
|
|
2893
|
-
import { existsSync as
|
|
2894
|
-
import { join as
|
|
2895
|
-
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";
|
|
2896
2900
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
2897
2901
|
|
|
2898
2902
|
// src/lib/readiness-process.ts
|
|
@@ -3399,8 +3403,232 @@ function retainedMementosRegistration(commands) {
|
|
|
3399
3403
|
return values[0];
|
|
3400
3404
|
}
|
|
3401
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
|
+
|
|
3402
3630
|
// src/lib/registration.ts
|
|
3403
|
-
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-]+))$`);
|
|
3404
3632
|
function registrationName(command) {
|
|
3405
3633
|
if (typeof command !== "string")
|
|
3406
3634
|
return;
|
|
@@ -3477,7 +3705,7 @@ function hookRegisteredInSettings(settings, name, eventSpec, hookMatcher) {
|
|
|
3477
3705
|
// src/lib/store.ts
|
|
3478
3706
|
import { createHash as createHash4 } from "crypto";
|
|
3479
3707
|
import { existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync2, renameSync, lstatSync as lstatSync3 } from "fs";
|
|
3480
|
-
import { join as
|
|
3708
|
+
import { join as join10 } from "path";
|
|
3481
3709
|
init_db();
|
|
3482
3710
|
init_config();
|
|
3483
3711
|
init_manifest();
|
|
@@ -3595,7 +3823,7 @@ function getPinnedHook(name) {
|
|
|
3595
3823
|
return readLock().hooks[name];
|
|
3596
3824
|
}
|
|
3597
3825
|
function registryManagedMarker(name) {
|
|
3598
|
-
return
|
|
3826
|
+
return join10(getHooksDataDir(), "registry-managed", sha256Of(name) + ".json");
|
|
3599
3827
|
}
|
|
3600
3828
|
function isRegistryManaged(name) {
|
|
3601
3829
|
try {
|
|
@@ -3669,7 +3897,7 @@ function checkScriptHash(name, actual) {
|
|
|
3669
3897
|
|
|
3670
3898
|
// src/lib/codex-settings.ts
|
|
3671
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";
|
|
3672
|
-
import { dirname as
|
|
3900
|
+
import { dirname as dirname6 } from "path";
|
|
3673
3901
|
import { createHash as createHash5, randomUUID } from "crypto";
|
|
3674
3902
|
var snapshots = new WeakMap;
|
|
3675
3903
|
function current(path) {
|
|
@@ -3722,7 +3950,7 @@ function writeCodexSettings(path, settings, expectedSha256, beforeWrite) {
|
|
|
3722
3950
|
` });
|
|
3723
3951
|
}
|
|
3724
3952
|
function writeHookSettingsPreimage(path, settings, before, beforeWrite) {
|
|
3725
|
-
mkdirSync4(
|
|
3953
|
+
mkdirSync4(dirname6(path), { recursive: true, mode: 448 });
|
|
3726
3954
|
const lock = `${path}.hooks-write.lock`;
|
|
3727
3955
|
let fd;
|
|
3728
3956
|
try {
|
|
@@ -3752,18 +3980,15 @@ function writeHookSettingsPreimage(path, settings, before, beforeWrite) {
|
|
|
3752
3980
|
// src/lib/claude-skills-coordination.ts
|
|
3753
3981
|
import { createHash as createHash8 } from "crypto";
|
|
3754
3982
|
import { existsSync as existsSync11, lstatSync as lstatSync9 } from "fs";
|
|
3755
|
-
import { homedir as
|
|
3756
|
-
import { join as
|
|
3983
|
+
import { homedir as homedir7 } from "os";
|
|
3984
|
+
import { join as join17, resolve as resolve9 } from "path";
|
|
3757
3985
|
|
|
3758
3986
|
// ../../node_modules/.bun/@hasna+skills@0.10.78+a00d3064559565bb/node_modules/@hasna/skills/dist/index.js
|
|
3759
3987
|
import { existsSync as existsSync10 } from "fs";
|
|
3760
|
-
import { homedir as
|
|
3761
|
-
import { join as
|
|
3988
|
+
import { homedir as homedir6 } from "os";
|
|
3989
|
+
import { join as join11, resolve as resolve4 } from "path";
|
|
3762
3990
|
import { homedir as pathsResolverHomedir2 } from "os";
|
|
3763
3991
|
import { join as pathsResolverJoin2 } from "path";
|
|
3764
|
-
import { createHash as createHash6 } from "crypto";
|
|
3765
|
-
import { existsSync as existsSync52, readdirSync as readdirSync3, readFileSync as readFileSync42, statSync as statSync4 } from "fs";
|
|
3766
|
-
import { join as join52, sep as sep2 } from "path";
|
|
3767
3992
|
import { createHash as createHash32 } from "crypto";
|
|
3768
3993
|
import { createHash as createHash22 } from "crypto";
|
|
3769
3994
|
import { closeSync as closeSync22, constants as constants22, fstatSync as fstatSync22, lstatSync as lstatSync42, openSync as openSync22, readSync } from "fs";
|
|
@@ -3773,14 +3998,14 @@ import { createHash as createHash42 } from "crypto";
|
|
|
3773
3998
|
import { basename as basename3, dirname as dirname42, isAbsolute as isAbsolute32, resolve as resolve32 } from "path";
|
|
3774
3999
|
import { createHash as createHash52 } from "crypto";
|
|
3775
4000
|
import { closeSync as closeSync32, constants as constants3, fstatSync as fstatSync3, lstatSync as lstatSync5, openSync as openSync32, readSync as readSync2 } from "fs";
|
|
3776
|
-
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";
|
|
3777
4002
|
import { createHash as createHash30 } from "crypto";
|
|
3778
4003
|
import { lstatSync as lstatSync32, readFileSync as readFileSync26, readdirSync as readdirSync13, realpathSync as realpathSync13 } from "fs";
|
|
3779
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";
|
|
3780
4005
|
import { isDeepStrictEqual as isDeepStrictEqual9 } from "util";
|
|
3781
|
-
import { dirname as
|
|
4006
|
+
import { dirname as dirname62, isAbsolute as isAbsolute6, join as join82, resolve as resolve6 } from "path";
|
|
3782
4007
|
import { lstatSync as lstatSync6, readFileSync as readFileSync62, opendirSync } from "fs";
|
|
3783
|
-
import { createHash as
|
|
4008
|
+
import { createHash as createHash6 } from "crypto";
|
|
3784
4009
|
import { lstatSync as lstatSync7, opendirSync as opendirSync2 } from "fs";
|
|
3785
4010
|
import { dirname as dirname7, isAbsolute as isAbsolute7, join as join92, resolve as resolve7 } from "path";
|
|
3786
4011
|
import { createHash as createHash7 } from "crypto";
|
|
@@ -3855,7 +4080,6 @@ import { closeSync as closeSync19, constants as constants20, fstatSync as fstatS
|
|
|
3855
4080
|
import { basename as basename14, dirname as dirname25, isAbsolute as isAbsolute27, resolve as resolve26 } from "path";
|
|
3856
4081
|
import { createHash as createHash29 } from "crypto";
|
|
3857
4082
|
import { isAbsolute as isAbsolute30 } from "path";
|
|
3858
|
-
import { createHash as createHash34 } from "crypto";
|
|
3859
4083
|
var __defProp2 = Object.defineProperty;
|
|
3860
4084
|
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
3861
4085
|
var __returnValue2 = (v) => v;
|
|
@@ -10707,10 +10931,10 @@ var SKILLS_HOME_ENV = "SKILLS_HOME";
|
|
|
10707
10931
|
var DEFAULT_SQLITE_FILENAME = "server.db";
|
|
10708
10932
|
var GLOBAL_CONFIG_FILENAME = "config.json";
|
|
10709
10933
|
function effectiveHome() {
|
|
10710
|
-
return process.env["HOME"] || process.env["USERPROFILE"] ||
|
|
10934
|
+
return process.env["HOME"] || process.env["USERPROFILE"] || homedir6() || "/tmp";
|
|
10711
10935
|
}
|
|
10712
10936
|
function legacyDataRoot() {
|
|
10713
|
-
return
|
|
10937
|
+
return join11(effectiveHome(), ".hasna", "skills");
|
|
10714
10938
|
}
|
|
10715
10939
|
function resolverDataRoot(home = effectiveHome(), env) {
|
|
10716
10940
|
return dataDir2({ app: "skills", home, env });
|
|
@@ -10719,13 +10943,13 @@ function adoptResolverDataRoot2(resolved, env = process.env) {
|
|
|
10719
10943
|
const dataOverride = env.HASNA_DATA_HOME;
|
|
10720
10944
|
if (typeof dataOverride === "string" && dataOverride.trim().length > 0)
|
|
10721
10945
|
return true;
|
|
10722
|
-
return existsSync10(
|
|
10946
|
+
return existsSync10(join11(resolved, DEFAULT_SQLITE_FILENAME)) || existsSync10(join11(resolved, GLOBAL_CONFIG_FILENAME));
|
|
10723
10947
|
}
|
|
10724
10948
|
function exactDataRoot() {
|
|
10725
10949
|
for (const key of [DATA_DIR_ENV, HASNA_SKILLS_HOME_ENV, SKILLS_HOME_ENV]) {
|
|
10726
10950
|
const dir = process.env[key]?.trim();
|
|
10727
10951
|
if (dir)
|
|
10728
|
-
return
|
|
10952
|
+
return resolve4(dir);
|
|
10729
10953
|
}
|
|
10730
10954
|
return;
|
|
10731
10955
|
}
|
|
@@ -10734,7 +10958,7 @@ function getDataRoot() {
|
|
|
10734
10958
|
if (exact)
|
|
10735
10959
|
return exact;
|
|
10736
10960
|
const resolved = resolverDataRoot();
|
|
10737
|
-
return adoptResolverDataRoot2(resolved) ?
|
|
10961
|
+
return adoptResolverDataRoot2(resolved) ? resolve4(resolved) : resolve4(legacyDataRoot());
|
|
10738
10962
|
}
|
|
10739
10963
|
function getDataDirReadOnly() {
|
|
10740
10964
|
return getDataRoot();
|
|
@@ -10832,132 +11056,7 @@ class SkillEntryPaths {
|
|
|
10832
11056
|
this.files.add(key);
|
|
10833
11057
|
}
|
|
10834
11058
|
}
|
|
10835
|
-
var CONTENT_HASH_ALGORITHM = "sha256";
|
|
10836
11059
|
var HASH_EXCLUDE_DIRS = new Set([".git", "node_modules", "dist", "build", ".turbo"]);
|
|
10837
|
-
function excludedHashEntry(name, directory) {
|
|
10838
|
-
return name.startsWith(".") || directory && HASH_EXCLUDE_DIRS.has(name);
|
|
10839
|
-
}
|
|
10840
|
-
var HASH_COVERAGE = [
|
|
10841
|
-
"SKILL.md",
|
|
10842
|
-
"skill.json",
|
|
10843
|
-
"AGENTS.md",
|
|
10844
|
-
"package.json",
|
|
10845
|
-
"tsconfig.json",
|
|
10846
|
-
"src",
|
|
10847
|
-
"scripts",
|
|
10848
|
-
"assets",
|
|
10849
|
-
"references"
|
|
10850
|
-
];
|
|
10851
|
-
function normalizeLineEndings(content) {
|
|
10852
|
-
return content.replace(/\r\n/g, `
|
|
10853
|
-
`).replace(/\r/g, `
|
|
10854
|
-
`);
|
|
10855
|
-
}
|
|
10856
|
-
function canonicalizeManifest(raw) {
|
|
10857
|
-
let parsed;
|
|
10858
|
-
try {
|
|
10859
|
-
parsed = JSON.parse(raw);
|
|
10860
|
-
} catch {
|
|
10861
|
-
return normalizeLineEndings(raw);
|
|
10862
|
-
}
|
|
10863
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
10864
|
-
return normalizeLineEndings(raw);
|
|
10865
|
-
}
|
|
10866
|
-
const record = parsed;
|
|
10867
|
-
delete record.content_hash;
|
|
10868
|
-
if (record.provenance && typeof record.provenance === "object" && !Array.isArray(record.provenance)) {
|
|
10869
|
-
delete record.provenance.content_hash;
|
|
10870
|
-
}
|
|
10871
|
-
return `${JSON.stringify(sortObjectKeys(record), null, 2)}
|
|
10872
|
-
`;
|
|
10873
|
-
}
|
|
10874
|
-
function sortObjectKeys(value) {
|
|
10875
|
-
if (Array.isArray(value))
|
|
10876
|
-
return value.map((item) => sortObjectKeys(item));
|
|
10877
|
-
if (typeof value === "object" && value !== null) {
|
|
10878
|
-
const record = value;
|
|
10879
|
-
const sorted = Object.create(null);
|
|
10880
|
-
for (const key of Object.keys(record).sort())
|
|
10881
|
-
sorted[key] = sortObjectKeys(record[key]);
|
|
10882
|
-
return sorted;
|
|
10883
|
-
}
|
|
10884
|
-
return value;
|
|
10885
|
-
}
|
|
10886
|
-
function looksLikeText(buffer) {
|
|
10887
|
-
return !buffer.includes(0);
|
|
10888
|
-
}
|
|
10889
|
-
function collectBundleFiles(skillPath) {
|
|
10890
|
-
const files = [];
|
|
10891
|
-
const seen = new Set;
|
|
10892
|
-
for (const entry of HASH_COVERAGE) {
|
|
10893
|
-
if (seen.has(entry))
|
|
10894
|
-
continue;
|
|
10895
|
-
seen.add(entry);
|
|
10896
|
-
const absolute = join52(skillPath, entry);
|
|
10897
|
-
if (!existsSync52(absolute))
|
|
10898
|
-
continue;
|
|
10899
|
-
if (statSync4(absolute).isDirectory())
|
|
10900
|
-
collectDirectory(files, absolute, entry);
|
|
10901
|
-
else
|
|
10902
|
-
collectFile(files, absolute, entry);
|
|
10903
|
-
}
|
|
10904
|
-
return files.sort((a, b) => a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0);
|
|
10905
|
-
}
|
|
10906
|
-
function collectDirectory(files, dir, rel) {
|
|
10907
|
-
for (const entry of readdirSync3(dir).sort()) {
|
|
10908
|
-
if (entry.startsWith("."))
|
|
10909
|
-
continue;
|
|
10910
|
-
const absolute = join52(dir, entry);
|
|
10911
|
-
const childRel = `${rel}/${entry}`;
|
|
10912
|
-
let stats;
|
|
10913
|
-
try {
|
|
10914
|
-
stats = statSync4(absolute);
|
|
10915
|
-
} catch {
|
|
10916
|
-
continue;
|
|
10917
|
-
}
|
|
10918
|
-
if (stats.isSymbolicLink())
|
|
10919
|
-
continue;
|
|
10920
|
-
if (stats.isDirectory()) {
|
|
10921
|
-
if (excludedHashEntry(entry, true))
|
|
10922
|
-
continue;
|
|
10923
|
-
collectDirectory(files, absolute, childRel);
|
|
10924
|
-
} else if (stats.isFile()) {
|
|
10925
|
-
collectFile(files, absolute, childRel);
|
|
10926
|
-
}
|
|
10927
|
-
}
|
|
10928
|
-
}
|
|
10929
|
-
function collectFile(files, absolute, rel) {
|
|
10930
|
-
const buffer = readFileSync42(absolute);
|
|
10931
|
-
files.push(normalizeBundleFile(rel.split(sep2).join("/"), buffer));
|
|
10932
|
-
}
|
|
10933
|
-
function normalizeBundleFile(rel, buffer) {
|
|
10934
|
-
if (rel === "skill.json") {
|
|
10935
|
-
return { rel, content: new TextEncoder().encode(canonicalizeManifest(new TextDecoder().decode(buffer))) };
|
|
10936
|
-
}
|
|
10937
|
-
if (looksLikeText(buffer)) {
|
|
10938
|
-
const normalized = normalizeLineEndings(new TextDecoder().decode(buffer));
|
|
10939
|
-
return { rel, content: new TextEncoder().encode(normalized) };
|
|
10940
|
-
}
|
|
10941
|
-
return { rel, content: buffer };
|
|
10942
|
-
}
|
|
10943
|
-
function computeContentHash(skillPath) {
|
|
10944
|
-
return hashBundleFiles(collectBundleFiles(skillPath));
|
|
10945
|
-
}
|
|
10946
|
-
function* bundleHashParts(files) {
|
|
10947
|
-
for (const file of files) {
|
|
10948
|
-
yield new TextEncoder().encode(file.rel);
|
|
10949
|
-
yield new TextEncoder().encode(`\x00${file.content.length}\x00`);
|
|
10950
|
-
yield file.content;
|
|
10951
|
-
yield new TextEncoder().encode("\x00");
|
|
10952
|
-
}
|
|
10953
|
-
yield new TextEncoder().encode("\x00");
|
|
10954
|
-
}
|
|
10955
|
-
function hashBundleFiles(files) {
|
|
10956
|
-
const hash = createHash6(CONTENT_HASH_ALGORITHM);
|
|
10957
|
-
for (const part of bundleHashParts(files))
|
|
10958
|
-
hash.update(part);
|
|
10959
|
-
return hash.digest("hex");
|
|
10960
|
-
}
|
|
10961
11060
|
var CONTENT_HASH_LIMITS = Object.freeze({
|
|
10962
11061
|
entries: 1024,
|
|
10963
11062
|
rawBytes: 64 * 1024 * 1024,
|
|
@@ -10972,173 +11071,6 @@ var CONTENT_HASH_LIMITS = Object.freeze({
|
|
|
10972
11071
|
var typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
10973
11072
|
var byteLengthOf = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength").get;
|
|
10974
11073
|
var bufferOf = Object.getOwnPropertyDescriptor(typedArrayPrototype, "buffer").get;
|
|
10975
|
-
function verifyContentHash(skillPath, manifest) {
|
|
10976
|
-
const declaredHash = manifest?.provenance?.content_hash?.trim() || undefined;
|
|
10977
|
-
if (!declaredHash)
|
|
10978
|
-
return { declared: false, valid: false };
|
|
10979
|
-
if (!/^[a-f0-9]{64}$/.test(declaredHash)) {
|
|
10980
|
-
return { declared: true, valid: false, declaredHash };
|
|
10981
|
-
}
|
|
10982
|
-
const computedHash = computeContentHash(skillPath);
|
|
10983
|
-
return {
|
|
10984
|
-
declared: true,
|
|
10985
|
-
valid: computedHash === declaredHash,
|
|
10986
|
-
declaredHash,
|
|
10987
|
-
computedHash
|
|
10988
|
-
};
|
|
10989
|
-
}
|
|
10990
|
-
var PORTABLE_SKILL_STANDARD = "hasna.skill.v1";
|
|
10991
|
-
var SKILL_RUNTIMES = ["bun", "node", "python3"];
|
|
10992
|
-
var SKILL_SANDBOX_MODES = ["readonly-fs", "workspace-write", "full"];
|
|
10993
|
-
var SKILL_SYSTEM_DEPS_ALLOWLIST = [
|
|
10994
|
-
"ffmpeg",
|
|
10995
|
-
"ffprobe",
|
|
10996
|
-
"imagemagick",
|
|
10997
|
-
"convert",
|
|
10998
|
-
"curl",
|
|
10999
|
-
"wget",
|
|
11000
|
-
"git",
|
|
11001
|
-
"gh",
|
|
11002
|
-
"jq",
|
|
11003
|
-
"python3",
|
|
11004
|
-
"pip3",
|
|
11005
|
-
"node",
|
|
11006
|
-
"bun",
|
|
11007
|
-
"npm",
|
|
11008
|
-
"rsync",
|
|
11009
|
-
"pdftotext",
|
|
11010
|
-
"tesseract",
|
|
11011
|
-
"7z",
|
|
11012
|
-
"unzip",
|
|
11013
|
-
"zip"
|
|
11014
|
-
];
|
|
11015
|
-
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-]+)*))?$";
|
|
11016
|
-
var CONTENT_HASH_PATTERN = "^[a-f0-9]{64}$";
|
|
11017
|
-
var ENV_REFERENCE_PATTERN = "^[A-Z0-9_]+$";
|
|
11018
|
-
var MAX_RUNTIME_TIMEOUT_SECONDS = 900;
|
|
11019
|
-
function add2(target, code, message) {
|
|
11020
|
-
target.push({ code, message });
|
|
11021
|
-
}
|
|
11022
|
-
function isRecord(value) {
|
|
11023
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
11024
|
-
}
|
|
11025
|
-
function isNonEmptyString(value) {
|
|
11026
|
-
return typeof value === "string" && value.trim().length > 0;
|
|
11027
|
-
}
|
|
11028
|
-
function validatePortableManifestContract(manifest, options = {}) {
|
|
11029
|
-
const issues = [];
|
|
11030
|
-
if (!manifest) {
|
|
11031
|
-
add2(issues, "contract.manifest_missing", "No portable manifest to validate");
|
|
11032
|
-
return issues;
|
|
11033
|
-
}
|
|
11034
|
-
if (manifest.standard !== PORTABLE_SKILL_STANDARD) {
|
|
11035
|
-
add2(issues, "contract.standard_invalid", `standard must be '${PORTABLE_SKILL_STANDARD}'`);
|
|
11036
|
-
}
|
|
11037
|
-
if (!/^[a-z0-9][a-z0-9._-]*$/.test(manifest.name)) {
|
|
11038
|
-
add2(issues, "contract.name_invalid", `name '${manifest.name}' must be a lowercase slug (letters, numbers, dots, underscores, hyphens)`);
|
|
11039
|
-
}
|
|
11040
|
-
if (!isNonEmptyString(manifest.description)) {
|
|
11041
|
-
add2(issues, "contract.description_missing", "description is required");
|
|
11042
|
-
}
|
|
11043
|
-
if (!isNonEmptyString(manifest.version)) {
|
|
11044
|
-
add2(issues, "contract.version_missing", "version is required");
|
|
11045
|
-
} else if (!new RegExp(SEMVER_PATTERN2).test(manifest.version)) {
|
|
11046
|
-
add2(issues, "contract.version_invalid", `version '${manifest.version}' is not valid semver`);
|
|
11047
|
-
}
|
|
11048
|
-
validateRuntimeContract(manifest, issues, options.strict === true);
|
|
11049
|
-
const provenance = manifest.provenance;
|
|
11050
|
-
if (provenance && !isRecord(provenance)) {
|
|
11051
|
-
add2(issues, "contract.provenance_invalid", "provenance must be an object");
|
|
11052
|
-
} else {
|
|
11053
|
-
const sourceCommit = provenance?.source_commit;
|
|
11054
|
-
if (sourceCommit !== undefined && sourceCommit !== null && !isNonEmptyString(sourceCommit)) {
|
|
11055
|
-
add2(issues, "contract.source_commit_invalid", "provenance.source_commit must be a string");
|
|
11056
|
-
}
|
|
11057
|
-
const changelog = provenance?.changelog;
|
|
11058
|
-
if (changelog !== undefined && changelog !== null && !isNonEmptyString(changelog)) {
|
|
11059
|
-
add2(issues, "contract.changelog_invalid", "provenance.changelog must be a string");
|
|
11060
|
-
}
|
|
11061
|
-
const declaredHash = provenance?.content_hash;
|
|
11062
|
-
if (options.strict && !isNonEmptyString(declaredHash)) {
|
|
11063
|
-
add2(issues, "contract.content_hash_missing", "provenance.content_hash is required: a portable manifest must carry its canonical content hash");
|
|
11064
|
-
} else if (isNonEmptyString(declaredHash) && !new RegExp(CONTENT_HASH_PATTERN).test(declaredHash)) {
|
|
11065
|
-
add2(issues, "contract.content_hash_invalid", "provenance.content_hash must be a 64-character lowercase hex SHA-256");
|
|
11066
|
-
} else if (options.skillPath && isNonEmptyString(declaredHash)) {
|
|
11067
|
-
const verification = verifyContentHash(options.skillPath, manifest);
|
|
11068
|
-
if (!verification.valid) {
|
|
11069
|
-
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).`);
|
|
11070
|
-
}
|
|
11071
|
-
}
|
|
11072
|
-
}
|
|
11073
|
-
return issues;
|
|
11074
|
-
}
|
|
11075
|
-
function validateRuntimeContract(manifest, issues, strict) {
|
|
11076
|
-
const runtime = manifest.runtime;
|
|
11077
|
-
if (runtime === undefined) {
|
|
11078
|
-
if (strict && manifest.kind !== "instruction") {
|
|
11079
|
-
add2(issues, "contract.runtime_missing", "runtime contract is required: { runtime, entrypoint?, timeout?, needs_network?, env?, sandbox?, system_deps?, artifacts? }");
|
|
11080
|
-
}
|
|
11081
|
-
return;
|
|
11082
|
-
}
|
|
11083
|
-
if (!isRecord(runtime)) {
|
|
11084
|
-
add2(issues, "contract.runtime_invalid", "runtime must be an object");
|
|
11085
|
-
return;
|
|
11086
|
-
}
|
|
11087
|
-
const runtimeName = runtime.runtime;
|
|
11088
|
-
if (!SKILL_RUNTIMES.includes(runtimeName)) {
|
|
11089
|
-
add2(issues, "contract.runtime_invalid", `runtime.runtime must be one of: ${SKILL_RUNTIMES.join(", ")}`);
|
|
11090
|
-
}
|
|
11091
|
-
if (runtime.version !== undefined && runtime.version !== null && !isNonEmptyString(runtime.version)) {
|
|
11092
|
-
add2(issues, "contract.runtime_version_invalid", "runtime.version must be a string");
|
|
11093
|
-
}
|
|
11094
|
-
if (runtime.entrypoint !== undefined && runtime.entrypoint !== null && !isNonEmptyString(runtime.entrypoint)) {
|
|
11095
|
-
add2(issues, "contract.entrypoint_invalid", "runtime.entrypoint must be a relative path string");
|
|
11096
|
-
}
|
|
11097
|
-
if (runtime.timeout !== undefined && runtime.timeout !== null) {
|
|
11098
|
-
if (typeof runtime.timeout !== "number" || !Number.isInteger(runtime.timeout) || runtime.timeout < 1 || runtime.timeout > MAX_RUNTIME_TIMEOUT_SECONDS) {
|
|
11099
|
-
add2(issues, "contract.timeout_invalid", `runtime.timeout must be an integer between 1 and ${MAX_RUNTIME_TIMEOUT_SECONDS} seconds`);
|
|
11100
|
-
}
|
|
11101
|
-
}
|
|
11102
|
-
if (runtime.needs_network !== undefined && runtime.needs_network !== null && typeof runtime.needs_network !== "boolean") {
|
|
11103
|
-
add2(issues, "contract.needs_network_invalid", "runtime.needs_network must be a boolean");
|
|
11104
|
-
}
|
|
11105
|
-
if (runtime.env !== undefined && runtime.env !== null) {
|
|
11106
|
-
if (!Array.isArray(runtime.env)) {
|
|
11107
|
-
add2(issues, "contract.env_invalid", "runtime.env must be an array of secret REFERENCE names");
|
|
11108
|
-
} else {
|
|
11109
|
-
for (const reference of runtime.env) {
|
|
11110
|
-
if (typeof reference !== "string" || !new RegExp(ENV_REFERENCE_PATTERN).test(reference)) {
|
|
11111
|
-
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`);
|
|
11112
|
-
}
|
|
11113
|
-
}
|
|
11114
|
-
}
|
|
11115
|
-
}
|
|
11116
|
-
if (runtime.sandbox !== undefined && runtime.sandbox !== null && !SKILL_SANDBOX_MODES.includes(runtime.sandbox)) {
|
|
11117
|
-
add2(issues, "contract.sandbox_invalid", `runtime.sandbox must be one of: ${SKILL_SANDBOX_MODES.join(", ")}`);
|
|
11118
|
-
}
|
|
11119
|
-
if (runtime.system_deps !== undefined && runtime.system_deps !== null) {
|
|
11120
|
-
if (!Array.isArray(runtime.system_deps)) {
|
|
11121
|
-
add2(issues, "contract.system_deps_invalid", "runtime.system_deps must be an array");
|
|
11122
|
-
} else {
|
|
11123
|
-
for (const dep of runtime.system_deps) {
|
|
11124
|
-
if (!SKILL_SYSTEM_DEPS_ALLOWLIST.includes(dep)) {
|
|
11125
|
-
add2(issues, "contract.system_dep_not_allowed", `runtime.system_deps entry '${dep}' is not on the allowlist: ${SKILL_SYSTEM_DEPS_ALLOWLIST.join(", ")}`);
|
|
11126
|
-
}
|
|
11127
|
-
}
|
|
11128
|
-
}
|
|
11129
|
-
}
|
|
11130
|
-
if (runtime.artifacts !== undefined && runtime.artifacts !== null) {
|
|
11131
|
-
if (!Array.isArray(runtime.artifacts)) {
|
|
11132
|
-
add2(issues, "contract.artifacts_invalid", "runtime.artifacts must be an array of glob patterns");
|
|
11133
|
-
} else {
|
|
11134
|
-
for (const glob of runtime.artifacts) {
|
|
11135
|
-
if (!isNonEmptyString(glob)) {
|
|
11136
|
-
add2(issues, "contract.artifacts_invalid", "runtime.artifacts entries must be non-empty glob strings");
|
|
11137
|
-
}
|
|
11138
|
-
}
|
|
11139
|
-
}
|
|
11140
|
-
}
|
|
11141
|
-
}
|
|
11142
11074
|
var ANY_SEGMENT_COPY_EXCLUDES = new Set([
|
|
11143
11075
|
".git",
|
|
11144
11076
|
".DS_Store",
|
|
@@ -11828,14 +11760,14 @@ function captureClaudeMarketplaceEntry(path, marketplace, plugin, budget2 = { re
|
|
|
11828
11760
|
return { path, hashMode: CLAUDE_MARKETPLACE_ENTRY_HASH_MODE, marketplace, plugin, sha256: hashClaudeMarketplaceEntry(text, { marketplace, plugin }) };
|
|
11829
11761
|
}
|
|
11830
11762
|
var CLAUDE_ORPHAN_MARKER_MODE = "claude-plugin-orphaned-at-v1";
|
|
11831
|
-
var CACHE = `${
|
|
11763
|
+
var CACHE = `${sep2}.claude${sep2}plugins${sep2}cache${sep2}`;
|
|
11832
11764
|
function isClaudePluginCacheOrphanMarker(path) {
|
|
11833
|
-
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"))
|
|
11834
11766
|
return false;
|
|
11835
11767
|
const at = path.indexOf(CACHE);
|
|
11836
11768
|
if (at < 0 || path.indexOf(CACHE, at + 1) >= 0)
|
|
11837
11769
|
return false;
|
|
11838
|
-
const parts = path.slice(at + CACHE.length).split(
|
|
11770
|
+
const parts = path.slice(at + CACHE.length).split(sep2);
|
|
11839
11771
|
return parts.length === 4 && parts.every((part) => part && part !== "." && part !== "..");
|
|
11840
11772
|
}
|
|
11841
11773
|
function same(left, right) {
|
|
@@ -12284,10 +12216,10 @@ function assertHermesEnvironment(home) {
|
|
|
12284
12216
|
throw new Error("NATIVE_SKILL_DRIFT: Hermes project plugins require a dedicated discovery review");
|
|
12285
12217
|
}
|
|
12286
12218
|
function read(path) {
|
|
12287
|
-
for (let current2 = path;; current2 =
|
|
12219
|
+
for (let current2 = path;; current2 = dirname62(current2)) {
|
|
12288
12220
|
if (lstatSync6(current2, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
12289
12221
|
throw new Error("NATIVE_SKILL_DRIFT: symlink Hermes protection input");
|
|
12290
|
-
if (
|
|
12222
|
+
if (dirname62(current2) === current2)
|
|
12291
12223
|
break;
|
|
12292
12224
|
}
|
|
12293
12225
|
const stat = lstatSync6(path, { throwIfNoEntry: false });
|
|
@@ -12327,10 +12259,10 @@ function assertHermesProtection(home, config, command, profile, supervisor2) {
|
|
|
12327
12259
|
}
|
|
12328
12260
|
function assertNoHermesLegacyShadow(root) {
|
|
12329
12261
|
let entries = 0;
|
|
12330
|
-
for (let cursor = resolve6(root);; cursor =
|
|
12262
|
+
for (let cursor = resolve6(root);; cursor = dirname62(cursor)) {
|
|
12331
12263
|
if (lstatSync6(cursor, { throwIfNoEntry: false })?.isSymbolicLink())
|
|
12332
12264
|
throw new Error("NATIVE_SKILL_DRIFT: symlink Hermes legacy discovery root");
|
|
12333
|
-
if (
|
|
12265
|
+
if (dirname62(cursor) === cursor)
|
|
12334
12266
|
break;
|
|
12335
12267
|
}
|
|
12336
12268
|
function scan(path, depth) {
|
|
@@ -12447,7 +12379,7 @@ function capture(path, budget2, excludedRoots, omittedRoots = [], rows) {
|
|
|
12447
12379
|
if (!root)
|
|
12448
12380
|
return { path, sha256: null };
|
|
12449
12381
|
need3(root.isDirectory(), "Unsupported native discovery directory input");
|
|
12450
|
-
const hash =
|
|
12382
|
+
const hash = createHash6("sha256");
|
|
12451
12383
|
function walk(current2, relative2, before, depth) {
|
|
12452
12384
|
need3(depth <= 64, "Native discovery directory depth limit exceeded");
|
|
12453
12385
|
const names = [], directory = opendirSync2(current2);
|
|
@@ -12499,7 +12431,7 @@ function verifyDiscoveryDirectoryProjection(directories, omittedRoots, tolerance
|
|
|
12499
12431
|
const expected = directories.map((directory) => {
|
|
12500
12432
|
safe2(directory.path);
|
|
12501
12433
|
need3(Array.isArray(directory.entries), "Missing reviewed directory membership inventory");
|
|
12502
|
-
const hash =
|
|
12434
|
+
const hash = createHash6("sha256");
|
|
12503
12435
|
const kept = [];
|
|
12504
12436
|
for (const row of directory.entries) {
|
|
12505
12437
|
need3(typeof row === "string" && ++count <= AGENT_POLICY_LIMITS.discoveryDirectoryEntries, "Invalid reviewed directory membership rows");
|
|
@@ -12515,7 +12447,7 @@ function verifyDiscoveryDirectoryProjection(directories, omittedRoots, tolerance
|
|
|
12515
12447
|
}
|
|
12516
12448
|
need3(directory.sha256 === null ? directory.entries.length === 0 : hash.digest("hex") === directory.sha256, "Reviewed directory inventory does not match its fingerprint");
|
|
12517
12449
|
const absent = omittedRoots.some((root) => directory.path === root || directory.path.startsWith(root + "/"));
|
|
12518
|
-
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") };
|
|
12519
12451
|
});
|
|
12520
12452
|
const current2 = captureDiscoveryDirectoryProjection(directories.map((item) => item.path), omittedRoots);
|
|
12521
12453
|
for (let i = 0;i < current2.length; i++)
|
|
@@ -12603,7 +12535,6 @@ function hashRawDiscoveryFile(path, budget2, changes) {
|
|
|
12603
12535
|
closeSync4(fd);
|
|
12604
12536
|
}
|
|
12605
12537
|
}
|
|
12606
|
-
var BLOCK = 512;
|
|
12607
12538
|
var ANY_SEGMENT_EXCLUDES = new Set([
|
|
12608
12539
|
".git",
|
|
12609
12540
|
".ds_store",
|
|
@@ -12733,136 +12664,6 @@ var SKILL_BUNDLE_INSPECTION_LIMITS = Object.freeze({
|
|
|
12733
12664
|
pathBytes: 100,
|
|
12734
12665
|
timeoutMs: 5000
|
|
12735
12666
|
});
|
|
12736
|
-
|
|
12737
|
-
class SkillBundleInspectionError extends Error {
|
|
12738
|
-
code;
|
|
12739
|
-
constructor(code, message) {
|
|
12740
|
-
super(message);
|
|
12741
|
-
this.code = code;
|
|
12742
|
-
this.name = "SkillBundleInspectionError";
|
|
12743
|
-
}
|
|
12744
|
-
}
|
|
12745
|
-
function invalidBundle(message) {
|
|
12746
|
-
throw new SkillBundleInspectionError("BUNDLE_INVALID", message);
|
|
12747
|
-
}
|
|
12748
|
-
class BoundedTarReader {
|
|
12749
|
-
limits;
|
|
12750
|
-
check;
|
|
12751
|
-
header = new Uint8Array(BLOCK);
|
|
12752
|
-
headerOffset = 0;
|
|
12753
|
-
pending;
|
|
12754
|
-
bodyOffset = 0;
|
|
12755
|
-
padding = 0;
|
|
12756
|
-
zeroBlocks = 0;
|
|
12757
|
-
entries = [];
|
|
12758
|
-
paths = new SkillEntryPaths;
|
|
12759
|
-
fileBytes = 0;
|
|
12760
|
-
constructor(limits, check) {
|
|
12761
|
-
this.limits = limits;
|
|
12762
|
-
this.check = check;
|
|
12763
|
-
}
|
|
12764
|
-
push(chunk) {
|
|
12765
|
-
let offset = 0;
|
|
12766
|
-
while (offset < chunk.byteLength) {
|
|
12767
|
-
this.check();
|
|
12768
|
-
if (this.pending) {
|
|
12769
|
-
const count = Math.min(this.pending.bytes.byteLength - this.bodyOffset, chunk.byteLength - offset);
|
|
12770
|
-
this.pending.bytes.set(chunk.subarray(offset, offset + count), this.bodyOffset);
|
|
12771
|
-
offset += count;
|
|
12772
|
-
this.bodyOffset += count;
|
|
12773
|
-
if (this.bodyOffset === this.pending.bytes.byteLength) {
|
|
12774
|
-
this.entries.push(this.pending);
|
|
12775
|
-
this.pending = undefined;
|
|
12776
|
-
}
|
|
12777
|
-
} else if (this.padding) {
|
|
12778
|
-
const count = Math.min(this.padding, chunk.byteLength - offset);
|
|
12779
|
-
if (chunk.subarray(offset, offset + count).some((byte) => byte !== 0))
|
|
12780
|
-
invalidBundle("Nonzero tar body padding");
|
|
12781
|
-
offset += count;
|
|
12782
|
-
this.padding -= count;
|
|
12783
|
-
} else {
|
|
12784
|
-
const count = Math.min(BLOCK - this.headerOffset, chunk.byteLength - offset);
|
|
12785
|
-
this.header.set(chunk.subarray(offset, offset + count), this.headerOffset);
|
|
12786
|
-
offset += count;
|
|
12787
|
-
this.headerOffset += count;
|
|
12788
|
-
if (this.headerOffset === BLOCK) {
|
|
12789
|
-
this.readHeader();
|
|
12790
|
-
this.headerOffset = 0;
|
|
12791
|
-
}
|
|
12792
|
-
}
|
|
12793
|
-
}
|
|
12794
|
-
}
|
|
12795
|
-
finish() {
|
|
12796
|
-
this.check();
|
|
12797
|
-
if (this.pending || this.padding || this.headerOffset || this.zeroBlocks < 2)
|
|
12798
|
-
invalidBundle("Truncated tar bundle");
|
|
12799
|
-
return this.entries;
|
|
12800
|
-
}
|
|
12801
|
-
readHeader() {
|
|
12802
|
-
this.check();
|
|
12803
|
-
const h = this.header;
|
|
12804
|
-
if (h.every((byte) => byte === 0)) {
|
|
12805
|
-
this.zeroBlocks++;
|
|
12806
|
-
return;
|
|
12807
|
-
}
|
|
12808
|
-
if (this.zeroBlocks)
|
|
12809
|
-
invalidBundle("Nonzero tar data after terminator");
|
|
12810
|
-
if (this.entries.length >= this.limits.entries)
|
|
12811
|
-
throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle entry limit exceeded");
|
|
12812
|
-
let checksum = 0;
|
|
12813
|
-
for (let i = 0;i < BLOCK; i++)
|
|
12814
|
-
checksum += i >= 148 && i < 156 ? 32 : h[i];
|
|
12815
|
-
if (tarOctal(h.subarray(148, 156)) !== checksum)
|
|
12816
|
-
invalidBundle("Invalid tar header checksum");
|
|
12817
|
-
if (new TextDecoder().decode(h.subarray(257, 265)) !== "ustar\x00" + "00")
|
|
12818
|
-
invalidBundle("Unsupported tar format");
|
|
12819
|
-
if (h[156] !== 48 && h[156] !== 0 || h.subarray(157, 257).some((b) => b !== 0) || h.subarray(345).some((b) => b !== 0))
|
|
12820
|
-
invalidBundle("Unsupported tar entry or path prefix");
|
|
12821
|
-
const mode = tarOctal(h.subarray(100, 108));
|
|
12822
|
-
if (mode > 511)
|
|
12823
|
-
invalidBundle("Unsupported tar permission bits");
|
|
12824
|
-
tarOctal(h.subarray(108, 116));
|
|
12825
|
-
tarOctal(h.subarray(116, 124));
|
|
12826
|
-
tarOctal(h.subarray(136, 148));
|
|
12827
|
-
const size = tarOctal(h.subarray(124, 136));
|
|
12828
|
-
if (size > this.limits.fileBytes || this.fileBytes + size > this.limits.decompressedBytes) {
|
|
12829
|
-
throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle file byte limit exceeded");
|
|
12830
|
-
}
|
|
12831
|
-
const name = h.subarray(0, 100);
|
|
12832
|
-
const end = name.indexOf(0);
|
|
12833
|
-
if (end !== -1 && name.subarray(end).some((b) => b !== 0))
|
|
12834
|
-
invalidBundle("Invalid tar path padding");
|
|
12835
|
-
const raw = end === -1 ? name : name.subarray(0, end);
|
|
12836
|
-
if (raw.byteLength > this.limits.pathBytes)
|
|
12837
|
-
throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle path byte limit exceeded");
|
|
12838
|
-
let path;
|
|
12839
|
-
try {
|
|
12840
|
-
path = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(raw);
|
|
12841
|
-
} catch {
|
|
12842
|
-
return invalidBundle("Invalid UTF-8 bundle path");
|
|
12843
|
-
}
|
|
12844
|
-
this.paths.add(path, this.limits.pathBytes, invalidBundle, () => {
|
|
12845
|
-
throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle path byte limit exceeded");
|
|
12846
|
-
});
|
|
12847
|
-
this.fileBytes += size;
|
|
12848
|
-
this.pending = { path, mode, bytes: new Uint8Array(new ArrayBuffer(size)) };
|
|
12849
|
-
this.bodyOffset = 0;
|
|
12850
|
-
this.padding = (BLOCK - size % BLOCK) % BLOCK;
|
|
12851
|
-
if (!size) {
|
|
12852
|
-
this.entries.push(this.pending);
|
|
12853
|
-
this.pending = undefined;
|
|
12854
|
-
}
|
|
12855
|
-
}
|
|
12856
|
-
}
|
|
12857
|
-
function tarOctal(field2) {
|
|
12858
|
-
const text2 = new TextDecoder().decode(field2);
|
|
12859
|
-
if (!/^[0-7]+[\0 ]*$/.test(text2))
|
|
12860
|
-
invalidBundle("Invalid tar octal field");
|
|
12861
|
-
const value = Number.parseInt(text2, 8);
|
|
12862
|
-
if (!Number.isSafeInteger(value))
|
|
12863
|
-
invalidBundle("Tar integer is out of range");
|
|
12864
|
-
return value;
|
|
12865
|
-
}
|
|
12866
12667
|
var SKILL_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
|
|
12867
12668
|
function isValidSkillVersion(value) {
|
|
12868
12669
|
return typeof value === "string" && SKILL_VERSION_PATTERN.test(value) && !/^\.+$/.test(value) && !value.includes("..");
|
|
@@ -16089,50 +15890,6 @@ var SKILLS_API_URL_ENV_KEYS = ENV_KEYS.apiUrlKeys;
|
|
|
16089
15890
|
var SKILLS_API_KEY_ENV_KEYS = ENV_KEYS.apiKeyKeys;
|
|
16090
15891
|
var SKILLS_API_URL_ENV = SKILLS_API_URL_ENV_KEYS[0];
|
|
16091
15892
|
var SKILLS_API_KEY_ENV = SKILLS_API_KEY_ENV_KEYS[0];
|
|
16092
|
-
|
|
16093
|
-
class SkillsFleetCredentialError extends Error {
|
|
16094
|
-
code;
|
|
16095
|
-
next;
|
|
16096
|
-
constructor(message, code = "MISSING_API_CREDENTIAL", next) {
|
|
16097
|
-
super(message);
|
|
16098
|
-
this.name = "SkillsFleetCredentialError";
|
|
16099
|
-
this.code = code;
|
|
16100
|
-
if (next)
|
|
16101
|
-
this.next = next;
|
|
16102
|
-
}
|
|
16103
|
-
}
|
|
16104
|
-
function normalizeSkillsApiOrigin(apiUrl) {
|
|
16105
|
-
const url = new URL(apiUrl);
|
|
16106
|
-
if (url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
|
|
16107
|
-
throw new SkillsFleetCredentialError("A Skills API URL must use HTTPS (or loopback HTTP), without credentials, query or fragment", "INVALID_API_URL");
|
|
16108
|
-
}
|
|
16109
|
-
const pathname = url.pathname.replace(/\/+$/, "");
|
|
16110
|
-
if (url.origin === "https://api.hasna.com" && pathname === "/skills/v1") {
|
|
16111
|
-
url.pathname = "/skills";
|
|
16112
|
-
} else if (pathname === "/api" || pathname === "/api/v1") {
|
|
16113
|
-
url.pathname = "/";
|
|
16114
|
-
} else if (pathname.endsWith("/api/v1")) {
|
|
16115
|
-
url.pathname = pathname.slice(0, -"/api/v1".length) || "/";
|
|
16116
|
-
} else if (pathname.endsWith("/api")) {
|
|
16117
|
-
url.pathname = pathname.slice(0, -"/api".length) || "/";
|
|
16118
|
-
}
|
|
16119
|
-
return url.toString().replace(/\/+$/, "");
|
|
16120
|
-
}
|
|
16121
|
-
function skillsApiRequestUrl(apiUrl, route) {
|
|
16122
|
-
const origin = normalizeSkillsApiOrigin(apiUrl);
|
|
16123
|
-
if (!route.startsWith("/api/") || route.includes("#") || route.includes("\\")) {
|
|
16124
|
-
throw new SkillsFleetCredentialError("Invalid Skills API route", "INVALID_API_URL");
|
|
16125
|
-
}
|
|
16126
|
-
if (origin === "https://api.hasna.com/skills") {
|
|
16127
|
-
if (route === "/api/auth/whoami")
|
|
16128
|
-
return `${origin}/v1/auth/whoami`;
|
|
16129
|
-
if (!route.startsWith("/api/v1/")) {
|
|
16130
|
-
throw new SkillsFleetCredentialError("The internal Skills gateway has no established login contract yet. Select an explicitly configured instance with supported authentication.", "GATEWAY_AUTH_UNAVAILABLE");
|
|
16131
|
-
}
|
|
16132
|
-
return `${origin}${route.slice("/api".length)}`;
|
|
16133
|
-
}
|
|
16134
|
-
return `${origin}${route}`;
|
|
16135
|
-
}
|
|
16136
15893
|
var MAX_REMOTE_FILE_BYTES = 64 * 1024 * 1024;
|
|
16137
15894
|
var CODEX_NATIVE_POLICY_CAPABILITY = "host-path-allowlist-v1";
|
|
16138
15895
|
var CODEX_NATIVE_POLICY_RECEIPT_SCHEMA = "skills.codex-native-policy-acceptance/v1";
|
|
@@ -40052,46 +39809,6 @@ var revocation = exports_external.object({
|
|
|
40052
39809
|
});
|
|
40053
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() });
|
|
40054
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 };
|
|
40055
|
-
var record7 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
40056
|
-
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);
|
|
40057
|
-
var text2 = (v, max = 1024) => typeof v === "string" && !!v.trim() && v.length <= max && !/[\p{Cc}\p{Cs}\u2028\u2029]/u.test(v);
|
|
40058
|
-
var role2 = (v) => typeof v === "string" && ["owner", "admin", "member", "viewer"].includes(v);
|
|
40059
|
-
var invalidWorkspaceResult = "The server returned an invalid workspace selection result.";
|
|
40060
|
-
class WorkspaceIdentityMismatchError extends Error {
|
|
40061
|
-
constructor() {
|
|
40062
|
-
super("The verified account does not match the requested workspace context.");
|
|
40063
|
-
this.name = "WorkspaceIdentityMismatchError";
|
|
40064
|
-
}
|
|
40065
|
-
}
|
|
40066
|
-
function invalid3() {
|
|
40067
|
-
throw new Error(invalidWorkspaceResult);
|
|
40068
|
-
}
|
|
40069
|
-
function organization(v) {
|
|
40070
|
-
if (!record7(v) || !uuid8(v.id) || !text2(v.slug) || !text2(v.name))
|
|
40071
|
-
return invalid3();
|
|
40072
|
-
return { id: v.id, slug: v.slug, name: v.name };
|
|
40073
|
-
}
|
|
40074
|
-
function parseWorkspaceIdentity(value, expectedUserId) {
|
|
40075
|
-
if (!record7(value))
|
|
40076
|
-
return invalid3();
|
|
40077
|
-
const user = value.user;
|
|
40078
|
-
if (!record7(user) || !uuid8(user.id) || !uuid8(user.membershipId) || !text2(user.email, 320) || !(user.displayName === null || text2(user.displayName)) || !role2(user.role))
|
|
40079
|
-
return invalid3();
|
|
40080
|
-
if (user.id !== expectedUserId)
|
|
40081
|
-
throw new WorkspaceIdentityMismatchError;
|
|
40082
|
-
return { user: { id: user.id, membershipId: user.membershipId, email: user.email, displayName: user.displayName, role: user.role }, organization: organization(value.organization) };
|
|
40083
|
-
}
|
|
40084
|
-
function sessionToken(value) {
|
|
40085
|
-
if (typeof value !== "string" || !value || value.length > 8192 || /[^\x21-\x7e]/.test(value) || value.startsWith("sk_"))
|
|
40086
|
-
return invalid3();
|
|
40087
|
-
return value;
|
|
40088
|
-
}
|
|
40089
|
-
function parseWorkspaceSession(value, expected) {
|
|
40090
|
-
const identity5 = parseWorkspaceIdentity(value, expected.userId);
|
|
40091
|
-
if (identity5.user.membershipId !== expected.membershipId)
|
|
40092
|
-
throw new WorkspaceIdentityMismatchError;
|
|
40093
|
-
return { token: sessionToken(value.token), ...identity5 };
|
|
40094
|
-
}
|
|
40095
39812
|
var SKILLS_API_KEY_REF = credentialPointerEnvKey("skills");
|
|
40096
39813
|
var quoteUnavailableMessages = Object.freeze({
|
|
40097
39814
|
HOSTED_PROVIDER_UNAVAILABLE: "Hosted execution is temporarily unavailable on this Skills instance.",
|
|
@@ -40103,353 +39820,6 @@ var quoteUnavailableMessages = Object.freeze({
|
|
|
40103
39820
|
});
|
|
40104
39821
|
var KNOWN_SKILL_LIFECYCLE_CODES = new Set(["SKILL_ARCHIVE_PROFILE_CONFLICT", "LIFECYCLE_ROLE_REQUIRED"]);
|
|
40105
39822
|
var PRIVATE_PUBLICATION_MAX_BYTES = 16 * 1024 * 1024;
|
|
40106
|
-
var skillCreateFailures = {
|
|
40107
|
-
INVALID_SLUG: [400, "Provide a lowercase kebab-case skill slug."],
|
|
40108
|
-
INVALID_DISPLAY_NAME: [400, "Provide a nonempty skill display name."],
|
|
40109
|
-
INVALID_VISIBILITY: [400, "Use private or team visibility for source publication."],
|
|
40110
|
-
SESSION_EXPIRED: [401, "Sign in again before creating a private skill."],
|
|
40111
|
-
INTERACTIVE_SESSION_REQUIRED: [403, "An interactive account session is required to create a private skill."],
|
|
40112
|
-
ACCOUNT_UNAVAILABLE: [403, "The current account membership cannot create a private skill."],
|
|
40113
|
-
PLAN_REQUIRED: [403, "Private and team skills require the Pro plan."],
|
|
40114
|
-
SLUG_CONFLICT: [409, "This skill slug already exists. Inspect the existing skill before publishing."]
|
|
40115
|
-
};
|
|
40116
|
-
var failures2 = {
|
|
40117
|
-
INVALID_REQUEST: [400, "The publication request is invalid."],
|
|
40118
|
-
SESSION_EXPIRED: [401, "Sign in again to manage this publication."],
|
|
40119
|
-
ACCOUNT_UNAVAILABLE: [403, "The account is unavailable."],
|
|
40120
|
-
INTERACTIVE_SESSION_REQUIRED: [403, "An interactive account session is required."],
|
|
40121
|
-
PUBLICATION_FORBIDDEN: [403, "This session cannot manage the publication."],
|
|
40122
|
-
PUBLICATION_ENTITLEMENT_REQUIRED: [403, "The workspace is not entitled to publish private skills."],
|
|
40123
|
-
PUBLICATION_UNAVAILABLE: [404, "The publication is unavailable to this session."],
|
|
40124
|
-
MANIFEST_NAME_MISMATCH: [409, "The manifest name does not match the selected skill."],
|
|
40125
|
-
IDEMPOTENCY_CONFLICT: [409, "This request key already identifies different publication bytes. Use the saved recovery directory."],
|
|
40126
|
-
CURRENT_VERSION_CHANGED: [409, "The current version changed. Inspect it before explicitly starting another publication."],
|
|
40127
|
-
VERSION_EXISTS: [409, "This version already exists."],
|
|
40128
|
-
VERSION_RESERVED: [409, "This version is reserved by another publication."],
|
|
40129
|
-
PUBLICATION_COMMITTED: [409, "The publication is already committed."],
|
|
40130
|
-
PUBLICATION_UPLOAD_UNAVAILABLE: [409, "This publication cannot receive another upload."],
|
|
40131
|
-
PUBLICATION_LIMIT: [429, "The workspace publication limit has been reached."],
|
|
40132
|
-
PUBLICATION_BUSY: [503, "The publication is busy. Reconcile the saved intent before retrying."],
|
|
40133
|
-
PUBLICATION_UNCERTAIN: [503, "The publication outcome is uncertain. Reconcile the saved intent."],
|
|
40134
|
-
PUBLICATION_CAPABILITY_UNAVAILABLE: [503, "Private publishing is not enabled on this server."],
|
|
40135
|
-
PUBLICATION_SIGNING_UNAVAILABLE: [503, "Upload authorization is temporarily unavailable. Keep the same intent."]
|
|
40136
|
-
};
|
|
40137
|
-
|
|
40138
|
-
class PrivatePublicationError extends Error {
|
|
40139
|
-
code;
|
|
40140
|
-
uncertain;
|
|
40141
|
-
status;
|
|
40142
|
-
constructor(code, message, uncertain = false, status) {
|
|
40143
|
-
super(message);
|
|
40144
|
-
this.code = code;
|
|
40145
|
-
this.uncertain = uncertain;
|
|
40146
|
-
this.status = status;
|
|
40147
|
-
this.name = "PrivatePublicationError";
|
|
40148
|
-
}
|
|
40149
|
-
}
|
|
40150
|
-
var bad = () => {
|
|
40151
|
-
throw new PrivatePublicationError("INVALID_PUBLICATION_INPUT", "Invalid publication input or recovery data.");
|
|
40152
|
-
};
|
|
40153
|
-
var invalid4 = () => {
|
|
40154
|
-
throw new PrivatePublicationError("INVALID_PUBLICATION_RESPONSE", "The server returned an invalid publication result.");
|
|
40155
|
-
};
|
|
40156
|
-
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);
|
|
40157
|
-
var hash4 = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
|
|
40158
|
-
var record11 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
40159
|
-
var exact = (v, keys2) => record11(v) && Object.keys(v).sort().join(",") === keys2.sort().join(",");
|
|
40160
|
-
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));
|
|
40161
|
-
var publicationSha256 = (bytes) => createHash34("sha256").update(bytes).digest("hex");
|
|
40162
|
-
function checkedPrivateSkillCreate(value) {
|
|
40163
|
-
const refuse6 = (field3, accepted) => {
|
|
40164
|
-
throw new PrivatePublicationError("INVALID_SKILL_CREATE_INPUT", `Invalid ${field3}. ${accepted}`);
|
|
40165
|
-
};
|
|
40166
|
-
if (!record11(value) || !Object.keys(value).every((key2) => ["slug", "displayName", "description", "visibility", "confirm"].includes(key2)))
|
|
40167
|
-
return refuse6("create input", "Provide only slug, displayName, description, visibility and confirm.");
|
|
40168
|
-
if (value.confirm !== true)
|
|
40169
|
-
throw new PrivatePublicationError("SKILL_CREATE_CONFIRM_REQUIRED", "Explicit confirmation is required to create this skill.");
|
|
40170
|
-
if (typeof value.slug !== "string" || value.slug.length > 128 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value.slug))
|
|
40171
|
-
return refuse6("slug", "Use lowercase kebab-case, at most 128 characters.");
|
|
40172
|
-
if (typeof value.displayName !== "string" || !value.displayName.trim() || value.displayName.length > 256 || /[\p{Cc}\p{Cs}\u2028\u2029]/u.test(value.displayName))
|
|
40173
|
-
return refuse6("displayName", "Use nonempty text, at most 256 characters, without control characters.");
|
|
40174
|
-
if (value.description !== undefined && (typeof value.description !== "string" || Buffer.byteLength(value.description) > 8192 || /[\p{Cc}\p{Cs}]/u.test(value.description.replace(/[\r\n\t]/g, ""))))
|
|
40175
|
-
return refuse6("description", "Use text of at most 8192 UTF-8 bytes, without control characters other than tabs and newlines.");
|
|
40176
|
-
if (value.visibility !== undefined && value.visibility !== "private" && value.visibility !== "team")
|
|
40177
|
-
return refuse6("visibility", "Use private or team.");
|
|
40178
|
-
return Object.freeze({ slug: value.slug, displayName: value.displayName.trim(), description: value.description ?? "", visibility: value.visibility ?? "private" });
|
|
40179
|
-
}
|
|
40180
|
-
function checkedPublicationDeclaration(value) {
|
|
40181
|
-
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)
|
|
40182
|
-
return bad();
|
|
40183
|
-
try {
|
|
40184
|
-
const manifest = JSON.parse(value.manifestText);
|
|
40185
|
-
if (!record11(manifest) || manifest.version !== value.version || validatePortableManifestContract(manifest, { strict: true }).length || !hash4(manifest.provenance?.content_hash))
|
|
40186
|
-
return bad();
|
|
40187
|
-
} catch {
|
|
40188
|
-
return bad();
|
|
40189
|
-
}
|
|
40190
|
-
return Object.freeze({ ...value });
|
|
40191
|
-
}
|
|
40192
|
-
function checkedPublicationView(value, skillId, intentId, declaration) {
|
|
40193
|
-
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)
|
|
40194
|
-
return invalid4();
|
|
40195
|
-
if (declaration && ["version", "expectedCurrentVersionId", "archiveSha256", "archiveByteSize"].some((k) => value[k] !== declaration[k]))
|
|
40196
|
-
return invalid4();
|
|
40197
|
-
return Object.freeze({ ...value });
|
|
40198
|
-
}
|
|
40199
|
-
async function boundedJson(url2, init, token, mutation, budget3 = 15000, signal, create = false) {
|
|
40200
|
-
const controller = new AbortController;
|
|
40201
|
-
let reader;
|
|
40202
|
-
let response;
|
|
40203
|
-
const timeout2 = new PrivatePublicationError(create ? "SKILL_CREATE_UNCONFIRMED" : "PUBLICATION_UNCONFIRMED", create ? "Skill creation could not be confirmed. Inspect the workspace for this slug before another create; do not retry automatically." : "No confirmed publication result. Inspect the saved intent before retrying.", mutation);
|
|
40204
|
-
let timer;
|
|
40205
|
-
let abort;
|
|
40206
|
-
try {
|
|
40207
|
-
return await Promise.race([(async () => {
|
|
40208
|
-
if (signal?.aborted)
|
|
40209
|
-
throw timeout2;
|
|
40210
|
-
response = await fetch(url2, {
|
|
40211
|
-
...init,
|
|
40212
|
-
redirect: "error",
|
|
40213
|
-
credentials: "omit",
|
|
40214
|
-
signal: controller.signal,
|
|
40215
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }
|
|
40216
|
-
});
|
|
40217
|
-
const length = response.headers.get("content-length");
|
|
40218
|
-
if (length !== null && (!/^\d+$/.test(length) || Number(length) > 65536))
|
|
40219
|
-
return invalid4();
|
|
40220
|
-
reader = response.body?.getReader();
|
|
40221
|
-
const chunks = [];
|
|
40222
|
-
let size = 0;
|
|
40223
|
-
if (reader)
|
|
40224
|
-
while (true) {
|
|
40225
|
-
const part = await reader.read();
|
|
40226
|
-
if (part.done)
|
|
40227
|
-
break;
|
|
40228
|
-
size += part.value.byteLength;
|
|
40229
|
-
if (size > 65536)
|
|
40230
|
-
return invalid4();
|
|
40231
|
-
chunks.push(part.value);
|
|
40232
|
-
}
|
|
40233
|
-
if (controller.signal.aborted)
|
|
40234
|
-
throw timeout2;
|
|
40235
|
-
const bytes = Buffer.concat(chunks);
|
|
40236
|
-
let body;
|
|
40237
|
-
try {
|
|
40238
|
-
body = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
40239
|
-
} catch {
|
|
40240
|
-
return invalid4();
|
|
40241
|
-
}
|
|
40242
|
-
if (!response.ok) {
|
|
40243
|
-
const known = create ? skillCreateFailures : failures2;
|
|
40244
|
-
const code = record11(body) && typeof body.code === "string" && Object.hasOwn(known, body.code) ? body.code : null;
|
|
40245
|
-
if (code && known[code][0] === response.status)
|
|
40246
|
-
throw new PrivatePublicationError(code, known[code][1], mutation && code === "PUBLICATION_UNCERTAIN", response.status);
|
|
40247
|
-
if (create) {
|
|
40248
|
-
if (response.status >= 500)
|
|
40249
|
-
throw timeout2;
|
|
40250
|
-
throw new PrivatePublicationError("SKILL_CREATE_REQUEST_FAILED", "The server refused skill creation.", false, response.status);
|
|
40251
|
-
}
|
|
40252
|
-
throw new PrivatePublicationError("PUBLICATION_REQUEST_FAILED", "The publication request was refused. Inspect its status before retrying.", mutation && response.status >= 500, response.status);
|
|
40253
|
-
}
|
|
40254
|
-
if (create && response.status !== 201)
|
|
40255
|
-
return invalid4();
|
|
40256
|
-
return body;
|
|
40257
|
-
})(), new Promise((_, reject) => {
|
|
40258
|
-
abort = () => {
|
|
40259
|
-
controller.abort();
|
|
40260
|
-
reject(timeout2);
|
|
40261
|
-
};
|
|
40262
|
-
timer = setTimeout(abort, Math.max(1, Math.min(15000, budget3)));
|
|
40263
|
-
signal?.addEventListener("abort", abort, { once: true });
|
|
40264
|
-
})]);
|
|
40265
|
-
} catch (error61) {
|
|
40266
|
-
if (error61 instanceof PrivatePublicationError) {
|
|
40267
|
-
if (mutation && error61.code === "INVALID_PUBLICATION_RESPONSE")
|
|
40268
|
-
throw timeout2;
|
|
40269
|
-
throw error61;
|
|
40270
|
-
}
|
|
40271
|
-
throw timeout2;
|
|
40272
|
-
} finally {
|
|
40273
|
-
if (timer)
|
|
40274
|
-
clearTimeout(timer);
|
|
40275
|
-
if (abort)
|
|
40276
|
-
signal?.removeEventListener("abort", abort);
|
|
40277
|
-
controller.abort();
|
|
40278
|
-
if (reader)
|
|
40279
|
-
reader.cancel().catch(() => {});
|
|
40280
|
-
else
|
|
40281
|
-
response?.body?.cancel().catch(() => {});
|
|
40282
|
-
}
|
|
40283
|
-
}
|
|
40284
|
-
|
|
40285
|
-
class RemotePrivatePublicationsClient {
|
|
40286
|
-
apiOrigin;
|
|
40287
|
-
organizationId;
|
|
40288
|
-
userId;
|
|
40289
|
-
membershipId;
|
|
40290
|
-
#token;
|
|
40291
|
-
constructor(apiUrl, session) {
|
|
40292
|
-
const checked = parseWorkspaceSession(session, { userId: session?.user?.id, membershipId: session?.user?.membershipId });
|
|
40293
|
-
if (checked.user.role === "viewer")
|
|
40294
|
-
throw new PrivatePublicationError("PUBLICATION_FORBIDDEN", failures2.PUBLICATION_FORBIDDEN[1]);
|
|
40295
|
-
this.apiOrigin = normalizeSkillsApiOrigin(apiUrl);
|
|
40296
|
-
this.#token = checked.token;
|
|
40297
|
-
this.organizationId = checked.organization.id;
|
|
40298
|
-
this.userId = checked.user.id;
|
|
40299
|
-
this.membershipId = checked.user.membershipId;
|
|
40300
|
-
Object.freeze(this);
|
|
40301
|
-
}
|
|
40302
|
-
async createSkill(input2, options = {}) {
|
|
40303
|
-
const body = checkedPrivateSkillCreate(input2);
|
|
40304
|
-
if (options.timeoutMs !== undefined && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 15000))
|
|
40305
|
-
throw new PrivatePublicationError("INVALID_SKILL_CREATE_INPUT", "Invalid timeoutMs. Use an integer from 1 to 15000.");
|
|
40306
|
-
const value = await boundedJson(skillsApiRequestUrl(this.apiOrigin, "/api/v1/skills"), { method: "POST", body: JSON.stringify(body) }, this.#token, true, options.timeoutMs, options.signal, true);
|
|
40307
|
-
if (!record11(value) || !publicationUuid(value.id) || value.slug !== body.slug || value.displayName !== body.displayName || value.description !== body.description || value.visibility !== body.visibility || value.sourceType !== "private_hosted" || !record11(value.metadata) || value.metadata.ownerOrganizationId !== this.organizationId)
|
|
40308
|
-
throw new PrivatePublicationError("SKILL_CREATE_UNCONFIRMED", "Skill creation returned an unbound result. Inspect the workspace for this slug before another create; do not retry automatically.", true);
|
|
40309
|
-
return Object.freeze({ id: value.id, slug: body.slug, visibility: body.visibility, sourceType: "private_hosted", ownerOrganizationId: this.organizationId });
|
|
40310
|
-
}
|
|
40311
|
-
async getCapability(options = {}) {
|
|
40312
|
-
if (options.timeoutMs !== undefined && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 15000))
|
|
40313
|
-
return bad();
|
|
40314
|
-
const response = await boundedJson(skillsApiRequestUrl(this.apiOrigin, "/api/v1/capabilities"), {}, this.#token, false, options.timeoutMs, options.signal);
|
|
40315
|
-
const p = record11(response) && response.privatePublishing;
|
|
40316
|
-
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")
|
|
40317
|
-
throw new PrivatePublicationError("PUBLICATION_CONTRACT_UNAVAILABLE", "This server does not support the hosted private publication contract.");
|
|
40318
|
-
return Object.freeze({ ...p });
|
|
40319
|
-
}
|
|
40320
|
-
async#gate(enabled, options = {}) {
|
|
40321
|
-
if (!(await this.getCapability(options)).enabled && enabled)
|
|
40322
|
-
throw new PrivatePublicationError("PUBLICATION_CAPABILITY_UNAVAILABLE", failures2.PUBLICATION_CAPABILITY_UNAVAILABLE[1]);
|
|
40323
|
-
}
|
|
40324
|
-
#path(skillId, intentId) {
|
|
40325
|
-
if (!publicationUuid(skillId) || intentId !== undefined && !publicationUuid(intentId))
|
|
40326
|
-
return bad();
|
|
40327
|
-
return skillsApiRequestUrl(this.apiOrigin, `/api/v1/skills/${skillId}/publication-uploads${intentId ? `/${intentId}` : ""}`);
|
|
40328
|
-
}
|
|
40329
|
-
async#view(path, method, skillId, intentId, declaration, options = {}) {
|
|
40330
|
-
const value = await boundedJson(path, { method, ...method === "GET" ? {} : { body: JSON.stringify(declaration ?? {}) } }, this.#token, method !== "GET", options.timeoutMs, options.signal);
|
|
40331
|
-
try {
|
|
40332
|
-
if (!record11(value) || !Object.keys(value).every((k) => k === "upload" || k === "changed") || value.changed !== undefined && typeof value.changed !== "boolean")
|
|
40333
|
-
return invalid4();
|
|
40334
|
-
return checkedPublicationView(value.upload, skillId, intentId, declaration);
|
|
40335
|
-
} catch (error61) {
|
|
40336
|
-
if (method !== "GET")
|
|
40337
|
-
throw new PrivatePublicationError("PUBLICATION_UNCONFIRMED", "The publication result could not be confirmed. Reconcile the saved intent before another action.", true);
|
|
40338
|
-
throw error61;
|
|
40339
|
-
}
|
|
40340
|
-
}
|
|
40341
|
-
async begin(skillId, input2) {
|
|
40342
|
-
const path = this.#path(skillId), declaration = checkedPublicationDeclaration(input2);
|
|
40343
|
-
await this.#gate(true);
|
|
40344
|
-
return this.#view(path, "POST", skillId, undefined, declaration);
|
|
40345
|
-
}
|
|
40346
|
-
async get(skillId, intentId, options = {}) {
|
|
40347
|
-
const path = this.#path(skillId, intentId), until = Date.now() + (options.timeoutMs ?? 15000);
|
|
40348
|
-
await this.#gate(false, options);
|
|
40349
|
-
return this.#view(path, "GET", skillId, intentId, undefined, { ...options, timeoutMs: Math.max(1, until - Date.now()) });
|
|
40350
|
-
}
|
|
40351
|
-
async finalize(skillId, intentId) {
|
|
40352
|
-
const path = this.#path(skillId, intentId);
|
|
40353
|
-
await this.#gate(true);
|
|
40354
|
-
return this.#view(`${path}/finalize`, "POST", skillId, intentId);
|
|
40355
|
-
}
|
|
40356
|
-
async cancel(skillId, intentId) {
|
|
40357
|
-
const path = this.#path(skillId, intentId);
|
|
40358
|
-
await this.#gate(false);
|
|
40359
|
-
return this.#view(path, "DELETE", skillId, intentId);
|
|
40360
|
-
}
|
|
40361
|
-
async upload(skillId, intent, bytes) {
|
|
40362
|
-
const captured = checkedPublicationView(intent, skillId), path = this.#path(skillId, captured.id);
|
|
40363
|
-
if (!(bytes instanceof Uint8Array) || bytes.byteLength !== captured.archiveByteSize)
|
|
40364
|
-
return bad();
|
|
40365
|
-
const owned = Buffer.from(bytes);
|
|
40366
|
-
if (captured.state !== "awaiting_upload" || owned.byteLength !== captured.archiveByteSize || publicationSha256(owned) !== captured.archiveSha256)
|
|
40367
|
-
return bad();
|
|
40368
|
-
await this.#gate(true);
|
|
40369
|
-
const value = await boundedJson(`${path}/upload-url`, { method: "POST", body: "{}" }, this.#token, false);
|
|
40370
|
-
const upload = this.#upload(value, captured);
|
|
40371
|
-
const controller = new AbortController;
|
|
40372
|
-
let timer;
|
|
40373
|
-
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);
|
|
40374
|
-
try {
|
|
40375
|
-
await Promise.race([(async () => {
|
|
40376
|
-
const response = await fetch(upload.uploadUrl, { method: "PUT", headers: upload.headers, body: owned, redirect: "error", credentials: "omit", signal: controller.signal });
|
|
40377
|
-
response.body?.cancel().catch(() => {});
|
|
40378
|
-
if (response.status !== 200 || controller.signal.aborted)
|
|
40379
|
-
throw uncertain();
|
|
40380
|
-
})(), new Promise((_, reject) => {
|
|
40381
|
-
timer = setTimeout(() => {
|
|
40382
|
-
controller.abort();
|
|
40383
|
-
reject(uncertain());
|
|
40384
|
-
}, 30000);
|
|
40385
|
-
})]);
|
|
40386
|
-
} catch {
|
|
40387
|
-
throw uncertain();
|
|
40388
|
-
} finally {
|
|
40389
|
-
if (timer)
|
|
40390
|
-
clearTimeout(timer);
|
|
40391
|
-
controller.abort();
|
|
40392
|
-
}
|
|
40393
|
-
}
|
|
40394
|
-
#upload(value, intent) {
|
|
40395
|
-
if (!exact(value, ["upload"]) || !exact(value.upload, ["method", "uploadUrl", "headers", "expiresAt"]))
|
|
40396
|
-
return invalid4();
|
|
40397
|
-
const p = value.upload;
|
|
40398
|
-
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"]))
|
|
40399
|
-
return invalid4();
|
|
40400
|
-
let url2;
|
|
40401
|
-
try {
|
|
40402
|
-
url2 = new URL(p.uploadUrl);
|
|
40403
|
-
} catch {
|
|
40404
|
-
return invalid4();
|
|
40405
|
-
}
|
|
40406
|
-
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") ?? ""))
|
|
40407
|
-
return invalid4();
|
|
40408
|
-
const queryKeys = ["X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date", "X-Amz-Expires", "X-Amz-Security-Token", "X-Amz-Signature", "X-Amz-SignedHeaders"];
|
|
40409
|
-
if ([...url2.searchParams.keys()].sort().join(",") !== queryKeys.sort().join(","))
|
|
40410
|
-
return invalid4();
|
|
40411
|
-
const issued = url2.searchParams.get("X-Amz-Date"), ttl = url2.searchParams.get("X-Amz-Expires"), credential = url2.searchParams.get("X-Amz-Credential");
|
|
40412
|
-
const timestamp3 = /^(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)Z$/.exec(issued);
|
|
40413
|
-
const region = url2.hostname.split(".s3.")[1].split(".amazonaws.com")[0];
|
|
40414
|
-
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")))
|
|
40415
|
-
return invalid4();
|
|
40416
|
-
const issuedAt = Date.parse(`${timestamp3[1]}-${timestamp3[2]}-${timestamp3[3]}T${timestamp3[4]}:${timestamp3[5]}:${timestamp3[6]}Z`);
|
|
40417
|
-
if (!Number.isFinite(issuedAt) || issuedAt > Date.now() + 1000 || issuedAt + Number(ttl) * 1000 !== Date.parse(p.expiresAt))
|
|
40418
|
-
return invalid4();
|
|
40419
|
-
return { method: "PUT", uploadUrl: url2.href, expiresAt: p.expiresAt, headers: Object.freeze({ ...p.headers }) };
|
|
40420
|
-
}
|
|
40421
|
-
async wait(skillId, intentId, options = {}) {
|
|
40422
|
-
const timeout2 = options.timeoutMs ?? 60000;
|
|
40423
|
-
if (!Number.isSafeInteger(timeout2) || timeout2 < 0 || timeout2 > 300000)
|
|
40424
|
-
return bad();
|
|
40425
|
-
const until = Date.now() + timeout2;
|
|
40426
|
-
let previous;
|
|
40427
|
-
while (true) {
|
|
40428
|
-
if (options.signal?.aborted)
|
|
40429
|
-
throw new PrivatePublicationError("PUBLICATION_WAIT_ABORTED", "Stopped waiting. The server publication continues; inspect the saved intent.");
|
|
40430
|
-
let view;
|
|
40431
|
-
try {
|
|
40432
|
-
view = await this.get(skillId, intentId, { timeoutMs: timeout2 === 0 ? 15000 : Math.max(1, Math.min(15000, until - Date.now())), signal: options.signal });
|
|
40433
|
-
} catch (error61) {
|
|
40434
|
-
if (previous && Date.now() >= until && !options.signal?.aborted)
|
|
40435
|
-
return previous;
|
|
40436
|
-
throw error61;
|
|
40437
|
-
}
|
|
40438
|
-
previous = view;
|
|
40439
|
-
if (!["queued", "verifying"].includes(view.state) || Date.now() >= until)
|
|
40440
|
-
return view;
|
|
40441
|
-
await new Promise((resolve30) => {
|
|
40442
|
-
const timer = setTimeout(done, Math.min(1000, until - Date.now()));
|
|
40443
|
-
function done() {
|
|
40444
|
-
clearTimeout(timer);
|
|
40445
|
-
options.signal?.removeEventListener("abort", done);
|
|
40446
|
-
resolve30();
|
|
40447
|
-
}
|
|
40448
|
-
options.signal?.addEventListener("abort", done, { once: true });
|
|
40449
|
-
});
|
|
40450
|
-
}
|
|
40451
|
-
}
|
|
40452
|
-
}
|
|
40453
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}$/);
|
|
40454
39824
|
var sha6 = exports_external.string().regex(/^[a-f0-9]{64}$/);
|
|
40455
39825
|
var common = exports_external.object({
|
|
@@ -41657,7 +41027,7 @@ function claudeSkillsUsage(before, home) {
|
|
|
41657
41027
|
}
|
|
41658
41028
|
if (events3.length)
|
|
41659
41029
|
evidence.push(`Skills-managed hook entries in ${events3.join(", ")}`);
|
|
41660
|
-
const bridge =
|
|
41030
|
+
const bridge = join17(home, ".claude", "skills", "skills-cli", "SKILL.md");
|
|
41661
41031
|
let bridgePresent;
|
|
41662
41032
|
try {
|
|
41663
41033
|
bridgePresent = lstatSync9(bridge, { throwIfNoEntry: false }) !== undefined;
|
|
@@ -41671,8 +41041,8 @@ function claudeSkillsUsage(before, home) {
|
|
|
41671
41041
|
function skillsPolicyLocations(dataDir3) {
|
|
41672
41042
|
const state = (path) => existsSync11(path) ? "present" : "absent";
|
|
41673
41043
|
if (dataDir3 !== undefined)
|
|
41674
|
-
return [`${
|
|
41675
|
-
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 = [];
|
|
41676
41046
|
let selected = false;
|
|
41677
41047
|
for (const key2 of ["HASNA_SKILLS_DIR", "HASNA_SKILLS_HOME", "SKILLS_HOME"]) {
|
|
41678
41048
|
const value = env[key2]?.trim();
|
|
@@ -41682,13 +41052,13 @@ function skillsPolicyLocations(dataDir3) {
|
|
|
41682
41052
|
searched.push(`$${key2} (unset)`);
|
|
41683
41053
|
else {
|
|
41684
41054
|
selected = true;
|
|
41685
|
-
searched.push(`$${key2} -> ${
|
|
41055
|
+
searched.push(`$${key2} -> ${join17(resolve9(value), "agent-policy.json")} (selected, absent)`);
|
|
41686
41056
|
}
|
|
41687
41057
|
}
|
|
41688
41058
|
const override = env.HASNA_DATA_HOME;
|
|
41689
|
-
const base = typeof override === "string" && override.length > 0 ? override : process.platform === "darwin" ?
|
|
41690
|
-
const xdg =
|
|
41691
|
-
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"));
|
|
41692
41062
|
if (selected)
|
|
41693
41063
|
searched.push(`${xdgPolicy} (not consulted, ${state(xdgPolicy)})`);
|
|
41694
41064
|
else if (adopted) {
|
|
@@ -41696,7 +41066,7 @@ function skillsPolicyLocations(dataDir3) {
|
|
|
41696
41066
|
searched.push(`${xdgPolicy} (selected, absent)`);
|
|
41697
41067
|
} else
|
|
41698
41068
|
searched.push(`${xdgPolicy} (not selected: the directory holds no server.db or config.json and HASNA_DATA_HOME is unset; ${state(xdgPolicy)})`);
|
|
41699
|
-
const legacy =
|
|
41069
|
+
const legacy = join17(home, ".hasna", "skills", "agent-policy.json");
|
|
41700
41070
|
searched.push(selected ? `${legacy} (not consulted, ${state(legacy)})` : `${legacy} (selected, absent)`);
|
|
41701
41071
|
return searched;
|
|
41702
41072
|
}
|
|
@@ -41714,7 +41084,7 @@ function planCoordinatedClaudeSettings(before, replacement, options) {
|
|
|
41714
41084
|
if (!plan) {
|
|
41715
41085
|
const usage = claudeSkillsUsage(before, options.home);
|
|
41716
41086
|
if (usage.length)
|
|
41717
|
-
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`.");
|
|
41718
41088
|
}
|
|
41719
41089
|
return plan;
|
|
41720
41090
|
}
|
|
@@ -41727,22 +41097,771 @@ function coordinateClaudeSettings(before, replacement, options, beforeWrite) {
|
|
|
41727
41097
|
return true;
|
|
41728
41098
|
}
|
|
41729
41099
|
|
|
41730
|
-
// src/lib/
|
|
41731
|
-
|
|
41732
|
-
|
|
41733
|
-
|
|
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;
|
|
41734
41119
|
}
|
|
41735
|
-
function
|
|
41736
|
-
|
|
41737
|
-
|
|
41738
|
-
|
|
41739
|
-
|
|
41740
|
-
|
|
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
|
+
}
|
|
41741
41860
|
}
|
|
41742
41861
|
|
|
41743
41862
|
// src/lib/installer.ts
|
|
41744
|
-
var __dirname2 =
|
|
41745
|
-
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");
|
|
41746
41865
|
function normalizeHookName(name) {
|
|
41747
41866
|
return name.startsWith("hook-") ? name : `hook-${name}`;
|
|
41748
41867
|
}
|
|
@@ -41759,17 +41878,19 @@ function removeHookEntriesByName(entries, hookName) {
|
|
|
41759
41878
|
return kept.length === entry.hooks.length ? [entry] : kept.length ? [{ ...entry, hooks: kept }] : [];
|
|
41760
41879
|
});
|
|
41761
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
|
+
};
|
|
41762
41891
|
var EVENT_MAP = {
|
|
41763
|
-
claude:
|
|
41764
|
-
|
|
41765
|
-
PostToolUse: "PostToolUse",
|
|
41766
|
-
Stop: "Stop",
|
|
41767
|
-
Notification: "Notification",
|
|
41768
|
-
SessionStart: "SessionStart",
|
|
41769
|
-
SessionEnd: "SessionEnd",
|
|
41770
|
-
UserPromptSubmit: "UserPromptSubmit",
|
|
41771
|
-
SubagentStart: null
|
|
41772
|
-
},
|
|
41892
|
+
claude: CLAUDE_EVENT_MAP,
|
|
41893
|
+
qwen: CLAUDE_EVENT_MAP,
|
|
41773
41894
|
gemini: {
|
|
41774
41895
|
PreToolUse: "BeforeTool",
|
|
41775
41896
|
PostToolUse: "AfterTool",
|
|
@@ -41801,15 +41922,6 @@ var EVENT_MAP = {
|
|
|
41801
41922
|
SubagentStart: "SubagentStart"
|
|
41802
41923
|
}
|
|
41803
41924
|
};
|
|
41804
|
-
function getTargetSettingsDir(target) {
|
|
41805
|
-
if (target === "codex")
|
|
41806
|
-
return ".codex";
|
|
41807
|
-
if (target === "codewith")
|
|
41808
|
-
return ".codewith";
|
|
41809
|
-
if (target === "gemini")
|
|
41810
|
-
return ".gemini";
|
|
41811
|
-
return ".claude";
|
|
41812
|
-
}
|
|
41813
41925
|
function getGlobalSettingsPathOverride(target) {
|
|
41814
41926
|
if (target === "codex")
|
|
41815
41927
|
return process.env.HASNA_HOOKS_CODEX_SETTINGS_PATH ?? (process.env.CODEX_HOME ? resolve28(process.env.CODEX_HOME, "hooks.json") : undefined);
|
|
@@ -41817,34 +41929,38 @@ function getGlobalSettingsPathOverride(target) {
|
|
|
41817
41929
|
return process.env.HASNA_HOOKS_CLAUDE_SETTINGS_PATH ?? (process.env.CLAUDE_CONFIG_DIR ? resolve28(process.env.CLAUDE_CONFIG_DIR, "settings.json") : undefined);
|
|
41818
41930
|
if (target === "gemini")
|
|
41819
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;
|
|
41820
41936
|
return;
|
|
41821
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
|
+
}
|
|
41822
41944
|
function getSettingsPath(scope = "global", target = "claude", codewithConfigPath) {
|
|
41823
41945
|
if (target === "codewith" && codewithConfigPath)
|
|
41824
41946
|
return codewithConfigPath;
|
|
41825
|
-
if (target === "codewith" && scope === "global" && process.env.HASNA_HOOKS_CODEWITH_CONFIG_PATH) {
|
|
41826
|
-
return process.env.HASNA_HOOKS_CODEWITH_CONFIG_PATH;
|
|
41827
|
-
}
|
|
41828
41947
|
const globalOverride = scope === "global" ? getGlobalSettingsPathOverride(target) : undefined;
|
|
41829
41948
|
if (globalOverride)
|
|
41830
41949
|
return globalOverride;
|
|
41831
|
-
const
|
|
41832
|
-
if (
|
|
41833
|
-
return
|
|
41834
|
-
|
|
41835
|
-
return target === "codewith" ? join17(process.cwd(), dir, "config.toml") : join17(process.cwd(), dir, "settings.json");
|
|
41836
|
-
}
|
|
41837
|
-
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");
|
|
41838
41954
|
}
|
|
41839
41955
|
function getHookPath(name) {
|
|
41840
41956
|
const shortName = shortHookName(name);
|
|
41841
41957
|
const resolved = resolveHookDir(shortName);
|
|
41842
41958
|
if (resolved)
|
|
41843
41959
|
return resolved;
|
|
41844
|
-
return
|
|
41960
|
+
return join24(HOOKS_DIR, normalizeHookName(shortName));
|
|
41845
41961
|
}
|
|
41846
41962
|
function hookExists(name) {
|
|
41847
|
-
return
|
|
41963
|
+
return existsSync14(getHookPath(name));
|
|
41848
41964
|
}
|
|
41849
41965
|
var settingsPreimages = new WeakMap;
|
|
41850
41966
|
var unreadableSettings = new WeakMap;
|
|
@@ -41854,14 +41970,14 @@ function readSettings(scope = "global", target = "claude") {
|
|
|
41854
41970
|
return readCodexSettings(path);
|
|
41855
41971
|
let reason2 = "cannot be read";
|
|
41856
41972
|
try {
|
|
41857
|
-
if (
|
|
41858
|
-
const
|
|
41973
|
+
if (existsSync14(path)) {
|
|
41974
|
+
const text2 = readFileSync13(path, "utf-8");
|
|
41859
41975
|
reason2 = "is not valid JSON";
|
|
41860
|
-
const value = JSON.parse(
|
|
41976
|
+
const value = JSON.parse(text2);
|
|
41861
41977
|
reason2 = "does not hold a JSON object";
|
|
41862
41978
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
41863
41979
|
throw new TypeError(reason2);
|
|
41864
|
-
settingsPreimages.set(value, { path, text:
|
|
41980
|
+
settingsPreimages.set(value, { path, text: text2 });
|
|
41865
41981
|
return value;
|
|
41866
41982
|
}
|
|
41867
41983
|
} catch (error61) {
|
|
@@ -41871,7 +41987,7 @@ function readSettings(scope = "global", target = "claude") {
|
|
|
41871
41987
|
console.warn("[hooks] Cannot read hook settings; repair the selected file before installation.");
|
|
41872
41988
|
}
|
|
41873
41989
|
const empty = {};
|
|
41874
|
-
if (!
|
|
41990
|
+
if (!existsSync14(path))
|
|
41875
41991
|
settingsPreimages.set(empty, { path, text: null });
|
|
41876
41992
|
else
|
|
41877
41993
|
unreadableSettings.set(empty, { path, reason: reason2 });
|
|
@@ -41879,19 +41995,19 @@ function readSettings(scope = "global", target = "claude") {
|
|
|
41879
41995
|
}
|
|
41880
41996
|
function unreadableSettingsRefusal(settings, path) {
|
|
41881
41997
|
const captured = settingsPreimages.get(settings);
|
|
41882
|
-
if (captured?.path === path && captured.text !== null || !
|
|
41998
|
+
if (captured?.path === path && captured.text !== null || !existsSync14(path))
|
|
41883
41999
|
return;
|
|
41884
42000
|
const failed = unreadableSettings.get(settings);
|
|
41885
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";
|
|
41886
42002
|
return new ClaudeSettingsRefusal("settings_unreadable", `${path} ${reason2}, so Hooks wrote nothing. Repair the file or move it aside, then retry.`);
|
|
41887
42003
|
}
|
|
41888
42004
|
function settingsIdentity(path) {
|
|
41889
|
-
if (
|
|
42005
|
+
if (existsSync14(path))
|
|
41890
42006
|
return realpathSync4(path);
|
|
41891
|
-
return
|
|
42007
|
+
return existsSync14(dirname16(path)) ? join24(realpathSync4(dirname16(path)), basename12(path)) : resolve28(path);
|
|
41892
42008
|
}
|
|
41893
42009
|
function coordinatesWithSkills(path, target) {
|
|
41894
|
-
return target === "claude" && settingsIdentity(path) === settingsIdentity(
|
|
42010
|
+
return target === "claude" && settingsIdentity(path) === settingsIdentity(join24(homedir8(), ".claude/settings.json"));
|
|
41895
42011
|
}
|
|
41896
42012
|
function writerRefusal(error61) {
|
|
41897
42013
|
return { error: error61 instanceof Error ? error61.message : "Unknown error", ...error61 instanceof ClaudeSettingsRefusal ? { code: error61.code } : {} };
|
|
@@ -41913,21 +42029,21 @@ function writeSettings(settings, scope = "global", target = "claude", expectedSe
|
|
|
41913
42029
|
const before = settingsPreimages.get(settings);
|
|
41914
42030
|
if (!before || before.path !== path)
|
|
41915
42031
|
throw new Error("Claude settings require a valid captured preimage before installation.");
|
|
41916
|
-
const current2 =
|
|
42032
|
+
const current2 = existsSync14(path) ? readFileSync13(path, "utf8") : null;
|
|
41917
42033
|
if (current2 !== before.text)
|
|
41918
42034
|
throw new Error("Claude settings changed during installation; no settings were written.");
|
|
41919
42035
|
if (coordinateClaudeSettings(before.text, JSON.stringify(settings, null, 2) + `
|
|
41920
|
-
`, { home:
|
|
42036
|
+
`, { home: homedir8() }, beforeWrite))
|
|
41921
42037
|
return;
|
|
41922
42038
|
}
|
|
41923
42039
|
if (expectedSettingsSha256 !== undefined)
|
|
41924
42040
|
return writeHookSettingsPreimage(path, settings, captured.text, beforeWrite);
|
|
41925
42041
|
beforeWrite?.();
|
|
41926
|
-
const dir =
|
|
41927
|
-
if (!
|
|
41928
|
-
|
|
42042
|
+
const dir = dirname16(path);
|
|
42043
|
+
if (!existsSync14(dir)) {
|
|
42044
|
+
mkdirSync12(dir, { recursive: true });
|
|
41929
42045
|
}
|
|
41930
|
-
|
|
42046
|
+
writeFileSync10(path, JSON.stringify(settings, null, 2) + `
|
|
41931
42047
|
`);
|
|
41932
42048
|
}
|
|
41933
42049
|
function getTargetEventName(internalEvent, target) {
|
|
@@ -41936,7 +42052,7 @@ function getTargetEventName(internalEvent, target) {
|
|
|
41936
42052
|
function isEventSupported(internalEvent, target) {
|
|
41937
42053
|
return getTargetEventName(internalEvent, target) !== null;
|
|
41938
42054
|
}
|
|
41939
|
-
function
|
|
42055
|
+
function tomlString2(value) {
|
|
41940
42056
|
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
|
|
41941
42057
|
}
|
|
41942
42058
|
function codewithMatcher(matcher) {
|
|
@@ -42010,8 +42126,8 @@ function buildCodewithTomlFragment(name, profile, mementos) {
|
|
|
42010
42126
|
`[[hooks.${eventKey}]]`
|
|
42011
42127
|
];
|
|
42012
42128
|
if (matcher)
|
|
42013
|
-
lines.push(`matcher = ${
|
|
42014
|
-
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))}`);
|
|
42015
42131
|
fragments.push(lines.join(`
|
|
42016
42132
|
`));
|
|
42017
42133
|
}
|
|
@@ -42023,21 +42139,21 @@ function buildCodewithTomlFragment(name, profile, mementos) {
|
|
|
42023
42139
|
function readCodewithConfig(scope, configPath) {
|
|
42024
42140
|
const path = getSettingsPath(scope, "codewith", configPath);
|
|
42025
42141
|
try {
|
|
42026
|
-
return
|
|
42142
|
+
return existsSync14(path) ? readFileSync13(path, "utf-8") : "";
|
|
42027
42143
|
} catch {
|
|
42028
42144
|
return "";
|
|
42029
42145
|
}
|
|
42030
42146
|
}
|
|
42031
42147
|
function appendCodewithFragment(fragment, scope, configPath) {
|
|
42032
42148
|
const path = getSettingsPath(scope, "codewith", configPath);
|
|
42033
|
-
const dir =
|
|
42034
|
-
if (!
|
|
42035
|
-
|
|
42036
|
-
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") : "";
|
|
42037
42153
|
const sep10 = existing.trim() ? `
|
|
42038
42154
|
|
|
42039
42155
|
` : "";
|
|
42040
|
-
|
|
42156
|
+
writeFileSync10(path, `${existing.replace(/\s*$/, "")}${sep10}${fragment}`);
|
|
42041
42157
|
return path;
|
|
42042
42158
|
}
|
|
42043
42159
|
function detectConflict(name, scope, target) {
|
|
@@ -42080,14 +42196,59 @@ function detectRewriteConflict(name, scope, target, lookup = getHook) {
|
|
|
42080
42196
|
}
|
|
42081
42197
|
return;
|
|
42082
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
|
+
}
|
|
42083
42236
|
function installForTarget(name, scope, overwrite, target, profile, codewithMode = "fragment", codewithConfigPath, mementos, expectedSettingsSha256, beforeWrite) {
|
|
42084
42237
|
const shortName = shortHookName(name);
|
|
42085
|
-
if (isNativeSafetyName(shortName) && (profile || target === "gemini" || target === "codewith" && codewithMode === "write")) {
|
|
42238
|
+
if (isNativeSafetyName(shortName) && (profile || target === "gemini" || isAdapterTarget(target) || target === "codewith" && codewithMode === "write")) {
|
|
42086
42239
|
return { hook: shortName, success: false, error: "Bundled native safety guards support Claude/Codex and managed Codewith fragments, without registry profiles.", target };
|
|
42087
42240
|
}
|
|
42088
42241
|
if (!isNativeSafetyName(shortName) && !hookExists(shortName)) {
|
|
42089
42242
|
return { hook: shortName, success: false, error: `Hook '${shortName}' not found`, target };
|
|
42090
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
|
+
}
|
|
42091
42252
|
if (target === "codewith") {
|
|
42092
42253
|
try {
|
|
42093
42254
|
const fragment = buildCodewithTomlFragment(shortName, profile, mementos);
|
|
@@ -42138,7 +42299,8 @@ function installForTarget(name, scope, overwrite, target, profile, codewithMode
|
|
|
42138
42299
|
}
|
|
42139
42300
|
}
|
|
42140
42301
|
try {
|
|
42141
|
-
const
|
|
42302
|
+
const settingsTarget = target;
|
|
42303
|
+
const registered = getRegisteredHooksForTarget(scope, settingsTarget);
|
|
42142
42304
|
if (registered.includes(shortName) && !overwrite) {
|
|
42143
42305
|
return { hook: shortName, success: false, error: "Already installed. Use --overwrite to replace.", scope, target };
|
|
42144
42306
|
}
|
|
@@ -42147,7 +42309,7 @@ function installForTarget(name, scope, overwrite, target, profile, codewithMode
|
|
|
42147
42309
|
if (rewriteConflict) {
|
|
42148
42310
|
return { hook: shortName, success: false, error: `Refused: ${rewriteConflict}`, scope, target };
|
|
42149
42311
|
}
|
|
42150
|
-
registerHook(shortName, scope,
|
|
42312
|
+
registerHook(shortName, scope, settingsTarget, profile, mementos, (settings, selectedScope, selectedTarget) => writeSettings(settings, selectedScope, selectedTarget, expectedSettingsSha256, beforeWrite));
|
|
42151
42313
|
return {
|
|
42152
42314
|
hook: shortName,
|
|
42153
42315
|
success: true,
|
|
@@ -42330,6 +42492,9 @@ function unregisterHook(name, scope = "global", target = "claude") {
|
|
|
42330
42492
|
writeSettings(settings, scope, target);
|
|
42331
42493
|
}
|
|
42332
42494
|
function getRegisteredHooksForTarget(scope = "global", target = "claude") {
|
|
42495
|
+
if (isAdapterTarget(target)) {
|
|
42496
|
+
return [...new Set(readAdapterRegistrations(target, adapterOptions(scope)).map((entry) => entry.hook))];
|
|
42497
|
+
}
|
|
42333
42498
|
if (target === "codewith") {
|
|
42334
42499
|
const config2 = readCodewithConfig(scope);
|
|
42335
42500
|
const registered2 = [];
|
|
@@ -42368,20 +42533,37 @@ function getRegisteredHooksForTarget(scope = "global", target = "claude") {
|
|
|
42368
42533
|
function getRegisteredHooks(scope = "global") {
|
|
42369
42534
|
return getRegisteredHooksForTarget(scope, "claude");
|
|
42370
42535
|
}
|
|
42371
|
-
function removeHook(name, scope = "global", target = "claude") {
|
|
42536
|
+
function removeHook(name, scope = "global", target = "claude", options = {}) {
|
|
42372
42537
|
const shortName = shortHookName(name);
|
|
42373
42538
|
if (target === "all") {
|
|
42374
|
-
|
|
42375
|
-
const
|
|
42376
|
-
|
|
42377
|
-
|
|
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;
|
|
42378
42545
|
}
|
|
42379
42546
|
if (target === "codewith") {
|
|
42380
42547
|
return false;
|
|
42381
42548
|
}
|
|
42382
|
-
|
|
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);
|
|
42383
42556
|
}
|
|
42384
|
-
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
|
+
}
|
|
42385
42567
|
const registered = getRegisteredHooksForTarget(scope, target);
|
|
42386
42568
|
if (!registered.includes(name)) {
|
|
42387
42569
|
return false;
|
|
@@ -42389,78 +42571,8 @@ function removeHookForTarget(name, scope, target) {
|
|
|
42389
42571
|
unregisterHook(name, scope, target);
|
|
42390
42572
|
return true;
|
|
42391
42573
|
}
|
|
42392
|
-
|
|
42393
|
-
|
|
42394
|
-
init_app_home();
|
|
42395
|
-
import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync8, writeFileSync as writeFileSync9, readdirSync as readdirSync8, rmSync as rmSync3, cpSync as cpSync2 } from "fs";
|
|
42396
|
-
import { join as join20 } from "path";
|
|
42397
|
-
function getProfilesDir() {
|
|
42398
|
-
const newDir = join20(getEffectiveDataRoot(), "profiles");
|
|
42399
|
-
const oldDir = join20(getHomeDir(), ".hooks", "profiles");
|
|
42400
|
-
if (!existsSync13(newDir) && existsSync13(oldDir)) {
|
|
42401
|
-
mkdirSync10(newDir, { recursive: true });
|
|
42402
|
-
cpSync2(oldDir, newDir, { recursive: true });
|
|
42403
|
-
}
|
|
42404
|
-
return newDir;
|
|
42405
|
-
}
|
|
42406
|
-
function ensureProfilesDir() {
|
|
42407
|
-
const dir = getProfilesDir();
|
|
42408
|
-
if (!existsSync13(dir)) {
|
|
42409
|
-
mkdirSync10(dir, { recursive: true });
|
|
42410
|
-
}
|
|
42411
|
-
}
|
|
42412
|
-
function profilePath(id) {
|
|
42413
|
-
return join20(getProfilesDir(), `${id}.json`);
|
|
42414
|
-
}
|
|
42415
|
-
function shortUuid() {
|
|
42416
|
-
return crypto.randomUUID().slice(0, 8);
|
|
42417
|
-
}
|
|
42418
|
-
function createProfile(input2) {
|
|
42419
|
-
ensureProfilesDir();
|
|
42420
|
-
const id = shortUuid();
|
|
42421
|
-
const now = new Date().toISOString();
|
|
42422
|
-
const profile = {
|
|
42423
|
-
agent_id: id,
|
|
42424
|
-
agent_type: input2.agent_type,
|
|
42425
|
-
created_at: now,
|
|
42426
|
-
last_seen_at: now,
|
|
42427
|
-
preferences: {}
|
|
42428
|
-
};
|
|
42429
|
-
if (input2.name) {
|
|
42430
|
-
profile.name = input2.name;
|
|
42431
|
-
}
|
|
42432
|
-
writeFileSync9(profilePath(id), JSON.stringify(profile, null, 2) + `
|
|
42433
|
-
`);
|
|
42434
|
-
return profile;
|
|
42435
|
-
}
|
|
42436
|
-
function getProfile(id) {
|
|
42437
|
-
const path = profilePath(id);
|
|
42438
|
-
try {
|
|
42439
|
-
if (!existsSync13(path))
|
|
42440
|
-
return null;
|
|
42441
|
-
return JSON.parse(readFileSync8(path, "utf-8"));
|
|
42442
|
-
} catch {
|
|
42443
|
-
return null;
|
|
42444
|
-
}
|
|
42445
|
-
}
|
|
42446
|
-
function listProfiles() {
|
|
42447
|
-
const dir = getProfilesDir();
|
|
42448
|
-
if (!existsSync13(dir))
|
|
42449
|
-
return [];
|
|
42450
|
-
try {
|
|
42451
|
-
const files = readdirSync8(dir).filter((f) => f.endsWith(".json"));
|
|
42452
|
-
const profiles = [];
|
|
42453
|
-
for (const file2 of files) {
|
|
42454
|
-
try {
|
|
42455
|
-
const content = readFileSync8(join20(dir, file2), "utf-8");
|
|
42456
|
-
profiles.push(JSON.parse(content));
|
|
42457
|
-
} catch {}
|
|
42458
|
-
}
|
|
42459
|
-
return profiles.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
|
|
42460
|
-
} catch {
|
|
42461
|
-
return [];
|
|
42462
|
-
}
|
|
42463
|
-
}
|
|
42574
|
+
var JSON_SETTINGS_TARGETS = ["claude", "gemini", "codex", "qwen"];
|
|
42575
|
+
var ALL_REMOVABLE_TARGETS = [...JSON_SETTINGS_TARGETS, ...ADAPTER_TARGETS];
|
|
42464
42576
|
|
|
42465
42577
|
// src/mcp/server.ts
|
|
42466
42578
|
init_manifest();
|
|
@@ -43018,13 +43130,13 @@ function coerceForSqlite(value) {
|
|
|
43018
43130
|
return String(value);
|
|
43019
43131
|
}
|
|
43020
43132
|
// src/mcp/server.ts
|
|
43021
|
-
var __dirname3 =
|
|
43133
|
+
var __dirname3 = dirname29(fileURLToPath4(import.meta.url));
|
|
43022
43134
|
var pkg = { name: "@hasna/hooks", version: "0.0.0" };
|
|
43023
43135
|
try {
|
|
43024
43136
|
for (const rel of ["../../package.json", "../package.json", "../../../package.json"]) {
|
|
43025
|
-
const p =
|
|
43026
|
-
if (
|
|
43027
|
-
pkg = JSON.parse(
|
|
43137
|
+
const p = join34(__dirname3, rel);
|
|
43138
|
+
if (existsSync16(p)) {
|
|
43139
|
+
pkg = JSON.parse(readFileSync18(p, "utf-8"));
|
|
43028
43140
|
break;
|
|
43029
43141
|
}
|
|
43030
43142
|
}
|
|
@@ -43033,10 +43145,10 @@ async function runVerifiedHook(name, stdin, timeoutMs) {
|
|
|
43033
43145
|
const { resolveHook: resolveHook2, resolveScriptPath: resolveScriptPath2 } = await Promise.resolve().then(() => (init_resolve(), exports_resolve));
|
|
43034
43146
|
const resolved = resolveHook2(name);
|
|
43035
43147
|
const hookScript = resolveScriptPath2(name);
|
|
43036
|
-
if (!resolved || !hookScript || !
|
|
43148
|
+
if (!resolved || !hookScript || !existsSync16(hookScript)) {
|
|
43037
43149
|
throw new Error(`Hook '${name}' not found`);
|
|
43038
43150
|
}
|
|
43039
|
-
const content =
|
|
43151
|
+
const content = readFileSync18(hookScript);
|
|
43040
43152
|
const sha7 = sha256Of(content);
|
|
43041
43153
|
const check2 = checkScriptHash(name, sha7);
|
|
43042
43154
|
if (!check2.ok) {
|
|
@@ -43118,10 +43230,10 @@ function settingsChangeError(hook, scope, error61, code2) {
|
|
|
43118
43230
|
};
|
|
43119
43231
|
}
|
|
43120
43232
|
function truncateText(value, max = 160) {
|
|
43121
|
-
const
|
|
43122
|
-
if (
|
|
43123
|
-
return
|
|
43124
|
-
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))}...`;
|
|
43125
43237
|
}
|
|
43126
43238
|
function boundedLimit(value, fallback, max) {
|
|
43127
43239
|
if (!Number.isFinite(value) || !value || value <= 0)
|
|
@@ -43248,7 +43360,7 @@ function createHooksServer() {
|
|
|
43248
43360
|
const settingsPath = getSettingsPath(scope);
|
|
43249
43361
|
const issues = [];
|
|
43250
43362
|
const healthy = [];
|
|
43251
|
-
const settingsExist =
|
|
43363
|
+
const settingsExist = existsSync16(settingsPath);
|
|
43252
43364
|
if (!settingsExist) {
|
|
43253
43365
|
issues.push({ hook: "(settings)", issue: `${settingsPath} not found`, severity: "warning" });
|
|
43254
43366
|
}
|
|
@@ -43258,7 +43370,7 @@ function createHooksServer() {
|
|
|
43258
43370
|
const meta3 = custom2 ? resolveHookMeta(name) : getHook(name);
|
|
43259
43371
|
let hookHealthy = true;
|
|
43260
43372
|
if (custom2) {
|
|
43261
|
-
if (!
|
|
43373
|
+
if (!existsSync16(custom2.scriptPath)) {
|
|
43262
43374
|
issues.push({ hook: name, issue: `Custom hook script missing: ${custom2.scriptPath}`, severity: "error" });
|
|
43263
43375
|
hookHealthy = false;
|
|
43264
43376
|
}
|
|
@@ -43268,14 +43380,14 @@ function createHooksServer() {
|
|
|
43268
43380
|
continue;
|
|
43269
43381
|
}
|
|
43270
43382
|
const hookDir = getHookPath(name);
|
|
43271
|
-
if (!
|
|
43383
|
+
if (!existsSync16(join34(hookDir, "src", "hook.ts"))) {
|
|
43272
43384
|
issues.push({ hook: name, issue: "Missing src/hook.ts in package", severity: "error" });
|
|
43273
43385
|
hookHealthy = false;
|
|
43274
43386
|
}
|
|
43275
43387
|
}
|
|
43276
43388
|
if (meta3 && settingsExist) {
|
|
43277
43389
|
try {
|
|
43278
|
-
const settings = JSON.parse(
|
|
43390
|
+
const settings = JSON.parse(readFileSync18(settingsPath, "utf-8"));
|
|
43279
43391
|
if (!hookRegisteredInSettings(settings, name, meta3.event, matcherFor(meta3, "claude"))) {
|
|
43280
43392
|
const eventName = meta3.event.split(":")[0];
|
|
43281
43393
|
issues.push({ hook: name, issue: `Not registered under correct event (${eventName})`, severity: "error" });
|
|
@@ -43312,10 +43424,10 @@ function createHooksServer() {
|
|
|
43312
43424
|
return { content: [{ type: "text", text: JSON.stringify({ error: `Hook '${name}' not found` }) }] };
|
|
43313
43425
|
}
|
|
43314
43426
|
const hookPath = getHookPath(name);
|
|
43315
|
-
const readmePath =
|
|
43427
|
+
const readmePath = join34(hookPath, "README.md");
|
|
43316
43428
|
let readme = "";
|
|
43317
|
-
if (
|
|
43318
|
-
readme =
|
|
43429
|
+
if (existsSync16(readmePath)) {
|
|
43430
|
+
readme = readFileSync18(readmePath, "utf-8");
|
|
43319
43431
|
}
|
|
43320
43432
|
if (verbose) {
|
|
43321
43433
|
return { content: [{ type: "text", text: JSON.stringify({ ...meta3, readme }) }] };
|
|
@@ -43498,7 +43610,7 @@ function createHooksServer() {
|
|
|
43498
43610
|
const ctx = {
|
|
43499
43611
|
scope,
|
|
43500
43612
|
settings_path: settingsPath,
|
|
43501
|
-
settings_exists:
|
|
43613
|
+
settings_exists: existsSync16(settingsPath),
|
|
43502
43614
|
registered_hooks: hooks,
|
|
43503
43615
|
hook_count: hooks.length,
|
|
43504
43616
|
healthy,
|