@promptframe/creation 0.3.3 → 0.3.4

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,900 @@ 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 uploadGrantedPart(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
+
7636
+ // lib/local-upload-state.mjs
7637
+ import { constants as constants2 } from "node:fs";
7638
+ 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";
7639
+ import path3 from "node:path";
7640
+ import { randomBytes as randomBytes2 } from "node:crypto";
7641
+ var fail2 = () => {
7642
+ throw new CreationClientError("creation.local_upload.recovery_state_unavailable");
7643
+ };
7644
+ var flags = constants2.O_NOFOLLOW;
7645
+ var maxBytes = 1024 * 1024;
7646
+ var maxRecords = 100;
7647
+ var retentionMs = 24 * 60 * 60 * 1e3;
7648
+ async function directory(root) {
7649
+ try {
7650
+ await mkdir2(root, { mode: 448 });
7651
+ } catch (e) {
7652
+ if (e.code !== "EEXIST") throw e;
7653
+ }
7654
+ const info5 = await lstat3(root);
7655
+ if (!info5.isDirectory() || info5.isSymbolicLink() || info5.mode & 63 || process.getuid && info5.uid !== process.getuid()) fail2();
7656
+ }
7657
+ async function read(file) {
7658
+ let fd;
7659
+ try {
7660
+ fd = await open2(file, constants2.O_RDONLY | flags);
7661
+ const info5 = await fd.stat();
7662
+ if (!info5.isFile() || info5.mode & 63 || info5.size > maxBytes || process.getuid && info5.uid !== process.getuid()) fail2();
7663
+ return JSON.parse(await fd.readFile("utf8"));
7664
+ } catch (e) {
7665
+ if (e.code === "ENOENT") return null;
7666
+ fail2();
7667
+ } finally {
7668
+ await fd?.close();
7669
+ }
7670
+ }
7671
+ async function syncDirectory(root) {
7672
+ if (process.platform === "win32") return;
7673
+ const fd = await open2(root, constants2.O_RDONLY | constants2.O_DIRECTORY | flags);
7674
+ try {
7675
+ await fd.sync();
7676
+ } finally {
7677
+ await fd.close();
7678
+ }
7679
+ }
7680
+ async function birth(pid) {
7681
+ if (process.platform !== "linux") return null;
7682
+ try {
7683
+ const stat2 = await readFile2(`/proc/${pid}/stat`, "utf8"), end = stat2.lastIndexOf(")");
7684
+ return { boot: (await readFile2("/proc/sys/kernel/random/boot_id", "utf8")).trim(), start: stat2.slice(end + 2).split(" ")[19] };
7685
+ } catch (e) {
7686
+ if (e.code === "ENOENT") return false;
7687
+ fail2();
7688
+ }
7689
+ }
7690
+ async function localUploadState(root, { now = Date.now } = {}) {
7691
+ try {
7692
+ await directory(root);
7693
+ } catch {
7694
+ fail2();
7695
+ }
7696
+ const ownBirth = await birth(process.pid), owner = { pid: process.pid, birth: ownBirth, nonce: randomBytes2(16).toString("hex") };
7697
+ const file = (key) => {
7698
+ if (!/^[a-f0-9]{64}$/.test(key)) fail2();
7699
+ return path3.join(root, key + ".json");
7700
+ };
7701
+ async function write(key, value2) {
7702
+ const body = JSON.stringify(value2);
7703
+ if (Buffer.byteLength(body) > maxBytes) fail2();
7704
+ const destination = file(key), temporary = path3.join(root, key + "-" + randomBytes2(12).toString("hex") + ".partial");
7705
+ let fd;
7706
+ try {
7707
+ fd = await open2(temporary, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL | flags, 384);
7708
+ await fd.writeFile(body);
7709
+ await fd.sync();
7710
+ await fd.close();
7711
+ fd = void 0;
7712
+ const current = await lstat3(destination).catch((e) => {
7713
+ if (e.code !== "ENOENT") throw e;
7714
+ });
7715
+ if (current && (!current.isFile() || current.isSymbolicLink() || current.mode & 63)) fail2();
7716
+ await rename2(temporary, destination);
7717
+ await syncDirectory(root);
7718
+ } catch {
7719
+ fail2();
7720
+ } finally {
7721
+ await fd?.close();
7722
+ await unlink2(temporary).catch(() => {
7723
+ });
7724
+ }
7725
+ }
7726
+ async function lock(key) {
7727
+ const target = path3.join(root, key + ".lock");
7728
+ file(key);
7729
+ const reclaiming = async () => (await readdir(root)).some((name) => name.startsWith(key + ".reclaim-"));
7730
+ for (let attempt = 0; attempt < 2; attempt++) {
7731
+ if (await reclaiming()) throw new CreationClientError("creation.local_upload.transfer_owned_by_another_bridge");
7732
+ const staging = path3.join(root, key + "-" + randomBytes2(12).toString("hex") + ".claim");
7733
+ await mkdir2(staging, { mode: 448 });
7734
+ const prepared = await open2(path3.join(staging, "owner.json"), constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL | flags, 384);
7735
+ try {
7736
+ await prepared.writeFile(JSON.stringify(owner));
7737
+ await prepared.sync();
7738
+ } finally {
7739
+ await prepared.close();
7740
+ }
7741
+ await syncDirectory(staging);
7742
+ try {
7743
+ await rename2(staging, target);
7744
+ } catch (e) {
7745
+ await unlink2(path3.join(staging, "owner.json"));
7746
+ await rmdir(staging);
7747
+ if (!["EEXIST", "ENOTEMPTY"].includes(e.code)) fail2();
7748
+ const info5 = await lstat3(target);
7749
+ if (!info5.isDirectory() || info5.isSymbolicLink() || info5.mode & 63) fail2();
7750
+ const old = await read(path3.join(target, "owner.json"));
7751
+ if (!old || !Number.isSafeInteger(old.pid) || old.pid < 1 || !old.birth || process.platform !== "linux")
7752
+ throw new CreationClientError("creation.local_upload.transfer_owned_by_another_bridge");
7753
+ const current = await birth(old.pid);
7754
+ if (current && current.boot === old.birth.boot && current.start === old.birth.start)
7755
+ throw new CreationClientError("creation.local_upload.transfer_owned_by_another_bridge");
7756
+ if (!/^[a-f0-9]{32}$/.test(old.nonce)) fail2();
7757
+ const marker = path3.join(root, key + ".reclaim-" + old.nonce);
7758
+ try {
7759
+ await mkdir2(marker, { mode: 448 });
7760
+ } catch {
7761
+ throw new CreationClientError("creation.local_upload.transfer_owned_by_another_bridge");
7762
+ }
7763
+ try {
7764
+ const again = await read(path3.join(target, "owner.json"));
7765
+ if (JSON.stringify(again) !== JSON.stringify(old)) fail2();
7766
+ await unlink2(path3.join(target, "owner.json"));
7767
+ await rmdir(target);
7768
+ await syncDirectory(root);
7769
+ } finally {
7770
+ await rmdir(marker);
7771
+ await syncDirectory(root);
7772
+ }
7773
+ continue;
7774
+ }
7775
+ if (await reclaiming()) {
7776
+ const current = await read(path3.join(target, "owner.json"));
7777
+ if (current?.nonce !== owner.nonce) fail2();
7778
+ await unlink2(path3.join(target, "owner.json"));
7779
+ await rmdir(target);
7780
+ throw new CreationClientError("creation.local_upload.transfer_owned_by_another_bridge");
7781
+ }
7782
+ await syncDirectory(root);
7783
+ return async () => {
7784
+ const current = await read(path3.join(target, "owner.json"));
7785
+ if (current?.nonce !== owner.nonce) fail2();
7786
+ await unlink2(path3.join(target, "owner.json"));
7787
+ await rmdir(target);
7788
+ await syncDirectory(root);
7789
+ };
7790
+ }
7791
+ fail2();
7792
+ }
7793
+ async function cleanup({ admitNew = false } = {}) {
7794
+ const names = await readdir(root);
7795
+ let records = 0;
7796
+ for (const name of names) {
7797
+ if (/^[a-f0-9]{64}\.json$/.test(name)) {
7798
+ const key = name.slice(0, -5), value2 = await read(file(key));
7799
+ records++;
7800
+ const cutoff = Date.parse(value2?.expiresAt ?? "") + retentionMs;
7801
+ if (!Number.isFinite(cutoff) || now() < cutoff) continue;
7802
+ let release;
7803
+ try {
7804
+ release = await lock(key);
7805
+ } catch (e) {
7806
+ if (e instanceof CreationClientError) continue;
7807
+ throw e;
7808
+ }
7809
+ try {
7810
+ const latest = await read(file(key));
7811
+ if (JSON.stringify(latest) === JSON.stringify(value2)) {
7812
+ await unlink2(file(key));
7813
+ records--;
7814
+ }
7815
+ } finally {
7816
+ await release();
7817
+ }
7818
+ } else if (/^[a-f0-9]{64}-[a-f0-9]{24}\.claim$/.test(name)) {
7819
+ const target = path3.join(root, name), info5 = await lstat3(target);
7820
+ if (!info5.isDirectory() || info5.isSymbolicLink() || info5.mode & 63 || now() - info5.mtimeMs <= retentionMs) continue;
7821
+ const old = await read(path3.join(target, "owner.json"));
7822
+ if (!old || process.platform !== "linux") continue;
7823
+ const current = await birth(old.pid);
7824
+ if (current && current.boot === old.birth?.boot && current.start === old.birth?.start) continue;
7825
+ if (JSON.stringify(await read(path3.join(target, "owner.json"))) !== JSON.stringify(old)) continue;
7826
+ await unlink2(path3.join(target, "owner.json"));
7827
+ await rmdir(target);
7828
+ } else if (/^[a-f0-9]{64}-[a-f0-9]{24}\.partial$/.test(name)) {
7829
+ const info5 = await lstat3(path3.join(root, name));
7830
+ if (info5.isFile() && !info5.isSymbolicLink() && (!process.getuid || info5.uid === process.getuid()) && !(info5.mode & 63) && now() - info5.mtimeMs > retentionMs) {
7831
+ let release;
7832
+ try {
7833
+ release = await lock(name.slice(0, 64));
7834
+ } catch {
7835
+ continue;
7836
+ }
7837
+ try {
7838
+ await unlink2(path3.join(root, name));
7839
+ } finally {
7840
+ await release();
7841
+ }
7842
+ }
7843
+ }
7844
+ }
7845
+ await syncDirectory(root);
7846
+ if (admitNew && records >= maxRecords) throw new CreationClientError("creation.local_upload.local_recovery_limit");
7847
+ }
7848
+ return { read: async (key) => read(file(key)), write, lock, cleanup };
7849
+ }
7850
+
7851
+ // lib/local-upload.mjs
7852
+ var LOCAL_UPLOAD_PROTOCOL = "creation-local-file-upload/v1";
7853
+ var wire = "direct-object-upload.v2";
7854
+ var digest = (value2) => createHash2("sha256").update(JSON.stringify(value2)).digest("hex");
7855
+ var fail3 = (code) => {
7856
+ throw new CreationClientError("creation.local_upload." + code);
7857
+ };
7858
+ var knownError = (error4) => error4 instanceof CreationClientError && /^creation\.[a-z0-9_.:-]{1,180}$/.test(error4.message) ? error4.message : "creation.local_upload.control_unconfirmed";
7859
+ var typeByExtension = {
7860
+ ".png": ["image", "image/png"],
7861
+ ".jpg": ["image", "image/jpeg"],
7862
+ ".jpeg": ["image", "image/jpeg"],
7863
+ ".webp": ["image", "image/webp"],
7864
+ ".gif": ["image", "image/gif"],
7865
+ ".wav": ["audio", "audio/wav"],
7866
+ ".mp3": ["audio", "audio/mpeg"],
7867
+ ".m4a": ["audio", "audio/mp4"],
7868
+ ".flac": ["audio", "audio/flac"],
7869
+ ".mp4": ["video", "video/mp4"],
7870
+ ".mov": ["video", "video/quicktime"],
7871
+ ".webm": ["video", "video/webm"],
7872
+ ".pdf": ["document", "application/pdf"]
7873
+ };
7874
+ var terminal = /* @__PURE__ */ new Set(["ready", "aborted", "expired", "rejected"]);
7875
+ var sessionCheck = (session, state) => {
7876
+ 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");
7877
+ return session;
7878
+ };
7879
+ function partReceipts(authorization, state) {
7880
+ const session = sessionCheck(authorization?.session, state);
7881
+ if (authorization.contractVersion !== wire || !Array.isArray(authorization.uploadedParts) || !Array.isArray(authorization.grants) || authorization.grants.length > 2 || !Number.isSafeInteger(session.partSizeBytes) || session.partSizeBytes < 1 || session.partCount !== Math.ceil(state.file.sizeBytes / session.partSizeBytes)) fail3("authorization_invalid");
7882
+ const seen = /* @__PURE__ */ new Set();
7883
+ for (const part of authorization.uploadedParts) {
7884
+ 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 || part.sizeBytes !== Math.min(session.partSizeBytes, state.file.sizeBytes - (part.partNumber - 1) * session.partSizeBytes))
7885
+ fail3("part_receipt_unconfirmed");
7886
+ seen.add(part.partNumber);
7887
+ }
7888
+ return new Map(authorization.uploadedParts.map((part) => [part.partNumber, part]));
7889
+ }
7890
+ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch, now = Date.now } = {}) {
7891
+ if (!stateRoot) fail3("recovery_state_unavailable");
7892
+ let storePromise, closing = false, closePromise;
7893
+ const jobs = /* @__PURE__ */ new Map(), activeCalls = /* @__PURE__ */ new Set(), callControllers = /* @__PURE__ */ new Set();
7894
+ const store = () => storePromise ??= localUploadState(stateRoot, { now });
7895
+ const view = (state, job) => ({
7896
+ success: true,
7897
+ contractVersion: LOCAL_UPLOAD_PROTOCOL,
7898
+ idempotencyKey: state.idempotencyKey,
7899
+ projectId: state.projectId,
7900
+ sessionId: state.sessionId,
7901
+ file: { name: state.file.name, sizeBytes: state.file.sizeBytes, checksum: state.file.checksum },
7902
+ fileHost: { os: platform(), machine: hostname(), location: "bridge_host" },
7903
+ status: job ? "transferring" : state.phase,
7904
+ uploadId: state.uploadId ?? null,
7905
+ assetId: state.assetId ?? null,
7906
+ progress: { uploadedBytes: state.parts.reduce((sum, p2) => sum + p2.sizeBytes, 0) + (job?.progress ?? 0), totalBytes: state.file.sizeBytes },
7907
+ ...state.jobId ? { jobId: state.jobId } : {},
7908
+ ...state.errorCode ? { errorCode: state.errorCode } : {},
7909
+ ...state.result ? { result: state.result } : {},
7910
+ automaticReplayAllowed: false,
7911
+ 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."
7912
+ });
7913
+ async function rpc(send, transfer2) {
7914
+ const response = await send(transfer2);
7915
+ const result = response?.result ?? response;
7916
+ if (result?.isError) {
7917
+ let body2;
7918
+ try {
7919
+ body2 = JSON.parse(result.content?.find((block) => block.type === "text")?.text);
7920
+ } catch {
7921
+ }
7922
+ if (typeof body2?.errorCode === "string" && /^creation\.[a-z0-9_.:-]{1,180}$/.test(body2.errorCode)) throw new CreationClientError(body2.errorCode);
7923
+ fail3("control_unconfirmed");
7924
+ }
7925
+ let body;
7926
+ try {
7927
+ body = result.structuredContent ?? JSON.parse(result.content?.find((block) => block.type === "text")?.text);
7928
+ } catch {
7929
+ fail3("control_unconfirmed");
7930
+ }
7931
+ if (!body || body.success !== true) fail3("control_unconfirmed");
7932
+ return body;
7933
+ }
7934
+ async function observe(state, send, persist) {
7935
+ if (!state.uploadId) return state;
7936
+ const session = sessionCheck((await rpc(send, { action: "inspect", uploadId: state.uploadId })).session, state);
7937
+ state.expiresAt = session.expiresAt;
7938
+ if (["aborted", "expired", "rejected"].includes(session.state)) {
7939
+ state.phase = session.state;
7940
+ delete state.errorCode;
7941
+ } else if (session.state === "finalized") {
7942
+ state.jobId ??= `direct-upload:${state.uploadId}`;
7943
+ const response = await send({ action: "derivation", jobId: state.jobId });
7944
+ const result = response?.result ?? response;
7945
+ let body;
7946
+ try {
7947
+ body = result.structuredContent ?? JSON.parse(result.content?.find((block) => block.type === "text")?.text);
7948
+ } catch {
7949
+ fail3("control_unconfirmed");
7950
+ }
7951
+ if (result.isError) fail3("control_unconfirmed");
7952
+ if (body?.success === true && body.uploadId === state.uploadId && body.assetId === state.assetId) {
7953
+ state.phase = body.status === "ready" ? "ready" : body.status === "failed" ? "derivation_failed" : "derivatives_pending";
7954
+ state.result = { success: true, status: body.status, uploadId: state.uploadId, assetId: state.assetId, jobId: state.jobId };
7955
+ delete state.errorCode;
7956
+ } else if (body?.errorCode === "media_derivation.job_not_found") {
7957
+ state.phase = "completion_unconfirmed";
7958
+ state.errorCode = "creation.local_upload.completion_unconfirmed";
7959
+ } else fail3("session_identity_unconfirmed");
7960
+ }
7961
+ if (persist) await persist();
7962
+ return state;
7963
+ }
7964
+ async function transfer(job, authorization, send, binding) {
7965
+ const { state, file, abort, save } = job;
7966
+ const fileBudget = authorization?.transferBudget?.file?.totalMs ?? 6e5;
7967
+ if (!Number.isSafeInteger(fileBudget) || fileBudget < 1 || fileBudget > 18e5) fail3("transfer_budget_invalid");
7968
+ state.deadlineAtMs = Math.min(state.deadlineAtMs, (state.startedAtMs ?? now()) + fileBudget, Date.parse(state.expiresAt));
7969
+ await save();
7970
+ if (state.deadlineAtMs <= now()) fail3("transfer_deadline_expired");
7971
+ let envelope = authorization;
7972
+ while (true) {
7973
+ await binding.assertCurrent();
7974
+ abort.signal.throwIfAborted();
7975
+ await file.assertUnchanged();
7976
+ const session = sessionCheck(envelope.session, state);
7977
+ if (session.state === "finalized") break;
7978
+ if (!["authorized", "uploading"].includes(session.state)) fail3("session_not_transferable");
7979
+ const parts = partReceipts(envelope, state);
7980
+ state.parts = [...parts.values()].sort((a, b2) => a.partNumber - b2.partNumber);
7981
+ await save();
7982
+ if (parts.size === session.partCount) break;
7983
+ if (!envelope.grants.length) fail3("authorization_invalid");
7984
+ for (const grant of envelope.grants) {
7985
+ if (parts.has(grant.partNumber)) fail3("authorization_invalid");
7986
+ await binding.assertCurrent();
7987
+ abort.signal.throwIfAborted();
7988
+ state.phase = "transferring";
7989
+ state.pendingPart = grant.partNumber;
7990
+ await save();
7991
+ const part = await uploadGrantedPart(file, envelope, grant, {
7992
+ expectedUploadId: state.uploadId,
7993
+ expectedAssetId: state.assetId,
7994
+ signal: abort.signal,
7995
+ deadlineAtMs: state.deadlineAtMs,
7996
+ fetch: fetch2,
7997
+ now,
7998
+ onProgress: (progress) => {
7999
+ job.progress = progress.bytesRead;
8000
+ }
8001
+ });
8002
+ state.parts.push(part);
8003
+ state.parts.sort((a, b2) => a.partNumber - b2.partNumber);
8004
+ job.progress = 0;
8005
+ delete state.pendingPart;
8006
+ await save();
8007
+ }
8008
+ await binding.assertCurrent();
8009
+ abort.signal.throwIfAborted();
8010
+ envelope = (await rpc(send, { action: "resume", uploadId: state.uploadId })).authorization;
8011
+ }
8012
+ await binding.assertCurrent();
8013
+ abort.signal.throwIfAborted();
8014
+ await file.assertUnchanged();
8015
+ state.phase = "completing";
8016
+ await save();
8017
+ const completed = await rpc(send, { action: "complete", request: {
8018
+ contractVersion: wire,
8019
+ uploadId: state.uploadId,
8020
+ idempotencyKey: state.completeKey,
8021
+ parts: state.parts
8022
+ } });
8023
+ sessionCheck(completed.session, state);
8024
+ state.jobId = completed.jobId;
8025
+ state.phase = "derivatives_pending";
8026
+ delete state.errorCode;
8027
+ await save();
8028
+ }
8029
+ async function callCore({ input, scope, send, binding, signal }) {
8030
+ if (closing) fail3("bridge_closing");
8031
+ 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");
8032
+ if (!scope || Object.values(scope).some((value2) => typeof value2 !== "string" || !value2) || !binding?.assertCurrent) fail3("scope_unverified");
8033
+ await binding.assertCurrent();
8034
+ const key = digest([LOCAL_UPLOAD_PROTOCOL, scope, input.idempotencyKey]), persistence = await store();
8035
+ let job = jobs.get(key), state = job?.state ?? await persistence.read(key);
8036
+ 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");
8037
+ if (job && input.action === "status") return view(state, job);
8038
+ if (job && input.action === "cancel") {
8039
+ job.abort.abort();
8040
+ await job.done;
8041
+ job = void 0;
8042
+ state = await persistence.read(key);
8043
+ }
8044
+ if (job) return view(state, job);
8045
+ if (!state && input.action !== "upload") fail3("original_upload_not_found");
8046
+ if (input.action === "status") {
8047
+ const copy = structuredClone(state);
8048
+ await observe(copy, send);
8049
+ return view(copy);
8050
+ }
8051
+ if (jobs.size >= 2 && !["status", "cancel"].includes(input.action)) fail3("bridge_transfer_limit");
8052
+ await persistence.cleanup({ admitNew: !state });
8053
+ const release = await persistence.lock(key);
8054
+ let file;
8055
+ try {
8056
+ state = await persistence.read(key) ?? state;
8057
+ if (input.action === "cancel") {
8058
+ if (["ready", "derivatives_pending", "derivation_failed"].includes(state.phase))
8059
+ return view(await observe(state, send, () => persistence.write(key, state)));
8060
+ if (!state.uploadId) fail3("create_unconfirmed_observe_original_key");
8061
+ state.phase = "cancelling";
8062
+ await persistence.write(key, state);
8063
+ const result = await rpc(send, { action: "abort", request: {
8064
+ contractVersion: wire,
8065
+ uploadId: state.uploadId,
8066
+ idempotencyKey: state.abortKey,
8067
+ reasonCode: "user_cancelled"
8068
+ } });
8069
+ sessionCheck(result.session, state);
8070
+ state.phase = result.session.state;
8071
+ delete state.errorCode;
8072
+ await persistence.write(key, state);
8073
+ return view(state);
8074
+ }
8075
+ if (state && terminal.has(state.phase)) return view(await observe(state, send, () => persistence.write(key, state)));
8076
+ if (typeof input.filePath !== "string" || input.filePath.length > 4096) fail3("file_selection_required");
8077
+ const startedAtMs = state?.startedAtMs ?? now(), deadlineAtMs = state?.deadlineAtMs ?? startedAtMs + 6e5;
8078
+ file = await openLocalUploadFile(input.filePath, { signal, deadlineAtMs, now });
8079
+ const inferred = typeByExtension[path4.extname(file.name).toLowerCase()] ?? [];
8080
+ const assetKind = input.assetKind ?? inferred[0], mimeType = input.mimeType ?? inferred[1];
8081
+ if (!["image", "audio", "video", "document"].includes(assetKind) || typeof mimeType !== "string" || !/^\S+\/\S+$/.test(mimeType) || mimeType.length > 255) fail3("file_type_required");
8082
+ 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");
8083
+ if (!state) {
8084
+ state = {
8085
+ contractVersion: LOCAL_UPLOAD_PROTOCOL,
8086
+ key,
8087
+ projectId: input.projectId,
8088
+ sessionId: input.sessionId,
8089
+ idempotencyKey: input.idempotencyKey,
8090
+ startedAtMs,
8091
+ deadlineAtMs,
8092
+ completeKey: "complete-" + key,
8093
+ abortKey: "abort-" + key,
8094
+ file: { name: file.name, sizeBytes: file.sizeBytes, checksum: file.checksum, fingerprint: file.fingerprint },
8095
+ request: {
8096
+ contractVersion: wire,
8097
+ originalName: file.name,
8098
+ purpose: "project-asset",
8099
+ assetKind,
8100
+ mimeType,
8101
+ sizeBytes: file.sizeBytes,
8102
+ expectedChecksum: file.checksum,
8103
+ idempotencyKey: "create-" + key
8104
+ },
8105
+ phase: "creating",
8106
+ parts: [],
8107
+ expiresAt: new Date(now() + 30 * 60 * 1e3).toISOString()
8108
+ };
8109
+ await persistence.write(key, state);
8110
+ }
8111
+ await binding.assertCurrent();
8112
+ let authorization;
8113
+ if (!state.uploadId) {
8114
+ const created = await rpc(send, { action: "create", request: state.request });
8115
+ authorization = created.authorization;
8116
+ const session = authorization?.session;
8117
+ if (!session || typeof session.uploadId !== "string" || typeof session.assetId !== "string") fail3("authorization_invalid");
8118
+ state.uploadId = session.uploadId;
8119
+ state.assetId = session.assetId;
8120
+ sessionCheck(session, state);
8121
+ state.expiresAt = session.expiresAt;
8122
+ await persistence.write(key, state);
8123
+ } else {
8124
+ await observe(state, send, () => persistence.write(key, state));
8125
+ if (terminal.has(state.phase) || state.phase === "derivatives_pending" || state.phase === "derivation_failed") return view(state);
8126
+ authorization = (await rpc(send, { action: "resume", uploadId: state.uploadId })).authorization;
8127
+ }
8128
+ signal?.throwIfAborted();
8129
+ const abort = new AbortController();
8130
+ job = { state, file, abort, progress: 0, save: () => persistence.write(key, state) };
8131
+ jobs.set(key, job);
8132
+ file = void 0;
8133
+ job.done = Promise.resolve().then(() => transfer(job, authorization, (transfer2) => send(transfer2, { signal: abort.signal }), binding)).catch(async (error4) => {
8134
+ state.phase = "paused";
8135
+ state.errorCode = abort.signal.aborted ? "creation.local_upload.transfer_cancelled" : knownError(error4);
8136
+ await job.save();
8137
+ }).finally(async () => {
8138
+ try {
8139
+ await job.file.close();
8140
+ } finally {
8141
+ try {
8142
+ await release();
8143
+ } finally {
8144
+ jobs.delete(key);
8145
+ }
8146
+ }
8147
+ });
8148
+ job.done.catch(() => {
8149
+ });
8150
+ return view(state, job);
8151
+ } catch (error4) {
8152
+ if (state) {
8153
+ state.phase = "paused";
8154
+ state.errorCode = knownError(error4);
8155
+ await persistence.write(key, state);
8156
+ }
8157
+ throw error4;
8158
+ } finally {
8159
+ if (!jobs.has(key)) {
8160
+ await file?.close();
8161
+ await release();
8162
+ }
8163
+ }
8164
+ }
8165
+ return { call(options) {
8166
+ if (closing) fail3("bridge_closing");
8167
+ const controller = new AbortController(), abort = () => controller.abort();
8168
+ if (options.signal?.aborted) abort();
8169
+ else options.signal?.addEventListener("abort", abort, { once: true });
8170
+ callControllers.add(controller);
8171
+ const send = (transfer2, extra = {}) => options.send(transfer2, { signal: controller.signal, ...extra });
8172
+ const pending = callCore({ ...options, send, signal: controller.signal }).finally(() => {
8173
+ activeCalls.delete(pending);
8174
+ callControllers.delete(controller);
8175
+ options.signal?.removeEventListener("abort", abort);
8176
+ });
8177
+ activeCalls.add(pending);
8178
+ return pending;
8179
+ }, close() {
8180
+ return closePromise ??= (async () => {
8181
+ closing = true;
8182
+ for (const controller of callControllers) controller.abort();
8183
+ for (const job of jobs.values()) job.abort.abort();
8184
+ await Promise.allSettled([...activeCalls]);
8185
+ for (const job of jobs.values()) job.abort.abort();
8186
+ await Promise.allSettled([...jobs.values()].map((job) => job.done));
8187
+ })();
8188
+ } };
8189
+ }
8190
+
7303
8191
  // lib/version.mjs
