@hasna/hooks 0.13.0 → 0.13.1

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/bin/index.js CHANGED
@@ -20,14 +20,12 @@ var __toESM = (mod, isNodeMode, target) => {
20
20
  }
21
21
  target = mod != null ? __create(__getProtoOf(mod)) : {};
22
22
  const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
- if (mod && typeof mod === "object" || typeof mod === "function") {
24
- for (let key of __getOwnPropNames(mod))
25
- if (!__hasOwnProp.call(to, key))
26
- __defProp(to, key, {
27
- get: __accessProp.bind(mod, key),
28
- enumerable: true
29
- });
30
- }
23
+ for (let key of __getOwnPropNames(mod))
24
+ if (!__hasOwnProp.call(to, key))
25
+ __defProp(to, key, {
26
+ get: __accessProp.bind(mod, key),
27
+ enumerable: true
28
+ });
31
29
  if (canCache)
32
30
  cache.set(mod, to);
33
31
  return to;
@@ -935,18 +933,18 @@ var init_readiness_process = __esm(() => {
935
933
  // src/native-readiness.ts
936
934
  var exports_native_readiness = {};
937
935
  __export(exports_native_readiness, {
938
- TRASH_READINESS_DEFAULT_TIMEOUT_MS: () => TRASH_READINESS_DEFAULT_TIMEOUT_MS,
939
- TRASH_READINESS_MAX_TIMEOUT_MS: () => TRASH_READINESS_MAX_TIMEOUT_MS,
940
- TRASH_READINESS_NATIVE_TIMEOUT_SECONDS: () => TRASH_READINESS_NATIVE_TIMEOUT_SECONDS,
941
- checkTrashReadinessBinding: () => checkTrashReadinessBinding,
942
- handleReadinessSessionStart: () => handleReadinessSessionStart,
943
- isReadinessProvider: () => isReadinessProvider,
944
- parseTrashReadinessBinding: () => parseTrashReadinessBinding,
945
- readTrashReadinessBindingFile: () => readTrashReadinessBindingFile,
946
- readinessContext: () => readinessContext,
947
- readinessSessionStartOutput: () => readinessSessionStartOutput,
936
+ trashReadinessBindingPath: () => trashReadinessBindingPath,
948
937
  runTrashReadiness: () => runTrashReadiness,
949
- trashReadinessBindingPath: () => trashReadinessBindingPath
938
+ readinessSessionStartOutput: () => readinessSessionStartOutput,
939
+ readinessContext: () => readinessContext,
940
+ readTrashReadinessBindingFile: () => readTrashReadinessBindingFile,
941
+ parseTrashReadinessBinding: () => parseTrashReadinessBinding,
942
+ isReadinessProvider: () => isReadinessProvider,
943
+ handleReadinessSessionStart: () => handleReadinessSessionStart,
944
+ checkTrashReadinessBinding: () => checkTrashReadinessBinding,
945
+ TRASH_READINESS_NATIVE_TIMEOUT_SECONDS: () => TRASH_READINESS_NATIVE_TIMEOUT_SECONDS,
946
+ TRASH_READINESS_MAX_TIMEOUT_MS: () => TRASH_READINESS_MAX_TIMEOUT_MS,
947
+ TRASH_READINESS_DEFAULT_TIMEOUT_MS: () => TRASH_READINESS_DEFAULT_TIMEOUT_MS
950
948
  });
951
949
  import { createHash } from "crypto";
952
950
  import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "fs";
@@ -1203,21 +1201,21 @@ var init_semver = __esm(() => {
1203
1201
  // src/lib/manifest.ts
1204
1202
  var exports_manifest = {};
1205
1203
  __export(exports_manifest, {
1206
- HOOK_NAME_RE: () => HOOK_NAME_RE,
1207
- HookIdentityError: () => HookIdentityError,
1208
- ScriptContainmentError: () => ScriptContainmentError,
1209
- assertContained: () => assertContained,
1210
- customHookDir: () => customHookDir,
1211
- isInlineScript: () => isInlineScript,
1212
- listCustomHooks: () => listCustomHooks,
1213
- manifestSchema: () => manifestSchema,
1214
- normalizeManifestName: () => normalizeManifestName,
1215
- parseManifest: () => parseManifest,
1216
- readCustomManifest: () => readCustomManifest,
1217
- resolveScript: () => resolveScript,
1218
- scriptRelFor: () => scriptRelFor,
1204
+ writeCustomHook: () => writeCustomHook,
1219
1205
  shortManifestName: () => shortManifestName,
1220
- writeCustomHook: () => writeCustomHook
1206
+ scriptRelFor: () => scriptRelFor,
1207
+ resolveScript: () => resolveScript,
1208
+ readCustomManifest: () => readCustomManifest,
1209
+ parseManifest: () => parseManifest,
1210
+ normalizeManifestName: () => normalizeManifestName,
1211
+ manifestSchema: () => manifestSchema,
1212
+ listCustomHooks: () => listCustomHooks,
1213
+ isInlineScript: () => isInlineScript,
1214
+ customHookDir: () => customHookDir,
1215
+ assertContained: () => assertContained,
1216
+ ScriptContainmentError: () => ScriptContainmentError,
1217
+ HookIdentityError: () => HookIdentityError,
1218
+ HOOK_NAME_RE: () => HOOK_NAME_RE
1221
1219
  });
1222
1220
  import { existsSync as existsSync2, mkdirSync, readFileSync, readdirSync, realpathSync as realpathSync2, writeFileSync } from "fs";
1223
1221
  import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join4, normalize, resolve as resolve3, sep } from "path";
@@ -1394,11 +1392,11 @@ var init_manifest = __esm(() => {
1394
1392
  // src/lib/resolve.ts
1395
1393
  var exports_resolve = {};
1396
1394
  __export(exports_resolve, {
1397
- resolveBundledHooksDir: () => resolveBundledHooksDir,
1398
- resolveHook: () => resolveHook,
1399
- resolveHookDir: () => resolveHookDir,
1395
+ resolveScriptPath: () => resolveScriptPath,
1400
1396
  resolveHookMeta: () => resolveHookMeta,
1401
- resolveScriptPath: () => resolveScriptPath
1397
+ resolveHookDir: () => resolveHookDir,
1398
+ resolveHook: () => resolveHook,
1399
+ resolveBundledHooksDir: () => resolveBundledHooksDir
1402
1400
  });
1403
1401
  import { dirname as dirname3, join as join5 } from "path";
1404
1402
  import { existsSync as existsSync3 } from "fs";
@@ -2239,10 +2237,10 @@ var init_targets = __esm(() => {
2239
2237
  // src/lib/native-target.ts
2240
2238
  var exports_native_target = {};
2241
2239
  __export(exports_native_target, {
2242
- HOOK_RUN_TARGETS: () => HOOK_RUN_TARGETS,
2243
- isHookRunTarget: () => isHookRunTarget,
2240
+ nativeTargetCommandSuffix: () => nativeTargetCommandSuffix,
2244
2241
  nativeTargetArgs: () => nativeTargetArgs,
2245
- nativeTargetCommandSuffix: () => nativeTargetCommandSuffix
2242
+ isHookRunTarget: () => isHookRunTarget,
2243
+ HOOK_RUN_TARGETS: () => HOOK_RUN_TARGETS
2246
2244
  });
2247
2245
  function isHookRunTarget(value) {
2248
2246
  return typeof value === "string" && HOOK_RUN_TARGETS.includes(value);
@@ -2425,7 +2423,7 @@ function up(db) {
2425
2423
  db.exec(idx);
2426
2424
  }
2427
2425
  }
2428
- var init__001_initial = __esm(() => {
2426
+ var init_001_initial = __esm(() => {
2429
2427
  init_schema();
2430
2428
  });
2431
2429
 
@@ -2454,7 +2452,7 @@ function up2(db) {
2454
2452
  throw err;
2455
2453
  }
2456
2454
  }
2457
- var init__002_session_events = __esm(() => {
2455
+ var init_002_session_events = __esm(() => {
2458
2456
  init_schema();
2459
2457
  });
2460
2458
 
@@ -2483,7 +2481,7 @@ function up3(db) {
2483
2481
  throw err;
2484
2482
  }
2485
2483
  }
2486
- var init__003_user_prompt_submit_event = __esm(() => {
2484
+ var init_003_user_prompt_submit_event = __esm(() => {
2487
2485
  init_schema();
2488
2486
  });
2489
2487
 
@@ -2507,7 +2505,7 @@ var CREATE_HOOKS_TABLE = `
2507
2505
  last_verified_at TEXT
2508
2506
  )
2509
2507
  `, CREATE_HOOKS_INDEXES;
2510
- var init__004_hooks_table = __esm(() => {
2508
+ var init_004_hooks_table = __esm(() => {
2511
2509
  CREATE_HOOKS_INDEXES = [
2512
2510
  `CREATE INDEX IF NOT EXISTS idx_hooks_name ON hooks (name)`
2513
2511
  ];
@@ -2538,7 +2536,7 @@ function up5(db) {
2538
2536
  throw err;
2539
2537
  }
2540
2538
  }
2541
- var init__005_subagent_start_event = __esm(() => {
2539
+ var init_005_subagent_start_event = __esm(() => {
2542
2540
  init_schema();
2543
2541
  });
2544
2542
 
@@ -2570,11 +2568,11 @@ function runMigrations(db) {
2570
2568
  }
2571
2569
  var MIGRATIONS;
2572
2570
  var init_migrations = __esm(() => {
2573
- init__001_initial();
2574
- init__002_session_events();
2575
- init__003_user_prompt_submit_event();
2576
- init__004_hooks_table();
2577
- init__005_subagent_start_event();
2571
+ init_001_initial();
2572
+ init_002_session_events();
2573
+ init_003_user_prompt_submit_event();
2574
+ init_004_hooks_table();
2575
+ init_005_subagent_start_event();
2578
2576
  MIGRATIONS = [
2579
2577
  { version: "001_initial", up },
2580
2578
  { version: "002_session_events", up: up2 },
@@ -2716,14 +2714,14 @@ function runRetention(db, days) {
2716
2714
  // src/db/index.ts
2717
2715
  var exports_db = {};
2718
2716
  __export(exports_db, {
2719
- allowLocalStore: () => allowLocalStore,
2720
- closeDb: () => closeDb,
2721
- createTestDb: () => createTestDb,
2722
- getDb: () => getDb,
2723
- getDbPath: () => getDbPath,
2724
- isLocalStoreRefused: () => isLocalStoreRefused,
2717
+ refuseLocalStore: () => refuseLocalStore,
2725
2718
  localStoreRefusalMessage: () => localStoreRefusalMessage,
2726
- refuseLocalStore: () => refuseLocalStore
2719
+ isLocalStoreRefused: () => isLocalStoreRefused,
2720
+ getDbPath: () => getDbPath,
2721
+ getDb: () => getDb,
2722
+ createTestDb: () => createTestDb,
2723
+ closeDb: () => closeDb,
2724
+ allowLocalStore: () => allowLocalStore
2727
2725
  });
2728
2726
  import { Database } from "bun:sqlite";
2729
2727
  import { existsSync as existsSync7, mkdirSync as mkdirSync2, cpSync } from "fs";
@@ -2852,24 +2850,24 @@ var init_registry_artifact = __esm(() => {
2852
2850
  // src/lib/store.ts
2853
2851
  var exports_store = {};
2854
2852
  __export(exports_store, {
2855
- LockFileError: () => LockFileError,
2856
- checkScriptHash: () => checkScriptHash,
2857
- getHookRecord: () => getHookRecord,
2858
- getPinnedHook: () => getPinnedHook,
2859
- listHookRecords: () => listHookRecords,
2860
- markRegistryManaged: () => markRegistryManaged,
2861
- pinInstalledHook: () => pinInstalledHook,
2862
- readLock: () => readLock,
2863
- removeHookFromStore: () => removeHookFromStore,
2864
- removeHookRecord: () => removeHookRecord,
2865
- removePinnedHook: () => removePinnedHook,
2866
- retrustHook: () => retrustHook,
2867
- setPinnedHook: () => setPinnedHook,
2868
- sha256File: () => sha256File,
2869
- sha256Of: () => sha256Of,
2870
- upsertHookRecord: () => upsertHookRecord,
2853
+ writeLock: () => writeLock,
2871
2854
  verifyScriptHash: () => verifyScriptHash,
2872
- writeLock: () => writeLock
2855
+ upsertHookRecord: () => upsertHookRecord,
2856
+ sha256Of: () => sha256Of,
2857
+ sha256File: () => sha256File,
2858
+ setPinnedHook: () => setPinnedHook,
2859
+ retrustHook: () => retrustHook,
2860
+ removePinnedHook: () => removePinnedHook,
2861
+ removeHookRecord: () => removeHookRecord,
2862
+ removeHookFromStore: () => removeHookFromStore,
2863
+ readLock: () => readLock,
2864
+ pinInstalledHook: () => pinInstalledHook,
2865
+ markRegistryManaged: () => markRegistryManaged,
2866
+ listHookRecords: () => listHookRecords,
2867
+ getPinnedHook: () => getPinnedHook,
2868
+ getHookRecord: () => getHookRecord,
2869
+ checkScriptHash: () => checkScriptHash,
2870
+ LockFileError: () => LockFileError
2873
2871
  });
2874
2872
  import { createHash as createHash5 } from "crypto";
2875
2873
  import { existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync2, renameSync, lstatSync as lstatSync4 } from "fs";
@@ -3223,6 +3221,9 @@ import { homedir as homedir7 } from "os";
3223
3221
  import { join as join12, resolve as resolve5 } from "path";
3224
3222
  import { homedir as pathsResolverHomedir2 } from "os";
3225
3223
  import { join as pathsResolverJoin2 } from "path";
3224
+ import { createHash as createHash7 } from "crypto";
3225
+ import { existsSync as existsSync52, readdirSync as readdirSync3, readFileSync as readFileSync42, statSync as statSync4 } from "fs";
3226
+ import { join as join52, sep as sep2 } from "path";
3226
3227
  import { createHash as createHash32 } from "crypto";
3227
3228
  import { createHash as createHash22 } from "crypto";
3228
3229
  import { closeSync as closeSync22, constants as constants22, fstatSync as fstatSync22, lstatSync as lstatSync42, openSync as openSync22, readSync as readSync2 } from "fs";
@@ -3232,7 +3233,7 @@ import { createHash as createHash42 } from "crypto";
3232
3233
  import { basename as basename3, dirname as dirname42, isAbsolute as isAbsolute32, resolve as resolve32 } from "path";
3233
3234
  import { createHash as createHash52 } from "crypto";
3234
3235
  import { closeSync as closeSync32, constants as constants32, fstatSync as fstatSync32, lstatSync as lstatSync52, openSync as openSync32, readSync as readSync22 } from "fs";
3235
- import { basename as basename4, dirname as dirname52, isAbsolute as isAbsolute42, resolve as resolve42, sep as sep2 } from "path";
3236
+ import { basename as basename4, dirname as dirname52, isAbsolute as isAbsolute42, resolve as resolve42, sep as sep22 } from "path";
3236
3237
  import { createHash as createHash30 } from "crypto";
3237
3238
  import { lstatSync as lstatSync32, readFileSync as readFileSync26, readdirSync as readdirSync13, realpathSync as realpathSync13 } from "fs";
3238
3239
  import { basename as basename15, dirname as dirname26, isAbsolute as isAbsolute28, join as join38, relative as relative10, resolve as resolve27, sep as sep15 } from "path";
@@ -3242,7 +3243,7 @@ import { lstatSync as lstatSync6, readFileSync as readFileSync62, opendirSync }
3242
3243
  import { createHash as createHash62 } from "crypto";
3243
3244
  import { lstatSync as lstatSync7, opendirSync as opendirSync2 } from "fs";
3244
3245
  import { dirname as dirname72, isAbsolute as isAbsolute7, join as join92, resolve as resolve7 } from "path";
3245
- import { createHash as createHash7 } from "crypto";
3246
+ import { createHash as createHash72 } from "crypto";
3246
3247
  import { closeSync as closeSync42, constants as constants4, fstatSync as fstatSync4, lstatSync as lstatSync8, openSync as openSync42, readSync as readSync3 } from "fs";
3247
3248
  import { dirname as dirname8, isAbsolute as isAbsolute8, resolve as resolve8 } from "path";
3248
3249
  import { createHash as createHash11, randomUUID as randomUUID2 } from "crypto";
@@ -3314,6 +3315,7 @@ import { closeSync as closeSync19, constants as constants20, fstatSync as fstatS
3314
3315
  import { basename as basename14, dirname as dirname25, isAbsolute as isAbsolute27, resolve as resolve26 } from "path";
3315
3316
  import { createHash as createHash29 } from "crypto";
3316
3317
  import { isAbsolute as isAbsolute30 } from "path";
3318
+ import { createHash as createHash34 } from "crypto";
3317
3319
  function __exportSetter2(name, newValue) {
3318
3320
  this[name] = __returnValue2.bind(null, newValue);
3319
3321
  }
@@ -3403,6 +3405,257 @@ class SkillEntryPaths {
3403
3405
  this.files.add(key);
3404
3406
  }
3405
3407
  }
3408
+ function excludedHashEntry(name, directory) {
3409
+ return name.startsWith(".") || directory && HASH_EXCLUDE_DIRS.has(name);
3410
+ }
3411
+ function normalizeLineEndings(content) {
3412
+ return content.replace(/\r\n/g, `
3413
+ `).replace(/\r/g, `
3414
+ `);
3415
+ }
3416
+ function canonicalizeManifest(raw) {
3417
+ let parsed;
3418
+ try {
3419
+ parsed = JSON.parse(raw);
3420
+ } catch {
3421
+ return normalizeLineEndings(raw);
3422
+ }
3423
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
3424
+ return normalizeLineEndings(raw);
3425
+ }
3426
+ const record = parsed;
3427
+ delete record.content_hash;
3428
+ if (record.provenance && typeof record.provenance === "object" && !Array.isArray(record.provenance)) {
3429
+ delete record.provenance.content_hash;
3430
+ }
3431
+ return `${JSON.stringify(sortObjectKeys(record), null, 2)}
3432
+ `;
3433
+ }
3434
+ function sortObjectKeys(value) {
3435
+ if (Array.isArray(value))
3436
+ return value.map((item) => sortObjectKeys(item));
3437
+ if (typeof value === "object" && value !== null) {
3438
+ const record = value;
3439
+ const sorted = Object.create(null);
3440
+ for (const key of Object.keys(record).sort())
3441
+ sorted[key] = sortObjectKeys(record[key]);
3442
+ return sorted;
3443
+ }
3444
+ return value;
3445
+ }
3446
+ function looksLikeText(buffer) {
3447
+ return !buffer.includes(0);
3448
+ }
3449
+ function collectBundleFiles(skillPath) {
3450
+ const files = [];
3451
+ const seen = new Set;
3452
+ for (const entry of HASH_COVERAGE) {
3453
+ if (seen.has(entry))
3454
+ continue;
3455
+ seen.add(entry);
3456
+ const absolute2 = join52(skillPath, entry);
3457
+ if (!existsSync52(absolute2))
3458
+ continue;
3459
+ if (statSync4(absolute2).isDirectory())
3460
+ collectDirectory(files, absolute2, entry);
3461
+ else
3462
+ collectFile(files, absolute2, entry);
3463
+ }
3464
+ return files.sort((a, b) => a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0);
3465
+ }
3466
+ function collectDirectory(files, dir, rel) {
3467
+ for (const entry of readdirSync3(dir).sort()) {
3468
+ if (entry.startsWith("."))
3469
+ continue;
3470
+ const absolute2 = join52(dir, entry);
3471
+ const childRel = `${rel}/${entry}`;
3472
+ let stats;
3473
+ try {
3474
+ stats = statSync4(absolute2);
3475
+ } catch {
3476
+ continue;
3477
+ }
3478
+ if (stats.isSymbolicLink())
3479
+ continue;
3480
+ if (stats.isDirectory()) {
3481
+ if (excludedHashEntry(entry, true))
3482
+ continue;
3483
+ collectDirectory(files, absolute2, childRel);
3484
+ } else if (stats.isFile()) {
3485
+ collectFile(files, absolute2, childRel);
3486
+ }
3487
+ }
3488
+ }
3489
+ function collectFile(files, absolute2, rel) {
3490
+ const buffer = readFileSync42(absolute2);
3491
+ files.push(normalizeBundleFile(rel.split(sep2).join("/"), buffer));
3492
+ }
3493
+ function normalizeBundleFile(rel, buffer) {
3494
+ if (rel === "skill.json") {
3495
+ return { rel, content: new TextEncoder().encode(canonicalizeManifest(new TextDecoder().decode(buffer))) };
3496
+ }
3497
+ if (looksLikeText(buffer)) {
3498
+ const normalized = normalizeLineEndings(new TextDecoder().decode(buffer));
3499
+ return { rel, content: new TextEncoder().encode(normalized) };
3500
+ }
3501
+ return { rel, content: buffer };
3502
+ }
3503
+ function computeContentHash(skillPath) {
3504
+ return hashBundleFiles(collectBundleFiles(skillPath));
3505
+ }
3506
+ function* bundleHashParts(files) {
3507
+ for (const file of files) {
3508
+ yield new TextEncoder().encode(file.rel);
3509
+ yield new TextEncoder().encode(`\x00${file.content.length}\x00`);
3510
+ yield file.content;
3511
+ yield new TextEncoder().encode("\x00");
3512
+ }
3513
+ yield new TextEncoder().encode("\x00");
3514
+ }
3515
+ function hashBundleFiles(files) {
3516
+ const hash = createHash7(CONTENT_HASH_ALGORITHM);
3517
+ for (const part of bundleHashParts(files))
3518
+ hash.update(part);
3519
+ return hash.digest("hex");
3520
+ }
3521
+ function verifyContentHash(skillPath, manifest) {
3522
+ const declaredHash = manifest?.provenance?.content_hash?.trim() || undefined;
3523
+ if (!declaredHash)
3524
+ return { declared: false, valid: false };
3525
+ if (!/^[a-f0-9]{64}$/.test(declaredHash)) {
3526
+ return { declared: true, valid: false, declaredHash };
3527
+ }
3528
+ const computedHash = computeContentHash(skillPath);
3529
+ return {
3530
+ declared: true,
3531
+ valid: computedHash === declaredHash,
3532
+ declaredHash,
3533
+ computedHash
3534
+ };
3535
+ }
3536
+ function add2(target, code, message) {
3537
+ target.push({ code, message });
3538
+ }
3539
+ function isRecord(value) {
3540
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3541
+ }
3542
+ function isNonEmptyString(value) {
3543
+ return typeof value === "string" && value.trim().length > 0;
3544
+ }
3545
+ function validatePortableManifestContract(manifest, options = {}) {
3546
+ const issues = [];
3547
+ if (!manifest) {
3548
+ add2(issues, "contract.manifest_missing", "No portable manifest to validate");
3549
+ return issues;
3550
+ }
3551
+ if (manifest.standard !== PORTABLE_SKILL_STANDARD) {
3552
+ add2(issues, "contract.standard_invalid", `standard must be '${PORTABLE_SKILL_STANDARD}'`);
3553
+ }
3554
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(manifest.name)) {
3555
+ add2(issues, "contract.name_invalid", `name '${manifest.name}' must be a lowercase slug (letters, numbers, dots, underscores, hyphens)`);
3556
+ }
3557
+ if (!isNonEmptyString(manifest.description)) {
3558
+ add2(issues, "contract.description_missing", "description is required");
3559
+ }
3560
+ if (!isNonEmptyString(manifest.version)) {
3561
+ add2(issues, "contract.version_missing", "version is required");
3562
+ } else if (!new RegExp(SEMVER_PATTERN2).test(manifest.version)) {
3563
+ add2(issues, "contract.version_invalid", `version '${manifest.version}' is not valid semver`);
3564
+ }
3565
+ validateRuntimeContract(manifest, issues, options.strict === true);
3566
+ const provenance = manifest.provenance;
3567
+ if (provenance && !isRecord(provenance)) {
3568
+ add2(issues, "contract.provenance_invalid", "provenance must be an object");
3569
+ } else {
3570
+ const sourceCommit = provenance?.source_commit;
3571
+ if (sourceCommit !== undefined && sourceCommit !== null && !isNonEmptyString(sourceCommit)) {
3572
+ add2(issues, "contract.source_commit_invalid", "provenance.source_commit must be a string");
3573
+ }
3574
+ const changelog = provenance?.changelog;
3575
+ if (changelog !== undefined && changelog !== null && !isNonEmptyString(changelog)) {
3576
+ add2(issues, "contract.changelog_invalid", "provenance.changelog must be a string");
3577
+ }
3578
+ const declaredHash = provenance?.content_hash;
3579
+ if (options.strict && !isNonEmptyString(declaredHash)) {
3580
+ add2(issues, "contract.content_hash_missing", "provenance.content_hash is required: a portable manifest must carry its canonical content hash");
3581
+ } else if (isNonEmptyString(declaredHash) && !new RegExp(CONTENT_HASH_PATTERN).test(declaredHash)) {
3582
+ add2(issues, "contract.content_hash_invalid", "provenance.content_hash must be a 64-character lowercase hex SHA-256");
3583
+ } else if (options.skillPath && isNonEmptyString(declaredHash)) {
3584
+ const verification = verifyContentHash(options.skillPath, manifest);
3585
+ if (!verification.valid) {
3586
+ 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).`);
3587
+ }
3588
+ }
3589
+ }
3590
+ return issues;
3591
+ }
3592
+ function validateRuntimeContract(manifest, issues, strict) {
3593
+ const runtime = manifest.runtime;
3594
+ if (runtime === undefined) {
3595
+ if (strict && manifest.kind !== "instruction") {
3596
+ add2(issues, "contract.runtime_missing", "runtime contract is required: { runtime, entrypoint?, timeout?, needs_network?, env?, sandbox?, system_deps?, artifacts? }");
3597
+ }
3598
+ return;
3599
+ }
3600
+ if (!isRecord(runtime)) {
3601
+ add2(issues, "contract.runtime_invalid", "runtime must be an object");
3602
+ return;
3603
+ }
3604
+ const runtimeName = runtime.runtime;
3605
+ if (!SKILL_RUNTIMES.includes(runtimeName)) {
3606
+ add2(issues, "contract.runtime_invalid", `runtime.runtime must be one of: ${SKILL_RUNTIMES.join(", ")}`);
3607
+ }
3608
+ if (runtime.version !== undefined && runtime.version !== null && !isNonEmptyString(runtime.version)) {
3609
+ add2(issues, "contract.runtime_version_invalid", "runtime.version must be a string");
3610
+ }
3611
+ if (runtime.entrypoint !== undefined && runtime.entrypoint !== null && !isNonEmptyString(runtime.entrypoint)) {
3612
+ add2(issues, "contract.entrypoint_invalid", "runtime.entrypoint must be a relative path string");
3613
+ }
3614
+ if (runtime.timeout !== undefined && runtime.timeout !== null) {
3615
+ if (typeof runtime.timeout !== "number" || !Number.isInteger(runtime.timeout) || runtime.timeout < 1 || runtime.timeout > MAX_RUNTIME_TIMEOUT_SECONDS) {
3616
+ add2(issues, "contract.timeout_invalid", `runtime.timeout must be an integer between 1 and ${MAX_RUNTIME_TIMEOUT_SECONDS} seconds`);
3617
+ }
3618
+ }
3619
+ if (runtime.needs_network !== undefined && runtime.needs_network !== null && typeof runtime.needs_network !== "boolean") {
3620
+ add2(issues, "contract.needs_network_invalid", "runtime.needs_network must be a boolean");
3621
+ }
3622
+ if (runtime.env !== undefined && runtime.env !== null) {
3623
+ if (!Array.isArray(runtime.env)) {
3624
+ add2(issues, "contract.env_invalid", "runtime.env must be an array of secret REFERENCE names");
3625
+ } else {
3626
+ for (const reference of runtime.env) {
3627
+ if (typeof reference !== "string" || !new RegExp(ENV_REFERENCE_PATTERN).test(reference)) {
3628
+ 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`);
3629
+ }
3630
+ }
3631
+ }
3632
+ }
3633
+ if (runtime.sandbox !== undefined && runtime.sandbox !== null && !SKILL_SANDBOX_MODES.includes(runtime.sandbox)) {
3634
+ add2(issues, "contract.sandbox_invalid", `runtime.sandbox must be one of: ${SKILL_SANDBOX_MODES.join(", ")}`);
3635
+ }
3636
+ if (runtime.system_deps !== undefined && runtime.system_deps !== null) {
3637
+ if (!Array.isArray(runtime.system_deps)) {
3638
+ add2(issues, "contract.system_deps_invalid", "runtime.system_deps must be an array");
3639
+ } else {
3640
+ for (const dep of runtime.system_deps) {
3641
+ if (!SKILL_SYSTEM_DEPS_ALLOWLIST.includes(dep)) {
3642
+ add2(issues, "contract.system_dep_not_allowed", `runtime.system_deps entry '${dep}' is not on the allowlist: ${SKILL_SYSTEM_DEPS_ALLOWLIST.join(", ")}`);
3643
+ }
3644
+ }
3645
+ }
3646
+ }
3647
+ if (runtime.artifacts !== undefined && runtime.artifacts !== null) {
3648
+ if (!Array.isArray(runtime.artifacts)) {
3649
+ add2(issues, "contract.artifacts_invalid", "runtime.artifacts must be an array of glob patterns");
3650
+ } else {
3651
+ for (const glob of runtime.artifacts) {
3652
+ if (!isNonEmptyString(glob)) {
3653
+ add2(issues, "contract.artifacts_invalid", "runtime.artifacts entries must be non-empty glob strings");
3654
+ }
3655
+ }
3656
+ }
3657
+ }
3658
+ }
3406
3659
  function renderAgentHookCommand(command, agent, profileId, event) {
3407
3660
  if (typeof profileId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(profileId) || profileId.includes(".."))
3408
3661
  throw new Error("Invalid selection profile id");
@@ -3928,7 +4181,7 @@ function isClaudePluginCacheOrphanMarker(path) {
3928
4181
  const at = path.indexOf(CACHE);
3929
4182
  if (at < 0 || path.indexOf(CACHE, at + 1) >= 0)
3930
4183
  return false;
3931
- const parts = path.slice(at + CACHE.length).split(sep2);
4184
+ const parts = path.slice(at + CACHE.length).split(sep22);
3932
4185
  return parts.length === 4 && parts.every((part) => part && part !== "." && part !== "..");
3933
4186
  }
3934
4187
  function same(left, right) {
@@ -4605,7 +4858,7 @@ function hashRawDiscoveryFile(path, budget2, changes) {
4605
4858
  if (bytes > AGENT_POLICY_LIMITS.discoveryRawSourceBytes)
4606
4859
  throw new Error("Raw discovery file byte limit exceeded");
4607
4860
  consume(budget2, bytes);
4608
- return createHash7("sha256").update(text2).digest("hex");
4861
+ return createHash72("sha256").update(text2).digest("hex");
4609
4862
  }
4610
4863
  const initial = lstatSync8(path, { throwIfNoEntry: false });
4611
4864
  if (!initial)
@@ -4619,7 +4872,7 @@ function hashRawDiscoveryFile(path, budget2, changes) {
4619
4872
  const opened = fstatSync4(fd);
4620
4873
  if (!opened.isFile() || !same3(initial, opened))
4621
4874
  throw new Error("Raw discovery input changed during open");
4622
- const hash = createHash7("sha256"), buffer = Buffer.alloc(64 * 1024);
4875
+ const hash = createHash72("sha256"), buffer = Buffer.alloc(64 * 1024);
4623
4876
  let bytes = 0;
4624
4877
  while (true) {
4625
4878
  const count = readSync3(fd, buffer, 0, Math.min(buffer.length, AGENT_POLICY_LIMITS.discoveryRawSourceBytes - bytes + 1), null);
@@ -4640,6 +4893,128 @@ function hashRawDiscoveryFile(path, budget2, changes) {
4640
4893
  closeSync42(fd);
4641
4894
  }
4642
4895
  }
4896
+ function invalidBundle(message) {
4897
+ throw new SkillBundleInspectionError("BUNDLE_INVALID", message);
4898
+ }
4899
+
4900
+ class BoundedTarReader {
4901
+ limits;
4902
+ check;
4903
+ header = new Uint8Array(BLOCK);
4904
+ headerOffset = 0;
4905
+ pending;
4906
+ bodyOffset = 0;
4907
+ padding = 0;
4908
+ zeroBlocks = 0;
4909
+ entries = [];
4910
+ paths = new SkillEntryPaths;
4911
+ fileBytes = 0;
4912
+ constructor(limits, check) {
4913
+ this.limits = limits;
4914
+ this.check = check;
4915
+ }
4916
+ push(chunk) {
4917
+ let offset = 0;
4918
+ while (offset < chunk.byteLength) {
4919
+ this.check();
4920
+ if (this.pending) {
4921
+ const count = Math.min(this.pending.bytes.byteLength - this.bodyOffset, chunk.byteLength - offset);
4922
+ this.pending.bytes.set(chunk.subarray(offset, offset + count), this.bodyOffset);
4923
+ offset += count;
4924
+ this.bodyOffset += count;
4925
+ if (this.bodyOffset === this.pending.bytes.byteLength) {
4926
+ this.entries.push(this.pending);
4927
+ this.pending = undefined;
4928
+ }
4929
+ } else if (this.padding) {
4930
+ const count = Math.min(this.padding, chunk.byteLength - offset);
4931
+ if (chunk.subarray(offset, offset + count).some((byte) => byte !== 0))
4932
+ invalidBundle("Nonzero tar body padding");
4933
+ offset += count;
4934
+ this.padding -= count;
4935
+ } else {
4936
+ const count = Math.min(BLOCK - this.headerOffset, chunk.byteLength - offset);
4937
+ this.header.set(chunk.subarray(offset, offset + count), this.headerOffset);
4938
+ offset += count;
4939
+ this.headerOffset += count;
4940
+ if (this.headerOffset === BLOCK) {
4941
+ this.readHeader();
4942
+ this.headerOffset = 0;
4943
+ }
4944
+ }
4945
+ }
4946
+ }
4947
+ finish() {
4948
+ this.check();
4949
+ if (this.pending || this.padding || this.headerOffset || this.zeroBlocks < 2)
4950
+ invalidBundle("Truncated tar bundle");
4951
+ return this.entries;
4952
+ }
4953
+ readHeader() {
4954
+ this.check();
4955
+ const h = this.header;
4956
+ if (h.every((byte) => byte === 0)) {
4957
+ this.zeroBlocks++;
4958
+ return;
4959
+ }
4960
+ if (this.zeroBlocks)
4961
+ invalidBundle("Nonzero tar data after terminator");
4962
+ if (this.entries.length >= this.limits.entries)
4963
+ throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle entry limit exceeded");
4964
+ let checksum = 0;
4965
+ for (let i = 0;i < BLOCK; i++)
4966
+ checksum += i >= 148 && i < 156 ? 32 : h[i];
4967
+ if (tarOctal(h.subarray(148, 156)) !== checksum)
4968
+ invalidBundle("Invalid tar header checksum");
4969
+ if (new TextDecoder().decode(h.subarray(257, 265)) !== "ustar\x00" + "00")
4970
+ invalidBundle("Unsupported tar format");
4971
+ if (h[156] !== 48 && h[156] !== 0 || h.subarray(157, 257).some((b) => b !== 0) || h.subarray(345).some((b) => b !== 0))
4972
+ invalidBundle("Unsupported tar entry or path prefix");
4973
+ const mode = tarOctal(h.subarray(100, 108));
4974
+ if (mode > 511)
4975
+ invalidBundle("Unsupported tar permission bits");
4976
+ tarOctal(h.subarray(108, 116));
4977
+ tarOctal(h.subarray(116, 124));
4978
+ tarOctal(h.subarray(136, 148));
4979
+ const size = tarOctal(h.subarray(124, 136));
4980
+ if (size > this.limits.fileBytes || this.fileBytes + size > this.limits.decompressedBytes) {
4981
+ throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle file byte limit exceeded");
4982
+ }
4983
+ const name = h.subarray(0, 100);
4984
+ const end = name.indexOf(0);
4985
+ if (end !== -1 && name.subarray(end).some((b) => b !== 0))
4986
+ invalidBundle("Invalid tar path padding");
4987
+ const raw = end === -1 ? name : name.subarray(0, end);
4988
+ if (raw.byteLength > this.limits.pathBytes)
4989
+ throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle path byte limit exceeded");
4990
+ let path;
4991
+ try {
4992
+ path = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(raw);
4993
+ } catch {
4994
+ return invalidBundle("Invalid UTF-8 bundle path");
4995
+ }
4996
+ this.paths.add(path, this.limits.pathBytes, invalidBundle, () => {
4997
+ throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle path byte limit exceeded");
4998
+ });
4999
+ this.fileBytes += size;
5000
+ this.pending = { path, mode, bytes: new Uint8Array(new ArrayBuffer(size)) };
5001
+ this.bodyOffset = 0;
5002
+ this.padding = (BLOCK - size % BLOCK) % BLOCK;
5003
+ if (!size) {
5004
+ this.entries.push(this.pending);
5005
+ this.pending = undefined;
5006
+ }
5007
+ }
5008
+ }
5009
+ function tarOctal(field2) {
5010
+ const text2 = new TextDecoder().decode(field2);
5011
+ if (!/^[0-7]+[\0 ]*$/.test(text2))
5012
+ invalidBundle("Invalid tar octal field");
5013
+ const value = Number.parseInt(text2, 8);
5014
+ if (!Number.isSafeInteger(value))
5015
+ invalidBundle("Tar integer is out of range");
5016
+ return value;
5017
+ }
4643
5018
  function isValidSkillVersion(value) {
4644
5019
  return typeof value === "string" && SKILL_VERSION_PATTERN.test(value) && !/^\.+$/.test(value) && !value.includes("..");
4645
5020
  }
@@ -7569,6 +7944,38 @@ function clientTransportEnvKeys(name) {
7569
7944
  function credentialPointerEnvKey(name) {
7570
7945
  return `HASNA_${envToken(name)}_API_KEY_REF`;
7571
7946
  }
7947
+ function normalizeSkillsApiOrigin(apiUrl) {
7948
+ const url = new URL(apiUrl);
7949
+ if (url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
7950
+ throw new SkillsFleetCredentialError("A Skills API URL must use HTTPS (or loopback HTTP), without credentials, query or fragment", "INVALID_API_URL");
7951
+ }
7952
+ const pathname = url.pathname.replace(/\/+$/, "");
7953
+ if (url.origin === "https://api.hasna.com" && pathname === "/skills/v1") {
7954
+ url.pathname = "/skills";
7955
+ } else if (pathname === "/api" || pathname === "/api/v1") {
7956
+ url.pathname = "/";
7957
+ } else if (pathname.endsWith("/api/v1")) {
7958
+ url.pathname = pathname.slice(0, -"/api/v1".length) || "/";
7959
+ } else if (pathname.endsWith("/api")) {
7960
+ url.pathname = pathname.slice(0, -"/api".length) || "/";
7961
+ }
7962
+ return url.toString().replace(/\/+$/, "");
7963
+ }
7964
+ function skillsApiRequestUrl(apiUrl, route) {
7965
+ const origin = normalizeSkillsApiOrigin(apiUrl);
7966
+ if (!route.startsWith("/api/") || route.includes("#") || route.includes("\\")) {
7967
+ throw new SkillsFleetCredentialError("Invalid Skills API route", "INVALID_API_URL");
7968
+ }
7969
+ if (origin === "https://api.hasna.com/skills") {
7970
+ if (route === "/api/auth/whoami")
7971
+ return `${origin}/v1/auth/whoami`;
7972
+ if (!route.startsWith("/api/v1/")) {
7973
+ throw new SkillsFleetCredentialError("The internal Skills gateway has no established login contract yet. Select an explicitly configured instance with supported authentication.", "GATEWAY_AUTH_UNAVAILABLE");
7974
+ }
7975
+ return `${origin}${route.slice("/api".length)}`;
7976
+ }
7977
+ return `${origin}${route}`;
7978
+ }
7572
7979
  function refuse3(code, detail) {
7573
7980
  throw new Error(`${code}: ${detail}`);
7574
7981
  }
@@ -18726,6 +19133,326 @@ function date4(params) {
18726
19133
  function escapeRegExp(value) {
18727
19134
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
18728
19135
  }
19136
+ function invalid3() {
19137
+ throw new Error(invalidWorkspaceResult);
19138
+ }
19139
+ function organization(v) {
19140
+ if (!record7(v) || !uuid8(v.id) || !text2(v.slug) || !text2(v.name))
19141
+ return invalid3();
19142
+ return { id: v.id, slug: v.slug, name: v.name };
19143
+ }
19144
+ function parseWorkspaceIdentity(value, expectedUserId) {
19145
+ if (!record7(value))
19146
+ return invalid3();
19147
+ const user = value.user;
19148
+ if (!record7(user) || !uuid8(user.id) || !uuid8(user.membershipId) || !text2(user.email, 320) || !(user.displayName === null || text2(user.displayName)) || !role2(user.role))
19149
+ return invalid3();
19150
+ if (user.id !== expectedUserId)
19151
+ throw new WorkspaceIdentityMismatchError;
19152
+ return { user: { id: user.id, membershipId: user.membershipId, email: user.email, displayName: user.displayName, role: user.role }, organization: organization(value.organization) };
19153
+ }
19154
+ function sessionToken(value) {
19155
+ if (typeof value !== "string" || !value || value.length > 8192 || /[^\x21-\x7e]/.test(value) || value.startsWith("sk_"))
19156
+ return invalid3();
19157
+ return value;
19158
+ }
19159
+ function parseWorkspaceSession(value, expected) {
19160
+ const identity5 = parseWorkspaceIdentity(value, expected.userId);
19161
+ if (identity5.user.membershipId !== expected.membershipId)
19162
+ throw new WorkspaceIdentityMismatchError;
19163
+ return { token: sessionToken(value.token), ...identity5 };
19164
+ }
19165
+ function checkedPrivateSkillCreate(value) {
19166
+ const refuse6 = (field3, accepted) => {
19167
+ throw new PrivatePublicationError("INVALID_SKILL_CREATE_INPUT", `Invalid ${field3}. ${accepted}`);
19168
+ };
19169
+ if (!record11(value) || !Object.keys(value).every((key2) => ["slug", "displayName", "description", "visibility", "confirm"].includes(key2)))
19170
+ return refuse6("create input", "Provide only slug, displayName, description, visibility and confirm.");
19171
+ if (value.confirm !== true)
19172
+ throw new PrivatePublicationError("SKILL_CREATE_CONFIRM_REQUIRED", "Explicit confirmation is required to create this skill.");
19173
+ if (typeof value.slug !== "string" || value.slug.length > 128 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value.slug))
19174
+ return refuse6("slug", "Use lowercase kebab-case, at most 128 characters.");
19175
+ if (typeof value.displayName !== "string" || !value.displayName.trim() || value.displayName.length > 256 || /[\p{Cc}\p{Cs}\u2028\u2029]/u.test(value.displayName))
19176
+ return refuse6("displayName", "Use nonempty text, at most 256 characters, without control characters.");
19177
+ 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, ""))))
19178
+ return refuse6("description", "Use text of at most 8192 UTF-8 bytes, without control characters other than tabs and newlines.");
19179
+ if (value.visibility !== undefined && value.visibility !== "private" && value.visibility !== "team")
19180
+ return refuse6("visibility", "Use private or team.");
19181
+ return Object.freeze({ slug: value.slug, displayName: value.displayName.trim(), description: value.description ?? "", visibility: value.visibility ?? "private" });
19182
+ }
19183
+ function checkedPublicationDeclaration(value) {
19184
+ 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)
19185
+ return bad();
19186
+ try {
19187
+ const manifest = JSON.parse(value.manifestText);
19188
+ if (!record11(manifest) || manifest.version !== value.version || validatePortableManifestContract(manifest, { strict: true }).length || !hash4(manifest.provenance?.content_hash))
19189
+ return bad();
19190
+ } catch {
19191
+ return bad();
19192
+ }
19193
+ return Object.freeze({ ...value });
19194
+ }
19195
+ function checkedPublicationView(value, skillId, intentId, declaration) {
19196
+ 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)
19197
+ return invalid4();
19198
+ if (declaration && ["version", "expectedCurrentVersionId", "archiveSha256", "archiveByteSize"].some((k) => value[k] !== declaration[k]))
19199
+ return invalid4();
19200
+ return Object.freeze({ ...value });
19201
+ }
19202
+ async function boundedJson(url2, init, token, mutation, budget3 = 15000, signal, create = false) {
19203
+ const controller = new AbortController;
19204
+ let reader;
19205
+ let response;
19206
+ 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);
19207
+ let timer;
19208
+ let abort;
19209
+ try {
19210
+ return await Promise.race([(async () => {
19211
+ if (signal?.aborted)
19212
+ throw timeout2;
19213
+ response = await fetch(url2, {
19214
+ ...init,
19215
+ redirect: "error",
19216
+ credentials: "omit",
19217
+ signal: controller.signal,
19218
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }
19219
+ });
19220
+ const length = response.headers.get("content-length");
19221
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > 65536))
19222
+ return invalid4();
19223
+ reader = response.body?.getReader();
19224
+ const chunks = [];
19225
+ let size = 0;
19226
+ if (reader)
19227
+ while (true) {
19228
+ const part = await reader.read();
19229
+ if (part.done)
19230
+ break;
19231
+ size += part.value.byteLength;
19232
+ if (size > 65536)
19233
+ return invalid4();
19234
+ chunks.push(part.value);
19235
+ }
19236
+ if (controller.signal.aborted)
19237
+ throw timeout2;
19238
+ const bytes = Buffer.concat(chunks);
19239
+ let body;
19240
+ try {
19241
+ body = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
19242
+ } catch {
19243
+ return invalid4();
19244
+ }
19245
+ if (!response.ok) {
19246
+ const known = create ? skillCreateFailures : failures2;
19247
+ const code = record11(body) && typeof body.code === "string" && Object.hasOwn(known, body.code) ? body.code : null;
19248
+ if (code && known[code][0] === response.status)
19249
+ throw new PrivatePublicationError(code, known[code][1], mutation && code === "PUBLICATION_UNCERTAIN", response.status);
19250
+ if (create) {
19251
+ if (response.status >= 500)
19252
+ throw timeout2;
19253
+ throw new PrivatePublicationError("SKILL_CREATE_REQUEST_FAILED", "The server refused skill creation.", false, response.status);
19254
+ }
19255
+ throw new PrivatePublicationError("PUBLICATION_REQUEST_FAILED", "The publication request was refused. Inspect its status before retrying.", mutation && response.status >= 500, response.status);
19256
+ }
19257
+ if (create && response.status !== 201)
19258
+ return invalid4();
19259
+ return body;
19260
+ })(), new Promise((_, reject) => {
19261
+ abort = () => {
19262
+ controller.abort();
19263
+ reject(timeout2);
19264
+ };
19265
+ timer = setTimeout(abort, Math.max(1, Math.min(15000, budget3)));
19266
+ signal?.addEventListener("abort", abort, { once: true });
19267
+ })]);
19268
+ } catch (error61) {
19269
+ if (error61 instanceof PrivatePublicationError) {
19270
+ if (mutation && error61.code === "INVALID_PUBLICATION_RESPONSE")
19271
+ throw timeout2;
19272
+ throw error61;
19273
+ }
19274
+ throw timeout2;
19275
+ } finally {
19276
+ if (timer)
19277
+ clearTimeout(timer);
19278
+ if (abort)
19279
+ signal?.removeEventListener("abort", abort);
19280
+ controller.abort();
19281
+ if (reader)
19282
+ reader.cancel().catch(() => {});
19283
+ else
19284
+ response?.body?.cancel().catch(() => {});
19285
+ }
19286
+ }
19287
+
19288
+ class RemotePrivatePublicationsClient {
19289
+ apiOrigin;
19290
+ organizationId;
19291
+ userId;
19292
+ membershipId;
19293
+ #token;
19294
+ constructor(apiUrl, session) {
19295
+ const checked = parseWorkspaceSession(session, { userId: session?.user?.id, membershipId: session?.user?.membershipId });
19296
+ if (checked.user.role === "viewer")
19297
+ throw new PrivatePublicationError("PUBLICATION_FORBIDDEN", failures2.PUBLICATION_FORBIDDEN[1]);
19298
+ this.apiOrigin = normalizeSkillsApiOrigin(apiUrl);
19299
+ this.#token = checked.token;
19300
+ this.organizationId = checked.organization.id;
19301
+ this.userId = checked.user.id;
19302
+ this.membershipId = checked.user.membershipId;
19303
+ Object.freeze(this);
19304
+ }
19305
+ async createSkill(input2, options = {}) {
19306
+ const body = checkedPrivateSkillCreate(input2);
19307
+ if (options.timeoutMs !== undefined && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 15000))
19308
+ throw new PrivatePublicationError("INVALID_SKILL_CREATE_INPUT", "Invalid timeoutMs. Use an integer from 1 to 15000.");
19309
+ const value = await boundedJson(skillsApiRequestUrl(this.apiOrigin, "/api/v1/skills"), { method: "POST", body: JSON.stringify(body) }, this.#token, true, options.timeoutMs, options.signal, true);
19310
+ 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)
19311
+ 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);
19312
+ return Object.freeze({ id: value.id, slug: body.slug, visibility: body.visibility, sourceType: "private_hosted", ownerOrganizationId: this.organizationId });
19313
+ }
19314
+ async getCapability(options = {}) {
19315
+ if (options.timeoutMs !== undefined && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 15000))
19316
+ return bad();
19317
+ const response = await boundedJson(skillsApiRequestUrl(this.apiOrigin, "/api/v1/capabilities"), {}, this.#token, false, options.timeoutMs, options.signal);
19318
+ const p = record11(response) && response.privatePublishing;
19319
+ 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")
19320
+ throw new PrivatePublicationError("PUBLICATION_CONTRACT_UNAVAILABLE", "This server does not support the hosted private publication contract.");
19321
+ return Object.freeze({ ...p });
19322
+ }
19323
+ async#gate(enabled, options = {}) {
19324
+ if (!(await this.getCapability(options)).enabled && enabled)
19325
+ throw new PrivatePublicationError("PUBLICATION_CAPABILITY_UNAVAILABLE", failures2.PUBLICATION_CAPABILITY_UNAVAILABLE[1]);
19326
+ }
19327
+ #path(skillId, intentId) {
19328
+ if (!publicationUuid(skillId) || intentId !== undefined && !publicationUuid(intentId))
19329
+ return bad();
19330
+ return skillsApiRequestUrl(this.apiOrigin, `/api/v1/skills/${skillId}/publication-uploads${intentId ? `/${intentId}` : ""}`);
19331
+ }
19332
+ async#view(path, method, skillId, intentId, declaration, options = {}) {
19333
+ const value = await boundedJson(path, { method, ...method === "GET" ? {} : { body: JSON.stringify(declaration ?? {}) } }, this.#token, method !== "GET", options.timeoutMs, options.signal);
19334
+ try {
19335
+ if (!record11(value) || !Object.keys(value).every((k) => k === "upload" || k === "changed") || value.changed !== undefined && typeof value.changed !== "boolean")
19336
+ return invalid4();
19337
+ return checkedPublicationView(value.upload, skillId, intentId, declaration);
19338
+ } catch (error61) {
19339
+ if (method !== "GET")
19340
+ throw new PrivatePublicationError("PUBLICATION_UNCONFIRMED", "The publication result could not be confirmed. Reconcile the saved intent before another action.", true);
19341
+ throw error61;
19342
+ }
19343
+ }
19344
+ async begin(skillId, input2) {
19345
+ const path = this.#path(skillId), declaration = checkedPublicationDeclaration(input2);
19346
+ await this.#gate(true);
19347
+ return this.#view(path, "POST", skillId, undefined, declaration);
19348
+ }
19349
+ async get(skillId, intentId, options = {}) {
19350
+ const path = this.#path(skillId, intentId), until = Date.now() + (options.timeoutMs ?? 15000);
19351
+ await this.#gate(false, options);
19352
+ return this.#view(path, "GET", skillId, intentId, undefined, { ...options, timeoutMs: Math.max(1, until - Date.now()) });
19353
+ }
19354
+ async finalize(skillId, intentId) {
19355
+ const path = this.#path(skillId, intentId);
19356
+ await this.#gate(true);
19357
+ return this.#view(`${path}/finalize`, "POST", skillId, intentId);
19358
+ }
19359
+ async cancel(skillId, intentId) {
19360
+ const path = this.#path(skillId, intentId);
19361
+ await this.#gate(false);
19362
+ return this.#view(path, "DELETE", skillId, intentId);
19363
+ }
19364
+ async upload(skillId, intent, bytes) {
19365
+ const captured = checkedPublicationView(intent, skillId), path = this.#path(skillId, captured.id);
19366
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength !== captured.archiveByteSize)
19367
+ return bad();
19368
+ const owned = Buffer.from(bytes);
19369
+ if (captured.state !== "awaiting_upload" || owned.byteLength !== captured.archiveByteSize || publicationSha256(owned) !== captured.archiveSha256)
19370
+ return bad();
19371
+ await this.#gate(true);
19372
+ const value = await boundedJson(`${path}/upload-url`, { method: "POST", body: "{}" }, this.#token, false);
19373
+ const upload = this.#upload(value, captured);
19374
+ const controller = new AbortController;
19375
+ let timer;
19376
+ 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);
19377
+ try {
19378
+ await Promise.race([(async () => {
19379
+ const response = await fetch(upload.uploadUrl, { method: "PUT", headers: upload.headers, body: owned, redirect: "error", credentials: "omit", signal: controller.signal });
19380
+ response.body?.cancel().catch(() => {});
19381
+ if (response.status !== 200 || controller.signal.aborted)
19382
+ throw uncertain();
19383
+ })(), new Promise((_, reject) => {
19384
+ timer = setTimeout(() => {
19385
+ controller.abort();
19386
+ reject(uncertain());
19387
+ }, 30000);
19388
+ })]);
19389
+ } catch {
19390
+ throw uncertain();
19391
+ } finally {
19392
+ if (timer)
19393
+ clearTimeout(timer);
19394
+ controller.abort();
19395
+ }
19396
+ }
19397
+ #upload(value, intent) {
19398
+ if (!exact(value, ["upload"]) || !exact(value.upload, ["method", "uploadUrl", "headers", "expiresAt"]))
19399
+ return invalid4();
19400
+ const p = value.upload;
19401
+ 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"]))
19402
+ return invalid4();
19403
+ let url2;
19404
+ try {
19405
+ url2 = new URL(p.uploadUrl);
19406
+ } catch {
19407
+ return invalid4();
19408
+ }
19409
+ 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") ?? ""))
19410
+ return invalid4();
19411
+ const queryKeys = ["X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date", "X-Amz-Expires", "X-Amz-Security-Token", "X-Amz-Signature", "X-Amz-SignedHeaders"];
19412
+ if ([...url2.searchParams.keys()].sort().join(",") !== queryKeys.sort().join(","))
19413
+ return invalid4();
19414
+ const issued = url2.searchParams.get("X-Amz-Date"), ttl = url2.searchParams.get("X-Amz-Expires"), credential = url2.searchParams.get("X-Amz-Credential");
19415
+ const timestamp3 = /^(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)Z$/.exec(issued);
19416
+ const region = url2.hostname.split(".s3.")[1].split(".amazonaws.com")[0];
19417
+ 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")))
19418
+ return invalid4();
19419
+ const issuedAt = Date.parse(`${timestamp3[1]}-${timestamp3[2]}-${timestamp3[3]}T${timestamp3[4]}:${timestamp3[5]}:${timestamp3[6]}Z`);
19420
+ if (!Number.isFinite(issuedAt) || issuedAt > Date.now() + 1000 || issuedAt + Number(ttl) * 1000 !== Date.parse(p.expiresAt))
19421
+ return invalid4();
19422
+ return { method: "PUT", uploadUrl: url2.href, expiresAt: p.expiresAt, headers: Object.freeze({ ...p.headers }) };
19423
+ }
19424
+ async wait(skillId, intentId, options = {}) {
19425
+ const timeout2 = options.timeoutMs ?? 60000;
19426
+ if (!Number.isSafeInteger(timeout2) || timeout2 < 0 || timeout2 > 300000)
19427
+ return bad();
19428
+ const until = Date.now() + timeout2;
19429
+ let previous;
19430
+ while (true) {
19431
+ if (options.signal?.aborted)
19432
+ throw new PrivatePublicationError("PUBLICATION_WAIT_ABORTED", "Stopped waiting. The server publication continues; inspect the saved intent.");
19433
+ let view;
19434
+ try {
19435
+ view = await this.get(skillId, intentId, { timeoutMs: timeout2 === 0 ? 15000 : Math.max(1, Math.min(15000, until - Date.now())), signal: options.signal });
19436
+ } catch (error61) {
19437
+ if (previous && Date.now() >= until && !options.signal?.aborted)
19438
+ return previous;
19439
+ throw error61;
19440
+ }
19441
+ previous = view;
19442
+ if (!["queued", "verifying"].includes(view.state) || Date.now() >= until)
19443
+ return view;
19444
+ await new Promise((resolve30) => {
19445
+ const timer = setTimeout(done, Math.min(1000, until - Date.now()));
19446
+ function done() {
19447
+ clearTimeout(timer);
19448
+ options.signal?.removeEventListener("abort", done);
19449
+ resolve30();
19450
+ }
19451
+ options.signal?.addEventListener("abort", done, { once: true });
19452
+ });
19453
+ }
19454
+ }
19455
+ }
18729
19456
  function recurringMcpSchema(action) {
18730
19457
  return action === "activate" ? recurringSurfaceSchemas.activate.extend({ code, confirm: exports_external.literal(true) }) : recurringSurfaceSchemas[action];
18731
19458
  }
@@ -18737,7 +19464,7 @@ var __defProp2, __commonJS2 = (cb, mod) => () => (mod || cb((mod = { exports: {}
18737
19464
  configurable: true,
18738
19465
  set: __exportSetter2.bind(all, name)
18739
19466
  });
18740
- }, __require2, require_identity, require_visit, require_directives, require_anchors, require_applyReviver, require_toJS, require_Node, require_Alias, require_Scalar, require_createNode, require_Collection, require_stringifyComment, require_foldFlowLines, require_stringifyString, require_stringify, require_stringifyPair, require_log, require_merge, require_addPairToJSMap, require_Pair, require_stringifyCollection, require_YAMLMap, require_map, require_YAMLSeq, require_seq, require_string, require_null, require_bool, require_stringifyNumber, require_float, require_int, require_schema, require_schema2, require_binary, require_pairs, require_omap, require_bool2, require_float2, require_int2, require_set, require_timestamp, require_schema3, require_tags, require_Schema, require_stringifyDocument, require_Document, require_errors, require_resolve_props, require_util_contains_newline, require_util_flow_indent_check, require_util_map_includes, require_resolve_block_map, require_resolve_block_seq, require_resolve_end, require_resolve_flow_collection, require_compose_collection, require_resolve_block_scalar, require_resolve_flow_scalar, require_compose_scalar, require_util_empty_scalar_position, require_compose_node, require_compose_doc, require_composer, require_cst_scalar, require_cst_stringify, require_cst_visit, require_cst, require_lexer, require_line_counter, require_parser, require_public_api, RETIRED_CONFIG_KEY_REASONS, PATHS_RESOLVER_DATA_ENV = "HASNA_DATA_HOME", PATHS_RESOLVER_APP_SLUG_RE2, DATA_DIR_ENV = "HASNA_SKILLS_DIR", HASNA_SKILLS_HOME_ENV = "HASNA_SKILLS_HOME", SKILLS_HOME_ENV = "SKILLS_HOME", DEFAULT_SQLITE_FILENAME = "server.db", GLOBAL_CONFIG_FILENAME = "config.json", SKILLS, HOSTED_RUNTIMES, HOSTED_SOURCES, HOSTED_METADATA_SET_EMPTY_ERROR, SLUG = "[^,{}/]+", BRACE_SOURCE_EXCLUSION, SINGLE_SOURCE_EXCLUSION, RESERVED_SKILL_ENTRIES, KNOWN_TOP_LEVEL_ENTRIES, VALID_PROVENANCE_SOURCES, HASH_EXCLUDE_DIRS, CONTENT_HASH_LIMITS, typedArrayPrototype, byteLengthOf, bufferOf, ANY_SEGMENT_COPY_EXCLUDES, FIRST_SEGMENT_COPY_EXCLUDES, NATIVE_SKILL_ROOTS, INTEGRATION_AGENTS, AGENT_ADAPTERS, CLAUDE_SETTINGS_WITNESS_LIMITS, sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino && a.mode === b.mode && a.uid === b.uid && a.gid === b.gid && a.nlink === b.nlink && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs, BOOLEAN_PREFERENCES, ENUM_PREFERENCES, BUILTIN_MODEL_SELECTIONS, CLAUDE_BUILTIN_THEMES, BUILTIN_THEMES, CLAUDE_COORDINATED_HOOK_EVENTS, PERSISTED_EFFORT_LEVELS, SUMI_DISCOVERY_PROJECTION_FIELDS, budget = () => ({ remaining: 256 * 1024 * 1024 }), MEASURED_CODEX_CAPABILITIES, SUPPORTED_CODEX_HOOK_VERSIONS, CLAUDE_MARKETPLACE_ENTRY_HASH_MODE = "claude-marketplace-entry-v1", DOMAIN = "hasna.skills.claude-marketplace-entry.v1\x00", PATH_CHARACTERS = 4096, NAME, bounded = (key) => key.length > 64 ? `${key.slice(0, 64)}...` : key, quote3 = (text) => JSON.stringify(text).replace(/[^\x20-\x7e]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`), child = (path, key) => path + (/^[A-Za-z0-9_$-]{1,64}$/.test(key) ? `.${key}` : `[${JSON.stringify(bounded(key))}]`), reason = (error) => String(error?.message ?? error).replace(/^Claude settings witness /, ""), MARKETPLACE_KEYS, MARKETPLACE_METADATA_KEYS, ENTRY_BOUND_KEYS, ENTRY_OMITTED_KEYS, EXPERIMENTAL_KEYS, SOURCE_KEYS, field = (object2, key) => object2.entries.find(([name]) => name === key)?.[1], isString = (value) => value?.kind === "string", isBoolean = (value) => value?.kind === "literal" && (value.value === "true" || value.value === "false"), stringArray = (value) => value?.kind === "array" && value.items.every(isString), stringObject = (value) => value?.kind === "object" && value.entries.every(([, item]) => isString(item)), CLAUDE_ORPHAN_MARKER_MODE = "claude-plugin-orphaned-at-v1", CACHE, AGENT_POLICY_LIMITS, composer, Document, Schema, errors, Alias, identity, Pair, Scalar, YAMLMap, YAMLSeq, cst, lexer, lineCounter, parser, publicApi, visit, $Composer, $Document, $Schema, $YAMLError, $YAMLParseError, $YAMLWarning, $Alias, $isAlias, $isCollection, $isDocument, $isMap, $isNode, $isPair, $isScalar, $isSeq, $Pair, $Scalar, $YAMLMap, $YAMLSeq, $Lexer, $LineCounter, $Parser, $parse, $parseAllDocuments, $parseDocument, $stringify, $visit, $visitAsync, HERMES_OPT_OUT = ".no-bundled-skills", NativeDiscoveryWitnessChange, ANY_SEGMENT_EXCLUDES, ROOT_EXCLUDES, TOOL_SIDECAR_FILENAMES, CREDENTIAL_FILENAMES, ENV_TEMPLATE_NAMES, NON_DOTENV_EXTENSIONS, SKILL_BUNDLE_INSPECTION_LIMITS, SKILL_VERSION_PATTERN, MAX_PROFILE_SELECTIONS = 4096, MAX_PROFILE_DOCUMENT_BYTES, MAX_SKILL_SESSION_ID_CHARS = 256, PROFILE_SESSION_ENVELOPE_BYTES, MAX_RESOLVED_PROFILE_BYTES, SkillSelectionError, MAX_CACHED_PROFILE_AGE_MS, PLUGIN_PROJECTION_LIMITS, pluginHash = (bytes) => createHash10("sha256").update(bytes).digest("hex"), READ_FLAGS, WRITE_FLAGS, uid = () => typeof process.getuid === "function" ? BigInt(process.getuid()) : undefined, missing = (error) => Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT"), sha2 = (text2) => createHash12("sha256").update(text2).digest("hex"), EFFORT, VERBOSITY, CODEX_PLUGIN_MANIFEST_LOCATIONS, CODEX_PLUGIN_MANIFEST_DIRECTORIES, CODEX_PLUGIN_ROOT_CAPABILITY_ENTRIES, need5 = (value) => {
19467
+ }, __require2, require_identity, require_visit, require_directives, require_anchors, require_applyReviver, require_toJS, require_Node, require_Alias, require_Scalar, require_createNode, require_Collection, require_stringifyComment, require_foldFlowLines, require_stringifyString, require_stringify, require_stringifyPair, require_log, require_merge, require_addPairToJSMap, require_Pair, require_stringifyCollection, require_YAMLMap, require_map, require_YAMLSeq, require_seq, require_string, require_null, require_bool, require_stringifyNumber, require_float, require_int, require_schema, require_schema2, require_binary, require_pairs, require_omap, require_bool2, require_float2, require_int2, require_set, require_timestamp, require_schema3, require_tags, require_Schema, require_stringifyDocument, require_Document, require_errors, require_resolve_props, require_util_contains_newline, require_util_flow_indent_check, require_util_map_includes, require_resolve_block_map, require_resolve_block_seq, require_resolve_end, require_resolve_flow_collection, require_compose_collection, require_resolve_block_scalar, require_resolve_flow_scalar, require_compose_scalar, require_util_empty_scalar_position, require_compose_node, require_compose_doc, require_composer, require_cst_scalar, require_cst_stringify, require_cst_visit, require_cst, require_lexer, require_line_counter, require_parser, require_public_api, RETIRED_CONFIG_KEY_REASONS, PATHS_RESOLVER_DATA_ENV = "HASNA_DATA_HOME", PATHS_RESOLVER_APP_SLUG_RE2, DATA_DIR_ENV = "HASNA_SKILLS_DIR", HASNA_SKILLS_HOME_ENV = "HASNA_SKILLS_HOME", SKILLS_HOME_ENV = "SKILLS_HOME", DEFAULT_SQLITE_FILENAME = "server.db", GLOBAL_CONFIG_FILENAME = "config.json", SKILLS, HOSTED_RUNTIMES, HOSTED_SOURCES, HOSTED_METADATA_SET_EMPTY_ERROR, SLUG = "[^,{}/]+", BRACE_SOURCE_EXCLUSION, SINGLE_SOURCE_EXCLUSION, RESERVED_SKILL_ENTRIES, KNOWN_TOP_LEVEL_ENTRIES, VALID_PROVENANCE_SOURCES, CONTENT_HASH_ALGORITHM = "sha256", HASH_EXCLUDE_DIRS, HASH_COVERAGE, CONTENT_HASH_LIMITS, typedArrayPrototype, byteLengthOf, bufferOf, PORTABLE_SKILL_STANDARD = "hasna.skill.v1", SKILL_RUNTIMES, SKILL_SANDBOX_MODES, SKILL_SYSTEM_DEPS_ALLOWLIST, 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-]+)*))?$", CONTENT_HASH_PATTERN = "^[a-f0-9]{64}$", ENV_REFERENCE_PATTERN = "^[A-Z0-9_]+$", MAX_RUNTIME_TIMEOUT_SECONDS = 900, ANY_SEGMENT_COPY_EXCLUDES, FIRST_SEGMENT_COPY_EXCLUDES, NATIVE_SKILL_ROOTS, INTEGRATION_AGENTS, AGENT_ADAPTERS, CLAUDE_SETTINGS_WITNESS_LIMITS, sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino && a.mode === b.mode && a.uid === b.uid && a.gid === b.gid && a.nlink === b.nlink && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs, BOOLEAN_PREFERENCES, ENUM_PREFERENCES, BUILTIN_MODEL_SELECTIONS, CLAUDE_BUILTIN_THEMES, BUILTIN_THEMES, CLAUDE_COORDINATED_HOOK_EVENTS, PERSISTED_EFFORT_LEVELS, SUMI_DISCOVERY_PROJECTION_FIELDS, budget = () => ({ remaining: 256 * 1024 * 1024 }), MEASURED_CODEX_CAPABILITIES, SUPPORTED_CODEX_HOOK_VERSIONS, CLAUDE_MARKETPLACE_ENTRY_HASH_MODE = "claude-marketplace-entry-v1", DOMAIN = "hasna.skills.claude-marketplace-entry.v1\x00", PATH_CHARACTERS = 4096, NAME, bounded = (key) => key.length > 64 ? `${key.slice(0, 64)}...` : key, quote3 = (text) => JSON.stringify(text).replace(/[^\x20-\x7e]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`), child = (path, key) => path + (/^[A-Za-z0-9_$-]{1,64}$/.test(key) ? `.${key}` : `[${JSON.stringify(bounded(key))}]`), reason = (error) => String(error?.message ?? error).replace(/^Claude settings witness /, ""), MARKETPLACE_KEYS, MARKETPLACE_METADATA_KEYS, ENTRY_BOUND_KEYS, ENTRY_OMITTED_KEYS, EXPERIMENTAL_KEYS, SOURCE_KEYS, field = (object2, key) => object2.entries.find(([name]) => name === key)?.[1], isString = (value) => value?.kind === "string", isBoolean = (value) => value?.kind === "literal" && (value.value === "true" || value.value === "false"), stringArray = (value) => value?.kind === "array" && value.items.every(isString), stringObject = (value) => value?.kind === "object" && value.entries.every(([, item]) => isString(item)), CLAUDE_ORPHAN_MARKER_MODE = "claude-plugin-orphaned-at-v1", CACHE, AGENT_POLICY_LIMITS, composer, Document, Schema, errors, Alias, identity, Pair, Scalar, YAMLMap, YAMLSeq, cst, lexer, lineCounter, parser, publicApi, visit, $Composer, $Document, $Schema, $YAMLError, $YAMLParseError, $YAMLWarning, $Alias, $isAlias, $isCollection, $isDocument, $isMap, $isNode, $isPair, $isScalar, $isSeq, $Pair, $Scalar, $YAMLMap, $YAMLSeq, $Lexer, $LineCounter, $Parser, $parse, $parseAllDocuments, $parseDocument, $stringify, $visit, $visitAsync, HERMES_OPT_OUT = ".no-bundled-skills", NativeDiscoveryWitnessChange, BLOCK = 512, ANY_SEGMENT_EXCLUDES, ROOT_EXCLUDES, TOOL_SIDECAR_FILENAMES, CREDENTIAL_FILENAMES, ENV_TEMPLATE_NAMES, NON_DOTENV_EXTENSIONS, SKILL_BUNDLE_INSPECTION_LIMITS, SkillBundleInspectionError, SKILL_VERSION_PATTERN, MAX_PROFILE_SELECTIONS = 4096, MAX_PROFILE_DOCUMENT_BYTES, MAX_SKILL_SESSION_ID_CHARS = 256, PROFILE_SESSION_ENVELOPE_BYTES, MAX_RESOLVED_PROFILE_BYTES, SkillSelectionError, MAX_CACHED_PROFILE_AGE_MS, PLUGIN_PROJECTION_LIMITS, pluginHash = (bytes) => createHash10("sha256").update(bytes).digest("hex"), READ_FLAGS, WRITE_FLAGS, uid = () => typeof process.getuid === "function" ? BigInt(process.getuid()) : undefined, missing = (error) => Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT"), sha2 = (text2) => createHash12("sha256").update(text2).digest("hex"), EFFORT, VERBOSITY, CODEX_PLUGIN_MANIFEST_LOCATIONS, CODEX_PLUGIN_MANIFEST_DIRECTORIES, CODEX_PLUGIN_ROOT_CAPABILITY_ENTRIES, need5 = (value) => {
18741
19468
  if (!value)
18742
19469
  throw new Error("Incomplete or unsupported reviewed Codex hook dependency");
18743
19470
  }, record2 = (value) => Boolean(value && typeof value === "object" && !Array.isArray(value)), identifier = (value) => typeof value === "string" && value.length > 0 && value.length <= 64 && !/[^A-Za-z0-9_-]/.test(value), events, need6 = (value) => {
@@ -18760,7 +19487,7 @@ var __defProp2, __commonJS2 = (cb, mod) => () => (mod || cb((mod = { exports: {}
18760
19487
  }, MAX_SKILLS = 4096, MAX_NAME_BYTES = 1024, MAX_PATH_BYTES = 16384, MAX_PLUGIN_ID_BYTES = 1024, object3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value), scalar = (value, max) => typeof value === "string" && value.length > 0 && value.trim() === value && Buffer.byteLength(value, "utf8") <= max && !/[\u0000-\u001f\u007f]/u.test(value), remotePluginIdentifier = (value) => typeof value === "string" && /^[A-Za-z0-9_~-]{1,1024}$/.test(value), absolutePath2 = (value) => scalar(value, MAX_PATH_BYTES) && isAbsolute15(value), identifier2 = (v) => typeof v === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(v), CODEX_DEFAULT_AGENT_PLUGIN_VERSION = "1.0.0", CODEX_VENDOR_MARKETPLACES, CODEX_REMOTE_VENDOR_MARKETPLACES, identifier3 = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value), record4 = (value) => Boolean(value && typeof value === "object" && !Array.isArray(value)), directory = (path) => {
18761
19488
  const stat2 = lstatSync15(path, { throwIfNoEntry: false });
18762
19489
  return Boolean(stat2?.isDirectory() && !stat2.isSymbolicLink());
18763
- }, OTHER_PLUGIN_CONTROLS, VENDOR_MANIFEST_KEYS, DEFAULT_SKILLS_PATHS, VENDOR_APP_DECLARATION = "./.app.json", MAX_SUBTREE_ENTRIES = 20000, MAX_SUBTREE_DEPTH = 32, hiddenName = (name) => name.startsWith(".") || name === "node_modules", isSkillDocument, present = (path) => lstatSync15(path, { throwIfNoEntry: false }) !== undefined, holdsOtherControl = (path) => readdirSync7(path).some((name) => OTHER_PLUGIN_CONTROLS.includes(codexPluginRootCapabilityEntry(name) ?? "")), MAX_TRAILING_VENDOR_ROWS = 16, MAX_VENDOR_TABLES = 8, MAX_CONFIG_CANDIDATES = 128, HEADER, CLAUDE_PLUGIN_MANIFEST_LIMITS, DESCRIPTIVE_FIELDS, version = "0.10.78", package_default, MAX_PACKAGE_BYTES, MAX_CREDENTIAL_FILE_BYTES, INSPECT_CUSTOM, CREDENTIAL_SEAL, AMBIENT_ENVIRONMENT, requireSecretsSdk, IDEMPOTENT_METHODS, AUTHORITY_OVERRIDE_HEADERS, urlKeys, SKILLS_APP = "skills", ENV_KEYS, SKILLS_API_URL_ENV_KEYS, SKILLS_API_KEY_ENV_KEYS, SKILLS_API_URL_ENV, SKILLS_API_KEY_ENV, MAX_REMOTE_FILE_BYTES, CODEX_NATIVE_POLICY_CAPABILITY = "host-path-allowlist-v1", CODEX_NATIVE_POLICY_RECEIPT_SCHEMA = "skills.codex-native-policy-acceptance/v1", CODEX_NATIVE_POLICY_ANCESTRY_SAFETY_HOPS = 64, POLICY_FIELDS, MAX_ENVELOPE_ID_LENGTH = 256, MAX_EXECUTABLE_BYTES, MAX_BRIDGE_DOCUMENT_BYTES, PLATFORM_KEY, HEX_DIGEST, CODEX_NATIVE_POLICY_FD_ENV = "CODEX_NATIVE_SKILL_POLICY_FD", CODEX_NATIVE_POLICY_PEER_SCHEMA = "native-hook-policy-peer-v1", CODEX_NATIVE_POLICY_HELPER_TIMEOUT_MS = 5000, CODEX_NATIVE_POLICY_HELPER_MAX_OUTPUT_BYTES, CODEX_NATIVE_POLICY_DEADLINE_MARGIN_MS = 1000, CODEX_NATIVE_POLICY_HELPER_MIN_TIMEOUT_MS = 500, CODEX_NATIVE_POLICY_FIRST_HASH_BUDGET_MS = 3000, CODEX_NATIVE_POLICY_EXECUTABLE_CACHE_SCHEMA = "skills.codex-native-policy-executable-cache/v1", object5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value), witnessKey = (path, witness) => JSON.stringify([path, witness.dev, witness.ino, witness.size, witness.mtimeNs, witness.ctimeNs, witness.uid]), executableDigestMemory, currentUid = () => process.getuid?.() ?? -1, CODEX_SEMANTIC_CACHE_WITNESS_SCHEMA = "hasna.codex-semantic-cache-witness.v1", SEMANTIC_BOUND_ROOT_ENTRIES, identifier5 = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value), digest2 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value), refuse4 = () => {
19490
+ }, OTHER_PLUGIN_CONTROLS, VENDOR_MANIFEST_KEYS, DEFAULT_SKILLS_PATHS, VENDOR_APP_DECLARATION = "./.app.json", MAX_SUBTREE_ENTRIES = 20000, MAX_SUBTREE_DEPTH = 32, hiddenName = (name) => name.startsWith(".") || name === "node_modules", isSkillDocument, present = (path) => lstatSync15(path, { throwIfNoEntry: false }) !== undefined, holdsOtherControl = (path) => readdirSync7(path).some((name) => OTHER_PLUGIN_CONTROLS.includes(codexPluginRootCapabilityEntry(name) ?? "")), MAX_TRAILING_VENDOR_ROWS = 16, MAX_VENDOR_TABLES = 8, MAX_CONFIG_CANDIDATES = 128, HEADER, CLAUDE_PLUGIN_MANIFEST_LIMITS, DESCRIPTIVE_FIELDS, version = "0.10.78", package_default, MAX_PACKAGE_BYTES, MAX_CREDENTIAL_FILE_BYTES, INSPECT_CUSTOM, CREDENTIAL_SEAL, AMBIENT_ENVIRONMENT, requireSecretsSdk, IDEMPOTENT_METHODS, AUTHORITY_OVERRIDE_HEADERS, urlKeys, SKILLS_APP = "skills", ENV_KEYS, SKILLS_API_URL_ENV_KEYS, SKILLS_API_KEY_ENV_KEYS, SKILLS_API_URL_ENV, SKILLS_API_KEY_ENV, SkillsFleetCredentialError, MAX_REMOTE_FILE_BYTES, CODEX_NATIVE_POLICY_CAPABILITY = "host-path-allowlist-v1", CODEX_NATIVE_POLICY_RECEIPT_SCHEMA = "skills.codex-native-policy-acceptance/v1", CODEX_NATIVE_POLICY_ANCESTRY_SAFETY_HOPS = 64, POLICY_FIELDS, MAX_ENVELOPE_ID_LENGTH = 256, MAX_EXECUTABLE_BYTES, MAX_BRIDGE_DOCUMENT_BYTES, PLATFORM_KEY, HEX_DIGEST, CODEX_NATIVE_POLICY_FD_ENV = "CODEX_NATIVE_SKILL_POLICY_FD", CODEX_NATIVE_POLICY_PEER_SCHEMA = "native-hook-policy-peer-v1", CODEX_NATIVE_POLICY_HELPER_TIMEOUT_MS = 5000, CODEX_NATIVE_POLICY_HELPER_MAX_OUTPUT_BYTES, CODEX_NATIVE_POLICY_DEADLINE_MARGIN_MS = 1000, CODEX_NATIVE_POLICY_HELPER_MIN_TIMEOUT_MS = 500, CODEX_NATIVE_POLICY_FIRST_HASH_BUDGET_MS = 3000, CODEX_NATIVE_POLICY_EXECUTABLE_CACHE_SCHEMA = "skills.codex-native-policy-executable-cache/v1", object5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value), witnessKey = (path, witness) => JSON.stringify([path, witness.dev, witness.ino, witness.size, witness.mtimeNs, witness.ctimeNs, witness.uid]), executableDigestMemory, currentUid = () => process.getuid?.() ?? -1, CODEX_SEMANTIC_CACHE_WITNESS_SCHEMA = "hasna.codex-semantic-cache-witness.v1", SEMANTIC_BOUND_ROOT_ENTRIES, identifier5 = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value), digest2 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value), refuse4 = () => {
18764
19491
  throw new Error("CODEX_SEMANTIC_CACHE_WITNESS_UNSUPPORTED: review Codex plugin cache identity and controls");
18765
19492
  }, MAX_DOCUMENT_BYTES, MAX_RECEIPT_BYTES, codexHookEvents, PLUGIN_MANIFESTS, PLUGIN_ROOT_DEPTH = 3, CLI_BRIDGE_NAME = "skills-cli", CLI_BRIDGE_VERSION = 1, markdown = `---
18766
19493
  name: skills-cli
@@ -26168,7 +26895,11 @@ This bridge contains no skill payloads. Do not copy skill content into agent-nat
26168
26895
  Codec: ZodCodec,
26169
26896
  Boolean: ZodBoolean,
26170
26897
  String: ZodString
26171
- }, ...args), ZodIssueCode, ZodFirstPartyTypeKind, exports_iso, z2, RECOGNIZED_KEYS, fullTime, RESOLVING, exports_coerce, API_URL_ENV_VAR, MISSING_API_URL_HINT, VENDOR_TERMS, VENDOR_TAGS, vendorPattern, remoteAvailabilitySchema, remoteSkillSchema, secretValuePatterns, remoteSkillDetailSchema, remoteRegistrySchema, ARTICLE_MAX_COUNT = 12, ARTICLE_COUNT_ERROR, TOOL_PRIMITIVES, primitiveByName, HOSTED_RUNTIME_SKILL_NAMES, RECURRING_CONTRACT_VERSION = 1, MAX_RECURRING_CREDITS = 2147483647, sha256Schema, boundedInteger, positiveInteger, instant, slug, recurringRequestSchema, recurringTermsSchema, recurringActivationSchema, uuid3, instant2, integer3, digest3, list, inputs, budget2, period, preview, consent, refusal2, occurrence, revocation, 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() }), results, SKILLS_API_KEY_REF, quoteUnavailableMessages, KNOWN_SKILL_LIFECYCLE_CODES, PRIVATE_PUBLICATION_MAX_BYTES, uuid12, sha6, common, intentSchema, stateSchema, uuid13, context, page2, directory2, email4, code, recurringSurfaceSchemas, recurringSurfaceOperations, SKILLS_CLI_MCP_PARITY, REMOTE_CUSTOMER_OPERATIONS, MCP_CONTRACT_SCHEMA_VERSION = 1, stringSchema = (description) => ({
26898
+ }, ...args), ZodIssueCode, ZodFirstPartyTypeKind, exports_iso, z2, RECOGNIZED_KEYS, fullTime, RESOLVING, exports_coerce, API_URL_ENV_VAR, MISSING_API_URL_HINT, VENDOR_TERMS, VENDOR_TAGS, vendorPattern, remoteAvailabilitySchema, remoteSkillSchema, secretValuePatterns, remoteSkillDetailSchema, remoteRegistrySchema, ARTICLE_MAX_COUNT = 12, ARTICLE_COUNT_ERROR, TOOL_PRIMITIVES, primitiveByName, HOSTED_RUNTIME_SKILL_NAMES, RECURRING_CONTRACT_VERSION = 1, MAX_RECURRING_CREDITS = 2147483647, sha256Schema, boundedInteger, positiveInteger, instant, slug, recurringRequestSchema, recurringTermsSchema, recurringActivationSchema, uuid3, instant2, integer3, digest3, list, inputs, budget2, period, preview, consent, refusal2, occurrence, revocation, 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() }), results, record7 = (v) => !!v && typeof v === "object" && !Array.isArray(v), 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), text2 = (v, max = 1024) => typeof v === "string" && !!v.trim() && v.length <= max && !/[\p{Cc}\p{Cs}\u2028\u2029]/u.test(v), role2 = (v) => typeof v === "string" && ["owner", "admin", "member", "viewer"].includes(v), invalidWorkspaceResult = "The server returned an invalid workspace selection result.", WorkspaceIdentityMismatchError, SKILLS_API_KEY_REF, quoteUnavailableMessages, KNOWN_SKILL_LIFECYCLE_CODES, PRIVATE_PUBLICATION_MAX_BYTES, skillCreateFailures, failures2, PrivatePublicationError, bad = () => {
26899
+ throw new PrivatePublicationError("INVALID_PUBLICATION_INPUT", "Invalid publication input or recovery data.");
26900
+ }, invalid4 = () => {
26901
+ throw new PrivatePublicationError("INVALID_PUBLICATION_RESPONSE", "The server returned an invalid publication result.");
26902
+ }, 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), hash4 = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v), record11 = (v) => !!v && typeof v === "object" && !Array.isArray(v), exact = (v, keys22) => record11(v) && Object.keys(v).sort().join(",") === keys22.sort().join(","), 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)), publicationSha256 = (bytes) => createHash34("sha256").update(bytes).digest("hex"), uuid12, sha6, common, intentSchema, stateSchema, uuid13, context, page2, directory2, email4, code, recurringSurfaceSchemas, recurringSurfaceOperations, SKILLS_CLI_MCP_PARITY, REMOTE_CUSTOMER_OPERATIONS, MCP_CONTRACT_SCHEMA_VERSION = 1, stringSchema = (description) => ({
26172
26903
  type: "string",
26173
26904
  description
26174
26905
  }), stringArraySchema = (description) => ({
@@ -33058,6 +33789,17 @@ ${end.comment}` : end.comment;
33058
33789
  ]);
