@promptframe/creation 0.3.2 → 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.2";
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
  }
@@ -19729,6 +20530,7 @@ function assertMcpResponseBudget(result) {
19729
20530
 
19730
20531
  // lib/bridge-negotiation.mjs
19731
20532
  var CONTENT_TYPES = Object.freeze(["text", "image", "audio", "resource_link", "resource"]);
20533
+ var STANDARD_CONTENT_TYPES = Object.freeze(["text", "image", "resource"]);
19732
20534
  var versionParts = (value2) => {
19733
20535
  if (typeof value2 !== "string" || value2.length > 40 || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value2))
19734
20536
  throw new CreationClientError("creation.bridge_policy_invalid");
@@ -19744,7 +20546,7 @@ function compareBridgeVersions(left, right) {
19744
20546
  function readPlatformBridgePolicy(capabilities) {
19745
20547
  const policy = capabilities?.experimental?.["promptframe.creation"];
19746
20548
  if (policy === void 0) return null;
19747
- if (!policy || policy.contractVersion !== "creation-bridge-capabilities/v1" || policy.blockMaxBytes !== MCP_BLOCK_BYTES || policy.responseMaxBytes !== MCP_RESPONSE_BYTES || !Array.isArray(policy.contentTypes) || policy.contentTypes.length > CONTENT_TYPES.length || new Set(policy.contentTypes).size !== policy.contentTypes.length || !policy.contentTypes.includes("text") || policy.contentTypes.some((type) => !CONTENT_TYPES.includes(type)) || compareBridgeVersions(policy.recommendedBridge, policy.minBridge) < 0)
20549
+ if (!policy || policy.contractVersion !== "creation-bridge-capabilities/v1" || policy.blockMaxBytes !== MCP_BLOCK_BYTES || policy.responseMaxBytes !== MCP_RESPONSE_BYTES || !Array.isArray(policy.contentTypes) || policy.contentTypes.length > CONTENT_TYPES.length || new Set(policy.contentTypes).size !== policy.contentTypes.length || !policy.contentTypes.includes("text") || policy.contentTypes.some((type) => !CONTENT_TYPES.includes(type)) || policy.standardContentTypes !== void 0 && (!Array.isArray(policy.standardContentTypes) || policy.standardContentTypes.length !== STANDARD_CONTENT_TYPES.length || STANDARD_CONTENT_TYPES.some((type) => !policy.standardContentTypes.includes(type))) || compareBridgeVersions(policy.recommendedBridge, policy.minBridge) < 0)
19748
20550
  throw new CreationClientError("creation.bridge_policy_invalid");
19749
20551
  return Object.freeze({
19750
20552
  contractVersion: policy.contractVersion,
@@ -19752,7 +20554,8 @@ function readPlatformBridgePolicy(capabilities) {
19752
20554
  recommendedBridge: policy.recommendedBridge,
19753
20555
  contentTypes: [...policy.contentTypes],
19754
20556
  blockMaxBytes: policy.blockMaxBytes,
19755
- responseMaxBytes: policy.responseMaxBytes
20557
+ responseMaxBytes: policy.responseMaxBytes,
20558
+ ...policy.standardContentTypes ? { standardContentTypes: [...STANDARD_CONTENT_TYPES] } : {}
19756
20559
  });
19757
20560
  }
19758
20561
  function assertBridgeCompatible(capabilities, version3) {
@@ -19773,8 +20576,10 @@ var BridgeCompatibilityError = class extends CreationClientError {
19773
20576
  }
19774
20577
  };
19775
20578
  var bridgeErrorDetails = (error4) => error4 instanceof BridgeCompatibilityError ? error4.bridgeFacts : void 0;
19776
- function declaredHostContentCapabilities(capabilities) {
20579
+ function declaredHostContentCapabilities(capabilities, { initialized = false, standardContent = false } = {}) {
19777
20580
  const requested = capabilities?.experimental?.["promptframe.contentTypes"];
20581
+ if (requested === void 0 && initialized && standardContent)
20582
+ return { types: [...STANDARD_CONTENT_TYPES], source: "mcp-protocol" };
19778
20583
  if (!Array.isArray(requested) || requested.length > CONTENT_TYPES.length || requested.some((type) => !CONTENT_TYPES.includes(type))) return { types: ["text"], source: "text-fallback" };
19779
20584
  return { types: ["text", ...CONTENT_TYPES.filter((type) => type !== "text" && requested.includes(type))], source: "declared" };
19780
20585
  }
@@ -19823,23 +20628,23 @@ async function connectPlatform(credentials, { host = resolveHostIdentity(), cont
19823
20628
  }
19824
20629
 
19825
20630
  // lib/host-context.mjs
19826
- import { createHash as createHash3 } from "node:crypto";
20631
+ import { createHash as createHash5 } from "node:crypto";
19827
20632
 
19828
20633
  // lib/claude-host-session.mjs
19829
- import { constants } from "node:fs";
19830
- import { open as open2, mkdir as mkdir2, lstat as lstat2, rename as rename2, unlink as unlink2, rmdir } from "node:fs/promises";
19831
- 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";
19832
20637
  import { homedir as homedir3 } from "node:os";
19833
- import { createHash as createHash2, randomBytes as randomBytes2 } from "node:crypto";
20638
+ import { createHash as createHash4, randomBytes as randomBytes3 } from "node:crypto";
19834
20639
 
19835
20640
  // lib/claude-host-process.mjs
19836
- import { readFile as readFile2, readlink, stat } from "node:fs/promises";
19837
- import path2 from "node:path";
20641
+ import { readFile as readFile3, readlink, stat } from "node:fs/promises";
20642
+ import path5 from "node:path";
19838
20643
  import { homedir as homedir2 } from "node:os";
19839
- import { createHash } from "node:crypto";
19840
- 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");
19841
20646
  var bounded = async (file) => {
19842
- const value2 = await readFile2(file);
20647
+ const value2 = await readFile3(file);
19843
20648
  if (value2.length > 65536) throw Error("host_process_invalid");
19844
20649
  return value2;
19845
20650
  };
@@ -19868,8 +20673,8 @@ async function claudeHostProcess({
19868
20673
  if (visited.has(child.ppid)) return null;
19869
20674
  visited.add(child.ppid);
19870
20675
  const host = await readBirth(child.ppid);
19871
- const roots2 = [path2.join(home, ".claude", "remote", "ccd-cli"), path2.join(home, ".local", "share", "claude", "versions")];
19872
- 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)) {
19873
20678
  const executable = await readExecutable(host.exe);
19874
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;
19875
20680
  if (purpose === "hook") {
@@ -19877,8 +20682,8 @@ async function claudeHostProcess({
19877
20682
  if (!entryFile || !command2.some((arg) => arg.includes(entryFile)) || !command2.some((arg) => arg === "claude-host-hook" || arg.includes(" claude-host-hook"))) return null;
19878
20683
  }
19879
20684
  const binding = { pid: host.pid, birth: host.birth, uid, device: host.device, inode: host.inode, exe: host.exe, boot };
19880
- const digest4 = hash(binding);
19881
- 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() {
19882
20687
  try {
19883
20688
  const current = await readBirth(binding.pid);
19884
20689
  return current.birth === binding.birth && current.uid === uid && current.device === binding.device && current.inode === binding.inode && current.exe === binding.exe && await readBoot() === boot;
@@ -19906,22 +20711,22 @@ var canonical = (value2) => {
19906
20711
  return "{" + Object.keys(value2).sort().map((key) => JSON.stringify(key) + ":" + canonical(value2[key])).join(",") + "}";
19907
20712
  throw error2("request_invalid");
19908
20713
  };
19909
- var digest = (value2) => createHash2("sha256").update(canonical(value2)).digest("hex");
20714
+ var digest2 = (value2) => createHash4("sha256").update(canonical(value2)).digest("hex");
19910
20715
  var withoutProof = (args2) => Object.fromEntries(Object.entries(args2 ?? {}).filter(([key]) => key !== CLAUDE_HOST_PROOF));
19911
20716
  var later = (a, b2) => BigInt(a.birth) > BigInt(b2.birth) || a.birth === b2.birth && a.pid > b2.pid;
19912
- async function privateDirectory(directory) {
20717
+ async function privateDirectory(directory2) {
19913
20718
  try {
19914
- await mkdir2(directory, { mode: 448 });
20719
+ await mkdir3(directory2, { mode: 448 });
19915
20720
  } catch (e) {
19916
20721
  if (e.code !== "EEXIST") throw e;
19917
20722
  }
19918
- const info5 = await lstat2(directory);
20723
+ const info5 = await lstat4(directory2);
19919
20724
  if (!info5.isDirectory() || info5.isSymbolicLink() || info5.uid !== process.getuid?.() || info5.mode & 63) throw error2("host_identity_unavailable");
19920
20725
  }
19921
20726
  async function privateRead(file) {
19922
20727
  let handle;
19923
20728
  try {
19924
- handle = await open2(file, constants.O_RDONLY | constants.O_NOFOLLOW);
20729
+ handle = await open4(file, constants3.O_RDONLY | constants3.O_NOFOLLOW);
19925
20730
  const info5 = await handle.stat();
19926
20731
  if (!info5.isFile() || info5.uid !== process.getuid?.() || info5.mode & 63 || info5.size > 196608) throw error2("host_identity_unavailable");
19927
20732
  return JSON.parse(await handle.readFile("utf8"));
@@ -19934,9 +20739,9 @@ async function privateRead(file) {
19934
20739
  }
19935
20740
  async function createClaudeHostSession({ configFile: configFile2, env = process.env, root, association, hookProcess = false } = {}) {
19936
20741
  const owner = association === void 0 ? await claudeHostProcess({ env, purpose: hookProcess ? "hook" : "bridge" }) : association;
19937
- const base = root ?? path3.join(env.CLAUDE_CONFIG_DIR ?? path3.join(homedir3(), ".claude"), "promptframe-host-sessions");
19938
- const namespace = owner ? path3.join(base, digest([owner.digest, path3.resolve(configFile2)])) : null;
19939
- 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");
19940
20745
  async function state() {
19941
20746
  if (!owner || !await owner.isCurrent()) return null;
19942
20747
  const value2 = await privateRead(stateFile);
@@ -19948,10 +20753,10 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
19948
20753
  if (!owner || !await owner.isCurrent()) throw error2("host_identity_unavailable");
19949
20754
  await privateDirectory(base);
19950
20755
  await privateDirectory(namespace);
19951
- const lock = path3.join(namespace, "write.lock");
20756
+ const lock = path6.join(namespace, "write.lock");
19952
20757
  let acquired = false;
19953
20758
  for (let count = 0; count < 100; count++) try {
19954
- await mkdir2(lock, { mode: 448 });
20759
+ await mkdir3(lock, { mode: 448 });
19955
20760
  acquired = true;
19956
20761
  break;
19957
20762
  } catch (e) {
@@ -19965,13 +20770,13 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
19965
20770
  const current = await state(), next = await work(current);
19966
20771
  if (next === void 0) return;
19967
20772
  if (next === null) {
19968
- if (current) await unlink2(stateFile);
20773
+ if (current) await unlink3(stateFile);
19969
20774
  return;
19970
20775
  }
19971
20776
  const body = JSON.stringify(next);
19972
20777
  if (Buffer.byteLength(body) > 196608) throw error2("host_identity_unavailable");
19973
- temporary = path3.join(namespace, "state-" + randomBytes2(16).toString("hex") + ".partial");
19974
- 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);
19975
20780
  try {
19976
20781
  await file.writeFile(body);
19977
20782
  await file.sync();
@@ -19979,18 +20784,18 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
19979
20784
  await file.close();
19980
20785
  }
19981
20786
  if (!await owner.isCurrent()) throw error2("host_identity_unavailable");
19982
- await rename2(temporary, stateFile);
20787
+ await rename3(temporary, stateFile);
19983
20788
  temporary = void 0;
19984
- 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);
19985
20790
  try {
19986
- await directory.sync();
20791
+ await directory2.sync();
19987
20792
  } finally {
19988
- await directory.close();
20793
+ await directory2.close();
19989
20794
  }
19990
20795
  } finally {
19991
- if (temporary) await unlink2(temporary).catch(() => {
20796
+ if (temporary) await unlink3(temporary).catch(() => {
19992
20797
  });
19993
- await rmdir(lock);
20798
+ await rmdir2(lock);
19994
20799
  }
19995
20800
  }
19996
20801
  async function begin(raw) {
@@ -20002,7 +20807,7 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
20002
20807
  try {
20003
20808
  await transaction((current) => {
20004
20809
  const ticket = current?.tickets[proof];
20005
- 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");
20006
20811
  accepted = { threadId: current.sessionId, epoch: current.epoch };
20007
20812
  delete current.tickets[proof];
20008
20813
  return current;
@@ -20049,7 +20854,7 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
20049
20854
  tickets: same2 ? current.tickets : {}
20050
20855
  };
20051
20856
  if (event !== "PreToolUse") return next;
20052
- 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]);
20053
20858
  if (!nextId) {
20054
20859
  result = { hookSpecificOutput: { hookEventName: event, updatedInput: args2 } };
20055
20860
  return next;
@@ -20060,13 +20865,13 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
20060
20865
  return next;
20061
20866
  }
20062
20867
  if (Object.keys(next.tickets).length >= 128) delete next.tickets[Object.keys(next.tickets)[0]];
20063
- const token = randomBytes2(32).toString("hex");
20868
+ const token = randomBytes3(32).toString("hex");
20064
20869
  next.tickets[token] = { digest: key, epoch: next.epoch, sessionId: nextId };
20065
20870
  result = { hookSpecificOutput: { hookEventName: event, updatedInput: { ...args2, [CLAUDE_HOST_PROOF]: token } } };
20066
20871
  return next;
20067
20872
  });
20068
20873
  if (event === "SessionEnd") try {
20069
- await rmdir(namespace);
20874
+ await rmdir2(namespace);
20070
20875
  } catch (e) {
20071
20876
  if (!["ENOTEMPTY", "ENOENT"].includes(e.code)) throw e;
20072
20877
  }
@@ -20094,7 +20899,7 @@ async function runClaudeHostHook({ configFile: configFile2, input = process.stdi
20094
20899
  // lib/host-context.mjs
20095
20900
  var digestPattern = /^sha256:[a-f0-9]{64}$/;
20096
20901
  var accesses = /* @__PURE__ */ new Set(["independent-read", "controlled", "authority"]);
20097
- var digest2 = (value2) => "sha256:" + createHash3("sha256").update(value2).digest("hex");
20902
+ var digest3 = (value2) => "sha256:" + createHash5("sha256").update(value2).digest("hex");
20098
20903
  var canonical2 = (value2) => {
20099
20904
  if (value2 === null || typeof value2 === "string" || typeof value2 === "boolean" || typeof value2 === "number" && Number.isFinite(value2)) return JSON.stringify(value2);
20100
20905
  if (Array.isArray(value2)) return "[" + value2.map(canonical2).join(",") + "]";
@@ -20102,19 +20907,19 @@ var canonical2 = (value2) => {
20102
20907
  return "{" + Object.keys(value2).sort().map((key) => JSON.stringify(key) + ":" + canonical2(value2[key])).join(",") + "}";
20103
20908
  throw new CreationClientError("creation.request_invalid");
20104
20909
  };
20105
- var argumentsDigest = (value2) => digest2(canonical2(value2));
20910
+ var argumentsDigest = (value2) => digest3(canonical2(value2));
20106
20911
  var boundedSet = (map, key, value2) => {
20107
20912
  if (!map.has(key) && map.size >= 1024) map.delete(map.keys().next().value);
20108
20913
  map.set(key, value2);
20109
20914
  };
20110
- function createHostCallBridge(client, { credentials, host = resolveHostIdentity(), hostSession, onCatalogChange = () => {
20915
+ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(), hostSession, localUploads, onCatalogChange = () => {
20111
20916
  }, onKnowledgeChange = () => {
20112
20917
  } } = {}) {
20113
20918
  if (!credentials?.endpoint || !credentials.clientId) throw new CreationClientError("creation.bridge_identity_required");
20114
- const installationDigest = digest2(credentials.clientId);
20919
+ const installationDigest = digest3(credentials.clientId);
20115
20920
  const versions = /* @__PURE__ */ new Map(), controllers = /* @__PURE__ */ new Map(), catalogs = /* @__PURE__ */ new Map(), inflight = /* @__PURE__ */ new Map();
20116
20921
  const knowledgeVersions = /* @__PURE__ */ new Map(), upstream = client.getServerCapabilities?.() ?? {};
20117
- let platformDigest, accountDigest, directory, directoryRead, sequence = 0, hostEpoch;
20922
+ let platformDigest, accountDigest, directory2, directoryRead, sequence = 0, hostEpoch;
20118
20923
  function catalog(channel, version3, order) {
20119
20924
  if (typeof version3 !== "string" || !digestPattern.test(version3)) return;
20120
20925
  const old = catalogs.get(channel);
@@ -20131,7 +20936,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20131
20936
  const v2 = result?._meta?.["promptframe.creation"];
20132
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;
20133
20938
  const thread = params._meta?.threadId?.toLowerCase();
20134
- 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;
20135
20940
  for (const field of ["projectId", "sessionId"]) if (params.arguments?.[field] !== void 0 && v2[field] !== params.arguments[field]) return null;
20136
20941
  if (accountDigest && accountDigest !== v2.accountDigest) return null;
20137
20942
  const controllerKey = thread ?? "legacy", prior = controllers.get(controllerKey);
@@ -20149,7 +20954,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20149
20954
  const key = keyFor(target), c = v2.control;
20150
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;
20151
20956
  const old = versions.get(key), version3 = c.controlVersion, owned = c.editor.kind === "client" && c.editor.isCurrentClient;
20152
- 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";
20153
20958
  if (!old || version3 > old.version) boundedSet(versions, key, { version: version3, owned, needsRead: false, authorityOrder: order });
20154
20959
  else if (version3 === old.version && order >= (old.authorityOrder ?? 0)) {
20155
20960
  const freshRead = !result.isError && authorityRead && order > (old.invalidatedAt ?? 0);
@@ -20158,27 +20963,30 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20158
20963
  }
20159
20964
  return v2;
20160
20965
  }
20161
- async function send(params, binding) {
20966
+ async function send(params, binding, { signal, timeout = 6e4 } = {}) {
20162
20967
  await binding?.assertCurrent();
20163
- 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 } : {} }));
20164
20969
  await binding?.assertCurrent();
20165
20970
  return { result, trusted: remember(params, result, order) };
20166
20971
  }
20167
20972
  async function listTools() {
20168
20973
  const order = ++sequence, result = assertMcpResponseBudget(await client.listTools());
20169
20974
  if (result.tools.some((tool) => !accesses.has(tool._meta?.["promptframe.access"]))) throw new CreationClientError("creation.upgrade_required");
20170
- 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 };
20171
20976
  catalog("outer", result._meta?.["promptframe.catalogVersion"], order);
20172
20977
  return { ...result, tools: result.tools.map((tool) => {
20173
- 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;
20174
20982
  const { controlVersion: _managed, ...properties } = p2 ?? {};
20175
- return { ...tool, inputSchema: { ...tool.inputSchema, properties: { ...properties, ...host.kind === "claude-code" ? {
20983
+ return { ...tool, inputSchema: { ...schema, properties: { ...properties, ...host.kind === "claude-code" ? {
20176
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" }
20177
- } : {} }, ...tool.inputSchema.required ? { required: tool.inputSchema.required.filter((name) => name !== "controlVersion") } : {} } };
20985
+ } : {} }, ...schema.required ? { required: schema.required.filter((name) => name !== "controlVersion") } : {} } };
20178
20986
  }) };
20179
20987
  }
20180
20988
  async function ensureDirectory() {
20181
- if (!directory) {
20989
+ if (!directory2) {
20182
20990
  directoryRead ??= listTools().finally(() => {
20183
20991
  directoryRead = void 0;
20184
20992
  });
@@ -20186,7 +20994,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20186
20994
  }
20187
20995
  }
20188
20996
  function role(name) {
20189
- 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);
20190
20998
  if (found.length !== 1) throw new CreationClientError("creation.upgrade_required");
20191
20999
  return found[0].name;
20192
21000
  }
@@ -20232,7 +21040,8 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20232
21040
  readResource: (params) => knowledgeRead("resources", "readResource", params),
20233
21041
  listPrompts: (params) => knowledgeRead("prompts", "listPrompts", params),
20234
21042
  getPrompt: (params) => knowledgeRead("prompts", "getPrompt", params),
20235
- async call(raw) {
21043
+ close: () => localUploads?.close(),
21044
+ async call(raw, { signal } = {}) {
20236
21045
  for (const field of ["threadId", "controller", "clientDigest", "token", "controlVersion"]) if (Object.hasOwn(raw.arguments ?? {}, field))
20237
21046
  throw new CreationClientError("creation.transport_authority_managed_by_bridge");
20238
21047
  let binding = { host, arguments: raw.arguments, assertCurrent: async () => {
@@ -20252,7 +21061,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20252
21061
  raw = { ...raw, arguments: binding.arguments };
20253
21062
  await ensureDirectory();
20254
21063
  await binding.assertCurrent();
20255
- const definition = directory.tools.get(raw.name);
21064
+ const definition = directory2.tools.get(raw.name);
20256
21065
  if (!definition) throw new CreationClientError("creation.tool_unavailable");
20257
21066
  const access2 = definition._meta["promptframe.access"], managed = Object.hasOwn(definition.inputSchema.properties ?? {}, "controlVersion");
20258
21067
  let params = hostParameters(raw, binding.host, "independent-read");
@@ -20273,6 +21082,31 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20273
21082
  resolvedControl = observed.trusted?.control;
20274
21083
  }
20275
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
+ }
20276
21110
  const key = keyFor(params);
20277
21111
  let outgoing = params;
20278
21112
  if (managed) {
@@ -20312,7 +21146,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
20312
21146
  }
20313
21147
 
20314
21148
  // lib/runtime-bootstrap.mjs
20315
- import { createHash as createHash5, randomBytes as randomBytes3 } from "node:crypto";
21149
+ import { createHash as createHash7, randomBytes as randomBytes4 } from "node:crypto";
20316
21150
  import { gunzipSync } from "node:zlib";
20317
21151
 
20318
21152
  // node_modules/tar/dist/esm/index.min.js
@@ -23285,18 +24119,18 @@ var To = (s3) => {
23285
24119
  };
23286
24120
 
23287
24121
  // lib/runtime-bootstrap.mjs
23288
- 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";
23289
24123
  import { execFile } from "node:child_process";
23290
24124
  import { promisify } from "node:util";
23291
- import path5 from "node:path";
24125
+ import path8 from "node:path";
23292
24126
 
23293
24127
  // lib/runtime-package.mjs
23294
- import { lstat as lstat3, readdir, readFile as readFile3 } from "node:fs/promises";
23295
- import { createHash as createHash4 } from "node:crypto";
23296
- 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";
23297
24131
  var RUNTIME_PACKAGE_ENTRIES = Object.freeze(["package.json", "README.md", "LICENSE", "bin", "dist", "lib", "skills", "docs", ".codex-plugin", ".mcp.json"]);
23298
24132
  var OPTIONAL_HOST_ENTRIES = Object.freeze([".claude-plugin", ".claude-mcp.json"]);
23299
- var hash2 = (b2) => createHash4("sha256").update(b2).digest("hex");
24133
+ var hash2 = (b2) => createHash6("sha256").update(b2).digest("hex");
23300
24134
  var invalid = (code) => {
23301
24135
  throw new CreationClientError("installation." + code);
23302
24136
  };
@@ -23305,7 +24139,7 @@ async function inspectRuntimePackage(root, { entries } = {}) {
23305
24139
  entries = [...RUNTIME_PACKAGE_ENTRIES];
23306
24140
  for (const name of OPTIONAL_HOST_ENTRIES) {
23307
24141
  try {
23308
- await lstat3(path4.join(root, name));
24142
+ await lstat5(path7.join(root, name));
23309
24143
  entries.push(name);
23310
24144
  } catch (e) {
23311
24145
  if (e.code !== "ENOENT") throw e;
@@ -23317,19 +24151,19 @@ async function inspectRuntimePackage(root, { entries } = {}) {
23317
24151
  async function walk(relative) {
23318
24152
  let s3;
23319
24153
  try {
23320
- s3 = await lstat3(path4.join(root, relative));
24154
+ s3 = await lstat5(path7.join(root, relative));
23321
24155
  } catch (error4) {
23322
24156
  if (error4.code !== "ENOENT") throw error4;
23323
24157
  }
23324
24158
  if (!s3 || s3.isSymbolicLink()) invalid("package_file_invalid");
23325
24159
  if (s3.isDirectory()) {
23326
- for (const name of (await readdir(path4.join(root, relative))).sort()) {
24160
+ for (const name of (await readdir2(path7.join(root, relative))).sort()) {
23327
24161
  if (name === "node_modules" || name === "credentials.json" || name.startsWith(".env")) invalid("package_file_invalid");
23328
- await walk(path4.join(relative, name));
24162
+ await walk(path7.join(relative, name));
23329
24163
  }
23330
24164
  } else if (s3.isFile()) {
23331
24165
  if (s3.size > 32 * 1024 * 1024) invalid("package_too_large");
23332
- const body = await readFile3(path4.join(root, relative));
24166
+ const body = await readFile4(path7.join(root, relative));
23333
24167
  bytes2 += body.length;
23334
24168
  if (files.length >= 1024 || bytes2 > 32 * 1024 * 1024) invalid("package_too_large");
23335
24169
  files.push({ path: relative, bytes: body.length, sha256: hash2(body), body });
@@ -23346,7 +24180,7 @@ async function inspectRuntimePackage(root, { entries } = {}) {
23346
24180
  files,
23347
24181
  version: pkg.version,
23348
24182
  hosts: claude ? ["codex", "claude-code"] : ["codex"],
23349
- 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 }))))
23350
24184
  };
23351
24185
  }
23352
24186
 
@@ -23356,7 +24190,7 @@ var REGISTRY = "https://registry.npmjs.org";
23356
24190
  var MAX_ARCHIVE = 8 * 1024 * 1024;
23357
24191
  var MAX_PAYLOAD = 32 * 1024 * 1024;
23358
24192
  var MAX_TAR = 36 * 1024 * 1024;
23359
- var hash3 = (b2) => createHash5("sha256").update(b2).digest("hex");
24193
+ var hash3 = (b2) => createHash7("sha256").update(b2).digest("hex");
23360
24194
  var execute = promisify(execFile);
23361
24195
  var error3 = (code) => new CreationClientError("creation." + code);
23362
24196
  var version2 = (v2) => {
@@ -23381,29 +24215,29 @@ var snapshot = (payload) => ({
23381
24215
  version: payload.version,
23382
24216
  hosts: payload.hosts,
23383
24217
  payloadDigest: payload.payloadDigest,
23384
- 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 }))
23385
24219
  });
23386
24220
  async function info(file) {
23387
24221
  try {
23388
- return await lstat4(file);
24222
+ return await lstat6(file);
23389
24223
  } catch (e) {
23390
24224
  if (e.code === "ENOENT") return null;
23391
24225
  throw e;
23392
24226
  }
23393
24227
  }
23394
24228
  async function privateDirectory2(dir) {
23395
- await mkdir3(dir, { recursive: true, mode: 448 });
23396
- const s3 = await lstat4(dir);
24229
+ await mkdir4(dir, { recursive: true, mode: 448 });
24230
+ const s3 = await lstat6(dir);
23397
24231
  if (!s3.isDirectory() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63) throw error3("runtime_cache_owner_invalid");
23398
24232
  }
23399
24233
  async function privateJSON(file) {
23400
24234
  const s3 = await info(file);
23401
24235
  if (!s3) return null;
23402
24236
  if (!s3.isFile() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63 || s3.size > 512 * 1024) throw error3("runtime_cache_invalid");
23403
- return JSON.parse(await readFile4(file, "utf8"));
24237
+ return JSON.parse(await readFile5(file, "utf8"));
23404
24238
  }
23405
- async function syncDirectory(dir) {
23406
- const fd = await open3(dir, "r");
24239
+ async function syncDirectory2(dir) {
24240
+ const fd = await open5(dir, "r");
23407
24241
  try {
23408
24242
  await fd.sync();
23409
24243
  } finally {
@@ -23411,7 +24245,7 @@ async function syncDirectory(dir) {
23411
24245
  }
23412
24246
  }
23413
24247
  async function exclusiveJSON(file, value2) {
23414
- const fd = await open3(file, "wx", 384);
24248
+ const fd = await open5(file, "wx", 384);
23415
24249
  try {
23416
24250
  await fd.writeFile(JSON.stringify(value2) + "\n");
23417
24251
  await fd.sync();
@@ -23428,19 +24262,19 @@ function checkedRuntimeMetadata(value2, expectedVersion) {
23428
24262
  if (Buffer.from(encoded, "base64").toString("base64") !== encoded) throw error3("runtime_registry_identity_invalid");
23429
24263
  return { version: expectedVersion, integrity: value2.dist.integrity, tarball };
23430
24264
  }
23431
- async function boundedGet(url2, { fetchImpl = fetch, signal, maxBytes, timeoutMs }) {
24265
+ async function boundedGet(url2, { fetchImpl = fetch, signal, maxBytes: maxBytes2, timeoutMs }) {
23432
24266
  const controller = new AbortController(), abort = () => controller.abort(), timer = setTimeout(abort, timeoutMs);
23433
24267
  signal?.addEventListener("abort", abort, { once: true });
23434
24268
  if (signal?.aborted) abort();
23435
24269
  let response;
23436
24270
  try {
23437
24271
  response = await fetchImpl(url2, { signal: controller.signal, redirect: "error" });
23438
- 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");
23439
24273
  const chunks = [];
23440
24274
  let count = 0;
23441
24275
  for await (const chunk of response.body) {
23442
24276
  count += chunk.length;
23443
- if (count > maxBytes) throw error3("runtime_download_capacity");
24277
+ if (count > maxBytes2) throw error3("runtime_download_capacity");
23444
24278
  chunks.push(Buffer.from(chunk));
23445
24279
  }
23446
24280
  return Buffer.concat(chunks, count);
@@ -23455,7 +24289,7 @@ async function boundedGet(url2, { fetchImpl = fetch, signal, maxBytes, timeoutMs
23455
24289
  }
23456
24290
  }
23457
24291
  async function readRuntimeArchive(archive, metadata) {
23458
- 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");
23459
24293
  let raw;
23460
24294
  try {
23461
24295
  raw = gunzipSync(archive, { maxOutputLength: MAX_TAR });
@@ -23463,32 +24297,32 @@ async function readRuntimeArchive(archive, metadata) {
23463
24297
  throw error3("runtime_archive_invalid");
23464
24298
  }
23465
24299
  const files = [], names = /* @__PURE__ */ new Set();
23466
- let total = 0, entries = 0, failure2;
24300
+ let total = 0, entries = 0, failure3;
23467
24301
  const parser = Ct({ strict: true, onReadEntry: (entry) => {
23468
24302
  const name = entry.path;
23469
- 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");
23470
24304
  const relative = name.slice(8).replace(/\/$/, "");
23471
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])))
23472
- failure2 = error3("runtime_archive_invalid");
24306
+ failure3 = error3("runtime_archive_invalid");
23473
24307
  const portableName = relative.toLowerCase();
23474
- if (names.has(portableName)) failure2 = error3("runtime_archive_invalid");
24308
+ if (names.has(portableName)) failure3 = error3("runtime_archive_invalid");
23475
24309
  names.add(portableName);
23476
24310
  if (entry.type === "Directory") {
23477
- if (entry.size !== 0) failure2 = error3("runtime_archive_invalid");
24311
+ if (entry.size !== 0) failure3 = error3("runtime_archive_invalid");
23478
24312
  return;
23479
24313
  }
23480
24314
  total += entry.size;
23481
- 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");
23482
24316
  const chunks = [];
23483
24317
  let bytes2 = 0;
23484
24318
  entry.on("data", (chunk) => {
23485
24319
  bytes2 += chunk.length;
23486
- if (bytes2 > entry.size) failure2 = error3("runtime_archive_invalid");
23487
- 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));
23488
24322
  });
23489
24323
  entry.on("end", () => {
23490
- if (bytes2 !== entry.size) failure2 = error3("runtime_archive_invalid");
23491
- 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) });
23492
24326
  });
23493
24327
  } });
23494
24328
  await new Promise((resolve, reject) => {
@@ -23496,17 +24330,17 @@ async function readRuntimeArchive(archive, metadata) {
23496
24330
  parser.once("end", resolve);
23497
24331
  parser.end(raw);
23498
24332
  });
23499
- if (failure2) throw failure2;
24333
+ if (failure3) throw failure3;
23500
24334
  if (!files.length || files.length > 1024) throw error3("runtime_archive_invalid");
23501
24335
  return files;
23502
24336
  }
23503
24337
  async function cacheLock(root, signal) {
23504
- const name = path5.join(root, "prepare.lock"), end = Date.now() + 5e3;
24338
+ const name = path8.join(root, "prepare.lock"), end = Date.now() + 5e3;
23505
24339
  let fd;
23506
24340
  while (!fd) {
23507
24341
  signal?.throwIfAborted();
23508
24342
  try {
23509
- fd = await open3(name, "wx", 384);
24343
+ fd = await open5(name, "wx", 384);
23510
24344
  } catch (e) {
23511
24345
  if (e.code !== "EEXIST") throw e;
23512
24346
  if (Date.now() >= end) throw error3("runtime_cache_busy");
@@ -23517,7 +24351,7 @@ async function cacheLock(root, signal) {
23517
24351
  try {
23518
24352
  await fd.writeFile(JSON.stringify({ pid: process.pid, createdAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n");
23519
24353
  await fd.sync();
23520
- await syncDirectory(root);
24354
+ await syncDirectory2(root);
23521
24355
  } catch (e) {
23522
24356
  await fd.close();
23523
24357
  const now = await info(name);
@@ -23534,10 +24368,10 @@ async function cacheLock(root, signal) {
23534
24368
  async function verifyCached(target, metadata, hostKind) {
23535
24369
  if (!await info(target)) return null;
23536
24370
  await privateDirectory2(target);
23537
- const manifest = await privateJSON(path5.join(target, "runtime.json"));
24371
+ const manifest = await privateJSON(path8.join(target, "runtime.json"));
23538
24372
  if (!manifest || manifest.contractVersion !== "creation-verified-runtime/v1" || manifest.version !== metadata.version || manifest.integrity !== metadata.integrity)
23539
24373
  throw error3("runtime_cache_invalid");
23540
- const names = (await readdir2(target)).filter((name) => name !== "runtime.json").sort();
24374
+ const names = (await readdir3(target)).filter((name) => name !== "runtime.json").sort();
23541
24375
  if (names.some((name) => !roots.has(name)) || RUNTIME_PACKAGE_ENTRIES.some((name) => !names.includes(name))) throw error3("runtime_cache_invalid");
23542
24376
  const payload = await inspectRuntimePackage(target, { entries: names });
23543
24377
  if (!payload.hosts.includes(hostKind)) throw error3("runtime_host_unsupported");
@@ -23545,33 +24379,33 @@ async function verifyCached(target, metadata, hostKind) {
23545
24379
  return { version: payload.version, root: target, integrity: metadata.integrity, reused: true };
23546
24380
  }
23547
24381
  async function checkedVersionIndex(cacheRoot, metadata) {
23548
- const old = await privateJSON(path5.join(cacheRoot, "version-" + metadata.version + ".json"));
24382
+ const old = await privateJSON(path8.join(cacheRoot, "version-" + metadata.version + ".json"));
23549
24383
  if (old && JSON.stringify(old) !== JSON.stringify(metadata)) throw error3("runtime_registry_identity_conflict");
23550
24384
  return old;
23551
24385
  }
23552
24386
  async function prepareVerifiedRuntime(metadata, { cacheRoot, fetchImpl = fetch, signal, checkRuntime, hostKind = "codex" } = {}) {
23553
24387
  if (!["codex", "claude-code"].includes(hostKind)) throw error3("runtime_host_unsupported");
23554
- if (!path5.isAbsolute(cacheRoot ?? "")) throw error3("runtime_cache_owner_invalid");
24388
+ if (!path8.isAbsolute(cacheRoot ?? "")) throw error3("runtime_cache_owner_invalid");
23555
24389
  metadata = checkedRuntimeMetadata({ name: PACKAGE, version: metadata.version, dist: metadata }, metadata.version);
23556
24390
  await privateDirectory2(cacheRoot);
23557
24391
  await checkedVersionIndex(cacheRoot, metadata);
23558
- 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);
23559
24393
  if (existing) return existing;
23560
24394
  const archive = await boundedGet(metadata.tarball, { fetchImpl, signal, maxBytes: MAX_ARCHIVE, timeoutMs: 15e3 });
23561
24395
  const files = await readRuntimeArchive(archive, metadata), release = await cacheLock(cacheRoot, signal);
23562
- const temporary = path5.join(cacheRoot, ".partial-" + randomBytes3(12).toString("hex"));
24396
+ const temporary = path8.join(cacheRoot, ".partial-" + randomBytes4(12).toString("hex"));
23563
24397
  try {
23564
24398
  const index = await checkedVersionIndex(cacheRoot, metadata);
23565
24399
  const found = await verifyCached(target, metadata, hostKind);
23566
24400
  if (found) return found;
23567
24401
  const space = await statfs(cacheRoot, { bigint: true }), needed = BigInt(files.reduce((n, f2) => n + f2.body.length, 0) + 4 * 1024 * 1024);
23568
24402
  if (space.bavail * space.bsize < needed) throw error3("runtime_cache_capacity");
23569
- await mkdir3(temporary, { mode: 448 });
24403
+ await mkdir4(temporary, { mode: 448 });
23570
24404
  for (const file of files) {
23571
24405
  signal?.throwIfAborted();
23572
- const dest = path5.join(temporary, ...file.path.split("/"));
23573
- await mkdir3(path5.dirname(dest), { recursive: true, mode: 448 });
23574
- 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);
23575
24409
  try {
23576
24410
  await fd.writeFile(file.body);
23577
24411
  await fd.sync();
@@ -23590,28 +24424,28 @@ async function prepareVerifiedRuntime(metadata, { cacheRoot, fetchImpl = fetch,
23590
24424
  else {
23591
24425
  const result = await execute(
23592
24426
  process.execPath,
23593
- [path5.join(temporary, "bin/promptframe-creation.mjs"), "--version"],
24427
+ [path8.join(temporary, "bin/promptframe-creation.mjs"), "--version"],
23594
24428
  { timeout: 5e3, maxBuffer: 65536, windowsHide: true, signal, env: {
23595
24429
  ...process.env,
23596
- PROMPTFRAME_CREATION_CONFIG: path5.join(temporary, "no-credentials.json")
24430
+ PROMPTFRAME_CREATION_CONFIG: path8.join(temporary, "no-credentials.json")
23597
24431
  } }
23598
24432
  );
23599
24433
  if (result.stdout.trim() !== metadata.version || result.stderr.trim()) throw error3("runtime_package_version_invalid");
23600
24434
  }
23601
24435
  signal?.throwIfAborted();
23602
- await exclusiveJSON(path5.join(temporary, "runtime.json"), {
24436
+ await exclusiveJSON(path8.join(temporary, "runtime.json"), {
23603
24437
  contractVersion: "creation-verified-runtime/v1",
23604
24438
  version: metadata.version,
23605
24439
  integrity: metadata.integrity,
23606
24440
  payload: snapshot(payload)
23607
24441
  });
23608
- await syncDirectory(temporary);
24442
+ await syncDirectory2(temporary);
23609
24443
  if (!index) {
23610
- await exclusiveJSON(path5.join(cacheRoot, "version-" + metadata.version + ".json"), metadata);
23611
- await syncDirectory(cacheRoot);
24444
+ await exclusiveJSON(path8.join(cacheRoot, "version-" + metadata.version + ".json"), metadata);
24445
+ await syncDirectory2(cacheRoot);
23612
24446
  }
23613
- await rename3(temporary, target);
23614
- await syncDirectory(cacheRoot);
24447
+ await rename4(temporary, target);
24448
+ await syncDirectory2(cacheRoot);
23615
24449
  return { version: metadata.version, root: target, integrity: metadata.integrity, reused: false };
23616
24450
  } finally {
23617
24451
  try {
@@ -23649,7 +24483,7 @@ async function selectBridgeRuntime({ policy, currentVersion, lockedVersion, reso
23649
24483
  const raw = await boundedGet(REGISTRY + "/@promptframe%2fcreation/" + target, { fetchImpl, signal, maxBytes: 256 * 1024, timeoutMs: 5e3 });
23650
24484
  metadata = checkedRuntimeMetadata(JSON.parse(raw), target);
23651
24485
  } catch (e) {
23652
- const prior = await privateJSON(path5.join(cacheRoot, "version-" + target + ".json"));
24486
+ const prior = await privateJSON(path8.join(cacheRoot, "version-" + target + ".json"));
23653
24487
  if (!prior) throw e;
23654
24488
  metadata = checkedRuntimeMetadata({ name: PACKAGE, version: target, dist: prior }, target);
23655
24489
  metadataSource = "previously-verified-cache";
@@ -23675,16 +24509,16 @@ async function selectBridgeRuntime({ policy, currentVersion, lockedVersion, reso
23675
24509
 
23676
24510
  // lib/runtime-launch.mjs
23677
24511
  import { spawn } from "node:child_process";
23678
- import path6 from "node:path";
24512
+ import path9 from "node:path";
23679
24513
  async function launchSelectedBridge(selection, { host, configFile: configFile2, spawnImpl = spawn, env = process.env } = {}) {
23680
- 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))
23681
24515
  throw new CreationClientError("creation.runtime_launch_invalid");
23682
24516
  let child;
23683
24517
  try {
23684
24518
  child = spawnImpl(
23685
24519
  process.execPath,
23686
24520
  [
23687
- path6.join(selection.root, "bin/promptframe-creation.mjs"),
24521
+ path9.join(selection.root, "bin/promptframe-creation.mjs"),
23688
24522
  "bridge",
23689
24523
  "--config",
23690
24524
  configFile2,
@@ -23726,10 +24560,10 @@ async function launchSelectedBridge(selection, { host, configFile: configFile2,
23726
24560
  // lib/user-installation.mjs
23727
24561
  import { execFile as execFile2 } from "node:child_process";
23728
24562
  import { promisify as promisify2 } from "node:util";
23729
- import { createHash as createHash6, randomBytes as randomBytes4 } from "node:crypto";
23730
- 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";
23731
24565
  import { homedir as homedir4 } from "node:os";
23732
- import path7 from "node:path";
24566
+ import path10 from "node:path";
23733
24567
 
23734
24568
  // node_modules/smol-toml/dist/error.js
23735
24569
  function getLineColFromPtr(string4, ptr) {
@@ -24491,14 +25325,14 @@ var HAS_WELLFORMED = !!"".isWellFormed;
24491
25325
 
24492
25326
  // lib/user-installation.mjs
24493
25327
  var execute2 = promisify2(execFile2);
24494
- var hash4 = (b2) => createHash6("sha256").update(b2).digest("hex");
25328
+ var hash4 = (b2) => createHash8("sha256").update(b2).digest("hex");
24495
25329
  var InstallationError = class extends CreationClientError {
24496
25330
  constructor(code, details) {
24497
25331
  super("installation." + code);
24498
25332
  this.details = details;
24499
25333
  }
24500
25334
  };
24501
- var fail = (code, details) => {
25335
+ var fail4 = (code, details) => {
24502
25336
  throw new InstallationError(code, details);
24503
25337
  };
24504
25338
  var installationErrorDetails = (error4) => error4 instanceof InstallationError ? error4.details : void 0;
@@ -24522,16 +25356,16 @@ function pinnedGitSource(source) {
24522
25356
  const refKind = /^[a-f0-9]{40}$/i.test(ref) ? "commit" : /^(?:refs\/tags\/)?creation-v\d+\.\d+\.\d+$/.test(ref) ? "tag" : null;
24523
25357
  return refKind ? { refName: ref, refKind } : null;
24524
25358
  }
24525
- var json = async (file) => JSON.parse(await readFile5(file, "utf8"));
25359
+ var json = async (file) => JSON.parse(await readFile6(file, "utf8"));
24526
25360
  var pause2 = (ms2) => new Promise((r) => setTimeout(r, ms2));
24527
25361
  function validProfile(profile) {
24528
- 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");
24529
25363
  return profile;
24530
25364
  }
24531
25365
  function profileCredentialsPath(profile = "default", env = process.env) {
24532
25366
  validProfile(profile);
24533
- return profile === "default" ? credentialsPath(env) : path7.resolve(
24534
- 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"),
24535
25369
  "promptframe-creation",
24536
25370
  "profiles",
24537
25371
  profile,
@@ -24540,58 +25374,58 @@ function profileCredentialsPath(profile = "default", env = process.env) {
24540
25374
  }
24541
25375
  async function info2(file) {
24542
25376
  try {
24543
- return await lstat5(file);
25377
+ return await lstat7(file);
24544
25378
  } catch (e) {
24545
25379
  if (e.code === "ENOENT") return null;
24546
25380
  throw e;
24547
25381
  }
24548
25382
  }
24549
25383
  async function privateDirectory3(dir) {
24550
- await mkdir4(dir, { recursive: true, mode: 448 });
24551
- const s3 = await lstat5(dir);
24552
- 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");
24553
25387
  }
24554
25388
  async function privateRead2(file) {
24555
25389
  const s3 = await info2(file);
24556
25390
  if (!s3) return null;
24557
- 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");
24558
25392
  return json(file);
24559
25393
  }
24560
25394
  async function packageJSON(file) {
24561
25395
  const s3 = await info2(file);
24562
- 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");
24563
25397
  return json(file);
24564
25398
  }
24565
25399
  function sameTransport(actual, expected) {
24566
- 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;
24567
25401
  }
24568
25402
  async function managedTransport(installed, versions, serverName, profile, configFile2) {
24569
25403
  if (!installed) return null;
24570
25404
  const root = installed.source?.path;
24571
- 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");
24572
- const directory = await info2(root), definition = await info2(path7.join(root, ".mcp.json"));
24573
- if (!directory?.isDirectory() || directory.isSymbolicLink() || !definition?.isFile() || definition.isSymbolicLink()) fail("installed_files_invalid");
24574
- const ready = await privateRead2(path7.join(root, "installation.json"));
24575
- if (!ready || ready.profile !== profile || ready.configFile !== configFile2 || ready.version !== installed.version) fail("existing_registration_requires_review");
24576
- const bytes2 = await readFile5(path7.join(root, ".mcp.json")), entry = ready.files?.find((x) => x.path === ".mcp.json");
24577
- 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");
24578
25412
  const mcp = JSON.parse(bytes2).mcpServers?.[serverName];
24579
- 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");
24580
25414
  return mcp;
24581
25415
  }
24582
25416
  async function officialNpmInstallation(installed, servers, env, profile, configFile2) {
24583
25417
  if (profile !== "default" || configFile2 !== profileCredentialsPath("default", env)) return null;
24584
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));
24585
- if (candidates.length > 1) fail("existing_registration_requires_review");
25419
+ if (candidates.length > 1) fail4("existing_registration_requires_review");
24586
25420
  if (!candidates.length) return null;
24587
- const p2 = candidates[0], root = path7.join(path7.resolve(env.CODEX_HOME ?? path7.join(homedir4(), ".codex")), "plugins/cache", p2.marketplaceName, p2.name, p2.version);
24588
- const directory = await info2(root);
24589
- if (!directory?.isDirectory() || directory.isSymbolicLink()) fail("installed_files_invalid");
24590
- const pkg = await packageJSON(path7.join(root, "package.json")), manifest = await packageJSON(path7.join(root, ".codex-plugin/plugin.json"));
24591
- if (pkg.name !== "@promptframe/creation" || pkg.version !== p2.version || manifest.name !== p2.name || manifest.version !== p2.version) fail("installed_files_invalid");
24592
- const definition = (await packageJSON(path7.join(root, ".mcp.json"))).mcpServers?.promptframe;
24593
- 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");
24594
- 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");
24595
25429
  return {
24596
25430
  version: p2.version,
24597
25431
  profile,
@@ -24606,43 +25440,43 @@ async function officialNpmInstallation(installed, servers, env, profile, configF
24606
25440
  };
24607
25441
  }
24608
25442
  async function atomicJSON(file, value2) {
24609
- const temp = file + "." + randomBytes4(12).toString("hex") + ".tmp";
25443
+ const temp = file + "." + randomBytes5(12).toString("hex") + ".tmp";
24610
25444
  try {
24611
- const out = await open4(temp, "wx", 384);
25445
+ const out = await open6(temp, "wx", 384);
24612
25446
  try {
24613
25447
  await out.writeFile(JSON.stringify(value2, null, 2) + "\n");
24614
25448
  await out.sync();
24615
25449
  } finally {
24616
25450
  await out.close();
24617
25451
  }
24618
- await rename4(temp, file);
24619
- const directory = await open4(path7.dirname(file), "r");
25452
+ await rename5(temp, file);
25453
+ const directory2 = await open6(path10.dirname(file), "r");
24620
25454
  try {
24621
- await directory.sync();
25455
+ await directory2.sync();
24622
25456
  } finally {
24623
- await directory.close();
25457
+ await directory2.close();
24624
25458
  }
24625
25459
  } finally {
24626
25460
  await rm2(temp, { force: true });
24627
25461
  }
24628
25462
  }
24629
25463
  async function acquire(root, signal) {
24630
- const lock = path7.join(root, "install.lock");
25464
+ const lock = path10.join(root, "install.lock");
24631
25465
  const end = Date.now() + 3e4;
24632
25466
  let owned = false;
24633
25467
  while (!owned) {
24634
25468
  signal?.throwIfAborted();
24635
25469
  try {
24636
- await mkdir4(lock, { mode: 448 });
25470
+ await mkdir5(lock, { mode: 448 });
24637
25471
  owned = true;
24638
25472
  } catch (e) {
24639
25473
  if (e.code !== "EEXIST") throw e;
24640
- if (Date.now() >= end) fail("in_progress_or_interrupted_keep_existing");
25474
+ if (Date.now() >= end) fail4("in_progress_or_interrupted_keep_existing");
24641
25475
  await pause2(50);
24642
25476
  }
24643
25477
  }
24644
25478
  try {
24645
- 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 });
24646
25480
  } catch (e) {
24647
25481
  await rm2(lock, { recursive: true, force: true });
24648
25482
  throw e;
@@ -24661,7 +25495,7 @@ async function runCodexCommand(args2, { env = process.env } = {}) {
24661
25495
  return (await execute2("codex", args2, { env, encoding: "utf8", timeout: timeoutMs, maxBuffer: 2 * 1024 * 1024 })).stdout;
24662
25496
  } catch (e) {
24663
25497
  const cause = e.code === "ENOENT" ? "codex_required" : e.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" ? "command_output_limit" : e.killed ? "command_timeout" : "command_failed";
24664
- fail(cause, {
25498
+ fail4(cause, {
24665
25499
  phase: write ? "registration" : "local_check",
24666
25500
  commandKind: kind,
24667
25501
  elapsedMs: Math.round(performance.now() - start),
@@ -24679,16 +25513,16 @@ async function codexJSON(runCodex, args2) {
24679
25513
  if (typeof body !== "string" || Buffer.byteLength(body) > 2 * 1024 * 1024) throw Error();
24680
25514
  return JSON.parse(body);
24681
25515
  } catch {
24682
- 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" });
24683
25517
  }
24684
25518
  }
24685
25519
  async function relatedPlugins(runCodex, pluginName, env) {
24686
- 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");
24687
25521
  try {
24688
25522
  const s3 = await info2(config2);
24689
25523
  if (s3) {
24690
25524
  if (!s3.isFile() || s3.isSymbolicLink() || s3.size > 2 * 1024 * 1024) throw Error();
24691
- const plugins = parse3(await readFile5(config2, "utf8")).plugins ?? {};
25525
+ const plugins = parse3(await readFile6(config2, "utf8")).plugins ?? {};
24692
25526
  if (!plugins || typeof plugins !== "object" || Array.isArray(plugins) || Object.keys(plugins).length > 1024) throw Error();
24693
25527
  for (const id of Object.keys(plugins)) if (id.startsWith(pluginName + "@")) {
24694
25528
  const market = id.slice(pluginName.length + 1);
@@ -24698,19 +25532,19 @@ async function relatedPlugins(runCodex, pluginName, env) {
24698
25532
  }
24699
25533
  }
24700
25534
  } catch {
24701
- 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" });
24702
25536
  }
24703
25537
  const state = await codexJSON(runCodex, ["plugin", "marketplace", "list", "--json"]);
24704
- 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");
24705
25539
  for (const market of state.marketplaces) {
24706
- 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");
24707
25541
  let catalog;
24708
25542
  try {
24709
- catalog = await packageJSON(path7.join(market.root, ".agents/plugins/marketplace.json"));
25543
+ catalog = await packageJSON(path10.join(market.root, ".agents/plugins/marketplace.json"));
24710
25544
  } catch {
24711
- 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" });
24712
25546
  }
24713
- 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");
24714
25548
  if (catalog.plugins.some((p2) => p2?.name === pluginName)) related.add(market.name);
24715
25549
  const pinned = pinnedGitSource(market.marketplaceSource);
24716
25550
  if (pinned) pinnedMarketplaces.set(market.name, pinned);
@@ -24718,16 +25552,16 @@ async function relatedPlugins(runCodex, pluginName, env) {
24718
25552
  const installed = [];
24719
25553
  for (const market of related) {
24720
25554
  const list = await codexJSON(runCodex, ["plugin", "list", "--marketplace", market, "--json"]);
24721
- 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");
24722
25556
  for (const p2 of list.installed) {
24723
- 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");
24724
25558
  if (p2?.pluginId !== pluginName + "@" + market) continue;
24725
- 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");
24726
25560
  installed.push({ ...p2, ...pinnedMarketplaces.has(market) ? { pinnedMarketplace: pinnedMarketplaces.get(market) } : {} });
24727
25561
  }
24728
25562
  }
24729
- if (new Set(installed.map((p2) => p2.pluginId)).size !== installed.length) fail("local_registration_unconfirmed");
24730
- 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", {
24731
25565
  phase: "local_check",
24732
25566
  commandKind: "plugin_read",
24733
25567
  localRegistrationState: "unknown",
@@ -24737,11 +25571,11 @@ async function relatedPlugins(runCodex, pluginName, env) {
24737
25571
  }
24738
25572
  async function runNode(root, version3) {
24739
25573
  try {
24740
- const result = await execute2(process.execPath, [path7.join(root, "bin/promptframe-creation.mjs"), "--version"], { encoding: "utf8", timeout: 1e4, maxBuffer: 8192 });
24741
- 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");
24742
25576
  } catch (e) {
24743
25577
  if (e instanceof CreationClientError) throw e;
24744
- fail("runtime_check_failed");
25578
+ fail4("runtime_check_failed");
24745
25579
  }
24746
25580
  }
24747
25581
  async function checkInstalledRuntime(root, version3, command2, { env = process.env } = {}) {
@@ -24751,12 +25585,12 @@ async function checkInstalledRuntime(root, version3, command2, { env = process.e
24751
25585
  if (!major || Number(major[1]) < 20) throw Error("unsupported_node");
24752
25586
  const result = await execute2(
24753
25587
  command2,
24754
- [path7.join(root, "bin/promptframe-creation.mjs"), "--version"],
25588
+ [path10.join(root, "bin/promptframe-creation.mjs"), "--version"],
24755
25589
  { env, encoding: "utf8", timeout: 1e4, maxBuffer: 8192 }
24756
25590
  );
24757
25591
  if (result.stdout.trim() !== version3) throw Error("wrong_version");
24758
25592
  } catch {
24759
- fail("recorded_node_unavailable", {
25593
+ fail4("recorded_node_unavailable", {
24760
25594
  installedVersion: version3,
24761
25595
  action: "restore_recorded_node_or_connect_newer_version",
24762
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"
@@ -24787,44 +25621,44 @@ async function installForUser({
24787
25621
  validProfile(profile);
24788
25622
  const versionOutput = await runCodex(["--version"]);
24789
25623
  const match = versionOutput.match(/codex-cli (\d+)\.(\d+)\.(\d+)/);
24790
- if (!match || Number(match[1]) === 0 && Number(match[2]) < 160) fail("codex_0160_required");
24791
- const payload = await inspectRuntimePackage(path7.resolve(sourceRoot));
24792
- 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);
24793
25627
  await privateDirectory3(root);
24794
25628
  const release = await acquire(root, signal);
24795
- const versions = path7.join(root, "versions"), currentFile = path7.join(root, "current.json"), pendingFile = path7.join(root, "registration-pending.json");
24796
- 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");
24797
25631
  const pluginName = "promptframe-creation" + (profile === "default" ? "" : "-" + profile), marketplace = "promptframe-creation-user" + (profile === "default" ? "" : "-" + profile);
24798
25632
  const pluginId = pluginName + "@" + marketplace;
24799
- 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"));
24800
25634
  let previous, registrationStarted = false, newFiles = 0;
24801
25635
  try {
24802
25636
  signal?.throwIfAborted();
24803
25637
  await privateDirectory3(versions);
24804
- await privateDirectory3(path7.dirname(marketplaceFile));
25638
+ await privateDirectory3(path10.dirname(marketplaceFile));
24805
25639
  previous = await privateRead2(currentFile);
24806
- 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");
24807
25641
  const state = { installed: await relatedPlugins(runCodex, pluginName, env) };
24808
25642
  const installed = state.installed.find((x) => x.pluginId === pluginId);
24809
25643
  const legacy = await codexJSON(runCodex, ["mcp", "list", "--json"]);
24810
- if (!Array.isArray(legacy)) fail("local_registration_unconfirmed");
25644
+ if (!Array.isArray(legacy)) fail4("local_registration_unconfirmed");
24811
25645
  const serverName = "promptframe" + (profile === "default" ? "" : "-" + profile);
24812
25646
  const servers = legacy.filter((x) => x.name === serverName);
24813
25647
  const pending = await privateRead2(pendingFile);
24814
25648
  if (pending) {
24815
- 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");
24816
25650
  if (installed?.version !== pending.version || installed.enabled !== true || installed.source?.path !== pending.versionRoot)
24817
- 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" });
24818
25652
  const transport2 = await managedTransport(installed, versions, serverName, profile, configFile2);
24819
- if (servers.length !== 1 || servers[0].enabled === false || !sameTransport(servers[0].transport, transport2)) fail("registration_unconfirmed_keep_existing");
24820
- const ready = await privateRead2(path7.join(pending.versionRoot, "installation.json"));
24821
- 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");
24822
25656
  previous = pending;
24823
25657
  await atomicJSON(currentFile, pending);
24824
25658
  await rm2(pendingFile);
24825
25659
  }
24826
25660
  const pinned = state.installed.map((p2) => ({ plugin: p2, source: pinnedGitSource(p2.source) ?? p2.pinnedMarketplace })).find((p2) => p2.source);
24827
- if (pinned) fail("pinned_git_plugin_upgrade_required", {
25661
+ if (pinned) fail4("pinned_git_plugin_upgrade_required", {
24828
25662
  ...pinned.source,
24829
25663
  sourceType: "git",
24830
25664
  localRegistrationState: "present",
@@ -24833,10 +25667,10 @@ async function installForUser({
24833
25667
  });
24834
25668
  const official = await officialNpmInstallation(state.installed ?? [], servers, env, profile, configFile2);
24835
25669
  if (official) {
24836
- if (installed || previous) fail("existing_registration_requires_review");
25670
+ if (installed || previous) fail4("existing_registration_requires_review");
24837
25671
  const compared = compareVersions(official.version, payload.version);
24838
25672
  if (compared < 0) {
24839
- fail("npm_plugin_upgrade_required", {
25673
+ fail4("npm_plugin_upgrade_required", {
24840
25674
  installedVersion: official.version,
24841
25675
  requestedVersion: payload.version,
24842
25676
  pluginId: official.pluginId,
@@ -24851,11 +25685,11 @@ async function installForUser({
24851
25685
  if (legacy.some((x) => {
24852
25686
  if (x.name !== serverName) return false;
24853
25687
  return !recorded || !sameTransport(x.transport, recorded);
24854
- })) fail("legacy_mcp_entry_requires_review");
24855
- 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");
24856
25690
  if (installed && compareVersions(installed.version, payload.version) > 0) {
24857
25691
  if (!previous || previous.version !== installed.version || previous.versionRoot !== installed.source.path || installed.enabled !== true)
24858
- fail("existing_registration_requires_review");
25692
+ fail4("existing_registration_requires_review");
24859
25693
  await verifyInstalledRuntime(previous.versionRoot, previous.version, recorded.command, { env });
24860
25694
  return {
24861
25695
  ...previous,
@@ -24871,44 +25705,44 @@ async function installForUser({
24871
25705
  }
24872
25706
  const target = await info2(versionRoot);
24873
25707
  if (target) {
24874
- if (!target.isDirectory() || target.isSymbolicLink()) fail("version_content_conflict");
24875
- const ready = await privateRead2(path7.join(versionRoot, "installation.json"));
24876
- 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");
24877
25711
  for (const f2 of ready.files) {
24878
- if (!payload.files.some((p2) => p2.path === f2.path)) fail("installed_files_invalid");
24879
- const file = path7.join(versionRoot, f2.path), s3 = await info2(file);
24880
- 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");
24881
25715
  }
24882
- if (ready.files.length !== payload.files.length) fail("installed_files_invalid");
25716
+ if (ready.files.length !== payload.files.length) fail4("installed_files_invalid");
24883
25717
  } else {
24884
- await mkdir4(temporary, { mode: 448 });
25718
+ await mkdir5(temporary, { mode: 448 });
24885
25719
  for (const f2 of payload.files) {
24886
25720
  signal?.throwIfAborted();
24887
- await mkdir4(path7.dirname(path7.join(temporary, f2.path)), { recursive: true, mode: 448 });
24888
- 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 });
24889
25723
  }
24890
- const manifest = await json(path7.join(temporary, ".codex-plugin/plugin.json"));
25724
+ const manifest = await json(path10.join(temporary, ".codex-plugin/plugin.json"));
24891
25725
  manifest.name = pluginName;
24892
- 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");
24893
25727
  const mcp = { mcpServers: { ["promptframe" + (profile === "default" ? "" : "-" + profile)]: {
24894
25728
  command: process.execPath,
24895
- args: [path7.join(versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", configFile2],
25729
+ args: [path10.join(versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", configFile2],
24896
25730
  cwd: versionRoot
24897
25731
  } } };
24898
- 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");
24899
25733
  await checkRuntime(temporary, payload.version);
24900
25734
  const files = [];
24901
25735
  for (const f2 of payload.files) {
24902
- const body = await readFile5(path7.join(temporary, f2.path));
25736
+ const body = await readFile6(path10.join(temporary, f2.path));
24903
25737
  files.push({ path: f2.path, bytes: body.length, sha256: hash4(body) });
24904
25738
  }
24905
- 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 });
24906
25740
  signal?.throwIfAborted();
24907
- await rename4(temporary, versionRoot);
25741
+ await rename5(temporary, versionRoot);
24908
25742
  newFiles = payload.files.length;
24909
25743
  }
24910
25744
  if (newFiles === 0) {
24911
- const launch = (await json(path7.join(versionRoot, ".mcp.json"))).mcpServers?.[serverName];
25745
+ const launch = (await json(path10.join(versionRoot, ".mcp.json"))).mcpServers?.[serverName];
24912
25746
  await verifyInstalledRuntime(versionRoot, payload.version, launch.command, { env });
24913
25747
  }
24914
25748
  const complete = { version: payload.version, profile, configFile: configFile2, pluginId, versionRoot, payloadDigest: payload.payloadDigest };
@@ -24927,12 +25761,12 @@ async function installForUser({
24927
25761
  await runCodex(["plugin", "marketplace", "add", root, "--json"]);
24928
25762
  await runCodex(["plugin", "add", pluginId, "--json"]);
24929
25763
  const observed = (await relatedPlugins(runCodex, pluginName, env)).find((x) => x.pluginId === pluginId);
24930
- if (observed?.version !== payload.version || observed.enabled !== true) fail("registration_unconfirmed");
25764
+ if (observed?.version !== payload.version || observed.enabled !== true) fail4("registration_unconfirmed");
24931
25765
  const launch = await managedTransport(observed, versions, serverName, profile, configFile2);
24932
25766
  const hostMcp = await codexJSON(runCodex, ["mcp", "list", "--json"]);
24933
- if (!Array.isArray(hostMcp)) fail("registration_unconfirmed");
25767
+ if (!Array.isArray(hostMcp)) fail4("registration_unconfirmed");
24934
25768
  const effective = hostMcp.filter((x) => x.name === serverName);
24935
- 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");
24936
25770
  await atomicJSON(currentFile, complete);
24937
25771
  await rm2(pendingFile);
24938
25772
  }
@@ -24949,7 +25783,7 @@ async function installForUser({
24949
25783
  };
24950
25784
  } catch (error4) {
24951
25785
  if (registrationStarted) {
24952
- fail("registration_unconfirmed_keep_existing", {
25786
+ fail4("registration_unconfirmed_keep_existing", {
24953
25787
  ...installationErrorDetails(error4),
24954
25788
  phase: "registration_observation",
24955
25789
  localRegistrationState: "unknown",
@@ -24957,8 +25791,8 @@ async function installForUser({
24957
25791
  });
24958
25792
  }
24959
25793
  if (error4 instanceof CreationClientError) throw error4;
24960
- if (signal?.aborted) fail("interrupted_keep_existing");
24961
- fail("failed_keep_existing");
25794
+ if (signal?.aborted) fail4("interrupted_keep_existing");
25795
+ fail4("failed_keep_existing");
24962
25796
  } finally {
24963
25797
  await rm2(temporary, { recursive: true, force: true });
24964
25798
  await release();
@@ -24966,10 +25800,10 @@ async function installForUser({
24966
25800
  }
24967
25801
 
24968
25802
  // lib/claude-installation.mjs
24969
- import { createHash as createHash9, randomBytes as randomBytes6 } from "node:crypto";
24970
- 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";
24971
25805
  import { homedir as homedir9 } from "node:os";
24972
- import path12 from "node:path";
25806
+ import path15 from "node:path";
24973
25807
 
24974
25808
  // lib/claude-hook-definition.mjs
24975
25809
  function claudeHostHooks({ pluginName = "promptframe-creation", serverName, configFile: configFile2, nodeCommand = "node", runtimeRoot = "${CLAUDE_PLUGIN_ROOT}" } = {}) {
@@ -24992,10 +25826,10 @@ function claudeHostHooks({ pluginName = "promptframe-creation", serverName, conf
24992
25826
  // lib/claude-command.mjs
24993
25827
  import { execFile as execFile3 } from "node:child_process";
24994
25828
  import { promisify as promisify3 } from "node:util";
24995
- import { access, lstat as lstat6, readdir as readdir4 } from "node:fs/promises";
24996
- 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";
24997
25831
  import { homedir as homedir5 } from "node:os";
24998
- import path8 from "node:path";
25832
+ import path11 from "node:path";
24999
25833
  var execute3 = promisify3(execFile3);
25000
25834
  var ClaudeCommandError = class extends CreationClientError {
25001
25835
  constructor(code, details) {
@@ -25007,23 +25841,23 @@ var claudeErrorDetails = (error4) => error4 instanceof ClaudeCommandError ? erro
25007
25841
  async function resolveClaudeCommand({ env = process.env, homeDirectory = homedir5(), executable } = {}) {
25008
25842
  const selected = executable ?? env.PROMPTFRAME_CLAUDE_BIN;
25009
25843
  if (selected) {
25010
- if (!path8.isAbsolute(selected)) throw new CreationClientError("installation.claude_executable_invalid");
25011
- 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);
25012
25846
  return selected;
25013
25847
  }
25014
- for (const directory of (env.PATH ?? "").split(path8.delimiter).filter(path8.isAbsolute)) {
25015
- 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");
25016
25850
  try {
25017
- await access(file, constants2.X_OK);
25851
+ await access(file, constants4.X_OK);
25018
25852
  return file;
25019
25853
  } catch (e) {
25020
25854
  if (!["ENOENT", "EACCES", "ENOTDIR"].includes(e.code)) throw e;
25021
25855
  }
25022
25856
  }
25023
- const root = path8.join(homeDirectory, ".claude/remote/ccd-cli");
25857
+ const root = path11.join(homeDirectory, ".claude/remote/ccd-cli");
25024
25858
  let entries;
25025
25859
  try {
25026
- entries = await readdir4(root);
25860
+ entries = await readdir5(root);
25027
25861
  } catch (e) {
25028
25862
  if (e.code === "ENOENT") throw new CreationClientError("installation.claude_required");
25029
25863
  throw e;
@@ -25033,9 +25867,9 @@ async function resolveClaudeCommand({ env = process.env, homeDirectory = homedir
25033
25867
  for (const name of entries) {
25034
25868
  const match = name.match(/^(\d+)\.(\d+)\.(\d+)-[a-f0-9]{6,40}$/);
25035
25869
  if (!match) continue;
25036
- const file = path8.join(root, name), s3 = await lstat6(file);
25870
+ const file = path11.join(root, name), s3 = await lstat8(file);
25037
25871
  if (s3.isFile() && !s3.isSymbolicLink() && s3.uid === process.getuid?.()) {
25038
- await access(file, constants2.X_OK);
25872
+ await access(file, constants4.X_OK);
25039
25873
  candidates.push({ file, version: match.slice(1).map(Number) });
25040
25874
  }
25041
25875
  }
@@ -25071,17 +25905,17 @@ function createClaudeRunner({ env = process.env, executable, signal, resolve = r
25071
25905
  }
25072
25906
 
25073
25907
  // lib/claude-local-state.mjs
25074
- import { readFile as readFile6, lstat as lstat7 } from "node:fs/promises";
25908
+ import { readFile as readFile7, lstat as lstat9 } from "node:fs/promises";
25075
25909
  import { homedir as homedir6 } from "node:os";
25076
- import path9 from "node:path";
25910
+ import path12 from "node:path";
25077
25911
  function claudeConfigRoot(env = process.env) {
25078
- return path9.resolve(env.CLAUDE_CONFIG_DIR ?? path9.join(homedir6(), ".claude"));
25912
+ return path12.resolve(env.CLAUDE_CONFIG_DIR ?? path12.join(homedir6(), ".claude"));
25079
25913
  }
25080
25914
  async function readClaudeUserServer(serverName, env = process.env) {
25081
- 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");
25082
25916
  let info5;
25083
25917
  try {
25084
- info5 = await lstat7(file);
25918
+ info5 = await lstat9(file);
25085
25919
  } catch (e) {
25086
25920
  if (e.code === "ENOENT") return null;
25087
25921
  throw new CreationClientError("installation.claude_local_registration_unconfirmed");
@@ -25090,7 +25924,7 @@ async function readClaudeUserServer(serverName, env = process.env) {
25090
25924
  throw new CreationClientError("installation.claude_local_registration_unconfirmed");
25091
25925
  let state;
25092
25926
  try {
25093
- state = JSON.parse(await readFile6(file, "utf8"));
25927
+ state = JSON.parse(await readFile7(file, "utf8"));
25094
25928
  } catch {
25095
25929
  throw new CreationClientError("installation.claude_local_registration_unconfirmed");
25096
25930
  }
@@ -25101,30 +25935,30 @@ async function readClaudeUserServer(serverName, env = process.env) {
25101
25935
  }
25102
25936
 
25103
25937
  // lib/claude-mcp-installation.mjs
25104
- import { createHash as createHash8, randomBytes as randomBytes5 } from "node:crypto";
25105
- 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";
25106
25940
  import { homedir as homedir8 } from "node:os";
25107
- import path11 from "node:path";
25941
+ import path14 from "node:path";
25108
25942
 
25109
25943
  // lib/claude-hook-registration.mjs
25110
- import { createHash as createHash7 } from "node:crypto";
25111
- import { open as open5, rm as rm3 } from "node:fs/promises";
25112
- import { constants as constants3 } from "node:fs";
25113
- 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";
25114
25948
  import { homedir as homedir7 } from "node:os";
25115
25949
  var { privateDirectory: privateDirectory4, privateRead: privateRead3, atomicJSON: atomicJSON2, acquire: acquire2 } = installationFiles;
25116
- var digest3 = (value2) => createHash7("sha256").update(JSON.stringify(value2)).digest("hex");
25117
- var fail2 = () => {
25950
+ var digest4 = (value2) => createHash9("sha256").update(JSON.stringify(value2)).digest("hex");
25951
+ var fail5 = () => {
25118
25952
  throw new CreationClientError("installation.claude_hooks_require_review");
25119
25953
  };
25120
25954
  async function settings(file) {
25121
25955
  let handle;
25122
25956
  try {
25123
- handle = await open5(file, constants3.O_RDONLY | constants3.O_NOFOLLOW);
25957
+ handle = await open7(file, constants5.O_RDONLY | constants5.O_NOFOLLOW);
25124
25958
  const info5 = await handle.stat();
25125
- 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();
25126
25960
  const value2 = JSON.parse(await handle.readFile("utf8"));
25127
- 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();
25128
25962
  return value2;
25129
25963
  } catch (e) {
25130
25964
  if (e.code === "ENOENT") return {};
@@ -25133,49 +25967,49 @@ async function settings(file) {
25133
25967
  await handle?.close();
25134
25968
  }
25135
25969
  }
25136
- 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));
25137
25971
  async function verifyClaudeFallbackHooks(record2, env) {
25138
- if (!record2?.settingsFile || record2.settingsFile !== path10.join(claudeConfigRoot(env), "settings.json") || !record2.entries) fail2();
25139
- 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();
25140
25974
  return true;
25141
25975
  }
25142
25976
  async function registerClaudeFallbackHooks({ record: record2, root, env, nodeCommand, signal }) {
25143
- const directory = claudeConfigRoot(env), file = path10.join(directory, "settings.json");
25144
- const guard = path10.resolve(
25145
- 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"),
25146
25980
  "promptframe-creation",
25147
- "claude-hook-writer-" + digest3(directory)
25981
+ "claude-hook-writer-" + digest4(directory2)
25148
25982
  );
25149
25983
  await privateDirectory4(guard);
25150
25984
  const release = await acquire2(guard, signal);
25151
- 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");
25152
25986
  try {
25153
- await privateDirectory4(directory);
25987
+ await privateDirectory4(directory2);
25154
25988
  const entries = claudeHostHooks({ serverName: record2.serverName, configFile: record2.configFile, nodeCommand, runtimeRoot: record2.versionRoot });
25155
25989
  const expected = { contractVersion: "creation-claude-hooks/v1", settingsFile: file, profile: record2.profile, entries };
25156
25990
  const pending = await privateRead3(pendingFile), previous = await privateRead3(markerFile), before = await settings(file);
25157
25991
  if (pending) {
25158
- 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");
25159
25993
  await atomicJSON2(markerFile, expected);
25160
25994
  await rm3(pendingFile);
25161
25995
  return expected;
25162
25996
  }
25163
25997
  if (previous) {
25164
- 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();
25165
25999
  await verifyClaudeFallbackHooks(previous, env);
25166
- if (digest3(previous) === digest3(expected)) return previous;
26000
+ if (digest4(previous) === digest4(expected)) return previous;
25167
26001
  }
25168
26002
  const next = { ...before, hooks: { ...before.hooks } };
25169
26003
  for (const [event, wanted] of Object.entries(entries)) {
25170
26004
  const actual = next.hooks[event] ?? [];
25171
- if (!Array.isArray(actual)) fail2();
25172
- const owned = new Set((previous?.entries[event] ?? []).map(digest3));
25173
- if (wanted.some((entry) => actual.some((value2) => digest3(value2) === digest3(entry)) && !owned.has(digest3(entry)))) fail2();
25174
- 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];
25175
26009
  }
25176
26010
  signal?.throwIfAborted();
25177
26011
  await atomicJSON2(pendingFile, expected);
25178
- if (digest3(await settings(file)) !== digest3(before)) fail2();
26012
+ if (digest4(await settings(file)) !== digest4(before)) fail5();
25179
26013
  await atomicJSON2(file, next);
25180
26014
  if (!contains(await settings(file), entries)) throw new CreationClientError("installation.registration_unconfirmed_keep_existing");
25181
26015
  await atomicJSON2(markerFile, expected);
@@ -25188,7 +26022,7 @@ async function registerClaudeFallbackHooks({ record: record2, root, env, nodeCom
25188
26022
 
25189
26023
  // lib/claude-mcp-installation.mjs
25190
26024
  var { info: info3, privateDirectory: privateDirectory5, privateRead: privateRead4, atomicJSON: atomicJSON3, acquire: acquire3, compareVersions: compareVersions2 } = installationFiles;
25191
- var hash5 = (body) => createHash8("sha256").update(body).digest("hex");
26025
+ var hash5 = (body) => createHash10("sha256").update(body).digest("hex");
25192
26026
  var FallbackError = class extends CreationClientError {
25193
26027
  constructor(code, details) {
25194
26028
  super("installation." + code);
@@ -25196,14 +26030,14 @@ var FallbackError = class extends CreationClientError {
25196
26030
  }
25197
26031
  };
25198
26032
  var fallbackErrorDetails = (error4) => error4 instanceof FallbackError ? error4.details : void 0;
25199
- var fail3 = (code, details) => {
26033
+ var fail6 = (code, details) => {
25200
26034
  throw new FallbackError(code, details);
25201
26035
  };
25202
26036
  async function claimSkillDirectory(root) {
25203
26037
  try {
25204
- await mkdir5(root, { mode: 448 });
26038
+ await mkdir6(root, { mode: 448 });
25205
26039
  } catch (error4) {
25206
- if (error4.code === "EEXIST") fail3("claude_skill_requires_review");
26040
+ if (error4.code === "EEXIST") fail6("claude_skill_requires_review");
25207
26041
  throw error4;
25208
26042
  }
25209
26043
  }
@@ -25214,17 +26048,17 @@ function same(a, b2, depth = 0) {
25214
26048
  return left.length <= 256 && left.length === right.length && left.every((key, i) => key === right[i] && same(a[key], b2[key], depth + 1));
25215
26049
  }
25216
26050
  async function atomicText(file, body) {
25217
- const temporary = file + "." + randomBytes5(12).toString("hex") + ".tmp";
26051
+ const temporary = file + "." + randomBytes6(12).toString("hex") + ".tmp";
25218
26052
  try {
25219
- const fd = await open6(temporary, "wx", 384);
26053
+ const fd = await open8(temporary, "wx", 384);
25220
26054
  try {
25221
26055
  await fd.writeFile(body);
25222
26056
  await fd.sync();
25223
26057
  } finally {
25224
26058
  await fd.close();
25225
26059
  }
25226
- await rename5(temporary, file);
25227
- const dir = await open6(path11.dirname(file), "r");
26060
+ await rename6(temporary, file);
26061
+ const dir = await open8(path14.dirname(file), "r");
25228
26062
  try {
25229
26063
  await dir.sync();
25230
26064
  } finally {
@@ -25235,41 +26069,41 @@ async function atomicText(file, body) {
25235
26069
  }
25236
26070
  }
25237
26071
  async function verifyVersion(root, record2) {
25238
- const directory = await info3(root);
25239
- if (!directory?.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid?.() || directory.mode & 63) fail3("claude_installed_files_invalid");
25240
- const marker = await privateRead4(path11.join(root, "installation.json")), payload = await inspectRuntimePackage(root);
25241
- 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");
25242
26076
  return marker;
25243
26077
  }
25244
26078
  function mcpDefinition(record2, nodeCommand) {
25245
26079
  return {
25246
26080
  type: "stdio",
25247
26081
  command: nodeCommand,
25248
- 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"]
25249
26083
  };
25250
26084
  }
25251
26085
  function skillBody(payload, sourceName, name) {
25252
26086
  const file = payload.files.find((f2) => f2.path === "skills/" + sourceName + "/SKILL.md");
25253
- if (!file) fail3("package_incomplete");
26087
+ if (!file) fail6("package_incomplete");
25254
26088
  const body = file.body.toString("utf8");
25255
- 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");
25256
26090
  return body.replace("\nname: " + sourceName + "\n", "\nname: " + name + "\n");
25257
26091
  }
25258
26092
  async function observedSkill(plan, record2, { allowBefore = false } = {}) {
25259
- const directory = await info3(plan.root);
25260
- if (!directory) return false;
25261
- if (!directory.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid?.() || directory.mode & 63) fail3("claude_skill_requires_review");
25262
- const names = await readdir5(plan.root);
25263
- if (names.some((n) => !["SKILL.md", "promptframe-installation.json"].includes(n))) fail3("claude_skill_requires_review");
25264
- 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);
25265
26099
  if (!marker || marker.host !== "claude-code" || marker.profile !== record2.profile || marker.configFile !== record2.configFile || marker.name !== plan.name)
25266
- fail3("claude_skill_requires_review");
26100
+ fail6("claude_skill_requires_review");
25267
26101
  if (!s3 && allowBefore && plan.beforeSHA === null && marker.sha256 === null) return false;
25268
- if (!s3?.isFile() || s3.isSymbolicLink() || s3.size > 256 * 1024) fail3("claude_skill_requires_review");
25269
- const digest4 = hash5(await readFile7(file));
25270
- if (digest4 === plan.sha256 && marker.sha256 === plan.sha256) return true;
25271
- if (allowBefore && (digest4 === plan.beforeSHA || digest4 === plan.sha256) && marker.sha256 === plan.beforeSHA) return false;
25272
- 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");
25273
26107
  }
25274
26108
  async function installClaudeMcpFallback({
25275
26109
  sourceRoot,
@@ -25283,13 +26117,13 @@ async function installClaudeMcpFallback({
25283
26117
  nodeCommand,
25284
26118
  writeSkill = atomicText
25285
26119
  }) {
25286
- 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");
25287
26121
  await privateDirectory5(root);
25288
- 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"));
25289
26123
  let writeStarted = false, newFiles = 0;
25290
26124
  const complete = { host: "claude-code", mode: "mcp-and-skills", profile, configFile: configFile2, serverName, version: payload.version, versionRoot, payloadDigest: payload.payloadDigest };
25291
26125
  const checkBinding = (record2) => {
25292
- 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");
25293
26127
  };
25294
26128
  try {
25295
26129
  await privateDirectory5(versions);
@@ -25300,31 +26134,31 @@ async function installClaudeMcpFallback({
25300
26134
  complete.beforeServer = pending?.beforeServer ?? saved;
25301
26135
  const settled = async (record2) => {
25302
26136
  const ready2 = await verifyVersion(record2.versionRoot, record2);
25303
- 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");
25304
26138
  if (!same(saved, record2.server)) return false;
25305
26139
  if (compareVersions2(record2.version, "0.3.1") >= 0) await verifyClaudeFallbackHooks(record2.hostHooks, env);
25306
- 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");
25307
26141
  for (const [i, skill] of record2.skills.entries()) {
25308
26142
  const name = ["creation-setup", "video-creation"][i] + suffix;
25309
- if (skill.name !== name || skill.root !== path11.join(claudeConfigRoot(env), "skills", name) || !/^[a-f0-9]{64}$/.test(skill.sha256 ?? ""))
25310
- 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");
25311
26145
  if (!await observedSkill(skill, record2)) return false;
25312
26146
  }
25313
26147
  return true;
25314
26148
  };
25315
26149
  if (pending) {
25316
26150
  writeStarted = true;
25317
- 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");
25318
26152
  if (pending.phase === "mcp") {
25319
- if (!await settled(pending)) fail3("registration_unconfirmed_keep_existing");
26153
+ if (!await settled(pending)) fail6("registration_unconfirmed_keep_existing");
25320
26154
  await atomicJSON3(currentFile, pending);
25321
26155
  await rm4(pendingFile);
25322
26156
  previous = pending;
25323
26157
  pending = null;
25324
- } 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");
25325
26159
  }
25326
26160
  if (previous && !pending) {
25327
- if (!await settled(previous)) fail3("claude_local_registration_unconfirmed");
26161
+ if (!await settled(previous)) fail6("claude_local_registration_unconfirmed");
25328
26162
  if (compareVersions2(previous.version, payload.version) >= 0) {
25329
26163
  const ready2 = await verifyVersion(previous.versionRoot, previous);
25330
26164
  await verifyInstalledRuntime(previous.versionRoot, previous.version, ready2.nodeCommand, { env });
@@ -25343,15 +26177,15 @@ async function installClaudeMcpFallback({
25343
26177
  recordedRuntimeRetained: ready2.nodeCommand !== nodeCommand
25344
26178
  };
25345
26179
  }
25346
- } else if (saved && !pending) fail3("legacy_mcp_entry_requires_review");
26180
+ } else if (saved && !pending) fail6("legacy_mcp_entry_requires_review");
25347
26181
  if (await info3(versionRoot)) await verifyVersion(versionRoot, complete);
25348
26182
  else {
25349
- await mkdir5(temporary, { mode: 448 });
26183
+ await mkdir6(temporary, { mode: 448 });
25350
26184
  for (const file of payload.files) {
25351
26185
  signal?.throwIfAborted();
25352
- const dest = path11.join(temporary, file.path);
25353
- await mkdir5(path11.dirname(dest), { recursive: true, mode: 448 });
25354
- 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);
25355
26189
  try {
25356
26190
  await fd.writeFile(file.body);
25357
26191
  await fd.sync();
@@ -25360,33 +26194,33 @@ async function installClaudeMcpFallback({
25360
26194
  }
25361
26195
  }
25362
26196
  await checkRuntime(temporary, payload.version);
25363
- await atomicJSON3(path11.join(temporary, "installation.json"), { ...complete, nodeCommand });
26197
+ await atomicJSON3(path14.join(temporary, "installation.json"), { ...complete, nodeCommand });
25364
26198
  signal?.throwIfAborted();
25365
- await rename5(temporary, versionRoot);
26199
+ await rename6(temporary, versionRoot);
25366
26200
  newFiles = payload.files.length;
25367
26201
  }
25368
26202
  const ready = await verifyVersion(versionRoot, complete);
25369
26203
  complete.server = mcpDefinition(complete, ready.nodeCommand);
25370
26204
  if (newFiles === 0) await verifyInstalledRuntime(versionRoot, payload.version, ready.nodeCommand, { env });
25371
- const skillRoot = path11.join(claudeConfigRoot(env), "skills");
25372
- await mkdir5(skillRoot, { recursive: true, mode: 448 });
25373
- const parent = await lstat8(skillRoot);
25374
- 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");
25375
26209
  const plans = [];
25376
26210
  for (const sourceName of ["creation-setup", "video-creation"]) {
25377
- 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) };
25378
26212
  if (pending) {
25379
26213
  const old = pending.skills?.find((s3) => s3.name === name);
25380
- 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");
25381
26215
  plans.push({ ...old, body });
25382
26216
  } else {
25383
26217
  const existing = await info3(skill.root);
25384
26218
  let beforeSHA = null;
25385
26219
  if (existing) {
25386
- const marker = await privateRead4(path11.join(skill.root, "promptframe-installation.json"));
25387
- 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");
25388
26222
  const old = { ...skill, sha256: marker.sha256 };
25389
- if (!await observedSkill(old, complete)) fail3("claude_skill_requires_review");
26223
+ if (!await observedSkill(old, complete)) fail6("claude_skill_requires_review");
25390
26224
  beforeSHA = marker.sha256;
25391
26225
  }
25392
26226
  plans.push({ ...skill, beforeSHA, body });
@@ -25402,21 +26236,21 @@ async function installClaudeMcpFallback({
25402
26236
  if (await info3(plan.root)) {
25403
26237
  if (await observedSkill(plan, complete, { allowBefore: true })) continue;
25404
26238
  } else {
25405
- if (plan.beforeSHA !== null) fail3("claude_skill_requires_review");
26239
+ if (plan.beforeSHA !== null) fail6("claude_skill_requires_review");
25406
26240
  await claimSkillDirectory(plan.root);
25407
- 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 });
25408
26242
  }
25409
- await writeSkill(path11.join(plan.root, "SKILL.md"), plan.body);
25410
- 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 });
25411
26245
  }
25412
26246
  signal?.throwIfAborted();
25413
26247
  if (compareVersions2(payload.version, "0.3.1") >= 0) complete.hostHooks = await registerClaudeFallbackHooks({ record: complete, root, env, nodeCommand: ready.nodeCommand, signal });
25414
- 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");
25415
26249
  await atomicJSON3(pendingFile, { ...complete, phase: "mcp" });
25416
26250
  writeStarted = true;
25417
26251
  await runClaude(["mcp", "add-json", "--scope", "user", serverName, JSON.stringify(complete.server)]);
25418
26252
  saved = await readClaudeUserServer(serverName, env);
25419
- if (!await settled(complete)) fail3("registration_unconfirmed_keep_existing");
26253
+ if (!await settled(complete)) fail6("registration_unconfirmed_keep_existing");
25420
26254
  await atomicJSON3(currentFile, complete);
25421
26255
  await rm4(pendingFile);
25422
26256
  return {
@@ -25433,9 +26267,9 @@ async function installClaudeMcpFallback({
25433
26267
  versionStatus: "current"
25434
26268
  };
25435
26269
  } catch (error4) {
25436
- 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" });
25437
26271
  if (error4 instanceof CreationClientError) throw error4;
25438
- fail3(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
26272
+ fail6(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
25439
26273
  } finally {
25440
26274
  await rm4(temporary, { recursive: true, force: true });
25441
26275
  await release();
@@ -25453,7 +26287,7 @@ var ClaudeInstallationError = class extends CreationClientError {
25453
26287
  }
25454
26288
  };
25455
26289
  var claudeInstallationDetails = (error4) => error4 instanceof ClaudeInstallationError ? error4.details : void 0;
25456
- var fail4 = (code, details) => {
26290
+ var fail7 = (code, details) => {
25457
26291
  throw new ClaudeInstallationError(code, details);
25458
26292
  };
25459
26293
  async function jsonCommand(run, args2) {
@@ -25463,9 +26297,9 @@ async function jsonCommand(run, args2) {
25463
26297
  if (typeof body !== "string" || Buffer.byteLength(body) > 2 * 1024 * 1024) throw Error();
25464
26298
  value2 = JSON.parse(body);
25465
26299
  } catch {
25466
- fail4("claude_local_registration_unconfirmed");
26300
+ fail7("claude_local_registration_unconfirmed");
25467
26301
  }
25468
- 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");
25469
26303
  return value2;
25470
26304
  }
25471
26305
  async function registrations(run, pluginName, marketplace, root) {
@@ -25474,17 +26308,17 @@ async function registrations(run, pluginName, marketplace, root) {
25474
26308
  jsonCommand(run, ["plugin", "marketplace", "list", "--json"])
25475
26309
  ]);
25476
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"))
25477
- fail4("claude_local_registration_unconfirmed");
26311
+ fail7("claude_local_registration_unconfirmed");
25478
26312
  const related = plugins.filter((p2) => typeof p2?.id === "string" && p2.id.startsWith(pluginName + "@"));
25479
- 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 ?? ""))))
25480
- 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");
25481
26315
  const found = markets.filter((p2) => p2?.name === marketplace);
25482
26316
  if (found.length > 1 || found.some((p2) => p2.source !== "directory" || p2.path !== root || p2.installLocation !== root))
25483
- fail4("claude_existing_registration_requires_review");
26317
+ fail7("claude_existing_registration_requires_review");
25484
26318
  return { plugin: related[0], market: found[0] };
25485
26319
  }
25486
26320
  async function legacyUserMcp(env, serverName) {
25487
- if (await readClaudeUserServer(serverName, env)) fail4("legacy_mcp_entry_requires_review");
26321
+ if (await readClaudeUserServer(serverName, env)) fail7("legacy_mcp_entry_requires_review");
25488
26322
  }
25489
26323
  function transport(serverName, configFile2, command2 = process.execPath) {
25490
26324
  return { mcpServers: { [serverName]: {
@@ -25493,32 +26327,32 @@ function transport(serverName, configFile2, command2 = process.execPath) {
25493
26327
  } } };
25494
26328
  }
25495
26329
  async function verifyVersion2(root, { version: version3, profile, configFile: configFile2, payloadDigest, pluginName, serverName }) {
25496
- const directory = await info4(root);
25497
- if (!directory?.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid?.() || directory.mode & 63)
25498
- fail4("claude_installed_files_invalid");
25499
- const ready = await privateRead5(path12.join(root, "installation.json"));
25500
- 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");
25501
26335
  const actual = await inspectRuntimePackage(root);
25502
- if (actual.version !== version3 || JSON.stringify(actual.files.map(({ path: path14, bytes: bytes2, sha256 }) => ({ path: path14, bytes: bytes2, sha256 }))) !== JSON.stringify(ready.files))
25503
- fail4("claude_installed_files_invalid");
25504
- 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"));
25505
26339
  if (manifest.name !== pluginName || manifest.version !== version3 || manifest.skills !== "./skills/" || manifest.mcpServers !== "./.claude-mcp.json")
25506
- fail4("claude_installed_files_invalid");
26340
+ fail7("claude_installed_files_invalid");
25507
26341
  let runtimeCommand;
25508
26342
  for (const file of [".mcp.json", ".claude-mcp.json"]) {
25509
- const mcp = JSON.parse(await readFile8(path12.join(root, file), "utf8"));
26343
+ const mcp = JSON.parse(await readFile9(path15.join(root, file), "utf8"));
25510
26344
  const command2 = mcp.mcpServers?.[serverName]?.command;
25511
- 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");
25512
26346
  runtimeCommand = command2;
25513
26347
  }
25514
26348
  if (compareVersions3(version3, "0.3.1") >= 0 && JSON.stringify(manifest.hooks) !== JSON.stringify(claudeHostHooks({ pluginName, configFile: configFile2, nodeCommand: runtimeCommand })))
25515
- fail4("claude_installed_files_invalid");
26349
+ fail7("claude_installed_files_invalid");
25516
26350
  return { ...ready, runtimeCommand };
25517
26351
  }
25518
26352
  async function installForClaudeUser(options = {}) {
25519
26353
  const profile = options.profile ?? "default", env = options.env ?? process.env;
25520
26354
  validProfile2(profile);
25521
- 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");
25522
26356
  await privateDirectory6(modeRoot);
25523
26357
  const release = await acquire4(modeRoot, options.signal);
25524
26358
  try {
@@ -25540,37 +26374,37 @@ async function installClaudeUserLocked({
25540
26374
  nodeCommand = process.execPath
25541
26375
  } = {}) {
25542
26376
  validProfile2(profile);
25543
- if (!path12.isAbsolute(nodeCommand)) fail4("runtime_command_invalid");
26377
+ if (!path15.isAbsolute(nodeCommand)) fail7("runtime_command_invalid");
25544
26378
  const hostVersion = (await runClaude(["--version"])).trim().match(/^(\d+\.\d+\.\d+) \(Claude Code\)$/);
25545
- 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");
25546
26380
  const help = await runClaude(["--help"]);
25547
- 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");
25548
26382
  const hasPlugin = /^\s+plugin(?:\|plugins)?\s/m.test(help), hasMcp = /^\s+mcp\s/m.test(help);
25549
- 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");
25550
- 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"));
25551
- 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");
25552
26386
  if (!hasPlugin || fallbackState) {
25553
- if (!hasMcp) fail4("claude_capabilities_unconfirmed");
26387
+ if (!hasMcp) fail7("claude_capabilities_unconfirmed");
25554
26388
  return installClaudeMcpFallback({ sourceRoot, profile, env, configFile: configFile2, signal, runClaude, checkRuntime, verifyInstalledRuntime, nodeCommand });
25555
26389
  }
25556
- const payload = await inspectRuntimePackage(path12.resolve(sourceRoot));
26390
+ const payload = await inspectRuntimePackage(path15.resolve(sourceRoot));
25557
26391
  if (!payload.files.some((f2) => f2.path === ".claude-plugin/plugin.json") || !payload.files.some((f2) => f2.path === ".claude-mcp.json"))
25558
- fail4("claude_package_incomplete");
25559
- 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");
25560
26394
  await privateDirectory6(root);
25561
26395
  const release = await acquire4(root, signal);
25562
26396
  const suffix = profile === "default" ? "" : "-" + profile, pluginName = "promptframe-creation" + suffix, marketplace = "promptframe-creation-user" + suffix, pluginId = pluginName + "@" + marketplace, serverName = "promptframe" + suffix;
25563
- 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"));
25564
26398
  let registrationStarted = false, newFiles = 0;
25565
26399
  try {
25566
26400
  signal?.throwIfAborted();
25567
26401
  await privateDirectory6(versions);
25568
- await privateDirectory6(path12.dirname(catalogFile));
26402
+ await privateDirectory6(path15.dirname(catalogFile));
25569
26403
  await legacyUserMcp(env, serverName);
25570
26404
  let previous = await privateRead5(currentFile), pending = await privateRead5(pendingFile), state = await registrations(runClaude, pluginName, marketplace, root);
25571
26405
  const binding = { profile, configFile: configFile2, pluginId, pluginName, serverName, host: "claude-code" };
25572
26406
  const checkBinding = (record2) => {
25573
- 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");
25574
26408
  };
25575
26409
  checkBinding(previous);
25576
26410
  checkBinding(pending);
@@ -25588,10 +26422,10 @@ async function installClaudeUserLocked({
25588
26422
  previous = pending;
25589
26423
  pending = null;
25590
26424
  } else if (pending.phase !== "marketplace" || !state.market || state.plugin)
25591
- 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" });
25592
26426
  }
25593
- if (state.plugin && !previous && !pending) fail4("claude_existing_registration_requires_review");
25594
- 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");
25595
26429
  if (previous && compareVersions3(previous.version, payload.version) > 0) {
25596
26430
  const recorded = runtimeCommands.get(previous.versionRoot);
25597
26431
  await verifyInstalledRuntime(previous.versionRoot, previous.version, recorded, { env });
@@ -25609,17 +26443,17 @@ async function installClaudeUserLocked({
25609
26443
  }
25610
26444
  const complete = { ...binding, version: payload.version, versionRoot, payloadDigest: payload.payloadDigest };
25611
26445
  if (pending && (pending.version !== complete.version || pending.payloadDigest !== complete.payloadDigest))
25612
- fail4("registration_unconfirmed_keep_existing");
26446
+ fail7("registration_unconfirmed_keep_existing");
25613
26447
  if (await info4(versionRoot)) {
25614
26448
  const ready = await verifyVersion2(versionRoot, { ...complete, pluginName, serverName });
25615
26449
  runtimeCommands.set(versionRoot, ready.runtimeCommand);
25616
26450
  } else {
25617
- await mkdir6(temporary, { mode: 448 });
26451
+ await mkdir7(temporary, { mode: 448 });
25618
26452
  for (const file of payload.files) {
25619
26453
  signal?.throwIfAborted();
25620
- const dest = path12.join(temporary, file.path);
25621
- await mkdir6(path12.dirname(dest), { recursive: true, mode: 448 });
25622
- 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);
25623
26457
  try {
25624
26458
  await fd.writeFile(file.body);
25625
26459
  await fd.sync();
@@ -25627,21 +26461,21 @@ async function installClaudeUserLocked({
25627
26461
  await fd.close();
25628
26462
  }
25629
26463
  }
25630
- 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"));
25631
26465
  manifest.name = pluginName;
25632
26466
  if (manifest.hooks) manifest.hooks = claudeHostHooks({ pluginName, configFile: configFile2, nodeCommand });
25633
- await atomicJSON4(path12.join(temporary, ".claude-plugin/plugin.json"), manifest);
25634
- 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));
25635
26469
  await checkRuntime(temporary, payload.version);
25636
26470
  const installed = await inspectRuntimePackage(temporary);
25637
- await atomicJSON4(path12.join(temporary, "installation.json"), {
26471
+ await atomicJSON4(path15.join(temporary, "installation.json"), {
25638
26472
  ...binding,
25639
26473
  version: payload.version,
25640
26474
  payloadDigest: payload.payloadDigest,
25641
- 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 }))
25642
26476
  });
25643
26477
  signal?.throwIfAborted();
25644
- await rename6(temporary, versionRoot);
26478
+ await rename7(temporary, versionRoot);
25645
26479
  newFiles = payload.files.length;
25646
26480
  }
25647
26481
  if (newFiles === 0) await verifyInstalledRuntime(versionRoot, payload.version, runtimeCommands.get(versionRoot), { env });
@@ -25649,18 +26483,18 @@ async function installClaudeUserLocked({
25649
26483
  if (!already) {
25650
26484
  await atomicJSON4(catalogFile, { name: marketplace, owner: { name: "PromptFrame" }, plugins: [{ name: pluginName, source: "./versions/" + payload.version }] });
25651
26485
  if (!state.market) {
25652
- if (pending) fail4("registration_unconfirmed_keep_existing");
26486
+ if (pending) fail7("registration_unconfirmed_keep_existing");
25653
26487
  await atomicJSON4(pendingFile, { ...complete, phase: "marketplace" });
25654
26488
  registrationStarted = true;
25655
26489
  await runClaude(["plugin", "marketplace", "add", root, "--scope", "user", "--json"]);
25656
26490
  state = await registrations(runClaude, pluginName, marketplace, root);
25657
- if (!state.market) fail4("claude_registration_unconfirmed");
26491
+ if (!state.market) fail7("claude_registration_unconfirmed");
25658
26492
  }
25659
26493
  await atomicJSON4(pendingFile, { ...complete, phase: "plugin" });
25660
26494
  registrationStarted = true;
25661
26495
  await runClaude(["plugin", "install", pluginId, "--scope", "user", "--json"]);
25662
26496
  state = await registrations(runClaude, pluginName, marketplace, root);
25663
- if (!await observed(complete)) fail4("claude_registration_unconfirmed");
26497
+ if (!await observed(complete)) fail7("claude_registration_unconfirmed");
25664
26498
  await atomicJSON4(currentFile, complete);
25665
26499
  await rm5(pendingFile);
25666
26500
  }
@@ -25677,14 +26511,14 @@ async function installClaudeUserLocked({
25677
26511
  recordedRuntimeRetained: runtimeCommands.has(versionRoot) && runtimeCommands.get(versionRoot) !== nodeCommand
25678
26512
  };
25679
26513
  } catch (error4) {
25680
- if (registrationStarted) fail4("registration_unconfirmed_keep_existing", {
26514
+ if (registrationStarted) fail7("registration_unconfirmed_keep_existing", {
25681
26515
  ...claudeErrorDetails(error4),
25682
26516
  phase: "registration_observation",
25683
26517
  localRegistrationState: "unknown",
25684
26518
  action: "inspect_same_registration_no_second_add"
25685
26519
  });
25686
26520
  if (error4 instanceof CreationClientError) throw error4;
25687
- fail4(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
26521
+ fail7(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
25688
26522
  } finally {
25689
26523
  await rm5(temporary, { recursive: true, force: true });
25690
26524
  await release();
@@ -25693,7 +26527,7 @@ async function installClaudeUserLocked({
25693
26527
 
25694
26528
  // lib/cli.mjs
25695
26529
  import { fileURLToPath } from "node:url";
25696
- import path13 from "node:path";
26530
+ import path16 from "node:path";
25697
26531
  var args = process.argv.slice(2);
25698
26532
  var command = args.shift();
25699
26533
  var value = (key) => {
@@ -25701,7 +26535,7 @@ var value = (key) => {
25701
26535
  return i < 0 ? void 0 : args[i + 1];
25702
26536
  };
25703
26537
  var log = (value2) => process.stdout.write(JSON.stringify(value2) + "\n");
25704
- 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");
25705
26539
  async function probe(credentials) {
25706
26540
  const client = await connectPlatform(credentials, { host: resolveHostIdentity({ host: value("--host") }) });
25707
26541
  try {
@@ -25730,7 +26564,7 @@ async function tokenInput() {
25730
26564
  try {
25731
26565
  return await new Promise((resolve, reject) => {
25732
26566
  let text = "";
25733
- const read = (chunk) => {
26567
+ const read2 = (chunk) => {
25734
26568
  for (const byte of chunk) {
25735
26569
  if (byte === 3) {
25736
26570
  finish();
@@ -25752,10 +26586,10 @@ async function tokenInput() {
25752
26586
  }
25753
26587
  };
25754
26588
  const finish = () => {
25755
- input.removeListener("data", read);
26589
+ input.removeListener("data", read2);
25756
26590
  input.pause();
25757
26591
  };
25758
- input.on("data", read);
26592
+ input.on("data", read2);
25759
26593
  });
25760
26594
  } finally {
25761
26595
  input.setRawMode(Boolean(wasRaw));
@@ -25806,7 +26640,7 @@ async function setup({ silent = false } = {}) {
25806
26640
  version: 1,
25807
26641
  endpoint,
25808
26642
  token,
25809
- clientId: existing?.clientId ?? randomBytes7(24).toString("base64url"),
26643
+ clientId: existing?.clientId ?? randomBytes8(24).toString("base64url"),
25810
26644
  clientName: value("--name") ?? existing?.clientName ?? (resolveHostIdentity({ host: value("--host") }).kind === "claude-code" ? "Claude Code PromptFrame" : "Codex PromptFrame"),
25811
26645
  createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
25812
26646
  };
@@ -25841,7 +26675,7 @@ async function bridge() {
25841
26675
  resolvedVersion: value("--resolved-runtime-version"),
25842
26676
  signal: startup.signal,
25843
26677
  hostKind: identity.kind,
25844
- cacheRoot: path13.join(path13.dirname(configFile()), "runtime-cache")
26678
+ cacheRoot: path16.join(path16.dirname(configFile()), "runtime-cache")
25845
26679
  });
25846
26680
  startup.signal.throwIfAborted();
25847
26681
  } catch (error4) {
@@ -25875,11 +26709,15 @@ async function bridge() {
25875
26709
  credentials,
25876
26710
  host: identity,
25877
26711
  hostSession,
26712
+ localUploads: createLocalUploadManager({ stateRoot: path16.join(path16.dirname(configFile()), "local-upload-state") }),
25878
26713
  onCatalogChange: () => server.sendToolListChanged(),
25879
26714
  onKnowledgeChange: (kind) => kind === "resources" ? server.sendResourceListChanged() : server.sendPromptListChanged()
25880
26715
  });
25881
26716
  server.oninitialized = () => {
25882
- const declared = declaredHostContentCapabilities(server.getClientCapabilities());
26717
+ const declared = declaredHostContentCapabilities(
26718
+ server.getClientCapabilities(),
26719
+ { initialized: true, standardContent: !!policy?.standardContentTypes }
26720
+ );
25883
26721
  contentTypes = declared.types;
25884
26722
  contentSource = declared.source;
25885
26723
  };
@@ -25909,9 +26747,9 @@ async function bridge() {
25909
26747
  throw new Error("creation.connection_unresolved");
25910
26748
  }
25911
26749
  });
25912
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
26750
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
25913
26751
  try {
25914
- return await host.call(request.params);
26752
+ return await host.call(request.params, { signal: extra.signal });
25915
26753
  } catch (error4) {
25916
26754
  return {
25917
26755
  isError: true,
@@ -25933,6 +26771,7 @@ async function bridge() {
25933
26771
  const close = async () => {
25934
26772
  if (closing) return;
25935
26773
  closing = true;
26774
+ await host.close();
25936
26775
  await server.close().catch(() => {
25937
26776
  });
25938
26777
  await client.close().catch(() => {