@hasna/hooks 0.13.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/hooks-mcp.js CHANGED
@@ -912,11 +912,11 @@ var init_manifest = __esm(() => {
912
912
  // src/lib/resolve.ts
913
913
  var exports_resolve = {};
914
914
  __export(exports_resolve, {
915
- resolveBundledHooksDir: () => resolveBundledHooksDir,
916
- resolveHook: () => resolveHook,
917
- resolveHookDir: () => resolveHookDir,
915
+ resolveScriptPath: () => resolveScriptPath,
918
916
  resolveHookMeta: () => resolveHookMeta,
919
- resolveScriptPath: () => resolveScriptPath
917
+ resolveHookDir: () => resolveHookDir,
918
+ resolveHook: () => resolveHook,
919
+ resolveBundledHooksDir: () => resolveBundledHooksDir
920
920
  });
921
921
  import { dirname as dirname2, join as join4 } from "path";
922
922
  import { existsSync as existsSync3 } from "fs";
@@ -1050,7 +1050,7 @@ function up(db) {
1050
1050
  db.exec(idx);
1051
1051
  }
1052
1052
  }
1053
- var init__001_initial = __esm(() => {
1053
+ var init_001_initial = __esm(() => {
1054
1054
  init_schema();
1055
1055
  });
1056
1056
 
@@ -1079,7 +1079,7 @@ function up2(db) {
1079
1079
  throw err;
1080
1080
  }
1081
1081
  }
1082
- var init__002_session_events = __esm(() => {
1082
+ var init_002_session_events = __esm(() => {
1083
1083
  init_schema();
1084
1084
  });
1085
1085
 
@@ -1108,7 +1108,7 @@ function up3(db) {
1108
1108
  throw err;
1109
1109
  }
1110
1110
  }
1111
- var init__003_user_prompt_submit_event = __esm(() => {
1111
+ var init_003_user_prompt_submit_event = __esm(() => {
1112
1112
  init_schema();
1113
1113
  });
1114
1114
 
@@ -1132,7 +1132,7 @@ var CREATE_HOOKS_TABLE = `
1132
1132
  last_verified_at TEXT
1133
1133
  )
1134
1134
  `, CREATE_HOOKS_INDEXES;
1135
- var init__004_hooks_table = __esm(() => {
1135
+ var init_004_hooks_table = __esm(() => {
1136
1136
  CREATE_HOOKS_INDEXES = [
1137
1137
  `CREATE INDEX IF NOT EXISTS idx_hooks_name ON hooks (name)`
1138
1138
  ];
@@ -1163,7 +1163,7 @@ function up5(db) {
1163
1163
  throw err;
1164
1164
  }
1165
1165
  }
1166
- var init__005_subagent_start_event = __esm(() => {
1166
+ var init_005_subagent_start_event = __esm(() => {
1167
1167
  init_schema();
1168
1168
  });
1169
1169
 
@@ -1195,11 +1195,11 @@ function runMigrations(db) {
1195
1195
  }
1196
1196
  var MIGRATIONS;
1197
1197
  var init_migrations = __esm(() => {
1198
- init__001_initial();
1199
- init__002_session_events();
1200
- init__003_user_prompt_submit_event();
1201
- init__004_hooks_table();
1202
- init__005_subagent_start_event();
1198
+ init_001_initial();
1199
+ init_002_session_events();
1200
+ init_003_user_prompt_submit_event();
1201
+ init_004_hooks_table();
1202
+ init_005_subagent_start_event();
1203
1203
  MIGRATIONS = [
1204
1204
  { version: "001_initial", up },
1205
1205
  { version: "002_session_events", up: up2 },
@@ -1341,14 +1341,14 @@ function runRetention(db, days) {
1341
1341
  // src/db/index.ts
1342
1342
  var exports_db = {};
1343
1343
  __export(exports_db, {
1344
- allowLocalStore: () => allowLocalStore,
1345
- closeDb: () => closeDb,
1346
- createTestDb: () => createTestDb,
1347
- getDb: () => getDb,
1348
- getDbPath: () => getDbPath,
1349
- isLocalStoreRefused: () => isLocalStoreRefused,
1344
+ refuseLocalStore: () => refuseLocalStore,
1350
1345
  localStoreRefusalMessage: () => localStoreRefusalMessage,
1351
- refuseLocalStore: () => refuseLocalStore
1346
+ isLocalStoreRefused: () => isLocalStoreRefused,
1347
+ getDbPath: () => getDbPath,
1348
+ getDb: () => getDb,
1349
+ createTestDb: () => createTestDb,
1350
+ closeDb: () => closeDb,
1351
+ allowLocalStore: () => allowLocalStore
1352
1352
  });
1353
1353
  import { Database } from "bun:sqlite";
1354
1354
  import { existsSync as existsSync7, mkdirSync as mkdirSync2, cpSync } from "fs";
@@ -1456,14 +1456,14 @@ function redactValue(value) {
1456
1456
  }
1457
1457
  return value;
1458
1458
  }
1459
- function redactEventPayload(text2) {
1460
- if (text2 === null || text2 === undefined)
1459
+ function redactEventPayload(text3) {
1460
+ if (text3 === null || text3 === undefined)
1461
1461
  return null;
1462
1462
  try {
1463
- const parsed = JSON.parse(text2);
1463
+ const parsed = JSON.parse(text3);
1464
1464
  return redactText(JSON.stringify(redactValue(parsed)));
1465
1465
  } catch {
1466
- return redactText(text2);
1466
+ return redactText(text3);
1467
1467
  }
1468
1468
  }
1469
1469
  function projectEventRowForRead(row) {
@@ -1560,10 +1560,10 @@ function credentialDiskSources(name, env) {
1560
1560
  function profileDiskSources(name, env, profile) {
1561
1561
  return credentialDiskSourceList(name, env, profile).map((s) => s.path);
1562
1562
  }
1563
- function parseEnvFile(text2) {
1563
+ function parseEnvFile(text3) {
1564
1564
  const values = new Map;
1565
1565
  const unusable = new Set;
1566
- for (const rawLine of text2.split(/\r?\n/)) {
1566
+ for (const rawLine of text3.split(/\r?\n/)) {
1567
1567
  const line = rawLine.trim();
1568
1568
  if (line.length === 0 || line.startsWith("#"))
1569
1569
  continue;
@@ -1776,8 +1776,8 @@ function keychainAccount(env, options) {
1776
1776
  const user = env.USER?.trim();
1777
1777
  return user || null;
1778
1778
  }
1779
- function keychainFailureHint(text2) {
1780
- const line = text2.split(/\r?\n/).find((entry) => entry.trim().length > 0)?.trim() ?? "";
1779
+ function keychainFailureHint(text3) {
1780
+ const line = text3.split(/\r?\n/).find((entry) => entry.trim().length > 0)?.trim() ?? "";
1781
1781
  const clean = line.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 200);
1782
1782
  return clean ? `: ${clean}` : "";
1783
1783
  }
@@ -2601,9 +2601,9 @@ var init_hook_env = __esm(() => {
2601
2601
  // src/lib/run.ts
2602
2602
  var exports_run = {};
2603
2603
  __export(exports_run, {
2604
- BUN_ISOLATION_FLAGS: () => BUN_ISOLATION_FLAGS,
2604
+ executeVerifiedScript: () => executeVerifiedScript,
2605
2605
  HookTimeoutError: () => HookTimeoutError,
2606
- executeVerifiedScript: () => executeVerifiedScript
2606
+ BUN_ISOLATION_FLAGS: () => BUN_ISOLATION_FLAGS
2607
2607
  });
2608
2608
  import { randomBytes as randomBytes2 } from "crypto";
2609
2609
  import { rmSync as rmSync5, writeFileSync as writeFileSync11 } from "fs";
@@ -2767,12 +2767,12 @@ var init_run = __esm(() => {
2767
2767
  // src/lib/db-writer.ts
2768
2768
  var exports_db_writer = {};
2769
2769
  __export(exports_db_writer, {
2770
- __resetHookEventSinkNotice: () => __resetHookEventSinkNotice,
2771
- normalizeEventType: () => normalizeEventType,
2772
- recordHookRun: () => recordHookRun,
2773
- resolveEventType: () => resolveEventType,
2770
+ writeHookEvent: () => writeHookEvent,
2774
2771
  resolveHookEventSink: () => resolveHookEventSink,
2775
- writeHookEvent: () => writeHookEvent
2772
+ resolveEventType: () => resolveEventType,
2773
+ recordHookRun: () => recordHookRun,
2774
+ normalizeEventType: () => normalizeEventType,
2775
+ __resetHookEventSinkNotice: () => __resetHookEventSinkNotice
2776
2776
  });
2777
2777
  function resolveHookEventSink(env = process.env) {
2778
2778
  if (isLocalStoreRefused())
@@ -2894,7 +2894,7 @@ import { fileURLToPath as fileURLToPath4 } from "url";
2894
2894
 
2895
2895
  // src/lib/installer.ts
2896
2896
  init_registry();
2897
- import { existsSync as existsSync14, mkdirSync as mkdirSync12, readFileSync as readFileSync13, readdirSync as readdirSync8, realpathSync as realpathSync4, rmdirSync as rmdirSync4, unlinkSync as unlinkSync6, writeFileSync as writeFileSync10 } from "fs";
2897
+ import { existsSync as existsSync14, mkdirSync as mkdirSync12, readFileSync as readFileSync13, readdirSync as readdirSync12, realpathSync as realpathSync4, rmdirSync as rmdirSync4, unlinkSync as unlinkSync6, writeFileSync as writeFileSync10 } from "fs";
2898
2898
  import { join as join24, dirname as dirname16, basename as basename12, resolve as resolve28 } from "path";
2899
2899
  import { homedir as homedir8 } from "os";
2900
2900
  import { fileURLToPath as fileURLToPath3 } from "url";
@@ -3983,12 +3983,15 @@ import { existsSync as existsSync11, lstatSync as lstatSync9 } from "fs";
3983
3983
  import { homedir as homedir7 } from "os";
3984
3984
  import { join as join17, resolve as resolve9 } from "path";
3985
3985
 
3986
- // ../../node_modules/.bun/@hasna+skills@0.10.78+a00d3064559565bb/node_modules/@hasna/skills/dist/index.js
3986
+ // ../../../../../../home/hasna/.hasna/scratchpad/scratch/baf4a176-62b7-49a5-aab3-8dcbe08e5fc2/apps-copy/node_modules/.bun/@hasna+skills@0.10.78+a00d3064559565bb/node_modules/@hasna/skills/dist/index.js
3987
3987
  import { existsSync as existsSync10 } from "fs";
3988
3988
  import { homedir as homedir6 } from "os";
3989
3989
  import { join as join11, resolve as resolve4 } from "path";
3990
3990
  import { homedir as pathsResolverHomedir2 } from "os";
3991
3991
  import { join as pathsResolverJoin2 } from "path";
3992
+ import { createHash as createHash6 } from "crypto";
3993
+ import { existsSync as existsSync52, readdirSync as readdirSync3, readFileSync as readFileSync42, statSync as statSync4 } from "fs";
3994
+ import { join as join52, sep as sep2 } from "path";
3992
3995
  import { createHash as createHash32 } from "crypto";
3993
3996
  import { createHash as createHash22 } from "crypto";
3994
3997
  import { closeSync as closeSync22, constants as constants22, fstatSync as fstatSync22, lstatSync as lstatSync42, openSync as openSync22, readSync } from "fs";
@@ -3998,14 +4001,14 @@ import { createHash as createHash42 } from "crypto";
3998
4001
  import { basename as basename3, dirname as dirname42, isAbsolute as isAbsolute32, resolve as resolve32 } from "path";
3999
4002
  import { createHash as createHash52 } from "crypto";
4000
4003
  import { closeSync as closeSync32, constants as constants3, fstatSync as fstatSync3, lstatSync as lstatSync5, openSync as openSync32, readSync as readSync2 } from "fs";
4001
- import { basename as basename4, dirname as dirname52, isAbsolute as isAbsolute4, resolve as resolve42, sep as sep2 } from "path";
4004
+ import { basename as basename4, dirname as dirname52, isAbsolute as isAbsolute4, resolve as resolve42, sep as sep22 } from "path";
4002
4005
  import { createHash as createHash30 } from "crypto";
4003
4006
  import { lstatSync as lstatSync32, readFileSync as readFileSync26, readdirSync as readdirSync13, realpathSync as realpathSync13 } from "fs";
4004
4007
  import { basename as basename15, dirname as dirname26, isAbsolute as isAbsolute28, join as join38, relative as relative10, resolve as resolve27, sep as sep15 } from "path";
4005
4008
  import { isDeepStrictEqual as isDeepStrictEqual9 } from "util";
4006
4009
  import { dirname as dirname62, isAbsolute as isAbsolute6, join as join82, resolve as resolve6 } from "path";
4007
4010
  import { lstatSync as lstatSync6, readFileSync as readFileSync62, opendirSync } from "fs";
4008
- import { createHash as createHash6 } from "crypto";
4011
+ import { createHash as createHash62 } from "crypto";
4009
4012
  import { lstatSync as lstatSync7, opendirSync as opendirSync2 } from "fs";
4010
4013
  import { dirname as dirname7, isAbsolute as isAbsolute7, join as join92, resolve as resolve7 } from "path";
4011
4014
  import { createHash as createHash7 } from "crypto";
@@ -4080,6 +4083,7 @@ import { closeSync as closeSync19, constants as constants20, fstatSync as fstatS
4080
4083
  import { basename as basename14, dirname as dirname25, isAbsolute as isAbsolute27, resolve as resolve26 } from "path";
4081
4084
  import { createHash as createHash29 } from "crypto";
4082
4085
  import { isAbsolute as isAbsolute30 } from "path";
4086
+ import { createHash as createHash34 } from "crypto";
4083
4087
  var __defProp2 = Object.defineProperty;
4084
4088
  var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
4085
4089
  var __returnValue2 = (v) => v;
@@ -11056,7 +11060,132 @@ class SkillEntryPaths {
11056
11060
  this.files.add(key);
11057
11061
  }
11058
11062
  }
11063
+ var CONTENT_HASH_ALGORITHM = "sha256";
11059
11064
  var HASH_EXCLUDE_DIRS = new Set([".git", "node_modules", "dist", "build", ".turbo"]);
11065
+ function excludedHashEntry(name, directory) {
11066
+ return name.startsWith(".") || directory && HASH_EXCLUDE_DIRS.has(name);
11067
+ }
11068
+ var HASH_COVERAGE = [
11069
+ "SKILL.md",
11070
+ "skill.json",
11071
+ "AGENTS.md",
11072
+ "package.json",
11073
+ "tsconfig.json",
11074
+ "src",
11075
+ "scripts",
11076
+ "assets",
11077
+ "references"
11078
+ ];
11079
+ function normalizeLineEndings(content) {
11080
+ return content.replace(/\r\n/g, `
11081
+ `).replace(/\r/g, `
11082
+ `);
11083
+ }
11084
+ function canonicalizeManifest(raw) {
11085
+ let parsed;
11086
+ try {
11087
+ parsed = JSON.parse(raw);
11088
+ } catch {
11089
+ return normalizeLineEndings(raw);
11090
+ }
11091
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
11092
+ return normalizeLineEndings(raw);
11093
+ }
11094
+ const record = parsed;
11095
+ delete record.content_hash;
11096
+ if (record.provenance && typeof record.provenance === "object" && !Array.isArray(record.provenance)) {
11097
+ delete record.provenance.content_hash;
11098
+ }
11099
+ return `${JSON.stringify(sortObjectKeys(record), null, 2)}
11100
+ `;
11101
+ }
11102
+ function sortObjectKeys(value) {
11103
+ if (Array.isArray(value))
11104
+ return value.map((item) => sortObjectKeys(item));
11105
+ if (typeof value === "object" && value !== null) {
11106
+ const record = value;
11107
+ const sorted = Object.create(null);
11108
+ for (const key of Object.keys(record).sort())
11109
+ sorted[key] = sortObjectKeys(record[key]);
11110
+ return sorted;
11111
+ }
11112
+ return value;
11113
+ }
11114
+ function looksLikeText(buffer) {
11115
+ return !buffer.includes(0);
11116
+ }
11117
+ function collectBundleFiles(skillPath) {
11118
+ const files = [];
11119
+ const seen = new Set;
11120
+ for (const entry of HASH_COVERAGE) {
11121
+ if (seen.has(entry))
11122
+ continue;
11123
+ seen.add(entry);
11124
+ const absolute = join52(skillPath, entry);
11125
+ if (!existsSync52(absolute))
11126
+ continue;
11127
+ if (statSync4(absolute).isDirectory())
11128
+ collectDirectory(files, absolute, entry);
11129
+ else
11130
+ collectFile(files, absolute, entry);
11131
+ }
11132
+ return files.sort((a, b) => a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0);
11133
+ }
11134
+ function collectDirectory(files, dir, rel) {
11135
+ for (const entry of readdirSync3(dir).sort()) {
11136
+ if (entry.startsWith("."))
11137
+ continue;
11138
+ const absolute = join52(dir, entry);
11139
+ const childRel = `${rel}/${entry}`;
11140
+ let stats;
11141
+ try {
11142
+ stats = statSync4(absolute);
11143
+ } catch {
11144
+ continue;
11145
+ }
11146
+ if (stats.isSymbolicLink())
11147
+ continue;
11148
+ if (stats.isDirectory()) {
11149
+ if (excludedHashEntry(entry, true))
11150
+ continue;
11151
+ collectDirectory(files, absolute, childRel);
11152
+ } else if (stats.isFile()) {
11153
+ collectFile(files, absolute, childRel);
11154
+ }
11155
+ }
11156
+ }
11157
+ function collectFile(files, absolute, rel) {
11158
+ const buffer = readFileSync42(absolute);
11159
+ files.push(normalizeBundleFile(rel.split(sep2).join("/"), buffer));
11160
+ }
11161
+ function normalizeBundleFile(rel, buffer) {
11162
+ if (rel === "skill.json") {
11163
+ return { rel, content: new TextEncoder().encode(canonicalizeManifest(new TextDecoder().decode(buffer))) };
11164
+ }
11165
+ if (looksLikeText(buffer)) {
11166
+ const normalized = normalizeLineEndings(new TextDecoder().decode(buffer));
11167
+ return { rel, content: new TextEncoder().encode(normalized) };
11168
+ }
11169
+ return { rel, content: buffer };
11170
+ }
11171
+ function computeContentHash(skillPath) {
11172
+ return hashBundleFiles(collectBundleFiles(skillPath));
11173
+ }
11174
+ function* bundleHashParts(files) {
11175
+ for (const file of files) {
11176
+ yield new TextEncoder().encode(file.rel);
11177
+ yield new TextEncoder().encode(`\x00${file.content.length}\x00`);
11178
+ yield file.content;
11179
+ yield new TextEncoder().encode("\x00");
11180
+ }
11181
+ yield new TextEncoder().encode("\x00");
11182
+ }
11183
+ function hashBundleFiles(files) {
11184
+ const hash = createHash6(CONTENT_HASH_ALGORITHM);
11185
+ for (const part of bundleHashParts(files))
11186
+ hash.update(part);
11187
+ return hash.digest("hex");
11188
+ }
11060
11189
  var CONTENT_HASH_LIMITS = Object.freeze({
11061
11190
  entries: 1024,
11062
11191
  rawBytes: 64 * 1024 * 1024,
@@ -11071,6 +11200,173 @@ var CONTENT_HASH_LIMITS = Object.freeze({
11071
11200
  var typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
11072
11201
  var byteLengthOf = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength").get;
11073
11202
  var bufferOf = Object.getOwnPropertyDescriptor(typedArrayPrototype, "buffer").get;
11203
+ function verifyContentHash(skillPath, manifest) {
11204
+ const declaredHash = manifest?.provenance?.content_hash?.trim() || undefined;
11205
+ if (!declaredHash)
11206
+ return { declared: false, valid: false };
11207
+ if (!/^[a-f0-9]{64}$/.test(declaredHash)) {
11208
+ return { declared: true, valid: false, declaredHash };
11209
+ }
11210
+ const computedHash = computeContentHash(skillPath);
11211
+ return {
11212
+ declared: true,
11213
+ valid: computedHash === declaredHash,
11214
+ declaredHash,
11215
+ computedHash
11216
+ };
11217
+ }
11218
+ var PORTABLE_SKILL_STANDARD = "hasna.skill.v1";
11219
+ var SKILL_RUNTIMES = ["bun", "node", "python3"];
11220
+ var SKILL_SANDBOX_MODES = ["readonly-fs", "workspace-write", "full"];
11221
+ var SKILL_SYSTEM_DEPS_ALLOWLIST = [
11222
+ "ffmpeg",
11223
+ "ffprobe",
11224
+ "imagemagick",
11225
+ "convert",
11226
+ "curl",
11227
+ "wget",
11228
+ "git",
11229
+ "gh",
11230
+ "jq",
11231
+ "python3",
11232
+ "pip3",
11233
+ "node",
11234
+ "bun",
11235
+ "npm",
11236
+ "rsync",
11237
+ "pdftotext",
11238
+ "tesseract",
11239
+ "7z",
11240
+ "unzip",
11241
+ "zip"
11242
+ ];
11243
+ var SEMVER_PATTERN2 = "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$";
11244
+ var CONTENT_HASH_PATTERN = "^[a-f0-9]{64}$";
11245
+ var ENV_REFERENCE_PATTERN = "^[A-Z0-9_]+$";
11246
+ var MAX_RUNTIME_TIMEOUT_SECONDS = 900;
11247
+ function add2(target, code, message) {
11248
+ target.push({ code, message });
11249
+ }
11250
+ function isRecord(value) {
11251
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11252
+ }
11253
+ function isNonEmptyString(value) {
11254
+ return typeof value === "string" && value.trim().length > 0;
11255
+ }
11256
+ function validatePortableManifestContract(manifest, options = {}) {
11257
+ const issues = [];
11258
+ if (!manifest) {
11259
+ add2(issues, "contract.manifest_missing", "No portable manifest to validate");
11260
+ return issues;
11261
+ }
11262
+ if (manifest.standard !== PORTABLE_SKILL_STANDARD) {
11263
+ add2(issues, "contract.standard_invalid", `standard must be '${PORTABLE_SKILL_STANDARD}'`);
11264
+ }
11265
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(manifest.name)) {
11266
+ add2(issues, "contract.name_invalid", `name '${manifest.name}' must be a lowercase slug (letters, numbers, dots, underscores, hyphens)`);
11267
+ }
11268
+ if (!isNonEmptyString(manifest.description)) {
11269
+ add2(issues, "contract.description_missing", "description is required");
11270
+ }
11271
+ if (!isNonEmptyString(manifest.version)) {
11272
+ add2(issues, "contract.version_missing", "version is required");
11273
+ } else if (!new RegExp(SEMVER_PATTERN2).test(manifest.version)) {
11274
+ add2(issues, "contract.version_invalid", `version '${manifest.version}' is not valid semver`);
11275
+ }
11276
+ validateRuntimeContract(manifest, issues, options.strict === true);
11277
+ const provenance = manifest.provenance;
11278
+ if (provenance && !isRecord(provenance)) {
11279
+ add2(issues, "contract.provenance_invalid", "provenance must be an object");
11280
+ } else {
11281
+ const sourceCommit = provenance?.source_commit;
11282
+ if (sourceCommit !== undefined && sourceCommit !== null && !isNonEmptyString(sourceCommit)) {
11283
+ add2(issues, "contract.source_commit_invalid", "provenance.source_commit must be a string");
11284
+ }
11285
+ const changelog = provenance?.changelog;
11286
+ if (changelog !== undefined && changelog !== null && !isNonEmptyString(changelog)) {
11287
+ add2(issues, "contract.changelog_invalid", "provenance.changelog must be a string");
11288
+ }
11289
+ const declaredHash = provenance?.content_hash;
11290
+ if (options.strict && !isNonEmptyString(declaredHash)) {
11291
+ add2(issues, "contract.content_hash_missing", "provenance.content_hash is required: a portable manifest must carry its canonical content hash");
11292
+ } else if (isNonEmptyString(declaredHash) && !new RegExp(CONTENT_HASH_PATTERN).test(declaredHash)) {
11293
+ add2(issues, "contract.content_hash_invalid", "provenance.content_hash must be a 64-character lowercase hex SHA-256");
11294
+ } else if (options.skillPath && isNonEmptyString(declaredHash)) {
11295
+ const verification = verifyContentHash(options.skillPath, manifest);
11296
+ if (!verification.valid) {
11297
+ 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).`);
11298
+ }
11299
+ }
11300
+ }
11301
+ return issues;
11302
+ }
11303
+ function validateRuntimeContract(manifest, issues, strict) {
11304
+ const runtime = manifest.runtime;
11305
+ if (runtime === undefined) {
11306
+ if (strict && manifest.kind !== "instruction") {
11307
+ add2(issues, "contract.runtime_missing", "runtime contract is required: { runtime, entrypoint?, timeout?, needs_network?, env?, sandbox?, system_deps?, artifacts? }");
11308
+ }
11309
+ return;
11310
+ }
11311
+ if (!isRecord(runtime)) {
11312
+ add2(issues, "contract.runtime_invalid", "runtime must be an object");
11313
+ return;
11314
+ }
11315
+ const runtimeName = runtime.runtime;
11316
+ if (!SKILL_RUNTIMES.includes(runtimeName)) {
11317
+ add2(issues, "contract.runtime_invalid", `runtime.runtime must be one of: ${SKILL_RUNTIMES.join(", ")}`);
11318
+ }
11319
+ if (runtime.version !== undefined && runtime.version !== null && !isNonEmptyString(runtime.version)) {
11320
+ add2(issues, "contract.runtime_version_invalid", "runtime.version must be a string");
11321
+ }
11322
+ if (runtime.entrypoint !== undefined && runtime.entrypoint !== null && !isNonEmptyString(runtime.entrypoint)) {
11323
+ add2(issues, "contract.entrypoint_invalid", "runtime.entrypoint must be a relative path string");
11324
+ }
11325
+ if (runtime.timeout !== undefined && runtime.timeout !== null) {
11326
+ if (typeof runtime.timeout !== "number" || !Number.isInteger(runtime.timeout) || runtime.timeout < 1 || runtime.timeout > MAX_RUNTIME_TIMEOUT_SECONDS) {
11327
+ add2(issues, "contract.timeout_invalid", `runtime.timeout must be an integer between 1 and ${MAX_RUNTIME_TIMEOUT_SECONDS} seconds`);
11328
+ }
11329
+ }
11330
+ if (runtime.needs_network !== undefined && runtime.needs_network !== null && typeof runtime.needs_network !== "boolean") {
11331
+ add2(issues, "contract.needs_network_invalid", "runtime.needs_network must be a boolean");
11332
+ }
11333
+ if (runtime.env !== undefined && runtime.env !== null) {
11334
+ if (!Array.isArray(runtime.env)) {
11335
+ add2(issues, "contract.env_invalid", "runtime.env must be an array of secret REFERENCE names");
11336
+ } else {
11337
+ for (const reference of runtime.env) {
11338
+ if (typeof reference !== "string" || !new RegExp(ENV_REFERENCE_PATTERN).test(reference)) {
11339
+ 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`);
11340
+ }
11341
+ }
11342
+ }
11343
+ }
11344
+ if (runtime.sandbox !== undefined && runtime.sandbox !== null && !SKILL_SANDBOX_MODES.includes(runtime.sandbox)) {
11345
+ add2(issues, "contract.sandbox_invalid", `runtime.sandbox must be one of: ${SKILL_SANDBOX_MODES.join(", ")}`);
11346
+ }
11347
+ if (runtime.system_deps !== undefined && runtime.system_deps !== null) {
11348
+ if (!Array.isArray(runtime.system_deps)) {
11349
+ add2(issues, "contract.system_deps_invalid", "runtime.system_deps must be an array");
11350
+ } else {
11351
+ for (const dep of runtime.system_deps) {
11352
+ if (!SKILL_SYSTEM_DEPS_ALLOWLIST.includes(dep)) {
11353
+ add2(issues, "contract.system_dep_not_allowed", `runtime.system_deps entry '${dep}' is not on the allowlist: ${SKILL_SYSTEM_DEPS_ALLOWLIST.join(", ")}`);
11354
+ }
11355
+ }
11356
+ }
11357
+ }
11358
+ if (runtime.artifacts !== undefined && runtime.artifacts !== null) {
11359
+ if (!Array.isArray(runtime.artifacts)) {
11360
+ add2(issues, "contract.artifacts_invalid", "runtime.artifacts must be an array of glob patterns");
11361
+ } else {
11362
+ for (const glob of runtime.artifacts) {
11363
+ if (!isNonEmptyString(glob)) {
11364
+ add2(issues, "contract.artifacts_invalid", "runtime.artifacts entries must be non-empty glob strings");
11365
+ }
11366
+ }
11367
+ }
11368
+ }
11369
+ }
11074
11370
  var ANY_SEGMENT_COPY_EXCLUDES = new Set([
11075
11371
  ".git",
11076
11372
  ".DS_Store",
@@ -11760,14 +12056,14 @@ function captureClaudeMarketplaceEntry(path, marketplace, plugin, budget2 = { re
11760
12056
  return { path, hashMode: CLAUDE_MARKETPLACE_ENTRY_HASH_MODE, marketplace, plugin, sha256: hashClaudeMarketplaceEntry(text, { marketplace, plugin }) };
11761
12057
  }
11762
12058
  var CLAUDE_ORPHAN_MARKER_MODE = "claude-plugin-orphaned-at-v1";
11763
- var CACHE = `${sep2}.claude${sep2}plugins${sep2}cache${sep2}`;
12059
+ var CACHE = `${sep22}.claude${sep22}plugins${sep22}cache${sep22}`;
11764
12060
  function isClaudePluginCacheOrphanMarker(path) {
11765
12061
  if (typeof path !== "string" || basename4(path) !== ".orphaned_at" || !isAbsolute4(path) || resolve42(path) !== path || path.includes("\x00"))
11766
12062
  return false;
11767
12063
  const at = path.indexOf(CACHE);
11768
12064
  if (at < 0 || path.indexOf(CACHE, at + 1) >= 0)
11769
12065
  return false;
11770
- const parts = path.slice(at + CACHE.length).split(sep2);
12066
+ const parts = path.slice(at + CACHE.length).split(sep22);
11771
12067
  return parts.length === 4 && parts.every((part) => part && part !== "." && part !== "..");
11772
12068
  }
11773
12069
  function same(left, right) {
@@ -12379,7 +12675,7 @@ function capture(path, budget2, excludedRoots, omittedRoots = [], rows) {
12379
12675
  if (!root)
12380
12676
  return { path, sha256: null };
12381
12677
  need3(root.isDirectory(), "Unsupported native discovery directory input");
12382
- const hash = createHash6("sha256");
12678
+ const hash = createHash62("sha256");
12383
12679
  function walk(current2, relative2, before, depth) {
12384
12680
  need3(depth <= 64, "Native discovery directory depth limit exceeded");
12385
12681
  const names = [], directory = opendirSync2(current2);
@@ -12431,7 +12727,7 @@ function verifyDiscoveryDirectoryProjection(directories, omittedRoots, tolerance
12431
12727
  const expected = directories.map((directory) => {
12432
12728
  safe2(directory.path);
12433
12729
  need3(Array.isArray(directory.entries), "Missing reviewed directory membership inventory");
12434
- const hash = createHash6("sha256");
12730
+ const hash = createHash62("sha256");
12435
12731
  const kept = [];
12436
12732
  for (const row of directory.entries) {
12437
12733
  need3(typeof row === "string" && ++count <= AGENT_POLICY_LIMITS.discoveryDirectoryEntries, "Invalid reviewed directory membership rows");
@@ -12447,7 +12743,7 @@ function verifyDiscoveryDirectoryProjection(directories, omittedRoots, tolerance
12447
12743
  }
12448
12744
  need3(directory.sha256 === null ? directory.entries.length === 0 : hash.digest("hex") === directory.sha256, "Reviewed directory inventory does not match its fingerprint");
12449
12745
  const absent = omittedRoots.some((root) => directory.path === root || directory.path.startsWith(root + "/"));
12450
- return { path: directory.path, sha256: absent || directory.sha256 === null ? null : createHash6("sha256").update(kept.join("")).digest("hex") };
12746
+ return { path: directory.path, sha256: absent || directory.sha256 === null ? null : createHash62("sha256").update(kept.join("")).digest("hex") };
12451
12747
  });
12452
12748
  const current2 = captureDiscoveryDirectoryProjection(directories.map((item) => item.path), omittedRoots);
12453
12749
  for (let i = 0;i < current2.length; i++)
@@ -12535,6 +12831,7 @@ function hashRawDiscoveryFile(path, budget2, changes) {
12535
12831
  closeSync4(fd);
12536
12832
  }
12537
12833
  }
12834
+ var BLOCK = 512;
12538
12835
  var ANY_SEGMENT_EXCLUDES = new Set([
12539
12836
  ".git",
12540
12837
  ".ds_store",
@@ -12664,6 +12961,136 @@ var SKILL_BUNDLE_INSPECTION_LIMITS = Object.freeze({
12664
12961
  pathBytes: 100,
12665
12962
  timeoutMs: 5000
12666
12963
  });
12964
+
12965
+ class SkillBundleInspectionError extends Error {
12966
+ code;
12967
+ constructor(code, message) {
12968
+ super(message);
12969
+ this.code = code;
12970
+ this.name = "SkillBundleInspectionError";
12971
+ }
12972
+ }
12973
+ function invalidBundle(message) {
12974
+ throw new SkillBundleInspectionError("BUNDLE_INVALID", message);
12975
+ }
12976
+ class BoundedTarReader {
12977
+ limits;
12978
+ check;
12979
+ header = new Uint8Array(BLOCK);
12980
+ headerOffset = 0;
12981
+ pending;
12982
+ bodyOffset = 0;
12983
+ padding = 0;
12984
+ zeroBlocks = 0;
12985
+ entries = [];
12986
+ paths = new SkillEntryPaths;
12987
+ fileBytes = 0;
12988
+ constructor(limits, check) {
12989
+ this.limits = limits;
12990
+ this.check = check;
12991
+ }
12992
+ push(chunk) {
12993
+ let offset = 0;
12994
+ while (offset < chunk.byteLength) {
12995
+ this.check();
12996
+ if (this.pending) {
12997
+ const count = Math.min(this.pending.bytes.byteLength - this.bodyOffset, chunk.byteLength - offset);
12998
+ this.pending.bytes.set(chunk.subarray(offset, offset + count), this.bodyOffset);
12999
+ offset += count;
13000
+ this.bodyOffset += count;
13001
+ if (this.bodyOffset === this.pending.bytes.byteLength) {
13002
+ this.entries.push(this.pending);
13003
+ this.pending = undefined;
13004
+ }
13005
+ } else if (this.padding) {
13006
+ const count = Math.min(this.padding, chunk.byteLength - offset);
13007
+ if (chunk.subarray(offset, offset + count).some((byte) => byte !== 0))
13008
+ invalidBundle("Nonzero tar body padding");
13009
+ offset += count;
13010
+ this.padding -= count;
13011
+ } else {
13012
+ const count = Math.min(BLOCK - this.headerOffset, chunk.byteLength - offset);
13013
+ this.header.set(chunk.subarray(offset, offset + count), this.headerOffset);
13014
+ offset += count;
13015
+ this.headerOffset += count;
13016
+ if (this.headerOffset === BLOCK) {
13017
+ this.readHeader();
13018
+ this.headerOffset = 0;
13019
+ }
13020
+ }
13021
+ }
13022
+ }
13023
+ finish() {
13024
+ this.check();
13025
+ if (this.pending || this.padding || this.headerOffset || this.zeroBlocks < 2)
13026
+ invalidBundle("Truncated tar bundle");
13027
+ return this.entries;
13028
+ }
13029
+ readHeader() {
13030
+ this.check();
13031
+ const h = this.header;
13032
+ if (h.every((byte) => byte === 0)) {
13033
+ this.zeroBlocks++;
13034
+ return;
13035
+ }
13036
+ if (this.zeroBlocks)
13037
+ invalidBundle("Nonzero tar data after terminator");
13038
+ if (this.entries.length >= this.limits.entries)
13039
+ throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle entry limit exceeded");
13040
+ let checksum = 0;
13041
+ for (let i = 0;i < BLOCK; i++)
13042
+ checksum += i >= 148 && i < 156 ? 32 : h[i];
13043
+ if (tarOctal(h.subarray(148, 156)) !== checksum)
13044
+ invalidBundle("Invalid tar header checksum");
13045
+ if (new TextDecoder().decode(h.subarray(257, 265)) !== "ustar\x00" + "00")
13046
+ invalidBundle("Unsupported tar format");
13047
+ if (h[156] !== 48 && h[156] !== 0 || h.subarray(157, 257).some((b) => b !== 0) || h.subarray(345).some((b) => b !== 0))
13048
+ invalidBundle("Unsupported tar entry or path prefix");
13049
+ const mode = tarOctal(h.subarray(100, 108));
13050
+ if (mode > 511)
13051
+ invalidBundle("Unsupported tar permission bits");
13052
+ tarOctal(h.subarray(108, 116));
13053
+ tarOctal(h.subarray(116, 124));
13054
+ tarOctal(h.subarray(136, 148));
13055
+ const size = tarOctal(h.subarray(124, 136));
13056
+ if (size > this.limits.fileBytes || this.fileBytes + size > this.limits.decompressedBytes) {
13057
+ throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle file byte limit exceeded");
13058
+ }
13059
+ const name = h.subarray(0, 100);
13060
+ const end = name.indexOf(0);
13061
+ if (end !== -1 && name.subarray(end).some((b) => b !== 0))
13062
+ invalidBundle("Invalid tar path padding");
13063
+ const raw = end === -1 ? name : name.subarray(0, end);
13064
+ if (raw.byteLength > this.limits.pathBytes)
13065
+ throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle path byte limit exceeded");
13066
+ let path;
13067
+ try {
13068
+ path = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(raw);
13069
+ } catch {
13070
+ return invalidBundle("Invalid UTF-8 bundle path");
13071
+ }
13072
+ this.paths.add(path, this.limits.pathBytes, invalidBundle, () => {
13073
+ throw new SkillBundleInspectionError("BUNDLE_LIMIT", "Bundle path byte limit exceeded");
13074
+ });
13075
+ this.fileBytes += size;
13076
+ this.pending = { path, mode, bytes: new Uint8Array(new ArrayBuffer(size)) };
13077
+ this.bodyOffset = 0;
13078
+ this.padding = (BLOCK - size % BLOCK) % BLOCK;
13079
+ if (!size) {
13080
+ this.entries.push(this.pending);
13081
+ this.pending = undefined;
13082
+ }
13083
+ }
13084
+ }
13085
+ function tarOctal(field2) {
13086
+ const text2 = new TextDecoder().decode(field2);
13087
+ if (!/^[0-7]+[\0 ]*$/.test(text2))
13088
+ invalidBundle("Invalid tar octal field");
13089
+ const value = Number.parseInt(text2, 8);
13090
+ if (!Number.isSafeInteger(value))
13091
+ invalidBundle("Tar integer is out of range");
13092
+ return value;
13093
+ }
12667
13094
  var SKILL_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
12668
13095
  function isValidSkillVersion(value) {
12669
13096
  return typeof value === "string" && SKILL_VERSION_PATTERN.test(value) && !/^\.+$/.test(value) && !value.includes("..");
@@ -15890,6 +16317,50 @@ var SKILLS_API_URL_ENV_KEYS = ENV_KEYS.apiUrlKeys;
15890
16317
  var SKILLS_API_KEY_ENV_KEYS = ENV_KEYS.apiKeyKeys;
15891
16318
  var SKILLS_API_URL_ENV = SKILLS_API_URL_ENV_KEYS[0];
15892
16319
  var SKILLS_API_KEY_ENV = SKILLS_API_KEY_ENV_KEYS[0];
16320
+
16321
+ class SkillsFleetCredentialError extends Error {
16322
+ code;
16323
+ next;
16324
+ constructor(message, code = "MISSING_API_CREDENTIAL", next) {
16325
+ super(message);
16326
+ this.name = "SkillsFleetCredentialError";
16327
+ this.code = code;
16328
+ if (next)
16329
+ this.next = next;
16330
+ }
16331
+ }
16332
+ function normalizeSkillsApiOrigin(apiUrl) {
16333
+ const url = new URL(apiUrl);
16334
+ if (url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
16335
+ throw new SkillsFleetCredentialError("A Skills API URL must use HTTPS (or loopback HTTP), without credentials, query or fragment", "INVALID_API_URL");
16336
+ }
16337
+ const pathname = url.pathname.replace(/\/+$/, "");
16338
+ if (url.origin === "https://api.hasna.com" && pathname === "/skills/v1") {
16339
+ url.pathname = "/skills";
16340
+ } else if (pathname === "/api" || pathname === "/api/v1") {
16341
+ url.pathname = "/";
16342
+ } else if (pathname.endsWith("/api/v1")) {
16343
+ url.pathname = pathname.slice(0, -"/api/v1".length) || "/";
16344
+ } else if (pathname.endsWith("/api")) {
16345
+ url.pathname = pathname.slice(0, -"/api".length) || "/";
16346
+ }
16347
+ return url.toString().replace(/\/+$/, "");
16348
+ }
16349
+ function skillsApiRequestUrl(apiUrl, route) {
16350
+ const origin = normalizeSkillsApiOrigin(apiUrl);
16351
+ if (!route.startsWith("/api/") || route.includes("#") || route.includes("\\")) {
16352
+ throw new SkillsFleetCredentialError("Invalid Skills API route", "INVALID_API_URL");
16353
+ }
16354
+ if (origin === "https://api.hasna.com/skills") {
16355
+ if (route === "/api/auth/whoami")
16356
+ return `${origin}/v1/auth/whoami`;
16357
+ if (!route.startsWith("/api/v1/")) {
16358
+ throw new SkillsFleetCredentialError("The internal Skills gateway has no established login contract yet. Select an explicitly configured instance with supported authentication.", "GATEWAY_AUTH_UNAVAILABLE");
16359
+ }
16360
+ return `${origin}${route.slice("/api".length)}`;
16361
+ }
16362
+ return `${origin}${route}`;
16363
+ }
15893
16364
  var MAX_REMOTE_FILE_BYTES = 64 * 1024 * 1024;
15894
16365
  var CODEX_NATIVE_POLICY_CAPABILITY = "host-path-allowlist-v1";
15895
16366
  var CODEX_NATIVE_POLICY_RECEIPT_SCHEMA = "skills.codex-native-policy-acceptance/v1";
@@ -39809,6 +40280,46 @@ var revocation = exports_external.object({
39809
40280
  });
39810
40281
  var page = (item) => exports_external.object({ contractVersion: exports_external.literal(1), items: exports_external.array(item).max(100), nextCursor: exports_external.string().min(1).max(2048).nullable() });
39811
40282
  var results = { preview, draft: preview.nullable(), activate: exports_external.object({ replayed: exports_external.boolean(), consent }), list: page(consent), get: consent.nullable(), occurrences: page(occurrence), revoke: revocation };
40283
+ var record7 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
40284
+ var uuid8 = (v) => typeof v === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(v);
40285
+ var text2 = (v, max = 1024) => typeof v === "string" && !!v.trim() && v.length <= max && !/[\p{Cc}\p{Cs}\u2028\u2029]/u.test(v);
40286
+ var role2 = (v) => typeof v === "string" && ["owner", "admin", "member", "viewer"].includes(v);
40287
+ var invalidWorkspaceResult = "The server returned an invalid workspace selection result.";
40288
+ class WorkspaceIdentityMismatchError extends Error {
40289
+ constructor() {
40290
+ super("The verified account does not match the requested workspace context.");
40291
+ this.name = "WorkspaceIdentityMismatchError";
40292
+ }
40293
+ }
40294
+ function invalid3() {
40295
+ throw new Error(invalidWorkspaceResult);
40296
+ }
40297
+ function organization(v) {
40298
+ if (!record7(v) || !uuid8(v.id) || !text2(v.slug) || !text2(v.name))
40299
+ return invalid3();
40300
+ return { id: v.id, slug: v.slug, name: v.name };
40301
+ }
40302
+ function parseWorkspaceIdentity(value, expectedUserId) {
40303
+ if (!record7(value))
40304
+ return invalid3();
40305
+ const user = value.user;
40306
+ if (!record7(user) || !uuid8(user.id) || !uuid8(user.membershipId) || !text2(user.email, 320) || !(user.displayName === null || text2(user.displayName)) || !role2(user.role))
40307
+ return invalid3();
40308
+ if (user.id !== expectedUserId)
40309
+ throw new WorkspaceIdentityMismatchError;
40310
+ return { user: { id: user.id, membershipId: user.membershipId, email: user.email, displayName: user.displayName, role: user.role }, organization: organization(value.organization) };
40311
+ }
40312
+ function sessionToken(value) {
40313
+ if (typeof value !== "string" || !value || value.length > 8192 || /[^\x21-\x7e]/.test(value) || value.startsWith("sk_"))
40314
+ return invalid3();
40315
+ return value;
40316
+ }
40317
+ function parseWorkspaceSession(value, expected) {
40318
+ const identity5 = parseWorkspaceIdentity(value, expected.userId);
40319
+ if (identity5.user.membershipId !== expected.membershipId)
40320
+ throw new WorkspaceIdentityMismatchError;
40321
+ return { token: sessionToken(value.token), ...identity5 };
40322
+ }
39812
40323
  var SKILLS_API_KEY_REF = credentialPointerEnvKey("skills");
39813
40324
  var quoteUnavailableMessages = Object.freeze({
39814
40325
  HOSTED_PROVIDER_UNAVAILABLE: "Hosted execution is temporarily unavailable on this Skills instance.",
@@ -39820,6 +40331,353 @@ var quoteUnavailableMessages = Object.freeze({
39820
40331
  });
39821
40332
  var KNOWN_SKILL_LIFECYCLE_CODES = new Set(["SKILL_ARCHIVE_PROFILE_CONFLICT", "LIFECYCLE_ROLE_REQUIRED"]);
39822
40333
  var PRIVATE_PUBLICATION_MAX_BYTES = 16 * 1024 * 1024;
40334
+ var skillCreateFailures = {
40335
+ INVALID_SLUG: [400, "Provide a lowercase kebab-case skill slug."],
40336
+ INVALID_DISPLAY_NAME: [400, "Provide a nonempty skill display name."],
40337
+ INVALID_VISIBILITY: [400, "Use private or team visibility for source publication."],
40338
+ SESSION_EXPIRED: [401, "Sign in again before creating a private skill."],
40339
+ INTERACTIVE_SESSION_REQUIRED: [403, "An interactive account session is required to create a private skill."],
40340
+ ACCOUNT_UNAVAILABLE: [403, "The current account membership cannot create a private skill."],
40341
+ PLAN_REQUIRED: [403, "Private and team skills require the Pro plan."],
40342
+ SLUG_CONFLICT: [409, "This skill slug already exists. Inspect the existing skill before publishing."]
40343
+ };
40344
+ var failures2 = {
40345
+ INVALID_REQUEST: [400, "The publication request is invalid."],
40346
+ SESSION_EXPIRED: [401, "Sign in again to manage this publication."],
40347
+ ACCOUNT_UNAVAILABLE: [403, "The account is unavailable."],
40348
+ INTERACTIVE_SESSION_REQUIRED: [403, "An interactive account session is required."],
40349
+ PUBLICATION_FORBIDDEN: [403, "This session cannot manage the publication."],
40350
+ PUBLICATION_ENTITLEMENT_REQUIRED: [403, "The workspace is not entitled to publish private skills."],
40351
+ PUBLICATION_UNAVAILABLE: [404, "The publication is unavailable to this session."],
40352
+ MANIFEST_NAME_MISMATCH: [409, "The manifest name does not match the selected skill."],
40353
+ IDEMPOTENCY_CONFLICT: [409, "This request key already identifies different publication bytes. Use the saved recovery directory."],
40354
+ CURRENT_VERSION_CHANGED: [409, "The current version changed. Inspect it before explicitly starting another publication."],
40355
+ VERSION_EXISTS: [409, "This version already exists."],
40356
+ VERSION_RESERVED: [409, "This version is reserved by another publication."],
40357
+ PUBLICATION_COMMITTED: [409, "The publication is already committed."],
40358
+ PUBLICATION_UPLOAD_UNAVAILABLE: [409, "This publication cannot receive another upload."],
40359
+ PUBLICATION_LIMIT: [429, "The workspace publication limit has been reached."],
40360
+ PUBLICATION_BUSY: [503, "The publication is busy. Reconcile the saved intent before retrying."],
40361
+ PUBLICATION_UNCERTAIN: [503, "The publication outcome is uncertain. Reconcile the saved intent."],
40362
+ PUBLICATION_CAPABILITY_UNAVAILABLE: [503, "Private publishing is not enabled on this server."],
40363
+ PUBLICATION_SIGNING_UNAVAILABLE: [503, "Upload authorization is temporarily unavailable. Keep the same intent."]
40364
+ };
40365
+
40366
+ class PrivatePublicationError extends Error {
40367
+ code;
40368
+ uncertain;
40369
+ status;
40370
+ constructor(code, message, uncertain = false, status) {
40371
+ super(message);
40372
+ this.code = code;
40373
+ this.uncertain = uncertain;
40374
+ this.status = status;
40375
+ this.name = "PrivatePublicationError";
40376
+ }
40377
+ }
40378
+ var bad = () => {
40379
+ throw new PrivatePublicationError("INVALID_PUBLICATION_INPUT", "Invalid publication input or recovery data.");
40380
+ };
40381
+ var invalid4 = () => {
40382
+ throw new PrivatePublicationError("INVALID_PUBLICATION_RESPONSE", "The server returned an invalid publication result.");
40383
+ };
40384
+ var publicationUuid = (v) => typeof v === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(v);
40385
+ var hash4 = (v) => typeof v === "string" && /^[a-f0-9]{64}$/.test(v);
40386
+ var record11 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
40387
+ var exact = (v, keys2) => record11(v) && Object.keys(v).sort().join(",") === keys2.sort().join(",");
40388
+ var date5 = (v) => typeof v === "string" && /^\d{4}-\d\d-\d\dT[0-9:.]+(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(v) && Number.isFinite(Date.parse(v));
40389
+ var publicationSha256 = (bytes) => createHash34("sha256").update(bytes).digest("hex");
40390
+ function checkedPrivateSkillCreate(value) {
40391
+ const refuse6 = (field3, accepted) => {
40392
+ throw new PrivatePublicationError("INVALID_SKILL_CREATE_INPUT", `Invalid ${field3}. ${accepted}`);
40393
+ };
40394
+ if (!record11(value) || !Object.keys(value).every((key2) => ["slug", "displayName", "description", "visibility", "confirm"].includes(key2)))
40395
+ return refuse6("create input", "Provide only slug, displayName, description, visibility and confirm.");
40396
+ if (value.confirm !== true)
40397
+ throw new PrivatePublicationError("SKILL_CREATE_CONFIRM_REQUIRED", "Explicit confirmation is required to create this skill.");
40398
+ if (typeof value.slug !== "string" || value.slug.length > 128 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value.slug))
40399
+ return refuse6("slug", "Use lowercase kebab-case, at most 128 characters.");
40400
+ if (typeof value.displayName !== "string" || !value.displayName.trim() || value.displayName.length > 256 || /[\p{Cc}\p{Cs}\u2028\u2029]/u.test(value.displayName))
40401
+ return refuse6("displayName", "Use nonempty text, at most 256 characters, without control characters.");
40402
+ 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, ""))))
40403
+ return refuse6("description", "Use text of at most 8192 UTF-8 bytes, without control characters other than tabs and newlines.");
40404
+ if (value.visibility !== undefined && value.visibility !== "private" && value.visibility !== "team")
40405
+ return refuse6("visibility", "Use private or team.");
40406
+ return Object.freeze({ slug: value.slug, displayName: value.displayName.trim(), description: value.description ?? "", visibility: value.visibility ?? "private" });
40407
+ }
40408
+ function checkedPublicationDeclaration(value) {
40409
+ 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)
40410
+ return bad();
40411
+ try {
40412
+ const manifest = JSON.parse(value.manifestText);
40413
+ if (!record11(manifest) || manifest.version !== value.version || validatePortableManifestContract(manifest, { strict: true }).length || !hash4(manifest.provenance?.content_hash))
40414
+ return bad();
40415
+ } catch {
40416
+ return bad();
40417
+ }
40418
+ return Object.freeze({ ...value });
40419
+ }
40420
+ function checkedPublicationView(value, skillId, intentId, declaration) {
40421
+ 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)
40422
+ return invalid4();
40423
+ if (declaration && ["version", "expectedCurrentVersionId", "archiveSha256", "archiveByteSize"].some((k) => value[k] !== declaration[k]))
40424
+ return invalid4();
40425
+ return Object.freeze({ ...value });
40426
+ }
40427
+ async function boundedJson(url2, init, token, mutation, budget3 = 15000, signal, create = false) {
40428
+ const controller = new AbortController;
40429
+ let reader;
40430
+ let response;
40431
+ 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);
40432
+ let timer;
40433
+ let abort;
40434
+ try {
40435
+ return await Promise.race([(async () => {
40436
+ if (signal?.aborted)
40437
+ throw timeout2;
40438
+ response = await fetch(url2, {
40439
+ ...init,
40440
+ redirect: "error",
40441
+ credentials: "omit",
40442
+ signal: controller.signal,
40443
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }
40444
+ });
40445
+ const length = response.headers.get("content-length");
40446
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > 65536))
40447
+ return invalid4();
40448
+ reader = response.body?.getReader();
40449
+ const chunks = [];
40450
+ let size = 0;
40451
+ if (reader)
40452
+ while (true) {
40453
+ const part = await reader.read();
40454
+ if (part.done)
40455
+ break;
40456
+ size += part.value.byteLength;
40457
+ if (size > 65536)
40458
+ return invalid4();
40459
+ chunks.push(part.value);
40460
+ }
40461
+ if (controller.signal.aborted)
40462
+ throw timeout2;
40463
+ const bytes = Buffer.concat(chunks);
40464
+ let body;
40465
+ try {
40466
+ body = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
40467
+ } catch {
40468
+ return invalid4();
40469
+ }
40470
+ if (!response.ok) {
40471
+ const known = create ? skillCreateFailures : failures2;
40472
+ const code = record11(body) && typeof body.code === "string" && Object.hasOwn(known, body.code) ? body.code : null;
40473
+ if (code && known[code][0] === response.status)
40474
+ throw new PrivatePublicationError(code, known[code][1], mutation && code === "PUBLICATION_UNCERTAIN", response.status);
40475
+ if (create) {
40476
+ if (response.status >= 500)
40477
+ throw timeout2;
40478
+ throw new PrivatePublicationError("SKILL_CREATE_REQUEST_FAILED", "The server refused skill creation.", false, response.status);
40479
+ }
40480
+ throw new PrivatePublicationError("PUBLICATION_REQUEST_FAILED", "The publication request was refused. Inspect its status before retrying.", mutation && response.status >= 500, response.status);
40481
+ }
40482
+ if (create && response.status !== 201)
40483
+ return invalid4();
40484
+ return body;
40485
+ })(), new Promise((_, reject) => {
40486
+ abort = () => {
40487
+ controller.abort();
40488
+ reject(timeout2);
40489
+ };
40490
+ timer = setTimeout(abort, Math.max(1, Math.min(15000, budget3)));
40491
+ signal?.addEventListener("abort", abort, { once: true });
40492
+ })]);
40493
+ } catch (error61) {
40494
+ if (error61 instanceof PrivatePublicationError) {
40495
+ if (mutation && error61.code === "INVALID_PUBLICATION_RESPONSE")
40496
+ throw timeout2;
40497
+ throw error61;
40498
+ }
40499
+ throw timeout2;
40500
+ } finally {
40501
+ if (timer)
40502
+ clearTimeout(timer);
40503
+ if (abort)
40504
+ signal?.removeEventListener("abort", abort);
40505
+ controller.abort();
40506
+ if (reader)
40507
+ reader.cancel().catch(() => {});
40508
+ else
40509
+ response?.body?.cancel().catch(() => {});
40510
+ }
40511
+ }
40512
+
40513
+ class RemotePrivatePublicationsClient {
40514
+ apiOrigin;
40515
+ organizationId;
40516
+ userId;
40517
+ membershipId;
40518
+ #token;
40519
+ constructor(apiUrl, session) {
40520
+ const checked = parseWorkspaceSession(session, { userId: session?.user?.id, membershipId: session?.user?.membershipId });
40521
+ if (checked.user.role === "viewer")
40522
+ throw new PrivatePublicationError("PUBLICATION_FORBIDDEN", failures2.PUBLICATION_FORBIDDEN[1]);
40523
+ this.apiOrigin = normalizeSkillsApiOrigin(apiUrl);
40524
+ this.#token = checked.token;
40525
+ this.organizationId = checked.organization.id;
40526
+ this.userId = checked.user.id;
40527
+ this.membershipId = checked.user.membershipId;
40528
+ Object.freeze(this);
40529
+ }
40530
+ async createSkill(input2, options = {}) {
40531
+ const body = checkedPrivateSkillCreate(input2);
40532
+ if (options.timeoutMs !== undefined && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 15000))
40533
+ throw new PrivatePublicationError("INVALID_SKILL_CREATE_INPUT", "Invalid timeoutMs. Use an integer from 1 to 15000.");
40534
+ const value = await boundedJson(skillsApiRequestUrl(this.apiOrigin, "/api/v1/skills"), { method: "POST", body: JSON.stringify(body) }, this.#token, true, options.timeoutMs, options.signal, true);
40535
+ 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)
40536
+ 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);
40537
+ return Object.freeze({ id: value.id, slug: body.slug, visibility: body.visibility, sourceType: "private_hosted", ownerOrganizationId: this.organizationId });
40538
+ }
40539
+ async getCapability(options = {}) {
40540
+ if (options.timeoutMs !== undefined && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 15000))
40541
+ return bad();
40542
+ const response = await boundedJson(skillsApiRequestUrl(this.apiOrigin, "/api/v1/capabilities"), {}, this.#token, false, options.timeoutMs, options.signal);
40543
+ const p = record11(response) && response.privatePublishing;
40544
+ 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")
40545
+ throw new PrivatePublicationError("PUBLICATION_CONTRACT_UNAVAILABLE", "This server does not support the hosted private publication contract.");
40546
+ return Object.freeze({ ...p });
40547
+ }
40548
+ async#gate(enabled, options = {}) {
40549
+ if (!(await this.getCapability(options)).enabled && enabled)
40550
+ throw new PrivatePublicationError("PUBLICATION_CAPABILITY_UNAVAILABLE", failures2.PUBLICATION_CAPABILITY_UNAVAILABLE[1]);
40551
+ }
40552
+ #path(skillId, intentId) {
40553
+ if (!publicationUuid(skillId) || intentId !== undefined && !publicationUuid(intentId))
40554
+ return bad();
40555
+ return skillsApiRequestUrl(this.apiOrigin, `/api/v1/skills/${skillId}/publication-uploads${intentId ? `/${intentId}` : ""}`);
40556
+ }
40557
+ async#view(path, method, skillId, intentId, declaration, options = {}) {
40558
+ const value = await boundedJson(path, { method, ...method === "GET" ? {} : { body: JSON.stringify(declaration ?? {}) } }, this.#token, method !== "GET", options.timeoutMs, options.signal);
40559
+ try {
40560
+ if (!record11(value) || !Object.keys(value).every((k) => k === "upload" || k === "changed") || value.changed !== undefined && typeof value.changed !== "boolean")
40561
+ return invalid4();
40562
+ return checkedPublicationView(value.upload, skillId, intentId, declaration);
40563
+ } catch (error61) {
40564
+ if (method !== "GET")
40565
+ throw new PrivatePublicationError("PUBLICATION_UNCONFIRMED", "The publication result could not be confirmed. Reconcile the saved intent before another action.", true);
40566
+ throw error61;
40567
+ }
40568
+ }
40569
+ async begin(skillId, input2) {
40570
+ const path = this.#path(skillId), declaration = checkedPublicationDeclaration(input2);
40571
+ await this.#gate(true);
40572
+ return this.#view(path, "POST", skillId, undefined, declaration);
40573
+ }
40574
+ async get(skillId, intentId, options = {}) {
40575
+ const path = this.#path(skillId, intentId), until = Date.now() + (options.timeoutMs ?? 15000);
40576
+ await this.#gate(false, options);
40577
+ return this.#view(path, "GET", skillId, intentId, undefined, { ...options, timeoutMs: Math.max(1, until - Date.now()) });
40578
+ }
40579
+ async finalize(skillId, intentId) {
40580
+ const path = this.#path(skillId, intentId);
40581
+ await this.#gate(true);
40582
+ return this.#view(`${path}/finalize`, "POST", skillId, intentId);
40583
+ }
40584
+ async cancel(skillId, intentId) {
40585
+ const path = this.#path(skillId, intentId);
40586
+ await this.#gate(false);
40587
+ return this.#view(path, "DELETE", skillId, intentId);
40588
+ }
40589
+ async upload(skillId, intent, bytes) {
40590
+ const captured = checkedPublicationView(intent, skillId), path = this.#path(skillId, captured.id);
40591
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength !== captured.archiveByteSize)
40592
+ return bad();
40593
+ const owned = Buffer.from(bytes);
40594
+ if (captured.state !== "awaiting_upload" || owned.byteLength !== captured.archiveByteSize || publicationSha256(owned) !== captured.archiveSha256)
40595
+ return bad();
40596
+ await this.#gate(true);
40597
+ const value = await boundedJson(`${path}/upload-url`, { method: "POST", body: "{}" }, this.#token, false);
40598
+ const upload = this.#upload(value, captured);
40599
+ const controller = new AbortController;
40600
+ let timer;
40601
+ 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);
40602
+ try {
40603
+ await Promise.race([(async () => {
40604
+ const response = await fetch(upload.uploadUrl, { method: "PUT", headers: upload.headers, body: owned, redirect: "error", credentials: "omit", signal: controller.signal });
40605
+ response.body?.cancel().catch(() => {});
40606
+ if (response.status !== 200 || controller.signal.aborted)
40607
+ throw uncertain();
40608
+ })(), new Promise((_, reject) => {
40609
+ timer = setTimeout(() => {
40610
+ controller.abort();
40611
+ reject(uncertain());
40612
+ }, 30000);
40613
+ })]);
40614
+ } catch {
40615
+ throw uncertain();
40616
+ } finally {
40617
+ if (timer)
40618
+ clearTimeout(timer);
40619
+ controller.abort();
40620
+ }
40621
+ }
40622
+ #upload(value, intent) {
40623
+ if (!exact(value, ["upload"]) || !exact(value.upload, ["method", "uploadUrl", "headers", "expiresAt"]))
40624
+ return invalid4();
40625
+ const p = value.upload;
40626
+ 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"]))
40627
+ return invalid4();
40628
+ let url2;
40629
+ try {
40630
+ url2 = new URL(p.uploadUrl);
40631
+ } catch {
40632
+ return invalid4();
40633
+ }
40634
+ 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") ?? ""))
40635
+ return invalid4();
40636
+ const queryKeys = ["X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date", "X-Amz-Expires", "X-Amz-Security-Token", "X-Amz-Signature", "X-Amz-SignedHeaders"];
40637
+ if ([...url2.searchParams.keys()].sort().join(",") !== queryKeys.sort().join(","))
40638
+ return invalid4();
40639
+ const issued = url2.searchParams.get("X-Amz-Date"), ttl = url2.searchParams.get("X-Amz-Expires"), credential = url2.searchParams.get("X-Amz-Credential");
40640
+ const timestamp3 = /^(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)Z$/.exec(issued);
40641
+ const region = url2.hostname.split(".s3.")[1].split(".amazonaws.com")[0];
40642
+ 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")))
40643
+ return invalid4();
40644
+ const issuedAt = Date.parse(`${timestamp3[1]}-${timestamp3[2]}-${timestamp3[3]}T${timestamp3[4]}:${timestamp3[5]}:${timestamp3[6]}Z`);
40645
+ if (!Number.isFinite(issuedAt) || issuedAt > Date.now() + 1000 || issuedAt + Number(ttl) * 1000 !== Date.parse(p.expiresAt))
40646
+ return invalid4();
40647
+ return { method: "PUT", uploadUrl: url2.href, expiresAt: p.expiresAt, headers: Object.freeze({ ...p.headers }) };
40648
+ }
40649
+ async wait(skillId, intentId, options = {}) {
40650
+ const timeout2 = options.timeoutMs ?? 60000;
40651
+ if (!Number.isSafeInteger(timeout2) || timeout2 < 0 || timeout2 > 300000)
40652
+ return bad();
40653
+ const until = Date.now() + timeout2;
40654
+ let previous;
40655
+ while (true) {
40656
+ if (options.signal?.aborted)
40657
+ throw new PrivatePublicationError("PUBLICATION_WAIT_ABORTED", "Stopped waiting. The server publication continues; inspect the saved intent.");
40658
+ let view;
40659
+ try {
40660
+ view = await this.get(skillId, intentId, { timeoutMs: timeout2 === 0 ? 15000 : Math.max(1, Math.min(15000, until - Date.now())), signal: options.signal });
40661
+ } catch (error61) {
40662
+ if (previous && Date.now() >= until && !options.signal?.aborted)
40663
+ return previous;
40664
+ throw error61;
40665
+ }
40666
+ previous = view;
40667
+ if (!["queued", "verifying"].includes(view.state) || Date.now() >= until)
40668
+ return view;
40669
+ await new Promise((resolve30) => {
40670
+ const timer = setTimeout(done, Math.min(1000, until - Date.now()));
40671
+ function done() {
40672
+ clearTimeout(timer);
40673
+ options.signal?.removeEventListener("abort", done);
40674
+ resolve30();
40675
+ }
40676
+ options.signal?.addEventListener("abort", done, { once: true });
40677
+ });
40678
+ }
40679
+ }
40680
+ }
39823
40681
  var uuid12 = exports_external.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/);
39824
40682
  var sha6 = exports_external.string().regex(/^[a-f0-9]{64}$/);
39825
40683
  var common = exports_external.object({
@@ -41099,14 +41957,14 @@ function coordinateClaudeSettings(before, replacement, options, beforeWrite) {
41099
41957
 
41100
41958
  // src/lib/target-adapters.ts
41101
41959
  import { spawnSync } from "child_process";
41102
- import { chmodSync as chmodSync2, existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync8, readdirSync as readdirSync4, rmdirSync as rmdirSync2, statSync, unlinkSync as unlinkSync3, writeFileSync as writeFileSync9, renameSync as renameSync5 } from "fs";
41960
+ 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";
41103
41961
  import { tmpdir } from "os";
41104
41962
  import { basename as basename9, dirname as dirname9, join as join22 } from "path";
41105
41963
  import { randomUUID as randomUUID5 } from "crypto";
41106
41964
 
41107
41965
  // src/lib/profiles.ts
41108
41966
  init_app_home();
41109
- import { existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync7, readdirSync as readdirSync3, rmSync as rmSync3, cpSync as cpSync2 } from "fs";
41967
+ import { existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync7, readdirSync as readdirSync4, rmSync as rmSync3, cpSync as cpSync2 } from "fs";
41110
41968
  import { join as join20 } from "path";
41111
41969
  function getProfilesDir() {
41112
41970
  const newDir = join20(getEffectiveDataRoot(), "profiles");
@@ -41162,7 +42020,7 @@ function listProfiles() {
41162
42020
  if (!existsSync12(dir))
41163
42021
  return [];
41164
42022
  try {
41165
- const files = readdirSync3(dir).filter((f) => f.endsWith(".json"));
42023
+ const files = readdirSync4(dir).filter((f) => f.endsWith(".json"));
41166
42024
  const profiles = [];
41167
42025
  for (const file2 of files) {
41168
42026
  try {
@@ -41221,8 +42079,8 @@ function adapterPath(target, options, hook) {
41221
42079
  throw new Error(`No capability record for target '${target}'`);
41222
42080
  return capabilities.configPath;
41223
42081
  }
41224
- function redactedDiagnostic(text2) {
41225
- const line = (text2.split(`
42082
+ function redactedDiagnostic(text3) {
42083
+ const line = (text3.split(`
41226
42084
  `).find((entry) => entry.trim()) ?? "").trim();
41227
42085
  return line.slice(0, 300).replace(/[A-Za-z0-9_\-]{24,}/g, "<redacted>");
41228
42086
  }
@@ -41233,16 +42091,16 @@ function messageOf(error61) {
41233
42091
  return error61 instanceof Error ? error61.message : String(error61);
41234
42092
  }
41235
42093
  function readJsonObject(path) {
41236
- let text2;
42094
+ let text3;
41237
42095
  try {
41238
- text2 = readFileSync8(path, "utf-8");
42096
+ text3 = readFileSync8(path, "utf-8");
41239
42097
  } catch (error61) {
41240
42098
  if (error61?.code === "ENOENT")
41241
42099
  return { status: "absent" };
41242
42100
  return { status: "unreadable", kind: "file", reason: `cannot read ${path} (${redactedDiagnostic(messageOf(error61))})` };
41243
42101
  }
41244
42102
  try {
41245
- const value = JSON.parse(text2);
42103
+ const value = JSON.parse(text3);
41246
42104
  if (!value || typeof value !== "object" || Array.isArray(value)) {
41247
42105
  return { status: "unreadable", kind: "content", reason: `${path} is not a JSON object` };
41248
42106
  }
@@ -41276,11 +42134,11 @@ function tomlStringValue(raw) {
41276
42134
  }
41277
42135
  var TOML_HEADER_RE = /^\s*\[\[?[^\]]/;
41278
42136
  var KIMI_HOOK_HEADER_RE = /^\s*\[\[hooks\]\]\s*$/;
41279
- function splitToml(text2) {
42137
+ function splitToml(text3) {
41280
42138
  const preamble = [];
41281
42139
  const chunks = [];
41282
42140
  let current2 = null;
41283
- for (const line of text2.split(`
42141
+ for (const line of text3.split(`
41284
42142
  `)) {
41285
42143
  if (TOML_HEADER_RE.test(line)) {
41286
42144
  if (current2)
@@ -41297,20 +42155,20 @@ function splitToml(text2) {
41297
42155
  return { preamble, chunks };
41298
42156
  }
41299
42157
  function chunkCommand(chunk) {
41300
- const text2 = chunk.lines.join(`
42158
+ const text3 = chunk.lines.join(`
41301
42159
  `);
41302
- const basic = text2.match(/^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/m);
42160
+ const basic = text3.match(/^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/m);
41303
42161
  if (basic)
41304
42162
  return tomlStringValue(basic[1]);
41305
- const literal2 = text2.match(/^\s*command\s*=\s*'([^']*)'/m);
42163
+ const literal2 = text3.match(/^\s*command\s*=\s*'([^']*)'/m);
41306
42164
  return literal2 ? literal2[1] : undefined;
41307
42165
  }
41308
42166
  function isKimiHookChunk(chunk) {
41309
42167
  return KIMI_HOOK_HEADER_RE.test(chunk.header);
41310
42168
  }
41311
- function kimiRegistrations(text2) {
42169
+ function kimiRegistrations(text3) {
41312
42170
  const out = [];
41313
- for (const chunk of splitToml(text2).chunks) {
42171
+ for (const chunk of splitToml(text3).chunks) {
41314
42172
  if (!isKimiHookChunk(chunk))
41315
42173
  continue;
41316
42174
  const command = chunkCommand(chunk);
@@ -41329,8 +42187,8 @@ function kimiBlock(command, timeoutSeconds) {
41329
42187
  ].join(`
41330
42188
  `);
41331
42189
  }
41332
- function removeKimiChunk(text2, hook) {
41333
- const { preamble, chunks } = splitToml(text2);
42190
+ function removeKimiChunk(text3, hook) {
42191
+ const { preamble, chunks } = splitToml(text3);
41334
42192
  const kept = [...preamble];
41335
42193
  let removed = false;
41336
42194
  for (const chunk of chunks) {
@@ -41545,7 +42403,7 @@ function museBundles(options) {
41545
42403
  if (!existsSync13(root))
41546
42404
  return [];
41547
42405
  const out = [];
41548
- for (const entry of readdirSync4(root)) {
42406
+ for (const entry of readdirSync8(root)) {
41549
42407
  const manifestPath = join22(root, entry, ".muse-plugin", "plugin.json");
41550
42408
  if (!existsSync13(manifestPath))
41551
42409
  continue;
@@ -41769,11 +42627,11 @@ function removeFromAdapter(target, hook, options) {
41769
42627
  if (existing.status === "unreadable") {
41770
42628
  return { removed: false, reason: `${existing.reason}, so Hooks cannot tell whether '${hook}' is registered; nothing was removed` };
41771
42629
  }
41772
- const { text: text2, removed } = removeKimiChunk(existing.status === "verified" ? existing.text : "", hook);
42630
+ const { text: text3, removed } = removeKimiChunk(existing.status === "verified" ? existing.text : "", hook);
41773
42631
  if (!removed)
41774
42632
  return { removed: false, reason: `no '${hook}' entry in ${path}` };
41775
- writeText(path, text2.endsWith(`
41776
- `) ? text2 : `${text2}
42633
+ writeText(path, text3.endsWith(`
42634
+ `) ? text3 : `${text3}
41777
42635
  `);
41778
42636
  return { removed: true };
41779
42637
  }
@@ -41971,13 +42829,13 @@ function readSettings(scope = "global", target = "claude") {
41971
42829
  let reason2 = "cannot be read";
41972
42830
  try {
41973
42831
  if (existsSync14(path)) {
41974
- const text2 = readFileSync13(path, "utf-8");
42832
+ const text3 = readFileSync13(path, "utf-8");
41975
42833
  reason2 = "is not valid JSON";
41976
- const value = JSON.parse(text2);
42834
+ const value = JSON.parse(text3);
41977
42835
  reason2 = "does not hold a JSON object";
41978
42836
  if (!value || typeof value !== "object" || Array.isArray(value))
41979
42837
  throw new TypeError(reason2);
41980
- settingsPreimages.set(value, { path, text: text2 });
42838
+ settingsPreimages.set(value, { path, text: text3 });
41981
42839
  return value;
41982
42840
  }
41983
42841
  } catch (error61) {
@@ -43230,10 +44088,10 @@ function settingsChangeError(hook, scope, error61, code2) {
43230
44088
  };
43231
44089
  }
43232
44090
  function truncateText(value, max = 160) {
43233
- const text2 = String(value ?? "").replace(/\s+/g, " ").trim();
43234
- if (text2.length <= max)
43235
- return text2;
43236
- return `${text2.slice(0, Math.max(0, max - 3))}...`;
44091
+ const text3 = String(value ?? "").replace(/\s+/g, " ").trim();
44092
+ if (text3.length <= max)
44093
+ return text3;
44094
+ return `${text3.slice(0, Math.max(0, max - 3))}...`;
43237
44095
  }
43238
44096
  function boundedLimit(value, fallback, max) {
43239
44097
  if (!Number.isFinite(value) || !value || value <= 0)