33059
33790
  VALID_PROVENANCE_SOURCES = new Set(["official", "custom", "remote", "private", "private-hosted", "upstream", "extension"]);
33060
33791
  HASH_EXCLUDE_DIRS = new Set([".git", "node_modules", "dist", "build", ".turbo"]);
33792
+ HASH_COVERAGE = [
33793
+ "SKILL.md",
33794
+ "skill.json",
33795
+ "AGENTS.md",
33796
+ "package.json",
33797
+ "tsconfig.json",
33798
+ "src",
33799
+ "scripts",
33800
+ "assets",
33801
+ "references"
33802
+ ];
33061
33803
  CONTENT_HASH_LIMITS = Object.freeze({
33062
33804
  entries: 1024,
33063
33805
  rawBytes: 64 * 1024 * 1024,
@@ -33072,6 +33814,30 @@ ${end.comment}` : end.comment;
33072
33814
  typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
33073
33815
  byteLengthOf = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength").get;
33074
33816
  bufferOf = Object.getOwnPropertyDescriptor(typedArrayPrototype, "buffer").get;
33817
+ SKILL_RUNTIMES = ["bun", "node", "python3"];
33818
+ SKILL_SANDBOX_MODES = ["readonly-fs", "workspace-write", "full"];
33819
+ SKILL_SYSTEM_DEPS_ALLOWLIST = [
33820
+ "ffmpeg",
33821
+ "ffprobe",
33822
+ "imagemagick",
33823
+ "convert",
33824
+ "curl",
33825
+ "wget",
33826
+ "git",
33827
+ "gh",
33828
+ "jq",
33829
+ "python3",
33830
+ "pip3",
33831
+ "node",
33832
+ "bun",
33833
+ "npm",
33834
+ "rsync",
33835
+ "pdftotext",
33836
+ "tesseract",
33837
+ "7z",
33838
+ "unzip",
33839
+ "zip"
33840
+ ];
33075
33841
  ANY_SEGMENT_COPY_EXCLUDES = new Set([
33076
33842
  ".git",
33077
33843
  ".DS_Store",
@@ -33227,7 +33993,7 @@ ${end.comment}` : end.comment;
33227
33993
  archive: ["source", "url", "sha256"],
33228
33994
  command: ["source", "command", "timeout", "mode"]
33229
33995
  });
