@promptframe/creation 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -407,11 +407,11 @@ var require_codegen = __commonJS({
407
407
  const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
408
408
  return `${varKind} ${this.name}${rhs};` + _n2;
409
409
  }
410
- optimizeNames(names, constants4) {
410
+ optimizeNames(names, constants6) {
411
411
  if (!names[this.name.str])
412
412
  return;
413
413
  if (this.rhs)
414
- this.rhs = optimizeExpr(this.rhs, names, constants4);
414
+ this.rhs = optimizeExpr(this.rhs, names, constants6);
415
415
  return this;
416
416
  }
417
417
  get names() {
@@ -428,10 +428,10 @@ var require_codegen = __commonJS({
428
428
  render({ _n: _n2 }) {
429
429
  return `${this.lhs} = ${this.rhs};` + _n2;
430
430
  }
431
- optimizeNames(names, constants4) {
431
+ optimizeNames(names, constants6) {
432
432
  if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
433
433
  return;
434
- this.rhs = optimizeExpr(this.rhs, names, constants4);
434
+ this.rhs = optimizeExpr(this.rhs, names, constants6);
435
435
  return this;
436
436
  }
437
437
  get names() {
@@ -492,8 +492,8 @@ var require_codegen = __commonJS({
492
492
  optimizeNodes() {
493
493
  return `${this.code}` ? this : void 0;
494
494
  }
495
- optimizeNames(names, constants4) {
496
- this.code = optimizeExpr(this.code, names, constants4);
495
+ optimizeNames(names, constants6) {
496
+ this.code = optimizeExpr(this.code, names, constants6);
497
497
  return this;
498
498
  }
499
499
  get names() {
@@ -522,12 +522,12 @@ var require_codegen = __commonJS({
522
522
  }
523
523
  return nodes.length > 0 ? this : void 0;
524
524
  }
525
- optimizeNames(names, constants4) {
525
+ optimizeNames(names, constants6) {
526
526
  const { nodes } = this;
527
527
  let i = nodes.length;
528
528
  while (i--) {
529
529
  const n = nodes[i];
530
- if (n.optimizeNames(names, constants4))
530
+ if (n.optimizeNames(names, constants6))
531
531
  continue;
532
532
  subtractNames(names, n.names);
533
533
  nodes.splice(i, 1);
@@ -580,12 +580,12 @@ var require_codegen = __commonJS({
580
580
  return void 0;
581
581
  return this;
582
582
  }
583
- optimizeNames(names, constants4) {
583
+ optimizeNames(names, constants6) {
584
584
  var _a3;
585
- this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants4);
586
- if (!(super.optimizeNames(names, constants4) || this.else))
585
+ this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants6);
586
+ if (!(super.optimizeNames(names, constants6) || this.else))
587
587
  return;
588
- this.condition = optimizeExpr(this.condition, names, constants4);
588
+ this.condition = optimizeExpr(this.condition, names, constants6);
589
589
  return this;
590
590
  }
591
591
  get names() {
@@ -608,10 +608,10 @@ var require_codegen = __commonJS({
608
608
  render(opts) {
609
609
  return `for(${this.iteration})` + super.render(opts);
610
610
  }
611
- optimizeNames(names, constants4) {
612
- if (!super.optimizeNames(names, constants4))
611
+ optimizeNames(names, constants6) {
612
+ if (!super.optimizeNames(names, constants6))
613
613
  return;
614
- this.iteration = optimizeExpr(this.iteration, names, constants4);
614
+ this.iteration = optimizeExpr(this.iteration, names, constants6);
615
615
  return this;
616
616
  }
617
617
  get names() {
@@ -647,10 +647,10 @@ var require_codegen = __commonJS({
647
647
  render(opts) {
648
648
  return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
649
649
  }
650
- optimizeNames(names, constants4) {
651
- if (!super.optimizeNames(names, constants4))
650
+ optimizeNames(names, constants6) {
651
+ if (!super.optimizeNames(names, constants6))
652
652
  return;
653
- this.iterable = optimizeExpr(this.iterable, names, constants4);
653
+ this.iterable = optimizeExpr(this.iterable, names, constants6);
654
654
  return this;
655
655
  }
656
656
  get names() {
@@ -692,11 +692,11 @@ var require_codegen = __commonJS({
692
692
  (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
693
693
  return this;
694
694
  }
695
- optimizeNames(names, constants4) {
695
+ optimizeNames(names, constants6) {
696
696
  var _a3, _b;
697
- super.optimizeNames(names, constants4);
698
- (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants4);
699
- (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants4);
697
+ super.optimizeNames(names, constants6);
698
+ (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants6);
699
+ (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants6);
700
700
  return this;
701
701
  }
702
702
  get names() {
@@ -997,7 +997,7 @@ var require_codegen = __commonJS({
997
997
  function addExprNames(names, from) {
998
998
  return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
999
999
  }
1000
- function optimizeExpr(expr, names, constants4) {
1000
+ function optimizeExpr(expr, names, constants6) {
1001
1001
  if (expr instanceof code_1.Name)
1002
1002
  return replaceName(expr);
1003
1003
  if (!canOptimize(expr))
@@ -1012,14 +1012,14 @@ var require_codegen = __commonJS({
1012
1012
  return items;
1013
1013
  }, []));
1014
1014
  function replaceName(n) {
1015
- const c = constants4[n.str];
1015
+ const c = constants6[n.str];
1016
1016
  if (c === void 0 || names[n.str] !== 1)
1017
1017
  return n;
1018
1018
  delete names[n.str];
1019
1019
  return c;
1020
1020
  }
1021
1021
  function canOptimize(e) {
1022
- return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants4[c.str] !== void 0);
1022
+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants6[c.str] !== void 0);
1023
1023
  }
1024
1024
  }
1025
1025
  function subtractNames(names, from) {
@@ -2041,7 +2041,7 @@ var require_subschema = __commonJS({
2041
2041
  var require_fast_deep_equal = __commonJS({
2042
2042
  "node_modules/fast-deep-equal/index.js"(exports, module) {
2043
2043
  "use strict";
2044
- module.exports = function equal(a, b2) {
2044
+ module.exports = function equal2(a, b2) {
2045
2045
  if (a === b2) return true;
2046
2046
  if (a && b2 && typeof a == "object" && typeof b2 == "object") {
2047
2047
  if (a.constructor !== b2.constructor) return false;
@@ -2050,7 +2050,7 @@ var require_fast_deep_equal = __commonJS({
2050
2050
  length = a.length;
2051
2051
  if (length != b2.length) return false;
2052
2052
  for (i = length; i-- !== 0; )
2053
- if (!equal(a[i], b2[i])) return false;
2053
+ if (!equal2(a[i], b2[i])) return false;
2054
2054
  return true;
2055
2055
  }
2056
2056
  if (a.constructor === RegExp) return a.source === b2.source && a.flags === b2.flags;
@@ -2063,7 +2063,7 @@ var require_fast_deep_equal = __commonJS({
2063
2063
  if (!Object.prototype.hasOwnProperty.call(b2, keys[i])) return false;
2064
2064
  for (i = length; i-- !== 0; ) {
2065
2065
  var key = keys[i];
2066
- if (!equal(a[key], b2[key])) return false;
2066
+ if (!equal2(a[key], b2[key])) return false;
2067
2067
  }
2068
2068
  return true;
2069
2069
  }
@@ -2167,7 +2167,7 @@ var require_resolve = __commonJS({
2167
2167
  Object.defineProperty(exports, "__esModule", { value: true });
2168
2168
  exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
2169
2169
  var util_1 = require_util();
2170
- var equal = require_fast_deep_equal();
2170
+ var equal2 = require_fast_deep_equal();
2171
2171
  var traverse = require_json_schema_traverse();
2172
2172
  var SIMPLE_INLINED = /* @__PURE__ */ new Set([
2173
2173
  "type",
@@ -2305,7 +2305,7 @@ var require_resolve = __commonJS({
2305
2305
  });
2306
2306
  return localRefs;
2307
2307
  function checkAmbiguosRef(sch1, sch2, ref) {
2308
- if (sch2 !== void 0 && !equal(sch1, sch2))
2308
+ if (sch2 !== void 0 && !equal2(sch1, sch2))
2309
2309
  throw ambiguos(ref);
2310
2310
  }
2311
2311
  function ambiguos(ref) {
@@ -3259,8 +3259,8 @@ var require_utils = __commonJS({
3259
3259
  }
3260
3260
  return ind;
3261
3261
  }
3262
- function removeDotSegments(path14) {
3263
- let input = path14;
3262
+ function removeDotSegments(path17) {
3263
+ let input = path17;
3264
3264
  const output = [];
3265
3265
  let nextSlash = -1;
3266
3266
  let len = 0;
@@ -3669,8 +3669,8 @@ var require_schemes = __commonJS({
3669
3669
  }
3670
3670
  if (wsComponent.resourceName) {
3671
3671
  const queryIndex = wsComponent.resourceName.indexOf("?");
3672
- const path14 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
3673
- wsComponent.path = path14 && path14 !== "/" ? path14 : void 0;
3672
+ const path17 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
3673
+ wsComponent.path = path17 && path17 !== "/" ? path17 : void 0;
3674
3674
  wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
3675
3675
  wsComponent.resourceName = void 0;
3676
3676
  }
@@ -3924,7 +3924,7 @@ var require_fast_uri = __commonJS({
3924
3924
  target.fragment = relative.fragment;
3925
3925
  return target;
3926
3926
  }
3927
- function equal(uriA, uriB, options) {
3927
+ function equal2(uriA, uriB, options) {
3928
3928
  const normalizedA = normalizeComparableURI(uriA, options);
3929
3929
  const normalizedB = normalizeComparableURI(uriB, options);
3930
3930
  return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA === normalizedB;
@@ -4209,7 +4209,7 @@ var require_fast_uri = __commonJS({
4209
4209
  normalize,
4210
4210
  resolve,
4211
4211
  resolveComponent,
4212
- equal,
4212
+ equal: equal2,
4213
4213
  serialize,
4214
4214
  parse: parse4
4215
4215
  };
@@ -4269,7 +4269,7 @@ var require_core = __commonJS({
4269
4269
  var util_1 = require_util();
4270
4270
  var $dataRefSchema = require_data();
4271
4271
  var uri_1 = require_uri();
4272
- var defaultRegExp = (str, flags) => new RegExp(str, flags);
4272
+ var defaultRegExp = (str, flags2) => new RegExp(str, flags2);
4273
4273
  defaultRegExp.code = "new RegExp";
4274
4274
  var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
4275
4275
  var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
@@ -5299,9 +5299,9 @@ var require_equal = __commonJS({
5299
5299
  "node_modules/ajv/dist/runtime/equal.js"(exports) {
5300
5300
  "use strict";
5301
5301
  Object.defineProperty(exports, "__esModule", { value: true });
5302
- var equal = require_fast_deep_equal();
5303
- equal.code = 'require("ajv/dist/runtime/equal").default';
5304
- exports.default = equal;
5302
+ var equal2 = require_fast_deep_equal();
5303
+ equal2.code = 'require("ajv/dist/runtime/equal").default';
5304
+ exports.default = equal2;
5305
5305
  }
5306
5306
  });
5307
5307
 
@@ -7300,12 +7300,969 @@ var require_content_type = __commonJS({
7300
7300
  }
7301
7301
  });
7302
7302
 
7303
+ // lib/local-upload.mjs
7304
+ import { createHash as createHash2 } from "node:crypto";
7305
+ import { hostname, platform } from "node:os";
7306
+ import path4 from "node:path";
7307
+
7308
+ // lib/credentials.mjs
7309
+ import {
7310
+ lstat,
7311
+ mkdir,
7312
+ readFile,
7313
+ writeFile,
7314
+ rename,
7315
+ unlink
7316
+ } from "node:fs/promises";
7317
+ import { homedir } from "node:os";
7318
+ import path from "node:path";
7319
+ import { randomBytes } from "node:crypto";
7320
+ var CreationClientError = class extends Error {
7321
+ constructor(code) {
7322
+ super(code);
7323
+ this.name = "CreationClientError";
7324
+ }
7325
+ };
7326
+ function credentialsPath(env = process.env) {
7327
+ return path.resolve(
7328
+ env.PROMPTFRAME_CREATION_CONFIG ?? path.join(
7329
+ env.XDG_CONFIG_HOME ?? path.join(homedir(), ".config"),
7330
+ "promptframe-creation",
7331
+ "credentials.json"
7332
+ )
7333
+ );
7334
+ }
7335
+ function normalizeEndpoint(input) {
7336
+ let url2;
7337
+ try {
7338
+ url2 = new URL(input);
7339
+ } catch {
7340
+ throw new CreationClientError("endpoint.invalid");
7341
+ }
7342
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url2.hostname);
7343
+ if (url2.username || url2.password || url2.search || url2.hash || url2.protocol !== "https:" && !(loopback && url2.protocol === "http:"))
7344
+ throw new CreationClientError("endpoint.https_or_loopback_required");
7345
+ const base = url2.href.replace(/\/+$/, "");
7346
+ if (base.endsWith("/api/mcp")) return base;
7347
+ if (base.endsWith("/api")) return base + "/mcp";
7348
+ throw new CreationClientError("endpoint.api_base_required");
7349
+ }
7350
+ var secure = async (file, directory2 = false) => {
7351
+ let info5;
7352
+ try {
7353
+ info5 = await lstat(file);
7354
+ } catch (error4) {
7355
+ if (error4.code === "ENOENT") return null;
7356
+ throw error4;
7357
+ }
7358
+ if (info5.isSymbolicLink() || !(directory2 ? info5.isDirectory() : info5.isFile()) || info5.uid !== process.getuid?.() || (info5.mode & 63) !== 0)
7359
+ throw new CreationClientError("credentials.private_owner_required");
7360
+ return info5;
7361
+ };
7362
+ async function readCredentials(file = credentialsPath()) {
7363
+ if (!await secure(file)) return null;
7364
+ if (!await secure(path.dirname(file), true))
7365
+ throw new CreationClientError("credentials.private_owner_required");
7366
+ let value2;
7367
+ try {
7368
+ value2 = JSON.parse(await readFile(file, "utf8"));
7369
+ } catch {
7370
+ throw new CreationClientError("credentials.invalid");
7371
+ }
7372
+ if (value2.version !== 1 || typeof value2.token !== "string" || !/^pf_create_[A-Za-z0-9_-]{43}$/.test(value2.token) || typeof value2.clientId !== "string" || !/^[A-Za-z0-9_-]{16,128}$/.test(value2.clientId) || typeof value2.clientName !== "string" || !value2.clientName.trim() || value2.clientName.length > 160 || /[\x00-\x1f\x7f]/.test(value2.clientName))
7373
+ throw new CreationClientError("credentials.invalid");
7374
+ return { ...value2, endpoint: normalizeEndpoint(value2.endpoint) };
7375
+ }
7376
+ async function writeCredentials(value2, file = credentialsPath()) {
7377
+ const directory2 = path.dirname(file);
7378
+ await mkdir(directory2, { recursive: true, mode: 448 });
7379
+ await secure(directory2, true);
7380
+ await secure(file);
7381
+ const temporary = file + "." + randomBytes(12).toString("hex") + ".tmp";
7382
+ try {
7383
+ await writeFile(temporary, JSON.stringify(value2) + "\n", {
7384
+ flag: "wx",
7385
+ mode: 384
7386
+ });
7387
+ await rename(temporary, file);
7388
+ } finally {
7389
+ await unlink(temporary).catch((error4) => {
7390
+ if (error4.code !== "ENOENT") throw error4;
7391
+ });
7392
+ }
7393
+ }
7394
+
7395
+ // lib/local-upload-file.mjs
7396
+ import { constants } from "node:fs";
7397
+ import { open, lstat as lstat2 } from "node:fs/promises";
7398
+ import { createHash } from "node:crypto";
7399
+ import path2 from "node:path";
7400
+ import { Readable } from "node:stream";
7401
+ import { finished } from "node:stream/promises";
7402
+ var LOCAL_UPLOAD_MAX_BYTES = 2 * 1024 ** 3;
7403
+ var LOCAL_UPLOAD_READ_BYTES = 64 * 1024;
7404
+ var fingerprint = (stat2) => ({
7405
+ dev: String(stat2.dev),
7406
+ ino: String(stat2.ino),
7407
+ sizeBytes: Number(stat2.size),
7408
+ mtimeNs: String(stat2.mtimeNs),
7409
+ ctimeNs: String(stat2.ctimeNs)
7410
+ });
7411
+ var equal = (left, right) => Object.keys(left).every((key) => left[key] === right[key]);
7412
+ var failure = (code) => new CreationClientError("creation.local_upload." + code);
7413
+ async function openLocalUploadFile(selectedPath, { maxBytes: maxBytes2 = LOCAL_UPLOAD_MAX_BYTES, signal, deadlineAtMs = Infinity, now = Date.now } = {}) {
7414
+ if (typeof selectedPath !== "string" || !selectedPath || selectedPath.includes("\0") || !Number.isSafeInteger(maxBytes2) || maxBytes2 < 1 || maxBytes2 > LOCAL_UPLOAD_MAX_BYTES)
7415
+ throw failure("file_selection_invalid");
7416
+ if (process.platform !== "win32" && /^(?:[a-z]:[\\/]|\\\\)/i.test(selectedPath))
7417
+ throw failure("path_not_on_bridge_host");
7418
+ const selected = path2.resolve(selectedPath), name = path2.basename(selected);
7419
+ if (name.length > 512 || /[\x00-\x1f\x7f]/.test(name)) throw failure("file_selection_invalid");
7420
+ let handle;
7421
+ try {
7422
+ handle = await open(selected, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
7423
+ } catch (error4) {
7424
+ throw failure(error4.code === "ELOOP" ? "file_not_regular" : error4.code === "EACCES" || error4.code === "EPERM" ? "file_read_denied" : "file_not_on_bridge_host");
7425
+ }
7426
+ const abort = new AbortController(), streams = /* @__PURE__ */ new Map(), reads = /* @__PURE__ */ new Set();
7427
+ let closing = false, closed = false, original, closePromise;
7428
+ const checkSignal = (other) => {
7429
+ if (closing || closed) throw failure("file_closed");
7430
+ if (signal?.aborted || other?.aborted || abort.signal.aborted) throw failure("file_read_cancelled");
7431
+ if (now() >= deadlineAtMs) throw failure("file_read_timeout");
7432
+ };
7433
+ const read2 = async (buffer, offset, length, position) => {
7434
+ const pending = handle.read(buffer, offset, length, position);
7435
+ reads.add(pending);
7436
+ try {
7437
+ return await pending;
7438
+ } catch {
7439
+ throw failure("file_read_failed");
7440
+ } finally {
7441
+ reads.delete(pending);
7442
+ }
7443
+ };
7444
+ const assertUnchanged = async () => {
7445
+ checkSignal();
7446
+ try {
7447
+ const [current, named] = await Promise.all([handle.stat({ bigint: true }), lstat2(selected, { bigint: true })]);
7448
+ if (!current.isFile() || !named.isFile() || !equal(original, fingerprint(current)) || !equal(original, fingerprint(named))) throw failure("file_changed");
7449
+ } catch (error4) {
7450
+ if (error4 instanceof CreationClientError) throw error4;
7451
+ throw failure("file_changed");
7452
+ }
7453
+ };
7454
+ const close = () => closePromise ??= (async () => {
7455
+ closing = true;
7456
+ abort.abort();
7457
+ for (const stream of streams.keys()) stream.destroy(failure("file_read_cancelled"));
7458
+ await Promise.allSettled([...streams.values(), ...reads]);
7459
+ await handle.close();
7460
+ closed = true;
7461
+ })();
7462
+ try {
7463
+ checkSignal();
7464
+ const stat2 = await handle.stat({ bigint: true });
7465
+ if (!stat2.isFile()) throw failure("file_not_regular");
7466
+ if (stat2.size <= 0n || stat2.size > BigInt(maxBytes2)) throw failure("file_size_limit");
7467
+ original = fingerprint(stat2);
7468
+ await assertUnchanged();
7469
+ const hash6 = createHash("sha256"), buffer = Buffer.allocUnsafe(LOCAL_UPLOAD_READ_BYTES);
7470
+ for (let position = 0; position < original.sizeBytes; ) {
7471
+ checkSignal();
7472
+ const length = Math.min(buffer.length, original.sizeBytes - position);
7473
+ const { bytesRead } = await read2(buffer, 0, length, position);
7474
+ if (bytesRead === 0) throw failure("file_changed");
7475
+ hash6.update(buffer.subarray(0, bytesRead));
7476
+ position += bytesRead;
7477
+ }
7478
+ await assertUnchanged();
7479
+ const checksum = "sha256:" + hash6.digest("hex");
7480
+ return {
7481
+ name,
7482
+ sizeBytes: original.sizeBytes,
7483
+ checksum,
7484
+ fingerprint: { ...original, checksum },
7485
+ assertUnchanged,
7486
+ close,
7487
+ streamPart({ start, sizeBytes, signal: partSignal } = {}) {
7488
+ checkSignal(partSignal);
7489
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(sizeBytes) || start < 0 || sizeBytes < 1 || start + sizeBytes > original.sizeBytes) throw failure("part_range_invalid");
7490
+ async function* chunks() {
7491
+ await assertUnchanged();
7492
+ let position = start;
7493
+ while (position < start + sizeBytes) {
7494
+ checkSignal(partSignal);
7495
+ const bytes2 = Buffer.allocUnsafe(Math.min(LOCAL_UPLOAD_READ_BYTES, start + sizeBytes - position));
7496
+ const result = await read2(bytes2, 0, bytes2.length, position);
7497
+ checkSignal(partSignal);
7498
+ if (result.bytesRead === 0) throw failure("file_changed");
7499
+ position += result.bytesRead;
7500
+ yield bytes2.subarray(0, result.bytesRead);
7501
+ }
7502
+ await assertUnchanged();
7503
+ }
7504
+ const stream = Readable.from(chunks(), { objectMode: false, highWaterMark: LOCAL_UPLOAD_READ_BYTES });
7505
+ const done = finished(stream).finally(() => streams.delete(stream));
7506
+ done.catch(() => {
7507
+ });
7508
+ streams.set(stream, done);
7509
+ return stream;
7510
+ }
7511
+ };
7512
+ } catch (error4) {
7513
+ await close();
7514
+ if (error4 instanceof CreationClientError) throw error4;
7515
+ throw failure("file_read_failed");
7516
+ }
7517
+ }
7518
+
7519
+ // lib/local-upload-transfer.mjs
7520
+ import { Readable as Readable2 } from "node:stream";
7521
+ import { finished as finished2 } from "node:stream/promises";
7522
+ var fail = (code) => {
7523
+ throw new CreationClientError("creation.local_upload." + code);
7524
+ };
7525
+ var positive = (value2) => Number.isSafeInteger(value2) && value2 > 0;
7526
+ var forbiddenHeader = /^(?:authorization|cookie|host|connection|upgrade|proxy-.*)$/i;
7527
+ var defaultBudget = { totalMs: 3e5, firstProgressMs: 3e4, idleMs: 6e4 };
7528
+ async function transferGrantedPart(file, authorization, grant, {
7529
+ expectedUploadId,
7530
+ expectedAssetId,
7531
+ signal,
7532
+ deadlineAtMs = Infinity,
7533
+ fetch: fetchPart = globalThis.fetch,
7534
+ now = Date.now,
7535
+ onProgress = () => {
7536
+ }
7537
+ } = {}) {
7538
+ const session = authorization?.session;
7539
+ if (authorization?.contractVersion !== "direct-object-upload.v2" || !session || session.uploadId !== expectedUploadId || session.assetId !== expectedAssetId || session.sizeBytes !== file.sizeBytes || session.expectedChecksum !== file.checksum || !positive(session.partSizeBytes) || !positive(session.partCount) || session.partCount !== Math.ceil(file.sizeBytes / session.partSizeBytes) || !["authorized", "uploading"].includes(session.state)) fail("authorization_invalid");
7540
+ if (!grant || grant.method !== "PUT" || grant.uploadId !== expectedUploadId || grant.assetId !== expectedAssetId || !positive(grant.partNumber) || grant.partNumber > session.partCount || !Array.isArray(authorization.grants) || authorization.grants.filter((item) => item === grant).length !== 1) fail("grant_invalid");
7541
+ let destination;
7542
+ try {
7543
+ destination = new URL(grant.url);
7544
+ } catch {
7545
+ fail("grant_invalid");
7546
+ }
7547
+ if (!["https:", "http:"].includes(destination.protocol) || destination.username || destination.password || destination.hash || grant.url.length > 16 * 1024) fail("grant_invalid");
7548
+ const expires = [Date.parse(grant.expiresAt), Date.parse(session.expiresAt)];
7549
+ if (expires.some((value2) => !Number.isFinite(value2))) fail("grant_invalid");
7550
+ if (expires.some((value2) => value2 <= now())) fail("grant_expired");
7551
+ const budget = authorization.transferBudget?.part ?? defaultBudget;
7552
+ if (!positive(budget.totalMs) || budget.totalMs > 3e5 || !positive(budget.firstProgressMs) || budget.firstProgressMs > 12e4 || !positive(budget.idleMs) || budget.idleMs > 12e4)
7553
+ fail("transfer_budget_invalid");
7554
+ const start = (grant.partNumber - 1) * session.partSizeBytes;
7555
+ const sizeBytes = Math.min(session.partSizeBytes, file.sizeBytes - start);
7556
+ const headers = new Headers();
7557
+ if (!grant.requiredHeaders || typeof grant.requiredHeaders !== "object" || Array.isArray(grant.requiredHeaders) || Object.keys(grant.requiredHeaders).length > 64) fail("grant_invalid");
7558
+ for (const [name, value2] of Object.entries(grant.requiredHeaders)) {
7559
+ if (typeof value2 !== "string" || value2.length > 8192 || forbiddenHeader.test(name)) fail("grant_invalid");
7560
+ try {
7561
+ headers.set(name, value2);
7562
+ } catch {
7563
+ fail("grant_invalid");
7564
+ }
7565
+ }
7566
+ if (headers.has("content-length") && headers.get("content-length") !== String(sizeBytes)) fail("grant_invalid");
7567
+ headers.set("content-length", String(sizeBytes));
7568
+ const deadline = Math.min(now() + budget.totalMs, ...expires, deadlineAtMs);
7569
+ if (!Number.isFinite(deadline) || deadline <= now()) fail("transfer_deadline_expired");
7570
+ await file.assertUnchanged();
7571
+ if (signal?.aborted) fail("transfer_cancelled");
7572
+ const controller = new AbortController();
7573
+ let reason, firstTimer, idleTimer, totalTimer, bytesRead = 0;
7574
+ const abort = (code) => {
7575
+ reason ??= code;
7576
+ controller.abort();
7577
+ };
7578
+ const cancel = () => abort("transfer_cancelled");
7579
+ if (signal?.aborted) cancel();
7580
+ else signal?.addEventListener("abort", cancel, { once: true });
7581
+ const timer = (callback, ms2) => {
7582
+ const id = setTimeout(callback, ms2);
7583
+ id.unref?.();
7584
+ return id;
7585
+ };
7586
+ firstTimer = timer(() => abort("transfer_first_progress_timeout"), budget.firstProgressMs);
7587
+ totalTimer = timer(() => abort("transfer_timeout"), Math.max(1, deadline - now()));
7588
+ let input, body, bodyDone, inputDone, response;
7589
+ async function* chunks() {
7590
+ for await (const chunk of input) {
7591
+ if (controller.signal.aborted) fail(reason ?? "transfer_cancelled");
7592
+ clearTimeout(firstTimer);
7593
+ clearTimeout(idleTimer);
7594
+ idleTimer = timer(() => abort("transfer_idle_timeout"), budget.idleMs);
7595
+ bytesRead += chunk.length;
7596
+ onProgress({ partNumber: grant.partNumber, bytesRead, sizeBytes });
7597
+ yield chunk;
7598
+ }
7599
+ }
7600
+ try {
7601
+ input = file.streamPart({ start, sizeBytes, signal: controller.signal });
7602
+ body = Readable2.from(chunks(), { objectMode: false, highWaterMark: LOCAL_UPLOAD_READ_BYTES });
7603
+ bodyDone = finished2(body);
7604
+ bodyDone.catch(() => {
7605
+ });
7606
+ inputDone = finished2(input);
7607
+ inputDone.catch(() => {
7608
+ });
7609
+ response = await fetchPart(destination, { method: "PUT", headers, body, duplex: "half", redirect: "error", signal: controller.signal });
7610
+ if (!response.ok) fail("part_target_rejected");
7611
+ await bodyDone;
7612
+ await inputDone;
7613
+ if (bytesRead !== sizeBytes) fail("part_transfer_unconfirmed");
7614
+ await file.assertUnchanged();
7615
+ const etag = response.headers.get("etag");
7616
+ if (!etag || etag.length > 512 || /[\x00-\x1f\x7f]/.test(etag)) fail("part_receipt_unconfirmed");
7617
+ return { partNumber: grant.partNumber, etag, sizeBytes };
7618
+ } catch (error4) {
7619
+ if (reason) fail(reason);
7620
+ if (error4 instanceof CreationClientError) throw error4;
7621
+ fail("part_transfer_unconfirmed");
7622
+ } finally {
7623
+ controller.abort();
7624
+ clearTimeout(firstTimer);
7625
+ clearTimeout(idleTimer);
7626
+ clearTimeout(totalTimer);
7627
+ signal?.removeEventListener("abort", cancel);
7628
+ body?.destroy();
7629
+ input?.destroy();
7630
+ await Promise.allSettled([bodyDone, inputDone]);
7631
+ await response?.body?.cancel().catch(() => {
7632
+ });
7633
+ }
7634
+ }
7635
+ var effects = /* @__PURE__ */ new WeakMap();
7636
+ var readPartTransferEffect = (error4) => error4 && typeof error4 === "object" ? effects.get(error4) : void 0;
7637
+ async function uploadGrantedPart(file, authorization, grant, options = {}) {
7638
+ let dispatched = false;
7639
+ try {
7640
+ return await transferGrantedPart(file, authorization, grant, { ...options, fetch: async (...args2) => {
7641
+ dispatched = true;
7642
+ return (options.fetch ?? globalThis.fetch)(...args2);
7643
+ } });
7644
+ } catch (error4) {
7645
+ if (error4 && typeof error4 === "object") effects.set(error4, dispatched ? "unknown" : "not_dispatched");
7646
+ throw error4;
7647
+ }
7648
+ }
7649
+
7650
+ // lib/local-upload-state.mjs
7651
+ import { constants as constants2 } from "node:fs";
7652
+ import { open as open2, mkdir as mkdir2, lstat as lstat3, rename as rename2, unlink as unlink2, rmdir, readdir, readFile as readFile2 } from "node:fs/promises";
7653
+ import path3 from "node:path";
7654
+ import { randomBytes as randomBytes2 } from "node:crypto";
7655
+ var fail2 = () => {
7656
+ throw new CreationClientError("creation.local_upload.recovery_state_unavailable");
7657
+ };
7658
+ var flags = constants2.O_NOFOLLOW;
7659
+ var maxBytes = 1024 * 1024;
7660
+ var maxRecords = 100;
7661
+ var retentionMs = 24 * 60 * 60 * 1e3;
7662
+ async function directory(root) {
7663
+ try {
7664
+ await mkdir2(root, { mode: 448 });
7665
+ } catch (e) {
7666
+ if (e.code !== "EEXIST") throw e;
7667
+ }
7668
+ const info5 = await lstat3(root);
7669
+ if (!info5.isDirectory() || info5.isSymbolicLink() || info5.mode & 63 || process.getuid && info5.uid !== process.getuid()) fail2();
7670
+ }
7671
+ async function read(file) {
7672
+ let fd;
7673
+ try {
7674
+ fd = await open2(file, constants2.O_RDONLY | flags);
7675
+ const info5 = await fd.stat();
7676
+ if (!info5.isFile() || info5.mode & 63 || info5.size > maxBytes || process.getuid && info5.uid !== process.getuid()) fail2();
7677
+ return JSON.parse(await fd.readFile("utf8"));
7678
+ } catch (e) {
7679
+ if (e.code === "ENOENT") return null;
7680
+ fail2();
7681
+ } finally {
7682
+ await fd?.close();
7683
+ }
7684
+ }
7685
+ async function syncDirectory(root) {
7686
+ if (process.platform === "win32") return;
7687
+ const fd = await open2(root, constants2.O_RDONLY | constants2.O_DIRECTORY | flags);
7688
+ try {
7689
+ await fd.sync();
7690
+ } finally {
7691
+ await fd.close();
7692
+ }
7693
+ }
7694
+ async function birth(pid) {
7695
+ if (process.platform !== "linux") return null;
7696
+ try {
7697
+ const stat2 = await readFile2(`/proc/${pid}/stat`, "utf8"), end = stat2.lastIndexOf(")");
7698
+ return { boot: (await readFile2("/proc/sys/kernel/random/boot_id", "utf8")).trim(), start: stat2.slice(end + 2).split(" ")[19] };
7699
+ } catch (e) {
7700
+ if (e.code === "ENOENT") return false;
7701
+ fail2();
7702
+ }
7703
+ }
7704
+ async function localUploadState(root, { now = Date.now } = {}) {
7705
+ try {
7706
+ await directory(root);
7707
+ } catch {
7708
+ fail2();
7709
+ }
7710
+ const ownBirth = await birth(process.pid), owner = { pid: process.pid, birth: ownBirth, nonce: randomBytes2(16).toString("hex") };
7711
+ const file = (key) => {
7712
+ if (!/^[a-f0-9]{64}$/.test(key)) fail2();
7713
+ return path3.join(root, key + ".json");
7714
+ };
7715
+ async function write(key, value2) {
7716
+ const body = JSON.stringify(value2);
7717
+ if (Buffer.byteLength(body) > maxBytes) fail2();
7718
+ const destination = file(key), temporary = path3.join(root, key + "-" + randomBytes2(12).toString("hex") + ".partial");
7719
+ let fd;
7720
+ try {
7721
+ fd = await open2(temporary, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL | flags, 384);
7722
+ await fd.writeFile(body);
7723
+ await fd.sync();
7724
+ await fd.close();
7725
+ fd = void 0;
7726
+ const current = await lstat3(destination).catch((e) => {
7727
+ if (e.code !== "ENOENT") throw e;
7728
+ });
7729
+ if (current && (!current.isFile() || current.isSymbolicLink() || current.mode & 63)) fail2();
7730
+ await rename2(temporary, destination);
7731
+ await syncDirectory(root);
7732
+ } catch {
7733
+ fail2();
7734
+ } finally {
7735
+ await fd?.close();
7736
+ await unlink2(temporary).catch(() => {
7737
+ });
7738
+ }
7739
+ }
7740
+ async function lock(key) {
7741
+ const target = path3.join(root, key + ".lock");
7742
+ file(key);
7743
+ const reclaiming = async () => (await readdir(root)).some((name) => name.startsWith(key + ".reclaim-"));
7744
+ for (let attempt = 0; attempt < 2; attempt++) {
7745
+ if (await reclaiming()) throw new CreationClientError("creation.local_upload.transfer_owned_by_another_bridge");
7746
+ const staging = path3.join(root, key + "-" + randomBytes2(12).toString("hex") + ".claim");
7747
+ await mkdir2(staging, { mode: 448 });
7748
+ const prepared = await open2(path3.join(staging, "owner.json"), constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL | flags, 384);
7749
+ try {
7750
+ await prepared.writeFile(JSON.stringify(owner));
7751
+ await prepared.sync();
7752
+ } finally {
7753
+ await prepared.close();
7754
+ }
7755
+ await syncDirectory(staging);
7756
+ try {
7757
+ await rename2(staging, target);
7758
+ } catch (e) {
7759
+ await unlink2(path3.join(staging, "owner.json"));
7760
+ await rmdir(staging);
7761
+ if (!["EEXIST", "ENOTEMPTY"].includes(e.code)) fail2();
7762
+ const info5 = await lstat3(target);
7763
+ if (!info5.isDirectory() || info5.isSymbolicLink() || info5.mode & 63) fail2();
7764
+ const old = await read(path3.join(target, "owner.json"));
7765
+ if (!old || !Number.isSafeInteger(old.pid) || old.pid < 1 || !old.birth || process.platform !== "linux")
7766
+ throw new CreationClientError("creation.local_upload.transfer_owned_by_another_bridge");
7767
+ const current = await birth(old.pid);
7768
+ if (current && current.boot === old.birth.boot && current.start === old.birth.start)
7769
+ throw new CreationClientError("creation.local_upload.transfer_owned_by_another_bridge");
7770
+ if (!/^[a-f0-9]{32}$/.test(old.nonce)) fail2();
7771
+ const marker = path3.join(root, key + ".reclaim-" + old.nonce);
7772
+ try {
7773
+ await mkdir2(marker, { mode: 448 });
7774
+ } catch {
7775
+ throw new CreationClientError("creation.local_upload.transfer_owned_by_another_bridge");
7776
+ }
7777
+ try {
7778
+ const again = await read(path3.join(target, "owner.json"));
7779
+ if (JSON.stringify(again) !== JSON.stringify(old)) fail2();
7780
+ await unlink2(path3.join(target, "owner.json"));
7781
+ await rmdir(target);
7782
+ await syncDirectory(root);
7783
+ } finally {
7784
+ await rmdir(marker);
7785
+ await syncDirectory(root);
7786
+ }
7787
+ continue;
7788
+ }
7789
+ if (await reclaiming()) {
7790
+ const current = await read(path3.join(target, "owner.json"));
7791
+ if (current?.nonce !== owner.nonce) fail2();
7792
+ await unlink2(path3.join(target, "owner.json"));
7793
+ await rmdir(target);
7794
+ throw new CreationClientError("creation.local_upload.transfer_owned_by_another_bridge");
7795
+ }
7796
+ await syncDirectory(root);
7797
+ return async () => {
7798
+ const current = await read(path3.join(target, "owner.json"));
7799
+ if (current?.nonce !== owner.nonce) fail2();
7800
+ await unlink2(path3.join(target, "owner.json"));
7801
+ await rmdir(target);
7802
+ await syncDirectory(root);
7803
+ };
7804
+ }
7805
+ fail2();
7806
+ }
7807
+ async function cleanup({ admitNew = false } = {}) {
7808
+ const names = await readdir(root);
7809
+ let records = 0;
7810
+ for (const name of names) {
7811
+ if (/^[a-f0-9]{64}\.json$/.test(name)) {
7812
+ const key = name.slice(0, -5), value2 = await read(file(key));
7813
+ records++;
7814
+ const cutoff = Date.parse(value2?.expiresAt ?? "") + retentionMs;
7815
+ if (!Number.isFinite(cutoff) || now() < cutoff) continue;
7816
+ let release;
7817
+ try {
7818
+ release = await lock(key);
7819
+ } catch (e) {
7820
+ if (e instanceof CreationClientError) continue;
7821
+ throw e;
7822
+ }
7823
+ try {
7824
+ const latest = await read(file(key));
7825
+ if (JSON.stringify(latest) === JSON.stringify(value2)) {
7826
+ await unlink2(file(key));
7827
+ records--;
7828
+ }
7829
+ } finally {
7830
+ await release();
7831
+ }
7832
+ } else if (/^[a-f0-9]{64}-[a-f0-9]{24}\.claim$/.test(name)) {
7833
+ const target = path3.join(root, name), info5 = await lstat3(target);
7834
+ if (!info5.isDirectory() || info5.isSymbolicLink() || info5.mode & 63 || now() - info5.mtimeMs <= retentionMs) continue;
7835
+ const old = await read(path3.join(target, "owner.json"));
7836
+ if (!old || process.platform !== "linux") continue;
7837
+ const current = await birth(old.pid);
7838
+ if (current && current.boot === old.birth?.boot && current.start === old.birth?.start) continue;
7839
+ if (JSON.stringify(await read(path3.join(target, "owner.json"))) !== JSON.stringify(old)) continue;
7840
+ await unlink2(path3.join(target, "owner.json"));
7841
+ await rmdir(target);
7842
+ } else if (/^[a-f0-9]{64}-[a-f0-9]{24}\.partial$/.test(name)) {
7843
+ const info5 = await lstat3(path3.join(root, name));
7844
+ if (info5.isFile() && !info5.isSymbolicLink() && (!process.getuid || info5.uid === process.getuid()) && !(info5.mode & 63) && now() - info5.mtimeMs > retentionMs) {
7845
+ let release;
7846
+ try {
7847
+ release = await lock(name.slice(0, 64));
7848
+ } catch {
7849
+ continue;
7850
+ }
7851
+ try {
7852
+ await unlink2(path3.join(root, name));
7853
+ } finally {
7854
+ await release();
7855
+ }
7856
+ }
7857
+ }
7858
+ }
7859
+ await syncDirectory(root);
7860
+ if (admitNew && records >= maxRecords) throw new CreationClientError("creation.local_upload.local_recovery_limit");
7861
+ }
7862
+ return { read: async (key) => read(file(key)), write, lock, cleanup };
7863
+ }
7864
+
7865
+ // lib/local-upload.mjs
7866
+ var LOCAL_UPLOAD_PROTOCOL = "creation-local-file-upload/v1";
7867
+ var wire = "direct-object-upload.v2";
7868
+ var digest = (value2) => createHash2("sha256").update(JSON.stringify(value2)).digest("hex");
7869
+ var fail3 = (code) => {
7870
+ throw new CreationClientError("creation.local_upload." + code);
7871
+ };
7872
+ var knownError = (error4) => error4 instanceof CreationClientError && /^creation\.[a-z0-9_.:-]{1,180}$/.test(error4.message) ? error4.message : "creation.local_upload.control_unconfirmed";
7873
+ var typeByExtension = {
7874
+ ".png": ["image", "image/png"],
7875
+ ".jpg": ["image", "image/jpeg"],
7876
+ ".jpeg": ["image", "image/jpeg"],
7877
+ ".webp": ["image", "image/webp"],
7878
+ ".gif": ["image", "image/gif"],
7879
+ ".wav": ["audio", "audio/wav"],
7880
+ ".mp3": ["audio", "audio/mpeg"],
7881
+ ".m4a": ["audio", "audio/mp4"],
7882
+ ".flac": ["audio", "audio/flac"],
7883
+ ".mp4": ["video", "video/mp4"],
7884
+ ".mov": ["video", "video/quicktime"],
7885
+ ".webm": ["video", "video/webm"],
7886
+ ".pdf": ["document", "application/pdf"]
7887
+ };
7888
+ var terminal = /* @__PURE__ */ new Set(["ready", "aborted", "expired", "rejected"]);
7889
+ var sessionCheck = (session, state) => {
7890
+ if (!session || session.uploadId !== state.uploadId || session.assetId !== state.assetId || session.sizeBytes !== state.file.sizeBytes || session.expectedChecksum !== state.file.checksum || session.originalName !== state.file.name || session.scope?.projectId !== state.projectId || session.scope?.sessionId !== state.sessionId) fail3("session_identity_unconfirmed");
7891
+ return session;
7892
+ };
7893
+ function receiptsForSession(session, parts, state) {
7894
+ sessionCheck(session, state);
7895
+ if (!Array.isArray(parts) || !Number.isSafeInteger(session.partSizeBytes) || session.partSizeBytes < 1 || session.partCount !== Math.ceil(state.file.sizeBytes / session.partSizeBytes)) fail3("authorization_invalid");
7896
+ const seen = /* @__PURE__ */ new Set();
7897
+ for (const part of parts) {
7898
+ if (!Number.isSafeInteger(part.partNumber) || part.partNumber < 1 || part.partNumber > session.partCount || seen.has(part.partNumber) || typeof part.etag !== "string" || !part.etag || part.etag.length > 512 || /[\x00-\x1f\x7f]/.test(part.etag) || part.sizeBytes !== Math.min(session.partSizeBytes, state.file.sizeBytes - (part.partNumber - 1) * session.partSizeBytes))
7899
+ fail3("part_receipt_unconfirmed");
7900
+ seen.add(part.partNumber);
7901
+ }
7902
+ return new Map(parts.map((part) => [part.partNumber, part]));
7903
+ }
7904
+ function partReceipts(authorization, state) {
7905
+ if (authorization?.contractVersion !== wire || !Array.isArray(authorization.grants) || authorization.grants.length > 2)
7906
+ fail3("authorization_invalid");
7907
+ return receiptsForSession(authorization.session, authorization.uploadedParts, state);
7908
+ }
7909
+ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch, now = Date.now } = {}) {
7910
+ if (!stateRoot) fail3("recovery_state_unavailable");
7911
+ let storePromise, closing = false, closePromise;
7912
+ const jobs = /* @__PURE__ */ new Map(), activeCalls = /* @__PURE__ */ new Set(), callControllers = /* @__PURE__ */ new Set();
7913
+ const store = () => storePromise ??= localUploadState(stateRoot, { now });
7914
+ const view = (state, job) => ({
7915
+ success: true,
7916
+ contractVersion: LOCAL_UPLOAD_PROTOCOL,
7917
+ idempotencyKey: state.idempotencyKey,
7918
+ projectId: state.projectId,
7919
+ sessionId: state.sessionId,
7920
+ file: { name: state.file.name, sizeBytes: state.file.sizeBytes, checksum: state.file.checksum },
7921
+ fileHost: { os: platform(), machine: hostname(), location: "bridge_host" },
7922
+ status: job ? "transferring" : ["creating", "transferring", "completing", "cancelling"].includes(state.phase) ? "observation_required" : state.phase,
7923
+ phase: state.phase,
7924
+ transport: { activeInThisBridge: !!job },
7925
+ uploadId: state.uploadId ?? null,
7926
+ assetId: state.assetId ?? null,
7927
+ progress: { uploadedBytes: state.parts.reduce((sum, p2) => sum + p2.sizeBytes, 0) + (job?.progress ?? 0), totalBytes: state.file.sizeBytes },
7928
+ ...state.jobId ? { jobId: state.jobId } : {},
7929
+ ...state.pendingPart ? { unconfirmedPart: state.pendingPart } : {},
7930
+ ...state.errorCode ? { errorCode: state.errorCode } : {},
7931
+ ...state.result ? { result: state.result } : {},
7932
+ automaticReplayAllowed: false,
7933
+ next: job ? "Read status using this same key." : state.phase === "ready" ? "Use this asset in the same Studio project." : state.phase === "derivatives_pending" ? "Read status for the original asset validation and derivatives." : "Observe status or explicitly resume/cancel this same key. Do not create a replacement upload."
7934
+ });
7935
+ async function rpc(send, transfer2, options) {
7936
+ const response = await send(transfer2, options);
7937
+ const result = response?.result ?? response;
7938
+ if (result?.isError) {
7939
+ let body2;
7940
+ try {
7941
+ body2 = JSON.parse(result.content?.find((block) => block.type === "text")?.text);
7942
+ } catch {
7943
+ }
7944
+ if (typeof body2?.errorCode === "string" && /^creation\.[a-z0-9_.:-]{1,180}$/.test(body2.errorCode)) throw new CreationClientError(body2.errorCode);
7945
+ fail3("control_unconfirmed");
7946
+ }
7947
+ let body;
7948
+ try {
7949
+ body = result.structuredContent ?? JSON.parse(result.content?.find((block) => block.type === "text")?.text);
7950
+ } catch {
7951
+ fail3("control_unconfirmed");
7952
+ }
7953
+ if (!body || body.success !== true) fail3("control_unconfirmed");
7954
+ return body;
7955
+ }
7956
+ async function observe(state, send, persist) {
7957
+ if (!state.uploadId) return { state, session: void 0 };
7958
+ const session = sessionCheck((await rpc(send, { action: "inspect", uploadId: state.uploadId })).session, state);
7959
+ state.expiresAt = session.expiresAt;
7960
+ state.lastObservedUploadState = session.state;
7961
+ if (session.state === "uploaded_unverified") {
7962
+ state.phase = "completion_unconfirmed";
7963
+ state.errorCode = "creation.local_upload.completion_requires_resume";
7964
+ }
7965
+ if (["aborted", "expired", "rejected"].includes(session.state)) {
7966
+ state.phase = session.state;
7967
+ delete state.errorCode;
7968
+ } else if (session.state === "finalized") {
7969
+ state.jobId ??= `direct-upload:${state.uploadId}`;
7970
+ const response = await send({ action: "derivation", jobId: state.jobId });
7971
+ const result = response?.result ?? response;
7972
+ let body;
7973
+ try {
7974
+ body = result.structuredContent ?? JSON.parse(result.content?.find((block) => block.type === "text")?.text);
7975
+ } catch {
7976
+ fail3("control_unconfirmed");
7977
+ }
7978
+ if (result.isError) fail3("control_unconfirmed");
7979
+ if (body?.success === true && body.uploadId === state.uploadId && body.assetId === state.assetId) {
7980
+ state.phase = body.status === "ready" ? "ready" : body.status === "failed" ? "derivation_failed" : "derivatives_pending";
7981
+ state.result = { success: true, status: body.status, uploadId: state.uploadId, assetId: state.assetId, jobId: state.jobId };
7982
+ delete state.errorCode;
7983
+ } else if (body?.errorCode === "media_derivation.job_not_found") {
7984
+ state.phase = "completion_unconfirmed";
7985
+ state.errorCode = "creation.local_upload.completion_unconfirmed";
7986
+ } else fail3("session_identity_unconfirmed");
7987
+ }
7988
+ if (persist) await persist();
7989
+ return { state, session };
7990
+ }
7991
+ function assertOriginalDeadline(state) {
7992
+ if (!Number.isFinite(state.deadlineAtMs) || !Number.isFinite(Date.parse(state.expiresAt)) || Math.min(state.deadlineAtMs, Date.parse(state.expiresAt)) <= now()) fail3("transfer_deadline_expired");
7993
+ }
7994
+ async function completeOriginal(state, session, send, binding, signal, save) {
7995
+ await binding.assertCurrent();
7996
+ signal?.throwIfAborted();
7997
+ assertOriginalDeadline(state);
7998
+ const parts = receiptsForSession(session, state.parts, state);
7999
+ if (parts.size !== session.partCount || state.completeKey !== "complete-" + state.key) fail3("original_completion_receipts_required");
8000
+ state.phase = "completing";
8001
+ await save();
8002
+ const timeout = Math.max(1, Math.min(3e4, state.deadlineAtMs - now(), Date.parse(state.expiresAt) - now()));
8003
+ const boundedSignal = AbortSignal.any([AbortSignal.timeout(timeout), ...signal ? [signal] : []]);
8004
+ const completed = await rpc(send, { action: "complete", request: {
8005
+ contractVersion: wire,
8006
+ uploadId: state.uploadId,
8007
+ idempotencyKey: state.completeKey,
8008
+ parts: state.parts
8009
+ } }, { signal: boundedSignal, timeout });
8010
+ assertOriginalDeadline(state);
8011
+ sessionCheck(completed.session, state);
8012
+ if (completed.session.state !== "finalized" || completed.jobId !== `direct-upload:${state.uploadId}`) fail3("completion_unconfirmed");
8013
+ state.jobId = completed.jobId;
8014
+ state.phase = "derivatives_pending";
8015
+ delete state.errorCode;
8016
+ await save();
8017
+ }
8018
+ async function transfer(job, authorization, send, binding) {
8019
+ const { state, file, abort, save } = job;
8020
+ const fileBudget = authorization?.transferBudget?.file?.totalMs ?? 6e5;
8021
+ if (!Number.isSafeInteger(fileBudget) || fileBudget < 1 || fileBudget > 18e5) fail3("transfer_budget_invalid");
8022
+ state.deadlineAtMs = Math.min(state.deadlineAtMs, (state.startedAtMs ?? now()) + fileBudget, Date.parse(state.expiresAt));
8023
+ await save();
8024
+ if (state.deadlineAtMs <= now()) fail3("transfer_deadline_expired");
8025
+ let envelope = authorization;
8026
+ while (true) {
8027
+ await binding.assertCurrent();
8028
+ abort.signal.throwIfAborted();
8029
+ await file.assertUnchanged();
8030
+ const session = sessionCheck(envelope.session, state);
8031
+ if (session.state === "finalized") break;
8032
+ if (!["authorized", "uploading"].includes(session.state)) fail3("session_not_transferable");
8033
+ const parts = partReceipts(envelope, state);
8034
+ if (state.pendingPart !== void 0) {
8035
+ if (!parts.has(state.pendingPart)) fail3("part_effect_unconfirmed_observe_original");
8036
+ delete state.pendingPart;
8037
+ }
8038
+ state.parts = [...parts.values()].sort((a, b2) => a.partNumber - b2.partNumber);
8039
+ await save();
8040
+ if (parts.size === session.partCount) break;
8041
+ if (!envelope.grants.length) fail3("authorization_invalid");
8042
+ for (const grant of envelope.grants) {
8043
+ if (parts.has(grant.partNumber)) fail3("authorization_invalid");
8044
+ await binding.assertCurrent();
8045
+ abort.signal.throwIfAborted();
8046
+ state.phase = "transferring";
8047
+ state.pendingPart = grant.partNumber;
8048
+ await save();
8049
+ let part;
8050
+ try {
8051
+ part = await uploadGrantedPart(file, envelope, grant, {
8052
+ expectedUploadId: state.uploadId,
8053
+ expectedAssetId: state.assetId,
8054
+ signal: abort.signal,
8055
+ deadlineAtMs: state.deadlineAtMs,
8056
+ fetch: fetch2,
8057
+ now,
8058
+ onProgress: (progress) => {
8059
+ job.progress = progress.bytesRead;
8060
+ }
8061
+ });
8062
+ } catch (error4) {
8063
+ if (readPartTransferEffect(error4) === "not_dispatched") {
8064
+ delete state.pendingPart;
8065
+ await save();
8066
+ }
8067
+ throw error4;
8068
+ }
8069
+ state.parts.push(part);
8070
+ state.parts.sort((a, b2) => a.partNumber - b2.partNumber);
8071
+ job.progress = 0;
8072
+ delete state.pendingPart;
8073
+ await save();
8074
+ }
8075
+ await binding.assertCurrent();
8076
+ abort.signal.throwIfAborted();
8077
+ envelope = (await rpc(send, { action: "resume", uploadId: state.uploadId })).authorization;
8078
+ }
8079
+ await binding.assertCurrent();
8080
+ abort.signal.throwIfAborted();
8081
+ await file.assertUnchanged();
8082
+ await completeOriginal(state, envelope.session, send, binding, abort.signal, save);
8083
+ }
8084
+ async function callCore({ input, scope, send, binding, signal }) {
8085
+ if (closing) fail3("bridge_closing");
8086
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key2) => !["projectId", "sessionId", "action", "idempotencyKey", "filePath", "assetKind", "mimeType"].includes(key2)) || !["upload", "resume", "status", "cancel"].includes(input.action) || typeof input.idempotencyKey !== "string" || input.idempotencyKey.length < 8 || input.idempotencyKey.length > 200) fail3("request_invalid");
8087
+ if (!scope || Object.values(scope).some((value2) => typeof value2 !== "string" || !value2) || !binding?.assertCurrent) fail3("scope_unverified");
8088
+ await binding.assertCurrent();
8089
+ const key = digest([LOCAL_UPLOAD_PROTOCOL, scope, input.idempotencyKey]), persistence = await store();
8090
+ let job = jobs.get(key), state = job?.state ?? await persistence.read(key);
8091
+ if (state && (state.contractVersion !== LOCAL_UPLOAD_PROTOCOL || state.key !== key || state.projectId !== input.projectId || state.sessionId !== input.sessionId || !Array.isArray(state.parts))) fail3("recovery_state_unavailable");
8092
+ if (job && input.action === "status") return view(state, job);
8093
+ if (job && input.action === "cancel") {
8094
+ job.abort.abort();
8095
+ await job.done;
8096
+ job = void 0;
8097
+ state = await persistence.read(key);
8098
+ }
8099
+ if (job) return view(state, job);
8100
+ if (!state && input.action !== "upload") fail3("original_upload_not_found");
8101
+ if (input.action === "status") {
8102
+ const copy = structuredClone(state);
8103
+ await observe(copy, send);
8104
+ return view(copy);
8105
+ }
8106
+ if (jobs.size >= 2 && !["status", "cancel"].includes(input.action)) fail3("bridge_transfer_limit");
8107
+ await persistence.cleanup({ admitNew: !state });
8108
+ const release = await persistence.lock(key);
8109
+ let file;
8110
+ try {
8111
+ state = await persistence.read(key) ?? state;
8112
+ if (input.action === "cancel") {
8113
+ if (["ready", "derivatives_pending", "derivation_failed"].includes(state.phase))
8114
+ return view((await observe(state, send, () => persistence.write(key, state))).state);
8115
+ if (!state.uploadId) fail3("create_unconfirmed_observe_original_key");
8116
+ state.phase = "cancelling";
8117
+ await persistence.write(key, state);
8118
+ const result = await rpc(send, { action: "abort", request: {
8119
+ contractVersion: wire,
8120
+ uploadId: state.uploadId,
8121
+ idempotencyKey: state.abortKey,
8122
+ reasonCode: "user_cancelled"
8123
+ } });
8124
+ sessionCheck(result.session, state);
8125
+ state.phase = result.session.state;
8126
+ delete state.errorCode;
8127
+ await persistence.write(key, state);
8128
+ return view(state);
8129
+ }
8130
+ if (state && terminal.has(state.phase)) return view((await observe(state, send, () => persistence.write(key, state))).state);
8131
+ if (state?.uploadId) {
8132
+ const observed = await observe(state, send, () => persistence.write(key, state));
8133
+ if (terminal.has(state.phase) || state.phase === "derivatives_pending" || state.phase === "derivation_failed") return view(state);
8134
+ if (["uploaded_unverified", "finalized"].includes(observed.session.state)) {
8135
+ if (input.action !== "resume") return view(state);
8136
+ assertOriginalDeadline(state);
8137
+ if (input.filePath !== void 0) {
8138
+ if (typeof input.filePath !== "string" || input.filePath.length > 4096) fail3("file_selection_required");
8139
+ file = await openLocalUploadFile(input.filePath, { signal, deadlineAtMs: state.deadlineAtMs, now });
8140
+ if (JSON.stringify(state.file.fingerprint) !== JSON.stringify(file.fingerprint) || state.file.name !== file.name) fail3("file_changed");
8141
+ }
8142
+ if (input.assetKind !== void 0 && input.assetKind !== state.request.assetKind || input.mimeType !== void 0 && input.mimeType !== state.request.mimeType) fail3("file_changed");
8143
+ await completeOriginal(state, observed.session, send, binding, signal, () => persistence.write(key, state));
8144
+ return view(state);
8145
+ }
8146
+ }
8147
+ if (typeof input.filePath !== "string" || input.filePath.length > 4096) fail3("file_selection_required");
8148
+ const startedAtMs = state?.startedAtMs ?? now(), deadlineAtMs = state?.deadlineAtMs ?? startedAtMs + 6e5;
8149
+ file = await openLocalUploadFile(input.filePath, { signal, deadlineAtMs, now });
8150
+ const inferred = typeByExtension[path4.extname(file.name).toLowerCase()] ?? [];
8151
+ const assetKind = input.assetKind ?? inferred[0], mimeType = input.mimeType ?? inferred[1];
8152
+ if (!["image", "audio", "video", "document"].includes(assetKind) || typeof mimeType !== "string" || !/^\S+\/\S+$/.test(mimeType) || mimeType.length > 255) fail3("file_type_required");
8153
+ if (state && (JSON.stringify(state.file.fingerprint) !== JSON.stringify(file.fingerprint) || state.file.name !== file.name || state.request.assetKind !== assetKind || state.request.mimeType !== mimeType)) fail3("file_changed");
8154
+ if (!state) {
8155
+ state = {
8156
+ contractVersion: LOCAL_UPLOAD_PROTOCOL,
8157
+ key,
8158
+ projectId: input.projectId,
8159
+ sessionId: input.sessionId,
8160
+ idempotencyKey: input.idempotencyKey,
8161
+ startedAtMs,
8162
+ deadlineAtMs,
8163
+ completeKey: "complete-" + key,
8164
+ abortKey: "abort-" + key,
8165
+ file: { name: file.name, sizeBytes: file.sizeBytes, checksum: file.checksum, fingerprint: file.fingerprint },
8166
+ request: {
8167
+ contractVersion: wire,
8168
+ originalName: file.name,
8169
+ purpose: "project-asset",
8170
+ assetKind,
8171
+ mimeType,
8172
+ sizeBytes: file.sizeBytes,
8173
+ expectedChecksum: file.checksum,
8174
+ idempotencyKey: "create-" + key
8175
+ },
8176
+ phase: "creating",
8177
+ parts: [],
8178
+ expiresAt: new Date(now() + 30 * 60 * 1e3).toISOString()
8179
+ };
8180
+ await persistence.write(key, state);
8181
+ }
8182
+ await binding.assertCurrent();
8183
+ let authorization;
8184
+ if (!state.uploadId) {
8185
+ const created = await rpc(send, { action: "create", request: state.request });
8186
+ authorization = created.authorization;
8187
+ const session = authorization?.session;
8188
+ if (!session || typeof session.uploadId !== "string" || typeof session.assetId !== "string") fail3("authorization_invalid");
8189
+ state.uploadId = session.uploadId;
8190
+ state.assetId = session.assetId;
8191
+ sessionCheck(session, state);
8192
+ state.expiresAt = session.expiresAt;
8193
+ await persistence.write(key, state);
8194
+ } else {
8195
+ authorization = (await rpc(send, { action: "resume", uploadId: state.uploadId })).authorization;
8196
+ }
8197
+ signal?.throwIfAborted();
8198
+ const abort = new AbortController();
8199
+ job = { state, file, abort, progress: 0, save: () => persistence.write(key, state) };
8200
+ jobs.set(key, job);
8201
+ file = void 0;
8202
+ job.done = Promise.resolve().then(() => transfer(job, authorization, (transfer2, options) => send(transfer2, { signal: abort.signal, ...options }), binding)).catch(async (error4) => {
8203
+ state.phase = "paused";
8204
+ state.errorCode = abort.signal.aborted ? "creation.local_upload.transfer_cancelled" : knownError(error4);
8205
+ await job.save();
8206
+ }).finally(async () => {
8207
+ try {
8208
+ await job.file.close();
8209
+ } finally {
8210
+ try {
8211
+ await release();
8212
+ } finally {
8213
+ jobs.delete(key);
8214
+ }
8215
+ }
8216
+ });
8217
+ job.done.catch(() => {
8218
+ });
8219
+ return view(state, job);
8220
+ } catch (error4) {
8221
+ if (state) {
8222
+ state.phase = "paused";
8223
+ state.errorCode = knownError(error4);
8224
+ await persistence.write(key, state);
8225
+ }
8226
+ throw error4;
8227
+ } finally {
8228
+ if (!jobs.has(key)) {
8229
+ await file?.close();
8230
+ await release();
8231
+ }
8232
+ }
8233
+ }
8234
+ return { call(options) {
8235
+ if (closing) fail3("bridge_closing");
8236
+ const controller = new AbortController(), abort = () => controller.abort();
8237
+ if (options.signal?.aborted) abort();
8238
+ else options.signal?.addEventListener("abort", abort, { once: true });
8239
+ callControllers.add(controller);
8240
+ const send = (transfer2, extra = {}) => options.send(transfer2, { signal: controller.signal, ...extra });
8241
+ const pending = callCore({ ...options, send, signal: controller.signal }).finally(() => {
8242
+ activeCalls.delete(pending);
8243
+ callControllers.delete(controller);
8244
+ options.signal?.removeEventListener("abort", abort);
8245
+ });
8246
+ activeCalls.add(pending);
8247
+ return pending;
8248
+ }, close() {
8249
+ return closePromise ??= (async () => {
8250
+ closing = true;
8251
+ for (const controller of callControllers) controller.abort();
8252
+ for (const job of jobs.values()) job.abort.abort();
8253
+ await Promise.allSettled([...activeCalls]);
8254
+ for (const job of jobs.values()) job.abort.abort();
8255
+ await Promise.allSettled([...jobs.values()].map((job) => job.done));
8256
+ })();
8257
+ } };
8258
+ }
8259
+
7303
8260
  // lib/version.mjs
7304
- var CLIENT_VERSION = "0.3.3";
8261
+ var CLIENT_VERSION = "0.3.5";
7305
8262
  var CLIENT_PROTOCOL = "creation-client/v1";
7306
8263
 
7307
8264
  // lib/cli.mjs
7308
- import { randomBytes as randomBytes7 } from "node:crypto";
8265
+ import { randomBytes as randomBytes8 } from "node:crypto";
7309
8266
  import { spawn as spawn2 } from "node:child_process";
7310
8267
 
7311
8268
  // node_modules/zod/v4/core/util.js
@@ -7545,10 +8502,10 @@ function mergeDefs(...defs) {
7545
8502
  function cloneDef(schema) {
7546
8503
  return mergeDefs(schema._zod.def);
7547
8504
  }
7548
- function getElementAtPath(obj, path14) {
7549
- if (!path14)
8505
+ function getElementAtPath(obj, path17) {
8506
+ if (!path17)
7550
8507
  return obj;
7551
- return path14.reduce((acc, key) => acc?.[key], obj);
8508
+ return path17.reduce((acc, key) => acc?.[key], obj);
7552
8509
  }
7553
8510
  function promiseAllObject(promisesObj) {
7554
8511
  const keys = Object.keys(promisesObj);
@@ -7888,11 +8845,11 @@ function explicitlyAborted(x, startIndex = 0) {
7888
8845
  }
7889
8846
  return false;
7890
8847
  }
7891
- function prefixIssues(path14, issues) {
8848
+ function prefixIssues(path17, issues) {
7892
8849
  return issues.map((iss) => {
7893
8850
  var _a3;
7894
8851
  (_a3 = iss).path ?? (_a3.path = []);
7895
- iss.path.unshift(path14);
8852
+ iss.path.unshift(path17);
7896
8853
  return iss;
7897
8854
  });
7898
8855
  }
@@ -8353,16 +9310,16 @@ function flattenError(error4, mapper = (issue2) => issue2.message) {
8353
9310
  }
8354
9311
  function formatError(error4, mapper = (issue2) => issue2.message) {
8355
9312
  const fieldErrors = { _errors: [] };
8356
- const processError = (error5, path14 = []) => {
9313
+ const processError = (error5, path17 = []) => {
8357
9314
  for (const issue2 of error5.issues) {
8358
9315
  if (issue2.code === "invalid_union" && issue2.errors.length) {
8359
- issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
9316
+ issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
8360
9317
  } else if (issue2.code === "invalid_key") {
8361
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
9318
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
8362
9319
  } else if (issue2.code === "invalid_element") {
8363
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
9320
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
8364
9321
  } else {
8365
- const fullpath = [...path14, ...issue2.path];
9322
+ const fullpath = [...path17, ...issue2.path];
8366
9323
  if (fullpath.length === 0) {
8367
9324
  fieldErrors._errors.push(mapper(issue2));
8368
9325
  } else {
@@ -8370,9 +9327,9 @@ function formatError(error4, mapper = (issue2) => issue2.message) {
8370
9327
  let i = 0;
8371
9328
  while (i < fullpath.length) {
8372
9329
  const el = fullpath[i];
8373
- const terminal = i === fullpath.length - 1;
9330
+ const terminal2 = i === fullpath.length - 1;
8374
9331
  if (el === "_errors") {
8375
- if (terminal)
9332
+ if (terminal2)
8376
9333
  curr._errors.push(mapper(issue2));
8377
9334
  i++;
8378
9335
  continue;
@@ -8386,7 +9343,7 @@ function formatError(error4, mapper = (issue2) => issue2.message) {
8386
9343
  });
8387
9344
  }
8388
9345
  const node2 = curr[el];
8389
- if (terminal) {
9346
+ if (terminal2) {
8390
9347
  node2._errors.push(mapper(issue2));
8391
9348
  }
8392
9349
  curr = node2;
@@ -8441,10 +9398,10 @@ var _safeParse = (_Err) => (schema, value2, _ctx) => {
8441
9398
  if (result instanceof Promise) {
8442
9399
  throw new $ZodAsyncError();
8443
9400
  }
8444
- return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
9401
+ return result.issues.length ? failure2(_Err, result.issues, ctx) : { success: true, data: result.value };
8445
9402
  };
8446
9403
  var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
8447
- function failure(Err, issues, ctx) {
9404
+ function failure2(Err, issues, ctx) {
8448
9405
  let error4;
8449
9406
  return {
8450
9407
  success: false,
@@ -8468,7 +9425,7 @@ var _safeParseAsync = (_Err) => async (schema, value2, _ctx) => {
8468
9425
  let result = schema._zod.run({ value: value2, issues: [] }, ctx);
8469
9426
  if (result instanceof Promise)
8470
9427
  result = await result;
8471
- return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
9428
+ return result.issues.length ? failure2(_Err, result.issues, ctx) : { success: true, data: result.value };
8472
9429
  };
8473
9430
  var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid");
8474
9431
  var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback");
@@ -9197,9 +10154,9 @@ var asciiTabOrNewline = /[\t\n\r]/g;
9197
10154
  function stripTabAndNewline(value2) {
9198
10155
  return value2.replace(asciiTabOrNewline, "");
9199
10156
  }
9200
- function urlHostnameOk(url2, hostname) {
9201
- hostname.lastIndex = 0;
9202
- return hostname.test(url2.hostname);
10157
+ function urlHostnameOk(url2, hostname2) {
10158
+ hostname2.lastIndex = 0;
10159
+ return hostname2.test(url2.hostname);
9203
10160
  }
9204
10161
  function urlProtocolOk(url2, protocol) {
9205
10162
  protocol.lastIndex = 0;
@@ -10857,7 +11814,7 @@ function bucketFor(state, inst) {
10857
11814
  return bucket;
10858
11815
  }
10859
11816
  var handoff;
10860
- var open = [];
11817
+ var open3 = [];
10861
11818
  var memo = {
10862
11819
  alloc(_inst, payload, empty) {
10863
11820
  const bucket = handoff;
@@ -10866,7 +11823,7 @@ var memo = {
10866
11823
  handoff = void 0;
10867
11824
  const entry = { value: empty, issues: null };
10868
11825
  bucket.set(payload.value, entry);
10869
- open.push(entry);
11826
+ open3.push(entry);
10870
11827
  return empty;
10871
11828
  },
10872
11829
  guard(inst) {
@@ -10937,10 +11894,10 @@ var memo = {
10937
11894
  return payload;
10938
11895
  }
10939
11896
  handoff = bucket;
10940
- const depth = open.length;
11897
+ const depth = open3.length;
10941
11898
  const result = base(payload, ctx);
10942
11899
  handoff = void 0;
10943
- const entry = open.length > depth ? open.pop() : void 0;
11900
+ const entry = open3.length > depth ? open3.pop() : void 0;
10944
11901
  if (result instanceof Promise) {
10945
11902
  return result.then((r) => {
10946
11903
  if (entry)
@@ -17312,93 +18269,6 @@ var StdioServerTransport = class {
17312
18269
  }
17313
18270
  };
17314
18271
 
17315
- // lib/credentials.mjs
17316
- import {
17317
- lstat,
17318
- mkdir,
17319
- readFile,
17320
- writeFile,
17321
- rename,
17322
- unlink
17323
- } from "node:fs/promises";
17324
- import { homedir } from "node:os";
17325
- import path from "node:path";
17326
- import { randomBytes } from "node:crypto";
17327
- var CreationClientError = class extends Error {
17328
- constructor(code) {
17329
- super(code);
17330
- this.name = "CreationClientError";
17331
- }
17332
- };
17333
- function credentialsPath(env = process.env) {
17334
- return path.resolve(
17335
- env.PROMPTFRAME_CREATION_CONFIG ?? path.join(
17336
- env.XDG_CONFIG_HOME ?? path.join(homedir(), ".config"),
17337
- "promptframe-creation",
17338
- "credentials.json"
17339
- )
17340
- );
17341
- }
17342
- function normalizeEndpoint(input) {
17343
- let url2;
17344
- try {
17345
- url2 = new URL(input);
17346
- } catch {
17347
- throw new CreationClientError("endpoint.invalid");
17348
- }
17349
- const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url2.hostname);
17350
- if (url2.username || url2.password || url2.search || url2.hash || url2.protocol !== "https:" && !(loopback && url2.protocol === "http:"))
17351
- throw new CreationClientError("endpoint.https_or_loopback_required");
17352
- const base = url2.href.replace(/\/+$/, "");
17353
- if (base.endsWith("/api/mcp")) return base;
17354
- if (base.endsWith("/api")) return base + "/mcp";
17355
- throw new CreationClientError("endpoint.api_base_required");
17356
- }
17357
- var secure = async (file, directory = false) => {
17358
- let info5;
17359
- try {
17360
- info5 = await lstat(file);
17361
- } catch (error4) {
17362
- if (error4.code === "ENOENT") return null;
17363
- throw error4;
17364
- }
17365
- if (info5.isSymbolicLink() || !(directory ? info5.isDirectory() : info5.isFile()) || info5.uid !== process.getuid?.() || (info5.mode & 63) !== 0)
17366
- throw new CreationClientError("credentials.private_owner_required");
17367
- return info5;
17368
- };
17369
- async function readCredentials(file = credentialsPath()) {
17370
- if (!await secure(file)) return null;
17371
- if (!await secure(path.dirname(file), true))
17372
- throw new CreationClientError("credentials.private_owner_required");
17373
- let value2;
17374
- try {
17375
- value2 = JSON.parse(await readFile(file, "utf8"));
17376
- } catch {
17377
- throw new CreationClientError("credentials.invalid");
17378
- }
17379
- if (value2.version !== 1 || typeof value2.token !== "string" || !/^pf_create_[A-Za-z0-9_-]{43}$/.test(value2.token) || typeof value2.clientId !== "string" || !/^[A-Za-z0-9_-]{16,128}$/.test(value2.clientId) || typeof value2.clientName !== "string" || !value2.clientName.trim() || value2.clientName.length > 160 || /[\x00-\x1f\x7f]/.test(value2.clientName))
17380
- throw new CreationClientError("credentials.invalid");
17381
- return { ...value2, endpoint: normalizeEndpoint(value2.endpoint) };
17382
- }
17383
- async function writeCredentials(value2, file = credentialsPath()) {
17384
- const directory = path.dirname(file);
17385
- await mkdir(directory, { recursive: true, mode: 448 });
17386
- await secure(directory, true);
17387
- await secure(file);
17388
- const temporary = file + "." + randomBytes(12).toString("hex") + ".tmp";
17389
- try {
17390
- await writeFile(temporary, JSON.stringify(value2) + "\n", {
17391
- flag: "wx",
17392
- mode: 384
17393
- });
17394
- await rename(temporary, file);
17395
- } finally {
17396
- await unlink(temporary).catch((error4) => {
17397
- if (error4.code !== "ENOENT") throw error4;
17398
- });
17399
- }
17400
- }
17401
-
17402
18272
  // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
17403
18273
  var ExperimentalClientTasks = class {
17404
18274
  constructor(_client) {
@@ -18183,8 +19053,8 @@ async function random(size) {
18183
19053
  const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
18184
19054
  let result = "";
18185
19055
  while (result.length < size) {
18186
- const randomBytes8 = await getRandomValues(size - result.length);
18187
- for (const randomByte of randomBytes8) {
19056
+ const randomBytes9 = await getRandomValues(size - result.length);
19057
+ for (const randomByte of randomBytes9) {
18188
19058
  if (randomByte < evenDistCutoff) {
18189
19059
  result += mask[randomByte % mask.length];
18190
19060
  }
@@ -19827,23 +20697,23 @@ async function connectPlatform(credentials, { host = resolveHostIdentity(), cont
19827
20697
  }
19828
20698
 
19829
20699
  // lib/host-context.mjs
19830
- import { createHash as createHash3 } from "node:crypto";
20700
+ import { createHash as createHash5 } from "node:crypto";
19831
20701
 
19832
20702
  // lib/claude-host-session.mjs
19833
- import { constants } from "node:fs";
19834
- import { open as open2, mkdir as mkdir2, lstat as lstat2, rename as rename2, unlink as unlink2, rmdir } from "node:fs/promises";
19835
- import path3 from "node:path";
20703
+ import { constants as constants3 } from "node:fs";
20704
+ import { open as open4, mkdir as mkdir3, lstat as lstat4, rename as rename3, unlink as unlink3, rmdir as rmdir2 } from "node:fs/promises";
20705
+ import path6 from "node:path";
19836
20706
  import { homedir as homedir3 } from "node:os";
19837
- import { createHash as createHash2, randomBytes as randomBytes2 } from "node:crypto";
20707
+ import { createHash as createHash4, randomBytes as randomBytes3 } from "node:crypto";
19838
20708
 
19839
20709
  // lib/claude-host-process.mjs
19840
- import { readFile as readFile2, readlink, stat } from "node:fs/promises";
19841
- import path2 from "node:path";
20710
+ import { readFile as readFile3, readlink, stat } from "node:fs/promises";
20711
+ import path5 from "node:path";
19842
20712
  import { homedir as homedir2 } from "node:os";
19843
- import { createHash } from "node:crypto";
19844
- var hash = (value2) => createHash("sha256").update(JSON.stringify(value2)).digest("hex");
20713
+ import { createHash as createHash3 } from "node:crypto";
20714
+ var hash = (value2) => createHash3("sha256").update(JSON.stringify(value2)).digest("hex");
19845
20715
  var bounded = async (file) => {
19846
- const value2 = await readFile2(file);
20716
+ const value2 = await readFile3(file);
19847
20717
  if (value2.length > 65536) throw Error("host_process_invalid");
19848
20718
  return value2;
19849
20719
  };
@@ -19872,8 +20742,8 @@ async function claudeHostProcess({
19872
20742
  if (visited.has(child.ppid)) return null;
19873
20743
  visited.add(child.ppid);
19874
20744
  const host = await readBirth(child.ppid);
19875
- const roots2 = [path2.join(home, ".claude", "remote", "ccd-cli"), path2.join(home, ".local", "share", "claude", "versions")];
19876
- if (roots2.some((root) => path2.dirname(host.exe) === root)) {
20745
+ const roots2 = [path5.join(home, ".claude", "remote", "ccd-cli"), path5.join(home, ".local", "share", "claude", "versions")];
20746
+ if (roots2.some((root) => path5.dirname(host.exe) === root)) {
19877
20747
  const executable = await readExecutable(host.exe);
19878
20748
  if (host.uid !== uid || ![uid, 0].includes(executable.uid) || !executable.isFile() || executable.mode & 18 || host.inode !== executable.ino || host.device !== executable.dev) return null;
19879
20749
  if (purpose === "hook") {
@@ -19881,8 +20751,8 @@ async function claudeHostProcess({
19881
20751
  if (!entryFile || !command2.some((arg) => arg.includes(entryFile)) || !command2.some((arg) => arg === "claude-host-hook" || arg.includes(" claude-host-hook"))) return null;
19882
20752
  }
19883
20753
  const binding = { pid: host.pid, birth: host.birth, uid, device: host.device, inode: host.inode, exe: host.exe, boot };
19884
- const digest4 = hash(binding);
19885
- return { binding, digest: digest4, eventOrder: { birth: child.birth, pid: child.pid }, async isCurrent() {
20754
+ const digest5 = hash(binding);
20755
+ return { binding, digest: digest5, eventOrder: { birth: child.birth, pid: child.pid }, async isCurrent() {
19886
20756
  try {
19887
20757
  const current = await readBirth(binding.pid);
19888
20758
  return current.birth === binding.birth && current.uid === uid && current.device === binding.device && current.inode === binding.inode && current.exe === binding.exe && await readBoot() === boot;
@@ -19910,22 +20780,22 @@ var canonical = (value2) => {
19910
20780
  return "{" + Object.keys(value2).sort().map((key) => JSON.stringify(key) + ":" + canonical(value2[key])).join(",") + "}";
19911
20781
  throw error2("request_invalid");
19912
20782
  };
19913
- var digest = (value2) => createHash2("sha256").update(canonical(value2)).digest("hex");
20783
+ var digest2 = (value2) => createHash4("sha256").update(canonical(value2)).digest("hex");
19914
20784
  var withoutProof = (args2) => Object.fromEntries(Object.entries(args2 ?? {}).filter(([key]) => key !== CLAUDE_HOST_PROOF));
19915
20785
  var later = (a, b2) => BigInt(a.birth) > BigInt(b2.birth) || a.birth === b2.birth && a.pid > b2.pid;
19916
- async function privateDirectory(directory) {
20786
+ async function privateDirectory(directory2) {
19917
20787
  try {
19918
- await mkdir2(directory, { mode: 448 });
20788
+ await mkdir3(directory2, { mode: 448 });
19919
20789
  } catch (e) {
19920
20790
  if (e.code !== "EEXIST") throw e;
19921
20791
  }
19922
- const info5 = await lstat2(directory);
20792
+ const info5 = await lstat4(directory2);
19923
20793
  if (!info5.isDirectory() || info5.isSymbolicLink() || info5.uid !== process.getuid?.() || info5.mode & 63) throw error2("host_identity_unavailable");
19924
20794
  }
19925
20795
  async function privateRead(file) {
19926
20796
  let handle;
19927
20797
  try {
19928
- handle = await open2(file, constants.O_RDONLY | constants.O_NOFOLLOW);
20798
+ handle = await open4(file, constants3.O_RDONLY | constants3.O_NOFOLLOW);
19929
20799
  const info5 = await handle.stat();
19930
20800
  if (!info5.isFile() || info5.uid !== process.getuid?.() || info5.mode & 63 || info5.size > 196608) throw error2("host_identity_unavailable");
19931
20801
  return JSON.parse(await handle.readFile("utf8"));
@@ -19938,9 +20808,9 @@ async function privateRead(file) {
19938
20808
  }
19939
20809
  async function createClaudeHostSession({ configFile: configFile2, env = process.env, root, association, hookProcess = false } = {}) {
19940
20810
  const owner = association === void 0 ? await claudeHostProcess({ env, purpose: hookProcess ? "hook" : "bridge" }) : association;
19941
- const base = root ?? path3.join(env.CLAUDE_CONFIG_DIR ?? path3.join(homedir3(), ".claude"), "promptframe-host-sessions");
19942
- const namespace = owner ? path3.join(base, digest([owner.digest, path3.resolve(configFile2)])) : null;
19943
- const stateFile = namespace && path3.join(namespace, "state.json");
20811
+ const base = root ?? path6.join(env.CLAUDE_CONFIG_DIR ?? path6.join(homedir3(), ".claude"), "promptframe-host-sessions");
20812
+ const namespace = owner ? path6.join(base, digest2([owner.digest, path6.resolve(configFile2)])) : null;
20813
+ const stateFile = namespace && path6.join(namespace, "state.json");
19944
20814
  async function state() {
19945
20815
  if (!owner || !await owner.isCurrent()) return null;
19946
20816
  const value2 = await privateRead(stateFile);
@@ -19952,10 +20822,10 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
19952
20822
  if (!owner || !await owner.isCurrent()) throw error2("host_identity_unavailable");
19953
20823
  await privateDirectory(base);
19954
20824
  await privateDirectory(namespace);
19955
- const lock = path3.join(namespace, "write.lock");
20825
+ const lock = path6.join(namespace, "write.lock");
19956
20826
  let acquired = false;
19957
20827
  for (let count = 0; count < 100; count++) try {
19958
- await mkdir2(lock, { mode: 448 });
20828
+ await mkdir3(lock, { mode: 448 });
19959
20829
  acquired = true;
19960
20830
  break;
19961
20831
  } catch (e) {
@@ -19969,13 +20839,13 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
19969
20839
  const current = await state(), next = await work(current);
19970
20840
  if (next === void 0) return;
19971
20841
  if (next === null) {
19972
- if (current) await unlink2(stateFile);
20842
+ if (current) await unlink3(stateFile);
19973
20843
  return;
19974
20844
  }
19975
20845
  const body = JSON.stringify(next);
19976
20846
  if (Buffer.byteLength(body) > 196608) throw error2("host_identity_unavailable");
19977
- temporary = path3.join(namespace, "state-" + randomBytes2(16).toString("hex") + ".partial");
19978
- const file = await open2(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
20847
+ temporary = path6.join(namespace, "state-" + randomBytes3(16).toString("hex") + ".partial");
20848
+ const file = await open4(temporary, constants3.O_WRONLY | constants3.O_CREAT | constants3.O_EXCL | constants3.O_NOFOLLOW, 384);
19979
20849
  try {
19980
20850
  await file.writeFile(body);
19981
20851
  await file.sync();
@@ -19983,18 +20853,18 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
19983
20853
  await file.close();
19984
20854
  }
19985
20855
  if (!await owner.isCurrent()) throw error2("host_identity_unavailable");
19986
- await rename2(temporary, stateFile);
20856
+ await rename3(temporary, stateFile);
19987
20857
  temporary = void 0;
19988
- const directory = await open2(namespace, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
20858
+ const directory2 = await open4(namespace, constants3.O_RDONLY | constants3.O_DIRECTORY | constants3.O_NOFOLLOW);
19989
20859
  try {
19990
- await directory.sync();
20860
+ await directory2.sync();
19991
20861
  } finally {
19992
- await directory.close();
20862
+ await directory2.close();
19993
20863
  }
19994
20864
  } finally {
19995
- if (temporary) await unlink2(temporary).catch(() => {
20865
+ if (temporary) await unlink3(temporary).catch(() => {
19996
20866
  });
19997
- await rmdir(lock);
20867
+ await rmdir2(lock);
19998
20868
  }
19999
20869
  }
20000
20870
  async function begin(raw) {
@@ -20006,7 +20876,7 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
20006
20876
  try {
20007
20877
  await transaction((current) => {
20008
20878
  const ticket = current?.tickets[proof];
20009
- if (!current?.sessionId || !ticket || ticket.epoch !== current.epoch || ticket.sessionId !== current.sessionId || ticket.digest !== digest([raw.name, args2])) throw error2("host_identity_invalid");
20879
+ if (!current?.sessionId || !ticket || ticket.epoch !== current.epoch || ticket.sessionId !== current.sessionId || ticket.digest !== digest2([raw.name, args2])) throw error2("host_identity_invalid");
20010
20880
  accepted = { threadId: current.sessionId, epoch: current.epoch };
20011
20881
  delete current.tickets[proof];
20012
20882
  return current;
@@ -20053,7 +20923,7 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
20053
20923
  tickets: same2 ? current.tickets : {}
20054
20924
  };
20055
20925
  if (event !== "PreToolUse") return next;
20056
- const args2 = withoutProof(rawArgs), tool = input.tool_name.slice(input.tool_name.lastIndexOf("__") + 2), key = digest([tool, args2]);
20926
+ const args2 = withoutProof(rawArgs), tool = input.tool_name.slice(input.tool_name.lastIndexOf("__") + 2), key = digest2([tool, args2]);
20057
20927
  if (!nextId) {
20058
20928
  result = { hookSpecificOutput: { hookEventName: event, updatedInput: args2 } };
20059
20929
  return next;
@@ -20064,13 +20934,13 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
20064
20934
  return next;
20065
20935
  }
20066
20936
  if (Object.keys(next.tickets).length >= 128) delete next.tickets[Object.keys(next.tickets)[0]];
20067
- const token = randomBytes2(32).toString("hex");
20937
+ const token = randomBytes3(32).toString("hex");
20068
20938
  next.tickets[token] = { digest: key, epoch: next.epoch, sessionId: nextId };
20069
20939
  result = { hookSpecificOutput: { hookEventName: event, updatedInput: { ...args2, [CLAUDE_HOST_PROOF]: token } } };
20070
20940
  return next;
20071
20941
  });
20072
20942
  if (event === "SessionEnd") try {
20073
- await rmdir(namespace);
20943
+ await rmdir2(namespace);
20074
20944
  } catch (e) {
20075
20945
  if (!["ENOTEMPTY", "ENOENT"].includes(e.code)) throw e;
20076
20946
  }
@@ -20098,7 +20968,7 @@ async function runClaudeHostHook({ configFile: configFile2, input = process.stdi
20098
20968
  // lib/host-context.mjs
20099
20969
  var digestPattern = /^sha256:[a-f0-9]{64}$/;
20100
20970
  var accesses = /* @__PURE__ */ new Set(["independent-read", "controlled", "authority"]);
20101
- var digest2 = (value2) => "sha256:" + createHash3("sha256").update(value2).digest("hex");
20971
+ var digest3 = (value2) => "sha256:" + createHash5("sha256").update(value2).digest("hex");
20102
20972
  var canonical2 = (value2) => {
20103
20973
  if (value2 === null || typeof value2 === "string" || typeof value2 === "boolean" || typeof value2 === "number" && Number.isFinite(value2)) return JSON.stringify(value2);
20104
20974
  if (Array.isArray(value2)) return "[" + value2.map(canonical2).join(",") + "]";
@@ -20106,19 +20976,19 @@ var canonical2 = (value2) => {
20106
20976
  return "{" + Object.keys(value2).sort().map((key) => JSON.stringify(key) + ":" + canonical2(value2[key])).join(",") + "}";
20107
20977
  throw new CreationClientError("creation.request_invalid");
20108
20978
  };
20109
- var argumentsDigest = (value2) => digest2(canonical2(value2));
20979
+ var argumentsDigest = (value2) => digest3(canonical2(value2));
20110
20980
  var boundedSet = (map, key, value2) => {
20111
20981
  if (!map.has(key) && map.size >= 1024) map.delete(map.keys().next().value);
20112
20982
  map.set(key, value2);
20113
20983
  };
20114
- function createHostCallBridge(client, { credentials, host = resolveHostIdentity(), hostSession, onCatalogChange = () => {
20984
+ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(), hostSession, localUploads, onCatalogChange = () => {
20115
20985
  }, onKnowledgeChange = () => {
20116
20986
  } } = {}) {
20117
20987
  if (!credentials?.endpoint || !credentials.clientId) throw new CreationClientError("creation.bridge_identity_required");
20118
- const installationDigest = digest2(credentials.clientId);
20988
+ const installationDigest = digest3(credentials.clientId);
20119
20989
  const versions = /* @__PURE__ */ new Map(), controllers = /* @__PURE__ */ new Map(), catalogs = /* @__PURE__ */ new Map(), inflight = /* @__PURE__ */ new Map();
20120
20990
  const knowledgeVersions = /* @__PURE__ */ new Map(), upstream = client.getServerCapabilities?.() ?? {};
20121
- let platformDigest, accountDigest, directory, directoryRead, sequence = 0, hostEpoch;
20991
+ let platformDigest, accountDigest, directory2, directoryRead, sequence = 0, hostEpoch;
20122
20992
  function catalog(channel, version3, order) {
20123
20993
  if (typeof version3 !== "string" || !digestPattern.test(version3)) return;
20124
20994
  const old = catalogs.get(channel);
@@ -20135,7 +21005,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20135
21005
  const v2 = result?._meta?.["promptframe.creation"];
20136
21006
  if (!v2 || v2.contractVersion !== "creation-transport-metadata/v1" || !digestPattern.test(v2.platformDigest) || platformDigest && v2.platformDigest !== platformDigest || v2.installationDigest !== installationDigest || !digestPattern.test(v2.accountDigest) || !digestPattern.test(v2.controllerDigest)) return null;
20137
21007
  const thread = params._meta?.threadId?.toLowerCase();
20138
- if (thread ? v2.host?.kind !== host.kind || v2.host.threadDigest !== digest2(thread) : v2.host?.kind !== "legacy") return null;
21008
+ if (thread ? v2.host?.kind !== host.kind || v2.host.threadDigest !== digest3(thread) : v2.host?.kind !== "legacy") return null;
20139
21009
  for (const field of ["projectId", "sessionId"]) if (params.arguments?.[field] !== void 0 && v2[field] !== params.arguments[field]) return null;
20140
21010
  if (accountDigest && accountDigest !== v2.accountDigest) return null;
20141
21011
  const controllerKey = thread ?? "legacy", prior = controllers.get(controllerKey);
@@ -20153,7 +21023,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20153
21023
  const key = keyFor(target), c = v2.control;
20154
21024
  if (!key || !c || !Number.isSafeInteger(c.controlVersion) || c.controlVersion <= 0 || !["web", "client"].includes(c.editor?.kind) || typeof c.editor.isCurrentClient !== "boolean" || c.editor.kind === "web" && c.editor.isCurrentClient) return v2;
20155
21025
  const old = versions.get(key), version3 = c.controlVersion, owned = c.editor.kind === "client" && c.editor.isCurrentClient;
20156
- const authorityRead = directory?.tools.get(params.name)?._meta?.["promptframe.role"] === "control-read";
21026
+ const authorityRead = directory2?.tools.get(params.name)?._meta?.["promptframe.role"] === "control-read";
20157
21027
  if (!old || version3 > old.version) boundedSet(versions, key, { version: version3, owned, needsRead: false, authorityOrder: order });
20158
21028
  else if (version3 === old.version && order >= (old.authorityOrder ?? 0)) {
20159
21029
  const freshRead = !result.isError && authorityRead && order > (old.invalidatedAt ?? 0);
@@ -20162,27 +21032,30 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20162
21032
  }
20163
21033
  return v2;
20164
21034
  }
20165
- async function send(params, binding) {
21035
+ async function send(params, binding, { signal, timeout = 6e4 } = {}) {
20166
21036
  await binding?.assertCurrent();
20167
- const order = ++sequence, result = assertMcpResponseBudget(await client.callTool(params, void 0, { timeout: 6e4 }));
21037
+ const order = ++sequence, result = assertMcpResponseBudget(await client.callTool(params, void 0, { timeout, ...signal ? { signal } : {} }));
20168
21038
  await binding?.assertCurrent();
20169
21039
  return { result, trusted: remember(params, result, order) };
20170
21040
  }
20171
21041
  async function listTools() {
20172
21042
  const order = ++sequence, result = assertMcpResponseBudget(await client.listTools());
20173
21043
  if (result.tools.some((tool) => !accesses.has(tool._meta?.["promptframe.access"]))) throw new CreationClientError("creation.upgrade_required");
20174
- if (!directory || order >= directory.order) directory = { tools: new Map(result.tools.map((t) => [t.name, t])), order };
21044
+ if (!directory2 || order >= directory2.order) directory2 = { tools: new Map(result.tools.map((t) => [t.name, t])), order };
20175
21045
  catalog("outer", result._meta?.["promptframe.catalogVersion"], order);
20176
21046
  return { ...result, tools: result.tools.map((tool) => {
20177
- const p2 = tool.inputSchema.properties;
21047
+ const local = tool._meta?.["promptframe.localFileUpload"];
21048
+ const schema = local?.contractVersion === LOCAL_UPLOAD_PROTOCOL ? local.inputSchema : tool.inputSchema;
21049
+ if (!schema || schema.type !== "object") throw new CreationClientError("creation.upgrade_required");
21050
+ const p2 = schema.properties;
20178
21051
  const { controlVersion: _managed, ...properties } = p2 ?? {};
20179
- return { ...tool, inputSchema: { ...tool.inputSchema, properties: { ...properties, ...host.kind === "claude-code" ? {
21052
+ return { ...tool, inputSchema: { ...schema, properties: { ...properties, ...host.kind === "claude-code" ? {
20180
21053
  [CLAUDE_HOST_PROOF]: { type: "string", pattern: "^[a-f0-9]{64}$", description: "\u7531\u5F53\u524D\u5BBF\u4E3Bhook\u586B\u5165\u7684\u5355\u6B21\u8EAB\u4EFD\u51ED\u8BC1\uFF1B\u8BF7\u4FDD\u7559\uFF0C\u4E0D\u81EA\u884C\u586B\u5199\u3002" }
20181
- } : {} }, ...tool.inputSchema.required ? { required: tool.inputSchema.required.filter((name) => name !== "controlVersion") } : {} } };
21054
+ } : {} }, ...schema.required ? { required: schema.required.filter((name) => name !== "controlVersion") } : {} } };
20182
21055
  }) };
20183
21056
  }
20184
21057
  async function ensureDirectory() {
20185
- if (!directory) {
21058
+ if (!directory2) {
20186
21059
  directoryRead ??= listTools().finally(() => {
20187
21060
  directoryRead = void 0;
20188
21061
  });
@@ -20190,7 +21063,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20190
21063
  }
20191
21064
  }
20192
21065
  function role(name) {
20193
- const found = [...directory.tools.values()].filter((t) => t._meta?.["promptframe.role"] === name);
21066
+ const found = [...directory2.tools.values()].filter((t) => t._meta?.["promptframe.role"] === name);
20194
21067
  if (found.length !== 1) throw new CreationClientError("creation.upgrade_required");
20195
21068
  return found[0].name;
20196
21069
  }
@@ -20236,7 +21109,8 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20236
21109
  readResource: (params) => knowledgeRead("resources", "readResource", params),
20237
21110
  listPrompts: (params) => knowledgeRead("prompts", "listPrompts", params),
20238
21111
  getPrompt: (params) => knowledgeRead("prompts", "getPrompt", params),
20239
- async call(raw) {
21112
+ close: () => localUploads?.close(),
21113
+ async call(raw, { signal } = {}) {
20240
21114
  for (const field of ["threadId", "controller", "clientDigest", "token", "controlVersion"]) if (Object.hasOwn(raw.arguments ?? {}, field))
20241
21115
  throw new CreationClientError("creation.transport_authority_managed_by_bridge");
20242
21116
  let binding = { host, arguments: raw.arguments, assertCurrent: async () => {
@@ -20256,7 +21130,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20256
21130
  raw = { ...raw, arguments: binding.arguments };
20257
21131
  await ensureDirectory();
20258
21132
  await binding.assertCurrent();
20259
- const definition = directory.tools.get(raw.name);
21133
+ const definition = directory2.tools.get(raw.name);
20260
21134
  if (!definition) throw new CreationClientError("creation.tool_unavailable");
20261
21135
  const access2 = definition._meta["promptframe.access"], managed = Object.hasOwn(definition.inputSchema.properties ?? {}, "controlVersion");
20262
21136
  let params = hostParameters(raw, binding.host, "independent-read");
@@ -20277,6 +21151,31 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20277
21151
  resolvedControl = observed.trusted?.control;
20278
21152
  }
20279
21153
  hostParameters(raw, binding.host, effectiveAccess);
21154
+ const local = definition._meta["promptframe.localFileUpload"];
21155
+ if (local?.contractVersion === LOCAL_UPLOAD_PROTOCOL) {
21156
+ if (!localUploads) throw new CreationClientError("creation.upgrade_required");
21157
+ const { projectId, sessionId } = params.arguments ?? {};
21158
+ if (typeof projectId !== "string" || typeof sessionId !== "string") throw new CreationClientError("creation.request_invalid");
21159
+ const observed = await send({ name: role("control-read"), _meta: params._meta, arguments: { projectId, sessionId, pageSize: 1 } }, binding);
21160
+ if (observed.result.isError) return observed.result;
21161
+ if (!observed.trusted) throw new CreationClientError("creation.access_unverified");
21162
+ const value2 = await localUploads.call({
21163
+ input: params.arguments,
21164
+ binding,
21165
+ signal,
21166
+ scope: {
21167
+ platform: observed.trusted.platformDigest,
21168
+ account: observed.trusted.accountDigest,
21169
+ installation: installationDigest,
21170
+ host: binding.host.kind,
21171
+ thread: params._meta.threadId.toLowerCase(),
21172
+ projectId,
21173
+ sessionId
21174
+ },
21175
+ send: (transfer, options) => send({ name: params.name, _meta: params._meta, arguments: { projectId, sessionId, transfer } }, binding, { timeout: 3e4, ...options })
21176
+ });
21177
+ return assertMcpResponseBudget({ content: [{ type: "text", text: JSON.stringify(value2) }] });
21178
+ }
20280
21179
  const key = keyFor(params);
20281
21180
  let outgoing = params;
20282
21181
  if (managed) {
@@ -20316,7 +21215,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20316
21215
  }
20317
21216
 
20318
21217
  // lib/runtime-bootstrap.mjs
20319
- import { createHash as createHash5, randomBytes as randomBytes3 } from "node:crypto";
21218
+ import { createHash as createHash7, randomBytes as randomBytes4 } from "node:crypto";
20320
21219
  import { gunzipSync } from "node:zlib";
20321
21220
 
20322
21221
  // node_modules/tar/dist/esm/index.min.js
@@ -23289,18 +24188,18 @@ var To = (s3) => {
23289
24188
  };
23290
24189
 
23291
24190
  // lib/runtime-bootstrap.mjs
23292
- import { lstat as lstat4, mkdir as mkdir3, open as open3, readFile as readFile4, readdir as readdir2, rename as rename3, rm, statfs } from "node:fs/promises";
24191
+ import { lstat as lstat6, mkdir as mkdir4, open as open5, readFile as readFile5, readdir as readdir3, rename as rename4, rm, statfs } from "node:fs/promises";
23293
24192
  import { execFile } from "node:child_process";
23294
24193
  import { promisify } from "node:util";
23295
- import path5 from "node:path";
24194
+ import path8 from "node:path";
23296
24195
 
23297
24196
  // lib/runtime-package.mjs
23298
- import { lstat as lstat3, readdir, readFile as readFile3 } from "node:fs/promises";
23299
- import { createHash as createHash4 } from "node:crypto";
23300
- import path4 from "node:path";
24197
+ import { lstat as lstat5, readdir as readdir2, readFile as readFile4 } from "node:fs/promises";
24198
+ import { createHash as createHash6 } from "node:crypto";
24199
+ import path7 from "node:path";
23301
24200
  var RUNTIME_PACKAGE_ENTRIES = Object.freeze(["package.json", "README.md", "LICENSE", "bin", "dist", "lib", "skills", "docs", ".codex-plugin", ".mcp.json"]);
23302
24201
  var OPTIONAL_HOST_ENTRIES = Object.freeze([".claude-plugin", ".claude-mcp.json"]);
23303
- var hash2 = (b2) => createHash4("sha256").update(b2).digest("hex");
24202
+ var hash2 = (b2) => createHash6("sha256").update(b2).digest("hex");
23304
24203
  var invalid = (code) => {
23305
24204
  throw new CreationClientError("installation." + code);
23306
24205
  };
@@ -23309,7 +24208,7 @@ async function inspectRuntimePackage(root, { entries } = {}) {
23309
24208
  entries = [...RUNTIME_PACKAGE_ENTRIES];
23310
24209
  for (const name of OPTIONAL_HOST_ENTRIES) {
23311
24210
  try {
23312
- await lstat3(path4.join(root, name));
24211
+ await lstat5(path7.join(root, name));
23313
24212
  entries.push(name);
23314
24213
  } catch (e) {
23315
24214
  if (e.code !== "ENOENT") throw e;
@@ -23321,19 +24220,19 @@ async function inspectRuntimePackage(root, { entries } = {}) {
23321
24220
  async function walk(relative) {
23322
24221
  let s3;
23323
24222
  try {
23324
- s3 = await lstat3(path4.join(root, relative));
24223
+ s3 = await lstat5(path7.join(root, relative));
23325
24224
  } catch (error4) {
23326
24225
  if (error4.code !== "ENOENT") throw error4;
23327
24226
  }
23328
24227
  if (!s3 || s3.isSymbolicLink()) invalid("package_file_invalid");
23329
24228
  if (s3.isDirectory()) {
23330
- for (const name of (await readdir(path4.join(root, relative))).sort()) {
24229
+ for (const name of (await readdir2(path7.join(root, relative))).sort()) {
23331
24230
  if (name === "node_modules" || name === "credentials.json" || name.startsWith(".env")) invalid("package_file_invalid");
23332
- await walk(path4.join(relative, name));
24231
+ await walk(path7.join(relative, name));
23333
24232
  }
23334
24233
  } else if (s3.isFile()) {
23335
24234
  if (s3.size > 32 * 1024 * 1024) invalid("package_too_large");
23336
- const body = await readFile3(path4.join(root, relative));
24235
+ const body = await readFile4(path7.join(root, relative));
23337
24236
  bytes2 += body.length;
23338
24237
  if (files.length >= 1024 || bytes2 > 32 * 1024 * 1024) invalid("package_too_large");
23339
24238
  files.push({ path: relative, bytes: body.length, sha256: hash2(body), body });
@@ -23350,7 +24249,7 @@ async function inspectRuntimePackage(root, { entries } = {}) {
23350
24249
  files,
23351
24250
  version: pkg.version,
23352
24251
  hosts: claude ? ["codex", "claude-code"] : ["codex"],
23353
- payloadDigest: hash2(JSON.stringify(files.map(({ path: path14, bytes: bytes3, sha256 }) => ({ path: path14, bytes: bytes3, sha256 }))))
24252
+ payloadDigest: hash2(JSON.stringify(files.map(({ path: path17, bytes: bytes3, sha256 }) => ({ path: path17, bytes: bytes3, sha256 }))))
23354
24253
  };
23355
24254
  }
23356
24255
 
@@ -23360,7 +24259,7 @@ var REGISTRY = "https://registry.npmjs.org";
23360
24259
  var MAX_ARCHIVE = 8 * 1024 * 1024;
23361
24260
  var MAX_PAYLOAD = 32 * 1024 * 1024;
23362
24261
  var MAX_TAR = 36 * 1024 * 1024;
23363
- var hash3 = (b2) => createHash5("sha256").update(b2).digest("hex");
24262
+ var hash3 = (b2) => createHash7("sha256").update(b2).digest("hex");
23364
24263
  var execute = promisify(execFile);
23365
24264
  var error3 = (code) => new CreationClientError("creation." + code);
23366
24265
  var version2 = (v2) => {
@@ -23385,29 +24284,29 @@ var snapshot = (payload) => ({
23385
24284
  version: payload.version,
23386
24285
  hosts: payload.hosts,
23387
24286
  payloadDigest: payload.payloadDigest,
23388
- files: payload.files.map(({ path: path14, bytes: bytes2, sha256 }) => ({ path: path14, bytes: bytes2, sha256 }))
24287
+ files: payload.files.map(({ path: path17, bytes: bytes2, sha256 }) => ({ path: path17, bytes: bytes2, sha256 }))
23389
24288
  });
23390
24289
  async function info(file) {
23391
24290
  try {
23392
- return await lstat4(file);
24291
+ return await lstat6(file);
23393
24292
  } catch (e) {
23394
24293
  if (e.code === "ENOENT") return null;
23395
24294
  throw e;
23396
24295
  }
23397
24296
  }
23398
24297
  async function privateDirectory2(dir) {
23399
- await mkdir3(dir, { recursive: true, mode: 448 });
23400
- const s3 = await lstat4(dir);
24298
+ await mkdir4(dir, { recursive: true, mode: 448 });
24299
+ const s3 = await lstat6(dir);
23401
24300
  if (!s3.isDirectory() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63) throw error3("runtime_cache_owner_invalid");
23402
24301
  }
23403
24302
  async function privateJSON(file) {
23404
24303
  const s3 = await info(file);
23405
24304
  if (!s3) return null;
23406
24305
  if (!s3.isFile() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63 || s3.size > 512 * 1024) throw error3("runtime_cache_invalid");
23407
- return JSON.parse(await readFile4(file, "utf8"));
24306
+ return JSON.parse(await readFile5(file, "utf8"));
23408
24307
  }
23409
- async function syncDirectory(dir) {
23410
- const fd = await open3(dir, "r");
24308
+ async function syncDirectory2(dir) {
24309
+ const fd = await open5(dir, "r");
23411
24310
  try {
23412
24311
  await fd.sync();
23413
24312
  } finally {
@@ -23415,7 +24314,7 @@ async function syncDirectory(dir) {
23415
24314
  }
23416
24315
  }
23417
24316
  async function exclusiveJSON(file, value2) {
23418
- const fd = await open3(file, "wx", 384);
24317
+ const fd = await open5(file, "wx", 384);
23419
24318
  try {
23420
24319
  await fd.writeFile(JSON.stringify(value2) + "\n");
23421
24320
  await fd.sync();
@@ -23432,19 +24331,19 @@ function checkedRuntimeMetadata(value2, expectedVersion) {
23432
24331
  if (Buffer.from(encoded, "base64").toString("base64") !== encoded) throw error3("runtime_registry_identity_invalid");
23433
24332
  return { version: expectedVersion, integrity: value2.dist.integrity, tarball };
23434
24333
  }
23435
- async function boundedGet(url2, { fetchImpl = fetch, signal, maxBytes, timeoutMs }) {
24334
+ async function boundedGet(url2, { fetchImpl = fetch, signal, maxBytes: maxBytes2, timeoutMs }) {
23436
24335
  const controller = new AbortController(), abort = () => controller.abort(), timer = setTimeout(abort, timeoutMs);
23437
24336
  signal?.addEventListener("abort", abort, { once: true });
23438
24337
  if (signal?.aborted) abort();
23439
24338
  let response;
23440
24339
  try {
23441
24340
  response = await fetchImpl(url2, { signal: controller.signal, redirect: "error" });
23442
- if (response.status !== 200 || Number(response.headers.get("content-length") ?? 0) > maxBytes || !response.body) throw error3("runtime_fetch_unavailable");
24341
+ if (response.status !== 200 || Number(response.headers.get("content-length") ?? 0) > maxBytes2 || !response.body) throw error3("runtime_fetch_unavailable");
23443
24342
  const chunks = [];
23444
24343
  let count = 0;
23445
24344
  for await (const chunk of response.body) {
23446
24345
  count += chunk.length;
23447
- if (count > maxBytes) throw error3("runtime_download_capacity");
24346
+ if (count > maxBytes2) throw error3("runtime_download_capacity");
23448
24347
  chunks.push(Buffer.from(chunk));
23449
24348
  }
23450
24349
  return Buffer.concat(chunks, count);
@@ -23459,7 +24358,7 @@ async function boundedGet(url2, { fetchImpl = fetch, signal, maxBytes, timeoutMs
23459
24358
  }
23460
24359
  }
23461
24360
  async function readRuntimeArchive(archive, metadata) {
23462
- if (!Buffer.isBuffer(archive) || archive.length > MAX_ARCHIVE || "sha512-" + createHash5("sha512").update(archive).digest("base64") !== metadata.integrity) throw error3("runtime_integrity_invalid");
24361
+ if (!Buffer.isBuffer(archive) || archive.length > MAX_ARCHIVE || "sha512-" + createHash7("sha512").update(archive).digest("base64") !== metadata.integrity) throw error3("runtime_integrity_invalid");
23463
24362
  let raw;
23464
24363
  try {
23465
24364
  raw = gunzipSync(archive, { maxOutputLength: MAX_TAR });
@@ -23467,32 +24366,32 @@ async function readRuntimeArchive(archive, metadata) {
23467
24366
  throw error3("runtime_archive_invalid");
23468
24367
  }
23469
24368
  const files = [], names = /* @__PURE__ */ new Set();
23470
- let total = 0, entries = 0, failure2;
24369
+ let total = 0, entries = 0, failure3;
23471
24370
  const parser = Ct({ strict: true, onReadEntry: (entry) => {
23472
24371
  const name = entry.path;
23473
- if (++entries > 2048 || !["File", "Directory"].includes(entry.type) || !Number.isSafeInteger(entry.size) || entry.size < 0 || entry.size > MAX_PAYLOAD || typeof name !== "string" || name.length > 240 || !name.startsWith("package/") || name.includes("\\") || /[\x00-\x1f\x7f]/.test(name)) failure2 = error3("runtime_archive_invalid");
24372
+ if (++entries > 2048 || !["File", "Directory"].includes(entry.type) || !Number.isSafeInteger(entry.size) || entry.size < 0 || entry.size > MAX_PAYLOAD || typeof name !== "string" || name.length > 240 || !name.startsWith("package/") || name.includes("\\") || /[\x00-\x1f\x7f]/.test(name)) failure3 = error3("runtime_archive_invalid");
23474
24373
  const relative = name.slice(8).replace(/\/$/, "");
23475
24374
  if (relative && (relative.normalize("NFC") !== relative || /[<>:"|?*]/.test(relative) || relative.split("/").some((p2) => !p2 || p2 === "." || p2 === ".." || /[. ]$/.test(p2) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p2) || p2 === "node_modules" || p2 === "credentials.json" || p2.startsWith(".env")) || !roots.has(relative.split("/")[0])))
23476
- failure2 = error3("runtime_archive_invalid");
24375
+ failure3 = error3("runtime_archive_invalid");
23477
24376
  const portableName = relative.toLowerCase();
23478
- if (names.has(portableName)) failure2 = error3("runtime_archive_invalid");
24377
+ if (names.has(portableName)) failure3 = error3("runtime_archive_invalid");
23479
24378
  names.add(portableName);
23480
24379
  if (entry.type === "Directory") {
23481
- if (entry.size !== 0) failure2 = error3("runtime_archive_invalid");
24380
+ if (entry.size !== 0) failure3 = error3("runtime_archive_invalid");
23482
24381
  return;
23483
24382
  }
23484
24383
  total += entry.size;
23485
- if (total > MAX_PAYLOAD || files.length >= 1024 || !relative) failure2 = error3("runtime_archive_capacity");
24384
+ if (total > MAX_PAYLOAD || files.length >= 1024 || !relative) failure3 = error3("runtime_archive_capacity");
23486
24385
  const chunks = [];
23487
24386
  let bytes2 = 0;
23488
24387
  entry.on("data", (chunk) => {
23489
24388
  bytes2 += chunk.length;
23490
- if (bytes2 > entry.size) failure2 = error3("runtime_archive_invalid");
23491
- if (!failure2) chunks.push(Buffer.from(chunk));
24389
+ if (bytes2 > entry.size) failure3 = error3("runtime_archive_invalid");
24390
+ if (!failure3) chunks.push(Buffer.from(chunk));
23492
24391
  });
23493
24392
  entry.on("end", () => {
23494
- if (bytes2 !== entry.size) failure2 = error3("runtime_archive_invalid");
23495
- if (!failure2) files.push({ path: relative, body: Buffer.concat(chunks, bytes2) });
24393
+ if (bytes2 !== entry.size) failure3 = error3("runtime_archive_invalid");
24394
+ if (!failure3) files.push({ path: relative, body: Buffer.concat(chunks, bytes2) });
23496
24395
  });
23497
24396
  } });
23498
24397
  await new Promise((resolve, reject) => {
@@ -23500,17 +24399,17 @@ async function readRuntimeArchive(archive, metadata) {
23500
24399
  parser.once("end", resolve);
23501
24400
  parser.end(raw);
23502
24401
  });
23503
- if (failure2) throw failure2;
24402
+ if (failure3) throw failure3;
23504
24403
  if (!files.length || files.length > 1024) throw error3("runtime_archive_invalid");
23505
24404
  return files;
23506
24405
  }
23507
24406
  async function cacheLock(root, signal) {
23508
- const name = path5.join(root, "prepare.lock"), end = Date.now() + 5e3;
24407
+ const name = path8.join(root, "prepare.lock"), end = Date.now() + 5e3;
23509
24408
  let fd;
23510
24409
  while (!fd) {
23511
24410
  signal?.throwIfAborted();
23512
24411
  try {
23513
- fd = await open3(name, "wx", 384);
24412
+ fd = await open5(name, "wx", 384);
23514
24413
  } catch (e) {
23515
24414
  if (e.code !== "EEXIST") throw e;
23516
24415
  if (Date.now() >= end) throw error3("runtime_cache_busy");
@@ -23521,7 +24420,7 @@ async function cacheLock(root, signal) {
23521
24420
  try {
23522
24421
  await fd.writeFile(JSON.stringify({ pid: process.pid, createdAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n");
23523
24422
  await fd.sync();
23524
- await syncDirectory(root);
24423
+ await syncDirectory2(root);
23525
24424
  } catch (e) {
23526
24425
  await fd.close();
23527
24426
  const now = await info(name);
@@ -23538,10 +24437,10 @@ async function cacheLock(root, signal) {
23538
24437
  async function verifyCached(target, metadata, hostKind) {
23539
24438
  if (!await info(target)) return null;
23540
24439
  await privateDirectory2(target);
23541
- const manifest = await privateJSON(path5.join(target, "runtime.json"));
24440
+ const manifest = await privateJSON(path8.join(target, "runtime.json"));
23542
24441
  if (!manifest || manifest.contractVersion !== "creation-verified-runtime/v1" || manifest.version !== metadata.version || manifest.integrity !== metadata.integrity)
23543
24442
  throw error3("runtime_cache_invalid");
23544
- const names = (await readdir2(target)).filter((name) => name !== "runtime.json").sort();
24443
+ const names = (await readdir3(target)).filter((name) => name !== "runtime.json").sort();
23545
24444
  if (names.some((name) => !roots.has(name)) || RUNTIME_PACKAGE_ENTRIES.some((name) => !names.includes(name))) throw error3("runtime_cache_invalid");
23546
24445
  const payload = await inspectRuntimePackage(target, { entries: names });
23547
24446
  if (!payload.hosts.includes(hostKind)) throw error3("runtime_host_unsupported");
@@ -23549,33 +24448,33 @@ async function verifyCached(target, metadata, hostKind) {
23549
24448
  return { version: payload.version, root: target, integrity: metadata.integrity, reused: true };
23550
24449
  }
23551
24450
  async function checkedVersionIndex(cacheRoot, metadata) {
23552
- const old = await privateJSON(path5.join(cacheRoot, "version-" + metadata.version + ".json"));
24451
+ const old = await privateJSON(path8.join(cacheRoot, "version-" + metadata.version + ".json"));
23553
24452
  if (old && JSON.stringify(old) !== JSON.stringify(metadata)) throw error3("runtime_registry_identity_conflict");
23554
24453
  return old;
23555
24454
  }
23556
24455
  async function prepareVerifiedRuntime(metadata, { cacheRoot, fetchImpl = fetch, signal, checkRuntime, hostKind = "codex" } = {}) {
23557
24456
  if (!["codex", "claude-code"].includes(hostKind)) throw error3("runtime_host_unsupported");
23558
- if (!path5.isAbsolute(cacheRoot ?? "")) throw error3("runtime_cache_owner_invalid");
24457
+ if (!path8.isAbsolute(cacheRoot ?? "")) throw error3("runtime_cache_owner_invalid");
23559
24458
  metadata = checkedRuntimeMetadata({ name: PACKAGE, version: metadata.version, dist: metadata }, metadata.version);
23560
24459
  await privateDirectory2(cacheRoot);
23561
24460
  await checkedVersionIndex(cacheRoot, metadata);
23562
- const target = path5.join(cacheRoot, metadata.version + "-" + hash3(metadata.integrity)), existing = await verifyCached(target, metadata, hostKind);
24461
+ const target = path8.join(cacheRoot, metadata.version + "-" + hash3(metadata.integrity)), existing = await verifyCached(target, metadata, hostKind);
23563
24462
  if (existing) return existing;
23564
24463
  const archive = await boundedGet(metadata.tarball, { fetchImpl, signal, maxBytes: MAX_ARCHIVE, timeoutMs: 15e3 });
23565
24464
  const files = await readRuntimeArchive(archive, metadata), release = await cacheLock(cacheRoot, signal);
23566
- const temporary = path5.join(cacheRoot, ".partial-" + randomBytes3(12).toString("hex"));
24465
+ const temporary = path8.join(cacheRoot, ".partial-" + randomBytes4(12).toString("hex"));
23567
24466
  try {
23568
24467
  const index = await checkedVersionIndex(cacheRoot, metadata);
23569
24468
  const found = await verifyCached(target, metadata, hostKind);
23570
24469
  if (found) return found;
23571
24470
  const space = await statfs(cacheRoot, { bigint: true }), needed = BigInt(files.reduce((n, f2) => n + f2.body.length, 0) + 4 * 1024 * 1024);
23572
24471
  if (space.bavail * space.bsize < needed) throw error3("runtime_cache_capacity");
23573
- await mkdir3(temporary, { mode: 448 });
24472
+ await mkdir4(temporary, { mode: 448 });
23574
24473
  for (const file of files) {
23575
24474
  signal?.throwIfAborted();
23576
- const dest = path5.join(temporary, ...file.path.split("/"));
23577
- await mkdir3(path5.dirname(dest), { recursive: true, mode: 448 });
23578
- const fd = await open3(dest, "wx", 384);
24475
+ const dest = path8.join(temporary, ...file.path.split("/"));
24476
+ await mkdir4(path8.dirname(dest), { recursive: true, mode: 448 });
24477
+ const fd = await open5(dest, "wx", 384);
23579
24478
  try {
23580
24479
  await fd.writeFile(file.body);
23581
24480
  await fd.sync();
@@ -23594,28 +24493,28 @@ async function prepareVerifiedRuntime(metadata, { cacheRoot, fetchImpl = fetch,
23594
24493
  else {
23595
24494
  const result = await execute(
23596
24495
  process.execPath,
23597
- [path5.join(temporary, "bin/promptframe-creation.mjs"), "--version"],
24496
+ [path8.join(temporary, "bin/promptframe-creation.mjs"), "--version"],
23598
24497
  { timeout: 5e3, maxBuffer: 65536, windowsHide: true, signal, env: {
23599
24498
  ...process.env,
23600
- PROMPTFRAME_CREATION_CONFIG: path5.join(temporary, "no-credentials.json")
24499
+ PROMPTFRAME_CREATION_CONFIG: path8.join(temporary, "no-credentials.json")
23601
24500
  } }
23602
24501
  );
23603
24502
  if (result.stdout.trim() !== metadata.version || result.stderr.trim()) throw error3("runtime_package_version_invalid");
23604
24503
  }
23605
24504
  signal?.throwIfAborted();
23606
- await exclusiveJSON(path5.join(temporary, "runtime.json"), {
24505
+ await exclusiveJSON(path8.join(temporary, "runtime.json"), {
23607
24506
  contractVersion: "creation-verified-runtime/v1",
23608
24507
  version: metadata.version,
23609
24508
  integrity: metadata.integrity,
23610
24509
  payload: snapshot(payload)
23611
24510
  });
23612
- await syncDirectory(temporary);
24511
+ await syncDirectory2(temporary);
23613
24512
  if (!index) {
23614
- await exclusiveJSON(path5.join(cacheRoot, "version-" + metadata.version + ".json"), metadata);
23615
- await syncDirectory(cacheRoot);
24513
+ await exclusiveJSON(path8.join(cacheRoot, "version-" + metadata.version + ".json"), metadata);
24514
+ await syncDirectory2(cacheRoot);
23616
24515
  }
23617
- await rename3(temporary, target);
23618
- await syncDirectory(cacheRoot);
24516
+ await rename4(temporary, target);
24517
+ await syncDirectory2(cacheRoot);
23619
24518
  return { version: metadata.version, root: target, integrity: metadata.integrity, reused: false };
23620
24519
  } finally {
23621
24520
  try {
@@ -23653,7 +24552,7 @@ async function selectBridgeRuntime({ policy, currentVersion, lockedVersion, reso
23653
24552
  const raw = await boundedGet(REGISTRY + "/@promptframe%2fcreation/" + target, { fetchImpl, signal, maxBytes: 256 * 1024, timeoutMs: 5e3 });
23654
24553
  metadata = checkedRuntimeMetadata(JSON.parse(raw), target);
23655
24554
  } catch (e) {
23656
- const prior = await privateJSON(path5.join(cacheRoot, "version-" + target + ".json"));
24555
+ const prior = await privateJSON(path8.join(cacheRoot, "version-" + target + ".json"));
23657
24556
  if (!prior) throw e;
23658
24557
  metadata = checkedRuntimeMetadata({ name: PACKAGE, version: target, dist: prior }, target);
23659
24558
  metadataSource = "previously-verified-cache";
@@ -23679,16 +24578,16 @@ async function selectBridgeRuntime({ policy, currentVersion, lockedVersion, reso
23679
24578
 
23680
24579
  // lib/runtime-launch.mjs
23681
24580
  import { spawn } from "node:child_process";
23682
- import path6 from "node:path";
24581
+ import path9 from "node:path";
23683
24582
  async function launchSelectedBridge(selection, { host, configFile: configFile2, spawnImpl = spawn, env = process.env } = {}) {
23684
- if (!path6.isAbsolute(selection.root ?? "") || !path6.isAbsolute(configFile2 ?? "") || !["codex", "claude-code"].includes(host?.kind))
24583
+ if (!path9.isAbsolute(selection.root ?? "") || !path9.isAbsolute(configFile2 ?? "") || !["codex", "claude-code"].includes(host?.kind))
23685
24584
  throw new CreationClientError("creation.runtime_launch_invalid");
23686
24585
  let child;
23687
24586
  try {
23688
24587
  child = spawnImpl(
23689
24588
  process.execPath,
23690
24589
  [
23691
- path6.join(selection.root, "bin/promptframe-creation.mjs"),
24590
+ path9.join(selection.root, "bin/promptframe-creation.mjs"),
23692
24591
  "bridge",
23693
24592
  "--config",
23694
24593
  configFile2,
@@ -23730,10 +24629,10 @@ async function launchSelectedBridge(selection, { host, configFile: configFile2,
23730
24629
  // lib/user-installation.mjs
23731
24630
  import { execFile as execFile2 } from "node:child_process";
23732
24631
  import { promisify as promisify2 } from "node:util";
23733
- import { createHash as createHash6, randomBytes as randomBytes4 } from "node:crypto";
23734
- import { lstat as lstat5, mkdir as mkdir4, readdir as readdir3, readFile as readFile5, writeFile as writeFile2, rename as rename4, rm as rm2, open as open4 } from "node:fs/promises";
24632
+ import { createHash as createHash8, randomBytes as randomBytes5 } from "node:crypto";
24633
+ import { lstat as lstat7, mkdir as mkdir5, readdir as readdir4, readFile as readFile6, writeFile as writeFile2, rename as rename5, rm as rm2, open as open6 } from "node:fs/promises";
23735
24634
  import { homedir as homedir4 } from "node:os";
23736
- import path7 from "node:path";
24635
+ import path10 from "node:path";
23737
24636
 
23738
24637
  // node_modules/smol-toml/dist/error.js
23739
24638
  function getLineColFromPtr(string4, ptr) {
@@ -24495,14 +25394,14 @@ var HAS_WELLFORMED = !!"".isWellFormed;
24495
25394
 
24496
25395
  // lib/user-installation.mjs
24497
25396
  var execute2 = promisify2(execFile2);
24498
- var hash4 = (b2) => createHash6("sha256").update(b2).digest("hex");
25397
+ var hash4 = (b2) => createHash8("sha256").update(b2).digest("hex");
24499
25398
  var InstallationError = class extends CreationClientError {
24500
25399
  constructor(code, details) {
24501
25400
  super("installation." + code);
24502
25401
  this.details = details;
24503
25402
  }
24504
25403
  };
24505
- var fail = (code, details) => {
25404
+ var fail4 = (code, details) => {
24506
25405
  throw new InstallationError(code, details);
24507
25406
  };
24508
25407
  var installationErrorDetails = (error4) => error4 instanceof InstallationError ? error4.details : void 0;
@@ -24526,16 +25425,16 @@ function pinnedGitSource(source) {
24526
25425
  const refKind = /^[a-f0-9]{40}$/i.test(ref) ? "commit" : /^(?:refs\/tags\/)?creation-v\d+\.\d+\.\d+$/.test(ref) ? "tag" : null;
24527
25426
  return refKind ? { refName: ref, refKind } : null;
24528
25427
  }
24529
- var json = async (file) => JSON.parse(await readFile5(file, "utf8"));
25428
+ var json = async (file) => JSON.parse(await readFile6(file, "utf8"));
24530
25429
  var pause2 = (ms2) => new Promise((r) => setTimeout(r, ms2));
24531
25430
  function validProfile(profile) {
24532
- if (typeof profile !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(profile)) fail("profile_invalid");
25431
+ if (typeof profile !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(profile)) fail4("profile_invalid");
24533
25432
  return profile;
24534
25433
  }
24535
25434
  function profileCredentialsPath(profile = "default", env = process.env) {
24536
25435
  validProfile(profile);
24537
- return profile === "default" ? credentialsPath(env) : path7.resolve(
24538
- env.XDG_CONFIG_HOME ?? path7.join(homedir4(), ".config"),
25436
+ return profile === "default" ? credentialsPath(env) : path10.resolve(
25437
+ env.XDG_CONFIG_HOME ?? path10.join(homedir4(), ".config"),
24539
25438
  "promptframe-creation",
24540
25439
  "profiles",
24541
25440
  profile,
@@ -24544,58 +25443,58 @@ function profileCredentialsPath(profile = "default", env = process.env) {
24544
25443
  }
24545
25444
  async function info2(file) {
24546
25445
  try {
24547
- return await lstat5(file);
25446
+ return await lstat7(file);
24548
25447
  } catch (e) {
24549
25448
  if (e.code === "ENOENT") return null;
24550
25449
  throw e;
24551
25450
  }
24552
25451
  }
24553
25452
  async function privateDirectory3(dir) {
24554
- await mkdir4(dir, { recursive: true, mode: 448 });
24555
- const s3 = await lstat5(dir);
24556
- if (!s3.isDirectory() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63) fail("private_owner_required");
25453
+ await mkdir5(dir, { recursive: true, mode: 448 });
25454
+ const s3 = await lstat7(dir);
25455
+ if (!s3.isDirectory() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63) fail4("private_owner_required");
24557
25456
  }
24558
25457
  async function privateRead2(file) {
24559
25458
  const s3 = await info2(file);
24560
25459
  if (!s3) return null;
24561
- if (!s3.isFile() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63 || s3.size > 512 * 1024) fail("state_invalid");
25460
+ if (!s3.isFile() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63 || s3.size > 512 * 1024) fail4("state_invalid");
24562
25461
  return json(file);
24563
25462
  }
24564
25463
  async function packageJSON(file) {
24565
25464
  const s3 = await info2(file);
24566
- if (!s3?.isFile() || s3.isSymbolicLink() || s3.size > 512 * 1024) fail("installed_files_invalid");
25465
+ if (!s3?.isFile() || s3.isSymbolicLink() || s3.size > 512 * 1024) fail4("installed_files_invalid");
24567
25466
  return json(file);
24568
25467
  }
24569
25468
  function sameTransport(actual, expected) {
24570
- return actual?.type === "stdio" && actual.command === expected.command && typeof actual.cwd === "string" && path7.resolve(actual.cwd) === path7.resolve(expected.cwd) && JSON.stringify(actual.args) === JSON.stringify(expected.args) && JSON.stringify(actual.env_vars ?? []) === JSON.stringify(expected.env_vars ?? []) && !Object.keys(actual.env ?? {}).length;
25469
+ return actual?.type === "stdio" && actual.command === expected.command && typeof actual.cwd === "string" && path10.resolve(actual.cwd) === path10.resolve(expected.cwd) && JSON.stringify(actual.args) === JSON.stringify(expected.args) && JSON.stringify(actual.env_vars ?? []) === JSON.stringify(expected.env_vars ?? []) && !Object.keys(actual.env ?? {}).length;
24571
25470
  }
24572
25471
  async function managedTransport(installed, versions, serverName, profile, configFile2) {
24573
25472
  if (!installed) return null;
24574
25473
  const root = installed.source?.path;
24575
- if (installed.source?.source !== "local" || typeof root !== "string" || !/^\d+\.\d+\.\d+$/.test(installed.version ?? "") || root !== path7.join(versions, installed.version)) fail("existing_registration_requires_review");
24576
- const directory = await info2(root), definition = await info2(path7.join(root, ".mcp.json"));
24577
- if (!directory?.isDirectory() || directory.isSymbolicLink() || !definition?.isFile() || definition.isSymbolicLink()) fail("installed_files_invalid");
24578
- const ready = await privateRead2(path7.join(root, "installation.json"));
24579
- if (!ready || ready.profile !== profile || ready.configFile !== configFile2 || ready.version !== installed.version) fail("existing_registration_requires_review");
24580
- const bytes2 = await readFile5(path7.join(root, ".mcp.json")), entry = ready.files?.find((x) => x.path === ".mcp.json");
24581
- if (!entry || entry.bytes !== bytes2.length || entry.sha256 !== hash4(bytes2)) fail("installed_files_invalid");
25474
+ if (installed.source?.source !== "local" || typeof root !== "string" || !/^\d+\.\d+\.\d+$/.test(installed.version ?? "") || root !== path10.join(versions, installed.version)) fail4("existing_registration_requires_review");
25475
+ const directory2 = await info2(root), definition = await info2(path10.join(root, ".mcp.json"));
25476
+ if (!directory2?.isDirectory() || directory2.isSymbolicLink() || !definition?.isFile() || definition.isSymbolicLink()) fail4("installed_files_invalid");
25477
+ const ready = await privateRead2(path10.join(root, "installation.json"));
25478
+ if (!ready || ready.profile !== profile || ready.configFile !== configFile2 || ready.version !== installed.version) fail4("existing_registration_requires_review");
25479
+ const bytes2 = await readFile6(path10.join(root, ".mcp.json")), entry = ready.files?.find((x) => x.path === ".mcp.json");
25480
+ if (!entry || entry.bytes !== bytes2.length || entry.sha256 !== hash4(bytes2)) fail4("installed_files_invalid");
24582
25481
  const mcp = JSON.parse(bytes2).mcpServers?.[serverName];
24583
- if (!mcp || typeof mcp.command !== "string" || !mcp.command || mcp.cwd !== root || JSON.stringify(mcp.args) !== JSON.stringify([path7.join(root, "bin/promptframe-creation.mjs"), "bridge", "--config", configFile2])) fail("existing_registration_requires_review");
25482
+ if (!mcp || typeof mcp.command !== "string" || !mcp.command || mcp.cwd !== root || JSON.stringify(mcp.args) !== JSON.stringify([path10.join(root, "bin/promptframe-creation.mjs"), "bridge", "--config", configFile2])) fail4("existing_registration_requires_review");
24584
25483
  return mcp;
24585
25484
  }
24586
25485
  async function officialNpmInstallation(installed, servers, env, profile, configFile2) {
24587
25486
  if (profile !== "default" || configFile2 !== profileCredentialsPath("default", env)) return null;
24588
25487
  const candidates = installed.filter((p3) => p3.enabled === true && p3.name === "promptframe-creation" && p3.pluginId === "promptframe-creation@" + p3.marketplaceName && /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,140}$/.test(p3.marketplaceName ?? "") && /^\d+\.\d+\.\d+$/.test(p3.version ?? "") && p3.source?.source === "npm" && p3.source.package === "@promptframe/creation" && p3.source.version === p3.version && ["https://registry.npmjs.org", "https://registry.npmjs.org/"].includes(p3.source.registry));
24589
- if (candidates.length > 1) fail("existing_registration_requires_review");
25488
+ if (candidates.length > 1) fail4("existing_registration_requires_review");
24590
25489
  if (!candidates.length) return null;
24591
- const p2 = candidates[0], root = path7.join(path7.resolve(env.CODEX_HOME ?? path7.join(homedir4(), ".codex")), "plugins/cache", p2.marketplaceName, p2.name, p2.version);
24592
- const directory = await info2(root);
24593
- if (!directory?.isDirectory() || directory.isSymbolicLink()) fail("installed_files_invalid");
24594
- const pkg = await packageJSON(path7.join(root, "package.json")), manifest = await packageJSON(path7.join(root, ".codex-plugin/plugin.json"));
24595
- if (pkg.name !== "@promptframe/creation" || pkg.version !== p2.version || manifest.name !== p2.name || manifest.version !== p2.version) fail("installed_files_invalid");
24596
- const definition = (await packageJSON(path7.join(root, ".mcp.json"))).mcpServers?.promptframe;
24597
- if (!definition || definition.command !== "node" || definition.cwd !== "." || JSON.stringify(definition.args) !== JSON.stringify(["bin/promptframe-creation.mjs", "bridge"]) || JSON.stringify(definition.env_vars) !== JSON.stringify(["PROMPTFRAME_CREATION_CONFIG", "XDG_CONFIG_HOME"])) fail("legacy_mcp_entry_requires_review");
24598
- if (servers.length !== 1 || servers[0].enabled !== true || !sameTransport(servers[0].transport, { ...definition, cwd: root }) || JSON.stringify(servers[0].transport.env_vars) !== JSON.stringify(definition.env_vars)) fail("legacy_mcp_entry_requires_review");
25490
+ const p2 = candidates[0], root = path10.join(path10.resolve(env.CODEX_HOME ?? path10.join(homedir4(), ".codex")), "plugins/cache", p2.marketplaceName, p2.name, p2.version);
25491
+ const directory2 = await info2(root);
25492
+ if (!directory2?.isDirectory() || directory2.isSymbolicLink()) fail4("installed_files_invalid");
25493
+ const pkg = await packageJSON(path10.join(root, "package.json")), manifest = await packageJSON(path10.join(root, ".codex-plugin/plugin.json"));
25494
+ if (pkg.name !== "@promptframe/creation" || pkg.version !== p2.version || manifest.name !== p2.name || manifest.version !== p2.version) fail4("installed_files_invalid");
25495
+ const definition = (await packageJSON(path10.join(root, ".mcp.json"))).mcpServers?.promptframe;
25496
+ if (!definition || definition.command !== "node" || definition.cwd !== "." || JSON.stringify(definition.args) !== JSON.stringify(["bin/promptframe-creation.mjs", "bridge"]) || JSON.stringify(definition.env_vars) !== JSON.stringify(["PROMPTFRAME_CREATION_CONFIG", "XDG_CONFIG_HOME"])) fail4("legacy_mcp_entry_requires_review");
25497
+ if (servers.length !== 1 || servers[0].enabled !== true || !sameTransport(servers[0].transport, { ...definition, cwd: root }) || JSON.stringify(servers[0].transport.env_vars) !== JSON.stringify(definition.env_vars)) fail4("legacy_mcp_entry_requires_review");
24599
25498
  return {
24600
25499
  version: p2.version,
24601
25500
  profile,
@@ -24610,43 +25509,43 @@ async function officialNpmInstallation(installed, servers, env, profile, configF
24610
25509
  };
24611
25510
  }
24612
25511
  async function atomicJSON(file, value2) {
24613
- const temp = file + "." + randomBytes4(12).toString("hex") + ".tmp";
25512
+ const temp = file + "." + randomBytes5(12).toString("hex") + ".tmp";
24614
25513
  try {
24615
- const out = await open4(temp, "wx", 384);
25514
+ const out = await open6(temp, "wx", 384);
24616
25515
  try {
24617
25516
  await out.writeFile(JSON.stringify(value2, null, 2) + "\n");
24618
25517
  await out.sync();
24619
25518
  } finally {
24620
25519
  await out.close();
24621
25520
  }
24622
- await rename4(temp, file);
24623
- const directory = await open4(path7.dirname(file), "r");
25521
+ await rename5(temp, file);
25522
+ const directory2 = await open6(path10.dirname(file), "r");
24624
25523
  try {
24625
- await directory.sync();
25524
+ await directory2.sync();
24626
25525
  } finally {
24627
- await directory.close();
25526
+ await directory2.close();
24628
25527
  }
24629
25528
  } finally {
24630
25529
  await rm2(temp, { force: true });
24631
25530
  }
24632
25531
  }
24633
25532
  async function acquire(root, signal) {
24634
- const lock = path7.join(root, "install.lock");
25533
+ const lock = path10.join(root, "install.lock");
24635
25534
  const end = Date.now() + 3e4;
24636
25535
  let owned = false;
24637
25536
  while (!owned) {
24638
25537
  signal?.throwIfAborted();
24639
25538
  try {
24640
- await mkdir4(lock, { mode: 448 });
25539
+ await mkdir5(lock, { mode: 448 });
24641
25540
  owned = true;
24642
25541
  } catch (e) {
24643
25542
  if (e.code !== "EEXIST") throw e;
24644
- if (Date.now() >= end) fail("in_progress_or_interrupted_keep_existing");
25543
+ if (Date.now() >= end) fail4("in_progress_or_interrupted_keep_existing");
24645
25544
  await pause2(50);
24646
25545
  }
24647
25546
  }
24648
25547
  try {
24649
- await writeFile2(path7.join(lock, "owner.json"), JSON.stringify({ pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString() }), { flag: "wx", mode: 384 });
25548
+ await writeFile2(path10.join(lock, "owner.json"), JSON.stringify({ pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString() }), { flag: "wx", mode: 384 });
24650
25549
  } catch (e) {
24651
25550
  await rm2(lock, { recursive: true, force: true });
24652
25551
  throw e;
@@ -24665,7 +25564,7 @@ async function runCodexCommand(args2, { env = process.env } = {}) {
24665
25564
  return (await execute2("codex", args2, { env, encoding: "utf8", timeout: timeoutMs, maxBuffer: 2 * 1024 * 1024 })).stdout;
24666
25565
  } catch (e) {
24667
25566
  const cause = e.code === "ENOENT" ? "codex_required" : e.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" ? "command_output_limit" : e.killed ? "command_timeout" : "command_failed";
24668
- fail(cause, {
25567
+ fail4(cause, {
24669
25568
  phase: write ? "registration" : "local_check",
24670
25569
  commandKind: kind,
24671
25570
  elapsedMs: Math.round(performance.now() - start),
@@ -24683,16 +25582,16 @@ async function codexJSON(runCodex, args2) {
24683
25582
  if (typeof body !== "string" || Buffer.byteLength(body) > 2 * 1024 * 1024) throw Error();
24684
25583
  return JSON.parse(body);
24685
25584
  } catch {
24686
- fail("command_json_unconfirmed", { phase: "local_check", commandKind: commandKind(args2), localRegistrationState: "unknown", action: "retry_local_read" });
25585
+ fail4("command_json_unconfirmed", { phase: "local_check", commandKind: commandKind(args2), localRegistrationState: "unknown", action: "retry_local_read" });
24687
25586
  }
24688
25587
  }
24689
25588
  async function relatedPlugins(runCodex, pluginName, env) {
24690
- const related = /* @__PURE__ */ new Set(), registered = /* @__PURE__ */ new Set(), pinnedMarketplaces = /* @__PURE__ */ new Map(), config2 = path7.join(path7.resolve(env.CODEX_HOME ?? path7.join(homedir4(), ".codex")), "config.toml");
25589
+ const related = /* @__PURE__ */ new Set(), registered = /* @__PURE__ */ new Set(), pinnedMarketplaces = /* @__PURE__ */ new Map(), config2 = path10.join(path10.resolve(env.CODEX_HOME ?? path10.join(homedir4(), ".codex")), "config.toml");
24691
25590
  try {
24692
25591
  const s3 = await info2(config2);
24693
25592
  if (s3) {
24694
25593
  if (!s3.isFile() || s3.isSymbolicLink() || s3.size > 2 * 1024 * 1024) throw Error();
24695
- const plugins = parse3(await readFile5(config2, "utf8")).plugins ?? {};
25594
+ const plugins = parse3(await readFile6(config2, "utf8")).plugins ?? {};
24696
25595
  if (!plugins || typeof plugins !== "object" || Array.isArray(plugins) || Object.keys(plugins).length > 1024) throw Error();
24697
25596
  for (const id of Object.keys(plugins)) if (id.startsWith(pluginName + "@")) {
24698
25597
  const market = id.slice(pluginName.length + 1);
@@ -24702,19 +25601,19 @@ async function relatedPlugins(runCodex, pluginName, env) {
24702
25601
  }
24703
25602
  }
24704
25603
  } catch {
24705
- fail("local_config_unconfirmed", { phase: "local_check", commandKind: "local_config_read", localRegistrationState: "unknown", action: "review_local_plugin_registration" });
25604
+ fail4("local_config_unconfirmed", { phase: "local_check", commandKind: "local_config_read", localRegistrationState: "unknown", action: "review_local_plugin_registration" });
24706
25605
  }
24707
25606
  const state = await codexJSON(runCodex, ["plugin", "marketplace", "list", "--json"]);
24708
- if (!Array.isArray(state?.marketplaces) || state.marketplaces.length > 128) fail("local_catalog_unconfirmed");
25607
+ if (!Array.isArray(state?.marketplaces) || state.marketplaces.length > 128) fail4("local_catalog_unconfirmed");
24709
25608
  for (const market of state.marketplaces) {
24710
- if (typeof market.name !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,140}$/.test(market.name) || typeof market.root !== "string" || !path7.isAbsolute(market.root)) fail("local_catalog_unconfirmed");
25609
+ if (typeof market.name !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,140}$/.test(market.name) || typeof market.root !== "string" || !path10.isAbsolute(market.root)) fail4("local_catalog_unconfirmed");
24711
25610
  let catalog;
24712
25611
  try {
24713
- catalog = await packageJSON(path7.join(market.root, ".agents/plugins/marketplace.json"));
25612
+ catalog = await packageJSON(path10.join(market.root, ".agents/plugins/marketplace.json"));
24714
25613
  } catch {
24715
- fail("local_catalog_unconfirmed", { phase: "local_check", commandKind: "marketplace_read", localRegistrationState: "unknown", action: "restore_local_marketplace_catalog" });
25614
+ fail4("local_catalog_unconfirmed", { phase: "local_check", commandKind: "marketplace_read", localRegistrationState: "unknown", action: "restore_local_marketplace_catalog" });
24716
25615
  }
24717
- if (!Array.isArray(catalog?.plugins) || catalog.plugins.length > 1024) fail("local_catalog_unconfirmed");
25616
+ if (!Array.isArray(catalog?.plugins) || catalog.plugins.length > 1024) fail4("local_catalog_unconfirmed");
24718
25617
  if (catalog.plugins.some((p2) => p2?.name === pluginName)) related.add(market.name);
24719
25618
  const pinned = pinnedGitSource(market.marketplaceSource);
24720
25619
  if (pinned) pinnedMarketplaces.set(market.name, pinned);
@@ -24722,16 +25621,16 @@ async function relatedPlugins(runCodex, pluginName, env) {
24722
25621
  const installed = [];
24723
25622
  for (const market of related) {
24724
25623
  const list = await codexJSON(runCodex, ["plugin", "list", "--marketplace", market, "--json"]);
24725
- if (!Array.isArray(list?.installed) || list.installed.length > 1024) fail("local_registration_unconfirmed");
25624
+ if (!Array.isArray(list?.installed) || list.installed.length > 1024) fail4("local_registration_unconfirmed");
24726
25625
  for (const p2 of list.installed) {
24727
- if (typeof p2?.pluginId !== "string" || typeof p2.enabled !== "boolean") fail("local_registration_unconfirmed");
25626
+ if (typeof p2?.pluginId !== "string" || typeof p2.enabled !== "boolean") fail4("local_registration_unconfirmed");
24728
25627
  if (p2?.pluginId !== pluginName + "@" + market) continue;
24729
- if (p2.marketplaceName !== void 0 && p2.marketplaceName !== market) fail("local_registration_unconfirmed");
25628
+ if (p2.marketplaceName !== void 0 && p2.marketplaceName !== market) fail4("local_registration_unconfirmed");
24730
25629
  installed.push({ ...p2, ...pinnedMarketplaces.has(market) ? { pinnedMarketplace: pinnedMarketplaces.get(market) } : {} });
24731
25630
  }
24732
25631
  }
24733
- if (new Set(installed.map((p2) => p2.pluginId)).size !== installed.length) fail("local_registration_unconfirmed");
24734
- if ([...registered].some((id) => !installed.some((p2) => p2.pluginId === id))) fail("local_registration_unconfirmed", {
25632
+ if (new Set(installed.map((p2) => p2.pluginId)).size !== installed.length) fail4("local_registration_unconfirmed");
25633
+ if ([...registered].some((id) => !installed.some((p2) => p2.pluginId === id))) fail4("local_registration_unconfirmed", {
24735
25634
  phase: "local_check",
24736
25635
  commandKind: "plugin_read",
24737
25636
  localRegistrationState: "unknown",
@@ -24741,11 +25640,11 @@ async function relatedPlugins(runCodex, pluginName, env) {
24741
25640
  }
24742
25641
  async function runNode(root, version3) {
24743
25642
  try {
24744
- const result = await execute2(process.execPath, [path7.join(root, "bin/promptframe-creation.mjs"), "--version"], { encoding: "utf8", timeout: 1e4, maxBuffer: 8192 });
24745
- if (result.stdout.trim() !== version3) fail("runtime_version_mismatch");
25643
+ const result = await execute2(process.execPath, [path10.join(root, "bin/promptframe-creation.mjs"), "--version"], { encoding: "utf8", timeout: 1e4, maxBuffer: 8192 });
25644
+ if (result.stdout.trim() !== version3) fail4("runtime_version_mismatch");
24746
25645
  } catch (e) {
24747
25646
  if (e instanceof CreationClientError) throw e;
24748
- fail("runtime_check_failed");
25647
+ fail4("runtime_check_failed");
24749
25648
  }
24750
25649
  }
24751
25650
  async function checkInstalledRuntime(root, version3, command2, { env = process.env } = {}) {
@@ -24755,12 +25654,12 @@ async function checkInstalledRuntime(root, version3, command2, { env = process.e
24755
25654
  if (!major || Number(major[1]) < 20) throw Error("unsupported_node");
24756
25655
  const result = await execute2(
24757
25656
  command2,
24758
- [path7.join(root, "bin/promptframe-creation.mjs"), "--version"],
25657
+ [path10.join(root, "bin/promptframe-creation.mjs"), "--version"],
24759
25658
  { env, encoding: "utf8", timeout: 1e4, maxBuffer: 8192 }
24760
25659
  );
24761
25660
  if (result.stdout.trim() !== version3) throw Error("wrong_version");
24762
25661
  } catch {
24763
- fail("recorded_node_unavailable", {
25662
+ fail4("recorded_node_unavailable", {
24764
25663
  installedVersion: version3,
24765
25664
  action: "restore_recorded_node_or_connect_newer_version",
24766
25665
  next: "\u6062\u590D\u8BE5\u63D2\u4EF6\u8BB0\u5F55\u7684 Node.js 20+\uFF1B\u6216\u4ECE Studio \u83B7\u53D6\u8F83\u65B0\u7684\u63A8\u8350\u7248 connect \u6307\u4EE4\uFF0C\u4E3A\u65B0\u6865\u51C6\u5907\u5F53\u524D Node\u3002\u4E0D\u8981\u5220\u9664\u65E7\u7248\u672C\u3001\u51ED\u636E\u6216\u91CD\u6D3E\u539F\u4EFB\u52A1\u3002"
@@ -24791,44 +25690,44 @@ async function installForUser({
24791
25690
  validProfile(profile);
24792
25691
  const versionOutput = await runCodex(["--version"]);
24793
25692
  const match = versionOutput.match(/codex-cli (\d+)\.(\d+)\.(\d+)/);
24794
- if (!match || Number(match[1]) === 0 && Number(match[2]) < 160) fail("codex_0160_required");
24795
- const payload = await inspectRuntimePackage(path7.resolve(sourceRoot));
24796
- const root = path7.resolve(env.XDG_DATA_HOME ?? path7.join(homedir4(), ".local/share"), "promptframe-creation", profile);
25693
+ if (!match || Number(match[1]) === 0 && Number(match[2]) < 160) fail4("codex_0160_required");
25694
+ const payload = await inspectRuntimePackage(path10.resolve(sourceRoot));
25695
+ const root = path10.resolve(env.XDG_DATA_HOME ?? path10.join(homedir4(), ".local/share"), "promptframe-creation", profile);
24797
25696
  await privateDirectory3(root);
24798
25697
  const release = await acquire(root, signal);
24799
- const versions = path7.join(root, "versions"), currentFile = path7.join(root, "current.json"), pendingFile = path7.join(root, "registration-pending.json");
24800
- const marketplaceFile = path7.join(root, ".agents/plugins/marketplace.json");
25698
+ const versions = path10.join(root, "versions"), currentFile = path10.join(root, "current.json"), pendingFile = path10.join(root, "registration-pending.json");
25699
+ const marketplaceFile = path10.join(root, ".agents/plugins/marketplace.json");
24801
25700
  const pluginName = "promptframe-creation" + (profile === "default" ? "" : "-" + profile), marketplace = "promptframe-creation-user" + (profile === "default" ? "" : "-" + profile);
24802
25701
  const pluginId = pluginName + "@" + marketplace;
24803
- const versionRoot = path7.join(versions, payload.version), temporary = path7.join(versions, ".partial-" + randomBytes4(12).toString("hex"));
25702
+ const versionRoot = path10.join(versions, payload.version), temporary = path10.join(versions, ".partial-" + randomBytes5(12).toString("hex"));
24804
25703
  let previous, registrationStarted = false, newFiles = 0;
24805
25704
  try {
24806
25705
  signal?.throwIfAborted();
24807
25706
  await privateDirectory3(versions);
24808
- await privateDirectory3(path7.dirname(marketplaceFile));
25707
+ await privateDirectory3(path10.dirname(marketplaceFile));
24809
25708
  previous = await privateRead2(currentFile);
24810
- if (previous && (previous.profile !== profile || previous.pluginId !== pluginId || previous.configFile !== configFile2)) fail("profile_binding_conflict");
25709
+ if (previous && (previous.profile !== profile || previous.pluginId !== pluginId || previous.configFile !== configFile2)) fail4("profile_binding_conflict");
24811
25710
  const state = { installed: await relatedPlugins(runCodex, pluginName, env) };
24812
25711
  const installed = state.installed.find((x) => x.pluginId === pluginId);
24813
25712
  const legacy = await codexJSON(runCodex, ["mcp", "list", "--json"]);
24814
- if (!Array.isArray(legacy)) fail("local_registration_unconfirmed");
25713
+ if (!Array.isArray(legacy)) fail4("local_registration_unconfirmed");
24815
25714
  const serverName = "promptframe" + (profile === "default" ? "" : "-" + profile);
24816
25715
  const servers = legacy.filter((x) => x.name === serverName);
24817
25716
  const pending = await privateRead2(pendingFile);
24818
25717
  if (pending) {
24819
- if (pending.profile !== profile || pending.pluginId !== pluginId || pending.configFile !== configFile2 || pending.versionRoot !== path7.join(versions, pending.version)) fail("profile_binding_conflict");
25718
+ if (pending.profile !== profile || pending.pluginId !== pluginId || pending.configFile !== configFile2 || pending.versionRoot !== path10.join(versions, pending.version)) fail4("profile_binding_conflict");
24820
25719
  if (installed?.version !== pending.version || installed.enabled !== true || installed.source?.path !== pending.versionRoot)
24821
- fail("registration_unconfirmed_keep_existing", { phase: "registration_observation", localRegistrationState: "unknown", action: "inspect_same_registration_no_second_add" });
25720
+ fail4("registration_unconfirmed_keep_existing", { phase: "registration_observation", localRegistrationState: "unknown", action: "inspect_same_registration_no_second_add" });
24822
25721
  const transport2 = await managedTransport(installed, versions, serverName, profile, configFile2);
24823
- if (servers.length !== 1 || servers[0].enabled === false || !sameTransport(servers[0].transport, transport2)) fail("registration_unconfirmed_keep_existing");
24824
- const ready = await privateRead2(path7.join(pending.versionRoot, "installation.json"));
24825
- if (ready?.payloadDigest !== pending.payloadDigest) fail("installed_files_invalid");
25722
+ if (servers.length !== 1 || servers[0].enabled === false || !sameTransport(servers[0].transport, transport2)) fail4("registration_unconfirmed_keep_existing");
25723
+ const ready = await privateRead2(path10.join(pending.versionRoot, "installation.json"));
25724
+ if (ready?.payloadDigest !== pending.payloadDigest) fail4("installed_files_invalid");
24826
25725
  previous = pending;
24827
25726
  await atomicJSON(currentFile, pending);
24828
25727
  await rm2(pendingFile);
24829
25728
  }
24830
25729
  const pinned = state.installed.map((p2) => ({ plugin: p2, source: pinnedGitSource(p2.source) ?? p2.pinnedMarketplace })).find((p2) => p2.source);
24831
- if (pinned) fail("pinned_git_plugin_upgrade_required", {
25730
+ if (pinned) fail4("pinned_git_plugin_upgrade_required", {
24832
25731
  ...pinned.source,
24833
25732
  sourceType: "git",
24834
25733
  localRegistrationState: "present",
@@ -24837,10 +25736,10 @@ async function installForUser({
24837
25736
  });
24838
25737
  const official = await officialNpmInstallation(state.installed ?? [], servers, env, profile, configFile2);
24839
25738
  if (official) {
24840
- if (installed || previous) fail("existing_registration_requires_review");
25739
+ if (installed || previous) fail4("existing_registration_requires_review");
24841
25740
  const compared = compareVersions(official.version, payload.version);
24842
25741
  if (compared < 0) {
24843
- fail("npm_plugin_upgrade_required", {
25742
+ fail4("npm_plugin_upgrade_required", {
24844
25743
  installedVersion: official.version,
24845
25744
  requestedVersion: payload.version,
24846
25745
  pluginId: official.pluginId,
@@ -24855,11 +25754,11 @@ async function installForUser({
24855
25754
  if (legacy.some((x) => {
24856
25755
  if (x.name !== serverName) return false;
24857
25756
  return !recorded || !sameTransport(x.transport, recorded);
24858
- })) fail("legacy_mcp_entry_requires_review");
24859
- if (state.installed.some((p2) => p2.pluginId !== pluginId)) fail("existing_registration_requires_review");
25757
+ })) fail4("legacy_mcp_entry_requires_review");
25758
+ if (state.installed.some((p2) => p2.pluginId !== pluginId)) fail4("existing_registration_requires_review");
24860
25759
  if (installed && compareVersions(installed.version, payload.version) > 0) {
24861
25760
  if (!previous || previous.version !== installed.version || previous.versionRoot !== installed.source.path || installed.enabled !== true)
24862
- fail("existing_registration_requires_review");
25761
+ fail4("existing_registration_requires_review");
24863
25762
  await verifyInstalledRuntime(previous.versionRoot, previous.version, recorded.command, { env });
24864
25763
  return {
24865
25764
  ...previous,
@@ -24875,44 +25774,44 @@ async function installForUser({
24875
25774
  }
24876
25775
  const target = await info2(versionRoot);
24877
25776
  if (target) {
24878
- if (!target.isDirectory() || target.isSymbolicLink()) fail("version_content_conflict");
24879
- const ready = await privateRead2(path7.join(versionRoot, "installation.json"));
24880
- if (!ready || ready.payloadDigest !== payload.payloadDigest || ready.profile !== profile || ready.configFile !== configFile2) fail("version_content_conflict");
25777
+ if (!target.isDirectory() || target.isSymbolicLink()) fail4("version_content_conflict");
25778
+ const ready = await privateRead2(path10.join(versionRoot, "installation.json"));
25779
+ if (!ready || ready.payloadDigest !== payload.payloadDigest || ready.profile !== profile || ready.configFile !== configFile2) fail4("version_content_conflict");
24881
25780
  for (const f2 of ready.files) {
24882
- if (!payload.files.some((p2) => p2.path === f2.path)) fail("installed_files_invalid");
24883
- const file = path7.join(versionRoot, f2.path), s3 = await info2(file);
24884
- if (!s3?.isFile() || s3.isSymbolicLink() || s3.size !== f2.bytes || hash4(await readFile5(file)) !== f2.sha256) fail("installed_files_invalid");
25781
+ if (!payload.files.some((p2) => p2.path === f2.path)) fail4("installed_files_invalid");
25782
+ const file = path10.join(versionRoot, f2.path), s3 = await info2(file);
25783
+ if (!s3?.isFile() || s3.isSymbolicLink() || s3.size !== f2.bytes || hash4(await readFile6(file)) !== f2.sha256) fail4("installed_files_invalid");
24885
25784
  }
24886
- if (ready.files.length !== payload.files.length) fail("installed_files_invalid");
25785
+ if (ready.files.length !== payload.files.length) fail4("installed_files_invalid");
24887
25786
  } else {
24888
- await mkdir4(temporary, { mode: 448 });
25787
+ await mkdir5(temporary, { mode: 448 });
24889
25788
  for (const f2 of payload.files) {
24890
25789
  signal?.throwIfAborted();
24891
- await mkdir4(path7.dirname(path7.join(temporary, f2.path)), { recursive: true, mode: 448 });
24892
- await writeFile2(path7.join(temporary, f2.path), f2.body, { flag: "wx", mode: 384 });
25790
+ await mkdir5(path10.dirname(path10.join(temporary, f2.path)), { recursive: true, mode: 448 });
25791
+ await writeFile2(path10.join(temporary, f2.path), f2.body, { flag: "wx", mode: 384 });
24893
25792
  }
24894
- const manifest = await json(path7.join(temporary, ".codex-plugin/plugin.json"));
25793
+ const manifest = await json(path10.join(temporary, ".codex-plugin/plugin.json"));
24895
25794
  manifest.name = pluginName;
24896
- await writeFile2(path7.join(temporary, ".codex-plugin/plugin.json"), JSON.stringify(manifest, null, 2) + "\n");
25795
+ await writeFile2(path10.join(temporary, ".codex-plugin/plugin.json"), JSON.stringify(manifest, null, 2) + "\n");
24897
25796
  const mcp = { mcpServers: { ["promptframe" + (profile === "default" ? "" : "-" + profile)]: {
24898
25797
  command: process.execPath,
24899
- args: [path7.join(versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", configFile2],
25798
+ args: [path10.join(versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", configFile2],
24900
25799
  cwd: versionRoot
24901
25800
  } } };
24902
- await writeFile2(path7.join(temporary, ".mcp.json"), JSON.stringify(mcp, null, 2) + "\n");
25801
+ await writeFile2(path10.join(temporary, ".mcp.json"), JSON.stringify(mcp, null, 2) + "\n");
24903
25802
  await checkRuntime(temporary, payload.version);
24904
25803
  const files = [];
24905
25804
  for (const f2 of payload.files) {
24906
- const body = await readFile5(path7.join(temporary, f2.path));
25805
+ const body = await readFile6(path10.join(temporary, f2.path));
24907
25806
  files.push({ path: f2.path, bytes: body.length, sha256: hash4(body) });
24908
25807
  }
24909
- await atomicJSON(path7.join(temporary, "installation.json"), { version: payload.version, profile, configFile: configFile2, payloadDigest: payload.payloadDigest, files });
25808
+ await atomicJSON(path10.join(temporary, "installation.json"), { version: payload.version, profile, configFile: configFile2, payloadDigest: payload.payloadDigest, files });
24910
25809
  signal?.throwIfAborted();
24911
- await rename4(temporary, versionRoot);
25810
+ await rename5(temporary, versionRoot);
24912
25811
  newFiles = payload.files.length;
24913
25812
  }
24914
25813
  if (newFiles === 0) {
24915
- const launch = (await json(path7.join(versionRoot, ".mcp.json"))).mcpServers?.[serverName];
25814
+ const launch = (await json(path10.join(versionRoot, ".mcp.json"))).mcpServers?.[serverName];
24916
25815
  await verifyInstalledRuntime(versionRoot, payload.version, launch.command, { env });
24917
25816
  }
24918
25817
  const complete = { version: payload.version, profile, configFile: configFile2, pluginId, versionRoot, payloadDigest: payload.payloadDigest };
@@ -24931,12 +25830,12 @@ async function installForUser({
24931
25830
  await runCodex(["plugin", "marketplace", "add", root, "--json"]);
24932
25831
  await runCodex(["plugin", "add", pluginId, "--json"]);
24933
25832
  const observed = (await relatedPlugins(runCodex, pluginName, env)).find((x) => x.pluginId === pluginId);
24934
- if (observed?.version !== payload.version || observed.enabled !== true) fail("registration_unconfirmed");
25833
+ if (observed?.version !== payload.version || observed.enabled !== true) fail4("registration_unconfirmed");
24935
25834
  const launch = await managedTransport(observed, versions, serverName, profile, configFile2);
24936
25835
  const hostMcp = await codexJSON(runCodex, ["mcp", "list", "--json"]);
24937
- if (!Array.isArray(hostMcp)) fail("registration_unconfirmed");
25836
+ if (!Array.isArray(hostMcp)) fail4("registration_unconfirmed");
24938
25837
  const effective = hostMcp.filter((x) => x.name === serverName);
24939
- if (effective.length !== 1 || effective[0].enabled === false || !sameTransport(effective[0].transport, launch)) fail("registration_unconfirmed");
25838
+ if (effective.length !== 1 || effective[0].enabled === false || !sameTransport(effective[0].transport, launch)) fail4("registration_unconfirmed");
24940
25839
  await atomicJSON(currentFile, complete);
24941
25840
  await rm2(pendingFile);
24942
25841
  }
@@ -24953,7 +25852,7 @@ async function installForUser({
24953
25852
  };
24954
25853
  } catch (error4) {
24955
25854
  if (registrationStarted) {
24956
- fail("registration_unconfirmed_keep_existing", {
25855
+ fail4("registration_unconfirmed_keep_existing", {
24957
25856
  ...installationErrorDetails(error4),
24958
25857
  phase: "registration_observation",
24959
25858
  localRegistrationState: "unknown",
@@ -24961,8 +25860,8 @@ async function installForUser({
24961
25860
  });
24962
25861
  }
24963
25862
  if (error4 instanceof CreationClientError) throw error4;
24964
- if (signal?.aborted) fail("interrupted_keep_existing");
24965
- fail("failed_keep_existing");
25863
+ if (signal?.aborted) fail4("interrupted_keep_existing");
25864
+ fail4("failed_keep_existing");
24966
25865
  } finally {
24967
25866
  await rm2(temporary, { recursive: true, force: true });
24968
25867
  await release();
@@ -24970,10 +25869,10 @@ async function installForUser({
24970
25869
  }
24971
25870
 
24972
25871
  // lib/claude-installation.mjs
24973
- import { createHash as createHash9, randomBytes as randomBytes6 } from "node:crypto";
24974
- import { mkdir as mkdir6, open as open7, readFile as readFile8, rename as rename6, rm as rm5 } from "node:fs/promises";
25872
+ import { createHash as createHash11, randomBytes as randomBytes7 } from "node:crypto";
25873
+ import { mkdir as mkdir7, open as open9, readFile as readFile9, rename as rename7, rm as rm5 } from "node:fs/promises";
24975
25874
  import { homedir as homedir9 } from "node:os";
24976
- import path12 from "node:path";
25875
+ import path15 from "node:path";
24977
25876
 
24978
25877
  // lib/claude-hook-definition.mjs
24979
25878
  function claudeHostHooks({ pluginName = "promptframe-creation", serverName, configFile: configFile2, nodeCommand = "node", runtimeRoot = "${CLAUDE_PLUGIN_ROOT}" } = {}) {
@@ -24996,10 +25895,10 @@ function claudeHostHooks({ pluginName = "promptframe-creation", serverName, conf
24996
25895
  // lib/claude-command.mjs
24997
25896
  import { execFile as execFile3 } from "node:child_process";
24998
25897
  import { promisify as promisify3 } from "node:util";
24999
- import { access, lstat as lstat6, readdir as readdir4 } from "node:fs/promises";
25000
- import { constants as constants2 } from "node:fs";
25898
+ import { access, lstat as lstat8, readdir as readdir5 } from "node:fs/promises";
25899
+ import { constants as constants4 } from "node:fs";
25001
25900
  import { homedir as homedir5 } from "node:os";
25002
- import path8 from "node:path";
25901
+ import path11 from "node:path";
25003
25902
  var execute3 = promisify3(execFile3);
25004
25903
  var ClaudeCommandError = class extends CreationClientError {
25005
25904
  constructor(code, details) {
@@ -25011,23 +25910,23 @@ var claudeErrorDetails = (error4) => error4 instanceof ClaudeCommandError ? erro
25011
25910
  async function resolveClaudeCommand({ env = process.env, homeDirectory = homedir5(), executable } = {}) {
25012
25911
  const selected = executable ?? env.PROMPTFRAME_CLAUDE_BIN;
25013
25912
  if (selected) {
25014
- if (!path8.isAbsolute(selected)) throw new CreationClientError("installation.claude_executable_invalid");
25015
- await access(selected, constants2.X_OK);
25913
+ if (!path11.isAbsolute(selected)) throw new CreationClientError("installation.claude_executable_invalid");
25914
+ await access(selected, constants4.X_OK);
25016
25915
  return selected;
25017
25916
  }
25018
- for (const directory of (env.PATH ?? "").split(path8.delimiter).filter(path8.isAbsolute)) {
25019
- const file = path8.join(directory, process.platform === "win32" ? "claude.exe" : "claude");
25917
+ for (const directory2 of (env.PATH ?? "").split(path11.delimiter).filter(path11.isAbsolute)) {
25918
+ const file = path11.join(directory2, process.platform === "win32" ? "claude.exe" : "claude");
25020
25919
  try {
25021
- await access(file, constants2.X_OK);
25920
+ await access(file, constants4.X_OK);
25022
25921
  return file;
25023
25922
  } catch (e) {
25024
25923
  if (!["ENOENT", "EACCES", "ENOTDIR"].includes(e.code)) throw e;
25025
25924
  }
25026
25925
  }
25027
- const root = path8.join(homeDirectory, ".claude/remote/ccd-cli");
25926
+ const root = path11.join(homeDirectory, ".claude/remote/ccd-cli");
25028
25927
  let entries;
25029
25928
  try {
25030
- entries = await readdir4(root);
25929
+ entries = await readdir5(root);
25031
25930
  } catch (e) {
25032
25931
  if (e.code === "ENOENT") throw new CreationClientError("installation.claude_required");
25033
25932
  throw e;
@@ -25037,9 +25936,9 @@ async function resolveClaudeCommand({ env = process.env, homeDirectory = homedir
25037
25936
  for (const name of entries) {
25038
25937
  const match = name.match(/^(\d+)\.(\d+)\.(\d+)-[a-f0-9]{6,40}$/);
25039
25938
  if (!match) continue;
25040
- const file = path8.join(root, name), s3 = await lstat6(file);
25939
+ const file = path11.join(root, name), s3 = await lstat8(file);
25041
25940
  if (s3.isFile() && !s3.isSymbolicLink() && s3.uid === process.getuid?.()) {
25042
- await access(file, constants2.X_OK);
25941
+ await access(file, constants4.X_OK);
25043
25942
  candidates.push({ file, version: match.slice(1).map(Number) });
25044
25943
  }
25045
25944
  }
@@ -25075,17 +25974,17 @@ function createClaudeRunner({ env = process.env, executable, signal, resolve = r
25075
25974
  }
25076
25975
 
25077
25976
  // lib/claude-local-state.mjs
25078
- import { readFile as readFile6, lstat as lstat7 } from "node:fs/promises";
25977
+ import { readFile as readFile7, lstat as lstat9 } from "node:fs/promises";
25079
25978
  import { homedir as homedir6 } from "node:os";
25080
- import path9 from "node:path";
25979
+ import path12 from "node:path";
25081
25980
  function claudeConfigRoot(env = process.env) {
25082
- return path9.resolve(env.CLAUDE_CONFIG_DIR ?? path9.join(homedir6(), ".claude"));
25981
+ return path12.resolve(env.CLAUDE_CONFIG_DIR ?? path12.join(homedir6(), ".claude"));
25083
25982
  }
25084
25983
  async function readClaudeUserServer(serverName, env = process.env) {
25085
- const file = env.CLAUDE_CONFIG_DIR ? path9.join(claudeConfigRoot(env), ".claude.json") : path9.join(homedir6(), ".claude.json");
25984
+ const file = env.CLAUDE_CONFIG_DIR ? path12.join(claudeConfigRoot(env), ".claude.json") : path12.join(homedir6(), ".claude.json");
25086
25985
  let info5;
25087
25986
  try {
25088
- info5 = await lstat7(file);
25987
+ info5 = await lstat9(file);
25089
25988
  } catch (e) {
25090
25989
  if (e.code === "ENOENT") return null;
25091
25990
  throw new CreationClientError("installation.claude_local_registration_unconfirmed");
@@ -25094,7 +25993,7 @@ async function readClaudeUserServer(serverName, env = process.env) {
25094
25993
  throw new CreationClientError("installation.claude_local_registration_unconfirmed");
25095
25994
  let state;
25096
25995
  try {
25097
- state = JSON.parse(await readFile6(file, "utf8"));
25996
+ state = JSON.parse(await readFile7(file, "utf8"));
25098
25997
  } catch {
25099
25998
  throw new CreationClientError("installation.claude_local_registration_unconfirmed");
25100
25999
  }
@@ -25105,30 +26004,30 @@ async function readClaudeUserServer(serverName, env = process.env) {
25105
26004
  }
25106
26005
 
25107
26006
  // lib/claude-mcp-installation.mjs
25108
- import { createHash as createHash8, randomBytes as randomBytes5 } from "node:crypto";
25109
- import { mkdir as mkdir5, open as open6, readFile as readFile7, readdir as readdir5, rename as rename5, rm as rm4, lstat as lstat8 } from "node:fs/promises";
26007
+ import { createHash as createHash10, randomBytes as randomBytes6 } from "node:crypto";
26008
+ import { mkdir as mkdir6, open as open8, readFile as readFile8, readdir as readdir6, rename as rename6, rm as rm4, lstat as lstat10 } from "node:fs/promises";
25110
26009
  import { homedir as homedir8 } from "node:os";
25111
- import path11 from "node:path";
26010
+ import path14 from "node:path";
25112
26011
 
25113
26012
  // lib/claude-hook-registration.mjs
25114
- import { createHash as createHash7 } from "node:crypto";
25115
- import { open as open5, rm as rm3 } from "node:fs/promises";
25116
- import { constants as constants3 } from "node:fs";
25117
- import path10 from "node:path";
26013
+ import { createHash as createHash9 } from "node:crypto";
26014
+ import { open as open7, rm as rm3 } from "node:fs/promises";
26015
+ import { constants as constants5 } from "node:fs";
26016
+ import path13 from "node:path";
25118
26017
  import { homedir as homedir7 } from "node:os";
25119
26018
  var { privateDirectory: privateDirectory4, privateRead: privateRead3, atomicJSON: atomicJSON2, acquire: acquire2 } = installationFiles;
25120
- var digest3 = (value2) => createHash7("sha256").update(JSON.stringify(value2)).digest("hex");
25121
- var fail2 = () => {
26019
+ var digest4 = (value2) => createHash9("sha256").update(JSON.stringify(value2)).digest("hex");
26020
+ var fail5 = () => {
25122
26021
  throw new CreationClientError("installation.claude_hooks_require_review");
25123
26022
  };
25124
26023
  async function settings(file) {
25125
26024
  let handle;
25126
26025
  try {
25127
- handle = await open5(file, constants3.O_RDONLY | constants3.O_NOFOLLOW);
26026
+ handle = await open7(file, constants5.O_RDONLY | constants5.O_NOFOLLOW);
25128
26027
  const info5 = await handle.stat();
25129
- if (!info5.isFile() || info5.uid !== process.getuid?.() || info5.size > 512 * 1024) fail2();
26028
+ if (!info5.isFile() || info5.uid !== process.getuid?.() || info5.size > 512 * 1024) fail5();
25130
26029
  const value2 = JSON.parse(await handle.readFile("utf8"));
25131
- if (!value2 || typeof value2 !== "object" || Array.isArray(value2) || value2.hooks !== void 0 && (!value2.hooks || typeof value2.hooks !== "object" || Array.isArray(value2.hooks))) fail2();
26030
+ if (!value2 || typeof value2 !== "object" || Array.isArray(value2) || value2.hooks !== void 0 && (!value2.hooks || typeof value2.hooks !== "object" || Array.isArray(value2.hooks))) fail5();
25132
26031
  return value2;
25133
26032
  } catch (e) {
25134
26033
  if (e.code === "ENOENT") return {};
@@ -25137,49 +26036,49 @@ async function settings(file) {
25137
26036
  await handle?.close();
25138
26037
  }
25139
26038
  }
25140
- var contains = (value2, entries) => Object.entries(entries).every(([event, wanted]) => Array.isArray(value2.hooks?.[event]) && wanted.every((entry) => value2.hooks[event].filter((actual) => digest3(actual) === digest3(entry)).length === 1));
26039
+ var contains = (value2, entries) => Object.entries(entries).every(([event, wanted]) => Array.isArray(value2.hooks?.[event]) && wanted.every((entry) => value2.hooks[event].filter((actual) => digest4(actual) === digest4(entry)).length === 1));
25141
26040
  async function verifyClaudeFallbackHooks(record2, env) {
25142
- if (!record2?.settingsFile || record2.settingsFile !== path10.join(claudeConfigRoot(env), "settings.json") || !record2.entries) fail2();
25143
- if (!contains(await settings(record2.settingsFile), record2.entries)) fail2();
26041
+ if (!record2?.settingsFile || record2.settingsFile !== path13.join(claudeConfigRoot(env), "settings.json") || !record2.entries) fail5();
26042
+ if (!contains(await settings(record2.settingsFile), record2.entries)) fail5();
25144
26043
  return true;
25145
26044
  }
25146
26045
  async function registerClaudeFallbackHooks({ record: record2, root, env, nodeCommand, signal }) {
25147
- const directory = claudeConfigRoot(env), file = path10.join(directory, "settings.json");
25148
- const guard = path10.resolve(
25149
- env.XDG_DATA_HOME ?? path10.join(homedir7(), ".local/share"),
26046
+ const directory2 = claudeConfigRoot(env), file = path13.join(directory2, "settings.json");
26047
+ const guard = path13.resolve(
26048
+ env.XDG_DATA_HOME ?? path13.join(homedir7(), ".local/share"),
25150
26049
  "promptframe-creation",
25151
- "claude-hook-writer-" + digest3(directory)
26050
+ "claude-hook-writer-" + digest4(directory2)
25152
26051
  );
25153
26052
  await privateDirectory4(guard);
25154
26053
  const release = await acquire2(guard, signal);
25155
- const markerFile = path10.join(root, "hooks-current.json"), pendingFile = path10.join(root, "hooks-pending.json");
26054
+ const markerFile = path13.join(root, "hooks-current.json"), pendingFile = path13.join(root, "hooks-pending.json");
25156
26055
  try {
25157
- await privateDirectory4(directory);
26056
+ await privateDirectory4(directory2);
25158
26057
  const entries = claudeHostHooks({ serverName: record2.serverName, configFile: record2.configFile, nodeCommand, runtimeRoot: record2.versionRoot });
25159
26058
  const expected = { contractVersion: "creation-claude-hooks/v1", settingsFile: file, profile: record2.profile, entries };
25160
26059
  const pending = await privateRead3(pendingFile), previous = await privateRead3(markerFile), before = await settings(file);
25161
26060
  if (pending) {
25162
- if (digest3(pending) !== digest3(expected) || !contains(before, entries)) throw new CreationClientError("installation.registration_unconfirmed_keep_existing");
26061
+ if (digest4(pending) !== digest4(expected) || !contains(before, entries)) throw new CreationClientError("installation.registration_unconfirmed_keep_existing");
25163
26062
  await atomicJSON2(markerFile, expected);
25164
26063
  await rm3(pendingFile);
25165
26064
  return expected;
25166
26065
  }
25167
26066
  if (previous) {
25168
- if (previous.contractVersion !== expected.contractVersion || previous.profile !== record2.profile || previous.settingsFile !== file) fail2();
26067
+ if (previous.contractVersion !== expected.contractVersion || previous.profile !== record2.profile || previous.settingsFile !== file) fail5();
25169
26068
  await verifyClaudeFallbackHooks(previous, env);
25170
- if (digest3(previous) === digest3(expected)) return previous;
26069
+ if (digest4(previous) === digest4(expected)) return previous;
25171
26070
  }
25172
26071
  const next = { ...before, hooks: { ...before.hooks } };
25173
26072
  for (const [event, wanted] of Object.entries(entries)) {
25174
26073
  const actual = next.hooks[event] ?? [];
25175
- if (!Array.isArray(actual)) fail2();
25176
- const owned = new Set((previous?.entries[event] ?? []).map(digest3));
25177
- if (wanted.some((entry) => actual.some((value2) => digest3(value2) === digest3(entry)) && !owned.has(digest3(entry)))) fail2();
25178
- next.hooks[event] = [...actual.filter((entry) => !owned.has(digest3(entry))), ...wanted];
26074
+ if (!Array.isArray(actual)) fail5();
26075
+ const owned = new Set((previous?.entries[event] ?? []).map(digest4));
26076
+ if (wanted.some((entry) => actual.some((value2) => digest4(value2) === digest4(entry)) && !owned.has(digest4(entry)))) fail5();
26077
+ next.hooks[event] = [...actual.filter((entry) => !owned.has(digest4(entry))), ...wanted];
25179
26078
  }
25180
26079
  signal?.throwIfAborted();
25181
26080
  await atomicJSON2(pendingFile, expected);
25182
- if (digest3(await settings(file)) !== digest3(before)) fail2();
26081
+ if (digest4(await settings(file)) !== digest4(before)) fail5();
25183
26082
  await atomicJSON2(file, next);
25184
26083
  if (!contains(await settings(file), entries)) throw new CreationClientError("installation.registration_unconfirmed_keep_existing");
25185
26084
  await atomicJSON2(markerFile, expected);
@@ -25192,7 +26091,7 @@ async function registerClaudeFallbackHooks({ record: record2, root, env, nodeCom
25192
26091
 
25193
26092
  // lib/claude-mcp-installation.mjs
25194
26093
  var { info: info3, privateDirectory: privateDirectory5, privateRead: privateRead4, atomicJSON: atomicJSON3, acquire: acquire3, compareVersions: compareVersions2 } = installationFiles;
25195
- var hash5 = (body) => createHash8("sha256").update(body).digest("hex");
26094
+ var hash5 = (body) => createHash10("sha256").update(body).digest("hex");
25196
26095
  var FallbackError = class extends CreationClientError {
25197
26096
  constructor(code, details) {
25198
26097
  super("installation." + code);
@@ -25200,14 +26099,14 @@ var FallbackError = class extends CreationClientError {
25200
26099
  }
25201
26100
  };
25202
26101
  var fallbackErrorDetails = (error4) => error4 instanceof FallbackError ? error4.details : void 0;
25203
- var fail3 = (code, details) => {
26102
+ var fail6 = (code, details) => {
25204
26103
  throw new FallbackError(code, details);
25205
26104
  };
25206
26105
  async function claimSkillDirectory(root) {
25207
26106
  try {
25208
- await mkdir5(root, { mode: 448 });
26107
+ await mkdir6(root, { mode: 448 });
25209
26108
  } catch (error4) {
25210
- if (error4.code === "EEXIST") fail3("claude_skill_requires_review");
26109
+ if (error4.code === "EEXIST") fail6("claude_skill_requires_review");
25211
26110
  throw error4;
25212
26111
  }
25213
26112
  }
@@ -25218,17 +26117,17 @@ function same(a, b2, depth = 0) {
25218
26117
  return left.length <= 256 && left.length === right.length && left.every((key, i) => key === right[i] && same(a[key], b2[key], depth + 1));
25219
26118
  }
25220
26119
  async function atomicText(file, body) {
25221
- const temporary = file + "." + randomBytes5(12).toString("hex") + ".tmp";
26120
+ const temporary = file + "." + randomBytes6(12).toString("hex") + ".tmp";
25222
26121
  try {
25223
- const fd = await open6(temporary, "wx", 384);
26122
+ const fd = await open8(temporary, "wx", 384);
25224
26123
  try {
25225
26124
  await fd.writeFile(body);
25226
26125
  await fd.sync();
25227
26126
  } finally {
25228
26127
  await fd.close();
25229
26128
  }
25230
- await rename5(temporary, file);
25231
- const dir = await open6(path11.dirname(file), "r");
26129
+ await rename6(temporary, file);
26130
+ const dir = await open8(path14.dirname(file), "r");
25232
26131
  try {
25233
26132
  await dir.sync();
25234
26133
  } finally {
@@ -25239,41 +26138,41 @@ async function atomicText(file, body) {
25239
26138
  }
25240
26139
  }
25241
26140
  async function verifyVersion(root, record2) {
25242
- const directory = await info3(root);
25243
- if (!directory?.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid?.() || directory.mode & 63) fail3("claude_installed_files_invalid");
25244
- const marker = await privateRead4(path11.join(root, "installation.json")), payload = await inspectRuntimePackage(root);
25245
- if (!marker || marker.host !== "claude-code" || marker.mode !== "mcp-and-skills" || marker.profile !== record2.profile || marker.configFile !== record2.configFile || marker.version !== record2.version || marker.payloadDigest !== record2.payloadDigest || payload.payloadDigest !== marker.payloadDigest || !path11.isAbsolute(marker.nodeCommand ?? "")) fail3("claude_installed_files_invalid");
26141
+ const directory2 = await info3(root);
26142
+ if (!directory2?.isDirectory() || directory2.isSymbolicLink() || directory2.uid !== process.getuid?.() || directory2.mode & 63) fail6("claude_installed_files_invalid");
26143
+ const marker = await privateRead4(path14.join(root, "installation.json")), payload = await inspectRuntimePackage(root);
26144
+ if (!marker || marker.host !== "claude-code" || marker.mode !== "mcp-and-skills" || marker.profile !== record2.profile || marker.configFile !== record2.configFile || marker.version !== record2.version || marker.payloadDigest !== record2.payloadDigest || payload.payloadDigest !== marker.payloadDigest || !path14.isAbsolute(marker.nodeCommand ?? "")) fail6("claude_installed_files_invalid");
25246
26145
  return marker;
25247
26146
  }
25248
26147
  function mcpDefinition(record2, nodeCommand) {
25249
26148
  return {
25250
26149
  type: "stdio",
25251
26150
  command: nodeCommand,
25252
- args: [path11.join(record2.versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", record2.configFile, "--host", "claude-code"]
26151
+ args: [path14.join(record2.versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", record2.configFile, "--host", "claude-code"]
25253
26152
  };
25254
26153
  }
25255
26154
  function skillBody(payload, sourceName, name) {
25256
26155
  const file = payload.files.find((f2) => f2.path === "skills/" + sourceName + "/SKILL.md");
25257
- if (!file) fail3("package_incomplete");
26156
+ if (!file) fail6("package_incomplete");
25258
26157
  const body = file.body.toString("utf8");
25259
- if (!body.startsWith("---\n") || !body.includes("\nname: " + sourceName + "\n")) fail3("package_incomplete");
26158
+ if (!body.startsWith("---\n") || !body.includes("\nname: " + sourceName + "\n")) fail6("package_incomplete");
25260
26159
  return body.replace("\nname: " + sourceName + "\n", "\nname: " + name + "\n");
25261
26160
  }
25262
26161
  async function observedSkill(plan, record2, { allowBefore = false } = {}) {
25263
- const directory = await info3(plan.root);
25264
- if (!directory) return false;
25265
- if (!directory.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid?.() || directory.mode & 63) fail3("claude_skill_requires_review");
25266
- const names = await readdir5(plan.root);
25267
- if (names.some((n) => !["SKILL.md", "promptframe-installation.json"].includes(n))) fail3("claude_skill_requires_review");
25268
- const marker = await privateRead4(path11.join(plan.root, "promptframe-installation.json")), file = path11.join(plan.root, "SKILL.md"), s3 = await info3(file);
26162
+ const directory2 = await info3(plan.root);
26163
+ if (!directory2) return false;
26164
+ if (!directory2.isDirectory() || directory2.isSymbolicLink() || directory2.uid !== process.getuid?.() || directory2.mode & 63) fail6("claude_skill_requires_review");
26165
+ const names = await readdir6(plan.root);
26166
+ if (names.some((n) => !["SKILL.md", "promptframe-installation.json"].includes(n))) fail6("claude_skill_requires_review");
26167
+ const marker = await privateRead4(path14.join(plan.root, "promptframe-installation.json")), file = path14.join(plan.root, "SKILL.md"), s3 = await info3(file);
25269
26168
  if (!marker || marker.host !== "claude-code" || marker.profile !== record2.profile || marker.configFile !== record2.configFile || marker.name !== plan.name)
25270
- fail3("claude_skill_requires_review");
26169
+ fail6("claude_skill_requires_review");
25271
26170
  if (!s3 && allowBefore && plan.beforeSHA === null && marker.sha256 === null) return false;
25272
- if (!s3?.isFile() || s3.isSymbolicLink() || s3.size > 256 * 1024) fail3("claude_skill_requires_review");
25273
- const digest4 = hash5(await readFile7(file));
25274
- if (digest4 === plan.sha256 && marker.sha256 === plan.sha256) return true;
25275
- if (allowBefore && (digest4 === plan.beforeSHA || digest4 === plan.sha256) && marker.sha256 === plan.beforeSHA) return false;
25276
- fail3("claude_skill_requires_review");
26171
+ if (!s3?.isFile() || s3.isSymbolicLink() || s3.size > 256 * 1024) fail6("claude_skill_requires_review");
26172
+ const digest5 = hash5(await readFile8(file));
26173
+ if (digest5 === plan.sha256 && marker.sha256 === plan.sha256) return true;
26174
+ if (allowBefore && (digest5 === plan.beforeSHA || digest5 === plan.sha256) && marker.sha256 === plan.beforeSHA) return false;
26175
+ fail6("claude_skill_requires_review");
25277
26176
  }
25278
26177
  async function installClaudeMcpFallback({
25279
26178
  sourceRoot,
@@ -25287,13 +26186,13 @@ async function installClaudeMcpFallback({
25287
26186
  nodeCommand,
25288
26187
  writeSkill = atomicText
25289
26188
  }) {
25290
- const payload = await inspectRuntimePackage(path11.resolve(sourceRoot)), suffix = profile === "default" ? "" : "-" + profile, serverName = "promptframe" + suffix, root = path11.resolve(env.XDG_DATA_HOME ?? path11.join(homedir8(), ".local/share"), "promptframe-creation", profile, "claude-code-mcp");
26189
+ const payload = await inspectRuntimePackage(path14.resolve(sourceRoot)), suffix = profile === "default" ? "" : "-" + profile, serverName = "promptframe" + suffix, root = path14.resolve(env.XDG_DATA_HOME ?? path14.join(homedir8(), ".local/share"), "promptframe-creation", profile, "claude-code-mcp");
25291
26190
  await privateDirectory5(root);
25292
- const release = await acquire3(root, signal), versions = path11.join(root, "versions"), currentFile = path11.join(root, "current.json"), pendingFile = path11.join(root, "registration-pending.json"), versionRoot = path11.join(versions, payload.version), temporary = path11.join(versions, ".partial-" + randomBytes5(12).toString("hex"));
26191
+ const release = await acquire3(root, signal), versions = path14.join(root, "versions"), currentFile = path14.join(root, "current.json"), pendingFile = path14.join(root, "registration-pending.json"), versionRoot = path14.join(versions, payload.version), temporary = path14.join(versions, ".partial-" + randomBytes6(12).toString("hex"));
25293
26192
  let writeStarted = false, newFiles = 0;
25294
26193
  const complete = { host: "claude-code", mode: "mcp-and-skills", profile, configFile: configFile2, serverName, version: payload.version, versionRoot, payloadDigest: payload.payloadDigest };
25295
26194
  const checkBinding = (record2) => {
25296
- if (record2 && (record2.host !== "claude-code" || record2.mode !== "mcp-and-skills" || record2.profile !== profile || record2.configFile !== configFile2 || record2.serverName !== serverName || !/^\d+\.\d+\.\d+$/.test(record2.version ?? "") || record2.versionRoot !== path11.join(versions, record2.version))) fail3("profile_binding_conflict");
26195
+ if (record2 && (record2.host !== "claude-code" || record2.mode !== "mcp-and-skills" || record2.profile !== profile || record2.configFile !== configFile2 || record2.serverName !== serverName || !/^\d+\.\d+\.\d+$/.test(record2.version ?? "") || record2.versionRoot !== path14.join(versions, record2.version))) fail6("profile_binding_conflict");
25297
26196
  };
25298
26197
  try {
25299
26198
  await privateDirectory5(versions);
@@ -25304,31 +26203,31 @@ async function installClaudeMcpFallback({
25304
26203
  complete.beforeServer = pending?.beforeServer ?? saved;
25305
26204
  const settled = async (record2) => {
25306
26205
  const ready2 = await verifyVersion(record2.versionRoot, record2);
25307
- if (!same(record2.server, mcpDefinition(record2, ready2.nodeCommand))) fail3("claude_installed_files_invalid");
26206
+ if (!same(record2.server, mcpDefinition(record2, ready2.nodeCommand))) fail6("claude_installed_files_invalid");
25308
26207
  if (!same(saved, record2.server)) return false;
25309
26208
  if (compareVersions2(record2.version, "0.3.1") >= 0) await verifyClaudeFallbackHooks(record2.hostHooks, env);
25310
- if (!Array.isArray(record2.skills) || record2.skills.length !== 2) fail3("claude_skill_requires_review");
26209
+ if (!Array.isArray(record2.skills) || record2.skills.length !== 2) fail6("claude_skill_requires_review");
25311
26210
  for (const [i, skill] of record2.skills.entries()) {
25312
26211
  const name = ["creation-setup", "video-creation"][i] + suffix;
25313
- if (skill.name !== name || skill.root !== path11.join(claudeConfigRoot(env), "skills", name) || !/^[a-f0-9]{64}$/.test(skill.sha256 ?? ""))
25314
- fail3("claude_skill_requires_review");
26212
+ if (skill.name !== name || skill.root !== path14.join(claudeConfigRoot(env), "skills", name) || !/^[a-f0-9]{64}$/.test(skill.sha256 ?? ""))
26213
+ fail6("claude_skill_requires_review");
25315
26214
  if (!await observedSkill(skill, record2)) return false;
25316
26215
  }
25317
26216
  return true;
25318
26217
  };
25319
26218
  if (pending) {
25320
26219
  writeStarted = true;
25321
- if (pending.version !== complete.version || pending.payloadDigest !== complete.payloadDigest) fail3("registration_unconfirmed_keep_existing");
26220
+ if (pending.version !== complete.version || pending.payloadDigest !== complete.payloadDigest) fail6("registration_unconfirmed_keep_existing");
25322
26221
  if (pending.phase === "mcp") {
25323
- if (!await settled(pending)) fail3("registration_unconfirmed_keep_existing");
26222
+ if (!await settled(pending)) fail6("registration_unconfirmed_keep_existing");
25324
26223
  await atomicJSON3(currentFile, pending);
25325
26224
  await rm4(pendingFile);
25326
26225
  previous = pending;
25327
26226
  pending = null;
25328
- } else if (pending.phase !== "skills" || !same(saved, pending.beforeServer)) fail3("registration_unconfirmed_keep_existing");
26227
+ } else if (pending.phase !== "skills" || !same(saved, pending.beforeServer)) fail6("registration_unconfirmed_keep_existing");
25329
26228
  }
25330
26229
  if (previous && !pending) {
25331
- if (!await settled(previous)) fail3("claude_local_registration_unconfirmed");
26230
+ if (!await settled(previous)) fail6("claude_local_registration_unconfirmed");
25332
26231
  if (compareVersions2(previous.version, payload.version) >= 0) {
25333
26232
  const ready2 = await verifyVersion(previous.versionRoot, previous);
25334
26233
  await verifyInstalledRuntime(previous.versionRoot, previous.version, ready2.nodeCommand, { env });
@@ -25347,15 +26246,15 @@ async function installClaudeMcpFallback({
25347
26246
  recordedRuntimeRetained: ready2.nodeCommand !== nodeCommand
25348
26247
  };
25349
26248
  }
25350
- } else if (saved && !pending) fail3("legacy_mcp_entry_requires_review");
26249
+ } else if (saved && !pending) fail6("legacy_mcp_entry_requires_review");
25351
26250
  if (await info3(versionRoot)) await verifyVersion(versionRoot, complete);
25352
26251
  else {
25353
- await mkdir5(temporary, { mode: 448 });
26252
+ await mkdir6(temporary, { mode: 448 });
25354
26253
  for (const file of payload.files) {
25355
26254
  signal?.throwIfAborted();
25356
- const dest = path11.join(temporary, file.path);
25357
- await mkdir5(path11.dirname(dest), { recursive: true, mode: 448 });
25358
- const fd = await open6(dest, "wx", 384);
26255
+ const dest = path14.join(temporary, file.path);
26256
+ await mkdir6(path14.dirname(dest), { recursive: true, mode: 448 });
26257
+ const fd = await open8(dest, "wx", 384);
25359
26258
  try {
25360
26259
  await fd.writeFile(file.body);
25361
26260
  await fd.sync();
@@ -25364,33 +26263,33 @@ async function installClaudeMcpFallback({
25364
26263
  }
25365
26264
  }
25366
26265
  await checkRuntime(temporary, payload.version);
25367
- await atomicJSON3(path11.join(temporary, "installation.json"), { ...complete, nodeCommand });
26266
+ await atomicJSON3(path14.join(temporary, "installation.json"), { ...complete, nodeCommand });
25368
26267
  signal?.throwIfAborted();
25369
- await rename5(temporary, versionRoot);
26268
+ await rename6(temporary, versionRoot);
25370
26269
  newFiles = payload.files.length;
25371
26270
  }
25372
26271
  const ready = await verifyVersion(versionRoot, complete);
25373
26272
  complete.server = mcpDefinition(complete, ready.nodeCommand);
25374
26273
  if (newFiles === 0) await verifyInstalledRuntime(versionRoot, payload.version, ready.nodeCommand, { env });
25375
- const skillRoot = path11.join(claudeConfigRoot(env), "skills");
25376
- await mkdir5(skillRoot, { recursive: true, mode: 448 });
25377
- const parent = await lstat8(skillRoot);
25378
- if (!parent.isDirectory() || parent.isSymbolicLink() || parent.uid !== process.getuid?.()) fail3("claude_skill_requires_review");
26274
+ const skillRoot = path14.join(claudeConfigRoot(env), "skills");
26275
+ await mkdir6(skillRoot, { recursive: true, mode: 448 });
26276
+ const parent = await lstat10(skillRoot);
26277
+ if (!parent.isDirectory() || parent.isSymbolicLink() || parent.uid !== process.getuid?.()) fail6("claude_skill_requires_review");
25379
26278
  const plans = [];
25380
26279
  for (const sourceName of ["creation-setup", "video-creation"]) {
25381
- const name = sourceName + suffix, body = skillBody(payload, sourceName, name), skill = { name, root: path11.join(skillRoot, name), sha256: hash5(body) };
26280
+ const name = sourceName + suffix, body = skillBody(payload, sourceName, name), skill = { name, root: path14.join(skillRoot, name), sha256: hash5(body) };
25382
26281
  if (pending) {
25383
26282
  const old = pending.skills?.find((s3) => s3.name === name);
25384
- if (!old || old.root !== skill.root || old.sha256 !== skill.sha256) fail3("registration_unconfirmed_keep_existing");
26283
+ if (!old || old.root !== skill.root || old.sha256 !== skill.sha256) fail6("registration_unconfirmed_keep_existing");
25385
26284
  plans.push({ ...old, body });
25386
26285
  } else {
25387
26286
  const existing = await info3(skill.root);
25388
26287
  let beforeSHA = null;
25389
26288
  if (existing) {
25390
- const marker = await privateRead4(path11.join(skill.root, "promptframe-installation.json"));
25391
- if (!marker || marker.profile !== profile || marker.configFile !== configFile2 || marker.name !== name) fail3("claude_skill_requires_review");
26289
+ const marker = await privateRead4(path14.join(skill.root, "promptframe-installation.json"));
26290
+ if (!marker || marker.profile !== profile || marker.configFile !== configFile2 || marker.name !== name) fail6("claude_skill_requires_review");
25392
26291
  const old = { ...skill, sha256: marker.sha256 };
25393
- if (!await observedSkill(old, complete)) fail3("claude_skill_requires_review");
26292
+ if (!await observedSkill(old, complete)) fail6("claude_skill_requires_review");
25394
26293
  beforeSHA = marker.sha256;
25395
26294
  }
25396
26295
  plans.push({ ...skill, beforeSHA, body });
@@ -25406,21 +26305,21 @@ async function installClaudeMcpFallback({
25406
26305
  if (await info3(plan.root)) {
25407
26306
  if (await observedSkill(plan, complete, { allowBefore: true })) continue;
25408
26307
  } else {
25409
- if (plan.beforeSHA !== null) fail3("claude_skill_requires_review");
26308
+ if (plan.beforeSHA !== null) fail6("claude_skill_requires_review");
25410
26309
  await claimSkillDirectory(plan.root);
25411
- await atomicJSON3(path11.join(plan.root, "promptframe-installation.json"), { host: "claude-code", profile, configFile: configFile2, name: plan.name, sha256: null });
26310
+ await atomicJSON3(path14.join(plan.root, "promptframe-installation.json"), { host: "claude-code", profile, configFile: configFile2, name: plan.name, sha256: null });
25412
26311
  }
25413
- await writeSkill(path11.join(plan.root, "SKILL.md"), plan.body);
25414
- await atomicJSON3(path11.join(plan.root, "promptframe-installation.json"), { host: "claude-code", profile, configFile: configFile2, name: plan.name, sha256: plan.sha256 });
26312
+ await writeSkill(path14.join(plan.root, "SKILL.md"), plan.body);
26313
+ await atomicJSON3(path14.join(plan.root, "promptframe-installation.json"), { host: "claude-code", profile, configFile: configFile2, name: plan.name, sha256: plan.sha256 });
25415
26314
  }
25416
26315
  signal?.throwIfAborted();
25417
26316
  if (compareVersions2(payload.version, "0.3.1") >= 0) complete.hostHooks = await registerClaudeFallbackHooks({ record: complete, root, env, nodeCommand: ready.nodeCommand, signal });
25418
- if (!same(await readClaudeUserServer(serverName, env), complete.beforeServer)) fail3("claude_local_registration_changed");
26317
+ if (!same(await readClaudeUserServer(serverName, env), complete.beforeServer)) fail6("claude_local_registration_changed");
25419
26318
  await atomicJSON3(pendingFile, { ...complete, phase: "mcp" });
25420
26319
  writeStarted = true;
25421
26320
  await runClaude(["mcp", "add-json", "--scope", "user", serverName, JSON.stringify(complete.server)]);
25422
26321
  saved = await readClaudeUserServer(serverName, env);
25423
- if (!await settled(complete)) fail3("registration_unconfirmed_keep_existing");
26322
+ if (!await settled(complete)) fail6("registration_unconfirmed_keep_existing");
25424
26323
  await atomicJSON3(currentFile, complete);
25425
26324
  await rm4(pendingFile);
25426
26325
  return {
@@ -25437,9 +26336,9 @@ async function installClaudeMcpFallback({
25437
26336
  versionStatus: "current"
25438
26337
  };
25439
26338
  } catch (error4) {
25440
- if (writeStarted) fail3("registration_unconfirmed_keep_existing", { phase: "registration_observation", localRegistrationState: "unknown", action: "inspect_same_registration_no_second_add" });
26339
+ if (writeStarted) fail6("registration_unconfirmed_keep_existing", { phase: "registration_observation", localRegistrationState: "unknown", action: "inspect_same_registration_no_second_add" });
25441
26340
  if (error4 instanceof CreationClientError) throw error4;
25442
- fail3(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
26341
+ fail6(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
25443
26342
  } finally {
25444
26343
  await rm4(temporary, { recursive: true, force: true });
25445
26344
  await release();
@@ -25457,7 +26356,7 @@ var ClaudeInstallationError = class extends CreationClientError {
25457
26356
  }
25458
26357
  };
25459
26358
  var claudeInstallationDetails = (error4) => error4 instanceof ClaudeInstallationError ? error4.details : void 0;
25460
- var fail4 = (code, details) => {
26359
+ var fail7 = (code, details) => {
25461
26360
  throw new ClaudeInstallationError(code, details);
25462
26361
  };
25463
26362
  async function jsonCommand(run, args2) {
@@ -25467,9 +26366,9 @@ async function jsonCommand(run, args2) {
25467
26366
  if (typeof body !== "string" || Buffer.byteLength(body) > 2 * 1024 * 1024) throw Error();
25468
26367
  value2 = JSON.parse(body);
25469
26368
  } catch {
25470
- fail4("claude_local_registration_unconfirmed");
26369
+ fail7("claude_local_registration_unconfirmed");
25471
26370
  }
25472
- if (!Array.isArray(value2) || value2.length > 1024) fail4("claude_local_registration_unconfirmed");
26371
+ if (!Array.isArray(value2) || value2.length > 1024) fail7("claude_local_registration_unconfirmed");
25473
26372
  return value2;
25474
26373
  }
25475
26374
  async function registrations(run, pluginName, marketplace, root) {
@@ -25478,17 +26377,17 @@ async function registrations(run, pluginName, marketplace, root) {
25478
26377
  jsonCommand(run, ["plugin", "marketplace", "list", "--json"])
25479
26378
  ]);
25480
26379
  if (plugins.some((p2) => !p2 || typeof p2.id !== "string" || !p2.id || p2.id.length > 256 || typeof p2.scope !== "string" || typeof p2.version !== "string" || typeof p2.enabled !== "boolean" || typeof p2.installPath !== "string") || markets.some((p2) => !p2 || typeof p2.name !== "string" || !p2.name || typeof p2.source !== "string"))
25481
- fail4("claude_local_registration_unconfirmed");
26380
+ fail7("claude_local_registration_unconfirmed");
25482
26381
  const related = plugins.filter((p2) => typeof p2?.id === "string" && p2.id.startsWith(pluginName + "@"));
25483
- if (related.length > 1 || related.some((p2) => p2.id !== pluginName + "@" + marketplace || p2.scope !== "user" || typeof p2.enabled !== "boolean" || !/^\d+\.\d+\.\d+$/.test(p2.version ?? "") || !path12.isAbsolute(p2.installPath ?? "") || p2.readFromFolder !== void 0 && (!path12.isAbsolute(p2.readFromFolder) || !/^\d+\.\d+\.\d+$/.test(p2.folderVersion ?? ""))))
25484
- fail4("claude_existing_registration_requires_review");
26382
+ if (related.length > 1 || related.some((p2) => p2.id !== pluginName + "@" + marketplace || p2.scope !== "user" || typeof p2.enabled !== "boolean" || !/^\d+\.\d+\.\d+$/.test(p2.version ?? "") || !path15.isAbsolute(p2.installPath ?? "") || p2.readFromFolder !== void 0 && (!path15.isAbsolute(p2.readFromFolder) || !/^\d+\.\d+\.\d+$/.test(p2.folderVersion ?? ""))))
26383
+ fail7("claude_existing_registration_requires_review");
25485
26384
  const found = markets.filter((p2) => p2?.name === marketplace);
25486
26385
  if (found.length > 1 || found.some((p2) => p2.source !== "directory" || p2.path !== root || p2.installLocation !== root))
25487
- fail4("claude_existing_registration_requires_review");
26386
+ fail7("claude_existing_registration_requires_review");
25488
26387
  return { plugin: related[0], market: found[0] };
25489
26388
  }
25490
26389
  async function legacyUserMcp(env, serverName) {
25491
- if (await readClaudeUserServer(serverName, env)) fail4("legacy_mcp_entry_requires_review");
26390
+ if (await readClaudeUserServer(serverName, env)) fail7("legacy_mcp_entry_requires_review");
25492
26391
  }
25493
26392
  function transport(serverName, configFile2, command2 = process.execPath) {
25494
26393
  return { mcpServers: { [serverName]: {
@@ -25497,32 +26396,32 @@ function transport(serverName, configFile2, command2 = process.execPath) {
25497
26396
  } } };
25498
26397
  }
25499
26398
  async function verifyVersion2(root, { version: version3, profile, configFile: configFile2, payloadDigest, pluginName, serverName }) {
25500
- const directory = await info4(root);
25501
- if (!directory?.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid?.() || directory.mode & 63)
25502
- fail4("claude_installed_files_invalid");
25503
- const ready = await privateRead5(path12.join(root, "installation.json"));
25504
- if (!ready || ready.host !== "claude-code" || ready.version !== version3 || ready.profile !== profile || ready.configFile !== configFile2 || ready.payloadDigest !== payloadDigest || !Array.isArray(ready.files) || ready.files.length > 1024) fail4("claude_installed_files_invalid");
26399
+ const directory2 = await info4(root);
26400
+ if (!directory2?.isDirectory() || directory2.isSymbolicLink() || directory2.uid !== process.getuid?.() || directory2.mode & 63)
26401
+ fail7("claude_installed_files_invalid");
26402
+ const ready = await privateRead5(path15.join(root, "installation.json"));
26403
+ if (!ready || ready.host !== "claude-code" || ready.version !== version3 || ready.profile !== profile || ready.configFile !== configFile2 || ready.payloadDigest !== payloadDigest || !Array.isArray(ready.files) || ready.files.length > 1024) fail7("claude_installed_files_invalid");
25505
26404
  const actual = await inspectRuntimePackage(root);
25506
- if (actual.version !== version3 || JSON.stringify(actual.files.map(({ path: path14, bytes: bytes2, sha256 }) => ({ path: path14, bytes: bytes2, sha256 }))) !== JSON.stringify(ready.files))
25507
- fail4("claude_installed_files_invalid");
25508
- const manifest = JSON.parse(await readFile8(path12.join(root, ".claude-plugin/plugin.json"), "utf8"));
26405
+ if (actual.version !== version3 || JSON.stringify(actual.files.map(({ path: path17, bytes: bytes2, sha256 }) => ({ path: path17, bytes: bytes2, sha256 }))) !== JSON.stringify(ready.files))
26406
+ fail7("claude_installed_files_invalid");
26407
+ const manifest = JSON.parse(await readFile9(path15.join(root, ".claude-plugin/plugin.json"), "utf8"));
25509
26408
  if (manifest.name !== pluginName || manifest.version !== version3 || manifest.skills !== "./skills/" || manifest.mcpServers !== "./.claude-mcp.json")
25510
- fail4("claude_installed_files_invalid");
26409
+ fail7("claude_installed_files_invalid");
25511
26410
  let runtimeCommand;
25512
26411
  for (const file of [".mcp.json", ".claude-mcp.json"]) {
25513
- const mcp = JSON.parse(await readFile8(path12.join(root, file), "utf8"));
26412
+ const mcp = JSON.parse(await readFile9(path15.join(root, file), "utf8"));
25514
26413
  const command2 = mcp.mcpServers?.[serverName]?.command;
25515
- if (!path12.isAbsolute(command2 ?? "") || runtimeCommand !== void 0 && command2 !== runtimeCommand || JSON.stringify(mcp) !== JSON.stringify(transport(serverName, configFile2, command2))) fail4("claude_installed_files_invalid");
26414
+ if (!path15.isAbsolute(command2 ?? "") || runtimeCommand !== void 0 && command2 !== runtimeCommand || JSON.stringify(mcp) !== JSON.stringify(transport(serverName, configFile2, command2))) fail7("claude_installed_files_invalid");
25516
26415
  runtimeCommand = command2;
25517
26416
  }
25518
26417
  if (compareVersions3(version3, "0.3.1") >= 0 && JSON.stringify(manifest.hooks) !== JSON.stringify(claudeHostHooks({ pluginName, configFile: configFile2, nodeCommand: runtimeCommand })))
25519
- fail4("claude_installed_files_invalid");
26418
+ fail7("claude_installed_files_invalid");
25520
26419
  return { ...ready, runtimeCommand };
25521
26420
  }
25522
26421
  async function installForClaudeUser(options = {}) {
25523
26422
  const profile = options.profile ?? "default", env = options.env ?? process.env;
25524
26423
  validProfile2(profile);
25525
- const modeRoot = path12.resolve(env.XDG_DATA_HOME ?? path12.join(homedir9(), ".local/share"), "promptframe-creation", profile, "claude-code-mode");
26424
+ const modeRoot = path15.resolve(env.XDG_DATA_HOME ?? path15.join(homedir9(), ".local/share"), "promptframe-creation", profile, "claude-code-mode");
25526
26425
  await privateDirectory6(modeRoot);
25527
26426
  const release = await acquire4(modeRoot, options.signal);
25528
26427
  try {
@@ -25544,37 +26443,37 @@ async function installClaudeUserLocked({
25544
26443
  nodeCommand = process.execPath
25545
26444
  } = {}) {
25546
26445
  validProfile2(profile);
25547
- if (!path12.isAbsolute(nodeCommand)) fail4("runtime_command_invalid");
26446
+ if (!path15.isAbsolute(nodeCommand)) fail7("runtime_command_invalid");
25548
26447
  const hostVersion = (await runClaude(["--version"])).trim().match(/^(\d+\.\d+\.\d+) \(Claude Code\)$/);
25549
- if (!hostVersion || compareVersions3(hostVersion[1], "2.1.295") < 0) fail4("claude_21295_required");
26448
+ if (!hostVersion || compareVersions3(hostVersion[1], "2.1.295") < 0) fail7("claude_21295_required");
25550
26449
  const help = await runClaude(["--help"]);
25551
- if (typeof help !== "string" || Buffer.byteLength(help) > 128 * 1024) fail4("claude_capabilities_unconfirmed");
26450
+ if (typeof help !== "string" || Buffer.byteLength(help) > 128 * 1024) fail7("claude_capabilities_unconfirmed");
25552
26451
  const hasPlugin = /^\s+plugin(?:\|plugins)?\s/m.test(help), hasMcp = /^\s+mcp\s/m.test(help);
25553
- const base = path12.resolve(env.XDG_DATA_HOME ?? path12.join(homedir9(), ".local/share"), "promptframe-creation", profile), fallbackRoot = path12.join(base, "claude-code-mcp"), pluginRoot = path12.join(base, "claude-code");
25554
- const pluginPending = await info4(path12.join(pluginRoot, "registration-pending.json")), pluginCurrent = await info4(path12.join(pluginRoot, "current.json")), fallbackState = await info4(path12.join(fallbackRoot, "current.json")) || await info4(path12.join(fallbackRoot, "registration-pending.json"));
25555
- if ((!hasPlugin || fallbackState) && (pluginPending || pluginCurrent)) fail4("registration_unconfirmed_keep_existing");
26452
+ const base = path15.resolve(env.XDG_DATA_HOME ?? path15.join(homedir9(), ".local/share"), "promptframe-creation", profile), fallbackRoot = path15.join(base, "claude-code-mcp"), pluginRoot = path15.join(base, "claude-code");
26453
+ const pluginPending = await info4(path15.join(pluginRoot, "registration-pending.json")), pluginCurrent = await info4(path15.join(pluginRoot, "current.json")), fallbackState = await info4(path15.join(fallbackRoot, "current.json")) || await info4(path15.join(fallbackRoot, "registration-pending.json"));
26454
+ if ((!hasPlugin || fallbackState) && (pluginPending || pluginCurrent)) fail7("registration_unconfirmed_keep_existing");
25556
26455
  if (!hasPlugin || fallbackState) {
25557
- if (!hasMcp) fail4("claude_capabilities_unconfirmed");
26456
+ if (!hasMcp) fail7("claude_capabilities_unconfirmed");
25558
26457
  return installClaudeMcpFallback({ sourceRoot, profile, env, configFile: configFile2, signal, runClaude, checkRuntime, verifyInstalledRuntime, nodeCommand });
25559
26458
  }
25560
- const payload = await inspectRuntimePackage(path12.resolve(sourceRoot));
26459
+ const payload = await inspectRuntimePackage(path15.resolve(sourceRoot));
25561
26460
  if (!payload.files.some((f2) => f2.path === ".claude-plugin/plugin.json") || !payload.files.some((f2) => f2.path === ".claude-mcp.json"))
25562
- fail4("claude_package_incomplete");
25563
- const root = path12.resolve(env.XDG_DATA_HOME ?? path12.join(homedir9(), ".local/share"), "promptframe-creation", profile, "claude-code");
26461
+ fail7("claude_package_incomplete");
26462
+ const root = path15.resolve(env.XDG_DATA_HOME ?? path15.join(homedir9(), ".local/share"), "promptframe-creation", profile, "claude-code");
25564
26463
  await privateDirectory6(root);
25565
26464
  const release = await acquire4(root, signal);
25566
26465
  const suffix = profile === "default" ? "" : "-" + profile, pluginName = "promptframe-creation" + suffix, marketplace = "promptframe-creation-user" + suffix, pluginId = pluginName + "@" + marketplace, serverName = "promptframe" + suffix;
25567
- const versions = path12.join(root, "versions"), currentFile = path12.join(root, "current.json"), pendingFile = path12.join(root, "registration-pending.json"), catalogFile = path12.join(root, ".claude-plugin/marketplace.json"), versionRoot = path12.join(versions, payload.version), temporary = path12.join(versions, ".partial-" + randomBytes6(12).toString("hex"));
26466
+ const versions = path15.join(root, "versions"), currentFile = path15.join(root, "current.json"), pendingFile = path15.join(root, "registration-pending.json"), catalogFile = path15.join(root, ".claude-plugin/marketplace.json"), versionRoot = path15.join(versions, payload.version), temporary = path15.join(versions, ".partial-" + randomBytes7(12).toString("hex"));
25568
26467
  let registrationStarted = false, newFiles = 0;
25569
26468
  try {
25570
26469
  signal?.throwIfAborted();
25571
26470
  await privateDirectory6(versions);
25572
- await privateDirectory6(path12.dirname(catalogFile));
26471
+ await privateDirectory6(path15.dirname(catalogFile));
25573
26472
  await legacyUserMcp(env, serverName);
25574
26473
  let previous = await privateRead5(currentFile), pending = await privateRead5(pendingFile), state = await registrations(runClaude, pluginName, marketplace, root);
25575
26474
  const binding = { profile, configFile: configFile2, pluginId, pluginName, serverName, host: "claude-code" };
25576
26475
  const checkBinding = (record2) => {
25577
- if (record2 && (record2.profile !== profile || record2.configFile !== configFile2 || record2.pluginId !== pluginId || record2.host !== "claude-code" || !/^\d+\.\d+\.\d+$/.test(record2.version ?? "") || record2.versionRoot !== path12.join(versions, record2.version))) fail4("profile_binding_conflict");
26476
+ if (record2 && (record2.profile !== profile || record2.configFile !== configFile2 || record2.pluginId !== pluginId || record2.host !== "claude-code" || !/^\d+\.\d+\.\d+$/.test(record2.version ?? "") || record2.versionRoot !== path15.join(versions, record2.version))) fail7("profile_binding_conflict");
25578
26477
  };
25579
26478
  checkBinding(previous);
25580
26479
  checkBinding(pending);
@@ -25592,10 +26491,10 @@ async function installClaudeUserLocked({
25592
26491
  previous = pending;
25593
26492
  pending = null;
25594
26493
  } else if (pending.phase !== "marketplace" || !state.market || state.plugin)
25595
- fail4("registration_unconfirmed_keep_existing", { phase: "registration_observation", localRegistrationState: "unknown", action: "inspect_same_registration_no_second_add" });
26494
+ fail7("registration_unconfirmed_keep_existing", { phase: "registration_observation", localRegistrationState: "unknown", action: "inspect_same_registration_no_second_add" });
25596
26495
  }
25597
- if (state.plugin && !previous && !pending) fail4("claude_existing_registration_requires_review");
25598
- if (previous && !await observed(previous) && !pending) fail4("claude_local_registration_unconfirmed");
26496
+ if (state.plugin && !previous && !pending) fail7("claude_existing_registration_requires_review");
26497
+ if (previous && !await observed(previous) && !pending) fail7("claude_local_registration_unconfirmed");
25599
26498
  if (previous && compareVersions3(previous.version, payload.version) > 0) {
25600
26499
  const recorded = runtimeCommands.get(previous.versionRoot);
25601
26500
  await verifyInstalledRuntime(previous.versionRoot, previous.version, recorded, { env });
@@ -25613,17 +26512,17 @@ async function installClaudeUserLocked({
25613
26512
  }
25614
26513
  const complete = { ...binding, version: payload.version, versionRoot, payloadDigest: payload.payloadDigest };
25615
26514
  if (pending && (pending.version !== complete.version || pending.payloadDigest !== complete.payloadDigest))
25616
- fail4("registration_unconfirmed_keep_existing");
26515
+ fail7("registration_unconfirmed_keep_existing");
25617
26516
  if (await info4(versionRoot)) {
25618
26517
  const ready = await verifyVersion2(versionRoot, { ...complete, pluginName, serverName });
25619
26518
  runtimeCommands.set(versionRoot, ready.runtimeCommand);
25620
26519
  } else {
25621
- await mkdir6(temporary, { mode: 448 });
26520
+ await mkdir7(temporary, { mode: 448 });
25622
26521
  for (const file of payload.files) {
25623
26522
  signal?.throwIfAborted();
25624
- const dest = path12.join(temporary, file.path);
25625
- await mkdir6(path12.dirname(dest), { recursive: true, mode: 448 });
25626
- const fd = await open7(dest, "wx", 384);
26523
+ const dest = path15.join(temporary, file.path);
26524
+ await mkdir7(path15.dirname(dest), { recursive: true, mode: 448 });
26525
+ const fd = await open9(dest, "wx", 384);
25627
26526
  try {
25628
26527
  await fd.writeFile(file.body);
25629
26528
  await fd.sync();
@@ -25631,21 +26530,21 @@ async function installClaudeUserLocked({
25631
26530
  await fd.close();
25632
26531
  }
25633
26532
  }
25634
- const manifest = JSON.parse(await readFile8(path12.join(temporary, ".claude-plugin/plugin.json"), "utf8"));
26533
+ const manifest = JSON.parse(await readFile9(path15.join(temporary, ".claude-plugin/plugin.json"), "utf8"));
25635
26534
  manifest.name = pluginName;
25636
26535
  if (manifest.hooks) manifest.hooks = claudeHostHooks({ pluginName, configFile: configFile2, nodeCommand });
25637
- await atomicJSON4(path12.join(temporary, ".claude-plugin/plugin.json"), manifest);
25638
- for (const file of [".mcp.json", ".claude-mcp.json"]) await atomicJSON4(path12.join(temporary, file), transport(serverName, configFile2, nodeCommand));
26536
+ await atomicJSON4(path15.join(temporary, ".claude-plugin/plugin.json"), manifest);
26537
+ for (const file of [".mcp.json", ".claude-mcp.json"]) await atomicJSON4(path15.join(temporary, file), transport(serverName, configFile2, nodeCommand));
25639
26538
  await checkRuntime(temporary, payload.version);
25640
26539
  const installed = await inspectRuntimePackage(temporary);
25641
- await atomicJSON4(path12.join(temporary, "installation.json"), {
26540
+ await atomicJSON4(path15.join(temporary, "installation.json"), {
25642
26541
  ...binding,
25643
26542
  version: payload.version,
25644
26543
  payloadDigest: payload.payloadDigest,
25645
- files: installed.files.map(({ path: path14, bytes: bytes2, sha256 }) => ({ path: path14, bytes: bytes2, sha256 }))
26544
+ files: installed.files.map(({ path: path17, bytes: bytes2, sha256 }) => ({ path: path17, bytes: bytes2, sha256 }))
25646
26545
  });
25647
26546
  signal?.throwIfAborted();
25648
- await rename6(temporary, versionRoot);
26547
+ await rename7(temporary, versionRoot);
25649
26548
  newFiles = payload.files.length;
25650
26549
  }
25651
26550
  if (newFiles === 0) await verifyInstalledRuntime(versionRoot, payload.version, runtimeCommands.get(versionRoot), { env });
@@ -25653,18 +26552,18 @@ async function installClaudeUserLocked({
25653
26552
  if (!already) {
25654
26553
  await atomicJSON4(catalogFile, { name: marketplace, owner: { name: "PromptFrame" }, plugins: [{ name: pluginName, source: "./versions/" + payload.version }] });
25655
26554
  if (!state.market) {
25656
- if (pending) fail4("registration_unconfirmed_keep_existing");
26555
+ if (pending) fail7("registration_unconfirmed_keep_existing");
25657
26556
  await atomicJSON4(pendingFile, { ...complete, phase: "marketplace" });
25658
26557
  registrationStarted = true;
25659
26558
  await runClaude(["plugin", "marketplace", "add", root, "--scope", "user", "--json"]);
25660
26559
  state = await registrations(runClaude, pluginName, marketplace, root);
25661
- if (!state.market) fail4("claude_registration_unconfirmed");
26560
+ if (!state.market) fail7("claude_registration_unconfirmed");
25662
26561
  }
25663
26562
  await atomicJSON4(pendingFile, { ...complete, phase: "plugin" });
25664
26563
  registrationStarted = true;
25665
26564
  await runClaude(["plugin", "install", pluginId, "--scope", "user", "--json"]);
25666
26565
  state = await registrations(runClaude, pluginName, marketplace, root);
25667
- if (!await observed(complete)) fail4("claude_registration_unconfirmed");
26566
+ if (!await observed(complete)) fail7("claude_registration_unconfirmed");
25668
26567
  await atomicJSON4(currentFile, complete);
25669
26568
  await rm5(pendingFile);
25670
26569
  }
@@ -25681,14 +26580,14 @@ async function installClaudeUserLocked({
25681
26580
  recordedRuntimeRetained: runtimeCommands.has(versionRoot) && runtimeCommands.get(versionRoot) !== nodeCommand
25682
26581
  };
25683
26582
  } catch (error4) {
25684
- if (registrationStarted) fail4("registration_unconfirmed_keep_existing", {
26583
+ if (registrationStarted) fail7("registration_unconfirmed_keep_existing", {
25685
26584
  ...claudeErrorDetails(error4),
25686
26585
  phase: "registration_observation",
25687
26586
  localRegistrationState: "unknown",
25688
26587
  action: "inspect_same_registration_no_second_add"
25689
26588
  });
25690
26589
  if (error4 instanceof CreationClientError) throw error4;
25691
- fail4(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
26590
+ fail7(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
25692
26591
  } finally {
25693
26592
  await rm5(temporary, { recursive: true, force: true });
25694
26593
  await release();
@@ -25697,7 +26596,7 @@ async function installClaudeUserLocked({
25697
26596
 
25698
26597
  // lib/cli.mjs
25699
26598
  import { fileURLToPath } from "node:url";
25700
- import path13 from "node:path";
26599
+ import path16 from "node:path";
25701
26600
  var args = process.argv.slice(2);
25702
26601
  var command = args.shift();
25703
26602
  var value = (key) => {
@@ -25705,7 +26604,7 @@ var value = (key) => {
25705
26604
  return i < 0 ? void 0 : args[i + 1];
25706
26605
  };
25707
26606
  var log = (value2) => process.stdout.write(JSON.stringify(value2) + "\n");
25708
- var configFile = () => value("--config") ? path13.resolve(value("--config")) : profileCredentialsPath(value("--profile") ?? "default");
26607
+ var configFile = () => value("--config") ? path16.resolve(value("--config")) : profileCredentialsPath(value("--profile") ?? "default");
25709
26608
  async function probe(credentials) {
25710
26609
  const client = await connectPlatform(credentials, { host: resolveHostIdentity({ host: value("--host") }) });
25711
26610
  try {
@@ -25734,7 +26633,7 @@ async function tokenInput() {
25734
26633
  try {
25735
26634
  return await new Promise((resolve, reject) => {
25736
26635
  let text = "";
25737
- const read = (chunk) => {
26636
+ const read2 = (chunk) => {
25738
26637
  for (const byte of chunk) {
25739
26638
  if (byte === 3) {
25740
26639
  finish();
@@ -25756,10 +26655,10 @@ async function tokenInput() {
25756
26655
  }
25757
26656
  };
25758
26657
  const finish = () => {
25759
- input.removeListener("data", read);
26658
+ input.removeListener("data", read2);
25760
26659
  input.pause();
25761
26660
  };
25762
- input.on("data", read);
26661
+ input.on("data", read2);
25763
26662
  });
25764
26663
  } finally {
25765
26664
  input.setRawMode(Boolean(wasRaw));
@@ -25810,7 +26709,7 @@ async function setup({ silent = false } = {}) {
25810
26709
  version: 1,
25811
26710
  endpoint,
25812
26711
  token,
25813
- clientId: existing?.clientId ?? randomBytes7(24).toString("base64url"),
26712
+ clientId: existing?.clientId ?? randomBytes8(24).toString("base64url"),
25814
26713
  clientName: value("--name") ?? existing?.clientName ?? (resolveHostIdentity({ host: value("--host") }).kind === "claude-code" ? "Claude Code PromptFrame" : "Codex PromptFrame"),
25815
26714
  createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
25816
26715
  };
@@ -25845,7 +26744,7 @@ async function bridge() {
25845
26744
  resolvedVersion: value("--resolved-runtime-version"),
25846
26745
  signal: startup.signal,
25847
26746
  hostKind: identity.kind,
25848
- cacheRoot: path13.join(path13.dirname(configFile()), "runtime-cache")
26747
+ cacheRoot: path16.join(path16.dirname(configFile()), "runtime-cache")
25849
26748
  });
25850
26749
  startup.signal.throwIfAborted();
25851
26750
  } catch (error4) {
@@ -25879,6 +26778,7 @@ async function bridge() {
25879
26778
  credentials,
25880
26779
  host: identity,
25881
26780
  hostSession,
26781
+ localUploads: createLocalUploadManager({ stateRoot: path16.join(path16.dirname(configFile()), "local-upload-state") }),
25882
26782
  onCatalogChange: () => server.sendToolListChanged(),
25883
26783
  onKnowledgeChange: (kind) => kind === "resources" ? server.sendResourceListChanged() : server.sendPromptListChanged()
25884
26784
  });
@@ -25916,9 +26816,9 @@ async function bridge() {
25916
26816
  throw new Error("creation.connection_unresolved");
25917
26817
  }
25918
26818
  });
25919
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
26819
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
25920
26820
  try {
25921
- return await host.call(request.params);
26821
+ return await host.call(request.params, { signal: extra.signal });
25922
26822
  } catch (error4) {
25923
26823
  return {
25924
26824
  isError: true,
@@ -25940,6 +26840,7 @@ async function bridge() {
25940
26840
  const close = async () => {
25941
26841
  if (closing) return;
25942
26842
  closing = true;
26843
+ await host.close();
25943
26844
  await server.close().catch(() => {
25944
26845
  });
25945
26846
  await client.close().catch(() => {