7304
- var CLIENT_VERSION = "0.3.3";
8192
+ var CLIENT_VERSION = "0.3.4";
7305
8193
  var CLIENT_PROTOCOL = "creation-client/v1";
7306
8194
 
7307
8195
  // lib/cli.mjs
7308
- import { randomBytes as randomBytes7 } from "node:crypto";
8196
+ import { randomBytes as randomBytes8 } from "node:crypto";
7309
8197
  import { spawn as spawn2 } from "node:child_process";
7310
8198
 
7311
8199
  // node_modules/zod/v4/core/util.js
@@ -7545,10 +8433,10 @@ function mergeDefs(...defs) {
7545
8433
  function cloneDef(schema) {
7546
8434
  return mergeDefs(schema._zod.def);
7547
8435
  }
7548
- function getElementAtPath(obj, path14) {
7549
- if (!path14)
8436
+ function getElementAtPath(obj, path17) {
8437
+ if (!path17)
7550
8438
  return obj;
7551
- return path14.reduce((acc, key) => acc?.[key], obj);
8439
+ return path17.reduce((acc, key) => acc?.[key], obj);
7552
8440
  }
7553
8441
  function promiseAllObject(promisesObj) {
7554
8442
  const keys = Object.keys(promisesObj);
@@ -7888,11 +8776,11 @@ function explicitlyAborted(x, startIndex = 0) {
7888
8776
  }
7889
8777
  return false;
7890
8778
  }
7891
- function prefixIssues(path14, issues) {
8779
+ function prefixIssues(path17, issues) {
7892
8780
  return issues.map((iss) => {
7893
8781
  var _a3;
7894
8782
  (_a3 = iss).path ?? (_a3.path = []);
7895
- iss.path.unshift(path14);
8783
+ iss.path.unshift(path17);
7896
8784
  return iss;
7897
8785
  });
7898
8786
  }
@@ -8353,16 +9241,16 @@ function flattenError(error4, mapper = (issue2) => issue2.message) {
8353
9241
  }
8354
9242
  function formatError(error4, mapper = (issue2) => issue2.message) {
8355
9243
  const fieldErrors = { _errors: [] };
8356
- const processError = (error5, path14 = []) => {
9244
+ const processError = (error5, path17 = []) => {
8357
9245
  for (const issue2 of error5.issues) {
8358
9246
  if (issue2.code === "invalid_union" && issue2.errors.length) {
8359
- issue2.errors.map((issues) => processError({ issues }, [...path14, ...issue2.path]));
9247
+ issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
8360
9248
  } else if (issue2.code === "invalid_key") {
8361
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
9249
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
8362
9250
  } else if (issue2.code === "invalid_element") {
8363
- processError({ issues: issue2.issues }, [...path14, ...issue2.path]);
9251
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
8364
9252
  } else {
8365
- const fullpath = [...path14, ...issue2.path];
9253
+ const fullpath = [...path17, ...issue2.path];
8366
9254
  if (fullpath.length === 0) {
8367
9255
  fieldErrors._errors.push(mapper(issue2));
8368
9256
  } else {
@@ -8370,9 +9258,9 @@ function formatError(error4, mapper = (issue2) => issue2.message) {
8370
9258
  let i = 0;
8371
9259
  while (i < fullpath.length) {
8372
9260
  const el = fullpath[i];
8373
- const terminal = i === fullpath.length - 1;
9261
+ const terminal2 = i === fullpath.length - 1;
8374
9262
  if (el === "_errors") {
8375
- if (terminal)
9263
+ if (terminal2)
8376
9264
  curr._errors.push(mapper(issue2));
8377
9265
  i++;
8378
9266
  continue;
@@ -8386,7 +9274,7 @@ function formatError(error4, mapper = (issue2) => issue2.message) {
8386
9274
  });
8387
9275
  }
8388
9276
  const node2 = curr[el];
8389
- if (terminal) {
9277
+ if (terminal2) {
8390
9278
  node2._errors.push(mapper(issue2));
8391
9279
  }
8392
9280
  curr = node2;
@@ -8441,10 +9329,10 @@ var _safeParse = (_Err) => (schema, value2, _ctx) => {
8441
9329
  if (result instanceof Promise) {
8442
9330
  throw new $ZodAsyncError();
8443
9331
  }
8444
- return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
9332
+ return result.issues.length ? failure2(_Err, result.issues, ctx) : { success: true, data: result.value };
8445
9333
  };
8446
9334
  var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
8447
- function failure(Err, issues, ctx) {
9335
+ function failure2(Err, issues, ctx) {
8448
9336
  let error4;
8449
9337
  return {
8450
9338
  success: false,
@@ -8468,7 +9356,7 @@ var _safeParseAsync = (_Err) => async (schema, value2, _ctx) => {
8468
9356
  let result = schema._zod.run({ value: value2, issues: [] }, ctx);
8469
9357
  if (result instanceof Promise)
8470
9358
  result = await result;
8471
- return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };
9359
+ return result.issues.length ? failure2(_Err, result.issues, ctx) : { success: true, data: result.value };
8472
9360
  };
8473
9361
  var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid");
8474
9362
  var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback");
@@ -9197,9 +10085,9 @@ var asciiTabOrNewline = /[\t\n\r]/g;
9197
10085
  function stripTabAndNewline(value2) {
9198
10086
  return value2.replace(asciiTabOrNewline, "");
9199
10087
  }
9200
- function urlHostnameOk(url2, hostname) {
9201
- hostname.lastIndex = 0;
9202
- return hostname.test(url2.hostname);
10088
+ function urlHostnameOk(url2, hostname2) {
10089
+ hostname2.lastIndex = 0;
10090
+ return hostname2.test(url2.hostname);
9203
10091
  }
9204
10092
  function urlProtocolOk(url2, protocol) {
9205
10093
  protocol.lastIndex = 0;
@@ -10857,7 +11745,7 @@ function bucketFor(state, inst) {
10857
11745
  return bucket;
10858
11746
  }
10859
11747
  var handoff;
10860
- var open = [];
11748
+ var open3 = [];
10861
11749
  var memo = {
10862
11750
  alloc(_inst, payload, empty) {
10863
11751
  const bucket = handoff;
@@ -10866,7 +11754,7 @@ var memo = {
10866
11754
  handoff = void 0;
10867
11755
  const entry = { value: empty, issues: null };
10868
11756
  bucket.set(payload.value, entry);
10869
- open.push(entry);
11757
+ open3.push(entry);
10870
11758
  return empty;
10871
11759
  },
10872
11760
  guard(inst) {
@@ -10937,10 +11825,10 @@ var memo = {
10937
11825
  return payload;
10938
11826
  }
10939
11827
  handoff = bucket;
10940
- const depth = open.length;
11828
+ const depth = open3.length;
10941
11829
  const result = base(payload, ctx);
10942
11830
  handoff = void 0;
10943
- const entry = open.length > depth ? open.pop() : void 0;
11831
+ const entry = open3.length > depth ? open3.pop() : void 0;
10944
11832
  if (result instanceof Promise) {
10945
11833
  return result.then((r) => {
10946
11834
  if (entry)
@@ -17312,93 +18200,6 @@ var StdioServerTransport = class {
17312
18200
  }
17313
18201
  };
17314
18202
 
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
18203
  // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
17403
18204
  var ExperimentalClientTasks = class {
17404
18205
  constructor(_client) {
@@ -18183,8 +18984,8 @@ async function random(size) {
18183
18984
  const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
18184
18985
  let result = "";
18185
18986
  while (result.length < size) {
18186
- const randomBytes8 = await getRandomValues(size - result.length);
18187
- for (const randomByte of randomBytes8) {
18987
+ const randomBytes9 = await getRandomValues(size - result.length);
18988
+ for (const randomByte of randomBytes9) {
18188
18989
  if (randomByte < evenDistCutoff) {
18189
18990
  result += mask[randomByte % mask.length];
18190
18991
  }
@@ -19827,23 +20628,23 @@ async function connectPlatform(credentials, { host = resolveHostIdentity(), cont
19827
20628
  }
19828
20629
 
19829
20630
  // lib/host-context.mjs
19830
- import { createHash as createHash3 } from "node:crypto";
20631
+ import { createHash as createHash5 } from "node:crypto";
19831
20632
 
19832
20633
  // 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";
20634
+ import { constants as constants3 } from "node:fs";
20635
+ import { open as open4, mkdir as mkdir3, lstat as lstat4, rename as rename3, unlink as unlink3, rmdir as rmdir2 } from "node:fs/promises";
20636
+ import path6 from "node:path";
19836
20637
  import { homedir as homedir3 } from "node:os";
19837
- import { createHash as createHash2, randomBytes as randomBytes2 } from "node:crypto";
20638
+ import { createHash as createHash4, randomBytes as randomBytes3 } from "node:crypto";
19838
20639
 
19839
20640
  // lib/claude-host-process.mjs
19840
- import { readFile as readFile2, readlink, stat } from "node:fs/promises";
19841
- import path2 from "node:path";
20641
+ import { readFile as readFile3, readlink, stat } from "node:fs/promises";
20642
+ import path5 from "node:path";
19842
20643
  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");
20644
+ import { createHash as createHash3 } from "node:crypto";
20645
+ var hash = (value2) => createHash3("sha256").update(JSON.stringify(value2)).digest("hex");
19845
20646
  var bounded = async (file) => {
19846
- const value2 = await readFile2(file);
20647
+ const value2 = await readFile3(file);
19847
20648
  if (value2.length > 65536) throw Error("host_process_invalid");
19848
20649
  return value2;
19849
20650
  };
@@ -19872,8 +20673,8 @@ async function claudeHostProcess({
19872
20673
  if (visited.has(child.ppid)) return null;
19873
20674
  visited.add(child.ppid);
19874
20675
  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)) {
20676
+ const roots2 = [path5.join(home, ".claude", "remote", "ccd-cli"), path5.join(home, ".local", "share", "claude", "versions")];
20677
+ if (roots2.some((root) => path5.dirname(host.exe) === root)) {
19877
20678
  const executable = await readExecutable(host.exe);
19878
20679
  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
20680
  if (purpose === "hook") {
@@ -19881,8 +20682,8 @@ async function claudeHostProcess({
19881
20682
  if (!entryFile || !command2.some((arg) => arg.includes(entryFile)) || !command2.some((arg) => arg === "claude-host-hook" || arg.includes(" claude-host-hook"))) return null;
19882
20683
  }
19883
20684
  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() {
20685
+ const digest5 = hash(binding);
20686
+ return { binding, digest: digest5, eventOrder: { birth: child.birth, pid: child.pid }, async isCurrent() {
19886
20687
  try {
19887
20688
  const current = await readBirth(binding.pid);
19888
20689
  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 +20711,22 @@ var canonical = (value2) => {
19910
20711
  return "{" + Object.keys(value2).sort().map((key) => JSON.stringify(key) + ":" + canonical(value2[key])).join(",") + "}";
19911
20712
  throw error2("request_invalid");
19912
20713
  };
19913
- var digest = (value2) => createHash2("sha256").update(canonical(value2)).digest("hex");
20714
+ var digest2 = (value2) => createHash4("sha256").update(canonical(value2)).digest("hex");
19914
20715
  var withoutProof = (args2) => Object.fromEntries(Object.entries(args2 ?? {}).filter(([key]) => key !== CLAUDE_HOST_PROOF));
19915
20716
  var later = (a, b2) => BigInt(a.birth) > BigInt(b2.birth) || a.birth === b2.birth && a.pid > b2.pid;
19916
- async function privateDirectory(directory) {
20717
+ async function privateDirectory(directory2) {
19917
20718
  try {
19918
- await mkdir2(directory, { mode: 448 });
20719
+ await mkdir3(directory2, { mode: 448 });
19919
20720
  } catch (e) {
19920
20721
  if (e.code !== "EEXIST") throw e;
19921
20722
  }
19922
- const info5 = await lstat2(directory);
20723
+ const info5 = await lstat4(directory2);
19923
20724
  if (!info5.isDirectory() || info5.isSymbolicLink() || info5.uid !== process.getuid?.() || info5.mode & 63) throw error2("host_identity_unavailable");
19924
20725
  }
19925
20726
  async function privateRead(file) {
19926
20727
  let handle;
19927
20728
  try {
19928
- handle = await open2(file, constants.O_RDONLY | constants.O_NOFOLLOW);
20729
+ handle = await open4(file, constants3.O_RDONLY | constants3.O_NOFOLLOW);
19929
20730
  const info5 = await handle.stat();
19930
20731
  if (!info5.isFile() || info5.uid !== process.getuid?.() || info5.mode & 63 || info5.size > 196608) throw error2("host_identity_unavailable");
19931
20732
  return JSON.parse(await handle.readFile("utf8"));
@@ -19938,9 +20739,9 @@ async function privateRead(file) {
19938
20739
  }
19939
20740
  async function createClaudeHostSession({ configFile: configFile2, env = process.env, root, association, hookProcess = false } = {}) {
19940
20741
  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");
20742
+ const base = root ?? path6.join(env.CLAUDE_CONFIG_DIR ?? path6.join(homedir3(), ".claude"), "promptframe-host-sessions");
20743
+ const namespace = owner ? path6.join(base, digest2([owner.digest, path6.resolve(configFile2)])) : null;
20744
+ const stateFile = namespace && path6.join(namespace, "state.json");
19944
20745
  async function state() {
19945
20746
  if (!owner || !await owner.isCurrent()) return null;
19946
20747
  const value2 = await privateRead(stateFile);
@@ -19952,10 +20753,10 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
19952
20753
  if (!owner || !await owner.isCurrent()) throw error2("host_identity_unavailable");
19953
20754
  await privateDirectory(base);
19954
20755
  await privateDirectory(namespace);
19955
- const lock = path3.join(namespace, "write.lock");
20756
+ const lock = path6.join(namespace, "write.lock");
19956
20757
  let acquired = false;
19957
20758
  for (let count = 0; count < 100; count++) try {
19958
- await mkdir2(lock, { mode: 448 });
20759
+ await mkdir3(lock, { mode: 448 });
19959
20760
  acquired = true;
19960
20761
  break;
19961
20762
  } catch (e) {
@@ -19969,13 +20770,13 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
19969
20770
  const current = await state(), next = await work(current);
19970
20771
  if (next === void 0) return;
19971
20772
  if (next === null) {
19972
- if (current) await unlink2(stateFile);
20773
+ if (current) await unlink3(stateFile);
19973
20774
  return;
19974
20775
  }
19975
20776
  const body = JSON.stringify(next);
19976
20777
  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);
20778
+ temporary = path6.join(namespace, "state-" + randomBytes3(16).toString("hex") + ".partial");
20779
+ const file = await open4(temporary, constants3.O_WRONLY | constants3.O_CREAT | constants3.O_EXCL | constants3.O_NOFOLLOW, 384);
19979
20780
  try {
19980
20781
  await file.writeFile(body);
19981
20782
  await file.sync();
@@ -19983,18 +20784,18 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
19983
20784
  await file.close();
19984
20785
  }
19985
20786
  if (!await owner.isCurrent()) throw error2("host_identity_unavailable");
19986
- await rename2(temporary, stateFile);
20787
+ await rename3(temporary, stateFile);
19987
20788
  temporary = void 0;
19988
- const directory = await open2(namespace, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
20789
+ const directory2 = await open4(namespace, constants3.O_RDONLY | constants3.O_DIRECTORY | constants3.O_NOFOLLOW);
19989
20790
  try {
19990
- await directory.sync();
20791
+ await directory2.sync();
19991
20792
  } finally {
19992
- await directory.close();
20793
+ await directory2.close();
19993
20794
  }
19994
20795
  } finally {
19995
- if (temporary) await unlink2(temporary).catch(() => {
20796
+ if (temporary) await unlink3(temporary).catch(() => {
19996
20797
  });
19997
- await rmdir(lock);
20798
+ await rmdir2(lock);
19998
20799
  }
19999
20800
  }
20000
20801
  async function begin(raw) {
@@ -20006,7 +20807,7 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
20006
20807
  try {
20007
20808
  await transaction((current) => {
20008
20809
  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");
20810
+ if (!current?.sessionId || !ticket || ticket.epoch !== current.epoch || ticket.sessionId !== current.sessionId || ticket.digest !== digest2([raw.name, args2])) throw error2("host_identity_invalid");
20010
20811
  accepted = { threadId: current.sessionId, epoch: current.epoch };
20011
20812
  delete current.tickets[proof];
20012
20813
  return current;
@@ -20053,7 +20854,7 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
20053
20854
  tickets: same2 ? current.tickets : {}
20054
20855
  };
20055
20856
  if (event !== "PreToolUse") return next;
20056
- const args2 = withoutProof(rawArgs), tool = input.tool_name.slice(input.tool_name.lastIndexOf("__") + 2), key = digest([tool, args2]);
20857
+ const args2 = withoutProof(rawArgs), tool = input.tool_name.slice(input.tool_name.lastIndexOf("__") + 2), key = digest2([tool, args2]);
20057
20858
  if (!nextId) {
20058
20859
  result = { hookSpecificOutput: { hookEventName: event, updatedInput: args2 } };
20059
20860
  return next;
@@ -20064,13 +20865,13 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
20064
20865
  return next;
20065
20866
  }
20066
20867
  if (Object.keys(next.tickets).length >= 128) delete next.tickets[Object.keys(next.tickets)[0]];
20067
- const token = randomBytes2(32).toString("hex");
20868
+ const token = randomBytes3(32).toString("hex");
20068
20869
  next.tickets[token] = { digest: key, epoch: next.epoch, sessionId: nextId };
20069
20870
  result = { hookSpecificOutput: { hookEventName: event, updatedInput: { ...args2, [CLAUDE_HOST_PROOF]: token } } };
20070
20871
  return next;
20071
20872
  });
20072
20873
  if (event === "SessionEnd") try {
20073
- await rmdir(namespace);
20874
+ await rmdir2(namespace);
20074
20875
  } catch (e) {
20075
20876
  if (!["ENOTEMPTY", "ENOENT"].includes(e.code)) throw e;
20076
20877
  }
@@ -20098,7 +20899,7 @@ async function runClaudeHostHook({ configFile: configFile2, input = process.stdi
20098
20899
  // lib/host-context.mjs
20099
20900
  var digestPattern = /^sha256:[a-f0-9]{64}$/;
20100
20901
  var accesses = /* @__PURE__ */ new Set(["independent-read", "controlled", "authority"]);
20101
- var digest2 = (value2) => "sha256:" + createHash3("sha256").update(value2).digest("hex");
20902
+ var digest3 = (value2) => "sha256:" + createHash5("sha256").update(value2).digest("hex");
20102
20903
  var canonical2 = (value2) => {
20103
20904
  if (value2 === null || typeof value2 === "string" || typeof value2 === "boolean" || typeof value2 === "number" && Number.isFinite(value2)) return JSON.stringify(value2);
20104
20905
  if (Array.isArray(value2)) return "[" + value2.map(canonical2).join(",") + "]";
@@ -20106,19 +20907,19 @@ var canonical2 = (value2) => {
20106
20907
  return "{" + Object.keys(value2).sort().map((key) => JSON.stringify(key) + ":" + canonical2(value2[key])).join(",") + "}";
20107
20908
  throw new CreationClientError("creation.request_invalid");
20108
20909
  };
20109
- var argumentsDigest = (value2) => digest2(canonical2(value2));
20910
+ var argumentsDigest = (value2) => digest3(canonical2(value2));
20110
20911
  var boundedSet = (map, key, value2) => {
20111
20912
  if (!map.has(key) && map.size >= 1024) map.delete(map.keys().next().value);
20112
20913
  map.set(key, value2);
20113
20914
  };
20114
- function createHostCallBridge(client, { credentials, host = resolveHostIdentity(), hostSession, onCatalogChange = () => {
20915
+ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(), hostSession, localUploads, onCatalogChange = () => {
20115
20916
  }, onKnowledgeChange = () => {
20116
20917
  } } = {}) {
20117
20918
  if (!credentials?.endpoint || !credentials.clientId) throw new CreationClientError("creation.bridge_identity_required");
20118
- const installationDigest = digest2(credentials.clientId);
20919
+ const installationDigest = digest3(credentials.clientId);
20119
20920
  const versions = /* @__PURE__ */ new Map(), controllers = /* @__PURE__ */ new Map(), catalogs = /* @__PURE__ */ new Map(), inflight = /* @__PURE__ */ new Map();
20120
20921
  const knowledgeVersions = /* @__PURE__ */ new Map(), upstream = client.getServerCapabilities?.() ?? {};
20121
- let platformDigest, accountDigest, directory, directoryRead, sequence = 0, hostEpoch;
20922
+ let platformDigest, accountDigest, directory2, directoryRead, sequence = 0, hostEpoch;
20122
20923
  function catalog(channel, version3, order) {
20123
20924
  if (typeof version3 !== "string" || !digestPattern.test(version3)) return;
20124
20925
  const old = catalogs.get(channel);
@@ -20135,7 +20936,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20135
20936
  const v2 = result?._meta?.["promptframe.creation"];
20136
20937
  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
20938
  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;
20939
+ if (thread ? v2.host?.kind !== host.kind || v2.host.threadDigest !== digest3(thread) : v2.host?.kind !== "legacy") return null;
20139
20940
  for (const field of ["projectId", "sessionId"]) if (params.arguments?.[field] !== void 0 && v2[field] !== params.arguments[field]) return null;
20140
20941
  if (accountDigest && accountDigest !== v2.accountDigest) return null;
20141
20942
  const controllerKey = thread ?? "legacy", prior = controllers.get(controllerKey);
@@ -20153,7 +20954,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20153
20954
  const key = keyFor(target), c = v2.control;
20154
20955
  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
20956
  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";
20957
+ const authorityRead = directory2?.tools.get(params.name)?._meta?.["promptframe.role"] === "control-read";
20157
20958
  if (!old || version3 > old.version) boundedSet(versions, key, { version: version3, owned, needsRead: false, authorityOrder: order });
20158
20959
  else if (version3 === old.version && order >= (old.authorityOrder ?? 0)) {
20159
20960
  const freshRead = !result.isError && authorityRead && order > (old.invalidatedAt ?? 0);
@@ -20162,27 +20963,30 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20162
20963
  }
20163
20964
  return v2;
20164
20965
  }
20165
- async function send(params, binding) {
20966
+ async function send(params, binding, { signal, timeout = 6e4 } = {}) {
20166
20967
  await binding?.assertCurrent();
20167
- const order = ++sequence, result = assertMcpResponseBudget(await client.callTool(params, void 0, { timeout: 6e4 }));
20968
+ const order = ++sequence, result = assertMcpResponseBudget(await client.callTool(params, void 0, { timeout, ...signal ? { signal } : {} }));
20168
20969
  await binding?.assertCurrent();
20169
20970
  return { result, trusted: remember(params, result, order) };
20170
20971
  }
20171
20972
  async function listTools() {
20172
20973
  const order = ++sequence, result = assertMcpResponseBudget(await client.listTools());
20173
20974
  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 };
20975
+ if (!directory2 || order >= directory2.order) directory2 = { tools: new Map(result.tools.map((t) => [t.name, t])), order };
20175
20976
  catalog("outer", result._meta?.["promptframe.catalogVersion"], order);
20176
20977
  return { ...result, tools: result.tools.map((tool) => {
20177
- const p2 = tool.inputSchema.properties;
20978
+ const local = tool._meta?.["promptframe.localFileUpload"];
20979
+ const schema = local?.contractVersion === LOCAL_UPLOAD_PROTOCOL ? local.inputSchema : tool.inputSchema;
20980
+ if (!schema || schema.type !== "object") throw new CreationClientError("creation.upgrade_required");
20981
+ const p2 = schema.properties;
20178
20982
  const { controlVersion: _managed, ...properties } = p2 ?? {};
20179
- return { ...tool, inputSchema: { ...tool.inputSchema, properties: { ...properties, ...host.kind === "claude-code" ? {
20983
+ return { ...tool, inputSchema: { ...schema, properties: { ...properties, ...host.kind === "claude-code" ? {
20180
20984
  [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") } : {} } };
20985
+ } : {} }, ...schema.required ? { required: schema.required.filter((name) => name !== "controlVersion") } : {} } };
20182
20986
  }) };
20183
20987
  }
20184
20988
  async function ensureDirectory() {
20185
- if (!directory) {
20989
+ if (!directory2) {
20186
20990
  directoryRead ??= listTools().finally(() => {
20187
20991
  directoryRead = void 0;
20188
20992
  });
@@ -20190,7 +20994,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20190
20994
  }
20191
20995
  }
20192
20996
  function role(name) {
20193
- const found = [...directory.tools.values()].filter((t) => t._meta?.["promptframe.role"] === name);
20997
+ const found = [...directory2.tools.values()].filter((t) => t._meta?.["promptframe.role"] === name);
20194
20998
  if (found.length !== 1) throw new CreationClientError("creation.upgrade_required");
20195
20999
  return found[0].name;
20196
21000
  }
@@ -20236,7 +21040,8 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20236
21040
  readResource: (params) => knowledgeRead("resources", "readResource", params),
20237
21041
  listPrompts: (params) => knowledgeRead("prompts", "listPrompts", params),
20238
21042
  getPrompt: (params) => knowledgeRead("prompts", "getPrompt", params),
20239
- async call(raw) {
21043
+ close: () => localUploads?.close(),
21044
+ async call(raw, { signal } = {}) {
20240
21045
  for (const field of ["threadId", "controller", "clientDigest", "token", "controlVersion"]) if (Object.hasOwn(raw.arguments ?? {}, field))
20241
21046
  throw new CreationClientError("creation.transport_authority_managed_by_bridge");
20242
21047
  let binding = { host, arguments: raw.arguments, assertCurrent: async () => {
@@ -20256,7 +21061,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20256
21061
  raw = { ...raw, arguments: binding.arguments };
20257
21062
  await ensureDirectory();
20258
21063
  await binding.assertCurrent();
20259
- const definition = directory.tools.get(raw.name);
21064
+ const definition = directory2.tools.get(raw.name);
20260
21065
  if (!definition) throw new CreationClientError("creation.tool_unavailable");
20261
21066
  const access2 = definition._meta["promptframe.access"], managed = Object.hasOwn(definition.inputSchema.properties ?? {}, "controlVersion");
20262
21067
  let params = hostParameters(raw, binding.host, "independent-read");
@@ -20277,6 +21082,31 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20277
21082
  resolvedControl = observed.trusted?.control;
20278
21083
  }
20279
21084
  hostParameters(raw, binding.host, effectiveAccess);
21085
+ const local = definition._meta["promptframe.localFileUpload"];
21086
+ if (local?.contractVersion === LOCAL_UPLOAD_PROTOCOL) {
21087
+ if (!localUploads) throw new CreationClientError("creation.upgrade_required");
21088
+ const { projectId, sessionId } = params.arguments ?? {};
21089
+ if (typeof projectId !== "string" || typeof sessionId !== "string") throw new CreationClientError("creation.request_invalid");
21090
+ const observed = await send({ name: role("control-read"), _meta: params._meta, arguments: { projectId, sessionId, pageSize: 1 } }, binding);
21091
+ if (observed.result.isError) return observed.result;
21092
+ if (!observed.trusted) throw new CreationClientError("creation.access_unverified");
21093
+ const value2 = await localUploads.call({
21094
+ input: params.arguments,
21095
+ binding,
21096
+ signal,
21097
+ scope: {
21098
+ platform: observed.trusted.platformDigest,
21099
+ account: observed.trusted.accountDigest,
21100
+ installation: installationDigest,
21101
+ host: binding.host.kind,
21102
+ thread: params._meta.threadId.toLowerCase(),
21103
+ projectId,
21104
+ sessionId
21105
+ },
21106
+ send: (transfer, options) => send({ name: params.name, _meta: params._meta, arguments: { projectId, sessionId, transfer } }, binding, { timeout: 3e4, ...options })
21107
+ });
21108
+ return assertMcpResponseBudget({ content: [{ type: "text", text: JSON.stringify(value2) }] });
21109
+ }
20280
21110
  const key = keyFor(params);
20281
21111
  let outgoing = params;
20282
21112
  if (managed) {
@@ -20316,7 +21146,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20316
21146
  }
20317
21147
 
20318
21148
  // lib/runtime-bootstrap.mjs
20319
- import { createHash as createHash5, randomBytes as randomBytes3 } from "node:crypto";
21149
+ import { createHash as createHash7, randomBytes as randomBytes4 } from "node:crypto";
20320
21150
  import { gunzipSync } from "node:zlib";
20321
21151
 
20322
21152
  // node_modules/tar/dist/esm/index.min.js
@@ -23289,18 +24119,18 @@ var To = (s3) => {
23289
24119
  };
23290
24120
 
23291
24121
  // 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";
24122
+ 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
24123
  import { execFile } from "node:child_process";
23294
24124
  import { promisify } from "node:util";
23295
- import path5 from "node:path";
24125
+ import path8 from "node:path";
23296
24126
 
23297
24127
  // 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";
24128
+ import { lstat as lstat5, readdir as readdir2, readFile as readFile4 } from "node:fs/promises";
24129
+ import { createHash as createHash6 } from "node:crypto";
24130
+ import path7 from "node:path";
23301
24131
  var RUNTIME_PACKAGE_ENTRIES = Object.freeze(["package.json", "README.md", "LICENSE", "bin", "dist", "lib", "skills", "docs", ".codex-plugin", ".mcp.json"]);
23302
24132
  var OPTIONAL_HOST_ENTRIES = Object.freeze([".claude-plugin", ".claude-mcp.json"]);
23303
- var hash2 = (b2) => createHash4("sha256").update(b2).digest("hex");
24133
+ var hash2 = (b2) => createHash6("sha256").update(b2).digest("hex");
23304
24134
  var invalid = (code) => {
23305
24135
  throw new CreationClientError("installation." + code);
23306
24136
  };
@@ -23309,7 +24139,7 @@ async function inspectRuntimePackage(root, { entries } = {}) {
23309
24139
  entries = [...RUNTIME_PACKAGE_ENTRIES];
23310
24140
  for (const name of OPTIONAL_HOST_ENTRIES) {
23311
24141
  try {
23312
- await lstat3(path4.join(root, name));
24142
+ await lstat5(path7.join(root, name));
23313
24143
  entries.push(name);
23314
24144
  } catch (e) {
23315
24145
  if (e.code !== "ENOENT") throw e;
@@ -23321,19 +24151,19 @@ async function inspectRuntimePackage(root, { entries } = {}) {
23321
24151
  async function walk(relative) {
23322
24152
  let s3;
23323
24153
  try {
23324
- s3 = await lstat3(path4.join(root, relative));
24154
+ s3 = await lstat5(path7.join(root, relative));
23325
24155
  } catch (error4) {
23326
24156
  if (error4.code !== "ENOENT") throw error4;
23327
24157
  }
23328
24158
  if (!s3 || s3.isSymbolicLink()) invalid("package_file_invalid");
23329
24159
  if (s3.isDirectory()) {
23330
- for (const name of (await readdir(path4.join(root, relative))).sort()) {
24160
+ for (const name of (await readdir2(path7.join(root, relative))).sort()) {
23331
24161
  if (name === "node_modules" || name === "credentials.json" || name.startsWith(".env")) invalid("package_file_invalid");
23332
- await walk(path4.join(relative, name));
24162
+ await walk(path7.join(relative, name));
23333
24163
  }
23334
24164
  } else if (s3.isFile()) {
23335
24165
  if (s3.size > 32 * 1024 * 1024) invalid("package_too_large");
23336
- const body = await readFile3(path4.join(root, relative));
24166
+ const body = await readFile4(path7.join(root, relative));
23337
24167
  bytes2 += body.length;
23338
24168
  if (files.length >= 1024 || bytes2 > 32 * 1024 * 1024) invalid("package_too_large");
23339
24169
  files.push({ path: relative, bytes: body.length, sha256: hash2(body), body });
@@ -23350,7 +24180,7 @@ async function inspectRuntimePackage(root, { entries } = {}) {
23350
24180
  files,
23351
24181
  version: pkg.version,
23352
24182
  hosts: claude ? ["codex", "claude-code"] : ["codex"],
23353
- payloadDigest: hash2(JSON.stringify(files.map(({ path: path14, bytes: bytes3, sha256 }) => ({ path: path14, bytes: bytes3, sha256 }))))
24183
+ payloadDigest: hash2(JSON.stringify(files.map(({ path: path17, bytes: bytes3, sha256 }) => ({ path: path17, bytes: bytes3, sha256 }))))
23354
24184
  };
23355
24185
  }
23356
24186
 
@@ -23360,7 +24190,7 @@ var REGISTRY = "https://registry.npmjs.org";
23360
24190
  var MAX_ARCHIVE = 8 * 1024 * 1024;
23361
24191
  var MAX_PAYLOAD = 32 * 1024 * 1024;
23362
24192
  var MAX_TAR = 36 * 1024 * 1024;
23363
- var hash3 = (b2) => createHash5("sha256").update(b2).digest("hex");
24193
+ var hash3 = (b2) => createHash7("sha256").update(b2).digest("hex");
23364
24194
  var execute = promisify(execFile);
23365
24195
  var error3 = (code) => new CreationClientError("creation." + code);
23366
24196
  var version2 = (v2) => {
@@ -23385,29 +24215,29 @@ var snapshot = (payload) => ({
23385
24215
  version: payload.version,
23386
24216
  hosts: payload.hosts,
23387
24217
  payloadDigest: payload.payloadDigest,
23388
- files: payload.files.map(({ path: path14, bytes: bytes2, sha256 }) => ({ path: path14, bytes: bytes2, sha256 }))
24218
+ files: payload.files.map(({ path: path17, bytes: bytes2, sha256 }) => ({ path: path17, bytes: bytes2, sha256 }))
23389
24219
  });
23390
24220
  async function info(file) {
23391
24221
  try {
23392
- return await lstat4(file);
24222
+ return await lstat6(file);
23393
24223
  } catch (e) {
23394
24224
  if (e.code === "ENOENT") return null;
23395
24225
  throw e;
23396
24226
  }
23397
24227
  }
23398
24228
  async function privateDirectory2(dir) {
23399
- await mkdir3(dir, { recursive: true, mode: 448 });
23400
- const s3 = await lstat4(dir);
24229
+ await mkdir4(dir, { recursive: true, mode: 448 });
24230
+ const s3 = await lstat6(dir);
23401
24231
  if (!s3.isDirectory() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63) throw error3("runtime_cache_owner_invalid");
23402
24232
  }
23403
24233
  async function privateJSON(file) {
23404
24234
  const s3 = await info(file);
23405
24235
  if (!s3) return null;
23406
24236
  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"));
24237
+ return JSON.parse(await readFile5(file, "utf8"));
23408
24238
  }
23409
- async function syncDirectory(dir) {
23410
- const fd = await open3(dir, "r");
24239
+ async function syncDirectory2(dir) {
24240
+ const fd = await open5(dir, "r");
23411
24241
  try {
23412
24242
  await fd.sync();
23413
24243
  } finally {
@@ -23415,7 +24245,7 @@ async function syncDirectory(dir) {
23415
24245
  }
23416
24246
  }
23417
24247
  async function exclusiveJSON(file, value2) {
23418
- const fd = await open3(file, "wx", 384);
24248
+ const fd = await open5(file, "wx", 384);
23419
24249
  try {
23420
24250
  await fd.writeFile(JSON.stringify(value2) + "\n");
23421
24251
  await fd.sync();
@@ -23432,19 +24262,19 @@ function checkedRuntimeMetadata(value2, expectedVersion) {
23432
24262
  if (Buffer.from(encoded, "base64").toString("base64") !== encoded) throw error3("runtime_registry_identity_invalid");
23433
24263
  return { version: expectedVersion, integrity: value2.dist.integrity, tarball };
23434
24264
  }
23435
- async function boundedGet(url2, { fetchImpl = fetch, signal, maxBytes, timeoutMs }) {
24265
+ async function boundedGet(url2, { fetchImpl = fetch, signal, maxBytes: maxBytes2, timeoutMs }) {
23436
24266
  const controller = new AbortController(), abort = () => controller.abort(), timer = setTimeout(abort, timeoutMs);
23437
24267
  signal?.addEventListener("abort", abort, { once: true });
23438
24268
  if (signal?.aborted) abort();
23439
24269
  let response;
23440
24270
  try {
23441
24271
  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");
24272
+ if (response.status !== 200 || Number(response.headers.get("content-length") ?? 0) > maxBytes2 || !response.body) throw error3("runtime_fetch_unavailable");
23443
24273
  const chunks = [];
23444
24274
  let count = 0;
23445
24275
  for await (const chunk of response.body) {
23446
24276
  count += chunk.length;
23447
- if (count > maxBytes) throw error3("runtime_download_capacity");
24277
+ if (count > maxBytes2) throw error3("runtime_download_capacity");
23448
24278
  chunks.push(Buffer.from(chunk));
23449
24279
  }
23450
24280
  return Buffer.concat(chunks, count);
@@ -23459,7 +24289,7 @@ async function boundedGet(url2, { fetchImpl = fetch, signal, maxBytes, timeoutMs
23459
24289
  }
23460
24290
  }
23461
24291
  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");
24292
+ if (!Buffer.isBuffer(archive) || archive.length > MAX_ARCHIVE || "sha512-" + createHash7("sha512").update(archive).digest("base64") !== metadata.integrity) throw error3("runtime_integrity_invalid");
23463
24293
  let raw;
23464
24294
  try {
23465
24295
  raw = gunzipSync(archive, { maxOutputLength: MAX_TAR });
@@ -23467,32 +24297,32 @@ async function readRuntimeArchive(archive, metadata) {
23467
24297
  throw error3("runtime_archive_invalid");
23468
24298
  }
23469
24299
  const files = [], names = /* @__PURE__ */ new Set();
23470
- let total = 0, entries = 0, failure2;
24300
+ let total = 0, entries = 0, failure3;
23471
24301
  const parser = Ct({ strict: true, onReadEntry: (entry) => {
23472
24302
  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");
24303
+ 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
24304
  const relative = name.slice(8).replace(/\/$/, "");
23475
24305
  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");
24306
+ failure3 = error3("runtime_archive_invalid");
23477
24307
  const portableName = relative.toLowerCase();
23478
- if (names.has(portableName)) failure2 = error3("runtime_archive_invalid");
24308
+ if (names.has(portableName)) failure3 = error3("runtime_archive_invalid");
23479
24309
  names.add(portableName);
23480
24310
  if (entry.type === "Directory") {
23481
- if (entry.size !== 0) failure2 = error3("runtime_archive_invalid");
24311
+ if (entry.size !== 0) failure3 = error3("runtime_archive_invalid");
23482
24312
  return;
23483
24313
  }
23484
24314
  total += entry.size;
23485
- if (total > MAX_PAYLOAD || files.length >= 1024 || !relative) failure2 = error3("runtime_archive_capacity");
24315
+ if (total > MAX_PAYLOAD || files.length >= 1024 || !relative) failure3 = error3("runtime_archive_capacity");
23486
24316
  const chunks = [];
23487
24317
  let bytes2 = 0;
23488
24318
  entry.on("data", (chunk) => {
23489
24319
  bytes2 += chunk.length;
23490
- if (bytes2 > entry.size) failure2 = error3("runtime_archive_invalid");
23491
- if (!failure2) chunks.push(Buffer.from(chunk));
24320
+ if (bytes2 > entry.size) failure3 = error3("runtime_archive_invalid");
24321
+ if (!failure3) chunks.push(Buffer.from(chunk));
23492
24322
  });
23493
24323
  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) });
24324
+ if (bytes2 !== entry.size) failure3 = error3("runtime_archive_invalid");
24325
+ if (!failure3) files.push({ path: relative, body: Buffer.concat(chunks, bytes2) });
23496
24326
  });
23497
24327
  } });
23498
24328
  await new Promise((resolve, reject) => {
@@ -23500,17 +24330,17 @@ async function readRuntimeArchive(archive, metadata) {
23500
24330
  parser.once("end", resolve);
23501
24331
  parser.end(raw);
23502
24332
  });
23503
- if (failure2) throw failure2;
24333
+ if (failure3) throw failure3;
23504
24334
  if (!files.length || files.length > 1024) throw error3("runtime_archive_invalid");
23505
24335
  return files;
23506
24336
  }
23507
24337
  async function cacheLock(root, signal) {
23508
- const name = path5.join(root, "prepare.lock"), end = Date.now() + 5e3;
24338
+ const name = path8.join(root, "prepare.lock"), end = Date.now() + 5e3;
23509
24339
  let fd;
23510
24340
  while (!fd) {
23511
24341
  signal?.throwIfAborted();
23512
24342
  try {
23513
- fd = await open3(name, "wx", 384);
24343
+ fd = await open5(name, "wx", 384);
23514
24344
  } catch (e) {
23515
24345
  if (e.code !== "EEXIST") throw e;
23516
24346
  if (Date.now() >= end) throw error3("runtime_cache_busy");
@@ -23521,7 +24351,7 @@ async function cacheLock(root, signal) {
23521
24351
  try {
23522
24352
  await fd.writeFile(JSON.stringify({ pid: process.pid, createdAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n");
23523
24353
  await fd.sync();
23524
- await syncDirectory(root);
24354
+ await syncDirectory2(root);
23525
24355
  } catch (e) {
23526
24356
  await fd.close();
23527
24357
  const now = await info(name);
@@ -23538,10 +24368,10 @@ async function cacheLock(root, signal) {
23538
24368
  async function verifyCached(target, metadata, hostKind) {
23539
24369
  if (!await info(target)) return null;
23540
24370
  await privateDirectory2(target);
23541
- const manifest = await privateJSON(path5.join(target, "runtime.json"));
24371
+ const manifest = await privateJSON(path8.join(target, "runtime.json"));
23542
24372
  if (!manifest || manifest.contractVersion !== "creation-verified-runtime/v1" || manifest.version !== metadata.version || manifest.integrity !== metadata.integrity)
23543
24373
  throw error3("runtime_cache_invalid");
23544
- const names = (await readdir2(target)).filter((name) => name !== "runtime.json").sort();
24374
+ const names = (await readdir3(target)).filter((name) => name !== "runtime.json").sort();
23545
24375
  if (names.some((name) => !roots.has(name)) || RUNTIME_PACKAGE_ENTRIES.some((name) => !names.includes(name))) throw error3("runtime_cache_invalid");
23546
24376
  const payload = await inspectRuntimePackage(target, { entries: names });
23547
24377
  if (!payload.hosts.includes(hostKind)) throw error3("runtime_host_unsupported");
@@ -23549,33 +24379,33 @@ async function verifyCached(target, metadata, hostKind) {
23549
24379
  return { version: payload.version, root: target, integrity: metadata.integrity, reused: true };
23550
24380
  }
23551
24381
  async function checkedVersionIndex(cacheRoot, metadata) {
23552
- const old = await privateJSON(path5.join(cacheRoot, "version-" + metadata.version + ".json"));
24382
+ const old = await privateJSON(path8.join(cacheRoot, "version-" + metadata.version + ".json"));
23553
24383
  if (old && JSON.stringify(old) !== JSON.stringify(metadata)) throw error3("runtime_registry_identity_conflict");
23554
24384
  return old;
23555
24385
  }
23556
24386
  async function prepareVerifiedRuntime(metadata, { cacheRoot, fetchImpl = fetch, signal, checkRuntime, hostKind = "codex" } = {}) {
23557
24387
  if (!["codex", "claude-code"].includes(hostKind)) throw error3("runtime_host_unsupported");
23558
- if (!path5.isAbsolute(cacheRoot ?? "")) throw error3("runtime_cache_owner_invalid");
24388
+ if (!path8.isAbsolute(cacheRoot ?? "")) throw error3("runtime_cache_owner_invalid");
23559
24389
  metadata = checkedRuntimeMetadata({ name: PACKAGE, version: metadata.version, dist: metadata }, metadata.version);
23560
24390
  await privateDirectory2(cacheRoot);
23561
24391
  await checkedVersionIndex(cacheRoot, metadata);
23562
- const target = path5.join(cacheRoot, metadata.version + "-" + hash3(metadata.integrity)), existing = await verifyCached(target, metadata, hostKind);
24392
+ const target = path8.join(cacheRoot, metadata.version + "-" + hash3(metadata.integrity)), existing = await verifyCached(target, metadata, hostKind);
23563
24393
  if (existing) return existing;
23564
24394
  const archive = await boundedGet(metadata.tarball, { fetchImpl, signal, maxBytes: MAX_ARCHIVE, timeoutMs: 15e3 });
23565
24395
  const files = await readRuntimeArchive(archive, metadata), release = await cacheLock(cacheRoot, signal);
23566
- const temporary = path5.join(cacheRoot, ".partial-" + randomBytes3(12).toString("hex"));
24396
+ const temporary = path8.join(cacheRoot, ".partial-" + randomBytes4(12).toString("hex"));
23567
24397
  try {
23568
24398
  const index = await checkedVersionIndex(cacheRoot, metadata);
23569
24399
  const found = await verifyCached(target, metadata, hostKind);
23570
24400
  if (found) return found;
23571
24401
  const space = await statfs(cacheRoot, { bigint: true }), needed = BigInt(files.reduce((n, f2) => n + f2.body.length, 0) + 4 * 1024 * 1024);
23572
24402
  if (space.bavail * space.bsize < needed) throw error3("runtime_cache_capacity");
23573
- await mkdir3(temporary, { mode: 448 });
24403
+ await mkdir4(temporary, { mode: 448 });
23574
24404
  for (const file of files) {
23575
24405
  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);
24406
+ const dest = path8.join(temporary, ...file.path.split("/"));
24407
+ await mkdir4(path8.dirname(dest), { recursive: true, mode: 448 });
24408
+ const fd = await open5(dest, "wx", 384);
23579
24409
  try {
23580
24410
  await fd.writeFile(file.body);
23581
24411
  await fd.sync();
@@ -23594,28 +24424,28 @@ async function prepareVerifiedRuntime(metadata, { cacheRoot, fetchImpl = fetch,
23594
24424
  else {
23595
24425
  const result = await execute(
23596
24426
  process.execPath,
23597
- [path5.join(temporary, "bin/promptframe-creation.mjs"), "--version"],
24427
+ [path8.join(temporary, "bin/promptframe-creation.mjs"), "--version"],
23598
24428
  { timeout: 5e3, maxBuffer: 65536, windowsHide: true, signal, env: {
23599
24429
  ...process.env,
23600
- PROMPTFRAME_CREATION_CONFIG: path5.join(temporary, "no-credentials.json")
24430
+ PROMPTFRAME_CREATION_CONFIG: path8.join(temporary, "no-credentials.json")
23601
24431
  } }
23602
24432
  );
23603
24433
  if (result.stdout.trim() !== metadata.version || result.stderr.trim()) throw error3("runtime_package_version_invalid");
23604
24434
  }
23605
24435
  signal?.throwIfAborted();
23606
- await exclusiveJSON(path5.join(temporary, "runtime.json"), {
24436
+ await exclusiveJSON(path8.join(temporary, "runtime.json"), {
23607
24437
  contractVersion: "creation-verified-runtime/v1",
23608
24438
  version: metadata.version,
23609
24439
  integrity: metadata.integrity,
23610
24440
  payload: snapshot(payload)
23611
24441
  });
23612
- await syncDirectory(temporary);
24442
+ await syncDirectory2(temporary);
23613
24443
  if (!index) {
23614
- await exclusiveJSON(path5.join(cacheRoot, "version-" + metadata.version + ".json"), metadata);
23615
- await syncDirectory(cacheRoot);
24444
+ await exclusiveJSON(path8.join(cacheRoot, "version-" + metadata.version + ".json"), metadata);
24445
+ await syncDirectory2(cacheRoot);
23616
24446
  }
23617
- await rename3(temporary, target);
23618
- await syncDirectory(cacheRoot);
24447
+ await rename4(temporary, target);
24448
+ await syncDirectory2(cacheRoot);
23619
24449
  return { version: metadata.version, root: target, integrity: metadata.integrity, reused: false };
23620
24450
  } finally {
23621
24451
  try {
@@ -23653,7 +24483,7 @@ async function selectBridgeRuntime({ policy, currentVersion, lockedVersion, reso
23653
24483
  const raw = await boundedGet(REGISTRY + "/@promptframe%2fcreation/" + target, { fetchImpl, signal, maxBytes: 256 * 1024, timeoutMs: 5e3 });
23654
24484
  metadata = checkedRuntimeMetadata(JSON.parse(raw), target);
23655
24485
  } catch (e) {
23656
- const prior = await privateJSON(path5.join(cacheRoot, "version-" + target + ".json"));
24486
+ const prior = await privateJSON(path8.join(cacheRoot, "version-" + target + ".json"));
23657
24487
  if (!prior) throw e;
23658
24488
  metadata = checkedRuntimeMetadata({ name: PACKAGE, version: target, dist: prior }, target);
23659
24489
  metadataSource = "previously-verified-cache";
@@ -23679,16 +24509,16 @@ async function selectBridgeRuntime({ policy, currentVersion, lockedVersion, reso
23679
24509
 
23680
24510
  // lib/runtime-launch.mjs
23681
24511
  import { spawn } from "node:child_process";
23682
- import path6 from "node:path";
24512
+ import path9 from "node:path";
23683
24513
  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))
24514
+ if (!path9.isAbsolute(selection.root ?? "") || !path9.isAbsolute(configFile2 ?? "") || !["codex", "claude-code"].includes(host?.kind))
23685
24515
  throw new CreationClientError("creation.runtime_launch_invalid");
23686
24516
  let child;
23687
24517
  try {
23688
24518
  child = spawnImpl(
23689
24519
  process.execPath,
23690
24520
  [
23691
- path6.join(selection.root, "bin/promptframe-creation.mjs"),
24521
+ path9.join(selection.root, "bin/promptframe-creation.mjs"),
23692
24522
  "bridge",
23693
24523
  "--config",
23694
24524
  configFile2,
@@ -23730,10 +24560,10 @@ async function launchSelectedBridge(selection, { host, configFile: configFile2,
23730
24560
  // lib/user-installation.mjs
23731
24561
  import { execFile as execFile2 } from "node:child_process";
23732
24562
  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";
24563
+ import { createHash as createHash8, randomBytes as randomBytes5 } from "node:crypto";
24564
+ 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
24565
  import { homedir as homedir4 } from "node:os";
23736
- import path7 from "node:path";
24566
+ import path10 from "node:path";
23737
24567
 
23738
24568
  // node_modules/smol-toml/dist/error.js
23739
24569
  function getLineColFromPtr(string4, ptr) {
@@ -24495,14 +25325,14 @@ var HAS_WELLFORMED = !!"".isWellFormed;
24495
25325
 
24496
25326
  // lib/user-installation.mjs
24497
25327
  var execute2 = promisify2(execFile2);
24498
- var hash4 = (b2) => createHash6("sha256").update(b2).digest("hex");
25328
+ var hash4 = (b2) => createHash8("sha256").update(b2).digest("hex");
24499
25329
  var InstallationError = class extends CreationClientError {
24500
25330
  constructor(code, details) {
24501
25331
  super("installation." + code);
24502
25332
  this.details = details;
24503
25333
  }
24504
25334
  };
24505
- var fail = (code, details) => {
25335
+ var fail4 = (code, details) => {
24506
25336
  throw new InstallationError(code, details);
24507
25337
  };
24508
25338
  var installationErrorDetails = (error4) => error4 instanceof InstallationError ? error4.details : void 0;
@@ -24526,16 +25356,16 @@ function pinnedGitSource(source) {
24526
25356
  const refKind = /^[a-f0-9]{40}$/i.test(ref) ? "commit" : /^(?:refs\/tags\/)?creation-v\d+\.\d+\.\d+$/.test(ref) ? "tag" : null;
24527
25357
  return refKind ? { refName: ref, refKind } : null;
24528
25358
  }
24529
- var json = async (file) => JSON.parse(await readFile5(file, "utf8"));
25359
+ var json = async (file) => JSON.parse(await readFile6(file, "utf8"));
24530
25360
  var pause2 = (ms2) => new Promise((r) => setTimeout(r, ms2));
24531
25361
  function validProfile(profile) {
24532
- if (typeof profile !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(profile)) fail("profile_invalid");
25362
+ if (typeof profile !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(profile)) fail4("profile_invalid");
24533
25363
  return profile;
24534
25364
  }
24535
25365
  function profileCredentialsPath(profile = "default", env = process.env) {
24536
25366
  validProfile(profile);
24537
- return profile === "default" ? credentialsPath(env) : path7.resolve(
24538
- env.XDG_CONFIG_HOME ?? path7.join(homedir4(), ".config"),
25367
+ return profile === "default" ? credentialsPath(env) : path10.resolve(
25368
+ env.XDG_CONFIG_HOME ?? path10.join(homedir4(), ".config"),
24539
25369
  "promptframe-creation",
24540
25370
  "profiles",
24541
25371
  profile,
@@ -24544,58 +25374,58 @@ function profileCredentialsPath(profile = "default", env = process.env) {
24544
25374
  }
24545
25375
  async function info2(file) {
24546
25376
  try {
24547
- return await lstat5(file);
25377
+ return await lstat7(file);
24548
25378
  } catch (e) {
24549
25379
  if (e.code === "ENOENT") return null;
24550
25380
  throw e;
24551
25381
  }
24552
25382
  }
24553
25383
  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");
25384
+ await mkdir5(dir, { recursive: true, mode: 448 });
25385
+ const s3 = await lstat7(dir);
25386
+ if (!s3.isDirectory() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63) fail4("private_owner_required");
24557
25387
  }
24558
25388
  async function privateRead2(file) {
24559
25389
  const s3 = await info2(file);
24560
25390
  if (!s3) return null;
24561
- if (!s3.isFile() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63 || s3.size > 512 * 1024) fail("state_invalid");
25391
+ if (!s3.isFile() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63 || s3.size > 512 * 1024) fail4("state_invalid");
24562
25392
  return json(file);
24563
25393
  }
24564
25394
  async function packageJSON(file) {
24565
25395
  const s3 = await info2(file);
24566
- if (!s3?.isFile() || s3.isSymbolicLink() || s3.size > 512 * 1024) fail("installed_files_invalid");
25396
+ if (!s3?.isFile() || s3.isSymbolicLink() || s3.size > 512 * 1024) fail4("installed_files_invalid");
24567
25397
  return json(file);
24568
25398
  }
24569
25399
  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;
25400
+ 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
25401
  }
24572
25402
  async function managedTransport(installed, versions, serverName, profile, configFile2) {
24573
25403
  if (!installed) return null;
24574
25404
  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");
25405
+ 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");
25406
+ const directory2 = await info2(root), definition = await info2(path10.join(root, ".mcp.json"));
25407
+ if (!directory2?.isDirectory() || directory2.isSymbolicLink() || !definition?.isFile() || definition.isSymbolicLink()) fail4("installed_files_invalid");
25408
+ const ready = await privateRead2(path10.join(root, "installation.json"));
25409
+ if (!ready || ready.profile !== profile || ready.configFile !== configFile2 || ready.version !== installed.version) fail4("existing_registration_requires_review");
25410
+ const bytes2 = await readFile6(path10.join(root, ".mcp.json")), entry = ready.files?.find((x) => x.path === ".mcp.json");
25411
+ if (!entry || entry.bytes !== bytes2.length || entry.sha256 !== hash4(bytes2)) fail4("installed_files_invalid");
24582
25412
  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");
25413
+ 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
25414
  return mcp;
24585
25415
  }
24586
25416
  async function officialNpmInstallation(installed, servers, env, profile, configFile2) {
24587
25417
  if (profile !== "default" || configFile2 !== profileCredentialsPath("default", env)) return null;
24588
25418
  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");
25419
+ if (candidates.length > 1) fail4("existing_registration_requires_review");
24590
25420
  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");
25421
+ const p2 = candidates[0], root = path10.join(path10.resolve(env.CODEX_HOME ?? path10.join(homedir4(), ".codex")), "plugins/cache", p2.marketplaceName, p2.name, p2.version);
25422
+ const directory2 = await info2(root);
25423
+ if (!directory2?.isDirectory() || directory2.isSymbolicLink()) fail4("installed_files_invalid");
25424
+ const pkg = await packageJSON(path10.join(root, "package.json")), manifest = await packageJSON(path10.join(root, ".codex-plugin/plugin.json"));
25425
+ if (pkg.name !== "@promptframe/creation" || pkg.version !== p2.version || manifest.name !== p2.name || manifest.version !== p2.version) fail4("installed_files_invalid");
25426
+ const definition = (await packageJSON(path10.join(root, ".mcp.json"))).mcpServers?.promptframe;
25427
+ 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");
25428
+ 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
25429
  return {
24600
25430
  version: p2.version,
24601
25431
  profile,
@@ -24610,43 +25440,43 @@ async function officialNpmInstallation(installed, servers, env, profile, configF
24610
25440
  };
24611
25441
  }
24612
25442
  async function atomicJSON(file, value2) {
24613
- const temp = file + "." + randomBytes4(12).toString("hex") + ".tmp";
25443
+ const temp = file + "." + randomBytes5(12).toString("hex") + ".tmp";
24614
25444
  try {
24615
- const out = await open4(temp, "wx", 384);
25445
+ const out = await open6(temp, "wx", 384);
24616
25446
  try {
24617
25447
  await out.writeFile(JSON.stringify(value2, null, 2) + "\n");
24618
25448
  await out.sync();
24619
25449
  } finally {
24620
25450
  await out.close();
24621
25451
  }
24622
- await rename4(temp, file);
24623
- const directory = await open4(path7.dirname(file), "r");
25452
+ await rename5(temp, file);
25453
+ const directory2 = await open6(path10.dirname(file), "r");
24624
25454
  try {
24625
- await directory.sync();
25455
+ await directory2.sync();
24626
25456
  } finally {
24627
- await directory.close();
25457
+ await directory2.close();
24628
25458
  }
24629
25459
  } finally {
24630
25460
  await rm2(temp, { force: true });
24631
25461
  }
24632
25462
  }
24633
25463
  async function acquire(root, signal) {
24634
- const lock = path7.join(root, "install.lock");
25464
+ const lock = path10.join(root, "install.lock");
24635
25465
  const end = Date.now() + 3e4;
24636
25466
  let owned = false;
24637
25467
  while (!owned) {
24638
25468
  signal?.throwIfAborted();
24639
25469
  try {
24640
- await mkdir4(lock, { mode: 448 });
25470
+ await mkdir5(lock, { mode: 448 });
24641
25471
  owned = true;
24642
25472
  } catch (e) {
24643
25473
  if (e.code !== "EEXIST") throw e;
24644
- if (Date.now() >= end) fail("in_progress_or_interrupted_keep_existing");
25474
+ if (Date.now() >= end) fail4("in_progress_or_interrupted_keep_existing");
24645
25475
  await pause2(50);
24646
25476
  }
24647
25477
  }
24648
25478
  try {
24649
- await writeFile2(path7.join(lock, "owner.json"), JSON.stringify({ pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString() }), { flag: "wx", mode: 384 });
25479
+ await writeFile2(path10.join(lock, "owner.json"), JSON.stringify({ pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString() }), { flag: "wx", mode: 384 });
24650
25480
  } catch (e) {
24651
25481
  await rm2(lock, { recursive: true, force: true });
24652
25482
  throw e;
@@ -24665,7 +25495,7 @@ async function runCodexCommand(args2, { env = process.env } = {}) {
24665
25495
  return (await execute2("codex", args2, { env, encoding: "utf8", timeout: timeoutMs, maxBuffer: 2 * 1024 * 1024 })).stdout;
24666
25496
  } catch (e) {
24667
25497
  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, {
25498
+ fail4(cause, {
24669
25499
  phase: write ? "registration" : "local_check",
24670
25500
  commandKind: kind,
24671
25501
  elapsedMs: Math.round(performance.now() - start),
@@ -24683,16 +25513,16 @@ async function codexJSON(runCodex, args2) {
24683
25513
  if (typeof body !== "string" || Buffer.byteLength(body) > 2 * 1024 * 1024) throw Error();
24684
25514
  return JSON.parse(body);
24685
25515
  } catch {
24686
- fail("command_json_unconfirmed", { phase: "local_check", commandKind: commandKind(args2), localRegistrationState: "unknown", action: "retry_local_read" });
25516
+ fail4("command_json_unconfirmed", { phase: "local_check", commandKind: commandKind(args2), localRegistrationState: "unknown", action: "retry_local_read" });
24687
25517
  }
24688
25518
  }
24689
25519
  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");
25520
+ 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
25521
  try {
24692
25522
  const s3 = await info2(config2);
24693
25523
  if (s3) {
24694
25524
  if (!s3.isFile() || s3.isSymbolicLink() || s3.size > 2 * 1024 * 1024) throw Error();
24695
- const plugins = parse3(await readFile5(config2, "utf8")).plugins ?? {};
25525
+ const plugins = parse3(await readFile6(config2, "utf8")).plugins ?? {};
24696
25526
  if (!plugins || typeof plugins !== "object" || Array.isArray(plugins) || Object.keys(plugins).length > 1024) throw Error();
24697
25527
  for (const id of Object.keys(plugins)) if (id.startsWith(pluginName + "@")) {
24698
25528
  const market = id.slice(pluginName.length + 1);
@@ -24702,19 +25532,19 @@ async function relatedPlugins(runCodex, pluginName, env) {
24702
25532
  }
24703
25533
  }
24704
25534
  } catch {
24705
- fail("local_config_unconfirmed", { phase: "local_check", commandKind: "local_config_read", localRegistrationState: "unknown", action: "review_local_plugin_registration" });
25535
+ fail4("local_config_unconfirmed", { phase: "local_check", commandKind: "local_config_read", localRegistrationState: "unknown", action: "review_local_plugin_registration" });
24706
25536
  }
24707
25537
  const state = await codexJSON(runCodex, ["plugin", "marketplace", "list", "--json"]);
24708
- if (!Array.isArray(state?.marketplaces) || state.marketplaces.length > 128) fail("local_catalog_unconfirmed");
25538
+ if (!Array.isArray(state?.marketplaces) || state.marketplaces.length > 128) fail4("local_catalog_unconfirmed");
24709
25539
  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");
25540
+ 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
25541
  let catalog;
24712
25542
  try {
24713
- catalog = await packageJSON(path7.join(market.root, ".agents/plugins/marketplace.json"));
25543
+ catalog = await packageJSON(path10.join(market.root, ".agents/plugins/marketplace.json"));
24714
25544
  } catch {
24715
- fail("local_catalog_unconfirmed", { phase: "local_check", commandKind: "marketplace_read", localRegistrationState: "unknown", action: "restore_local_marketplace_catalog" });
25545
+ fail4("local_catalog_unconfirmed", { phase: "local_check", commandKind: "marketplace_read", localRegistrationState: "unknown", action: "restore_local_marketplace_catalog" });
24716
25546
  }
24717
- if (!Array.isArray(catalog?.plugins) || catalog.plugins.length > 1024) fail("local_catalog_unconfirmed");
25547
+ if (!Array.isArray(catalog?.plugins) || catalog.plugins.length > 1024) fail4("local_catalog_unconfirmed");
24718
25548
  if (catalog.plugins.some((p2) => p2?.name === pluginName)) related.add(market.name);
24719
25549
  const pinned = pinnedGitSource(market.marketplaceSource);
24720
25550
  if (pinned) pinnedMarketplaces.set(market.name, pinned);
@@ -24722,16 +25552,16 @@ async function relatedPlugins(runCodex, pluginName, env) {
24722
25552
  const installed = [];
24723
25553
  for (const market of related) {
24724
25554
  const list = await codexJSON(runCodex, ["plugin", "list", "--marketplace", market, "--json"]);
24725
- if (!Array.isArray(list?.installed) || list.installed.length > 1024) fail("local_registration_unconfirmed");
25555
+ if (!Array.isArray(list?.installed) || list.installed.length > 1024) fail4("local_registration_unconfirmed");
24726
25556
  for (const p2 of list.installed) {
24727
- if (typeof p2?.pluginId !== "string" || typeof p2.enabled !== "boolean") fail("local_registration_unconfirmed");
25557
+ if (typeof p2?.pluginId !== "string" || typeof p2.enabled !== "boolean") fail4("local_registration_unconfirmed");
24728
25558
  if (p2?.pluginId !== pluginName + "@" + market) continue;
24729
- if (p2.marketplaceName !== void 0 && p2.marketplaceName !== market) fail("local_registration_unconfirmed");
25559
+ if (p2.marketplaceName !== void 0 && p2.marketplaceName !== market) fail4("local_registration_unconfirmed");
24730
25560
  installed.push({ ...p2, ...pinnedMarketplaces.has(market) ? { pinnedMarketplace: pinnedMarketplaces.get(market) } : {} });
24731
25561
  }
24732
25562
  }
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", {
25563
+ if (new Set(installed.map((p2) => p2.pluginId)).size !== installed.length) fail4("local_registration_unconfirmed");
25564
+ if ([...registered].some((id) => !installed.some((p2) => p2.pluginId === id))) fail4("local_registration_unconfirmed", {
24735
25565
  phase: "local_check",
24736
25566
  commandKind: "plugin_read",
24737
25567
  localRegistrationState: "unknown",
@@ -24741,11 +25571,11 @@ async function relatedPlugins(runCodex, pluginName, env) {
24741
25571
  }
24742
25572
  async function runNode(root, version3) {
24743
25573
  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");
25574
+ const result = await execute2(process.execPath, [path10.join(root, "bin/promptframe-creation.mjs"), "--version"], { encoding: "utf8", timeout: 1e4, maxBuffer: 8192 });
25575
+ if (result.stdout.trim() !== version3) fail4("runtime_version_mismatch");
24746
25576
  } catch (e) {
24747
25577
  if (e instanceof CreationClientError) throw e;
24748
- fail("runtime_check_failed");
25578
+ fail4("runtime_check_failed");
24749
25579
  }
24750
25580
  }
24751
25581
  async function checkInstalledRuntime(root, version3, command2, { env = process.env } = {}) {
@@ -24755,12 +25585,12 @@ async function checkInstalledRuntime(root, version3, command2, { env = process.e
24755
25585
  if (!major || Number(major[1]) < 20) throw Error("unsupported_node");
24756
25586
  const result = await execute2(
24757
25587
  command2,
24758
- [path7.join(root, "bin/promptframe-creation.mjs"), "--version"],
25588
+ [path10.join(root, "bin/promptframe-creation.mjs"), "--version"],
24759
25589
  { env, encoding: "utf8", timeout: 1e4, maxBuffer: 8192 }
24760
25590
  );
24761
25591
  if (result.stdout.trim() !== version3) throw Error("wrong_version");
24762
25592
  } catch {
24763
- fail("recorded_node_unavailable", {
25593
+ fail4("recorded_node_unavailable", {
24764
25594
  installedVersion: version3,
24765
25595
  action: "restore_recorded_node_or_connect_newer_version",
24766
25596
  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 +25621,44 @@ async function installForUser({
24791
25621
  validProfile(profile);
24792
25622
  const versionOutput = await runCodex(["--version"]);
24793
25623
  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);
25624
+ if (!match || Number(match[1]) === 0 && Number(match[2]) < 160) fail4("codex_0160_required");
25625
+ const payload = await inspectRuntimePackage(path10.resolve(sourceRoot));
25626
+ const root = path10.resolve(env.XDG_DATA_HOME ?? path10.join(homedir4(), ".local/share"), "promptframe-creation", profile);
24797
25627
  await privateDirectory3(root);
24798
25628
  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");
25629
+ const versions = path10.join(root, "versions"), currentFile = path10.join(root, "current.json"), pendingFile = path10.join(root, "registration-pending.json");
25630
+ const marketplaceFile = path10.join(root, ".agents/plugins/marketplace.json");
24801
25631
  const pluginName = "promptframe-creation" + (profile === "default" ? "" : "-" + profile), marketplace = "promptframe-creation-user" + (profile === "default" ? "" : "-" + profile);
24802
25632
  const pluginId = pluginName + "@" + marketplace;
24803
- const versionRoot = path7.join(versions, payload.version), temporary = path7.join(versions, ".partial-" + randomBytes4(12).toString("hex"));
25633
+ const versionRoot = path10.join(versions, payload.version), temporary = path10.join(versions, ".partial-" + randomBytes5(12).toString("hex"));
24804
25634
  let previous, registrationStarted = false, newFiles = 0;
24805
25635
  try {
24806
25636
  signal?.throwIfAborted();
24807
25637
  await privateDirectory3(versions);
24808
- await privateDirectory3(path7.dirname(marketplaceFile));
25638
+ await privateDirectory3(path10.dirname(marketplaceFile));
24809
25639
  previous = await privateRead2(currentFile);
24810
- if (previous && (previous.profile !== profile || previous.pluginId !== pluginId || previous.configFile !== configFile2)) fail("profile_binding_conflict");
25640
+ if (previous && (previous.profile !== profile || previous.pluginId !== pluginId || previous.configFile !== configFile2)) fail4("profile_binding_conflict");
24811
25641
  const state = { installed: await relatedPlugins(runCodex, pluginName, env) };
24812
25642
  const installed = state.installed.find((x) => x.pluginId === pluginId);
24813
25643
  const legacy = await codexJSON(runCodex, ["mcp", "list", "--json"]);
24814
- if (!Array.isArray(legacy)) fail("local_registration_unconfirmed");
25644
+ if (!Array.isArray(legacy)) fail4("local_registration_unconfirmed");
24815
25645
  const serverName = "promptframe" + (profile === "default" ? "" : "-" + profile);
24816
25646
  const servers = legacy.filter((x) => x.name === serverName);
24817
25647
  const pending = await privateRead2(pendingFile);
24818
25648
  if (pending) {
24819
- if (pending.profile !== profile || pending.pluginId !== pluginId || pending.configFile !== configFile2 || pending.versionRoot !== path7.join(versions, pending.version)) fail("profile_binding_conflict");
25649
+ if (pending.profile !== profile || pending.pluginId !== pluginId || pending.configFile !== configFile2 || pending.versionRoot !== path10.join(versions, pending.version)) fail4("profile_binding_conflict");
24820
25650
  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" });
25651
+ fail4("registration_unconfirmed_keep_existing", { phase: "registration_observation", localRegistrationState: "unknown", action: "inspect_same_registration_no_second_add" });
24822
25652
  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");
25653
+ if (servers.length !== 1 || servers[0].enabled === false || !sameTransport(servers[0].transport, transport2)) fail4("registration_unconfirmed_keep_existing");
25654
+ const ready = await privateRead2(path10.join(pending.versionRoot, "installation.json"));
25655
+ if (ready?.payloadDigest !== pending.payloadDigest) fail4("installed_files_invalid");
24826
25656
  previous = pending;
24827
25657
  await atomicJSON(currentFile, pending);
24828
25658
  await rm2(pendingFile);
24829
25659
  }
24830
25660
  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", {
25661
+ if (pinned) fail4("pinned_git_plugin_upgrade_required", {
24832
25662
  ...pinned.source,
24833
25663
  sourceType: "git",
24834
25664
  localRegistrationState: "present",
@@ -24837,10 +25667,10 @@ async function installForUser({
24837
25667
  });
24838
25668
  const official = await officialNpmInstallation(state.installed ?? [], servers, env, profile, configFile2);
24839
25669
  if (official) {
24840
- if (installed || previous) fail("existing_registration_requires_review");
25670
+ if (installed || previous) fail4("existing_registration_requires_review");
24841
25671
  const compared = compareVersions(official.version, payload.version);
24842
25672
  if (compared < 0) {
24843
- fail("npm_plugin_upgrade_required", {
25673
+ fail4("npm_plugin_upgrade_required", {
24844
25674
  installedVersion: official.version,
24845
25675
  requestedVersion: payload.version,
24846
25676
  pluginId: official.pluginId,
@@ -24855,11 +25685,11 @@ async function installForUser({
24855
25685
  if (legacy.some((x) => {
24856
25686
  if (x.name !== serverName) return false;
24857
25687
  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");
25688
+ })) fail4("legacy_mcp_entry_requires_review");
25689
+ if (state.installed.some((p2) => p2.pluginId !== pluginId)) fail4("existing_registration_requires_review");
24860
25690
  if (installed && compareVersions(installed.version, payload.version) > 0) {
24861
25691
  if (!previous || previous.version !== installed.version || previous.versionRoot !== installed.source.path || installed.enabled !== true)
24862
- fail("existing_registration_requires_review");
25692
+ fail4("existing_registration_requires_review");
24863
25693
  await verifyInstalledRuntime(previous.versionRoot, previous.version, recorded.command, { env });
24864
25694
  return {
24865
25695
  ...previous,
@@ -24875,44 +25705,44 @@ async function installForUser({
24875
25705
  }
24876
25706
  const target = await info2(versionRoot);
24877
25707
  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");
25708
+ if (!target.isDirectory() || target.isSymbolicLink()) fail4("version_content_conflict");
25709
+ const ready = await privateRead2(path10.join(versionRoot, "installation.json"));
25710
+ if (!ready || ready.payloadDigest !== payload.payloadDigest || ready.profile !== profile || ready.configFile !== configFile2) fail4("version_content_conflict");
24881
25711
  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");
25712
+ if (!payload.files.some((p2) => p2.path === f2.path)) fail4("installed_files_invalid");
25713
+ const file = path10.join(versionRoot, f2.path), s3 = await info2(file);
25714
+ if (!s3?.isFile() || s3.isSymbolicLink() || s3.size !== f2.bytes || hash4(await readFile6(file)) !== f2.sha256) fail4("installed_files_invalid");
24885
25715
  }
24886
- if (ready.files.length !== payload.files.length) fail("installed_files_invalid");
25716
+ if (ready.files.length !== payload.files.length) fail4("installed_files_invalid");
24887
25717
  } else {
24888
- await mkdir4(temporary, { mode: 448 });
25718
+ await mkdir5(temporary, { mode: 448 });
24889
25719
  for (const f2 of payload.files) {
24890
25720
  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 });
25721
+ await mkdir5(path10.dirname(path10.join(temporary, f2.path)), { recursive: true, mode: 448 });
25722
+ await writeFile2(path10.join(temporary, f2.path), f2.body, { flag: "wx", mode: 384 });
24893
25723
  }
24894
- const manifest = await json(path7.join(temporary, ".codex-plugin/plugin.json"));
25724
+ const manifest = await json(path10.join(temporary, ".codex-plugin/plugin.json"));
24895
25725
  manifest.name = pluginName;
24896
- await writeFile2(path7.join(temporary, ".codex-plugin/plugin.json"), JSON.stringify(manifest, null, 2) + "\n");
25726
+ await writeFile2(path10.join(temporary, ".codex-plugin/plugin.json"), JSON.stringify(manifest, null, 2) + "\n");
24897
25727
  const mcp = { mcpServers: { ["promptframe" + (profile === "default" ? "" : "-" + profile)]: {
24898
25728
  command: process.execPath,
24899
- args: [path7.join(versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", configFile2],
25729
+ args: [path10.join(versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", configFile2],
24900
25730
  cwd: versionRoot
24901
25731
  } } };
24902
- await writeFile2(path7.join(temporary, ".mcp.json"), JSON.stringify(mcp, null, 2) + "\n");
25732
+ await writeFile2(path10.join(temporary, ".mcp.json"), JSON.stringify(mcp, null, 2) + "\n");
24903
25733
  await checkRuntime(temporary, payload.version);
24904
25734
  const files = [];
24905
25735
  for (const f2 of payload.files) {
24906
- const body = await readFile5(path7.join(temporary, f2.path));
25736
+ const body = await readFile6(path10.join(temporary, f2.path));
24907
25737
  files.push({ path: f2.path, bytes: body.length, sha256: hash4(body) });
24908
25738
  }
24909
- await atomicJSON(path7.join(temporary, "installation.json"), { version: payload.version, profile, configFile: configFile2, payloadDigest: payload.payloadDigest, files });
25739
+ await atomicJSON(path10.join(temporary, "installation.json"), { version: payload.version, profile, configFile: configFile2, payloadDigest: payload.payloadDigest, files });
24910
25740
  signal?.throwIfAborted();
24911
- await rename4(temporary, versionRoot);
25741
+ await rename5(temporary, versionRoot);
24912
25742
  newFiles = payload.files.length;
24913
25743
  }
24914
25744
  if (newFiles === 0) {
24915
- const launch = (await json(path7.join(versionRoot, ".mcp.json"))).mcpServers?.[serverName];
25745
+ const launch = (await json(path10.join(versionRoot, ".mcp.json"))).mcpServers?.[serverName];
24916
25746
  await verifyInstalledRuntime(versionRoot, payload.version, launch.command, { env });
24917
25747
  }
24918
25748
  const complete = { version: payload.version, profile, configFile: configFile2, pluginId, versionRoot, payloadDigest: payload.payloadDigest };
@@ -24931,12 +25761,12 @@ async function installForUser({
24931
25761
  await runCodex(["plugin", "marketplace", "add", root, "--json"]);
24932
25762
  await runCodex(["plugin", "add", pluginId, "--json"]);
24933
25763
  const observed = (await relatedPlugins(runCodex, pluginName, env)).find((x) => x.pluginId === pluginId);
24934
- if (observed?.version !== payload.version || observed.enabled !== true) fail("registration_unconfirmed");
25764
+ if (observed?.version !== payload.version || observed.enabled !== true) fail4("registration_unconfirmed");
24935
25765
  const launch = await managedTransport(observed, versions, serverName, profile, configFile2);
24936
25766
  const hostMcp = await codexJSON(runCodex, ["mcp", "list", "--json"]);
24937
- if (!Array.isArray(hostMcp)) fail("registration_unconfirmed");
25767
+ if (!Array.isArray(hostMcp)) fail4("registration_unconfirmed");
24938
25768
  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");
25769
+ if (effective.length !== 1 || effective[0].enabled === false || !sameTransport(effective[0].transport, launch)) fail4("registration_unconfirmed");
24940
25770
  await atomicJSON(currentFile, complete);
24941
25771
  await rm2(pendingFile);
24942
25772
  }
@@ -24953,7 +25783,7 @@ async function installForUser({
24953
25783
  };
24954
25784
  } catch (error4) {
24955
25785
  if (registrationStarted) {
24956
- fail("registration_unconfirmed_keep_existing", {
25786
+ fail4("registration_unconfirmed_keep_existing", {
24957
25787
  ...installationErrorDetails(error4),
24958
25788
  phase: "registration_observation",
24959
25789
  localRegistrationState: "unknown",
@@ -24961,8 +25791,8 @@ async function installForUser({
24961
25791
  });
24962
25792
  }
24963
25793
  if (error4 instanceof CreationClientError) throw error4;
24964
- if (signal?.aborted) fail("interrupted_keep_existing");
24965
- fail("failed_keep_existing");
25794
+ if (signal?.aborted) fail4("interrupted_keep_existing");
25795
+ fail4("failed_keep_existing");
24966
25796
  } finally {
24967
25797
  await rm2(temporary, { recursive: true, force: true });
24968
25798
  await release();
@@ -24970,10 +25800,10 @@ async function installForUser({
24970
25800
  }
24971
25801
 
24972
25802
  // 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";
25803
+ import { createHash as createHash11, randomBytes as randomBytes7 } from "node:crypto";
25804
+ import { mkdir as mkdir7, open as open9, readFile as readFile9, rename as rename7, rm as rm5 } from "node:fs/promises";
24975
25805
  import { homedir as homedir9 } from "node:os";
24976
- import path12 from "node:path";
25806
+ import path15 from "node:path";
24977
25807
 
24978
25808
  // lib/claude-hook-definition.mjs
24979
25809
  function claudeHostHooks({ pluginName = "promptframe-creation", serverName, configFile: configFile2, nodeCommand = "node", runtimeRoot = "${CLAUDE_PLUGIN_ROOT}" } = {}) {
@@ -24996,10 +25826,10 @@ function claudeHostHooks({ pluginName = "promptframe-creation", serverName, conf
24996
25826
  // lib/claude-command.mjs
24997
25827
  import { execFile as execFile3 } from "node:child_process";
24998
25828
  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";
25829
+ import { access, lstat as lstat8, readdir as readdir5 } from "node:fs/promises";
25830
+ import { constants as constants4 } from "node:fs";
25001
25831
  import { homedir as homedir5 } from "node:os";
25002
- import path8 from "node:path";
25832
+ import path11 from "node:path";
25003
25833
  var execute3 = promisify3(execFile3);
25004
25834
  var ClaudeCommandError = class extends CreationClientError {
25005
25835
  constructor(code, details) {
@@ -25011,23 +25841,23 @@ var claudeErrorDetails = (error4) => error4 instanceof ClaudeCommandError ? erro
25011
25841
  async function resolveClaudeCommand({ env = process.env, homeDirectory = homedir5(), executable } = {}) {
25012
25842
  const selected = executable ?? env.PROMPTFRAME_CLAUDE_BIN;
25013
25843
  if (selected) {
25014
- if (!path8.isAbsolute(selected)) throw new CreationClientError("installation.claude_executable_invalid");
25015
- await access(selected, constants2.X_OK);
25844
+ if (!path11.isAbsolute(selected)) throw new CreationClientError("installation.claude_executable_invalid");
25845
+ await access(selected, constants4.X_OK);
25016
25846
  return selected;
25017
25847
  }
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");
25848
+ for (const directory2 of (env.PATH ?? "").split(path11.delimiter).filter(path11.isAbsolute)) {
25849
+ const file = path11.join(directory2, process.platform === "win32" ? "claude.exe" : "claude");
25020
25850
  try {
25021
- await access(file, constants2.X_OK);
25851
+ await access(file, constants4.X_OK);
25022
25852
  return file;
25023
25853
  } catch (e) {
25024
25854
  if (!["ENOENT", "EACCES", "ENOTDIR"].includes(e.code)) throw e;
25025
25855
  }
25026
25856
  }
25027
- const root = path8.join(homeDirectory, ".claude/remote/ccd-cli");
25857
+ const root = path11.join(homeDirectory, ".claude/remote/ccd-cli");
25028
25858
  let entries;
25029
25859
  try {
25030
- entries = await readdir4(root);
25860
+ entries = await readdir5(root);
25031
25861
  } catch (e) {
25032
25862
  if (e.code === "ENOENT") throw new CreationClientError("installation.claude_required");
25033
25863
  throw e;
@@ -25037,9 +25867,9 @@ async function resolveClaudeCommand({ env = process.env, homeDirectory = homedir
25037
25867
  for (const name of entries) {
25038
25868
  const match = name.match(/^(\d+)\.(\d+)\.(\d+)-[a-f0-9]{6,40}$/);
25039
25869
  if (!match) continue;
25040
- const file = path8.join(root, name), s3 = await lstat6(file);
25870
+ const file = path11.join(root, name), s3 = await lstat8(file);
25041
25871
  if (s3.isFile() && !s3.isSymbolicLink() && s3.uid === process.getuid?.()) {
25042
- await access(file, constants2.X_OK);
25872
+ await access(file, constants4.X_OK);
25043
25873
  candidates.push({ file, version: match.slice(1).map(Number) });
25044
25874
  }
25045
25875
  }
@@ -25075,17 +25905,17 @@ function createClaudeRunner({ env = process.env, executable, signal, resolve = r
25075
25905
  }
25076
25906
 
25077
25907
  // lib/claude-local-state.mjs
25078
- import { readFile as readFile6, lstat as lstat7 } from "node:fs/promises";
25908
+ import { readFile as readFile7, lstat as lstat9 } from "node:fs/promises";
25079
25909
  import { homedir as homedir6 } from "node:os";
25080
- import path9 from "node:path";
25910
+ import path12 from "node:path";
25081
25911
  function claudeConfigRoot(env = process.env) {
25082
- return path9.resolve(env.CLAUDE_CONFIG_DIR ?? path9.join(homedir6(), ".claude"));
25912
+ return path12.resolve(env.CLAUDE_CONFIG_DIR ?? path12.join(homedir6(), ".claude"));
25083
25913
  }
25084
25914
  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");
25915
+ const file = env.CLAUDE_CONFIG_DIR ? path12.join(claudeConfigRoot(env), ".claude.json") : path12.join(homedir6(), ".claude.json");
25086
25916
  let info5;
25087
25917
  try {
25088
- info5 = await lstat7(file);
25918
+ info5 = await lstat9(file);
25089
25919
  } catch (e) {
25090
25920
  if (e.code === "ENOENT") return null;
25091
25921
  throw new CreationClientError("installation.claude_local_registration_unconfirmed");
@@ -25094,7 +25924,7 @@ async function readClaudeUserServer(serverName, env = process.env) {
25094
25924
  throw new CreationClientError("installation.claude_local_registration_unconfirmed");
25095
25925
  let state;
25096
25926
  try {
25097
- state = JSON.parse(await readFile6(file, "utf8"));
25927
+ state = JSON.parse(await readFile7(file, "utf8"));
25098
25928
  } catch {
25099
25929
  throw new CreationClientError("installation.claude_local_registration_unconfirmed");
25100
25930
  }
@@ -25105,30 +25935,30 @@ async function readClaudeUserServer(serverName, env = process.env) {
25105
25935
  }
25106
25936
 
25107
25937
  // 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";
25938
+ import { createHash as createHash10, randomBytes as randomBytes6 } from "node:crypto";
25939
+ 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
25940
  import { homedir as homedir8 } from "node:os";
25111
- import path11 from "node:path";
25941
+ import path14 from "node:path";
25112
25942
 
25113
25943
  // 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";
25944
+ import { createHash as createHash9 } from "node:crypto";
25945
+ import { open as open7, rm as rm3 } from "node:fs/promises";
25946
+ import { constants as constants5 } from "node:fs";
25947
+ import path13 from "node:path";
25118
25948
  import { homedir as homedir7 } from "node:os";
25119
25949
  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 = () => {
25950
+ var digest4 = (value2) => createHash9("sha256").update(JSON.stringify(value2)).digest("hex");
25951
+ var fail5 = () => {
25122
25952
  throw new CreationClientError("installation.claude_hooks_require_review");
25123
25953
  };
25124
25954
  async function settings(file) {
25125
25955
  let handle;
25126
25956
  try {
25127
- handle = await open5(file, constants3.O_RDONLY | constants3.O_NOFOLLOW);
25957
+ handle = await open7(file, constants5.O_RDONLY | constants5.O_NOFOLLOW);
25128
25958
  const info5 = await handle.stat();
25129
- if (!info5.isFile() || info5.uid !== process.getuid?.() || info5.size > 512 * 1024) fail2();
25959
+ if (!info5.isFile() || info5.uid !== process.getuid?.() || info5.size > 512 * 1024) fail5();
25130
25960
  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();
25961
+ if (!value2 || typeof value2 !== "object" || Array.isArray(value2) || value2.hooks !== void 0 && (!value2.hooks || typeof value2.hooks !== "object" || Array.isArray(value2.hooks))) fail5();
25132
25962
  return value2;
25133
25963
  } catch (e) {
25134
25964
  if (e.code === "ENOENT") return {};
@@ -25137,49 +25967,49 @@ async function settings(file) {
25137
25967
  await handle?.close();
25138
25968
  }
25139
25969
  }
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));
25970
+ 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
25971
  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();
25972
+ if (!record2?.settingsFile || record2.settingsFile !== path13.join(claudeConfigRoot(env), "settings.json") || !record2.entries) fail5();
25973
+ if (!contains(await settings(record2.settingsFile), record2.entries)) fail5();
25144
25974
  return true;
25145
25975
  }
25146
25976
  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"),
25977
+ const directory2 = claudeConfigRoot(env), file = path13.join(directory2, "settings.json");
25978
+ const guard = path13.resolve(
25979
+ env.XDG_DATA_HOME ?? path13.join(homedir7(), ".local/share"),
25150
25980
  "promptframe-creation",
25151
- "claude-hook-writer-" + digest3(directory)
25981
+ "claude-hook-writer-" + digest4(directory2)
25152
25982
  );
25153
25983
  await privateDirectory4(guard);
25154
25984
  const release = await acquire2(guard, signal);
25155
- const markerFile = path10.join(root, "hooks-current.json"), pendingFile = path10.join(root, "hooks-pending.json");
25985
+ const markerFile = path13.join(root, "hooks-current.json"), pendingFile = path13.join(root, "hooks-pending.json");
25156
25986
  try {
25157
- await privateDirectory4(directory);
25987
+ await privateDirectory4(directory2);
25158
25988
  const entries = claudeHostHooks({ serverName: record2.serverName, configFile: record2.configFile, nodeCommand, runtimeRoot: record2.versionRoot });
25159
25989
  const expected = { contractVersion: "creation-claude-hooks/v1", settingsFile: file, profile: record2.profile, entries };
25160
25990
  const pending = await privateRead3(pendingFile), previous = await privateRead3(markerFile), before = await settings(file);
25161
25991
  if (pending) {
25162
- if (digest3(pending) !== digest3(expected) || !contains(before, entries)) throw new CreationClientError("installation.registration_unconfirmed_keep_existing");
25992
+ if (digest4(pending) !== digest4(expected) || !contains(before, entries)) throw new CreationClientError("installation.registration_unconfirmed_keep_existing");
25163
25993
  await atomicJSON2(markerFile, expected);
25164
25994
  await rm3(pendingFile);
25165
25995
  return expected;
25166
25996
  }
25167
25997
  if (previous) {
25168
- if (previous.contractVersion !== expected.contractVersion || previous.profile !== record2.profile || previous.settingsFile !== file) fail2();
25998
+ if (previous.contractVersion !== expected.contractVersion || previous.profile !== record2.profile || previous.settingsFile !== file) fail5();
25169
25999
  await verifyClaudeFallbackHooks(previous, env);
25170
- if (digest3(previous) === digest3(expected)) return previous;
26000
+ if (digest4(previous) === digest4(expected)) return previous;
25171
26001
  }
25172
26002
  const next = { ...before, hooks: { ...before.hooks } };
25173
26003
  for (const [event, wanted] of Object.entries(entries)) {
25174
26004
  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];
26005
+ if (!Array.isArray(actual)) fail5();
26006
+ const owned = new Set((previous?.entries[event] ?? []).map(digest4));
26007
+ if (wanted.some((entry) => actual.some((value2) => digest4(value2) === digest4(entry)) && !owned.has(digest4(entry)))) fail5();
26008
+ next.hooks[event] = [...actual.filter((entry) => !owned.has(digest4(entry))), ...wanted];
25179
26009
  }
25180
26010
  signal?.throwIfAborted();
25181
26011
  await atomicJSON2(pendingFile, expected);
25182
- if (digest3(await settings(file)) !== digest3(before)) fail2();
26012
+ if (digest4(await settings(file)) !== digest4(before)) fail5();
25183
26013
  await atomicJSON2(file, next);
25184
26014
  if (!contains(await settings(file), entries)) throw new CreationClientError("installation.registration_unconfirmed_keep_existing");
25185
26015
  await atomicJSON2(markerFile, expected);
@@ -25192,7 +26022,7 @@ async function registerClaudeFallbackHooks({ record: record2, root, env, nodeCom
25192
26022
 
25193
26023
  // lib/claude-mcp-installation.mjs
25194
26024
  var { info: info3, privateDirectory: privateDirectory5, privateRead: privateRead4, atomicJSON: atomicJSON3, acquire: acquire3, compareVersions: compareVersions2 } = installationFiles;
25195
- var hash5 = (body) => createHash8("sha256").update(body).digest("hex");
26025
+ var hash5 = (body) => createHash10("sha256").update(body).digest("hex");
25196
26026
  var FallbackError = class extends CreationClientError {
25197
26027
  constructor(code, details) {
25198
26028
  super("installation." + code);
@@ -25200,14 +26030,14 @@ var FallbackError = class extends CreationClientError {
25200
26030
  }
25201
26031
  };
25202
26032
  var fallbackErrorDetails = (error4) => error4 instanceof FallbackError ? error4.details : void 0;
25203
- var fail3 = (code, details) => {
26033
+ var fail6 = (code, details) => {
25204
26034
  throw new FallbackError(code, details);
25205
26035
  };
25206
26036
  async function claimSkillDirectory(root) {
25207
26037
  try {
25208
- await mkdir5(root, { mode: 448 });
26038
+ await mkdir6(root, { mode: 448 });
25209
26039
  } catch (error4) {
25210
- if (error4.code === "EEXIST") fail3("claude_skill_requires_review");
26040
+ if (error4.code === "EEXIST") fail6("claude_skill_requires_review");
25211
26041
  throw error4;
25212
26042
  }
25213
26043
  }
@@ -25218,17 +26048,17 @@ function same(a, b2, depth = 0) {
25218
26048
  return left.length <= 256 && left.length === right.length && left.every((key, i) => key === right[i] && same(a[key], b2[key], depth + 1));
25219
26049
  }
25220
26050
  async function atomicText(file, body) {
25221
- const temporary = file + "." + randomBytes5(12).toString("hex") + ".tmp";
26051
+ const temporary = file + "." + randomBytes6(12).toString("hex") + ".tmp";
25222
26052
  try {
25223
- const fd = await open6(temporary, "wx", 384);
26053
+ const fd = await open8(temporary, "wx", 384);
25224
26054
  try {
25225
26055
  await fd.writeFile(body);
25226
26056
  await fd.sync();
25227
26057
  } finally {
25228
26058
  await fd.close();
25229
26059
  }
25230
- await rename5(temporary, file);
25231
- const dir = await open6(path11.dirname(file), "r");
26060
+ await rename6(temporary, file);
26061
+ const dir = await open8(path14.dirname(file), "r");
25232
26062
  try {
25233
26063
  await dir.sync();
25234
26064
  } finally {
@@ -25239,41 +26069,41 @@ async function atomicText(file, body) {
25239
26069
  }
25240
26070
  }
25241
26071
  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");
26072
+ const directory2 = await info3(root);
26073
+ if (!directory2?.isDirectory() || directory2.isSymbolicLink() || directory2.uid !== process.getuid?.() || directory2.mode & 63) fail6("claude_installed_files_invalid");
26074
+ const marker = await privateRead4(path14.join(root, "installation.json")), payload = await inspectRuntimePackage(root);
26075
+ 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
26076
  return marker;
25247
26077
  }
25248
26078
  function mcpDefinition(record2, nodeCommand) {
25249
26079
  return {
25250
26080
  type: "stdio",
25251
26081
  command: nodeCommand,
25252
- args: [path11.join(record2.versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", record2.configFile, "--host", "claude-code"]
26082
+ args: [path14.join(record2.versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", record2.configFile, "--host", "claude-code"]
25253
26083
  };
25254
26084
  }
25255
26085
  function skillBody(payload, sourceName, name) {
25256
26086
  const file = payload.files.find((f2) => f2.path === "skills/" + sourceName + "/SKILL.md");
25257
- if (!file) fail3("package_incomplete");
26087
+ if (!file) fail6("package_incomplete");
25258
26088
  const body = file.body.toString("utf8");
25259
- if (!body.startsWith("---\n") || !body.includes("\nname: " + sourceName + "\n")) fail3("package_incomplete");
26089
+ if (!body.startsWith("---\n") || !body.includes("\nname: " + sourceName + "\n")) fail6("package_incomplete");
25260
26090
  return body.replace("\nname: " + sourceName + "\n", "\nname: " + name + "\n");
25261
26091
  }
25262
26092
  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);
26093
+ const directory2 = await info3(plan.root);
26094
+ if (!directory2) return false;
26095
+ if (!directory2.isDirectory() || directory2.isSymbolicLink() || directory2.uid !== process.getuid?.() || directory2.mode & 63) fail6("claude_skill_requires_review");
26096
+ const names = await readdir6(plan.root);
26097
+ if (names.some((n) => !["SKILL.md", "promptframe-installation.json"].includes(n))) fail6("claude_skill_requires_review");
26098
+ const marker = await privateRead4(path14.join(plan.root, "promptframe-installation.json")), file = path14.join(plan.root, "SKILL.md"), s3 = await info3(file);
25269
26099
  if (!marker || marker.host !== "claude-code" || marker.profile !== record2.profile || marker.configFile !== record2.configFile || marker.name !== plan.name)
25270
- fail3("claude_skill_requires_review");
26100
+ fail6("claude_skill_requires_review");
25271
26101
  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");
26102
+ if (!s3?.isFile() || s3.isSymbolicLink() || s3.size > 256 * 1024) fail6("claude_skill_requires_review");
26103
+ const digest5 = hash5(await readFile8(file));
26104
+ if (digest5 === plan.sha256 && marker.sha256 === plan.sha256) return true;
26105
+ if (allowBefore && (digest5 === plan.beforeSHA || digest5 === plan.sha256) && marker.sha256 === plan.beforeSHA) return false;
26106
+ fail6("claude_skill_requires_review");
25277
26107
  }
25278
26108
  async function installClaudeMcpFallback({
25279
26109
  sourceRoot,
@@ -25287,13 +26117,13 @@ async function installClaudeMcpFallback({
25287
26117
  nodeCommand,
25288
26118
  writeSkill = atomicText
25289
26119
  }) {
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");
26120
+ 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
26121
  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"));
26122
+ 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
26123
  let writeStarted = false, newFiles = 0;
25294
26124
  const complete = { host: "claude-code", mode: "mcp-and-skills", profile, configFile: configFile2, serverName, version: payload.version, versionRoot, payloadDigest: payload.payloadDigest };
25295
26125
  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");
26126
+ 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
26127
  };
25298
26128
  try {
25299
26129
  await privateDirectory5(versions);
@@ -25304,31 +26134,31 @@ async function installClaudeMcpFallback({
25304
26134
  complete.beforeServer = pending?.beforeServer ?? saved;
25305
26135
  const settled = async (record2) => {
25306
26136
  const ready2 = await verifyVersion(record2.versionRoot, record2);
25307
- if (!same(record2.server, mcpDefinition(record2, ready2.nodeCommand))) fail3("claude_installed_files_invalid");
26137
+ if (!same(record2.server, mcpDefinition(record2, ready2.nodeCommand))) fail6("claude_installed_files_invalid");
25308
26138
  if (!same(saved, record2.server)) return false;
25309
26139
  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");
26140
+ if (!Array.isArray(record2.skills) || record2.skills.length !== 2) fail6("claude_skill_requires_review");
25311
26141
  for (const [i, skill] of record2.skills.entries()) {
25312
26142
  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");
26143
+ if (skill.name !== name || skill.root !== path14.join(claudeConfigRoot(env), "skills", name) || !/^[a-f0-9]{64}$/.test(skill.sha256 ?? ""))
26144
+ fail6("claude_skill_requires_review");
25315
26145
  if (!await observedSkill(skill, record2)) return false;
25316
26146
  }
25317
26147
  return true;
25318
26148
  };
25319
26149
  if (pending) {
25320
26150
  writeStarted = true;
25321
- if (pending.version !== complete.version || pending.payloadDigest !== complete.payloadDigest) fail3("registration_unconfirmed_keep_existing");
26151
+ if (pending.version !== complete.version || pending.payloadDigest !== complete.payloadDigest) fail6("registration_unconfirmed_keep_existing");
25322
26152
  if (pending.phase === "mcp") {
25323
- if (!await settled(pending)) fail3("registration_unconfirmed_keep_existing");
26153
+ if (!await settled(pending)) fail6("registration_unconfirmed_keep_existing");
25324
26154
  await atomicJSON3(currentFile, pending);
25325
26155
  await rm4(pendingFile);
25326
26156
  previous = pending;
25327
26157
  pending = null;
25328
- } else if (pending.phase !== "skills" || !same(saved, pending.beforeServer)) fail3("registration_unconfirmed_keep_existing");
26158
+ } else if (pending.phase !== "skills" || !same(saved, pending.beforeServer)) fail6("registration_unconfirmed_keep_existing");
25329
26159
  }
25330
26160
  if (previous && !pending) {
25331
- if (!await settled(previous)) fail3("claude_local_registration_unconfirmed");
26161
+ if (!await settled(previous)) fail6("claude_local_registration_unconfirmed");
25332
26162
  if (compareVersions2(previous.version, payload.version) >= 0) {
25333
26163
  const ready2 = await verifyVersion(previous.versionRoot, previous);
25334
26164
  await verifyInstalledRuntime(previous.versionRoot, previous.version, ready2.nodeCommand, { env });
@@ -25347,15 +26177,15 @@ async function installClaudeMcpFallback({
25347
26177
  recordedRuntimeRetained: ready2.nodeCommand !== nodeCommand
25348
26178
  };
25349
26179
  }
25350
- } else if (saved && !pending) fail3("legacy_mcp_entry_requires_review");
26180
+ } else if (saved && !pending) fail6("legacy_mcp_entry_requires_review");
25351
26181
  if (await info3(versionRoot)) await verifyVersion(versionRoot, complete);
25352
26182
  else {
25353
- await mkdir5(temporary, { mode: 448 });
26183
+ await mkdir6(temporary, { mode: 448 });
25354
26184
  for (const file of payload.files) {
25355
26185
  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);
26186
+ const dest = path14.join(temporary, file.path);
26187
+ await mkdir6(path14.dirname(dest), { recursive: true, mode: 448 });
26188
+ const fd = await open8(dest, "wx", 384);
25359
26189
  try {
25360
26190
  await fd.writeFile(file.body);
25361
26191
  await fd.sync();
@@ -25364,33 +26194,33 @@ async function installClaudeMcpFallback({
25364
26194
  }
25365
26195
  }
25366
26196
  await checkRuntime(temporary, payload.version);
25367
- await atomicJSON3(path11.join(temporary, "installation.json"), { ...complete, nodeCommand });
26197
+ await atomicJSON3(path14.join(temporary, "installation.json"), { ...complete, nodeCommand });
25368
26198
  signal?.throwIfAborted();
25369
- await rename5(temporary, versionRoot);
26199
+ await rename6(temporary, versionRoot);
25370
26200
  newFiles = payload.files.length;
25371
26201
  }
25372
26202
  const ready = await verifyVersion(versionRoot, complete);
25373
26203
  complete.server = mcpDefinition(complete, ready.nodeCommand);
25374
26204
  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");
26205
+ const skillRoot = path14.join(claudeConfigRoot(env), "skills");
26206
+ await mkdir6(skillRoot, { recursive: true, mode: 448 });
26207
+ const parent = await lstat10(skillRoot);
26208
+ if (!parent.isDirectory() || parent.isSymbolicLink() || parent.uid !== process.getuid?.()) fail6("claude_skill_requires_review");
25379
26209
  const plans = [];
25380
26210
  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) };
26211
+ const name = sourceName + suffix, body = skillBody(payload, sourceName, name), skill = { name, root: path14.join(skillRoot, name), sha256: hash5(body) };
25382
26212
  if (pending) {
25383
26213
  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");
26214
+ if (!old || old.root !== skill.root || old.sha256 !== skill.sha256) fail6("registration_unconfirmed_keep_existing");
25385
26215
  plans.push({ ...old, body });
25386
26216
  } else {
25387
26217
  const existing = await info3(skill.root);
25388
26218
  let beforeSHA = null;
25389
26219
  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");
26220
+ const marker = await privateRead4(path14.join(skill.root, "promptframe-installation.json"));
26221
+ if (!marker || marker.profile !== profile || marker.configFile !== configFile2 || marker.name !== name) fail6("claude_skill_requires_review");
25392
26222
  const old = { ...skill, sha256: marker.sha256 };
25393
- if (!await observedSkill(old, complete)) fail3("claude_skill_requires_review");
26223
+ if (!await observedSkill(old, complete)) fail6("claude_skill_requires_review");
25394
26224
  beforeSHA = marker.sha256;
25395
26225
  }
25396
26226
  plans.push({ ...skill, beforeSHA, body });
@@ -25406,21 +26236,21 @@ async function installClaudeMcpFallback({
25406
26236
  if (await info3(plan.root)) {
25407
26237
  if (await observedSkill(plan, complete, { allowBefore: true })) continue;
25408
26238
  } else {
25409
- if (plan.beforeSHA !== null) fail3("claude_skill_requires_review");
26239
+ if (plan.beforeSHA !== null) fail6("claude_skill_requires_review");
25410
26240
  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 });
26241
+ await atomicJSON3(path14.join(plan.root, "promptframe-installation.json"), { host: "claude-code", profile, configFile: configFile2, name: plan.name, sha256: null });
25412
26242
  }
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 });
26243
+ await writeSkill(path14.join(plan.root, "SKILL.md"), plan.body);
26244
+ await atomicJSON3(path14.join(plan.root, "promptframe-installation.json"), { host: "claude-code", profile, configFile: configFile2, name: plan.name, sha256: plan.sha256 });
25415
26245
  }
25416
26246
  signal?.throwIfAborted();
25417
26247
  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");
26248
+ if (!same(await readClaudeUserServer(serverName, env), complete.beforeServer)) fail6("claude_local_registration_changed");
25419
26249
  await atomicJSON3(pendingFile, { ...complete, phase: "mcp" });
25420
26250
  writeStarted = true;
25421
26251
  await runClaude(["mcp", "add-json", "--scope", "user", serverName, JSON.stringify(complete.server)]);
25422
26252
  saved = await readClaudeUserServer(serverName, env);
25423
- if (!await settled(complete)) fail3("registration_unconfirmed_keep_existing");
26253
+ if (!await settled(complete)) fail6("registration_unconfirmed_keep_existing");
25424
26254
  await atomicJSON3(currentFile, complete);
25425
26255
  await rm4(pendingFile);
25426
26256
  return {
@@ -25437,9 +26267,9 @@ async function installClaudeMcpFallback({
25437
26267
  versionStatus: "current"
25438
26268
  };
25439
26269
  } catch (error4) {
25440
- if (writeStarted) fail3("registration_unconfirmed_keep_existing", { phase: "registration_observation", localRegistrationState: "unknown", action: "inspect_same_registration_no_second_add" });
26270
+ if (writeStarted) fail6("registration_unconfirmed_keep_existing", { phase: "registration_observation", localRegistrationState: "unknown", action: "inspect_same_registration_no_second_add" });
25441
26271
  if (error4 instanceof CreationClientError) throw error4;
25442
- fail3(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
26272
+ fail6(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
25443
26273
  } finally {
25444
26274
  await rm4(temporary, { recursive: true, force: true });
25445
26275
  await release();
@@ -25457,7 +26287,7 @@ var ClaudeInstallationError = class extends CreationClientError {
25457
26287
  }
25458
26288
  };
25459
26289
  var claudeInstallationDetails = (error4) => error4 instanceof ClaudeInstallationError ? error4.details : void 0;
25460
- var fail4 = (code, details) => {
26290
+ var fail7 = (code, details) => {
25461
26291
  throw new ClaudeInstallationError(code, details);
25462
26292
  };
25463
26293
  async function jsonCommand(run, args2) {
@@ -25467,9 +26297,9 @@ async function jsonCommand(run, args2) {
25467
26297
  if (typeof body !== "string" || Buffer.byteLength(body) > 2 * 1024 * 1024) throw Error();
25468
26298
  value2 = JSON.parse(body);
25469
26299
  } catch {
25470
- fail4("claude_local_registration_unconfirmed");
26300
+ fail7("claude_local_registration_unconfirmed");
25471
26301
  }
25472
- if (!Array.isArray(value2) || value2.length > 1024) fail4("claude_local_registration_unconfirmed");
26302
+ if (!Array.isArray(value2) || value2.length > 1024) fail7("claude_local_registration_unconfirmed");
25473
26303
  return value2;
25474
26304
  }
25475
26305
  async function registrations(run, pluginName, marketplace, root) {
@@ -25478,17 +26308,17 @@ async function registrations(run, pluginName, marketplace, root) {
25478
26308
  jsonCommand(run, ["plugin", "marketplace", "list", "--json"])
25479
26309
  ]);
25480
26310
  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");
26311
+ fail7("claude_local_registration_unconfirmed");
25482
26312
  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");
26313
+ 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 ?? ""))))
26314
+ fail7("claude_existing_registration_requires_review");
25485
26315
  const found = markets.filter((p2) => p2?.name === marketplace);
25486
26316
  if (found.length > 1 || found.some((p2) => p2.source !== "directory" || p2.path !== root || p2.installLocation !== root))
25487
- fail4("claude_existing_registration_requires_review");
26317
+ fail7("claude_existing_registration_requires_review");
25488
26318
  return { plugin: related[0], market: found[0] };
25489
26319
  }
25490
26320
  async function legacyUserMcp(env, serverName) {
25491
- if (await readClaudeUserServer(serverName, env)) fail4("legacy_mcp_entry_requires_review");
26321
+ if (await readClaudeUserServer(serverName, env)) fail7("legacy_mcp_entry_requires_review");
25492
26322
  }
25493
26323
  function transport(serverName, configFile2, command2 = process.execPath) {
25494
26324
  return { mcpServers: { [serverName]: {
@@ -25497,32 +26327,32 @@ function transport(serverName, configFile2, command2 = process.execPath) {
25497
26327
  } } };
25498
26328
  }
25499
26329
  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");
26330
+ const directory2 = await info4(root);
26331
+ if (!directory2?.isDirectory() || directory2.isSymbolicLink() || directory2.uid !== process.getuid?.() || directory2.mode & 63)
26332
+ fail7("claude_installed_files_invalid");
26333
+ const ready = await privateRead5(path15.join(root, "installation.json"));
26334
+ 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
26335
  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"));
26336
+ if (actual.version !== version3 || JSON.stringify(actual.files.map(({ path: path17, bytes: bytes2, sha256 }) => ({ path: path17, bytes: bytes2, sha256 }))) !== JSON.stringify(ready.files))
26337
+ fail7("claude_installed_files_invalid");
26338
+ const manifest = JSON.parse(await readFile9(path15.join(root, ".claude-plugin/plugin.json"), "utf8"));
25509
26339
  if (manifest.name !== pluginName || manifest.version !== version3 || manifest.skills !== "./skills/" || manifest.mcpServers !== "./.claude-mcp.json")
25510
- fail4("claude_installed_files_invalid");
26340
+ fail7("claude_installed_files_invalid");
25511
26341
  let runtimeCommand;
25512
26342
  for (const file of [".mcp.json", ".claude-mcp.json"]) {
25513
- const mcp = JSON.parse(await readFile8(path12.join(root, file), "utf8"));
26343
+ const mcp = JSON.parse(await readFile9(path15.join(root, file), "utf8"));
25514
26344
  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");
26345
+ if (!path15.isAbsolute(command2 ?? "") || runtimeCommand !== void 0 && command2 !== runtimeCommand || JSON.stringify(mcp) !== JSON.stringify(transport(serverName, configFile2, command2))) fail7("claude_installed_files_invalid");
25516
26346
  runtimeCommand = command2;
25517
26347
  }
25518
26348
  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");
26349
+ fail7("claude_installed_files_invalid");
25520
26350
  return { ...ready, runtimeCommand };
25521
26351
  }
25522
26352
  async function installForClaudeUser(options = {}) {
25523
26353
  const profile = options.profile ?? "default", env = options.env ?? process.env;
25524
26354
  validProfile2(profile);
25525
- const modeRoot = path12.resolve(env.XDG_DATA_HOME ?? path12.join(homedir9(), ".local/share"), "promptframe-creation", profile, "claude-code-mode");
26355
+ const modeRoot = path15.resolve(env.XDG_DATA_HOME ?? path15.join(homedir9(), ".local/share"), "promptframe-creation", profile, "claude-code-mode");
25526
26356
  await privateDirectory6(modeRoot);
25527
26357
  const release = await acquire4(modeRoot, options.signal);
25528
26358
  try {
@@ -25544,37 +26374,37 @@ async function installClaudeUserLocked({
25544
26374
  nodeCommand = process.execPath
25545
26375
  } = {}) {
25546
26376
  validProfile2(profile);
25547
- if (!path12.isAbsolute(nodeCommand)) fail4("runtime_command_invalid");
26377
+ if (!path15.isAbsolute(nodeCommand)) fail7("runtime_command_invalid");
25548
26378
  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");
26379
+ if (!hostVersion || compareVersions3(hostVersion[1], "2.1.295") < 0) fail7("claude_21295_required");
25550
26380
  const help = await runClaude(["--help"]);
25551
- if (typeof help !== "string" || Buffer.byteLength(help) > 128 * 1024) fail4("claude_capabilities_unconfirmed");
26381
+ if (typeof help !== "string" || Buffer.byteLength(help) > 128 * 1024) fail7("claude_capabilities_unconfirmed");
25552
26382
  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");
26383
+ 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");
26384
+ 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"));
26385
+ if ((!hasPlugin || fallbackState) && (pluginPending || pluginCurrent)) fail7("registration_unconfirmed_keep_existing");
25556
26386
  if (!hasPlugin || fallbackState) {
25557
- if (!hasMcp) fail4("claude_capabilities_unconfirmed");
26387
+ if (!hasMcp) fail7("claude_capabilities_unconfirmed");
25558
26388
  return installClaudeMcpFallback({ sourceRoot, profile, env, configFile: configFile2, signal, runClaude, checkRuntime, verifyInstalledRuntime, nodeCommand });
25559
26389
  }
25560
- const payload = await inspectRuntimePackage(path12.resolve(sourceRoot));
26390
+ const payload = await inspectRuntimePackage(path15.resolve(sourceRoot));
25561
26391
  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");
26392
+ fail7("claude_package_incomplete");
26393
+ const root = path15.resolve(env.XDG_DATA_HOME ?? path15.join(homedir9(), ".local/share"), "promptframe-creation", profile, "claude-code");
25564
26394
  await privateDirectory6(root);
25565
26395
  const release = await acquire4(root, signal);
25566
26396
  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"));
26397
+ 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
26398
  let registrationStarted = false, newFiles = 0;
25569
26399
  try {
25570
26400
  signal?.throwIfAborted();
25571
26401
  await privateDirectory6(versions);
25572
- await privateDirectory6(path12.dirname(catalogFile));
26402
+ await privateDirectory6(path15.dirname(catalogFile));
25573
26403
  await legacyUserMcp(env, serverName);
25574
26404
  let previous = await privateRead5(currentFile), pending = await privateRead5(pendingFile), state = await registrations(runClaude, pluginName, marketplace, root);
25575
26405
  const binding = { profile, configFile: configFile2, pluginId, pluginName, serverName, host: "claude-code" };
25576
26406
  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");
26407
+ 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
26408
  };
25579
26409
  checkBinding(previous);
25580
26410
  checkBinding(pending);
@@ -25592,10 +26422,10 @@ async function installClaudeUserLocked({
25592
26422
  previous = pending;
25593
26423
  pending = null;
25594
26424
  } 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" });
26425
+ fail7("registration_unconfirmed_keep_existing", { phase: "registration_observation", localRegistrationState: "unknown", action: "inspect_same_registration_no_second_add" });
25596
26426
  }
25597
- if (state.plugin && !previous && !pending) fail4("claude_existing_registration_requires_review");
25598
- if (previous && !await observed(previous) && !pending) fail4("claude_local_registration_unconfirmed");
26427
+ if (state.plugin && !previous && !pending) fail7("claude_existing_registration_requires_review");
26428
+ if (previous && !await observed(previous) && !pending) fail7("claude_local_registration_unconfirmed");
25599
26429
  if (previous && compareVersions3(previous.version, payload.version) > 0) {
25600
26430
  const recorded = runtimeCommands.get(previous.versionRoot);
25601
26431
  await verifyInstalledRuntime(previous.versionRoot, previous.version, recorded, { env });
@@ -25613,17 +26443,17 @@ async function installClaudeUserLocked({
25613
26443
  }
25614
26444
  const complete = { ...binding, version: payload.version, versionRoot, payloadDigest: payload.payloadDigest };
25615
26445
  if (pending && (pending.version !== complete.version || pending.payloadDigest !== complete.payloadDigest))
25616
- fail4("registration_unconfirmed_keep_existing");
26446
+ fail7("registration_unconfirmed_keep_existing");
25617
26447
  if (await info4(versionRoot)) {
25618
26448
  const ready = await verifyVersion2(versionRoot, { ...complete, pluginName, serverName });
25619
26449
  runtimeCommands.set(versionRoot, ready.runtimeCommand);
25620
26450
  } else {
25621
- await mkdir6(temporary, { mode: 448 });
26451
+ await mkdir7(temporary, { mode: 448 });
25622
26452
  for (const file of payload.files) {
25623
26453
  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);
26454
+ const dest = path15.join(temporary, file.path);
26455
+ await mkdir7(path15.dirname(dest), { recursive: true, mode: 448 });
26456
+ const fd = await open9(dest, "wx", 384);
25627
26457
  try {
25628
26458
  await fd.writeFile(file.body);
25629
26459
  await fd.sync();
@@ -25631,21 +26461,21 @@ async function installClaudeUserLocked({
25631
26461
  await fd.close();
25632
26462
  }
25633
26463
  }
25634
- const manifest = JSON.parse(await readFile8(path12.join(temporary, ".claude-plugin/plugin.json"), "utf8"));
26464
+ const manifest = JSON.parse(await readFile9(path15.join(temporary, ".claude-plugin/plugin.json"), "utf8"));
25635
26465
  manifest.name = pluginName;
25636
26466
  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));
26467
+ await atomicJSON4(path15.join(temporary, ".claude-plugin/plugin.json"), manifest);
26468
+ for (const file of [".mcp.json", ".claude-mcp.json"]) await atomicJSON4(path15.join(temporary, file), transport(serverName, configFile2, nodeCommand));
25639
26469
  await checkRuntime(temporary, payload.version);
25640
26470
  const installed = await inspectRuntimePackage(temporary);
25641
- await atomicJSON4(path12.join(temporary, "installation.json"), {
26471
+ await atomicJSON4(path15.join(temporary, "installation.json"), {
25642
26472
  ...binding,
25643
26473
  version: payload.version,
25644
26474
  payloadDigest: payload.payloadDigest,
25645
- files: installed.files.map(({ path: path14, bytes: bytes2, sha256 }) => ({ path: path14, bytes: bytes2, sha256 }))
26475
+ files: installed.files.map(({ path: path17, bytes: bytes2, sha256 }) => ({ path: path17, bytes: bytes2, sha256 }))
25646
26476
  });
25647
26477
  signal?.throwIfAborted();
25648
- await rename6(temporary, versionRoot);
26478
+ await rename7(temporary, versionRoot);
25649
26479
  newFiles = payload.files.length;
25650
26480
  }
25651
26481
  if (newFiles === 0) await verifyInstalledRuntime(versionRoot, payload.version, runtimeCommands.get(versionRoot), { env });
@@ -25653,18 +26483,18 @@ async function installClaudeUserLocked({
25653
26483
  if (!already) {
25654
26484
  await atomicJSON4(catalogFile, { name: marketplace, owner: { name: "PromptFrame" }, plugins: [{ name: pluginName, source: "./versions/" + payload.version }] });
25655
26485
  if (!state.market) {
25656
- if (pending) fail4("registration_unconfirmed_keep_existing");
26486
+ if (pending) fail7("registration_unconfirmed_keep_existing");
25657
26487
  await atomicJSON4(pendingFile, { ...complete, phase: "marketplace" });
25658
26488
  registrationStarted = true;
25659
26489
  await runClaude(["plugin", "marketplace", "add", root, "--scope", "user", "--json"]);
25660
26490
  state = await registrations(runClaude, pluginName, marketplace, root);
25661
- if (!state.market) fail4("claude_registration_unconfirmed");
26491
+ if (!state.market) fail7("claude_registration_unconfirmed");
25662
26492
  }
25663
26493
  await atomicJSON4(pendingFile, { ...complete, phase: "plugin" });
25664
26494
  registrationStarted = true;
25665
26495
  await runClaude(["plugin", "install", pluginId, "--scope", "user", "--json"]);
25666
26496
  state = await registrations(runClaude, pluginName, marketplace, root);
25667
- if (!await observed(complete)) fail4("claude_registration_unconfirmed");
26497
+ if (!await observed(complete)) fail7("claude_registration_unconfirmed");
25668
26498
  await atomicJSON4(currentFile, complete);
25669
26499
  await rm5(pendingFile);
25670
26500
  }
@@ -25681,14 +26511,14 @@ async function installClaudeUserLocked({
25681
26511
  recordedRuntimeRetained: runtimeCommands.has(versionRoot) && runtimeCommands.get(versionRoot) !== nodeCommand
25682
26512
  };
25683
26513
  } catch (error4) {
25684
- if (registrationStarted) fail4("registration_unconfirmed_keep_existing", {
26514
+ if (registrationStarted) fail7("registration_unconfirmed_keep_existing", {
25685
26515
  ...claudeErrorDetails(error4),
25686
26516
  phase: "registration_observation",
25687
26517
  localRegistrationState: "unknown",
25688
26518
  action: "inspect_same_registration_no_second_add"
25689
26519
  });
25690
26520
  if (error4 instanceof CreationClientError) throw error4;
25691
- fail4(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
26521
+ fail7(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
25692
26522
  } finally {
25693
26523
  await rm5(temporary, { recursive: true, force: true });
25694
26524
  await release();
@@ -25697,7 +26527,7 @@ async function installClaudeUserLocked({
25697
26527
 
25698
26528
  // lib/cli.mjs
25699
26529
  import { fileURLToPath } from "node:url";
25700
- import path13 from "node:path";
26530
+ import path16 from "node:path";
25701
26531
  var args = process.argv.slice(2);
25702
26532
  var command = args.shift();
25703
26533
  var value = (key) => {
@@ -25705,7 +26535,7 @@ var value = (key) => {
25705
26535
  return i < 0 ? void 0 : args[i + 1];
25706
26536
  };
25707
26537
  var log = (value2) => process.stdout.write(JSON.stringify(value2) + "\n");
25708
- var configFile = () => value("--config") ? path13.resolve(value("--config")) : profileCredentialsPath(value("--profile") ?? "default");
26538
+ var configFile = () => value("--config") ? path16.resolve(value("--config")) : profileCredentialsPath(value("--profile") ?? "default");
25709
26539
  async function probe(credentials) {
25710
26540
  const client = await connectPlatform(credentials, { host: resolveHostIdentity({ host: value("--host") }) });
25711
26541
  try {
@@ -25734,7 +26564,7 @@ async function tokenInput() {
25734
26564
  try {
25735
26565
  return await new Promise((resolve, reject) => {
25736
26566
  let text = "";
25737
- const read = (chunk) => {
26567
+ const read2 = (chunk) => {
25738
26568
  for (const byte of chunk) {
25739
26569
  if (byte === 3) {
25740
26570
  finish();
@@ -25756,10 +26586,10 @@ async function tokenInput() {
25756
26586
  }
25757
26587
  };
25758
26588
  const finish = () => {
25759
- input.removeListener("data", read);
26589
+ input.removeListener("data", read2);
25760
26590
  input.pause();
25761
26591
  };
25762
- input.on("data", read);
26592
+ input.on("data", read2);
25763
26593
  });
25764
26594
  } finally {
25765
26595
  input.setRawMode(Boolean(wasRaw));
@@ -25810,7 +26640,7 @@ async function setup({ silent = false } = {}) {
25810
26640
  version: 1,
25811
26641
  endpoint,
25812
26642
  token,
25813
- clientId: existing?.clientId ?? randomBytes7(24).toString("base64url"),
26643
+ clientId: existing?.clientId ?? randomBytes8(24).toString("base64url"),
25814
26644
  clientName: value("--name") ?? existing?.clientName ?? (resolveHostIdentity({ host: value("--host") }).kind === "claude-code" ? "Claude Code PromptFrame" : "Codex PromptFrame"),
25815
26645
  createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
25816
26646
  };
@@ -25845,7 +26675,7 @@ async function bridge() {
25845
26675
  resolvedVersion: value("--resolved-runtime-version"),
25846
26676
  signal: startup.signal,
25847
26677
  hostKind: identity.kind,
25848
- cacheRoot: path13.join(path13.dirname(configFile()), "runtime-cache")
26678
+ cacheRoot: path16.join(path16.dirname(configFile()), "runtime-cache")
25849
26679
  });
25850
26680
  startup.signal.throwIfAborted();
25851
26681
  } catch (error4) {
@@ -25879,6 +26709,7 @@ async function bridge() {
25879
26709
  credentials,
25880
26710
  host: identity,
25881
26711
  hostSession,
26712
+ localUploads: createLocalUploadManager({ stateRoot: path16.join(path16.dirname(configFile()), "local-upload-state") }),
25882
26713
  onCatalogChange: () => server.sendToolListChanged(),
25883
26714
  onKnowledgeChange: (kind) => kind === "resources" ? server.sendResourceListChanged() : server.sendPromptListChanged()
25884
26715
  });
@@ -25916,9 +26747,9 @@ async function bridge() {
25916
26747
  throw new Error("creation.connection_unresolved");
25917
26748
  }
25918
26749
  });
25919
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
26750
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
25920
26751
  try {
25921
- return await host.call(request.params);
26752
+ return await host.call(request.params, { signal: extra.signal });
25922
26753
  } catch (error4) {
25923
26754
  return {
25924
26755
  isError: true,
@@ -25940,6 +26771,7 @@ async function bridge() {
25940
26771
  const close = async () => {
25941
26772
  if (closing) return;
25942
26773
  closing = true;
26774
+ await host.close();
25943
26775
  await server.close().catch(() => {
25944
26776
  });
25945
26777
  await client.close().catch(() => {