33230
- CACHE = `${sep2}.claude${sep2}plugins${sep2}cache${sep2}`;
33996
+ CACHE = `${sep22}.claude${sep22}plugins${sep22}cache${sep22}`;
33231
33997
  AGENT_POLICY_LIMITS = Object.freeze({ bytes: 1024 * 1024, agents: 16, discoverySources: 2048, discoveryRawSourceBytes: 64 * 1024 * 1024, discoveryRawTotalBytes: 256 * 1024 * 1024, discoveryPathLinks: 40, discoveryPathSteps: 256, discoveryPathSourceMetadataBytes: 64 * 1024, discoveryPathTotalMetadataBytes: 8 * 1024 * 1024, discoveryRoots: 512, discoveryDirectories: 64, discoveryDirectoryEntries: 20000, discoveryDirectoryBytes: 8 * 1024 * 1024, builtinNames: 2048, rootAliases: 2, fields: 64, pathCharacters: 4096 });
33232
33998
  composer = require_composer();
33233
33999
  Document = require_Document();
@@ -33411,6 +34177,14 @@ ${end.comment}` : end.comment;
33411
34177
  pathBytes: 100,
33412
34178
  timeoutMs: 5000
33413
34179
  });
34180
+ SkillBundleInspectionError = class SkillBundleInspectionError extends Error {
34181
+ code;
34182
+ constructor(code, message) {
34183
+ super(message);
34184
+ this.code = code;
34185
+ this.name = "SkillBundleInspectionError";
34186
+ }
34187
+ };
33414
34188
  SKILL_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
33415
34189
  MAX_PROFILE_DOCUMENT_BYTES = 8 * 1024 * 1024;
33416
34190
  PROFILE_SESSION_ENVELOPE_BYTES = MAX_PROFILE_SELECTIONS * 67 + MAX_SKILL_SESSION_ID_CHARS * 12 + 512;
@@ -33635,6 +34409,17 @@ ${end.comment}` : end.comment;
33635
34409
  SKILLS_API_KEY_ENV_KEYS = ENV_KEYS.apiKeyKeys;
33636
34410
  SKILLS_API_URL_ENV = SKILLS_API_URL_ENV_KEYS[0];
33637
34411
  SKILLS_API_KEY_ENV = SKILLS_API_KEY_ENV_KEYS[0];
34412
+ SkillsFleetCredentialError = class SkillsFleetCredentialError extends Error {
34413
+ code;
34414
+ next;
34415
+ constructor(message, code = "MISSING_API_CREDENTIAL", next) {
34416
+ super(message);
34417
+ this.name = "SkillsFleetCredentialError";
34418
+ this.code = code;
34419
+ if (next)
34420
+ this.next = next;
34421
+ }
34422
+ };
33638
34423
  MAX_REMOTE_FILE_BYTES = 64 * 1024 * 1024;
33639
34424
  POLICY_FIELDS = ["capability", "mode", "allowedHostPaths", "nonHostSources", "processId", "effectiveConfigDigest"];
33640
34425
  MAX_EXECUTABLE_BYTES = 2 * 1024 * 1024 * 1024;
@@ -38802,6 +39587,12 @@ ${end.comment}` : end.comment;
38802
39587
  cancellationIsSeparate: exports_external.literal(true)
38803
39588
  });
38804
39589
  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 };
39590
+ WorkspaceIdentityMismatchError = class WorkspaceIdentityMismatchError extends Error {
39591
+ constructor() {
39592
+ super("The verified account does not match the requested workspace context.");
39593
+ this.name = "WorkspaceIdentityMismatchError";
39594
+ }
39595
+ };
38805
39596
  SKILLS_API_KEY_REF = credentialPointerEnvKey("skills");
38806
39597
  quoteUnavailableMessages = Object.freeze({
38807
39598
  HOSTED_PROVIDER_UNAVAILABLE: "Hosted execution is temporarily unavailable on this Skills instance.",
@@ -38813,6 +39604,49 @@ ${end.comment}` : end.comment;
38813
39604
  });
38814
39605
  KNOWN_SKILL_LIFECYCLE_CODES = new Set(["SKILL_ARCHIVE_PROFILE_CONFLICT", "LIFECYCLE_ROLE_REQUIRED"]);
38815
39606
  PRIVATE_PUBLICATION_MAX_BYTES = 16 * 1024 * 1024;
39607
+ skillCreateFailures = {
39608
+ INVALID_SLUG: [400, "Provide a lowercase kebab-case skill slug."],
39609
+ INVALID_DISPLAY_NAME: [400, "Provide a nonempty skill display name."],
39610
+ INVALID_VISIBILITY: [400, "Use private or team visibility for source publication."],
39611
+ SESSION_EXPIRED: [401, "Sign in again before creating a private skill."],
39612
+ INTERACTIVE_SESSION_REQUIRED: [403, "An interactive account session is required to create a private skill."],
39613
+ ACCOUNT_UNAVAILABLE: [403, "The current account membership cannot create a private skill."],
39614
+ PLAN_REQUIRED: [403, "Private and team skills require the Pro plan."],
39615
+ SLUG_CONFLICT: [409, "This skill slug already exists. Inspect the existing skill before publishing."]
39616
+ };
39617
+ failures2 = {
39618
+ INVALID_REQUEST: [400, "The publication request is invalid."],
39619
+ SESSION_EXPIRED: [401, "Sign in again to manage this publication."],
39620
+ ACCOUNT_UNAVAILABLE: [403, "The account is unavailable."],
39621
+ INTERACTIVE_SESSION_REQUIRED: [403, "An interactive account session is required."],
39622
+ PUBLICATION_FORBIDDEN: [403, "This session cannot manage the publication."],
39623
+ PUBLICATION_ENTITLEMENT_REQUIRED: [403, "The workspace is not entitled to publish private skills."],
39624
+ PUBLICATION_UNAVAILABLE: [404, "The publication is unavailable to this session."],
39625
+ MANIFEST_NAME_MISMATCH: [409, "The manifest name does not match the selected skill."],
39626
+ IDEMPOTENCY_CONFLICT: [409, "This request key already identifies different publication bytes. Use the saved recovery directory."],
39627
+ CURRENT_VERSION_CHANGED: [409, "The current version changed. Inspect it before explicitly starting another publication."],
39628
+ VERSION_EXISTS: [409, "This version already exists."],
39629
+ VERSION_RESERVED: [409, "This version is reserved by another publication."],
39630
+ PUBLICATION_COMMITTED: [409, "The publication is already committed."],
39631
+ PUBLICATION_UPLOAD_UNAVAILABLE: [409, "This publication cannot receive another upload."],
39632
+ PUBLICATION_LIMIT: [429, "The workspace publication limit has been reached."],
39633
+ PUBLICATION_BUSY: [503, "The publication is busy. Reconcile the saved intent before retrying."],
39634
+ PUBLICATION_UNCERTAIN: [503, "The publication outcome is uncertain. Reconcile the saved intent."],
39635
+ PUBLICATION_CAPABILITY_UNAVAILABLE: [503, "Private publishing is not enabled on this server."],
39636
+ PUBLICATION_SIGNING_UNAVAILABLE: [503, "Upload authorization is temporarily unavailable. Keep the same intent."]
39637
+ };
39638
+ PrivatePublicationError = class PrivatePublicationError extends Error {
39639
+ code;
39640
+ uncertain;
39641
+ status;
39642
+ constructor(code, message, uncertain = false, status) {
39643
+ super(message);
39644
+ this.code = code;
39645
+ this.uncertain = uncertain;
39646
+ this.status = status;
39647
+ this.name = "PrivatePublicationError";
39648
+ }
39649
+ };
38816
39650
  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}$/);
38817
39651
  sha6 = exports_external.string().regex(/^[a-f0-9]{64}$/);
38818
39652
  common = exports_external.object({
@@ -40075,7 +40909,7 @@ var init_claude_skills_coordination = __esm(() => {
40075
40909
  });
40076
40910
 
40077
40911
  // src/lib/profiles.ts
40078
- import { existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync7, readdirSync as readdirSync3, rmSync as rmSync3, cpSync as cpSync2 } from "fs";
40912
+ import { existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync7, readdirSync as readdirSync4, rmSync as rmSync3, cpSync as cpSync2 } from "fs";
40079
40913
  import { join as join20 } from "path";
40080
40914
  function getProfilesDir() {
40081
40915
  const newDir = join20(getEffectiveDataRoot(), "profiles");
@@ -40131,7 +40965,7 @@ function listProfiles() {
40131
40965
  if (!existsSync12(dir))
40132
40966
  return [];
40133
40967
  try {
40134
- const files = readdirSync3(dir).filter((f) => f.endsWith(".json"));
40968
+ const files = readdirSync4(dir).filter((f) => f.endsWith(".json"));
40135
40969
  const profiles = [];
40136
40970
  for (const file2 of files) {
40137
40971
  try {
@@ -40193,7 +41027,7 @@ var init_profiles = __esm(() => {
40193
41027
 
40194
41028
  // src/lib/target-adapters.ts
40195
41029
  import { spawnSync } from "child_process";
40196
- 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";
41030
+ import { chmodSync as chmodSync2, existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync8, readdirSync as readdirSync8, rmdirSync as rmdirSync2, statSync, unlinkSync as unlinkSync3, writeFileSync as writeFileSync9, renameSync as renameSync5 } from "fs";
40197
41031
  import { tmpdir } from "os";
40198
41032
  import { basename as basename9, dirname as dirname9, join as join22 } from "path";
40199
41033
  import { randomUUID as randomUUID5 } from "crypto";
@@ -40221,8 +41055,8 @@ function adapterPath(target, options, hook) {
40221
41055
  throw new Error(`No capability record for target '${target}'`);
40222
41056
  return capabilities.configPath;
40223
41057
  }
40224
- function redactedDiagnostic(text2) {
40225
- const line = (text2.split(`
41058
+ function redactedDiagnostic(text3) {
41059
+ const line = (text3.split(`
40226
41060
  `).find((entry) => entry.trim()) ?? "").trim();
40227
41061
  return line.slice(0, 300).replace(/[A-Za-z0-9_\-]{24,}/g, "<redacted>");
40228
41062
  }
@@ -40233,16 +41067,16 @@ function messageOf(error61) {
40233
41067
  return error61 instanceof Error ? error61.message : String(error61);
40234
41068
  }
40235
41069
  function readJsonObject(path) {
40236
- let text2;
41070
+ let text3;
40237
41071
  try {
40238
- text2 = readFileSync8(path, "utf-8");
41072
+ text3 = readFileSync8(path, "utf-8");
40239
41073
  } catch (error61) {
40240
41074
  if (error61?.code === "ENOENT")
40241
41075
  return { status: "absent" };
40242
41076
  return { status: "unreadable", kind: "file", reason: `cannot read ${path} (${redactedDiagnostic(messageOf(error61))})` };
40243
41077
  }
40244
41078
  try {
40245
- const value = JSON.parse(text2);
41079
+ const value = JSON.parse(text3);
40246
41080
  if (!value || typeof value !== "object" || Array.isArray(value)) {
40247
41081
  return { status: "unreadable", kind: "content", reason: `${path} is not a JSON object` };
40248
41082
  }
@@ -40274,11 +41108,11 @@ function tomlString(value) {
40274
41108
  function tomlStringValue(raw) {
40275
41109
  return raw.replace(/\\"/g, '"').replace(/\\\\/g, "\\");
40276
41110
  }
40277
- function splitToml(text2) {
41111
+ function splitToml(text3) {
40278
41112
  const preamble = [];
40279
41113
  const chunks = [];
40280
41114
  let current2 = null;
40281
- for (const line of text2.split(`
41115
+ for (const line of text3.split(`
40282
41116
  `)) {
40283
41117
  if (TOML_HEADER_RE.test(line)) {
40284
41118
  if (current2)
@@ -40295,20 +41129,20 @@ function splitToml(text2) {
40295
41129
  return { preamble, chunks };
40296
41130
  }
40297
41131
  function chunkCommand(chunk) {
40298
- const text2 = chunk.lines.join(`
41132
+ const text3 = chunk.lines.join(`
40299
41133
  `);
40300
- const basic = text2.match(/^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/m);
41134
+ const basic = text3.match(/^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/m);
40301
41135
  if (basic)
40302
41136
  return tomlStringValue(basic[1]);
40303
- const literal2 = text2.match(/^\s*command\s*=\s*'([^']*)'/m);
41137
+ const literal2 = text3.match(/^\s*command\s*=\s*'([^']*)'/m);
40304
41138
  return literal2 ? literal2[1] : undefined;
40305
41139
  }
40306
41140
  function isKimiHookChunk(chunk) {
40307
41141
  return KIMI_HOOK_HEADER_RE.test(chunk.header);
40308
41142
  }
40309
- function kimiRegistrations(text2) {
41143
+ function kimiRegistrations(text3) {
40310
41144
  const out = [];
40311
- for (const chunk of splitToml(text2).chunks) {
41145
+ for (const chunk of splitToml(text3).chunks) {
40312
41146
  if (!isKimiHookChunk(chunk))
40313
41147
  continue;
40314
41148
  const command = chunkCommand(chunk);
@@ -40327,8 +41161,8 @@ function kimiBlock(command, timeoutSeconds) {
40327
41161
  ].join(`
40328
41162
  `);
40329
41163
  }
40330
- function removeKimiChunk(text2, hook) {
40331
- const { preamble, chunks } = splitToml(text2);
41164
+ function removeKimiChunk(text3, hook) {
41165
+ const { preamble, chunks } = splitToml(text3);
40332
41166
  const kept = [...preamble];
40333
41167
  let removed = false;
40334
41168
  for (const chunk of chunks) {
@@ -40542,7 +41376,7 @@ function museBundles(options) {
40542
41376
  if (!existsSync13(root))
40543
41377
  return [];
40544
41378
  const out = [];
40545
- for (const entry of readdirSync4(root)) {
41379
+ for (const entry of readdirSync8(root)) {
40546
41380
  const manifestPath = join22(root, entry, ".muse-plugin", "plugin.json");
40547
41381
  if (!existsSync13(manifestPath))
40548
41382
  continue;
@@ -40766,11 +41600,11 @@ function removeFromAdapter(target, hook, options) {
40766
41600
  if (existing.status === "unreadable") {
40767
41601
  return { removed: false, reason: `${existing.reason}, so Hooks cannot tell whether '${hook}' is registered; nothing was removed` };
40768
41602
  }
40769
- const { text: text2, removed } = removeKimiChunk(existing.status === "verified" ? existing.text : "", hook);
41603
+ const { text: text3, removed } = removeKimiChunk(existing.status === "verified" ? existing.text : "", hook);
40770
41604
  if (!removed)
40771
41605
  return { removed: false, reason: `no '${hook}' entry in ${path}` };
40772
- writeText(path, text2.endsWith(`
40773
- `) ? text2 : `${text2}
41606
+ writeText(path, text3.endsWith(`
41607
+ `) ? text3 : `${text3}
40774
41608
  `);
40775
41609
  return { removed: true };
40776
41610
  }
@@ -40876,31 +41710,31 @@ var init_target_adapters = __esm(() => {
40876
41710
  // src/lib/installer.ts
40877
41711
  var exports_installer = {};
40878
41712
  __export(exports_installer, {
40879
- adapterOptions: () => adapterOptions,
40880
- buildCodewithTomlFragment: () => buildCodewithTomlFragment,
40881
- detectRewriteConflict: () => detectRewriteConflict,
40882
- getHookPath: () => getHookPath,
40883
- getInstalledHooks: () => getInstalledHooks,
40884
- getRegisteredHooks: () => getRegisteredHooks,
40885
- getRegisteredHooksForTarget: () => getRegisteredHooksForTarget,
40886
- getSettingsPath: () => getSettingsPath,
40887
- hookExists: () => hookExists,
40888
- installHook: () => installHook,
40889
- installHooks: () => installHooks,
40890
- installNativeReadinessRegistration: () => installNativeReadinessRegistration,
40891
- isEventSupported: () => isEventSupported,
40892
- planClaudeSettingsWrite: () => planClaudeSettingsWrite,
40893
- previewNativeReadinessRegistration: () => previewNativeReadinessRegistration,
40894
- previewNativeSafetyRegistration: () => previewNativeSafetyRegistration,
40895
- pruneStaleRegistrations: () => pruneStaleRegistrations,
40896
- removeCodewithHookEntry: () => removeCodewithHookEntry,
40897
- removeFailureMessage: () => removeFailureMessage,
40898
- removeHook: () => removeHook,
40899
- scanStaleRegistrations: () => scanStaleRegistrations,
41713
+ writerRefusal: () => writerRefusal,
40900
41714
  uninstallHook: () => uninstallHook,
40901
- writerRefusal: () => writerRefusal
41715
+ scanStaleRegistrations: () => scanStaleRegistrations,
41716
+ removeHook: () => removeHook,
41717
+ removeFailureMessage: () => removeFailureMessage,
41718
+ removeCodewithHookEntry: () => removeCodewithHookEntry,
41719
+ pruneStaleRegistrations: () => pruneStaleRegistrations,
41720
+ previewNativeSafetyRegistration: () => previewNativeSafetyRegistration,
41721
+ previewNativeReadinessRegistration: () => previewNativeReadinessRegistration,
41722
+ planClaudeSettingsWrite: () => planClaudeSettingsWrite,
41723
+ isEventSupported: () => isEventSupported,
41724
+ installNativeReadinessRegistration: () => installNativeReadinessRegistration,
41725
+ installHooks: () => installHooks,
41726
+ installHook: () => installHook,
41727
+ hookExists: () => hookExists,
41728
+ getSettingsPath: () => getSettingsPath,
41729
+ getRegisteredHooksForTarget: () => getRegisteredHooksForTarget,
41730
+ getRegisteredHooks: () => getRegisteredHooks,
41731
+ getInstalledHooks: () => getInstalledHooks,
41732
+ getHookPath: () => getHookPath,
41733
+ detectRewriteConflict: () => detectRewriteConflict,
41734
+ buildCodewithTomlFragment: () => buildCodewithTomlFragment,
41735
+ adapterOptions: () => adapterOptions
40902
41736
  });
40903
- import { existsSync as existsSync14, mkdirSync as mkdirSync12, readFileSync as readFileSync13, readdirSync as readdirSync8, realpathSync as realpathSync7, rmdirSync as rmdirSync4, unlinkSync as unlinkSync6, writeFileSync as writeFileSync10 } from "fs";
41737
+ import { existsSync as existsSync14, mkdirSync as mkdirSync12, readFileSync as readFileSync13, readdirSync as readdirSync12, realpathSync as realpathSync7, rmdirSync as rmdirSync4, unlinkSync as unlinkSync6, writeFileSync as writeFileSync10 } from "fs";
40904
41738
  import { join as join24, dirname as dirname16, basename as basename12, resolve as resolve28 } from "path";
40905
41739
  import { homedir as homedir9 } from "os";
40906
41740
  import { fileURLToPath as fileURLToPath3 } from "url";
@@ -40967,13 +41801,13 @@ function readSettings(scope = "global", target = "claude") {
40967
41801
  let reason2 = "cannot be read";
40968
41802
  try {
40969
41803
  if (existsSync14(path)) {
40970
- const text2 = readFileSync13(path, "utf-8");
41804
+ const text3 = readFileSync13(path, "utf-8");
40971
41805
  reason2 = "is not valid JSON";
40972
- const value = JSON.parse(text2);
41806
+ const value = JSON.parse(text3);
40973
41807
  reason2 = "does not hold a JSON object";
40974
41808
  if (!value || typeof value !== "object" || Array.isArray(value))
40975
41809
  throw new TypeError(reason2);
40976
- settingsPreimages.set(value, { path, text: text2 });
41810
+ settingsPreimages.set(value, { path, text: text3 });
40977
41811
  return value;
40978
41812
  }
40979
41813
  } catch (error61) {
@@ -41755,7 +42589,7 @@ function codewithHasHookEntry(name, scope = "global") {
41755
42589
  }
41756
42590
  }
41757
42591
  function removeStoreDirFailClosed(dir) {
41758
- const entries = readdirSync8(dir, { withFileTypes: true });
42592
+ const entries = readdirSync12(dir, { withFileTypes: true });
41759
42593
  for (const entry of entries) {
41760
42594
  if (entry.isDirectory()) {
41761
42595
  removeStoreDirFailClosed(join24(dir, entry.name));
@@ -41983,7 +42817,7 @@ var init_installer = __esm(() => {
41983
42817
 
41984
42818
  // src/native-safety.ts
41985
42819
  import { execFile } from "child_process";
41986
- import { createHash as createHash18, randomUUID as randomUUID7 } from "crypto";
42820
+ import { createHash as createHash9, randomUUID as randomUUID7 } from "crypto";
41987
42821
  import { closeSync as closeSync5, constants as constants5, existsSync as existsSync15, fstatSync as fstatSync5, fsyncSync, linkSync, lstatSync as lstatSync16, mkdirSync as mkdirSync13, openSync as openSync5, readFileSync as readFileSync18, realpathSync as realpathSync11, renameSync as renameSync7, unlinkSync as unlinkSync8, writeFileSync as writeFileSync11 } from "fs";
41988
42822
  import { homedir as homedir10 } from "os";
41989
42823
  import { dirname as dirname23, isAbsolute as isAbsolute9, join as join32, resolve as resolve30 } from "path";
@@ -42017,8 +42851,8 @@ function readOwned(path) {
42017
42851
  closeSync5(fd);
42018
42852
  }
42019
42853
  }
42020
- function parseRecord(text2, home) {
42021
- const record6 = JSON.parse(text2);
42854
+ function parseRecord(text3, home) {
42855
+ const record6 = JSON.parse(text3);
42022
42856
  if (!record6 || Array.isArray(record6) || Object.keys(record6).sort().join() !== "command,harness,schema" || record6.schema !== "hasna.hooks.native-safety.v1" || record6.harness !== "sumi" || typeof record6.command !== "string")
42023
42857
  throw new NativeSafetyError("binding_invalid");
42024
42858
  const binding = nativeSafetyCommandBinding(record6.command);
@@ -42026,8 +42860,8 @@ function parseRecord(text2, home) {
42026
42860
  throw new NativeSafetyError("binding_invalid");
42027
42861
  return record6;
42028
42862
  }
42029
- function parseSumiRecord(text2, home) {
42030
- const record6 = parseRecord(text2, home);
42863
+ function parseSumiRecord(text3, home) {
42864
+ const record6 = parseRecord(text3, home);
42031
42865
  if (!isPreviousNativeSafetyCommand(record6.command))
42032
42866
  throw new NativeSafetyError("binding_invalid");
42033
42867
  return record6;
@@ -42048,8 +42882,8 @@ function nativeSafetyRecordText(command) {
42048
42882
  function readNativeSafetyRegistration(home = homedir10()) {
42049
42883
  try {
42050
42884
  home = canonicalHome(home);
42051
- const path = join32(home, ".hasna/hooks/native", filename), text2 = readOwned(path);
42052
- return { record: parseSumiRecord(text2, home), sha256: hash(text2), path, text: text2 };
42885
+ const path = join32(home, ".hasna/hooks/native", filename), text3 = readOwned(path);
42886
+ return { record: parseSumiRecord(text3, home), sha256: hash(text3), path, text: text3 };
42053
42887
  } catch (error61) {
42054
42888
  if (error61 instanceof NativeSafetyError)
42055
42889
  throw error61;
@@ -42075,8 +42909,8 @@ function nativeSafetyBindingIntegrityReason(home = homedir10()) {
42075
42909
  }
42076
42910
  function registerNativeSafety(options = {}) {
42077
42911
  const home = canonicalHome(options.home ?? homedir10());
42078
- const text2 = nativeSafetyRecordText(options.command ?? installedSumiNativeSafetyCommand());
42079
- parseSumiRecord(text2, home);
42912
+ const text3 = nativeSafetyRecordText(options.command ?? installedSumiNativeSafetyCommand());
42913
+ parseSumiRecord(text3, home);
42080
42914
  for (const dir of [join32(home, ".hasna"), join32(home, ".hasna/hooks"), join32(home, ".hasna/hooks/native")]) {
42081
42915
  try {
42082
42916
  mkdirSync13(dir, { mode: 448 });
@@ -42108,7 +42942,7 @@ function registerNativeSafety(options = {}) {
42108
42942
  if (!(error61 instanceof NativeSafetyError) || error61.code !== "binding_missing")
42109
42943
  throw error61;
42110
42944
  }
42111
- if (before?.sha256 === hash(text2))
42945
+ if (before?.sha256 === hash(text3))
42112
42946
  return { ok: true, changed: false, path, sha256: before.sha256 };
42113
42947
  if (before ? options.expectedSHA256 !== before.sha256 : options.expectedSHA256 !== undefined && options.expectedSHA256 !== "absent")
42114
42948
  throw new NativeSafetyError("binding_changed");
@@ -42134,7 +42968,7 @@ function registerNativeSafety(options = {}) {
42134
42968
  const fd = openSync5(temporary, constants5.O_CREAT | constants5.O_EXCL | constants5.O_WRONLY, 384);
42135
42969
  try {
42136
42970
  temporaryIdentity = fstatSync5(fd);
42137
- writeFileSync11(fd, text2);
42971
+ writeFileSync11(fd, text3);
42138
42972
  fsyncSync(fd);
42139
42973
  } finally {
42140
42974
  closeSync5(fd);
@@ -42151,7 +42985,7 @@ function registerNativeSafety(options = {}) {
42151
42985
  }
42152
42986
  syncDirectory(directory3);
42153
42987
  const after = readNativeSafetyRegistration(home);
42154
- if (after.sha256 !== hash(text2))
42988
+ if (after.sha256 !== hash(text3))
42155
42989
  throw new NativeSafetyError("binding_changed");
42156
42990
  return { ok: true, changed: true, path, sha256: after.sha256 };
42157
42991
  } finally {
@@ -42266,7 +43100,7 @@ async function verifyNativeSafetyExecutionRegistration(home = homedir10()) {
42266
43100
  throw new NativeSafetyError("binding_changed");
42267
43101
  return { path: before.path, sha256: before.sha256 };
42268
43102
  }
42269
- var NativeSafetyError, executionSchema = "hasna.hooks.execution.v1", hash = (value) => createHash18("sha256").update(value).digest("hex"), filename = "sumi-trash-guard.json", owner2 = (uid2) => uid2 === 0 || uid2 === process.getuid?.();
43103
+ var NativeSafetyError, executionSchema = "hasna.hooks.execution.v1", hash = (value) => createHash9("sha256").update(value).digest("hex"), filename = "sumi-trash-guard.json", owner2 = (uid2) => uid2 === 0 || uid2 === process.getuid?.();
42270
43104
  var init_native_safety2 = __esm(() => {
42271
43105
  init_native_safety();
42272
43106
  NativeSafetyError = class NativeSafetyError extends Error {
@@ -42284,13 +43118,13 @@ var init_native_safety2 = __esm(() => {
42284
43118
  // src/lib/native-safety-registration.ts
42285
43119
  var exports_native_safety_registration = {};
42286
43120
  __export(exports_native_safety_registration, {
42287
- NativeRegistrationError: () => NativeRegistrationError,
42288
- applyNativeReadinessRegistration: () => applyNativeReadinessRegistration,
42289
- applyNativeSafetyRegistration: () => applyNativeSafetyRegistration,
43121
+ planNativeSafetyRegistration: () => planNativeSafetyRegistration,
42290
43122
  planNativeReadinessRegistration: () => planNativeReadinessRegistration,
42291
- planNativeSafetyRegistration: () => planNativeSafetyRegistration
43123
+ applyNativeSafetyRegistration: () => applyNativeSafetyRegistration,
43124
+ applyNativeReadinessRegistration: () => applyNativeReadinessRegistration,
43125
+ NativeRegistrationError: () => NativeRegistrationError
42292
43126
  });
42293
- import { createHash as createHash20, randomUUID as randomUUID8 } from "crypto";
43127
+ import { createHash as createHash18, randomUUID as randomUUID8 } from "crypto";
42294
43128
  import { constants as constants9, closeSync as closeSync8, fstatSync as fstatSync8, fsyncSync as fsyncSync5, lstatSync as lstatSync18, mkdirSync as mkdirSync14, openSync as openSync8, readFileSync as readFileSync20, realpathSync as realpathSync14, writeFileSync as writeFileSync12 } from "fs";
42295
43129
  import { basename as basename16, dirname as dirname27, isAbsolute as isAbsolute14, join as join34, relative as relative2, resolve as resolve31 } from "path";
42296
43130
  import { homedir as homedir11 } from "os";
@@ -42370,8 +43204,8 @@ function read3(path) {
42370
43204
  function assertLosslessJson(raw) {
42371
43205
  const tokens = /"(?:\\[\s\S]|[^"\\])*"|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?|true|false|null|[{}\[\],:]/g;
42372
43206
  const stack = [];
42373
- function decimal(text2) {
42374
- const match = /^(-?)([0-9]+)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/.exec(text2);
43207
+ function decimal(text3) {
43208
+ const match = /^(-?)([0-9]+)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/.exec(text3);
42375
43209
  need11((match[4]?.replace(/^[+-]/, "").length ?? 0) <= 6, "settings_invalid");
42376
43210
  let digits = (match[2] + (match[3] ?? "")).replace(/^0+/, "");
42377
43211
  if (!digits)
@@ -42705,7 +43539,7 @@ async function applySumiRegistration(expectedPlanDigest, dependencies) {
42705
43539
  var NativeRegistrationError, need11 = (value, code2) => {
42706
43540
  if (!value)
42707
43541
  throw new NativeRegistrationError(code2);
42708
- }, sha7 = (value) => createHash20("sha256").update(value).digest("hex"), planNativeSafetyRegistration = (options, dependencies = {}) => planRegistration({ target: options.target, guard: options.guard ?? "trash-guard" }, dependencies), applyNativeSafetyRegistration = (options, dependencies = {}) => applyRegistration({ target: options.target, guard: options.guard ?? "trash-guard", expectedPlanDigest: options.expectedPlanDigest }, dependencies), planNativeReadinessRegistration = (options, sumiDependencies = {}) => options?.target === "sumi" ? planSumiRegistration(sumiDependencies) : planRegistration({ target: options?.target, guard: "trash-guard", readiness: true }), applyNativeReadinessRegistration = (options, sumiDependencies = {}) => options?.target === "sumi" ? applySumiRegistration(options.expectedPlanDigest, sumiDependencies) : applyRegistration({ target: options?.target, guard: "trash-guard", expectedPlanDigest: options?.expectedPlanDigest, readiness: true });
43542
+ }, sha7 = (value) => createHash18("sha256").update(value).digest("hex"), planNativeSafetyRegistration = (options, dependencies = {}) => planRegistration({ target: options.target, guard: options.guard ?? "trash-guard" }, dependencies), applyNativeSafetyRegistration = (options, dependencies = {}) => applyRegistration({ target: options.target, guard: options.guard ?? "trash-guard", expectedPlanDigest: options.expectedPlanDigest }, dependencies), planNativeReadinessRegistration = (options, sumiDependencies = {}) => options?.target === "sumi" ? planSumiRegistration(sumiDependencies) : planRegistration({ target: options?.target, guard: "trash-guard", readiness: true }), applyNativeReadinessRegistration = (options, sumiDependencies = {}) => options?.target === "sumi" ? applySumiRegistration(options.expectedPlanDigest, sumiDependencies) : applyRegistration({ target: options?.target, guard: "trash-guard", expectedPlanDigest: options?.expectedPlanDigest, readiness: true });
42709
43543
  var init_native_safety_registration = __esm(() => {
42710
43544
  init_installer();
42711
43545
  init_native_safety2();
@@ -42773,7 +43607,7 @@ var init_native_child_env = __esm(() => {
42773
43607
 
42774
43608
  // src/lib/codex-safety-check.ts
42775
43609
  import { spawn as spawn3, execFile as execFile2 } from "child_process";
42776
- import { createHash as createHash31 } from "crypto";
43610
+ import { createHash as createHash25 } from "crypto";
42777
43611
  import { constants as constants21, openSync as openSync15, closeSync as closeSync15, fstatSync as fstatSync15, lstatSync as lstatSync29, readFileSync as readFileSync22, realpathSync as realpathSync17 } from "fs";
42778
43612
  import { homedir as homedir13 } from "os";
42779
43613
  import { dirname as dirname30, isAbsolute as isAbsolute29, resolve as resolve35 } from "path";
@@ -43044,7 +43878,7 @@ async function verifyCodexNativeSafety(options = {}, dependencies = {}) {
43044
43878
  await rpc.close();
43045
43879
  }
43046
43880
  }
43047
- var SUPPORTED_CODEX_SAFETY_VERSIONS, versions, CODEX_EXECUTABLE_MAX_BYTES = 512000000, CodexSafetyError, digest4 = (bytes) => createHash31("sha256").update(bytes).digest("hex");
43881
+ var SUPPORTED_CODEX_SAFETY_VERSIONS, versions, CODEX_EXECUTABLE_MAX_BYTES = 512000000, CodexSafetyError, digest4 = (bytes) => createHash25("sha256").update(bytes).digest("hex");
43048
43882
  var init_codex_safety_check = __esm(() => {
43049
43883
  init_native_safety();
43050
43884
  init_registry();
@@ -43067,13 +43901,13 @@ var init_codex_safety_check = __esm(() => {
43067
43901
  // src/lib/codex-safety-trust.ts
43068
43902
  var exports_codex_safety_trust = {};
43069
43903
  __export(exports_codex_safety_trust, {
43070
- CodexTrustError: () => CodexTrustError,
43071
- applyCodexReadinessTrust: () => applyCodexReadinessTrust,
43072
- applyCodexSafetyTrust: () => applyCodexSafetyTrust,
43904
+ planCodexSafetyTrust: () => planCodexSafetyTrust,
43073
43905
  planCodexReadinessTrust: () => planCodexReadinessTrust,
43074
- planCodexSafetyTrust: () => planCodexSafetyTrust
43906
+ applyCodexSafetyTrust: () => applyCodexSafetyTrust,
43907
+ applyCodexReadinessTrust: () => applyCodexReadinessTrust,
43908
+ CodexTrustError: () => CodexTrustError
43075
43909
  });
43076
- import { createHash as createHash33, randomUUID as randomUUID9 } from "crypto";
43910
+ import { createHash as createHash31, randomUUID as randomUUID9 } from "crypto";
43077
43911
  import { constants as constants23, closeSync as closeSync20, fsyncSync as fsyncSync8, fstatSync as fstatSync20, lstatSync as lstatSync33, mkdirSync as mkdirSync15, openSync as openSync20, readFileSync as readFileSync23, realpathSync as realpathSync18, writeFileSync as writeFileSync13 } from "fs";
43078
43912
  import { dirname as dirname31, isAbsolute as isAbsolute31, join as join39, relative as relative7 } from "path";
43079
43913
  import { homedir as homedir14 } from "os";
@@ -43294,7 +44128,7 @@ async function applyTrust(options, dependencies = {}) {
43294
44128
  await rpc.close();
43295
44129
  }
43296
44130
  }
43297
- var CodexTrustError, sha10 = (value) => createHash33("sha256").update(value).digest("hex"), planCodexSafetyTrust = (options = {}, dependencies = {}) => planTrust({ ...options, readiness: false }, dependencies), applyCodexSafetyTrust = (options, dependencies = {}) => applyTrust({ ...options, readiness: false }, dependencies), planCodexReadinessTrust = (options = {}, dependencies = {}) => planTrust({ ...options, readiness: true }, dependencies), applyCodexReadinessTrust = (options, dependencies = {}) => applyTrust({ ...options, readiness: true }, dependencies);
44131
+ var CodexTrustError, sha10 = (value) => createHash31("sha256").update(value).digest("hex"), planCodexSafetyTrust = (options = {}, dependencies = {}) => planTrust({ ...options, readiness: false }, dependencies), applyCodexSafetyTrust = (options, dependencies = {}) => applyTrust({ ...options, readiness: false }, dependencies), planCodexReadinessTrust = (options = {}, dependencies = {}) => planTrust({ ...options, readiness: true }, dependencies), applyCodexReadinessTrust = (options, dependencies = {}) => applyTrust({ ...options, readiness: true }, dependencies);
43298
44132
  var init_codex_safety_trust = __esm(() => {
43299
44133
  init_codex_safety_check();
43300
44134
  init_native_safety2();
@@ -43315,7 +44149,7 @@ var init_codex_safety_trust = __esm(() => {
43315
44149
  });
43316
44150
 
43317
44151
  // ../../node_modules/.bun/commander@12.1.0/node_modules/commander/lib/error.js
43318
- var require_error = __commonJS(function(exports) {
44152
+ var require_error = __commonJS((exports) => {
43319
44153
  class CommanderError extends Error {
43320
44154
  constructor(exitCode, code2, message) {
43321
44155
  super(message);
@@ -43339,7 +44173,7 @@ var require_error = __commonJS(function(exports) {
43339
44173
  });
43340
44174
 
43341
44175
  // ../../node_modules/.bun/commander@12.1.0/node_modules/commander/lib/argument.js
43342
- var require_argument = __commonJS(function(exports) {
44176
+ var require_argument = __commonJS((exports) => {
43343
44177
  var { InvalidArgumentError } = require_error();
43344
44178
 
43345
44179
  class Argument {
@@ -43418,7 +44252,7 @@ var require_argument = __commonJS(function(exports) {
43418
44252
  });
43419
44253
 
43420
44254
  // ../../node_modules/.bun/commander@12.1.0/node_modules/commander/lib/help.js
43421
- var require_help = __commonJS(function(exports) {
44255
+ var require_help = __commonJS((exports) => {
43422
44256
  var { humanReadableArgName } = require_argument();
43423
44257
 
43424
44258
  class Help {
@@ -43667,7 +44501,7 @@ var require_help = __commonJS(function(exports) {
43667
44501
  });
43668
44502
 
43669
44503
  // ../../node_modules/.bun/commander@12.1.0/node_modules/commander/lib/option.js
43670
- var require_option = __commonJS(function(exports) {
44504
+ var require_option = __commonJS((exports) => {
43671
44505
  var { InvalidArgumentError } = require_error();
43672
44506
 
43673
44507
  class Option {
@@ -43818,7 +44652,7 @@ var require_option = __commonJS(function(exports) {
43818
44652
  });
43819
44653
 
43820
44654
  // ../../node_modules/.bun/commander@12.1.0/node_modules/commander/lib/suggestSimilar.js
43821
- var require_suggestSimilar = __commonJS(function(exports) {
44655
+ var require_suggestSimilar = __commonJS((exports) => {
43822
44656
  var maxDistance = 3;
43823
44657
  function editDistance(a, b) {
43824
44658
  if (Math.abs(a.length - b.length) > maxDistance)
@@ -43891,7 +44725,7 @@ var require_suggestSimilar = __commonJS(function(exports) {
43891
44725
  });
43892
44726
 
43893
44727
  // ../../node_modules/.bun/commander@12.1.0/node_modules/commander/lib/command.js
43894
- var require_command = __commonJS(function(exports) {
44728
+ var require_command = __commonJS((exports) => {
43895
44729
  var EventEmitter = __require("events").EventEmitter;
43896
44730
  var childProcess = __require("child_process");
43897
44731
  var path = __require("path");
@@ -45071,7 +45905,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
45071
45905
  }
45072
45906
  this._exit(exitCode, "commander.help", "(outputHelp)");
45073
45907
  }
45074
- addHelpText(position, text2) {
45908
+ addHelpText(position, text3) {
45075
45909
  const allowedValues = ["beforeAll", "before", "after", "afterAll"];
45076
45910
  if (!allowedValues.includes(position)) {
45077
45911
  throw new Error(`Unexpected value for position to addHelpText.
@@ -45080,10 +45914,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
45080
45914
  const helpEvent = `${position}Help`;
45081
45915
  this.on(helpEvent, (context3) => {
45082
45916
  let helpStr;
45083
- if (typeof text2 === "function") {
45084
- helpStr = text2({ error: context3.error, command: context3.command });
45917
+ if (typeof text3 === "function") {
45918
+ helpStr = text3({ error: context3.error, command: context3.command });
45085
45919
  } else {
45086
- helpStr = text2;
45920
+ helpStr = text3;
45087
45921
  }
45088
45922
  if (helpStr) {
45089
45923
  context3.write(`${helpStr}
@@ -45134,7 +45968,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
45134
45968
  });
45135
45969
 
45136
45970
  // ../../node_modules/.bun/commander@12.1.0/node_modules/commander/index.js
45137
- var require_commander = __commonJS(function(exports) {
45971
+ var require_commander = __commonJS((exports) => {
45138
45972
  var { Argument } = require_argument();
45139
45973
  var { Command } = require_command();
45140
45974
  var { CommanderError, InvalidArgumentError } = require_error();
@@ -45154,7 +45988,7 @@ var require_commander = __commonJS(function(exports) {
45154
45988
  });
45155
45989
 
45156
45990
  // ../../node_modules/.bun/cli-spinners@2.9.2/node_modules/cli-spinners/spinners.json
45157
- var require_spinners = __commonJS(function(exports, module) {
45991
+ var require_spinners = __commonJS((exports, module) => {
45158
45992
  module.exports = {
45159
45993
  dots: {
45160
45994
  interval: 80,
@@ -46780,7 +47614,7 @@ var require_spinners = __commonJS(function(exports, module) {
46780
47614
  });
46781
47615
 
46782
47616
  // ../../node_modules/.bun/cli-spinners@2.9.2/node_modules/cli-spinners/index.js
46783
- var require_cli_spinners = __commonJS(function(exports, module) {
47617
+ var require_cli_spinners = __commonJS((exports, module) => {
46784
47618
  var spinners = Object.assign({}, require_spinners());
46785
47619
  var spinnersList = Object.keys(spinners);
46786
47620
  Object.defineProperty(spinners, "random", {
@@ -47063,14 +47897,14 @@ function redactValue2(value) {
47063
47897
  }
47064
47898
  return value;
47065
47899
  }
47066
- function redactEventPayload(text2) {
47067
- if (text2 === null || text2 === undefined)
47900
+ function redactEventPayload(text3) {
47901
+ if (text3 === null || text3 === undefined)
47068
47902
  return null;
47069
47903
  try {
47070
- const parsed = JSON.parse(text2);
47904
+ const parsed = JSON.parse(text3);
47071
47905
  return redactText(JSON.stringify(redactValue2(parsed)));
47072
47906
  } catch {
47073
- return redactText(text2);
47907
+ return redactText(text3);
47074
47908
  }
47075
47909
  }
47076
47910
  function projectEventRowForRead(row) {
@@ -47278,10 +48112,10 @@ function credentialDiskSources(name, env) {
47278
48112
  function profileDiskSources(name, env, profile) {
47279
48113
  return credentialDiskSourceList(name, env, profile).map((s) => s.path);
47280
48114
  }
47281
- function parseEnvFile(text2) {
48115
+ function parseEnvFile(text3) {
47282
48116
  const values = new Map;
47283
48117
  const unusable = new Set;
47284
- for (const rawLine of text2.split(/\r?\n/)) {
48118
+ for (const rawLine of text3.split(/\r?\n/)) {
47285
48119
  const line = rawLine.trim();
47286
48120
  if (line.length === 0 || line.startsWith("#"))
47287
48121
  continue;
@@ -47506,8 +48340,8 @@ function keychainAccount(env, options) {
47506
48340
  const user = env.USER?.trim();
47507
48341
  return user || null;
47508
48342
  }
47509
- function keychainFailureHint(text2) {
47510
- const line = text2.split(/\r?\n/).find((entry) => entry.trim().length > 0)?.trim() ?? "";
48343
+ function keychainFailureHint(text3) {
48344
+ const line = text3.split(/\r?\n/).find((entry) => entry.trim().length > 0)?.trim() ?? "";
47511
48345
  const clean = line.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 200);
47512
48346
  return clean ? `: ${clean}` : "";
47513
48347
  }
@@ -48134,14 +48968,14 @@ var init_local_opt_in = __esm(() => {
48134
48968
  // src/lib/transport.ts
48135
48969
  var exports_transport = {};
48136
48970
  __export(exports_transport, {
48137
- __resetHooksLocalNotice: () => __resetHooksLocalNotice,
48138
- announceHooksLocalMode: () => announceHooksLocalMode,
48139
- hooksRegistryOrigin: () => hooksRegistryOrigin,
48140
- resolveHooksRequestAuthority: () => resolveHooksRequestAuthority,
48141
- resolveHooksServePublishKey: () => resolveHooksServePublishKey,
48142
- resolveHooksServePublishKeyAsync: () => resolveHooksServePublishKeyAsync,
48971
+ rethrowHooksAuthorityFailure: () => rethrowHooksAuthorityFailure,
48143
48972
  resolveHooksTransport: () => resolveHooksTransport,
48144
- rethrowHooksAuthorityFailure: () => rethrowHooksAuthorityFailure
48973
+ resolveHooksServePublishKeyAsync: () => resolveHooksServePublishKeyAsync,
48974
+ resolveHooksServePublishKey: () => resolveHooksServePublishKey,
48975
+ resolveHooksRequestAuthority: () => resolveHooksRequestAuthority,
48976
+ hooksRegistryOrigin: () => hooksRegistryOrigin,
48977
+ announceHooksLocalMode: () => announceHooksLocalMode,
48978
+ __resetHooksLocalNotice: () => __resetHooksLocalNotice
48145
48979
  });
48146
48980
  function __resetHooksLocalNotice() {
48147
48981
  localNoticePrinted = false;
@@ -48281,12 +49115,12 @@ var init_transport2 = __esm(() => {
48281
49115
  // src/lib/db-writer.ts
48282
49116
  var exports_db_writer = {};
48283
49117
  __export(exports_db_writer, {
48284
- __resetHookEventSinkNotice: () => __resetHookEventSinkNotice,
48285
- normalizeEventType: () => normalizeEventType,
48286
- recordHookRun: () => recordHookRun,
48287
- resolveEventType: () => resolveEventType,
49118
+ writeHookEvent: () => writeHookEvent,
48288
49119
  resolveHookEventSink: () => resolveHookEventSink,
48289
- writeHookEvent: () => writeHookEvent
49120
+ resolveEventType: () => resolveEventType,
49121
+ recordHookRun: () => recordHookRun,
49122
+ normalizeEventType: () => normalizeEventType,
49123
+ __resetHookEventSinkNotice: () => __resetHookEventSinkNotice
48290
49124
  });
48291
49125
  function resolveHookEventSink(env = process.env) {
48292
49126
  if (isLocalStoreRefused())
@@ -48482,7 +49316,7 @@ var init_stop_review_context = __esm(() => {
48482
49316
 
48483
49317
  // src/lib/hook-env.ts
48484
49318
  import { dirname as dirname36, isAbsolute as isAbsolute36 } from "path";
48485
- import { existsSync as existsSync17, realpathSync as realpathSync21, statSync as statSync4 } from "fs";
49319
+ import { existsSync as existsSync17, realpathSync as realpathSync21, statSync as statSync5 } from "fs";
48486
49320
  import { tmpdir as tmpdir2 } from "os";
48487
49321
  function isDeniedEnvName(name) {
48488
49322
  const upper = name.toUpperCase();
@@ -48523,7 +49357,7 @@ function isUnsafePathEntry(entry, home) {
48523
49357
  return true;
48524
49358
  }
48525
49359
  try {
48526
- if ((statSync4(entry).mode & 2) !== 0)
49360
+ if ((statSync5(entry).mode & 2) !== 0)
48527
49361
  return true;
48528
49362
  } catch {}
48529
49363
  return false;
@@ -48660,9 +49494,9 @@ var init_hook_env = __esm(() => {
48660
49494
  // src/lib/run.ts
48661
49495
  var exports_run = {};
48662
49496
  __export(exports_run, {
48663
- BUN_ISOLATION_FLAGS: () => BUN_ISOLATION_FLAGS,
49497
+ executeVerifiedScript: () => executeVerifiedScript,
48664
49498
  HookTimeoutError: () => HookTimeoutError,
48665
- executeVerifiedScript: () => executeVerifiedScript
49499
+ BUN_ISOLATION_FLAGS: () => BUN_ISOLATION_FLAGS
48666
49500
  });
48667
49501
  import { randomBytes as randomBytes2 } from "crypto";
48668
49502
  import { rmSync as rmSync5, writeFileSync as writeFileSync14 } from "fs";
@@ -48825,19 +49659,19 @@ var init_run = __esm(() => {
48825
49659
 
48826
49660
  // src/lib/sumi-stop-plugin.ts
48827
49661
  import { spawn as spawn5 } from "child_process";
48828
- import { createHash as createHash34 } from "crypto";
49662
+ import { createHash as createHash33 } from "crypto";
48829
49663
  import { closeSync as closeSync26, constants as constants25, fstatSync as fstatSync26, lstatSync as lstatSync37, openSync as openSync26, readFileSync as readFileSync29, realpathSync as realpathSync23 } from "fs";
48830
49664
  import { homedir as homedir17 } from "os";
48831
49665
  import { dirname as dirname38, isAbsolute as isAbsolute38, normalize as normalize4 } from "path";
48832
49666
  function isSumiStopReviewEnvelope(v) {
48833
- if (!record6(v) || !keys3(v, ["schema", "sessionId", "turnId", "inputRevision", "capturedAt", "lastUserPrompt", "lastAssistantMessage", "runtime"], ["goal", "goalAvailability"]) || v.schema !== "hooks.stop-review.v1" || !identifier4(v.sessionId) || !identifier4(v.turnId) || !identifier4(v.inputRevision) || typeof v.capturedAt !== "string" || !Number.isFinite(Date.parse(v.capturedAt)) || !text2(v.lastUserPrompt) || !text2(v.lastAssistantMessage) || !record6(v.runtime))
49667
+ if (!record6(v) || !keys3(v, ["schema", "sessionId", "turnId", "inputRevision", "capturedAt", "lastUserPrompt", "lastAssistantMessage", "runtime"], ["goal", "goalAvailability"]) || v.schema !== "hooks.stop-review.v1" || !identifier4(v.sessionId) || !identifier4(v.turnId) || !identifier4(v.inputRevision) || typeof v.capturedAt !== "string" || !Number.isFinite(Date.parse(v.capturedAt)) || !text3(v.lastUserPrompt) || !text3(v.lastAssistantMessage) || !record6(v.runtime))
48834
49668
  return false;
48835
49669
  const runtime = v.runtime;
48836
49670
  if (!keys3(runtime, [...FLAGS, "stopReason", "continuationCount"], ["agentPauseAdmission"]) || !FLAGS.every((key2) => typeof runtime[key2] === "boolean") || !STOP_REASONS.includes(runtime.stopReason) || !count(runtime.continuationCount))
48837
49671
  return false;
48838
49672
  if (runtime.agentPauseAdmission !== undefined && runtime.agentPauseAdmission !== "parent_final_cas")
48839
49673
  return false;
48840
- if (v.goal !== undefined && v.goal !== null && (!record6(v.goal) || !keys3(v.goal, ["id", "objective", "status"], ["statusSource", "pauseReason", "activationEpoch"]) || !identifier4(v.goal.id) || !text2(v.goal.objective) || !GOAL_STATUSES.includes(v.goal.status)))
49674
+ if (v.goal !== undefined && v.goal !== null && (!record6(v.goal) || !keys3(v.goal, ["id", "objective", "status"], ["statusSource", "pauseReason", "activationEpoch"]) || !identifier4(v.goal.id) || !text3(v.goal.objective) || !GOAL_STATUSES.includes(v.goal.status)))
48841
49675
  return false;
48842
49676
  if (record6(v.goal)) {
48843
49677
  const pauseFacts = [v.goal.statusSource, v.goal.pauseReason, v.goal.activationEpoch];
@@ -48866,10 +49700,10 @@ function isParentStopReviewResult(v, envelope, harness) {
48866
49700
  if (Math.abs(total - 1) > 0.02)
48867
49701
  return false;
48868
49702
  }
48869
- if (v.continuationPrompt !== undefined && !text2(v.continuationPrompt, 4096))
49703
+ if (v.continuationPrompt !== undefined && !text3(v.continuationPrompt, 4096))
48870
49704
  return false;
48871
49705
  if (v.action === "continue") {
48872
- return v.reason === "actionable_remaining" && v.classification === "actionable_remaining" && assessment !== undefined && v.instruction !== undefined && text2(v.continuationPrompt, 4096) && v.admission.settlement === "none";
49706
+ return v.reason === "actionable_remaining" && v.classification === "actionable_remaining" && assessment !== undefined && v.instruction !== undefined && text3(v.continuationPrompt, 4096) && v.admission.settlement === "none";
48873
49707
  }
48874
49708
  if (v.continuationPrompt !== undefined)
48875
49709
  return false;
@@ -48895,7 +49729,7 @@ function verifySumiStopReviewCommand(command, expected) {
48895
49729
  if (!before.isFile() || !owners.includes(before.uid) || (before.mode & 18) !== 0 || (before.mode & 64) === 0 || before.size < 1 || before.size > 268435456)
48896
49730
  return false;
48897
49731
  const bytes = readFileSync29(fd), after = fstatSync26(fd), target = lstatSync37(command);
48898
- return bytes.length === before.size && before.size === after.size && before.ino === after.ino && before.mtimeMs === after.mtimeMs && before.mode === after.mode && target.isFile() && target.ino === before.ino && target.dev === before.dev && target.size === before.size && target.mtimeMs === before.mtimeMs && realpathSync23(command) === command && createHash34("sha256").update(bytes).digest("hex") === expected;
49732
+ return bytes.length === before.size && before.size === after.size && before.ino === after.ino && before.mtimeMs === after.mtimeMs && before.mode === after.mode && target.isFile() && target.ino === before.ino && target.dev === before.dev && target.size === before.size && target.mtimeMs === before.mtimeMs && realpathSync23(command) === command && createHash33("sha256").update(bytes).digest("hex") === expected;
48899
49733
  } catch {
48900
49734
  return false;
48901
49735
  } finally {
@@ -48989,7 +49823,7 @@ function createSumiStopReviewPlugin(options, dependencies = {}) {
48989
49823
  }
48990
49824
  };
48991
49825
  }
48992
- var MAX_OUTPUT = 16384, CLASSES, FLAGS, GOAL_STATUSES, STOP_REASONS, CONFIG_ENV, record6 = (v) => !!v && typeof v === "object" && !Array.isArray(v), keys3 = (v, required2, optional2 = []) => required2.every((key2) => Object.hasOwn(v, key2)) && Object.keys(v).every((key2) => required2.includes(key2) || optional2.includes(key2)), identifier4 = (v) => typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(v), text2 = (v, max = Infinity) => typeof v === "string" && v.trim().length > 0 && Buffer.byteLength(v) <= max, probability = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1, count = (v) => Number.isSafeInteger(v) && v >= 0, className = (v) => CLASSES.includes(v), digest6 = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v), pathForm = (v) => typeof v === "string" && isAbsolute38(v) && normalize4(v) === v && Buffer.byteLength(v) <= 4096 && !/[\u0000-\u001f\u007f]/.test(v), sumiStopCapability = (v) => {
49826
+ var MAX_OUTPUT = 16384, CLASSES, FLAGS, GOAL_STATUSES, STOP_REASONS, CONFIG_ENV, record6 = (v) => !!v && typeof v === "object" && !Array.isArray(v), keys3 = (v, required2, optional2 = []) => required2.every((key2) => Object.hasOwn(v, key2)) && Object.keys(v).every((key2) => required2.includes(key2) || optional2.includes(key2)), identifier4 = (v) => typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(v), text3 = (v, max = Infinity) => typeof v === "string" && v.trim().length > 0 && Buffer.byteLength(v) <= max, probability = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1, count = (v) => Number.isSafeInteger(v) && v >= 0, className = (v) => CLASSES.includes(v), digest6 = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v), pathForm = (v) => typeof v === "string" && isAbsolute38(v) && normalize4(v) === v && Buffer.byteLength(v) <= 4096 && !/[\u0000-\u001f\u007f]/.test(v), sumiStopCapability = (v) => {
48993
49827
  if (!record6(v) || !keys3(v, ["schema", "admission", "harness"], ["agentPauseAdmission"]) || v.schema !== "hooks.stop-review.v1" || v.admission !== "parent_final_cas" || v.harness !== "sumi")
48994
49828
  return null;
48995
49829
  if (v.agentPauseAdmission === undefined)
@@ -49117,13 +49951,13 @@ var init_opencode_stop_plugin = __esm(() => {
49117
49951
  // src/lib/opencode-stop-install.ts
49118
49952
  var exports_opencode_stop_install = {};
49119
49953
  __export(exports_opencode_stop_install, {
49120
- OpenCodeStopInstallError: () => OpenCodeStopInstallError,
49121
- applyOpenCodeStopInstall: () => applyOpenCodeStopInstall,
49122
- installedOpenCodeStopPins: () => installedOpenCodeStopPins,
49123
- openCodeConfigPath: () => openCodeConfigPath,
49124
- openCodeStopEntry: () => openCodeStopEntry,
49954
+ verifyOpenCodeStopInstall: () => verifyOpenCodeStopInstall,
49125
49955
  planOpenCodeStopInstall: () => planOpenCodeStopInstall,
49126
- verifyOpenCodeStopInstall: () => verifyOpenCodeStopInstall
49956
+ openCodeStopEntry: () => openCodeStopEntry,
49957
+ openCodeConfigPath: () => openCodeConfigPath,
49958
+ installedOpenCodeStopPins: () => installedOpenCodeStopPins,
49959
+ applyOpenCodeStopInstall: () => applyOpenCodeStopInstall,
49960
+ OpenCodeStopInstallError: () => OpenCodeStopInstallError
49127
49961
  });
49128
49962
  import { createHash as createHash35, randomUUID as randomUUID11 } from "crypto";
49129
49963
  import {
@@ -49228,10 +50062,10 @@ function readConfig(path) {
49228
50062
  throw new OpenCodeStopInstallError("config_unsafe", `${path} is writable by group or others or not owned by this user`);
49229
50063
  if (stat2.size > MAX_CONFIG_BYTES)
49230
50064
  throw new OpenCodeStopInstallError("config_invalid", "config exceeds its size bound");
49231
- const text3 = readFileSync30(fd, "utf8");
50065
+ const text4 = readFileSync30(fd, "utf8");
49232
50066
  let config2;
49233
50067
  try {
49234
- config2 = JSON.parse(text3);
50068
+ config2 = JSON.parse(text4);
49235
50069
  } catch {
49236
50070
  throw new OpenCodeStopInstallError("config_invalid", "not strict JSON; edit JSONC by hand");
49237
50071
  }
@@ -49239,7 +50073,7 @@ function readConfig(path) {
49239
50073
  throw new OpenCodeStopInstallError("config_invalid", "config is not a JSON object");
49240
50074
  if (config2.plugin !== undefined && !Array.isArray(config2.plugin))
49241
50075
  throw new OpenCodeStopInstallError("config_invalid", "plugin is not an array");
49242
- return { path, text: text3, sha256: hash4(text3), mode: stat2.mode & 511, config: config2 };
50076
+ return { path, text: text4, sha256: hash5(text4), mode: stat2.mode & 511, config: config2 };
49243
50077
  } finally {
49244
50078
  closeSync27(fd);
49245
50079
  }
@@ -49261,12 +50095,12 @@ function siblingConflict(path) {
49261
50095
  throw new OpenCodeStopInstallError("config_unsafe");
49262
50096
  if (stat2.size > MAX_CONFIG_BYTES)
49263
50097
  throw new OpenCodeStopInstallError("config_invalid", "sibling config exceeds its size bound");
49264
- const text3 = readFileSync30(fd, "utf8");
50098
+ const text4 = readFileSync30(fd, "utf8");
49265
50099
  const after = fstatSync27(fd);
49266
- if (Buffer.byteLength(text3) > MAX_CONFIG_BYTES || stat2.size !== after.size || stat2.mtimeMs !== after.mtimeMs) {
50100
+ if (Buffer.byteLength(text4) > MAX_CONFIG_BYTES || stat2.size !== after.size || stat2.mtimeMs !== after.mtimeMs) {
49267
50101
  throw new OpenCodeStopInstallError("config_changed");
49268
50102
  }
49269
- if (text3.includes(OPENCODE_STOP_PLUGIN_SCHEMA) || text3.includes("opencode-stop-plugin"))
50103
+ if (text4.includes(OPENCODE_STOP_PLUGIN_SCHEMA) || text4.includes("opencode-stop-plugin"))
49270
50104
  return sibling;
49271
50105
  } finally {
49272
50106
  closeSync27(fd);
@@ -49285,16 +50119,16 @@ function plan(state, pins) {
49285
50119
  const entry = openCodeStopEntry(pins);
49286
50120
  const unchanged = owned.length === 1 && JSON.stringify(owned[0]) === JSON.stringify(entry);
49287
50121
  const next = { ...state.config, plugin: owned.length ? plugins.map((spec) => ownEntry(spec) ? entry : spec) : [...plugins, entry] };
49288
- const text3 = unchanged ? state.text : JSON.stringify(next, null, 2) + `
50122
+ const text4 = unchanged ? state.text : JSON.stringify(next, null, 2) + `
49289
50123
  `;
49290
50124
  return {
49291
- text: text3,
50125
+ text: text4,
49292
50126
  plan: {
49293
50127
  ok: true,
49294
50128
  target: "opencode",
49295
50129
  path: state.path,
49296
50130
  currentSha256: state.sha256,
49297
- desiredSha256: hash4(text3),
50131
+ desiredSha256: hash5(text4),
49298
50132
  action: unchanged ? "unchanged" : owned.length ? "update" : "add",
49299
50133
  ...owned.length ? { previousEntryVerified: entryVerified(owned[0]) } : {},
49300
50134
  entry,
@@ -49345,7 +50179,7 @@ function applyOpenCodeStopInstall(options) {
49345
50179
  if (state.text !== undefined) {
49346
50180
  const backup = `${options.path}.before-${state.sha256}`;
49347
50181
  if (existsSync18(backup)) {
49348
- if (hash4(readFileSync30(backup)) !== state.sha256)
50182
+ if (hash5(readFileSync30(backup)) !== state.sha256)
49349
50183
  throw new OpenCodeStopInstallError("config_changed", "a different preserved original already exists");
49350
50184
  } else {
49351
50185
  const fd2 = openSync27(backup, constants26.O_CREAT | constants26.O_EXCL | constants26.O_WRONLY, 384);
@@ -49355,7 +50189,7 @@ function applyOpenCodeStopInstall(options) {
49355
50189
  } finally {
49356
50190
  closeSync27(fd2);
49357
50191
  }
49358
- if (hash4(readFileSync30(backup)) !== state.sha256)
50192
+ if (hash5(readFileSync30(backup)) !== state.sha256)
49359
50193
  throw new OpenCodeStopInstallError("config_changed", "preserved original did not read back");
49360
50194
  }
49361
50195
  }
@@ -49427,7 +50261,7 @@ function verifyOpenCodeStopInstall(options) {
49427
50261
  nativeAdoptionVerified: false
49428
50262
  };
49429
50263
  }
49430
- var OpenCodeStopInstallError, MAX_CONFIG_BYTES = 1048576, MAX_PLUGIN_BYTES = 16777216, SIBLINGS, hash4 = (value) => createHash35("sha256").update(value).digest("hex"), owner3 = (uid2) => uid2 === 0 || uid2 === process.getuid?.(), record9 = (v) => !!v && typeof v === "object" && !Array.isArray(v), ownEntry = (spec) => Array.isArray(spec) && spec.length === 2 && typeof spec[0] === "string" && record9(spec[1]) && spec[1].schema === OPENCODE_STOP_PLUGIN_SCHEMA;
50264
+ var OpenCodeStopInstallError, MAX_CONFIG_BYTES = 1048576, MAX_PLUGIN_BYTES = 16777216, SIBLINGS, hash5 = (value) => createHash35("sha256").update(value).digest("hex"), owner3 = (uid2) => uid2 === 0 || uid2 === process.getuid?.(), record9 = (v) => !!v && typeof v === "object" && !Array.isArray(v), ownEntry = (spec) => Array.isArray(spec) && spec.length === 2 && typeof spec[0] === "string" && record9(spec[1]) && spec[1].schema === OPENCODE_STOP_PLUGIN_SCHEMA;
49431
50265
  var init_opencode_stop_install = __esm(() => {
49432
50266
  init_native_safety();
49433
50267
  init_sumi_binding();
@@ -49449,15 +50283,15 @@ var init_opencode_stop_install = __esm(() => {
49449
50283
  // src/lib/sumi-stop-install.ts
49450
50284
  var exports_sumi_stop_install = {};
49451
50285
  __export(exports_sumi_stop_install, {
49452
- SumiStopInstallError: () => SumiStopInstallError,
49453
- applySumiStopInstall: () => applySumiStopInstall,
49454
- installedSumiStopPins: () => installedSumiStopPins,
49455
- planSumiStopInstall: () => planSumiStopInstall,
49456
- sumiStopPluginPath: () => sumiStopPluginPath,
50286
+ verifySumiStopInstall: () => verifySumiStopInstall,
49457
50287
  sumiStopWrapper: () => sumiStopWrapper,
49458
- verifySumiStopInstall: () => verifySumiStopInstall
50288
+ sumiStopPluginPath: () => sumiStopPluginPath,
50289
+ planSumiStopInstall: () => planSumiStopInstall,
50290
+ installedSumiStopPins: () => installedSumiStopPins,
50291
+ applySumiStopInstall: () => applySumiStopInstall,
50292
+ SumiStopInstallError: () => SumiStopInstallError
49459
50293
  });
49460
- import { createHash as createHash36, randomUUID as randomUUID12 } from "crypto";
50294
+ import { createHash as createHash37, randomUUID as randomUUID12 } from "crypto";
49461
50295
  import { closeSync as closeSync28, constants as constants27, existsSync as existsSync19, fstatSync as fstatSync28, fsyncSync as fsyncSync11, linkSync as linkSync6, lstatSync as lstatSync39, mkdirSync as mkdirSync17, openSync as openSync28, readFileSync as readFileSync31, realpathSync as realpathSync26, renameSync as renameSync9, unlinkSync as unlinkSync10, writeFileSync as writeFileSync16 } from "fs";
49462
50296
  import { homedir as homedir19 } from "os";
49463
50297
  import { basename as basename20, dirname as dirname40, isAbsolute as isAbsolute40, join as join47, resolve as resolve39 } from "path";
@@ -49579,10 +50413,10 @@ function readState(path) {
49579
50413
  const stat2 = fstatSync28(fd);
49580
50414
  if (!stat2.isFile() || !owner4(stat2.uid) || stat2.mode & 18 || stat2.size > MAX_BYTES)
49581
50415
  throw new SumiStopInstallError("config_unsafe");
49582
- const text3 = readFileSync31(fd, "utf8");
49583
- if (Buffer.byteLength(text3) > MAX_BYTES)
50416
+ const text4 = readFileSync31(fd, "utf8");
50417
+ if (Buffer.byteLength(text4) > MAX_BYTES)
49584
50418
  throw new SumiStopInstallError("config_unsafe");
49585
- return { path, text: text3, sha256: hash6(text3), mode: stat2.mode & 511 };
50419
+ return { path, text: text4, sha256: hash7(text4), mode: stat2.mode & 511 };
49586
50420
  } finally {
49587
50421
  closeSync28(fd);
49588
50422
  }
@@ -49619,14 +50453,14 @@ function plan2(state, pins) {
49619
50453
  const previous = storedPins(state);
49620
50454
  if (!pinsVerified(pins))
49621
50455
  throw new SumiStopInstallError("pins_drifted");
49622
- const text3 = sumiStopWrapper(pins);
49623
- return { text: text3, plan: {
50456
+ const text4 = sumiStopWrapper(pins);
50457
+ return { text: text4, plan: {
49624
50458
  ok: true,
49625
50459
  target: "sumi",
49626
50460
  path: state.path,
49627
50461
  currentSha256: state.sha256,
49628
- desiredSha256: hash6(text3),
49629
- action: state.text === text3 ? "unchanged" : previous ? "update" : "add",
50462
+ desiredSha256: hash7(text4),
50463
+ action: state.text === text4 ? "unchanged" : previous ? "update" : "add",
49630
50464
  ...previous ? { previousEntryVerified: pinsVerified(previous) } : {},
49631
50465
  nativeAdoptionVerified: false,
49632
50466
  mayAffectRunningSessions: true
@@ -49750,7 +50584,7 @@ function verifySumiStopInstall(options) {
49750
50584
  };
49751
50585
  }
49752
50586
  var SumiStopInstallError, HEADER2 = `// @hasna/hooks managed Sumi stop-review v1
49753
- `, NAME2 = "hasna-hooks-stop-review", MAX_BYTES = 1048576, hash6 = (value) => createHash36("sha256").update(value).digest("hex"), owner4 = (uid2) => uid2 === 0 || uid2 === process.getuid?.();
50587
+ `, NAME2 = "hasna-hooks-stop-review", MAX_BYTES = 1048576, hash7 = (value) => createHash37("sha256").update(value).digest("hex"), owner4 = (uid2) => uid2 === 0 || uid2 === process.getuid?.();
49754
50588
  var init_sumi_stop_install = __esm(() => {
49755
50589
  init_opencode_stop_install();
49756
50590
  init_native_safety();
@@ -49771,9 +50605,9 @@ var init_sumi_stop_install = __esm(() => {
49771
50605
  // src/lib/custom-install.ts
49772
50606
  var exports_custom_install = {};
49773
50607
  __export(exports_custom_install, {
49774
- ensureCustomDir: () => ensureCustomDir,
50608
+ isCustomSource: () => isCustomSource,
49775
50609
  installCustomSource: () => installCustomSource,
49776
- isCustomSource: () => isCustomSource
50610
+ ensureCustomDir: () => ensureCustomDir
49777
50611
  });
49778
50612
  import { existsSync as existsSync20, mkdirSync as mkdirSync18, mkdtempSync as mkdtempSync2, readFileSync as readFileSync32, rmSync as rmSync6 } from "fs";
49779
50613
  import { join as join48 } from "path";
@@ -49886,21 +50720,21 @@ var init_custom_install = __esm(() => {
49886
50720
  // src/lib/sync.ts
49887
50721
  var exports_sync = {};
49888
50722
  __export(exports_sync, {
49889
- commitSyncArtifacts: () => commitSyncArtifacts,
49890
- fetchPinnedHook: () => fetchPinnedHook,
49891
- installPinnedFromBundled: () => installPinnedFromBundled,
49892
- planSync: () => planSync,
50723
+ syncHooks: () => syncHooks,
49893
50724
  stageSyncArtifacts: () => stageSyncArtifacts,
49894
- syncHooks: () => syncHooks
50725
+ planSync: () => planSync,
50726
+ installPinnedFromBundled: () => installPinnedFromBundled,
50727
+ fetchPinnedHook: () => fetchPinnedHook,
50728
+ commitSyncArtifacts: () => commitSyncArtifacts
49895
50729
  });
49896
- import { createHash as createHash37, randomUUID as randomUUID13 } from "crypto";
50730
+ import { createHash as createHash38, randomUUID as randomUUID13 } from "crypto";
49897
50731
  import { readFileSync as readFileSync33, lstatSync as lstatSync40, mkdirSync as mkdirSync19, writeFileSync as writeFileSync17, accessSync as accessSync5, constants as constants28, existsSync as existsSync21 } from "fs";
49898
50732
  import { dirname as dirname41, join as join49, resolve as resolve40, sep as sep18 } from "path";
49899
- function sha256OfText(text3) {
49900
- return createHash37("sha256").update(text3).digest("hex");
50733
+ function sha256OfText(text4) {
50734
+ return createHash38("sha256").update(text4).digest("hex");
49901
50735
  }
49902
50736
  function sha256OfPath(path) {
49903
- return createHash37("sha256").update(readFileSync33(path)).digest("hex");
50737
+ return createHash38("sha256").update(readFileSync33(path)).digest("hex");
49904
50738
  }
49905
50739
  function collectBundledCatalog() {
49906
50740
  const out = [];
@@ -50101,7 +50935,7 @@ function prepareRegistryCommit(staged) {
50101
50935
  writeFileSync17(path, bytes, { flag: "wx", mode: 384 });
50102
50936
  if (!readFileSync33(path).equals(bytes))
50103
50937
  throw new Error("REGISTRY_PRESERVATION_READBACK_FAILED");
50104
- receipt.push({ target, preserved: path, sha256: createHash37("sha256").update(bytes).digest("hex"), readback: true });
50938
+ receipt.push({ target, preserved: path, sha256: createHash38("sha256").update(bytes).digest("hex"), readback: true });
50105
50939
  }
50106
50940
  writeFileSync17(join49(recovery, "receipt.json"), JSON.stringify(receipt, null, 2) + `
50107
50941
  `, { flag: "wx", mode: 384 });
@@ -50358,8 +51192,8 @@ var init_pg_migrations = __esm(() => {
50358
51192
  // src/db/remote-storage.ts
50359
51193
  var exports_remote_storage = {};
50360
51194
  __export(exports_remote_storage, {
50361
- PgAdapterAsync: () => PgAdapterAsync,
50362
- sslConfigFor: () => sslConfigFor
51195
+ sslConfigFor: () => sslConfigFor,
51196
+ PgAdapterAsync: () => PgAdapterAsync
50363
51197
  });
50364
51198
  import pg from "pg";
50365
51199
  function translatePlaceholders(sql) {
@@ -50454,29 +51288,29 @@ var init_remote_storage = () => {};
50454
51288
  // src/db/storage-sync.ts
50455
51289
  var exports_storage_sync = {};
50456
51290
  __export(exports_storage_sync, {
50457
- HOOKS_STORAGE_BACKEND_ENV: () => HOOKS_STORAGE_BACKEND_ENV,
50458
- HOOKS_STORAGE_BACKEND_FALLBACK_ENV: () => HOOKS_STORAGE_BACKEND_FALLBACK_ENV,
50459
- HOOKS_STORAGE_ENV: () => HOOKS_STORAGE_ENV,
50460
- HOOKS_STORAGE_FALLBACK_ENV: () => HOOKS_STORAGE_FALLBACK_ENV,
50461
- HOOKS_STORAGE_TABLES: () => HOOKS_STORAGE_TABLES,
50462
- RETIRED_STORAGE_MODE_ENV: () => RETIRED_STORAGE_MODE_ENV,
50463
- STORAGE_BACKENDS: () => STORAGE_BACKENDS,
50464
- STORAGE_BACKEND_ENV: () => STORAGE_BACKEND_ENV,
50465
- STORAGE_DATABASE_ENV: () => STORAGE_DATABASE_ENV,
50466
- STORAGE_TABLES: () => STORAGE_TABLES,
50467
- getStorageBackend: () => getStorageBackend,
50468
- getStorageDatabaseEnv: () => getStorageDatabaseEnv,
50469
- getStorageDatabaseEnvName: () => getStorageDatabaseEnvName,
50470
- getStorageDatabaseUrl: () => getStorageDatabaseUrl,
50471
- getStoragePg: () => getStoragePg,
50472
- getStorageStatus: () => getStorageStatus,
50473
- getSyncMetaAll: () => getSyncMetaAll,
50474
- parseStorageTables: () => parseStorageTables,
50475
- resolveTables: () => resolveTables,
50476
- runStorageMigrations: () => runStorageMigrations,
50477
- storagePull: () => storagePull,
51291
+ storageSync: () => storageSync,
50478
51292
  storagePush: () => storagePush,
50479
- storageSync: () => storageSync
51293
+ storagePull: () => storagePull,
51294
+ runStorageMigrations: () => runStorageMigrations,
51295
+ resolveTables: () => resolveTables,
51296
+ parseStorageTables: () => parseStorageTables,
51297
+ getSyncMetaAll: () => getSyncMetaAll,
51298
+ getStorageStatus: () => getStorageStatus,
51299
+ getStoragePg: () => getStoragePg,
51300
+ getStorageDatabaseUrl: () => getStorageDatabaseUrl,
51301
+ getStorageDatabaseEnvName: () => getStorageDatabaseEnvName,
51302
+ getStorageDatabaseEnv: () => getStorageDatabaseEnv,
51303
+ getStorageBackend: () => getStorageBackend,
51304
+ STORAGE_TABLES: () => STORAGE_TABLES,
51305
+ STORAGE_DATABASE_ENV: () => STORAGE_DATABASE_ENV,
51306
+ STORAGE_BACKEND_ENV: () => STORAGE_BACKEND_ENV,
51307
+ STORAGE_BACKENDS: () => STORAGE_BACKENDS,
51308
+ RETIRED_STORAGE_MODE_ENV: () => RETIRED_STORAGE_MODE_ENV,
51309
+ HOOKS_STORAGE_TABLES: () => HOOKS_STORAGE_TABLES,
51310
+ HOOKS_STORAGE_FALLBACK_ENV: () => HOOKS_STORAGE_FALLBACK_ENV,
51311
+ HOOKS_STORAGE_ENV: () => HOOKS_STORAGE_ENV,
51312
+ HOOKS_STORAGE_BACKEND_FALLBACK_ENV: () => HOOKS_STORAGE_BACKEND_FALLBACK_ENV,
51313
+ HOOKS_STORAGE_BACKEND_ENV: () => HOOKS_STORAGE_BACKEND_ENV
50480
51314
  });
50481
51315
  function readEnv(name) {
50482
51316
  const value = process.env[name]?.trim();
@@ -50809,31 +51643,31 @@ var init_storage_sync = __esm(() => {
50809
51643
  // src/storage.ts
50810
51644
  var exports_storage = {};
50811
51645
  __export(exports_storage, {
50812
- HOOKS_STORAGE_BACKEND_ENV: () => HOOKS_STORAGE_BACKEND_ENV,
50813
- HOOKS_STORAGE_BACKEND_FALLBACK_ENV: () => HOOKS_STORAGE_BACKEND_FALLBACK_ENV,
50814
- HOOKS_STORAGE_ENV: () => HOOKS_STORAGE_ENV,
50815
- HOOKS_STORAGE_FALLBACK_ENV: () => HOOKS_STORAGE_FALLBACK_ENV,
50816
- HOOKS_STORAGE_TABLES: () => HOOKS_STORAGE_TABLES,
50817
- PG_MIGRATIONS: () => PG_MIGRATIONS,
50818
- PgAdapterAsync: () => PgAdapterAsync,
50819
- RETIRED_STORAGE_MODE_ENV: () => RETIRED_STORAGE_MODE_ENV,
50820
- STORAGE_BACKENDS: () => STORAGE_BACKENDS,
50821
- STORAGE_BACKEND_ENV: () => STORAGE_BACKEND_ENV,
50822
- STORAGE_DATABASE_ENV: () => STORAGE_DATABASE_ENV,
50823
- STORAGE_TABLES: () => STORAGE_TABLES,
50824
- getStorageBackend: () => getStorageBackend,
50825
- getStorageDatabaseEnv: () => getStorageDatabaseEnv,
50826
- getStorageDatabaseEnvName: () => getStorageDatabaseEnvName,
50827
- getStorageDatabaseUrl: () => getStorageDatabaseUrl,
50828
- getStoragePg: () => getStoragePg,
50829
- getStorageStatus: () => getStorageStatus,
50830
- getSyncMetaAll: () => getSyncMetaAll,
50831
- parseStorageTables: () => parseStorageTables,
50832
- resolveTables: () => resolveTables,
50833
- runStorageMigrations: () => runStorageMigrations,
50834
- storagePull: () => storagePull,
51646
+ storageSync: () => storageSync,
50835
51647
  storagePush: () => storagePush,
50836
- storageSync: () => storageSync
51648
+ storagePull: () => storagePull,
51649
+ runStorageMigrations: () => runStorageMigrations,
51650
+ resolveTables: () => resolveTables,
51651
+ parseStorageTables: () => parseStorageTables,
51652
+ getSyncMetaAll: () => getSyncMetaAll,
51653
+ getStorageStatus: () => getStorageStatus,
51654
+ getStoragePg: () => getStoragePg,
51655
+ getStorageDatabaseUrl: () => getStorageDatabaseUrl,
51656
+ getStorageDatabaseEnvName: () => getStorageDatabaseEnvName,
51657
+ getStorageDatabaseEnv: () => getStorageDatabaseEnv,
51658
+ getStorageBackend: () => getStorageBackend,
51659
+ STORAGE_TABLES: () => STORAGE_TABLES,
51660
+ STORAGE_DATABASE_ENV: () => STORAGE_DATABASE_ENV,
51661
+ STORAGE_BACKEND_ENV: () => STORAGE_BACKEND_ENV,
51662
+ STORAGE_BACKENDS: () => STORAGE_BACKENDS,
51663
+ RETIRED_STORAGE_MODE_ENV: () => RETIRED_STORAGE_MODE_ENV,
51664
+ PgAdapterAsync: () => PgAdapterAsync,
51665
+ PG_MIGRATIONS: () => PG_MIGRATIONS,
51666
+ HOOKS_STORAGE_TABLES: () => HOOKS_STORAGE_TABLES,
51667
+ HOOKS_STORAGE_FALLBACK_ENV: () => HOOKS_STORAGE_FALLBACK_ENV,
51668
+ HOOKS_STORAGE_ENV: () => HOOKS_STORAGE_ENV,
51669
+ HOOKS_STORAGE_BACKEND_FALLBACK_ENV: () => HOOKS_STORAGE_BACKEND_FALLBACK_ENV,
51670
+ HOOKS_STORAGE_BACKEND_ENV: () => HOOKS_STORAGE_BACKEND_ENV
50837
51671
  });
50838
51672
  var init_storage = __esm(() => {
50839
51673
  init_storage_sync();
@@ -51279,9 +52113,9 @@ var init_legacy_registry_artifact = __esm(() => {
51279
52113
  // src/lib/hosted-registry.ts
51280
52114
  var exports_hosted_registry = {};
51281
52115
  __export(exports_hosted_registry, {
51282
- HostedRegistry: () => HostedRegistry,
52116
+ REGISTRY_MIGRATIONS: () => REGISTRY_MIGRATIONS,
51283
52117
  PgRegistryStore: () => PgRegistryStore,
51284
- REGISTRY_MIGRATIONS: () => REGISTRY_MIGRATIONS
52118
+ HostedRegistry: () => HostedRegistry
51285
52119
  });
51286
52120
 
51287
52121
  class PgRegistryStore {
@@ -51420,7 +52254,7 @@ var init_hosted_registry = __esm(() => {
51420
52254
  });
51421
52255
 
51422
52256
  // ../contracts/dist/auth/index.js
51423
- import { createHash as createHash38, createHmac as createHmac2, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual2 } from "crypto";
52257
+ import { createHash as createHash39, createHmac as createHmac2, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual2 } from "crypto";
51424
52258
  function isValidTenantId(value) {
51425
52259
  return typeof value === "string" && TENANT_ID_PATTERN.test(value);
51426
52260
  }
@@ -51768,12 +52602,12 @@ class ApiKeyStore {
51768
52602
  return row.revoked_at !== null && row.revoked_at !== undefined;
51769
52603
  };
51770
52604
  async status(kid, nowMs = Date.now()) {
51771
- const record7 = await this.findByKid(kid);
51772
- if (!record7)
52605
+ const record10 = await this.findByKid(kid);
52606
+ if (!record10)
51773
52607
  return "unknown";
51774
- if (record7.revokedAt)
52608
+ if (record10.revokedAt)
51775
52609
  return "revoked";
51776
- if (record7.expiresAt && new Date(record7.expiresAt).getTime() <= nowMs)
52610
+ if (record10.expiresAt && new Date(record10.expiresAt).getTime() <= nowMs)
51777
52611
  return "expired";
51778
52612
  return "active";
51779
52613
  }
@@ -51837,8 +52671,8 @@ function readHeader(source, name) {
51837
52671
  if (typeof Headers !== "undefined" && source instanceof Headers) {
51838
52672
  return source.get(name);
51839
52673
  }
51840
- const record7 = source;
51841
- const value = record7[name] ?? record7[lower] ?? record7[name.toUpperCase()];
52674
+ const record10 = source;
52675
+ const value = record10[name] ?? record10[lower] ?? record10[name.toUpperCase()];
51842
52676
  if (Array.isArray(value))
51843
52677
  return value[0] ?? null;
51844
52678
  return value ?? null;
@@ -52119,7 +52953,7 @@ async function registryReady() {
52119
52953
  function json2(body, status = 200, headers = {}) {
52120
52954
  return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store", ...headers } });
52121
52955
  }
52122
- async function boundedJson(request) {
52956
+ async function boundedJson2(request) {
52123
52957
  if (!request.body)
52124
52958
  throw new RegistryError(400, "REGISTRY_BODY_REQUIRED");
52125
52959
  const reader = request.body.getReader(), chunks = [];
@@ -52162,7 +52996,7 @@ async function handleRegistryRequest(request, key2, registry2) {
52162
52996
  if (path === "/v1/lock" && request.method === "GET")
52163
52997
  return json2(await owner5.selection(url2.searchParams.get("profile") ?? "fleet"));
52164
52998
  if (path === "/v1/hooks" && request.method === "PUT")
52165
- return json2(await owner5.publish(await boundedJson(request)));
52999
+ return json2(await owner5.publish(await boundedJson2(request)));
52166
53000
  const artifact = /^\/v1\/hooks\/([^/]+)\/([^/]+)$/.exec(path);
52167
53001
  if (artifact && request.method === "GET") {
52168
53002
  const { body, row, format, portable } = await owner5.artifactWire(decodeURIComponent(artifact[1]), decodeURIComponent(artifact[2]));
@@ -52174,7 +53008,7 @@ async function handleRegistryRequest(request, key2, registry2) {
52174
53008
  if (request.method === "GET")
52175
53009
  return json2(await owner5.selection(profile));
52176
53010
  if (request.method === "PUT")
52177
- return json2(await owner5.select(profile, await boundedJson(request)));
53011
+ return json2(await owner5.select(profile, await boundedJson2(request)));
52178
53012
  }
52179
53013
  return json2({ error: "REGISTRY_ROUTE_NOT_FOUND" }, 404);
52180
53014
  } catch (error61) {
@@ -52198,12 +53032,12 @@ var init_registry_http = __esm(() => {
52198
53032
  // src/serve.ts
52199
53033
  var exports_serve = {};
52200
53034
  __export(exports_serve, {
52201
- DEFAULT_SERVE_PORT: () => DEFAULT_SERVE_PORT,
52202
- SERVE_HOST: () => SERVE_HOST,
52203
- SERVE_SERVICE_NAME: () => SERVE_SERVICE_NAME,
52204
- handleServeRequest: () => handleServeRequest,
53035
+ startServeServer: () => startServeServer,
52205
53036
  resolveServeOptions: () => resolveServeOptions,
52206
- startServeServer: () => startServeServer
53037
+ handleServeRequest: () => handleServeRequest,
53038
+ SERVE_SERVICE_NAME: () => SERVE_SERVICE_NAME,
53039
+ SERVE_HOST: () => SERVE_HOST,
53040
+ DEFAULT_SERVE_PORT: () => DEFAULT_SERVE_PORT
52207
53041
  });
52208
53042
  import { readFileSync as readFileSync34 } from "fs";
52209
53043
  import { dirname as dirname43, join as join50 } from "path";
@@ -52490,12 +53324,12 @@ class HooksRegistryApiClient {
52490
53324
  payload = JSON.stringify(opts.body);
52491
53325
  }
52492
53326
  const response = await this.fetchImpl(url2.toString(), { ...opts.init, method, headers, body: payload });
52493
- const text3 = await response.text();
52494
- const data = text3 ? (() => {
53327
+ const text4 = await response.text();
53328
+ const data = text4 ? (() => {
52495
53329
  try {
52496
- return JSON.parse(text3);
53330
+ return JSON.parse(text4);
52497
53331
  } catch {
52498
- return text3;
53332
+ return text4;
52499
53333
  }
52500
53334
  })() : undefined;
52501
53335
  if (!response.ok) {
@@ -52644,14 +53478,14 @@ var init_registry_client = __esm(() => {
52644
53478
  // src/sdk/index.ts
52645
53479
  var exports_sdk = {};
52646
53480
  __export(exports_sdk, {
52647
- HooksClient: () => HooksClient,
52648
- HooksRegistryApiClient: () => HooksRegistryApiClient,
52649
- HooksRegistryApiError: () => ApiError,
52650
- createHooksClient: () => createHooksClient,
52651
- createHooksRegistryApiClient: () => createHooksRegistryApiClient,
52652
- hooksRegistryApiClientFor: () => hooksRegistryApiClientFor,
53481
+ resolveHooksSdkAuthority: () => resolveHooksSdkAuthority,
52653
53482
  hooksRegistryOrigin: () => hooksRegistryOrigin,
52654
- resolveHooksSdkAuthority: () => resolveHooksSdkAuthority
53483
+ hooksRegistryApiClientFor: () => hooksRegistryApiClientFor,
53484
+ createHooksRegistryApiClient: () => createHooksRegistryApiClient,
53485
+ createHooksClient: () => createHooksClient,
53486
+ HooksRegistryApiError: () => ApiError,
53487
+ HooksRegistryApiClient: () => HooksRegistryApiClient,
53488
+ HooksClient: () => HooksClient
52655
53489
  });
52656
53490
 
52657
53491
  class HooksClient {
@@ -52822,8 +53656,8 @@ var CF_API = "https://api.cloudflare.com/client/v4";
52822
53656
  // src/lib/legacy-registry-import.ts
52823
53657
  var exports_legacy_registry_import = {};
52824
53658
  __export(exports_legacy_registry_import, {
52825
- importLegacyRegistryExport: () => importLegacyRegistryExport,
52826
- readLegacyRegistryExport: () => readLegacyRegistryExport
53659
+ readLegacyRegistryExport: () => readLegacyRegistryExport,
53660
+ importLegacyRegistryExport: () => importLegacyRegistryExport
52827
53661
  });
52828
53662
  import { constants as constants29, closeSync as closeSync29, fstatSync as fstatSync29, lstatSync as lstatSync41, openSync as openSync29, readSync as readSync6, realpathSync as realpathSync27 } from "fs";
52829
53663
  import { dirname as dirname46, isAbsolute as isAbsolute41, join as join51, resolve as resolve43 } from "path";
@@ -52861,10 +53695,10 @@ function fileBytes(root, relative12, expected) {
52861
53695
  }
52862
53696
  if (count2 !== stat2.size)
52863
53697
  refuse6();
52864
- const exact = bytes.subarray(0, count2);
52865
- if (expected && scriptDigest(decode3(exact)) !== expected.sha256)
53698
+ const exact2 = bytes.subarray(0, count2);
53699
+ if (expected && scriptDigest(decode3(exact2)) !== expected.sha256)
52866
53700
  refuse6();
52867
- return exact;
53701
+ return exact2;
52868
53702
  } finally {
52869
53703
  closeSync29(fd);
52870
53704
  }
@@ -53039,8 +53873,8 @@ var init_registry_prerequisites = __esm(() => {
53039
53873
  // src/mcp/authority.ts
53040
53874
  var exports_authority = {};
53041
53875
  __export(exports_authority, {
53042
- decideHooksMcpAuthority: () => decideHooksMcpAuthority,
53043
- resolveHooksMcpAuthority: () => resolveHooksMcpAuthority
53876
+ resolveHooksMcpAuthority: () => resolveHooksMcpAuthority,
53877
+ decideHooksMcpAuthority: () => decideHooksMcpAuthority
53044
53878
  });
53045
53879
  function resolveHooksMcpAuthority(env = process.env) {
53046
53880
  const transport = resolveHooksTransport(env);
@@ -53065,12 +53899,12 @@ var init_authority2 = __esm(() => {
53065
53899
  // src/mcp/server.ts
53066
53900
  var exports_server = {};
53067
53901
  __export(exports_server, {
53068
- MCP_PORT: () => MCP_PORT,
53069
- MCP_SSE_HOST: () => MCP_SSE_HOST,
53070
- createHooksServer: () => createHooksServer,
53071
- sseAuthToken: () => sseAuthToken,
53902
+ startStdioServer: () => startStdioServer,
53072
53903
  startSSEServer: () => startSSEServer,
53073
- startStdioServer: () => startStdioServer
53904
+ sseAuthToken: () => sseAuthToken,
53905
+ createHooksServer: () => createHooksServer,
53906
+ MCP_SSE_HOST: () => MCP_SSE_HOST,
53907
+ MCP_PORT: () => MCP_PORT
53074
53908
  });
53075
53909
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
53076
53910
  import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
@@ -53078,7 +53912,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
53078
53912
  import { z as z3 } from "zod";
53079
53913
  import { createServer } from "http";
53080
53914
  import { existsSync as existsSync23, readFileSync as readFileSync36 } from "fs";
53081
- import { join as join52, dirname as dirname47 } from "path";
53915
+ import { join as join53, dirname as dirname47 } from "path";
53082
53916
  import { fileURLToPath as fileURLToPath7 } from "url";
53083
53917
  async function runVerifiedHook(name, stdin, timeoutMs) {
53084
53918
  const { resolveHook: resolveHook2, resolveScriptPath: resolveScriptPath2 } = await Promise.resolve().then(() => (init_resolve(), exports_resolve));
@@ -53169,10 +54003,10 @@ function settingsChangeError(hook, scope, error61, code2) {
53169
54003
  };
53170
54004
  }
53171
54005
  function truncateText(value, max = 160) {
53172
- const text3 = String(value ?? "").replace(/\s+/g, " ").trim();
53173
- if (text3.length <= max)
53174
- return text3;
53175
- return `${text3.slice(0, Math.max(0, max - 3))}...`;
54006
+ const text4 = String(value ?? "").replace(/\s+/g, " ").trim();
54007
+ if (text4.length <= max)
54008
+ return text4;
54009
+ return `${text4.slice(0, Math.max(0, max - 3))}...`;
53176
54010
  }
53177
54011
  function boundedLimit(value, fallback, max) {
53178
54012
  if (!Number.isFinite(value) || !value || value <= 0)
@@ -53318,7 +54152,7 @@ function createHooksServer() {
53318
54152
  continue;
53319
54153
  }
53320
54154
  const hookDir = getHookPath(name);
53321
- if (!existsSync23(join52(hookDir, "src", "hook.ts"))) {
54155
+ if (!existsSync23(join53(hookDir, "src", "hook.ts"))) {
53322
54156
  issues.push({ hook: name, issue: "Missing src/hook.ts in package", severity: "error" });
53323
54157
  hookHealthy = false;
53324
54158
  }
@@ -53362,7 +54196,7 @@ function createHooksServer() {
53362
54196
  return { content: [{ type: "text", text: JSON.stringify({ error: `Hook '${name}' not found` }) }] };
53363
54197
  }
53364
54198
  const hookPath = getHookPath(name);
53365
- const readmePath = join52(hookPath, "README.md");
54199
+ const readmePath = join53(hookPath, "README.md");
53366
54200
  let readme = "";
53367
54201
  if (existsSync23(readmePath)) {
53368
54202
  readme = readFileSync36(readmePath, "utf-8");
@@ -54076,7 +54910,7 @@ var init_server = __esm(() => {
54076
54910
  pkg = { name: "@hasna/hooks", version: "0.0.0" };
54077
54911
  try {
54078
54912
  for (const rel of ["../../package.json", "../package.json", "../../../package.json"]) {
54079
- const p = join52(__dirname3, rel);
54913
+ const p = join53(__dirname3, rel);
54080
54914
  if (existsSync23(p)) {
54081
54915
  pkg = JSON.parse(readFileSync36(p, "utf-8"));
54082
54916
  break;
@@ -54090,14 +54924,14 @@ var init_server = __esm(() => {
54090
54924
  // src/mcp/http.ts
54091
54925
  var exports_http = {};
54092
54926
  __export(exports_http, {
54093
- DEFAULT_MCP_HTTP_PORT: () => DEFAULT_MCP_HTTP_PORT,
54094
- MCP_HTTP_HOST: () => MCP_HTTP_HOST,
54095
- MCP_SERVICE_NAME: () => MCP_SERVICE_NAME,
54096
- handleMcpRequest: () => handleMcpRequest,
54097
- healthPayload: () => healthPayload,
54098
- isHttpMode: () => isHttpMode,
54927
+ startMcpHttpServer: () => startMcpHttpServer,
54099
54928
  resolveMcpHttpPort: () => resolveMcpHttpPort,
54100
- startMcpHttpServer: () => startMcpHttpServer
54929
+ isHttpMode: () => isHttpMode,
54930
+ healthPayload: () => healthPayload,
54931
+ handleMcpRequest: () => handleMcpRequest,
54932
+ MCP_SERVICE_NAME: () => MCP_SERVICE_NAME,
54933
+ MCP_HTTP_HOST: () => MCP_HTTP_HOST,
54934
+ DEFAULT_MCP_HTTP_PORT: () => DEFAULT_MCP_HTTP_PORT
54101
54935
  });
54102
54936
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
54103
54937
  function isHttpMode(args) {
@@ -54149,13 +54983,13 @@ var init_http = () => {};
54149
54983
  // src/lib/native-readiness-binding.ts
54150
54984
  var exports_native_readiness_binding = {};
54151
54985
  __export(exports_native_readiness_binding, {
54152
- ReadinessBindingError: () => ReadinessBindingError,
54153
- registerTrashReadinessBinding: () => registerTrashReadinessBinding
54986
+ registerTrashReadinessBinding: () => registerTrashReadinessBinding,
54987
+ ReadinessBindingError: () => ReadinessBindingError
54154
54988
  });
54155
- import { createHash as createHash39, randomUUID as randomUUID14 } from "crypto";
54989
+ import { createHash as createHash40, randomUUID as randomUUID14 } from "crypto";
54156
54990
  import { closeSync as closeSync30, constants as constants30, fsyncSync as fsyncSync12, lstatSync as lstatSync43, mkdirSync as mkdirSync20, openSync as openSync30, realpathSync as realpathSync28, writeFileSync as writeFileSync18 } from "fs";
54157
54991
  import { homedir as homedir20 } from "os";
54158
- import { dirname as dirname48, join as join53 } from "path";
54992
+ import { dirname as dirname48, join as join55 } from "path";
54159
54993
  function need16(value, code2) {
54160
54994
  if (!value)
54161
54995
  throw new ReadinessBindingError(code2);
@@ -54213,7 +55047,7 @@ async function registerTrashReadinessBinding(input2, expectedSHA256) {
54213
55047
  const operationId = randomUUID14();
54214
55048
  let directory3 = home;
54215
55049
  for (const part of [".hasna", "hooks", "native", "trash-readiness"]) {
54216
- directory3 = join53(directory3, part);
55050
+ directory3 = join55(directory3, part);
54217
55051
  try {
54218
55052
  mkdirSync20(directory3, { mode: 448 });
54219
55053
  syncDirectory6(dirname48(directory3));
@@ -54223,12 +55057,12 @@ async function registerTrashReadinessBinding(input2, expectedSHA256) {
54223
55057
  }
54224
55058
  safeDirectory4(directory3);
54225
55059
  }
54226
- const operation = join53(directory3, operationId);
55060
+ const operation = join55(directory3, operationId);
54227
55061
  mkdirSync20(operation, { mode: 448 });
54228
55062
  syncDirectory6(directory3);
54229
55063
  if (before)
54230
- exclusive3(join53(operation, "binding.before"), before.raw);
54231
- exclusive3(join53(operation, "intent.json"), JSON.stringify({ operationId, target, expectedSHA256, desiredSHA256: digest5 }) + `
55064
+ exclusive3(join55(operation, "binding.before"), before.raw);
55065
+ exclusive3(join55(operation, "intent.json"), JSON.stringify({ operationId, target, expectedSHA256, desiredSHA256: digest5 }) + `
54232
55066
  `);
54233
55067
  let writeMayHaveStarted = false;
54234
55068
  try {
@@ -54246,7 +55080,7 @@ async function registerTrashReadinessBinding(input2, expectedSHA256) {
54246
55080
  syncDirectory6(directory3);
54247
55081
  need16(read4()?.sha256 === digest5, "binding_changed");
54248
55082
  const receipt = { ok: true, changed: true, operationId, path: target, sha256: digest5, configurationReady: true, nativeAdoptionVerified: false };
54249
- exclusive3(join53(operation, "receipt.json"), JSON.stringify(receipt) + `
55083
+ exclusive3(join55(operation, "receipt.json"), JSON.stringify(receipt) + `
54250
55084
  `);
54251
55085
  return receipt;
54252
55086
  } catch (error61) {
@@ -54255,7 +55089,7 @@ async function registerTrashReadinessBinding(input2, expectedSHA256) {
54255
55089
  const code2 = error61?.code;
54256
55090
  const refusal3 = { code: typeof code2 === "string" && code2 ? code2 : "writer_refused", message: error61 instanceof Error ? error61.message : String(error61) };
54257
55091
  try {
54258
- exclusive3(join53(operation, "refused.json"), JSON.stringify({ ok: false, outcome: "refused", operationId, path: target, expectedSHA256, refusal: refusal3 }) + `
55092
+ exclusive3(join55(operation, "refused.json"), JSON.stringify({ ok: false, outcome: "refused", operationId, path: target, expectedSHA256, refusal: refusal3 }) + `
54259
55093
  `);
54260
55094
  } catch {
54261
55095
  throw new ReadinessBindingError("binding_outcome_uncertain", operationId);
@@ -54263,7 +55097,7 @@ async function registerTrashReadinessBinding(input2, expectedSHA256) {
54263
55097
  throw new ReadinessBindingError("binding_refused", operationId, refusal3);
54264
55098
  }
54265
55099
  }
54266
- var ReadinessBindingError, sha11 = (bytes) => createHash39("sha256").update(bytes).digest("hex");
55100
+ var ReadinessBindingError, sha11 = (bytes) => createHash40("sha256").update(bytes).digest("hex");
54267
55101
  var init_native_readiness_binding = __esm(() => {
54268
55102
  init_native_readiness();
54269
55103
  init_codex_settings();
@@ -54289,7 +55123,7 @@ init_native_safety();
54289
55123
  init_native_safety2();
54290
55124
  init_registry();
54291
55125
  import { constants as constants16, closeSync as closeSync10, fstatSync as fstatSync10, lstatSync as lstatSync26, openSync as openSync10, readFileSync as readFileSync21, realpathSync as realpathSync16 } from "fs";
54292
- import { createHash as createHash25 } from "crypto";
55126
+ import { createHash as createHash20 } from "crypto";
54293
55127
  import { dirname as dirname29, isAbsolute as isAbsolute17, join as join35, resolve as resolve33 } from "path";
54294
55128
  import { homedir as homedir12 } from "os";
54295
55129
 
@@ -54305,7 +55139,7 @@ function need13(value, code2) {
54305
55139
  if (!value)
54306
55140
  throw new ClaudeSafetyError(code2);
54307
55141
  }
54308
- var sha9 = (value) => createHash25("sha256").update(value).digest("hex");
55142
+ var sha9 = (value) => createHash20("sha256").update(value).digest("hex");
54309
55143
  function read5(path) {
54310
55144
  try {
54311
55145
  const resolved = realpathSync16(path);
@@ -54601,9 +55435,9 @@ function exactEventsHome() {
54601
55435
  return;
54602
55436
  }
54603
55437
  function getEventsHome() {
54604
- const exact = exactEventsHome();
54605
- if (exact)
54606
- return resolve36(exact);
55438
+ const exact2 = exactEventsHome();
55439
+ if (exact2)
55440
+ return resolve36(exact2);
54607
55441
  const resolved = resolverHome();
54608
55442
  return adoptResolverHome(resolved) ? resolve36(resolved) : resolve36(legacyHomeDir());
54609
55443
  }
@@ -55076,11 +55910,11 @@ function ipv6Groups(address) {
55076
55910
  const doubleColon = raw.indexOf("::");
55077
55911
  const headText = doubleColon === -1 ? raw : raw.slice(0, doubleColon);
55078
55912
  const tailText = doubleColon === -1 ? "" : raw.slice(doubleColon + 2);
55079
- const parseGroups = (text2) => {
55080
- if (text2 === "")
55913
+ const parseGroups = (text3) => {
55914
+ if (text3 === "")
55081
55915
  return [];
55082
55916
  const out = [];
55083
- for (const part of text2.split(":")) {
55917
+ for (const part of text3.split(":")) {
55084
55918
  if (part.includes(".")) {
55085
55919
  const v4 = ipv4ToInt(part);
55086
55920
  if (v4 === undefined)
@@ -55868,11 +56702,11 @@ function createClient(options) {
55868
56702
  return options.createClient();
55869
56703
  return new EventsClient({ store: new JsonEventsStore(options.dataDir), webhookTargetPolicy: webhookTargetPolicyFromEnv() });
55870
56704
  }
55871
- function print(value, json2, text2) {
56705
+ function print(value, json2, text3) {
55872
56706
  if (json2)
55873
56707
  console.log(JSON.stringify(value, null, 2));
55874
56708
  else
55875
- console.log(text2);
56709
+ console.log(text3);
55876
56710
  }
55877
56711
  function fail2(error61, json2) {
55878
56712
  const message = error61 instanceof Error ? error61.message : String(error61);
@@ -56060,7 +56894,7 @@ var {
56060
56894
  // src/cli/index.tsx
56061
56895
  import chalk2 from "chalk";
56062
56896
  import { existsSync as existsSync25, readFileSync as readFileSync37, rmSync as rmSync7 } from "fs";
56063
- import { join as join54, dirname as dirname49 } from "path";
56897
+ import { join as join56, dirname as dirname49 } from "path";
56064
56898
  import { fileURLToPath as fileURLToPath8 } from "url";
56065
56899
  import { homedir as homedir21 } from "os";
56066
56900
 
@@ -57254,10 +58088,45 @@ init_app_home();
57254
58088
  init_config();
57255
58089
  init_local_opt_in();
57256
58090
  init_transport2();
58091
+
58092
+ // src/lib/gate-route.ts
58093
+ init_transport2();
58094
+ var KEYCHAIN_INTERACTION_NOT_ALLOWED_STATUS = 36;
58095
+ var HOOKS_RUN_UNREADABLE_KEYCHAIN_AUTHORITY = "configured by the Keychain item hasna.credentials.hooks.api-key, which this session may not read " + "(security exit 36); hooks run executes the hook pinned in hooks.lock and uses no registry credential";
58096
+ var UNREADABLE_HOOKS_KEYCHAIN_ITEM = /^The Keychain lookup for keychain:hasna\.credentials\.hooks\.api-(?:key|url)@\S+ failed \(security exited 36(?:[:)])/;
58097
+ function isHooksKeychainInteractionRefusal(error61) {
58098
+ let current2 = error61;
58099
+ for (let depth = 0;depth < 4 && current2 instanceof Error; depth++) {
58100
+ if (current2.name === "CredentialResolutionError") {
58101
+ const status = current2.keychainStatus;
58102
+ if (status !== undefined)
58103
+ return status === KEYCHAIN_INTERACTION_NOT_ALLOWED_STATUS;
58104
+ return UNREADABLE_HOOKS_KEYCHAIN_ITEM.test(current2.message);
58105
+ }
58106
+ current2 = current2.cause;
58107
+ }
58108
+ return false;
58109
+ }
58110
+ function hooksAmbientGateRoute(command, env = process.env, options = {}) {
58111
+ let transport;
58112
+ try {
58113
+ transport = resolveHooksTransport(env, options);
58114
+ } catch (error61) {
58115
+ if (command === "run" && isHooksKeychainInteractionRefusal(error61)) {
58116
+ return { kind: "hosted", authority: HOOKS_RUN_UNREADABLE_KEYCHAIN_AUTHORITY };
58117
+ }
58118
+ return { kind: "fail", detail: error61 instanceof Error ? error61.message : String(error61) };
58119
+ }
58120
+ if (transport.mode !== "remote" || !transport.authority)
58121
+ return { kind: "fail" };
58122
+ return { kind: "hosted", authority: transport.authority.v1BaseUrl };
58123
+ }
58124
+
58125
+ // src/cli/index.tsx
57257
58126
  init_db();
57258
58127
  import { jsxDEV as jsxDEV8 } from "react/jsx-dev-runtime";
57259
58128
  var __dirname4 = dirname49(fileURLToPath8(import.meta.url));
57260
- var pkgPath = existsSync25(join54(__dirname4, "..", "package.json")) ? join54(__dirname4, "..", "package.json") : join54(__dirname4, "..", "..", "package.json");
58129
+ var pkgPath = existsSync25(join56(__dirname4, "..", "package.json")) ? join56(__dirname4, "..", "package.json") : join56(__dirname4, "..", "..", "package.json");
57261
58130
  var pkg2 = JSON.parse(readFileSync37(pkgPath, "utf-8"));
57262
58131
  var program3 = new Command;
57263
58132
  function resolveScope(options) {
@@ -57319,10 +58188,10 @@ function parseLimit(value, fallback, max) {
57319
58188
  return Math.min(parsed, max);
57320
58189
  }
57321
58190
  function truncateText2(value, max = 96) {
57322
- const text3 = (value ?? "").replace(/\s+/g, " ").trim();
57323
- if (text3.length <= max)
57324
- return text3;
57325
- return `${text3.slice(0, Math.max(0, max - 3))}...`;
58191
+ const text4 = (value ?? "").replace(/\s+/g, " ").trim();
58192
+ if (text4.length <= max)
58193
+ return text4;
58194
+ return `${text4.slice(0, Math.max(0, max - 3))}...`;
57326
58195
  }
57327
58196
  function projectLogRows2(rows) {
57328
58197
  return rows.map((row) => projectEventRowForRead({ ...row }));
@@ -57481,7 +58350,7 @@ program3.command("init").description("Register a new agent profile with a unique
57481
58350
  if (profile.name) {
57482
58351
  console.log(` ${chalk2.dim("Name:")} ${profile.name}`);
57483
58352
  }
57484
- console.log(` ${chalk2.dim("Profile:")} ${join54(getProfilesDir(), `${profile.agent_id}.json`)}`);
58353
+ console.log(` ${chalk2.dim("Profile:")} ${join56(getProfilesDir(), `${profile.agent_id}.json`)}`);
57485
58354
  console.log();
57486
58355
  console.log(chalk2.dim(" Install hooks with this profile:"));
57487
58356
  console.log(` hooks install gitguard --profile ${profile.agent_id}`);
@@ -57751,7 +58620,7 @@ program3.command("install").alias("add").argument("[hooks...]", "Hooks to instal
57751
58620
  }
57752
58621
  const { isCustomSource: isCustomSource2, installCustomSource: installCustomSource2 } = await Promise.resolve().then(() => (init_custom_install(), exports_custom_install));
57753
58622
  const { readCustomManifest: readCustomManifest2, HOOK_NAME_RE: HOOK_NAME_RE2 } = await Promise.resolve().then(() => (init_manifest(), exports_manifest));
57754
- const { resolveHooksTransport: resolveHooksTransport3 } = await Promise.resolve().then(() => (init_transport2(), exports_transport));
58623
+ const { resolveHooksTransport: resolveHooksTransport4 } = await Promise.resolve().then(() => (init_transport2(), exports_transport));
57755
58624
  const { sha256Of: sha256Of2, pinInstalledHook: pinInstalledHook2 } = await Promise.resolve().then(() => (init_store(), exports_store));
57756
58625
  const { installPinnedFromBundled: installPinnedFromBundled2, fetchPinnedHook: fetchPinnedHook2 } = await Promise.resolve().then(() => (init_sync(), exports_sync));
57757
58626
  const { readFileSync: readFileSyncFs } = await import("fs");
@@ -57846,7 +58715,7 @@ Dry run \u2014 would install (${scope}, ${target}):
57846
58715
  const installedPinned = [];
57847
58716
  for (const { arg, pinned } of pinnedRequests) {
57848
58717
  try {
57849
- const transport = resolveHooksTransport3();
58718
+ const transport = resolveHooksTransport4();
57850
58719
  const pinnedInstall = transport.mode === "remote" && transport.authority ? await fetchPinnedHook2(pinned.name, pinned.version, transport.authority.origin, transport.authority) : await installPinnedFromBundled2(pinned.name, pinned.version);
57851
58720
  installedPinned.push(pinnedInstall.name);
57852
58721
  if (options.json) {
@@ -58266,7 +59135,7 @@ program3.command("doctor").option("-g, --global", "Check global settings", false
58266
59135
  continue;
58267
59136
  }
58268
59137
  const hookDir = getHookPath(name);
58269
- const hookScript = join54(hookDir, "src", "hook.ts");
59138
+ const hookScript = join56(hookDir, "src", "hook.ts");
58270
59139
  if (!existsSync25(hookScript)) {
58271
59140
  issues.push({ hook: name, issue: "Missing src/hook.ts in package", severity: "error" });
58272
59141
  hookHealthy = false;
@@ -58380,7 +59249,7 @@ program3.command("update").argument("[hooks...]", "Hooks to update (defaults to
58380
59249
  const { resolveHook: resolveHook2 } = await Promise.resolve().then(() => (init_resolve(), exports_resolve));
58381
59250
  const { sha256File: sha256File2, setPinnedHook: setPinnedHook2, upsertHookRecord: upsertHookRecord2 } = await Promise.resolve().then(() => (init_store(), exports_store));
58382
59251
  const { getDb: getDb2, isLocalStoreRefused: isLocalStoreRefused2 } = await Promise.resolve().then(() => (init_db(), exports_db));
58383
- const { resolveHooksTransport: resolveHooksTransport3 } = await Promise.resolve().then(() => (init_transport2(), exports_transport));
59252
+ const { resolveHooksTransport: resolveHooksTransport4 } = await Promise.resolve().then(() => (init_transport2(), exports_transport));
58384
59253
  const { installPinnedFromBundled: installPinnedFromBundled2, fetchPinnedHook: fetchPinnedHook2 } = await Promise.resolve().then(() => (init_sync(), exports_sync));
58385
59254
  const { isCustomSource: isCustomSource2 } = await Promise.resolve().then(() => (init_custom_install(), exports_custom_install));
58386
59255
  const { HOOK_NAME_RE: HOOK_NAME_RE2 } = await Promise.resolve().then(() => (init_manifest(), exports_manifest));
@@ -58403,7 +59272,7 @@ program3.command("update").argument("[hooks...]", "Hooks to update (defaults to
58403
59272
  const pinned = parseNameVersion(arg);
58404
59273
  if (pinned) {
58405
59274
  try {
58406
- const transport = resolveHooksTransport3();
59275
+ const transport = resolveHooksTransport4();
58407
59276
  const pinnedInstall = transport.mode === "remote" && transport.authority ? await fetchPinnedHook2(pinned.name, pinned.version, transport.authority.origin, transport.authority) : await installPinnedFromBundled2(pinned.name, pinned.version);
58408
59277
  const registered = installHook(pinnedInstall.name, { scope, overwrite: true });
58409
59278
  if (!registered.success) {
@@ -58427,18 +59296,18 @@ program3.command("update").argument("[hooks...]", "Hooks to update (defaults to
58427
59296
  const result = installHook(arg, { scope, overwrite: true });
58428
59297
  const resolved = resolveHook2(arg);
58429
59298
  if (result.success && resolved) {
58430
- const hash5 = await sha256File2(resolved.scriptPath);
58431
- setPinnedHook2(resolved.name, { version: resolved.version, sha256: hash5, source: resolved.source });
59299
+ const hash6 = await sha256File2(resolved.scriptPath);
59300
+ setPinnedHook2(resolved.name, { version: resolved.version, sha256: hash6, source: resolved.source });
58432
59301
  if (!isLocalStoreRefused2()) {
58433
59302
  upsertHookRecord2(getDb2(), {
58434
59303
  name: resolved.name,
58435
59304
  version: resolved.version,
58436
- sha256: hash5,
59305
+ sha256: hash6,
58437
59306
  source_type: resolved.source,
58438
59307
  last_verified_at: new Date().toISOString()
58439
59308
  });
58440
59309
  }
58441
- results2.push({ ...result, pinned: { version: resolved.version, sha256: hash5 } });
59310
+ results2.push({ ...result, pinned: { version: resolved.version, sha256: hash6 } });
58442
59311
  continue;
58443
59312
  }
58444
59313
  results2.push(result);
@@ -58480,7 +59349,7 @@ program3.command("docs").argument("[hook]", "Hook name (shows general docs if om
58480
59349
  return;
58481
59350
  }
58482
59351
  const hookPath = getHookPath(hook);
58483
- const readmePath = join54(hookPath, "README.md");
59352
+ const readmePath = join56(hookPath, "README.md");
58484
59353
  let readme = "";
58485
59354
  if (existsSync25(readmePath)) {
58486
59355
  readme = readFileSync37(readmePath, "utf-8");
@@ -58753,10 +59622,10 @@ logCmd.command("list").description("List hook events").option("--hook <name>", "
58753
59622
  console.log(chalk2.dim(`
58754
59623
  Compact rows shown. Use --json for full event records or --limit <n> to change row count.`));
58755
59624
  });
58756
- logCmd.command("search <text>").description("Search hook events by tool_input or error text").option("-n, --limit <n>", "Number of rows to show", "50").option("-j, --json", "Output as JSON", false).action(async (text3, options) => {
59625
+ logCmd.command("search <text>").description("Search hook events by tool_input or error text").option("-n, --limit <n>", "Number of rows to show", "50").option("-j, --json", "Output as JSON", false).action(async (text4, options) => {
58757
59626
  const db = await openLocalStoreOrExit(options.json);
58758
59627
  const limit = parseInt(options.limit) || 50;
58759
- const q = `%${text3}%`;
59628
+ const q = `%${text4}%`;
58760
59629
  const rows = db.query("SELECT * FROM hook_events WHERE tool_input LIKE ? OR error LIKE ? ORDER BY timestamp DESC LIMIT ?").all(q, q, limit);
58761
59630
  const projected2 = projectLogRows2(rows);
58762
59631
  if (options.json) {
@@ -58764,11 +59633,11 @@ logCmd.command("search <text>").description("Search hook events by tool_input or
58764
59633
  return;
58765
59634
  }
58766
59635
  if (projected2.length === 0) {
58767
- console.log(chalk2.dim(`No events matching "${text3}".`));
59636
+ console.log(chalk2.dim(`No events matching "${text4}".`));
58768
59637
  return;
58769
59638
  }
58770
59639
  console.log(chalk2.bold(`
58771
- Search results for "${text3}" (${projected2.length})
59640
+ Search results for "${text4}" (${projected2.length})
58772
59641
  `));
58773
59642
  for (const row of projected2) {
58774
59643
  const ts = row.timestamp.slice(0, 19).replace("T", " ");
@@ -59481,17 +60350,10 @@ function enforceTransportGate() {
59481
60350
  announceHooksLocalMode();
59482
60351
  return;
59483
60352
  }
59484
- let transport;
59485
- try {
59486
- transport = resolveHooksTransport(process.env);
59487
- } catch (error61) {
59488
- const message = error61 instanceof Error ? error61.message : String(error61);
59489
- failClosedForMissingApiEnv(message);
59490
- }
59491
- if (transport.mode !== "remote" || !transport.authority) {
59492
- failClosedForMissingApiEnv();
59493
- }
59494
- refuseLocalStore(hooksHostedRouteLocalStoreRefusal(transport.authority.v1BaseUrl));
60353
+ const route = hooksAmbientGateRoute(token, process.env);
60354
+ if (route.kind === "fail")
60355
+ failClosedForMissingApiEnv(route.detail);
60356
+ refuseLocalStore(hooksHostedRouteLocalStoreRefusal(route.authority));
59495
60357
  }
59496
60358
  enforceTransportGate();
59497
60359
  program3.parse();