@promptframe/creation 0.3.9 → 0.3.11

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, constants7) {
410
+ optimizeNames(names, constants8) {
411
411
  if (!names[this.name.str])
412
412
  return;
413
413
  if (this.rhs)
414
- this.rhs = optimizeExpr(this.rhs, names, constants7);
414
+ this.rhs = optimizeExpr(this.rhs, names, constants8);
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, constants7) {
431
+ optimizeNames(names, constants8) {
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, constants7);
434
+ this.rhs = optimizeExpr(this.rhs, names, constants8);
435
435
  return this;
436
436
  }
437
437
  get names() {
@@ -470,9 +470,9 @@ var require_codegen = __commonJS({
470
470
  }
471
471
  };
472
472
  var Throw = class extends Node {
473
- constructor(error4) {
473
+ constructor(error5) {
474
474
  super();
475
- this.error = error4;
475
+ this.error = error5;
476
476
  }
477
477
  render({ _n: _n2 }) {
478
478
  return `throw ${this.error};` + _n2;
@@ -492,8 +492,8 @@ var require_codegen = __commonJS({
492
492
  optimizeNodes() {
493
493
  return `${this.code}` ? this : void 0;
494
494
  }
495
- optimizeNames(names, constants7) {
496
- this.code = optimizeExpr(this.code, names, constants7);
495
+ optimizeNames(names, constants8) {
496
+ this.code = optimizeExpr(this.code, names, constants8);
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, constants7) {
525
+ optimizeNames(names, constants8) {
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, constants7))
530
+ if (n.optimizeNames(names, constants8))
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, constants7) {
583
+ optimizeNames(names, constants8) {
584
584
  var _a3;
585
- this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants7);
586
- if (!(super.optimizeNames(names, constants7) || this.else))
585
+ this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants8);
586
+ if (!(super.optimizeNames(names, constants8) || this.else))
587
587
  return;
588
- this.condition = optimizeExpr(this.condition, names, constants7);
588
+ this.condition = optimizeExpr(this.condition, names, constants8);
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, constants7) {
612
- if (!super.optimizeNames(names, constants7))
611
+ optimizeNames(names, constants8) {
612
+ if (!super.optimizeNames(names, constants8))
613
613
  return;
614
- this.iteration = optimizeExpr(this.iteration, names, constants7);
614
+ this.iteration = optimizeExpr(this.iteration, names, constants8);
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, constants7) {
651
- if (!super.optimizeNames(names, constants7))
650
+ optimizeNames(names, constants8) {
651
+ if (!super.optimizeNames(names, constants8))
652
652
  return;
653
- this.iterable = optimizeExpr(this.iterable, names, constants7);
653
+ this.iterable = optimizeExpr(this.iterable, names, constants8);
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, constants7) {
695
+ optimizeNames(names, constants8) {
696
696
  var _a3, _b;
697
- super.optimizeNames(names, constants7);
698
- (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants7);
699
- (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants7);
697
+ super.optimizeNames(names, constants8);
698
+ (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants8);
699
+ (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants8);
700
700
  return this;
701
701
  }
702
702
  get names() {
@@ -709,9 +709,9 @@ var require_codegen = __commonJS({
709
709
  }
710
710
  };
711
711
  var Catch = class extends BlockNode {
712
- constructor(error4) {
712
+ constructor(error5) {
713
713
  super();
714
- this.error = error4;
714
+ this.error = error5;
715
715
  }
716
716
  render(opts) {
717
717
  return `catch(${this.error})` + super.render(opts);
@@ -902,9 +902,9 @@ var require_codegen = __commonJS({
902
902
  this._blockNode(node2);
903
903
  this.code(tryBody);
904
904
  if (catchCode) {
905
- const error4 = this.name("e");
906
- this._currNode = node2.catch = new Catch(error4);
907
- catchCode(error4);
905
+ const error5 = this.name("e");
906
+ this._currNode = node2.catch = new Catch(error5);
907
+ catchCode(error5);
908
908
  }
909
909
  if (finallyCode) {
910
910
  this._currNode = node2.finally = new Finally();
@@ -913,8 +913,8 @@ var require_codegen = __commonJS({
913
913
  return this._endBlockNode(Catch, Finally);
914
914
  }
915
915
  // `throw` statement
916
- throw(error4) {
917
- return this._leafNode(new Throw(error4));
916
+ throw(error5) {
917
+ return this._leafNode(new Throw(error5));
918
918
  }
919
919
  // start self-balancing block
920
920
  block(body, nodeCount) {
@@ -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, constants7) {
1000
+ function optimizeExpr(expr, names, constants8) {
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 = constants7[n.str];
1015
+ const c = constants8[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 && constants7[c.str] !== void 0);
1022
+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants8[c.str] !== void 0);
1023
1023
  }
1024
1024
  }
1025
1025
  function subtractNames(names, from) {
@@ -1058,10 +1058,10 @@ var require_util = __commonJS({
1058
1058
  var codegen_1 = require_codegen();
1059
1059
  var code_1 = require_code();
1060
1060
  function toHash(arr) {
1061
- const hash6 = {};
1061
+ const hash7 = {};
1062
1062
  for (const item of arr)
1063
- hash6[item] = true;
1064
- return hash6;
1063
+ hash7[item] = true;
1064
+ return hash7;
1065
1065
  }
1066
1066
  exports.toHash = toHash;
1067
1067
  function alwaysValidSchema(it2, schema) {
@@ -1270,10 +1270,10 @@ var require_errors = __commonJS({
1270
1270
  exports.keyword$DataError = {
1271
1271
  message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)`
1272
1272
  };
1273
- function reportError(cxt, error4 = exports.keywordError, errorPaths, overrideAllErrors) {
1273
+ function reportError(cxt, error5 = exports.keywordError, errorPaths, overrideAllErrors) {
1274
1274
  const { it: it2 } = cxt;
1275
1275
  const { gen, compositeRule, allErrors } = it2;
1276
- const errObj = errorObjectCode(cxt, error4, errorPaths);
1276
+ const errObj = errorObjectCode(cxt, error5, errorPaths);
1277
1277
  if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
1278
1278
  addError(gen, errObj);
1279
1279
  } else {
@@ -1281,10 +1281,10 @@ var require_errors = __commonJS({
1281
1281
  }
1282
1282
  }
1283
1283
  exports.reportError = reportError;
1284
- function reportExtraError(cxt, error4 = exports.keywordError, errorPaths) {
1284
+ function reportExtraError(cxt, error5 = exports.keywordError, errorPaths) {
1285
1285
  const { it: it2 } = cxt;
1286
1286
  const { gen, compositeRule, allErrors } = it2;
1287
- const errObj = errorObjectCode(cxt, error4, errorPaths);
1287
+ const errObj = errorObjectCode(cxt, error5, errorPaths);
1288
1288
  addError(gen, errObj);
1289
1289
  if (!(compositeRule || allErrors)) {
1290
1290
  returnErrors(it2, names_1.default.vErrors);
@@ -1335,19 +1335,19 @@ var require_errors = __commonJS({
1335
1335
  schema: new codegen_1.Name("schema"),
1336
1336
  parentSchema: new codegen_1.Name("parentSchema")
1337
1337
  };
1338
- function errorObjectCode(cxt, error4, errorPaths) {
1338
+ function errorObjectCode(cxt, error5, errorPaths) {
1339
1339
  const { createErrors } = cxt.it;
1340
1340
  if (createErrors === false)
1341
1341
  return (0, codegen_1._)`{}`;
1342
- return errorObject(cxt, error4, errorPaths);
1342
+ return errorObject(cxt, error5, errorPaths);
1343
1343
  }
1344
- function errorObject(cxt, error4, errorPaths = {}) {
1344
+ function errorObject(cxt, error5, errorPaths = {}) {
1345
1345
  const { gen, it: it2 } = cxt;
1346
1346
  const keyValues = [
1347
1347
  errorInstancePath(it2, errorPaths),
1348
1348
  errorSchemaPath(cxt, errorPaths)
1349
1349
  ];
1350
- extraErrorProps(cxt, error4, keyValues);
1350
+ extraErrorProps(cxt, error5, keyValues);
1351
1351
  return gen.object(...keyValues);
1352
1352
  }
1353
1353
  function errorInstancePath({ errorPath }, { instancePath }) {
@@ -3259,8 +3259,8 @@ var require_utils = __commonJS({
3259
3259
  }
3260
3260
  return ind;
3261
3261
  }
3262
- function removeDotSegments(path18) {
3263
- let input = path18;
3262
+ function removeDotSegments(path20) {
3263
+ let input = path20;
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 path18 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
3673
- wsComponent.path = path18 && path18 !== "/" ? path18 : void 0;
3672
+ const path20 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
3673
+ wsComponent.path = path20 && path20 !== "/" ? path20 : void 0;
3674
3674
  wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
3675
3675
  wsComponent.resourceName = void 0;
3676
3676
  }
@@ -5012,7 +5012,7 @@ var require_limitNumber = __commonJS({
5012
5012
  exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
5013
5013
  exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
5014
5014
  };
5015
- var error4 = {
5015
+ var error5 = {
5016
5016
  message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,
5017
5017
  params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
5018
5018
  };
@@ -5021,7 +5021,7 @@ var require_limitNumber = __commonJS({
5021
5021
  type: "number",
5022
5022
  schemaType: "number",
5023
5023
  $data: true,
5024
- error: error4,
5024
+ error: error5,
5025
5025
  code(cxt) {
5026
5026
  const { keyword, data, schemaCode } = cxt;
5027
5027
  cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
@@ -5037,7 +5037,7 @@ var require_multipleOf = __commonJS({
5037
5037
  "use strict";
5038
5038
  Object.defineProperty(exports, "__esModule", { value: true });
5039
5039
  var codegen_1 = require_codegen();
5040
- var error4 = {
5040
+ var error5 = {
5041
5041
  message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`,
5042
5042
  params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`
5043
5043
  };
@@ -5046,7 +5046,7 @@ var require_multipleOf = __commonJS({
5046
5046
  type: "number",
5047
5047
  schemaType: "number",
5048
5048
  $data: true,
5049
- error: error4,
5049
+ error: error5,
5050
5050
  code(cxt) {
5051
5051
  const { gen, data, schemaCode, it: it2 } = cxt;
5052
5052
  const prec = it2.opts.multipleOfPrecision;
@@ -5093,7 +5093,7 @@ var require_limitLength = __commonJS({
5093
5093
  var codegen_1 = require_codegen();
5094
5094
  var util_1 = require_util();
5095
5095
  var ucs2length_1 = require_ucs2length();
5096
- var error4 = {
5096
+ var error5 = {
5097
5097
  message({ keyword, schemaCode }) {
5098
5098
  const comp = keyword === "maxLength" ? "more" : "fewer";
5099
5099
  return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;
@@ -5105,7 +5105,7 @@ var require_limitLength = __commonJS({
5105
5105
  type: "string",
5106
5106
  schemaType: "number",
5107
5107
  $data: true,
5108
- error: error4,
5108
+ error: error5,
5109
5109
  code(cxt) {
5110
5110
  const { keyword, data, schemaCode, it: it2 } = cxt;
5111
5111
  const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
@@ -5125,7 +5125,7 @@ var require_pattern = __commonJS({
5125
5125
  var code_1 = require_code2();
5126
5126
  var util_1 = require_util();
5127
5127
  var codegen_1 = require_codegen();
5128
- var error4 = {
5128
+ var error5 = {
5129
5129
  message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,
5130
5130
  params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`
5131
5131
  };
@@ -5134,7 +5134,7 @@ var require_pattern = __commonJS({
5134
5134
  type: "string",
5135
5135
  schemaType: "string",
5136
5136
  $data: true,
5137
- error: error4,
5137
+ error: error5,
5138
5138
  code(cxt) {
5139
5139
  const { gen, data, $data, schema, schemaCode, it: it2 } = cxt;
5140
5140
  const u2 = it2.opts.unicodeRegExp ? "u" : "";
@@ -5160,7 +5160,7 @@ var require_limitProperties = __commonJS({
5160
5160
  "use strict";
5161
5161
  Object.defineProperty(exports, "__esModule", { value: true });
5162
5162
  var codegen_1 = require_codegen();
5163
- var error4 = {
5163
+ var error5 = {
5164
5164
  message({ keyword, schemaCode }) {
5165
5165
  const comp = keyword === "maxProperties" ? "more" : "fewer";
5166
5166
  return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;
@@ -5172,7 +5172,7 @@ var require_limitProperties = __commonJS({
5172
5172
  type: "object",
5173
5173
  schemaType: "number",
5174
5174
  $data: true,
5175
- error: error4,
5175
+ error: error5,
5176
5176
  code(cxt) {
5177
5177
  const { keyword, data, schemaCode } = cxt;
5178
5178
  const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
@@ -5191,7 +5191,7 @@ var require_required = __commonJS({
5191
5191
  var code_1 = require_code2();
5192
5192
  var codegen_1 = require_codegen();
5193
5193
  var util_1 = require_util();
5194
- var error4 = {
5194
+ var error5 = {
5195
5195
  message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`,
5196
5196
  params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`
5197
5197
  };
@@ -5200,7 +5200,7 @@ var require_required = __commonJS({
5200
5200
  type: "object",
5201
5201
  schemaType: "array",
5202
5202
  $data: true,
5203
- error: error4,
5203
+ error: error5,
5204
5204
  code(cxt) {
5205
5205
  const { gen, schema, schemaCode, data, $data, it: it2 } = cxt;
5206
5206
  const { opts } = it2;
@@ -5271,7 +5271,7 @@ var require_limitItems = __commonJS({
5271
5271
  "use strict";
5272
5272
  Object.defineProperty(exports, "__esModule", { value: true });
5273
5273
  var codegen_1 = require_codegen();
5274
- var error4 = {
5274
+ var error5 = {
5275
5275
  message({ keyword, schemaCode }) {
5276
5276
  const comp = keyword === "maxItems" ? "more" : "fewer";
5277
5277
  return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;
@@ -5283,7 +5283,7 @@ var require_limitItems = __commonJS({
5283
5283
  type: "array",
5284
5284
  schemaType: "number",
5285
5285
  $data: true,
5286
- error: error4,
5286
+ error: error5,
5287
5287
  code(cxt) {
5288
5288
  const { keyword, data, schemaCode } = cxt;
5289
5289
  const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
@@ -5314,7 +5314,7 @@ var require_uniqueItems = __commonJS({
5314
5314
  var codegen_1 = require_codegen();
5315
5315
  var util_1 = require_util();
5316
5316
  var equal_1 = require_equal();
5317
- var error4 = {
5317
+ var error5 = {
5318
5318
  message: ({ params: { i, j: j2 } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j2} and ${i} are identical)`,
5319
5319
  params: ({ params: { i, j: j2 } }) => (0, codegen_1._)`{i: ${i}, j: ${j2}}`
5320
5320
  };
@@ -5323,7 +5323,7 @@ var require_uniqueItems = __commonJS({
5323
5323
  type: "array",
5324
5324
  schemaType: "boolean",
5325
5325
  $data: true,
5326
- error: error4,
5326
+ error: error5,
5327
5327
  code(cxt) {
5328
5328
  const { gen, data, $data, schema, parentSchema, schemaCode, it: it2 } = cxt;
5329
5329
  if (!$data && !schema)
@@ -5380,14 +5380,14 @@ var require_const = __commonJS({
5380
5380
  var codegen_1 = require_codegen();
5381
5381
  var util_1 = require_util();
5382
5382
  var equal_1 = require_equal();
5383
- var error4 = {
5383
+ var error5 = {
5384
5384
  message: "must be equal to constant",
5385
5385
  params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`
5386
5386
  };
5387
5387
  var def = {
5388
5388
  keyword: "const",
5389
5389
  $data: true,
5390
- error: error4,
5390
+ error: error5,
5391
5391
  code(cxt) {
5392
5392
  const { gen, data, $data, schemaCode, schema } = cxt;
5393
5393
  if ($data || schema && typeof schema == "object") {
@@ -5409,7 +5409,7 @@ var require_enum = __commonJS({
5409
5409
  var codegen_1 = require_codegen();
5410
5410
  var util_1 = require_util();
5411
5411
  var equal_1 = require_equal();
5412
- var error4 = {
5412
+ var error5 = {
5413
5413
  message: "must be equal to one of the allowed values",
5414
5414
  params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`
5415
5415
  };
@@ -5417,7 +5417,7 @@ var require_enum = __commonJS({
5417
5417
  keyword: "enum",
5418
5418
  schemaType: "array",
5419
5419
  $data: true,
5420
- error: error4,
5420
+ error: error5,
5421
5421
  code(cxt) {
5422
5422
  const { gen, data, $data, schema, schemaCode, it: it2 } = cxt;
5423
5423
  if (!$data && schema.length === 0)
@@ -5496,7 +5496,7 @@ var require_additionalItems = __commonJS({
5496
5496
  exports.validateAdditionalItems = void 0;
5497
5497
  var codegen_1 = require_codegen();
5498
5498
  var util_1 = require_util();
5499
- var error4 = {
5499
+ var error5 = {
5500
5500
  message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
5501
5501
  params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
5502
5502
  };
@@ -5505,7 +5505,7 @@ var require_additionalItems = __commonJS({
5505
5505
  type: "array",
5506
5506
  schemaType: ["boolean", "object"],
5507
5507
  before: "uniqueItems",
5508
- error: error4,
5508
+ error: error5,
5509
5509
  code(cxt) {
5510
5510
  const { parentSchema, it: it2 } = cxt;
5511
5511
  const { items } = parentSchema;
@@ -5624,7 +5624,7 @@ var require_items2020 = __commonJS({
5624
5624
  var util_1 = require_util();
5625
5625
  var code_1 = require_code2();
5626
5626
  var additionalItems_1 = require_additionalItems();
5627
- var error4 = {
5627
+ var error5 = {
5628
5628
  message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
5629
5629
  params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
5630
5630
  };
@@ -5633,7 +5633,7 @@ var require_items2020 = __commonJS({
5633
5633
  type: "array",
5634
5634
  schemaType: ["object", "boolean"],
5635
5635
  before: "uniqueItems",
5636
- error: error4,
5636
+ error: error5,
5637
5637
  code(cxt) {
5638
5638
  const { schema, parentSchema, it: it2 } = cxt;
5639
5639
  const { prefixItems } = parentSchema;
@@ -5657,7 +5657,7 @@ var require_contains = __commonJS({
5657
5657
  Object.defineProperty(exports, "__esModule", { value: true });
5658
5658
  var codegen_1 = require_codegen();
5659
5659
  var util_1 = require_util();
5660
- var error4 = {
5660
+ var error5 = {
5661
5661
  message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,
5662
5662
  params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}`
5663
5663
  };
@@ -5667,7 +5667,7 @@ var require_contains = __commonJS({
5667
5667
  schemaType: ["object", "boolean"],
5668
5668
  before: "uniqueItems",
5669
5669
  trackErrors: true,
5670
- error: error4,
5670
+ error: error5,
5671
5671
  code(cxt) {
5672
5672
  const { gen, schema, parentSchema, data, it: it2 } = cxt;
5673
5673
  let min;
@@ -5845,7 +5845,7 @@ var require_propertyNames = __commonJS({
5845
5845
  Object.defineProperty(exports, "__esModule", { value: true });
5846
5846
  var codegen_1 = require_codegen();
5847
5847
  var util_1 = require_util();
5848
- var error4 = {
5848
+ var error5 = {
5849
5849
  message: "property name must be valid",
5850
5850
  params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`
5851
5851
  };
@@ -5853,7 +5853,7 @@ var require_propertyNames = __commonJS({
5853
5853
  keyword: "propertyNames",
5854
5854
  type: "object",
5855
5855
  schemaType: ["object", "boolean"],
5856
- error: error4,
5856
+ error: error5,
5857
5857
  code(cxt) {
5858
5858
  const { gen, schema, data, it: it2 } = cxt;
5859
5859
  if ((0, util_1.alwaysValidSchema)(it2, schema))
@@ -5890,7 +5890,7 @@ var require_additionalProperties = __commonJS({
5890
5890
  var codegen_1 = require_codegen();
5891
5891
  var names_1 = require_names();
5892
5892
  var util_1 = require_util();
5893
- var error4 = {
5893
+ var error5 = {
5894
5894
  message: "must NOT have additional properties",
5895
5895
  params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`
5896
5896
  };
@@ -5900,7 +5900,7 @@ var require_additionalProperties = __commonJS({
5900
5900
  schemaType: ["boolean", "object"],
5901
5901
  allowUndefined: true,
5902
5902
  trackErrors: true,
5903
- error: error4,
5903
+ error: error5,
5904
5904
  code(cxt) {
5905
5905
  const { gen, schema, parentSchema, data, errsCount, it: it2 } = cxt;
5906
5906
  if (!errsCount)
@@ -6174,7 +6174,7 @@ var require_oneOf = __commonJS({
6174
6174
  Object.defineProperty(exports, "__esModule", { value: true });
6175
6175
  var codegen_1 = require_codegen();
6176
6176
  var util_1 = require_util();
6177
- var error4 = {
6177
+ var error5 = {
6178
6178
  message: "must match exactly one schema in oneOf",
6179
6179
  params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`
6180
6180
  };
@@ -6182,7 +6182,7 @@ var require_oneOf = __commonJS({
6182
6182
  keyword: "oneOf",
6183
6183
  schemaType: "array",
6184
6184
  trackErrors: true,
6185
- error: error4,
6185
+ error: error5,
6186
6186
  code(cxt) {
6187
6187
  const { gen, schema, parentSchema, it: it2 } = cxt;
6188
6188
  if (!Array.isArray(schema))
@@ -6259,7 +6259,7 @@ var require_if = __commonJS({
6259
6259
  Object.defineProperty(exports, "__esModule", { value: true });
6260
6260
  var codegen_1 = require_codegen();
6261
6261
  var util_1 = require_util();
6262
- var error4 = {
6262
+ var error5 = {
6263
6263
  message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`,
6264
6264
  params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`
6265
6265
  };
@@ -6267,7 +6267,7 @@ var require_if = __commonJS({
6267
6267
  keyword: "if",
6268
6268
  schemaType: ["object", "boolean"],
6269
6269
  trackErrors: true,
6270
- error: error4,
6270
+ error: error5,
6271
6271
  code(cxt) {
6272
6272
  const { gen, parentSchema, it: it2 } = cxt;
6273
6273
  if (parentSchema.then === void 0 && parentSchema.else === void 0) {
@@ -6393,7 +6393,7 @@ var require_format = __commonJS({
6393
6393
  "use strict";
6394
6394
  Object.defineProperty(exports, "__esModule", { value: true });
6395
6395
  var codegen_1 = require_codegen();
6396
- var error4 = {
6396
+ var error5 = {
6397
6397
  message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`,
6398
6398
  params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`
6399
6399
  };
@@ -6402,7 +6402,7 @@ var require_format = __commonJS({
6402
6402
  type: ["number", "string"],
6403
6403
  schemaType: "string",
6404
6404
  $data: true,
6405
- error: error4,
6405
+ error: error5,
6406
6406
  code(cxt, ruleType) {
6407
6407
  const { gen, data, $data, schema, schemaCode, it: it2 } = cxt;
6408
6408
  const { opts, errSchemaPath, schemaEnv, self } = it2;
@@ -6557,7 +6557,7 @@ var require_discriminator = __commonJS({
6557
6557
  var compile_1 = require_compile();
6558
6558
  var ref_error_1 = require_ref_error();
6559
6559
  var util_1 = require_util();
6560
- var error4 = {
6560
+ var error5 = {
6561
6561
  message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`,
6562
6562
  params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`
6563
6563
  };
@@ -6565,7 +6565,7 @@ var require_discriminator = __commonJS({
6565
6565
  keyword: "discriminator",
6566
6566
  type: "object",
6567
6567
  schemaType: "object",
6568
- error: error4,
6568
+ error: error5,
6569
6569
  code(cxt) {
6570
6570
  const { gen, data, schema, parentSchema, it: it2 } = cxt;
6571
6571
  const { oneOf } = parentSchema;
@@ -6890,7 +6890,7 @@ var require_formats = __commonJS({
6890
6890
  }
6891
6891
  exports.fullFormats = {
6892
6892
  // date: http://tools.ietf.org/html/rfc3339#section-5.6
6893
- date: fmtDef(date4, compareDate),
6893
+ date: fmtDef(date5, compareDate),
6894
6894
  // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
6895
6895
  time: fmtDef(getTime(true), compareTime),
6896
6896
  "date-time": fmtDef(getDateTime(true), compareDateTime),
@@ -6956,7 +6956,7 @@ var require_formats = __commonJS({
6956
6956
  }
6957
6957
  var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
6958
6958
  var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
6959
- function date4(str) {
6959
+ function date5(str) {
6960
6960
  const matches = DATE.exec(str);
6961
6961
  if (!matches)
6962
6962
  return false;
@@ -7025,7 +7025,7 @@ var require_formats = __commonJS({
7025
7025
  const time3 = getTime(strictTimeZone);
7026
7026
  return function date_time(str) {
7027
7027
  const dateTime = str.split(DATE_TIME_SEPARATOR);
7028
- return dateTime.length === 2 && date4(dateTime[0]) && time3(dateTime[1]);
7028
+ return dateTime.length === 2 && date5(dateTime[0]) && time3(dateTime[1]);
7029
7029
  };
7030
7030
  }
7031
7031
  function compareDateTime(dt1, dt2) {
@@ -7097,7 +7097,7 @@ var require_limit = __commonJS({
7097
7097
  formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
7098
7098
  formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
7099
7099
  };
7100
- var error4 = {
7100
+ var error5 = {
7101
7101
  message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,
7102
7102
  params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
7103
7103
  };
@@ -7106,7 +7106,7 @@ var require_limit = __commonJS({
7106
7106
  type: "string",
7107
7107
  schemaType: "string",
7108
7108
  $data: true,
7109
- error: error4,
7109
+ error: error5,
7110
7110
  code(cxt) {
7111
7111
  const { gen, data, schemaCode, keyword, it: it2 } = cxt;
7112
7112
  const { opts, self } = it2;
@@ -7347,15 +7347,15 @@ function normalizeEndpoint(input) {
7347
7347
  if (base.endsWith("/api")) return base + "/mcp";
7348
7348
  throw new CreationClientError("endpoint.api_base_required");
7349
7349
  }
7350
- var secure = async (file, directory2 = false) => {
7350
+ var secure = async (file, directory3 = false) => {
7351
7351
  let info5;
7352
7352
  try {
7353
7353
  info5 = await lstat(file);
7354
- } catch (error4) {
7355
- if (error4.code === "ENOENT") return null;
7356
- throw error4;
7354
+ } catch (error5) {
7355
+ if (error5.code === "ENOENT") return null;
7356
+ throw error5;
7357
7357
  }
7358
- if (info5.isSymbolicLink() || !(directory2 ? info5.isDirectory() : info5.isFile()) || info5.uid !== process.getuid?.() || (info5.mode & 63) !== 0)
7358
+ if (info5.isSymbolicLink() || !(directory3 ? info5.isDirectory() : info5.isFile()) || info5.uid !== process.getuid?.() || (info5.mode & 63) !== 0)
7359
7359
  throw new CreationClientError("credentials.private_owner_required");
7360
7360
  return info5;
7361
7361
  };
@@ -7374,9 +7374,9 @@ async function readCredentials(file = credentialsPath()) {
7374
7374
  return { ...value2, endpoint: normalizeEndpoint(value2.endpoint) };
7375
7375
  }
7376
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);
7377
+ const directory3 = path.dirname(file);
7378
+ await mkdir(directory3, { recursive: true, mode: 448 });
7379
+ await secure(directory3, true);
7380
7380
  await secure(file);
7381
7381
  const temporary = file + "." + randomBytes(12).toString("hex") + ".tmp";
7382
7382
  try {
@@ -7386,8 +7386,8 @@ async function writeCredentials(value2, file = credentialsPath()) {
7386
7386
  });
7387
7387
  await rename(temporary, file);
7388
7388
  } finally {
7389
- await unlink(temporary).catch((error4) => {
7390
- if (error4.code !== "ENOENT") throw error4;
7389
+ await unlink(temporary).catch((error5) => {
7390
+ if (error5.code !== "ENOENT") throw error5;
7391
7391
  });
7392
7392
  }
7393
7393
  }
@@ -7420,8 +7420,8 @@ async function openLocalUploadFile(selectedPath, { maxBytes: maxBytes2 = LOCAL_U
7420
7420
  let handle;
7421
7421
  try {
7422
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");
7423
+ } catch (error5) {
7424
+ throw failure(error5.code === "ELOOP" ? "file_not_regular" : error5.code === "EACCES" || error5.code === "EPERM" ? "file_read_denied" : "file_not_on_bridge_host");
7425
7425
  }
7426
7426
  const abort = new AbortController(), streams = /* @__PURE__ */ new Map(), reads = /* @__PURE__ */ new Set();
7427
7427
  let closing = false, closed = false, original, closePromise;
@@ -7446,8 +7446,8 @@ async function openLocalUploadFile(selectedPath, { maxBytes: maxBytes2 = LOCAL_U
7446
7446
  try {
7447
7447
  const [current, named] = await Promise.all([handle.stat({ bigint: true }), lstat2(selected, { bigint: true })]);
7448
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;
7449
+ } catch (error5) {
7450
+ if (error5 instanceof CreationClientError) throw error5;
7451
7451
  throw failure("file_changed");
7452
7452
  }
7453
7453
  };
@@ -7466,17 +7466,17 @@ async function openLocalUploadFile(selectedPath, { maxBytes: maxBytes2 = LOCAL_U
7466
7466
  if (stat3.size <= 0n || stat3.size > BigInt(maxBytes2)) throw failure("file_size_limit");
7467
7467
  original = fingerprint(stat3);
7468
7468
  await assertUnchanged();
7469
- const hash6 = createHash("sha256"), buffer = Buffer.allocUnsafe(LOCAL_UPLOAD_READ_BYTES);
7469
+ const hash7 = createHash("sha256"), buffer = Buffer.allocUnsafe(LOCAL_UPLOAD_READ_BYTES);
7470
7470
  for (let position = 0; position < original.sizeBytes; ) {
7471
7471
  checkSignal();
7472
7472
  const length = Math.min(buffer.length, original.sizeBytes - position);
7473
7473
  const { bytesRead } = await read2(buffer, 0, length, position);
7474
7474
  if (bytesRead === 0) throw failure("file_changed");
7475
- hash6.update(buffer.subarray(0, bytesRead));
7475
+ hash7.update(buffer.subarray(0, bytesRead));
7476
7476
  position += bytesRead;
7477
7477
  }
7478
7478
  await assertUnchanged();
7479
- const checksum = "sha256:" + hash6.digest("hex");
7479
+ const checksum = "sha256:" + hash7.digest("hex");
7480
7480
  return {
7481
7481
  name,
7482
7482
  sizeBytes: original.sizeBytes,
@@ -7509,9 +7509,9 @@ async function openLocalUploadFile(selectedPath, { maxBytes: maxBytes2 = LOCAL_U
7509
7509
  return stream;
7510
7510
  }
7511
7511
  };
7512
- } catch (error4) {
7512
+ } catch (error5) {
7513
7513
  await close();
7514
- if (error4 instanceof CreationClientError) throw error4;
7514
+ if (error5 instanceof CreationClientError) throw error5;
7515
7515
  throw failure("file_read_failed");
7516
7516
  }
7517
7517
  }
@@ -7519,12 +7519,56 @@ async function openLocalUploadFile(selectedPath, { maxBytes: maxBytes2 = LOCAL_U
7519
7519
  // lib/local-upload-transfer.mjs
7520
7520
  import { Readable as Readable2 } from "node:stream";
7521
7521
  import { finished as finished2 } from "node:stream/promises";
7522
+ import { performance as performance2 } from "node:perf_hooks";
7522
7523
  var fail = (code) => {
7523
7524
  throw new CreationClientError("creation.local_upload." + code);
7524
7525
  };
7525
7526
  var positive = (value2) => Number.isSafeInteger(value2) && value2 > 0;
7526
7527
  var forbiddenHeader = /^(?:authorization|cookie|host|connection|upgrade|proxy-.*)$/i;
7527
7528
  var defaultBudget = { totalMs: 3e5, firstProgressMs: 3e4, idleMs: 6e4 };
7529
+ var stages = /* @__PURE__ */ new Set(["validating", "checking_file", "opening_stream", "streaming", "awaiting_response", "finishing_stream", "reading_receipt"]);
7530
+ var causes = /* @__PURE__ */ new Set([
7531
+ "local_read_failed",
7532
+ "local_file_changed",
7533
+ "local_read_cancelled",
7534
+ "dns_failure",
7535
+ "connection_refused",
7536
+ "connection_interrupted",
7537
+ "network_timeout",
7538
+ "tls_rejected",
7539
+ "transport_unconfirmed",
7540
+ "http_rejected",
7541
+ "byte_count_mismatch",
7542
+ "etag_missing",
7543
+ "cancelled",
7544
+ "first_progress_timeout",
7545
+ "idle_timeout",
7546
+ "deadline_elapsed",
7547
+ "validation_refused",
7548
+ "stream_unconfirmed"
7549
+ ]);
7550
+ var localCause = (error5) => error5 instanceof CreationClientError ? {
7551
+ "creation.local_upload.file_read_failed": "local_read_failed",
7552
+ "creation.local_upload.file_changed": "local_file_changed",
7553
+ "creation.local_upload.file_read_cancelled": "local_read_cancelled"
7554
+ }[error5.message] : void 0;
7555
+ var networkCause = (error5) => {
7556
+ const code = typeof error5?.cause?.code === "string" ? error5.cause.code : error5?.code;
7557
+ if (["ENOTFOUND", "EAI_AGAIN"].includes(code)) return "dns_failure";
7558
+ if (code === "ECONNREFUSED") return "connection_refused";
7559
+ if (["ECONNRESET", "EPIPE", "UND_ERR_SOCKET"].includes(code)) return "connection_interrupted";
7560
+ if (["ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT"].includes(code)) return "network_timeout";
7561
+ if (["ERR_TLS_CERT_ALTNAME_INVALID", "CERT_HAS_EXPIRED", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "DEPTH_ZERO_SELF_SIGNED_CERT"].includes(code)) return "tls_rejected";
7562
+ return "transport_unconfirmed";
7563
+ };
7564
+ function safePartTransferDiagnostic(value2) {
7565
+ if (!value2 || !stages.has(value2.stage) || !causes.has(value2.causeCode)) return;
7566
+ const result = { stage: value2.stage, causeCode: value2.causeCode };
7567
+ for (const key of ["requestId", "uploadId", "assetId"]) if (typeof value2[key] === "string" && /^[A-Za-z0-9_.:-]{1,200}$/.test(value2[key])) result[key] = value2[key];
7568
+ for (const key of ["partNumber", "expectedBytes", "bytesRead", "elapsedMs"]) if (Number.isSafeInteger(value2[key]) && value2[key] >= 0) result[key] = value2[key];
7569
+ if (Number.isInteger(value2.httpStatus) && value2.httpStatus >= 100 && value2.httpStatus <= 599) result.httpStatus = value2.httpStatus;
7570
+ return Object.freeze(result);
7571
+ }
7528
7572
  async function transferGrantedPart(file, authorization, grant, {
7529
7573
  expectedUploadId,
7530
7574
  expectedAssetId,
@@ -7533,6 +7577,8 @@ async function transferGrantedPart(file, authorization, grant, {
7533
7577
  fetch: fetchPart = globalThis.fetch,
7534
7578
  now = Date.now,
7535
7579
  onProgress = () => {
7580
+ },
7581
+ onTransferState = () => {
7536
7582
  }
7537
7583
  } = {}) {
7538
7584
  const session = authorization?.session;
@@ -7553,6 +7599,14 @@ async function transferGrantedPart(file, authorization, grant, {
7553
7599
  fail("transfer_budget_invalid");
7554
7600
  const start = (grant.partNumber - 1) * session.partSizeBytes;
7555
7601
  const sizeBytes = Math.min(session.partSizeBytes, file.sizeBytes - start);
7602
+ const report = (stage, extra = {}) => onTransferState({
7603
+ stage,
7604
+ uploadId: session.uploadId,
7605
+ assetId: session.assetId,
7606
+ partNumber: grant.partNumber,
7607
+ expectedBytes: sizeBytes,
7608
+ ...extra
7609
+ });
7556
7610
  const headers = new Headers();
7557
7611
  if (!grant.requiredHeaders || typeof grant.requiredHeaders !== "object" || Array.isArray(grant.requiredHeaders) || Object.keys(grant.requiredHeaders).length > 64) fail("grant_invalid");
7558
7612
  for (const [name, value2] of Object.entries(grant.requiredHeaders)) {
@@ -7567,12 +7621,24 @@ async function transferGrantedPart(file, authorization, grant, {
7567
7621
  headers.set("content-length", String(sizeBytes));
7568
7622
  const deadline = Math.min(now() + budget.totalMs, ...expires, deadlineAtMs);
7569
7623
  if (!Number.isFinite(deadline) || deadline <= now()) fail("transfer_deadline_expired");
7570
- await file.assertUnchanged();
7624
+ report("checking_file", { bytesRead: 0 });
7625
+ try {
7626
+ await file.assertUnchanged();
7627
+ } catch (error5) {
7628
+ report("checking_file", { causeCode: localCause(error5) ?? "local_read_failed" });
7629
+ throw error5;
7630
+ }
7571
7631
  if (signal?.aborted) fail("transfer_cancelled");
7572
7632
  const controller = new AbortController();
7573
7633
  let reason, firstTimer, idleTimer, totalTimer, bytesRead = 0;
7574
7634
  const abort = (code) => {
7575
7635
  reason ??= code;
7636
+ onTransferState({ bytesRead, causeCode: {
7637
+ transfer_cancelled: "cancelled",
7638
+ transfer_first_progress_timeout: "first_progress_timeout",
7639
+ transfer_idle_timeout: "idle_timeout",
7640
+ transfer_timeout: "deadline_elapsed"
7641
+ }[reason] });
7576
7642
  controller.abort();
7577
7643
  };
7578
7644
  const cancel = () => abort("transfer_cancelled");
@@ -7585,19 +7651,30 @@ async function transferGrantedPart(file, authorization, grant, {
7585
7651
  };
7586
7652
  firstTimer = timer(() => abort("transfer_first_progress_timeout"), budget.firstProgressMs);
7587
7653
  totalTimer = timer(() => abort("transfer_timeout"), Math.max(1, deadline - now()));
7588
- let input, body, bodyDone, inputDone, response;
7654
+ let input, body, bodyDone, inputDone, response, closing = false, streamFailure = false;
7589
7655
  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;
7656
+ try {
7657
+ for await (const chunk of input) {
7658
+ if (controller.signal.aborted) fail(reason ?? "transfer_cancelled");
7659
+ clearTimeout(firstTimer);
7660
+ clearTimeout(idleTimer);
7661
+ idleTimer = timer(() => abort("transfer_idle_timeout"), budget.idleMs);
7662
+ bytesRead += chunk.length;
7663
+ report("streaming", { bytesRead });
7664
+ onProgress({ partNumber: grant.partNumber, bytesRead, sizeBytes });
7665
+ yield chunk;
7666
+ }
7667
+ report("awaiting_response", { bytesRead });
7668
+ } catch (error5) {
7669
+ if (!reason && !closing) {
7670
+ streamFailure = true;
7671
+ report("streaming", { bytesRead, causeCode: localCause(error5) ?? (["EIO", "EACCES", "EPERM", "ESTALE", "EBADF"].includes(error5?.code) ? "local_read_failed" : "stream_unconfirmed") });
7672
+ }
7673
+ throw error5;
7598
7674
  }
7599
7675
  }
7600
7676
  try {
7677
+ report("opening_stream", { bytesRead });
7601
7678
  input = file.streamPart({ start, sizeBytes, signal: controller.signal });
7602
7679
  body = Readable2.from(chunks(), { objectMode: false, highWaterMark: LOCAL_UPLOAD_READ_BYTES });
7603
7680
  bodyDone = finished2(body);
@@ -7607,19 +7684,41 @@ async function transferGrantedPart(file, authorization, grant, {
7607
7684
  inputDone.catch(() => {
7608
7685
  });
7609
7686
  response = await fetchPart(destination, { method: "PUT", headers, body, duplex: "half", redirect: "error", signal: controller.signal });
7610
- if (!response.ok) fail("part_target_rejected");
7687
+ report("finishing_stream", { bytesRead, httpStatus: response.status });
7688
+ if (!response.ok) {
7689
+ report("finishing_stream", { bytesRead, httpStatus: response.status, causeCode: "http_rejected" });
7690
+ fail("part_target_rejected");
7691
+ }
7611
7692
  await bodyDone;
7612
7693
  await inputDone;
7613
- if (bytesRead !== sizeBytes) fail("part_transfer_unconfirmed");
7614
- await file.assertUnchanged();
7694
+ if (bytesRead !== sizeBytes) {
7695
+ report("finishing_stream", { bytesRead, causeCode: "byte_count_mismatch" });
7696
+ fail("part_transfer_unconfirmed");
7697
+ }
7698
+ report("checking_file", { bytesRead });
7699
+ try {
7700
+ await file.assertUnchanged();
7701
+ } catch (error5) {
7702
+ report("checking_file", { bytesRead, causeCode: localCause(error5) ?? "local_read_failed" });
7703
+ throw error5;
7704
+ }
7705
+ report("reading_receipt", { bytesRead });
7615
7706
  const etag = response.headers.get("etag");
7616
- if (!etag || etag.length > 512 || /[\x00-\x1f\x7f]/.test(etag)) fail("part_receipt_unconfirmed");
7707
+ if (!etag || etag.length > 512 || /[\x00-\x1f\x7f]/.test(etag)) {
7708
+ report("reading_receipt", { bytesRead, causeCode: "etag_missing" });
7709
+ fail("part_receipt_unconfirmed");
7710
+ }
7617
7711
  return { partNumber: grant.partNumber, etag, sizeBytes };
7618
- } catch (error4) {
7712
+ } catch (error5) {
7619
7713
  if (reason) fail(reason);
7620
- if (error4 instanceof CreationClientError) throw error4;
7714
+ if (error5 instanceof CreationClientError) {
7715
+ if (localCause(error5)) onTransferState({ causeCode: localCause(error5) });
7716
+ throw error5;
7717
+ }
7718
+ if (!streamFailure) onTransferState({ causeCode: networkCause(error5) });
7621
7719
  fail("part_transfer_unconfirmed");
7622
7720
  } finally {
7721
+ closing = true;
7623
7722
  controller.abort();
7624
7723
  clearTimeout(firstTimer);
7625
7724
  clearTimeout(idleTimer);
@@ -7633,17 +7732,28 @@ async function transferGrantedPart(file, authorization, grant, {
7633
7732
  }
7634
7733
  }
7635
7734
  var effects = /* @__PURE__ */ new WeakMap();
7636
- var readPartTransferEffect = (error4) => error4 && typeof error4 === "object" ? effects.get(error4) : void 0;
7735
+ var diagnostics = /* @__PURE__ */ new WeakMap();
7736
+ var readPartTransferEffect = (error5) => error5 && typeof error5 === "object" ? effects.get(error5) : void 0;
7737
+ var readPartTransferDiagnostic = (error5) => error5 && typeof error5 === "object" ? diagnostics.get(error5) : void 0;
7637
7738
  async function uploadGrantedPart(file, authorization, grant, options = {}) {
7638
- let dispatched = false;
7739
+ let dispatched = false, state = { stage: "validating", bytesRead: 0 };
7740
+ const monotonic = options.monotonicNow ?? (() => performance2.now()), started = monotonic();
7639
7741
  try {
7640
- return await transferGrantedPart(file, authorization, grant, { ...options, fetch: async (...args2) => {
7742
+ return await transferGrantedPart(file, authorization, grant, { ...options, onTransferState: (value2) => {
7743
+ state = { ...state, ...value2 };
7744
+ }, fetch: async (...args2) => {
7641
7745
  dispatched = true;
7642
7746
  return (options.fetch ?? globalThis.fetch)(...args2);
7643
7747
  } });
7644
- } catch (error4) {
7645
- if (error4 && typeof error4 === "object") effects.set(error4, dispatched ? "unknown" : "not_dispatched");
7646
- throw error4;
7748
+ } catch (error5) {
7749
+ if (error5 && typeof error5 === "object") effects.set(error5, dispatched ? "unknown" : "not_dispatched");
7750
+ if (error5 && typeof error5 === "object") diagnostics.set(error5, safePartTransferDiagnostic({
7751
+ ...state,
7752
+ requestId: options.requestId,
7753
+ causeCode: state.causeCode ?? (!dispatched && state.stage === "validating" ? "validation_refused" : networkCause(error5)),
7754
+ elapsedMs: Math.max(0, Math.floor(monotonic() - started))
7755
+ }));
7756
+ throw error5;
7647
7757
  }
7648
7758
  }
7649
7759
 
@@ -7869,7 +7979,7 @@ var digest = (value2) => createHash2("sha256").update(JSON.stringify(value2)).di
7869
7979
  var fail3 = (code) => {
7870
7980
  throw new CreationClientError("creation.local_upload." + code);
7871
7981
  };
7872
- var knownError = (error4) => error4 instanceof CreationClientError && /^creation\.[a-z0-9_.:-]{1,180}$/.test(error4.message) ? error4.message : "creation.local_upload.control_unconfirmed";
7982
+ var knownError = (error5) => error5 instanceof CreationClientError && /^creation\.[a-z0-9_.:-]{1,180}$/.test(error5.message) ? error5.message : "creation.local_upload.control_unconfirmed";
7873
7983
  var createRefusal = (code) => /^creation\.direct_object_upload\.(?:size_limit_exceeded|pending_bytes_quota_exceeded|concurrent_multipart_quota_exceeded|daily_bytes_quota_exceeded|durable_storage_quota_exceeded|capacity_unavailable|admission_facts_unavailable)$/.test(code);
7874
7984
  var typeByExtension = {
7875
7985
  ".png": ["image", "image/png"],
@@ -7940,6 +8050,7 @@ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch,
7940
8050
  ...state.pendingPart ? { unconfirmedPart: state.pendingPart } : {},
7941
8051
  ...state.errorCode ? { errorCode: state.errorCode } : {},
7942
8052
  ...state.result ? { result: state.result } : {},
8053
+ ...safePartTransferDiagnostic(state.lastTransferDiagnostic) ? { lastTransferDiagnostic: safePartTransferDiagnostic(state.lastTransferDiagnostic) } : {},
7943
8054
  ...state.createObservation ? { creation: { outcome: state.createDisposition ?? "unconfirmed", ...state.createObservation } } : {},
7944
8055
  automaticReplayAllowed: false,
7945
8056
  next: job ? "Read status using this same key." : terminalNext[state.phase] ?? (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.")
@@ -8094,6 +8205,7 @@ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch,
8094
8205
  part = await uploadGrantedPart(file, envelope, grant, {
8095
8206
  expectedUploadId: state.uploadId,
8096
8207
  expectedAssetId: state.assetId,
8208
+ requestId: state.request.idempotencyKey,
8097
8209
  signal: abort.signal,
8098
8210
  deadlineAtMs: state.deadlineAtMs,
8099
8211
  fetch: fetch2,
@@ -8102,17 +8214,20 @@ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch,
8102
8214
  job.progress = progress.bytesRead;
8103
8215
  }
8104
8216
  });
8105
- } catch (error4) {
8106
- if (readPartTransferEffect(error4) === "not_dispatched") {
8217
+ } catch (error5) {
8218
+ const diagnostic = readPartTransferDiagnostic(error5);
8219
+ if (diagnostic) state.lastTransferDiagnostic = diagnostic;
8220
+ if (readPartTransferEffect(error5) === "not_dispatched") {
8107
8221
  delete state.pendingPart;
8108
8222
  await save();
8109
8223
  }
8110
- throw error4;
8224
+ throw error5;
8111
8225
  }
8112
8226
  state.parts.push(part);
8113
8227
  state.parts.sort((a, b2) => a.partNumber - b2.partNumber);
8114
8228
  job.progress = 0;
8115
8229
  delete state.pendingPart;
8230
+ delete state.lastTransferDiagnostic;
8116
8231
  await save();
8117
8232
  }
8118
8233
  await binding.assertCurrent();
@@ -8233,11 +8348,11 @@ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch,
8233
8348
  let created;
8234
8349
  try {
8235
8350
  created = await rpc(send, { action: "create", request: state.request });
8236
- } catch (error4) {
8237
- const code = knownError(error4);
8351
+ } catch (error5) {
8352
+ const code = knownError(error5);
8238
8353
  state.createDisposition = createRefusal(code) ? "rejected" : "unconfirmed";
8239
8354
  if (createRefusal(code)) state.createErrorCode = code;
8240
- throw error4;
8355
+ throw error5;
8241
8356
  }
8242
8357
  authorization = created.authorization;
8243
8358
  const session = authorization?.session;
@@ -8255,9 +8370,9 @@ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch,
8255
8370
  job = { state, file, abort, progress: 0, save: () => persistence.write(key, state) };
8256
8371
  jobs.set(key, job);
8257
8372
  file = void 0;
8258
- job.done = Promise.resolve().then(() => transfer(job, authorization, (transfer2, options) => send(transfer2, { signal: abort.signal, ...options }), binding)).catch(async (error4) => {
8373
+ job.done = Promise.resolve().then(() => transfer(job, authorization, (transfer2, options) => send(transfer2, { signal: abort.signal, ...options }), binding)).catch(async (error5) => {
8259
8374
  state.phase = "paused";
8260
- state.errorCode = abort.signal.aborted ? "creation.local_upload.transfer_cancelled" : knownError(error4);
8375
+ state.errorCode = abort.signal.aborted ? "creation.local_upload.transfer_cancelled" : knownError(error5);
8261
8376
  await job.save();
8262
8377
  }).finally(async () => {
8263
8378
  try {
@@ -8273,13 +8388,13 @@ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch,
8273
8388
  job.done.catch(() => {
8274
8389
  });
8275
8390
  return view(state, job);
8276
- } catch (error4) {
8391
+ } catch (error5) {
8277
8392
  if (state) {
8278
8393
  state.phase = state.createDisposition === "rejected" && !state.uploadId ? "create_rejected" : "paused";
8279
- state.errorCode = knownError(error4);
8394
+ state.errorCode = knownError(error5);
8280
8395
  await persistence.write(key, state);
8281
8396
  }
8282
- throw error4;
8397
+ throw error5;
8283
8398
  } finally {
8284
8399
  if (!jobs.has(key)) {
8285
8400
  await file?.close();
@@ -8314,7 +8429,7 @@ function createLocalUploadManager({ stateRoot, fetch: fetch2 = globalThis.fetch,
8314
8429
  }
8315
8430
 
8316
8431
  // lib/version.mjs
8317
- var CLIENT_VERSION = "0.3.9";
8432
+ var CLIENT_VERSION = "0.3.11";
8318
8433
  var CLIENT_PROTOCOL = "creation-client/v1";
8319
8434
 
8320
8435
  // lib/cli.mjs
@@ -8417,9 +8532,9 @@ function assertNever(_x) {
8417
8532
  }
8418
8533
  function assert(_2) {
8419
8534
  }
8420
- function getEnumValues(entries) {
8421
- const numericValues = Object.values(entries).filter((v2) => typeof v2 === "number");
8422
- const values = Object.entries(entries).filter(([k2, _2]) => numericValues.indexOf(+k2) === -1).map(([_2, v2]) => v2);
8535
+ function getEnumValues(entries2) {
8536
+ const numericValues = Object.values(entries2).filter((v2) => typeof v2 === "number");
8537
+ const values = Object.entries(entries2).filter(([k2, _2]) => numericValues.indexOf(+k2) === -1).map(([_2, v2]) => v2);
8423
8538
  return values;
8424
8539
  }
8425
8540
  function joinValues(array2, separator = "|") {
@@ -8558,10 +8673,10 @@ function mergeDefs(...defs) {
8558
8673
  function cloneDef(schema) {
8559
8674
  return mergeDefs(schema._zod.def);
8560
8675
  }
8561
- function getElementAtPath(obj, path18) {
8562
- if (!path18)
8676
+ function getElementAtPath(obj, path20) {
8677
+ if (!path20)
8563
8678
  return obj;
8564
- return path18.reduce((acc, key) => acc?.[key], obj);
8679
+ return path20.reduce((acc, key) => acc?.[key], obj);
8565
8680
  }
8566
8681
  function promiseAllObject(promisesObj) {
8567
8682
  const keys = Object.keys(promisesObj);
@@ -8901,11 +9016,11 @@ function explicitlyAborted(x, startIndex = 0) {
8901
9016
  }
8902
9017
  return false;
8903
9018
  }
8904
- function prefixIssues(path18, issues) {
9019
+ function prefixIssues(path20, issues) {
8905
9020
  return issues.map((iss) => {
8906
9021
  var _a3;
8907
9022
  (_a3 = iss).path ?? (_a3.path = []);
8908
- iss.path.unshift(path18);
9023
+ iss.path.unshift(path20);
8909
9024
  return iss;
8910
9025
  });
8911
9026
  }
@@ -9352,10 +9467,10 @@ function node(obj, key, make) {
9352
9467
  }
9353
9468
  return obj[key];
9354
9469
  }
9355
- function flattenError(error4, mapper = (issue2) => issue2.message) {
9470
+ function flattenError(error5, mapper = (issue2) => issue2.message) {
9356
9471
  const fieldErrors = {};
9357
9472
  const formErrors = [];
9358
- for (const sub of error4.issues) {
9473
+ for (const sub of error5.issues) {
9359
9474
  if (sub.path.length > 0) {
9360
9475
  node(fieldErrors, sub.path[0], () => []).push(mapper(sub));
9361
9476
  } else {
@@ -9364,18 +9479,18 @@ function flattenError(error4, mapper = (issue2) => issue2.message) {
9364
9479
  }
9365
9480
  return { formErrors, fieldErrors };
9366
9481
  }
9367
- function formatError(error4, mapper = (issue2) => issue2.message) {
9482
+ function formatError(error5, mapper = (issue2) => issue2.message) {
9368
9483
  const fieldErrors = { _errors: [] };
9369
- const processError = (error5, path18 = []) => {
9370
- for (const issue2 of error5.issues) {
9484
+ const processError = (error6, path20 = []) => {
9485
+ for (const issue2 of error6.issues) {
9371
9486
  if (issue2.code === "invalid_union" && issue2.errors.length) {
9372
- issue2.errors.map((issues) => processError({ issues }, [...path18, ...issue2.path]));
9487
+ issue2.errors.map((issues) => processError({ issues }, [...path20, ...issue2.path]));
9373
9488
  } else if (issue2.code === "invalid_key") {
9374
- processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
9489
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
9375
9490
  } else if (issue2.code === "invalid_element") {
9376
- processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
9491
+ processError({ issues: issue2.issues }, [...path20, ...issue2.path]);
9377
9492
  } else {
9378
- const fullpath = [...path18, ...issue2.path];
9493
+ const fullpath = [...path20, ...issue2.path];
9379
9494
  if (fullpath.length === 0) {
9380
9495
  fieldErrors._errors.push(mapper(issue2));
9381
9496
  } else {
@@ -9409,7 +9524,7 @@ function formatError(error4, mapper = (issue2) => issue2.message) {
9409
9524
  }
9410
9525
  }
9411
9526
  };
9412
- processError(error4);
9527
+ processError(error5);
9413
9528
  return fieldErrors;
9414
9529
  }
9415
9530
 
@@ -9458,19 +9573,19 @@ var _safeParse = (_Err) => (schema, value2, _ctx) => {
9458
9573
  };
9459
9574
  var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
9460
9575
  function failure2(Err, issues, ctx) {
9461
- let error4;
9576
+ let error5;
9462
9577
  return {
9463
9578
  success: false,
9464
9579
  get error() {
9465
- if (!error4) {
9466
- error4 = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config())));
9580
+ if (!error5) {
9581
+ error5 = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config())));
9467
9582
  issues = void 0;
9468
9583
  ctx = void 0;
9469
9584
  }
9470
- return error4;
9585
+ return error5;
9471
9586
  },
9472
9587
  set error(e) {
9473
- error4 = e;
9588
+ error5 = e;
9474
9589
  issues = void 0;
9475
9590
  ctx = void 0;
9476
9591
  }
@@ -14722,10 +14837,10 @@ var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
14722
14837
  };
14723
14838
  });
14724
14839
  function _enum(values, params) {
14725
- const entries = Array.isArray(values) ? Object.fromEntries(values.map((v2) => [v2, v2])) : values;
14840
+ const entries2 = Array.isArray(values) ? Object.fromEntries(values.map((v2) => [v2, v2])) : values;
14726
14841
  return new ZodEnum({
14727
14842
  type: "enum",
14728
- entries,
14843
+ entries: entries2,
14729
14844
  ...util_exports.normalizeParams(params)
14730
14845
  });
14731
14846
  }
@@ -16611,8 +16726,8 @@ var Protocol = class {
16611
16726
  resolver(message);
16612
16727
  } else {
16613
16728
  const errorMessage = message;
16614
- const error4 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
16615
- resolver(error4);
16729
+ const error5 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
16730
+ resolver(error5);
16616
16731
  }
16617
16732
  } else {
16618
16733
  const messageType = queuedMessage.type === "response" ? "Response" : "Error";
@@ -16656,8 +16771,8 @@ var Protocol = class {
16656
16771
  nextCursor,
16657
16772
  _meta: {}
16658
16773
  };
16659
- } catch (error4) {
16660
- throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error4 instanceof Error ? error4.message : String(error4)}`);
16774
+ } catch (error5) {
16775
+ throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error5 instanceof Error ? error5.message : String(error5)}`);
16661
16776
  }
16662
16777
  });
16663
16778
  this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {
@@ -16679,11 +16794,11 @@ var Protocol = class {
16679
16794
  _meta: {},
16680
16795
  ...cancelledTask
16681
16796
  };
16682
- } catch (error4) {
16683
- if (error4 instanceof McpError) {
16684
- throw error4;
16797
+ } catch (error5) {
16798
+ if (error5 instanceof McpError) {
16799
+ throw error5;
16685
16800
  }
16686
- throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error4 instanceof Error ? error4.message : String(error4)}`);
16801
+ throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error5 instanceof Error ? error5.message : String(error5)}`);
16687
16802
  }
16688
16803
  });
16689
16804
  }
@@ -16744,9 +16859,9 @@ var Protocol = class {
16744
16859
  this._onclose();
16745
16860
  };
16746
16861
  const _onerror = this.transport?.onerror;
16747
- this._transport.onerror = (error4) => {
16748
- _onerror?.(error4);
16749
- this._onerror(error4);
16862
+ this._transport.onerror = (error5) => {
16863
+ _onerror?.(error5);
16864
+ this._onerror(error5);
16750
16865
  };
16751
16866
  const _onmessage = this._transport?.onmessage;
16752
16867
  this._transport.onmessage = (message, extra) => {
@@ -16777,22 +16892,22 @@ var Protocol = class {
16777
16892
  controller.abort();
16778
16893
  }
16779
16894
  this._requestHandlerAbortControllers.clear();
16780
- const error4 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
16895
+ const error5 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
16781
16896
  this._transport = void 0;
16782
16897
  this.onclose?.();
16783
16898
  for (const handler of responseHandlers.values()) {
16784
- handler(error4);
16899
+ handler(error5);
16785
16900
  }
16786
16901
  }
16787
- _onerror(error4) {
16788
- this.onerror?.(error4);
16902
+ _onerror(error5) {
16903
+ this.onerror?.(error5);
16789
16904
  }
16790
16905
  _onnotification(notification) {
16791
16906
  const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
16792
16907
  if (handler === void 0) {
16793
16908
  return;
16794
16909
  }
16795
- Promise.resolve().then(() => handler(notification)).catch((error4) => this._onerror(new Error(`Uncaught error in notification handler: ${error4}`)));
16910
+ Promise.resolve().then(() => handler(notification)).catch((error5) => this._onerror(new Error(`Uncaught error in notification handler: ${error5}`)));
16796
16911
  }
16797
16912
  _onrequest(request, extra) {
16798
16913
  const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
@@ -16822,15 +16937,15 @@ var Protocol = class {
16822
16937
  };
16823
16938
  if (relatedTaskId && relatedTaskLookup) {
16824
16939
  const queuedError = { type: "error", message: errorResponse, timestamp: Date.now() };
16825
- relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error4) => this._onerror(new Error(`Failed to send an error response: ${error4}`)));
16940
+ relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error5) => this._onerror(new Error(`Failed to send an error response: ${error5}`)));
16826
16941
  } else if (relatedTaskId && this._taskMessageQueue) {
16827
16942
  this._enqueueTaskMessage(relatedTaskId, {
16828
16943
  type: "error",
16829
16944
  message: errorResponse,
16830
16945
  timestamp: Date.now()
16831
- }, capturedTransport?.sessionId).catch((error4) => this._onerror(new Error(`Failed to enqueue error response: ${error4}`)));
16946
+ }, capturedTransport?.sessionId).catch((error5) => this._onerror(new Error(`Failed to enqueue error response: ${error5}`)));
16832
16947
  } else {
16833
- capturedTransport?.send(errorResponse).catch((error4) => this._onerror(new Error(`Failed to send an error response: ${error4}`)));
16948
+ capturedTransport?.send(errorResponse).catch((error5) => this._onerror(new Error(`Failed to send an error response: ${error5}`)));
16834
16949
  }
16835
16950
  return;
16836
16951
  }
@@ -16899,7 +17014,7 @@ var Protocol = class {
16899
17014
  } else {
16900
17015
  await capturedTransport?.send(response);
16901
17016
  }
16902
- }, async (error4) => {
17017
+ }, async (error5) => {
16903
17018
  if (abortController.signal.aborted) {
16904
17019
  return;
16905
17020
  }
@@ -16907,9 +17022,9 @@ var Protocol = class {
16907
17022
  jsonrpc: "2.0",
16908
17023
  id: request.id,
16909
17024
  error: {
16910
- code: Number.isSafeInteger(error4["code"]) ? error4["code"] : ErrorCode.InternalError,
16911
- message: error4.message ?? "Internal error",
16912
- ...error4["data"] !== void 0 && { data: error4["data"] }
17025
+ code: Number.isSafeInteger(error5["code"]) ? error5["code"] : ErrorCode.InternalError,
17026
+ message: error5.message ?? "Internal error",
17027
+ ...error5["data"] !== void 0 && { data: error5["data"] }
16913
17028
  }
16914
17029
  };
16915
17030
  if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) {
@@ -16921,7 +17036,7 @@ var Protocol = class {
16921
17036
  } else {
16922
17037
  await capturedTransport?.send(errorResponse);
16923
17038
  }
16924
- }).catch((error4) => this._onerror(new Error(`Failed to send response: ${error4}`))).finally(() => {
17039
+ }).catch((error5) => this._onerror(new Error(`Failed to send response: ${error5}`))).finally(() => {
16925
17040
  if (this._requestHandlerAbortControllers.get(request.id) === abortController) {
16926
17041
  this._requestHandlerAbortControllers.delete(request.id);
16927
17042
  }
@@ -16940,11 +17055,11 @@ var Protocol = class {
16940
17055
  if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {
16941
17056
  try {
16942
17057
  this._resetTimeout(messageId);
16943
- } catch (error4) {
17058
+ } catch (error5) {
16944
17059
  this._responseHandlers.delete(messageId);
16945
17060
  this._progressHandlers.delete(messageId);
16946
17061
  this._cleanupTimeout(messageId);
16947
- responseHandler(error4);
17062
+ responseHandler(error5);
16948
17063
  return;
16949
17064
  }
16950
17065
  }
@@ -16958,8 +17073,8 @@ var Protocol = class {
16958
17073
  if (isJSONRPCResultResponse(response)) {
16959
17074
  resolver(response);
16960
17075
  } else {
16961
- const error4 = new McpError(response.error.code, response.error.message, response.error.data);
16962
- resolver(error4);
17076
+ const error5 = new McpError(response.error.code, response.error.message, response.error.data);
17077
+ resolver(error5);
16963
17078
  }
16964
17079
  return;
16965
17080
  }
@@ -16987,8 +17102,8 @@ var Protocol = class {
16987
17102
  if (isJSONRPCResultResponse(response)) {
16988
17103
  handler(response);
16989
17104
  } else {
16990
- const error4 = McpError.fromError(response.error.code, response.error.message, response.error.data);
16991
- handler(error4);
17105
+ const error5 = McpError.fromError(response.error.code, response.error.message, response.error.data);
17106
+ handler(error5);
16992
17107
  }
16993
17108
  }
16994
17109
  get transport() {
@@ -17033,10 +17148,10 @@ var Protocol = class {
17033
17148
  try {
17034
17149
  const result = await this.request(request, resultSchema, options);
17035
17150
  yield { type: "result", result };
17036
- } catch (error4) {
17151
+ } catch (error5) {
17037
17152
  yield {
17038
17153
  type: "error",
17039
- error: error4 instanceof McpError ? error4 : new McpError(ErrorCode.InternalError, String(error4))
17154
+ error: error5 instanceof McpError ? error5 : new McpError(ErrorCode.InternalError, String(error5))
17040
17155
  };
17041
17156
  }
17042
17157
  return;
@@ -17079,10 +17194,10 @@ var Protocol = class {
17079
17194
  await new Promise((resolve) => setTimeout(resolve, pollInterval));
17080
17195
  options?.signal?.throwIfAborted();
17081
17196
  }
17082
- } catch (error4) {
17197
+ } catch (error5) {
17083
17198
  yield {
17084
17199
  type: "error",
17085
- error: error4 instanceof McpError ? error4 : new McpError(ErrorCode.InternalError, String(error4))
17200
+ error: error5 instanceof McpError ? error5 : new McpError(ErrorCode.InternalError, String(error5))
17086
17201
  };
17087
17202
  }
17088
17203
  }
@@ -17094,8 +17209,8 @@ var Protocol = class {
17094
17209
  request(request, resultSchema, options) {
17095
17210
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
17096
17211
  return new Promise((resolve, reject) => {
17097
- const earlyReject = (error4) => {
17098
- reject(error4);
17212
+ const earlyReject = (error5) => {
17213
+ reject(error5);
17099
17214
  };
17100
17215
  if (!this._transport) {
17101
17216
  earlyReject(new Error("Not connected"));
@@ -17155,9 +17270,9 @@ var Protocol = class {
17155
17270
  requestId: messageId,
17156
17271
  reason: String(reason)
17157
17272
  }
17158
- }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error5) => this._onerror(new Error(`Failed to send cancellation: ${error5}`)));
17159
- const error4 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));
17160
- reject(error4);
17273
+ }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error6) => this._onerror(new Error(`Failed to send cancellation: ${error6}`)));
17274
+ const error5 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));
17275
+ reject(error5);
17161
17276
  };
17162
17277
  this._responseHandlers.set(messageId, (response) => {
17163
17278
  if (options?.signal?.aborted) {
@@ -17173,8 +17288,8 @@ var Protocol = class {
17173
17288
  } else {
17174
17289
  resolve(parseResult.data);
17175
17290
  }
17176
- } catch (error4) {
17177
- reject(error4);
17291
+ } catch (error5) {
17292
+ reject(error5);
17178
17293
  }
17179
17294
  });
17180
17295
  options?.signal?.addEventListener("abort", () => {
@@ -17198,14 +17313,14 @@ var Protocol = class {
17198
17313
  type: "request",
17199
17314
  message: jsonrpcRequest,
17200
17315
  timestamp: Date.now()
17201
- }).catch((error4) => {
17316
+ }).catch((error5) => {
17202
17317
  this._cleanupTimeout(messageId);
17203
- reject(error4);
17318
+ reject(error5);
17204
17319
  });
17205
17320
  } else {
17206
- this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error4) => {
17321
+ this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error5) => {
17207
17322
  this._cleanupTimeout(messageId);
17208
- reject(error4);
17323
+ reject(error5);
17209
17324
  });
17210
17325
  }
17211
17326
  });
@@ -17298,7 +17413,7 @@ var Protocol = class {
17298
17413
  }
17299
17414
  };
17300
17415
  }
17301
- this._transport?.send(jsonrpcNotification2, options).catch((error4) => this._onerror(error4));
17416
+ this._transport?.send(jsonrpcNotification2, options).catch((error5) => this._onerror(error5));
17302
17417
  });
17303
17418
  return;
17304
17419
  }
@@ -18152,11 +18267,11 @@ var Server = class extends Protocol {
18152
18267
  if (!validationResult.valid) {
18153
18268
  throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);
18154
18269
  }
18155
- } catch (error4) {
18156
- if (error4 instanceof McpError) {
18157
- throw error4;
18270
+ } catch (error5) {
18271
+ if (error5 instanceof McpError) {
18272
+ throw error5;
18158
18273
  }
18159
- throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error4 instanceof Error ? error4.message : String(error4)}`);
18274
+ throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error5 instanceof Error ? error5.message : String(error5)}`);
18160
18275
  }
18161
18276
  }
18162
18277
  return result;
@@ -18268,14 +18383,14 @@ var StdioServerTransport = class {
18268
18383
  try {
18269
18384
  this._readBuffer.append(chunk);
18270
18385
  this.processReadBuffer();
18271
- } catch (error4) {
18272
- this.onerror?.(error4);
18386
+ } catch (error5) {
18387
+ this.onerror?.(error5);
18273
18388
  this.close().catch(() => {
18274
18389
  });
18275
18390
  }
18276
18391
  };
18277
- this._onerror = (error4) => {
18278
- this.onerror?.(error4);
18392
+ this._onerror = (error5) => {
18393
+ this.onerror?.(error5);
18279
18394
  };
18280
18395
  this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize });
18281
18396
  }
@@ -18298,8 +18413,8 @@ var StdioServerTransport = class {
18298
18413
  break;
18299
18414
  }
18300
18415
  this.onmessage?.(message);
18301
- } catch (error4) {
18302
- this.onerror?.(error4);
18416
+ } catch (error5) {
18417
+ this.onerror?.(error5);
18303
18418
  }
18304
18419
  }
18305
18420
  }
@@ -18396,14 +18511,14 @@ var ExperimentalClientTasks = class {
18396
18511
  };
18397
18512
  return;
18398
18513
  }
18399
- } catch (error4) {
18400
- if (error4 instanceof McpError) {
18401
- yield { type: "error", error: error4 };
18514
+ } catch (error5) {
18515
+ if (error5 instanceof McpError) {
18516
+ yield { type: "error", error: error5 };
18402
18517
  return;
18403
18518
  }
18404
18519
  yield {
18405
18520
  type: "error",
18406
- error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error4 instanceof Error ? error4.message : String(error4)}`)
18521
+ error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error5 instanceof Error ? error5.message : String(error5)}`)
18407
18522
  };
18408
18523
  return;
18409
18524
  }
@@ -18716,9 +18831,9 @@ var Client = class extends Protocol {
18716
18831
  this._setupListChangedHandlers(this._pendingListChangedConfig);
18717
18832
  this._pendingListChangedConfig = void 0;
18718
18833
  }
18719
- } catch (error4) {
18834
+ } catch (error5) {
18720
18835
  void this.close();
18721
- throw error4;
18836
+ throw error5;
18722
18837
  }
18723
18838
  }
18724
18839
  /**
@@ -18888,11 +19003,11 @@ var Client = class extends Protocol {
18888
19003
  if (!validationResult.valid) {
18889
19004
  throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
18890
19005
  }
18891
- } catch (error4) {
18892
- if (error4 instanceof McpError) {
18893
- throw error4;
19006
+ } catch (error5) {
19007
+ if (error5 instanceof McpError) {
19008
+ throw error5;
18894
19009
  }
18895
- throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error4 instanceof Error ? error4.message : String(error4)}`);
19010
+ throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error5 instanceof Error ? error5.message : String(error5)}`);
18896
19011
  }
18897
19012
  }
18898
19013
  }
@@ -18967,8 +19082,8 @@ var Client = class extends Protocol {
18967
19082
  const items = await fetcher();
18968
19083
  onChanged(null, items);
18969
19084
  } catch (e) {
18970
- const error4 = e instanceof Error ? e : new Error(String(e));
18971
- onChanged(error4, null);
19085
+ const error5 = e instanceof Error ? e : new Error(String(e));
19086
+ onChanged(error5, null);
18972
19087
  }
18973
19088
  };
18974
19089
  const handler = () => {
@@ -19475,12 +19590,12 @@ async function parseErrorResponse(input) {
19475
19590
  const body = input instanceof Response ? await input.text() : input;
19476
19591
  try {
19477
19592
  const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
19478
- const { error: error4, error_description, error_uri } = result;
19479
- const errorClass = OAUTH_ERRORS[error4] || ServerError;
19593
+ const { error: error5, error_description, error_uri } = result;
19594
+ const errorClass = OAUTH_ERRORS[error5] || ServerError;
19480
19595
  return new errorClass(error_description || "", error_uri);
19481
- } catch (error4) {
19596
+ } catch (error5) {
19482
19597
  const redirect = input instanceof Response ? unfollowedRedirect(input, input.url) : void 0;
19483
- const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}${redirect ?? `Invalid OAuth error response: ${error4}. Raw body: ${body}`}`;
19598
+ const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}${redirect ?? `Invalid OAuth error response: ${error5}. Raw body: ${body}`}`;
19484
19599
  return new ServerError(errorMessage);
19485
19600
  }
19486
19601
  }
@@ -19507,15 +19622,15 @@ function boundElsewhereError(stored, issuer) {
19507
19622
  async function auth(provider, options) {
19508
19623
  try {
19509
19624
  return await authInternal(provider, options);
19510
- } catch (error4) {
19511
- if (error4 instanceof InvalidClientError || error4 instanceof UnauthorizedClientError) {
19625
+ } catch (error5) {
19626
+ if (error5 instanceof InvalidClientError || error5 instanceof UnauthorizedClientError) {
19512
19627
  await provider.invalidateCredentials?.("all");
19513
19628
  return await authInternal(provider, options);
19514
- } else if (error4 instanceof InvalidGrantError) {
19629
+ } else if (error5 instanceof InvalidGrantError) {
19515
19630
  await provider.invalidateCredentials?.("tokens");
19516
19631
  return await authInternal(provider, options);
19517
19632
  }
19518
- throw error4;
19633
+ throw error5;
19519
19634
  }
19520
19635
  }
19521
19636
  async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
@@ -19631,10 +19746,10 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
19631
19746
  await bindClientInformation();
19632
19747
  await provider.saveTokens({ ...newTokens, issuer });
19633
19748
  return "AUTHORIZED";
19634
- } catch (error4) {
19635
- if (!(error4 instanceof OAuthError) || error4 instanceof ServerError) {
19749
+ } catch (error5) {
19750
+ if (!(error5 instanceof OAuthError) || error5 instanceof ServerError) {
19636
19751
  } else {
19637
- throw error4;
19752
+ throw error5;
19638
19753
  }
19639
19754
  }
19640
19755
  }
@@ -19692,11 +19807,11 @@ function extractWWWAuthenticateParams(res) {
19692
19807
  }
19693
19808
  }
19694
19809
  const scope = extractFieldFromWwwAuth(res, "scope") || void 0;
19695
- const error4 = extractFieldFromWwwAuth(res, "error") || void 0;
19810
+ const error5 = extractFieldFromWwwAuth(res, "error") || void 0;
19696
19811
  return {
19697
19812
  resourceMetadataUrl,
19698
19813
  scope,
19699
- error: error4
19814
+ error: error5
19700
19815
  };
19701
19816
  }
19702
19817
  function extractFieldFromWwwAuth(response, fieldName) {
@@ -19729,15 +19844,15 @@ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn =
19729
19844
  async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
19730
19845
  try {
19731
19846
  return await fetchWithinOrigin(fetchFn)(url2, { headers });
19732
- } catch (error4) {
19733
- if (error4 instanceof TypeError) {
19847
+ } catch (error5) {
19848
+ if (error5 instanceof TypeError) {
19734
19849
  if (headers) {
19735
19850
  return fetchWithCorsRetry(url2, void 0, fetchFn);
19736
19851
  } else {
19737
19852
  return void 0;
19738
19853
  }
19739
19854
  }
19740
- throw error4;
19855
+ throw error5;
19741
19856
  }
19742
19857
  }
19743
19858
  function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
@@ -20186,8 +20301,8 @@ var EventSourceParserStream = class extends TransformStream {
20186
20301
  onEvent: (event) => {
20187
20302
  controller.enqueue(event);
20188
20303
  },
20189
- onError(error4) {
20190
- typeof onError == "function" && onError(error4), (onError === "terminate" || error4.type === "max-buffer-size-exceeded") && controller.error(error4);
20304
+ onError(error5) {
20305
+ typeof onError == "function" && onError(error5), (onError === "terminate" || error5.type === "max-buffer-size-exceeded") && controller.error(error5);
20191
20306
  },
20192
20307
  onRetry,
20193
20308
  onComment,
@@ -20249,9 +20364,9 @@ var StreamableHTTPClientTransport = class {
20249
20364
  scope: this._scope,
20250
20365
  fetchFn: this._fetchWithInit
20251
20366
  });
20252
- } catch (error4) {
20253
- this.onerror?.(error4);
20254
- throw error4;
20367
+ } catch (error5) {
20368
+ this.onerror?.(error5);
20369
+ throw error5;
20255
20370
  }
20256
20371
  if (result !== "AUTHORIZED") {
20257
20372
  throw new UnauthorizedError();
@@ -20304,9 +20419,9 @@ var StreamableHTTPClientTransport = class {
20304
20419
  throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);
20305
20420
  }
20306
20421
  this._handleSseStream(response.body, options, true);
20307
- } catch (error4) {
20308
- this.onerror?.(error4);
20309
- throw error4;
20422
+ } catch (error5) {
20423
+ this.onerror?.(error5);
20424
+ throw error5;
20310
20425
  }
20311
20426
  }
20312
20427
  /**
@@ -20338,8 +20453,8 @@ var StreamableHTTPClientTransport = class {
20338
20453
  }
20339
20454
  const delay = this._getNextReconnectionDelay(attemptCount);
20340
20455
  this._reconnectionTimeout = setTimeout(() => {
20341
- this._startOrAuthSse(options).catch((error4) => {
20342
- this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error4 instanceof Error ? error4.message : String(error4)}`));
20456
+ this._startOrAuthSse(options).catch((error5) => {
20457
+ this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error5 instanceof Error ? error5.message : String(error5)}`));
20343
20458
  this._scheduleReconnection(options, attemptCount + 1);
20344
20459
  });
20345
20460
  }, delay);
@@ -20382,8 +20497,8 @@ var StreamableHTTPClientTransport = class {
20382
20497
  }
20383
20498
  }
20384
20499
  this.onmessage?.(message);
20385
- } catch (error4) {
20386
- this.onerror?.(error4);
20500
+ } catch (error5) {
20501
+ this.onerror?.(error5);
20387
20502
  }
20388
20503
  }
20389
20504
  }
@@ -20396,8 +20511,8 @@ var StreamableHTTPClientTransport = class {
20396
20511
  replayMessageId
20397
20512
  }, 0);
20398
20513
  }
20399
- } catch (error4) {
20400
- this.onerror?.(new Error(`SSE stream disconnected: ${error4}`));
20514
+ } catch (error5) {
20515
+ this.onerror?.(new Error(`SSE stream disconnected: ${error5}`));
20401
20516
  const canResume = isReconnectable || hasPrimingEvent;
20402
20517
  const needsReconnect = canResume && !receivedResponse;
20403
20518
  if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
@@ -20407,8 +20522,8 @@ var StreamableHTTPClientTransport = class {
20407
20522
  onresumptiontoken,
20408
20523
  replayMessageId
20409
20524
  }, 0);
20410
- } catch (error5) {
20411
- this.onerror?.(new Error(`Failed to reconnect: ${error5 instanceof Error ? error5.message : String(error5)}`));
20525
+ } catch (error6) {
20526
+ this.onerror?.(new Error(`Failed to reconnect: ${error6 instanceof Error ? error6.message : String(error6)}`));
20412
20527
  }
20413
20528
  }
20414
20529
  }
@@ -20491,8 +20606,8 @@ var StreamableHTTPClientTransport = class {
20491
20606
  return this.send(message);
20492
20607
  }
20493
20608
  if (response.status === 403 && this._authProvider) {
20494
- const { resourceMetadataUrl, scope, error: error4 } = extractWWWAuthenticateParams(response);
20495
- if (error4 === "insufficient_scope") {
20609
+ const { resourceMetadataUrl, scope, error: error5 } = extractWWWAuthenticateParams(response);
20610
+ if (error5 === "insufficient_scope") {
20496
20611
  const wwwAuthHeader = response.headers.get("WWW-Authenticate");
20497
20612
  if (this._lastUpscopingHeader === wwwAuthHeader) {
20498
20613
  throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
@@ -20547,9 +20662,9 @@ var StreamableHTTPClientTransport = class {
20547
20662
  } else {
20548
20663
  await response.body?.cancel();
20549
20664
  }
20550
- } catch (error4) {
20551
- this.onerror?.(error4);
20552
- throw error4;
20665
+ } catch (error5) {
20666
+ this.onerror?.(error5);
20667
+ throw error5;
20553
20668
  }
20554
20669
  }
20555
20670
  get sessionId() {
@@ -20584,9 +20699,9 @@ var StreamableHTTPClientTransport = class {
20584
20699
  throw new StreamableHTTPError(response.status, `Failed to terminate session: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);
20585
20700
  }
20586
20701
  this._sessionId = void 0;
20587
- } catch (error4) {
20588
- this.onerror?.(error4);
20589
- throw error4;
20702
+ } catch (error5) {
20703
+ this.onerror?.(error5);
20704
+ throw error5;
20590
20705
  }
20591
20706
  }
20592
20707
  setProtocolVersion(version3) {
@@ -20700,7 +20815,7 @@ var BridgeCompatibilityError = class extends CreationClientError {
20700
20815
  });
20701
20816
  }
20702
20817
  };
20703
- var bridgeErrorDetails = (error4) => error4 instanceof BridgeCompatibilityError ? error4.bridgeFacts : void 0;
20818
+ var bridgeErrorDetails = (error5) => error5 instanceof BridgeCompatibilityError ? error5.bridgeFacts : void 0;
20704
20819
  function declaredHostContentCapabilities(capabilities, { initialized = false, standardContent = false } = {}) {
20705
20820
  const requested = capabilities?.experimental?.["promptframe.contentTypes"];
20706
20821
  if (requested === void 0 && initialized && standardContent)
@@ -20710,8 +20825,316 @@ function declaredHostContentCapabilities(capabilities, { initialized = false, st
20710
20825
  }
20711
20826
  var declaredHostContentTypes = (capabilities) => declaredHostContentCapabilities(capabilities).types;
20712
20827
 
20828
+ // lib/local-accounts.mjs
20829
+ import { constants as constants3 } from "node:fs";
20830
+ import { open as open4, lstat as lstat4, mkdir as mkdir3, rename as rename3, unlink as unlink3, opendir } from "node:fs/promises";
20831
+ import { homedir as homedir2 } from "node:os";
20832
+ import path5 from "node:path";
20833
+ import { createHash as createHash3, randomUUID } from "node:crypto";
20834
+ var LOCAL_ACCOUNT_DIRECTORY_VERSION = "promptframe-local-account-directory/v1";
20835
+ var LOCAL_AGENT_ACCOUNT_VERSION = "promptframe-local-agent-account/v1";
20836
+ var clients = ["creation", "component-cli"];
20837
+ var digestFormat = /^sha256:[a-f0-9]{64}$/;
20838
+ var hexFormat = /^[a-f0-9]{64}$/;
20839
+ var recordLimit = 16 * 1024;
20840
+ var hash = (value2) => "sha256:" + createHash3("sha256").update(value2).digest("hex");
20841
+ var failure3 = (code) => new CreationClientError("accounts." + code);
20842
+ var plain = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2);
20843
+ var date4 = (value2) => typeof value2 === "string" && Number.isFinite(Date.parse(value2));
20844
+ function localAccountsRoot(env = process.env) {
20845
+ return path5.resolve(env.PROMPTFRAME_ACCOUNT_DIRECTORY ?? path5.join(
20846
+ env.XDG_CONFIG_HOME ?? path5.join(homedir2(), ".config"),
20847
+ "promptframe",
20848
+ "accounts",
20849
+ "v1"
20850
+ ));
20851
+ }
20852
+ function parseAccountIdentity(value2) {
20853
+ if (!plain(value2) || Object.keys(value2).length !== 3 || value2.contractVersion !== "promptframe-account-identity/v1" || !digestFormat.test(value2.platformDigest ?? "") || !digestFormat.test(value2.accountDigest ?? ""))
20854
+ throw failure3("identity_invalid");
20855
+ return { contractVersion: value2.contractVersion, platformDigest: value2.platformDigest, accountDigest: value2.accountDigest };
20856
+ }
20857
+ function localAccountKey(identity) {
20858
+ const value2 = parseAccountIdentity(identity);
20859
+ return value2.platformDigest.slice(7) + "-" + value2.accountDigest.slice(7);
20860
+ }
20861
+ function localReferenceId(client, configFile2) {
20862
+ if (!clients.includes(client) || typeof configFile2 !== "string" || !path5.isAbsolute(configFile2))
20863
+ throw failure3("reference_invalid");
20864
+ return hash(JSON.stringify([client, path5.resolve(configFile2)]));
20865
+ }
20866
+ function localCredentialDigest(token) {
20867
+ if (typeof token !== "string" || !token || token.length > 4096) throw failure3("reference_invalid");
20868
+ return hash(token);
20869
+ }
20870
+ function privateOwner(info5, directory3 = false) {
20871
+ const uid = process.getuid?.();
20872
+ if (uid === void 0 || info5.uid !== uid || (info5.mode & 63) !== 0 || info5.isSymbolicLink() || !(directory3 ? info5.isDirectory() : info5.isFile()))
20873
+ throw failure3("private_storage_required");
20874
+ }
20875
+ async function directory2(file, create = false) {
20876
+ if (create) await mkdir3(file, { recursive: true, mode: 448 });
20877
+ try {
20878
+ privateOwner(await lstat4(file), true);
20879
+ return true;
20880
+ } catch (error5) {
20881
+ if (!create && error5.code === "ENOENT") return false;
20882
+ throw error5;
20883
+ }
20884
+ }
20885
+ async function ownedPath(root, segments, create = false) {
20886
+ if (!await directory2(root, create)) return void 0;
20887
+ let current = root;
20888
+ for (const segment of segments) {
20889
+ current = path5.join(current, segment);
20890
+ if (!await directory2(current, create)) return void 0;
20891
+ }
20892
+ return current;
20893
+ }
20894
+ async function readJson(file) {
20895
+ let fd;
20896
+ try {
20897
+ fd = await open4(file, constants3.O_RDONLY | constants3.O_NOFOLLOW | (constants3.O_NONBLOCK ?? 0));
20898
+ const before = await fd.stat();
20899
+ privateOwner(before);
20900
+ if (before.size > recordLimit) throw failure3("record_too_large");
20901
+ const buffer = Buffer.alloc(recordLimit + 1);
20902
+ const { bytesRead } = await fd.read(buffer, 0, buffer.length, 0);
20903
+ const after = await fd.stat(), current = await lstat4(file);
20904
+ if (bytesRead !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs || current.dev !== before.dev || current.ino !== before.ino) throw failure3("reference_changed");
20905
+ try {
20906
+ return JSON.parse(buffer.subarray(0, bytesRead).toString("utf8"));
20907
+ } catch {
20908
+ throw failure3("record_invalid");
20909
+ }
20910
+ } catch (error5) {
20911
+ if (error5.code === "ENOENT") return void 0;
20912
+ if (error5.code === "ELOOP") throw failure3("private_storage_required");
20913
+ throw error5;
20914
+ } finally {
20915
+ await fd?.close();
20916
+ }
20917
+ }
20918
+ async function writeJson(directoryPath, name, value2) {
20919
+ const payload = JSON.stringify(value2) + "\n";
20920
+ if (Buffer.byteLength(payload) > recordLimit) throw failure3("record_too_large");
20921
+ const parent = await open4(directoryPath, constants3.O_RDONLY | constants3.O_DIRECTORY | constants3.O_NOFOLLOW);
20922
+ const temporary = path5.join(directoryPath, "." + randomUUID() + ".tmp");
20923
+ try {
20924
+ const owner = await parent.stat();
20925
+ privateOwner(owner, true);
20926
+ const fd = await open4(temporary, constants3.O_WRONLY | constants3.O_CREAT | constants3.O_EXCL | constants3.O_NOFOLLOW, 384);
20927
+ try {
20928
+ await fd.writeFile(payload);
20929
+ await fd.sync();
20930
+ } finally {
20931
+ await fd.close();
20932
+ }
20933
+ const current = await lstat4(directoryPath);
20934
+ if (current.dev !== owner.dev || current.ino !== owner.ino) throw failure3("reference_changed");
20935
+ try {
20936
+ privateOwner(await lstat4(path5.join(directoryPath, name)));
20937
+ } catch (error5) {
20938
+ if (error5.code !== "ENOENT") throw error5;
20939
+ }
20940
+ await rename3(temporary, path5.join(directoryPath, name));
20941
+ await parent.sync();
20942
+ } finally {
20943
+ await parent.close();
20944
+ await unlink3(temporary).catch((error5) => {
20945
+ if (error5.code !== "ENOENT") throw error5;
20946
+ });
20947
+ }
20948
+ }
20949
+ function referencePath(identity, client) {
20950
+ const value2 = parseAccountIdentity(identity);
20951
+ if (!clients.includes(client)) throw failure3("reference_invalid");
20952
+ return ["identities", value2.platformDigest.slice(7), value2.accountDigest.slice(7), client];
20953
+ }
20954
+ function parseReference(value2, identity, client, id) {
20955
+ const fields = [
20956
+ "contractVersion",
20957
+ "identity",
20958
+ "client",
20959
+ "referenceId",
20960
+ "configFile",
20961
+ "endpoint",
20962
+ "credentialDigest",
20963
+ "observedAt",
20964
+ "expiresAt",
20965
+ "profile",
20966
+ "scopes"
20967
+ ];
20968
+ if (!plain(value2) || Object.keys(value2).some((key) => !fields.includes(key)) || value2.contractVersion !== LOCAL_ACCOUNT_DIRECTORY_VERSION || value2.client !== client || value2.referenceId !== id || localAccountKey(value2.identity) !== localAccountKey(identity) || typeof value2.configFile !== "string" || value2.configFile.length > 4096 || localReferenceId(client, value2.configFile) !== id || !digestFormat.test(value2.credentialDigest ?? "") || !date4(value2.observedAt) || value2.expiresAt !== void 0 && !date4(value2.expiresAt) || value2.profile !== void 0 && (typeof value2.profile !== "string" || !/^[A-Za-z0-9._-]{1,80}$/.test(value2.profile)) || value2.scopes !== void 0 && (!Array.isArray(value2.scopes) || value2.scopes.length > 20 || value2.scopes.some((scope) => typeof scope !== "string" || !/^[a-z0-9_.:-]{1,100}$/.test(scope))))
20969
+ throw failure3("record_invalid");
20970
+ let endpoint;
20971
+ try {
20972
+ endpoint = new URL(value2.endpoint);
20973
+ } catch {
20974
+ throw failure3("record_invalid");
20975
+ }
20976
+ if (typeof value2.endpoint !== "string" || value2.endpoint.length > 500 || endpoint.username || endpoint.password || endpoint.search || endpoint.hash || endpoint.protocol !== "https:" && !(endpoint.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(endpoint.hostname)))
20977
+ throw failure3("record_invalid");
20978
+ return value2;
20979
+ }
20980
+ async function recordAuthorization({
20981
+ root = localAccountsRoot(),
20982
+ identity,
20983
+ client,
20984
+ configFile: configFile2,
20985
+ endpoint,
20986
+ token,
20987
+ observedAt = (/* @__PURE__ */ new Date()).toISOString(),
20988
+ expiresAt,
20989
+ profile,
20990
+ scopes
20991
+ }) {
20992
+ identity = parseAccountIdentity(identity);
20993
+ if (typeof configFile2 !== "string" || !path5.isAbsolute(configFile2)) throw failure3("reference_invalid");
20994
+ configFile2 = path5.resolve(configFile2);
20995
+ const referenceId = localReferenceId(client, configFile2);
20996
+ const record2 = parseReference({
20997
+ contractVersion: LOCAL_ACCOUNT_DIRECTORY_VERSION,
20998
+ identity,
20999
+ client,
21000
+ referenceId,
21001
+ configFile: configFile2,
21002
+ endpoint,
21003
+ credentialDigest: localCredentialDigest(token),
21004
+ observedAt,
21005
+ ...expiresAt !== void 0 ? { expiresAt } : {},
21006
+ ...profile !== void 0 ? { profile } : {},
21007
+ ...scopes !== void 0 ? { scopes } : {}
21008
+ }, identity, client, referenceId);
21009
+ const parent = await ownedPath(root, referencePath(identity, client), true);
21010
+ await writeJson(parent, referenceId.slice(7) + ".json", record2);
21011
+ return { identityKey: localAccountKey(identity), referenceId };
21012
+ }
21013
+ async function readAuthorization({ root = localAccountsRoot(), identity, client, referenceId }) {
21014
+ if (!digestFormat.test(referenceId ?? "")) throw failure3("reference_invalid");
21015
+ const parent = await ownedPath(root, referencePath(identity, client));
21016
+ const value2 = parent ? await readJson(path5.join(parent, referenceId.slice(7) + ".json")) : void 0;
21017
+ return value2 === void 0 ? void 0 : parseReference(value2, identity, client, referenceId);
21018
+ }
21019
+ async function readAuthorizations({ root = localAccountsRoot(), identity, client }) {
21020
+ const parent = await ownedPath(root, referencePath(identity, client));
21021
+ if (!parent) return [];
21022
+ const records = [];
21023
+ for (const entry of await entries(parent)) {
21024
+ if (!/^[a-f0-9]{64}\.json$/.test(entry.name)) throw failure3("record_invalid");
21025
+ const value2 = await readLocalAuthorization({ root, identity, client, referenceId: "sha256:" + entry.name.slice(0, -5) });
21026
+ if (value2) records.push(value2);
21027
+ }
21028
+ return records.sort((a, b2) => a.referenceId.localeCompare(b2.referenceId));
21029
+ }
21030
+ async function entries(file) {
21031
+ const output = [];
21032
+ const handle = await opendir(file);
21033
+ for await (const entry of handle) {
21034
+ if (entry.name.startsWith(".")) continue;
21035
+ if (output.length === 256) throw failure3("listing_limit");
21036
+ output.push(entry);
21037
+ }
21038
+ return output;
21039
+ }
21040
+ async function listAccounts({ root = localAccountsRoot(), now = Date.now() } = {}) {
21041
+ const base = await ownedPath(root, ["identities"]);
21042
+ if (!base) return { accounts: [], complete: true };
21043
+ const accounts = [];
21044
+ for (const platform2 of await entries(base)) {
21045
+ if (!hexFormat.test(platform2.name)) throw failure3("record_invalid");
21046
+ const platformPath = await ownedPath(root, ["identities", platform2.name]);
21047
+ for (const account of await entries(platformPath)) {
21048
+ if (!hexFormat.test(account.name) || accounts.length === 256) throw failure3("listing_limit");
21049
+ const identity = {
21050
+ contractVersion: "promptframe-account-identity/v1",
21051
+ platformDigest: "sha256:" + platform2.name,
21052
+ accountDigest: "sha256:" + account.name
21053
+ };
21054
+ const grants = {};
21055
+ for (const client of clients) {
21056
+ grants[client] = [];
21057
+ const parent = await ownedPath(root, referencePath(identity, client));
21058
+ if (!parent) continue;
21059
+ for (const entry of await entries(parent)) {
21060
+ if (!/^[a-f0-9]{64}\.json$/.test(entry.name)) throw failure3("record_invalid");
21061
+ const ref = await readLocalAuthorization({ root, identity, client, referenceId: "sha256:" + entry.name.slice(0, -5) });
21062
+ if (!ref) continue;
21063
+ grants[client].push({
21064
+ referenceId: ref.referenceId,
21065
+ ...ref.profile ? { profile: ref.profile } : {},
21066
+ status: ref.expiresAt && Date.parse(ref.expiresAt) <= now ? "expired" : "stored",
21067
+ observedAt: ref.observedAt,
21068
+ ...ref.expiresAt ? { expiresAt: ref.expiresAt } : {}
21069
+ });
21070
+ }
21071
+ }
21072
+ accounts.push({
21073
+ identityKey: localAccountKey(identity),
21074
+ identity,
21075
+ grants,
21076
+ missingClients: clients.filter((client) => !grants[client].some((ref) => ref.status === "stored"))
21077
+ });
21078
+ }
21079
+ }
21080
+ return { accounts, complete: true };
21081
+ }
21082
+ function localAgentDigest(agent) {
21083
+ if (!agent || !["codex", "claude-code"].includes(agent.kind) || typeof agent.sessionId !== "string" || !threadFormat.test(agent.sessionId)) throw failure3("agent_required");
21084
+ return hash(JSON.stringify([agent.kind, agent.sessionId.toLowerCase()]));
21085
+ }
21086
+ async function selectAccount({ root = localAccountsRoot(), agent, identity }) {
21087
+ const agentDigest = localAgentDigest(agent);
21088
+ const parent = await ownedPath(root, ["selections"], true);
21089
+ const value2 = {
21090
+ contractVersion: LOCAL_AGENT_ACCOUNT_VERSION,
21091
+ agentKind: agent.kind,
21092
+ agentDigest,
21093
+ generation: randomUUID(),
21094
+ identity: parseAccountIdentity(identity),
21095
+ selectedAt: (/* @__PURE__ */ new Date()).toISOString()
21096
+ };
21097
+ await writeJson(parent, agent.kind + "-" + agentDigest.slice(7) + ".json", value2);
21098
+ return value2;
21099
+ }
21100
+ async function readSelectedAccount({ root = localAccountsRoot(), agent }) {
21101
+ const agentDigest = localAgentDigest(agent), parent = await ownedPath(root, ["selections"]);
21102
+ const value2 = parent ? await readJson(path5.join(parent, agent.kind + "-" + agentDigest.slice(7) + ".json")) : void 0;
21103
+ if (value2 === void 0) return void 0;
21104
+ if (!plain(value2) || Object.keys(value2).length !== 6 || value2.contractVersion !== LOCAL_AGENT_ACCOUNT_VERSION || value2.agentKind !== agent.kind || value2.agentDigest !== agentDigest || !threadFormat.test(value2.generation ?? "") || !date4(value2.selectedAt)) throw failure3("record_invalid");
21105
+ return { ...value2, identity: parseAccountIdentity(value2.identity) };
21106
+ }
21107
+ var accountIO = (operation) => async (...args2) => {
21108
+ try {
21109
+ return await operation(...args2);
21110
+ } catch (cause) {
21111
+ if (cause instanceof CreationClientError) throw cause;
21112
+ throw failure3(["EACCES", "EPERM", "ENOTDIR", "ELOOP"].includes(cause?.code) ? "private_storage_required" : "storage_unavailable");
21113
+ }
21114
+ };
21115
+ var recordLocalAuthorization = accountIO(recordAuthorization);
21116
+ var readLocalAuthorization = accountIO(readAuthorization);
21117
+ var readLocalAuthorizations = accountIO(readAuthorizations);
21118
+ var listLocalAccounts = accountIO(listAccounts);
21119
+ var selectLocalAccount = accountIO(selectAccount);
21120
+ var readSelectedLocalAccount = accountIO(readSelectedAccount);
21121
+
20713
21122
  // lib/connection.mjs
20714
- async function connectPlatform(credentials, { host = resolveHostIdentity(), contentTypes = () => ["text"], contentSource = () => "text-fallback", enforceMinimum = true, signal } = {}) {
21123
+ function connectionAccountIdentity(client, expected) {
21124
+ const raw = client.getServerCapabilities()?.experimental?.["promptframe.accountIdentity"];
21125
+ if (raw === void 0) {
21126
+ if (expected) throw new CreationClientError("accounts.identity_unavailable");
21127
+ return void 0;
21128
+ }
21129
+ const actual = parseAccountIdentity(raw);
21130
+ if (expected) {
21131
+ expected = parseAccountIdentity(expected);
21132
+ if (actual.platformDigest !== expected.platformDigest) throw new CreationClientError("accounts.platform_mismatch");
21133
+ if (actual.accountDigest !== expected.accountDigest) throw new CreationClientError("accounts.account_mismatch");
21134
+ }
21135
+ return actual;
21136
+ }
21137
+ async function connectPlatform(credentials, { host = resolveHostIdentity(), contentTypes = () => ["text"], contentSource = () => "text-fallback", enforceMinimum = true, signal, expectedIdentity } = {}) {
20715
21138
  const client = new Client(
20716
21139
  { name: "promptframe-creation-bridge", version: CLIENT_VERSION },
20717
21140
  { capabilities: {} }
@@ -20742,32 +21165,36 @@ async function connectPlatform(credentials, { host = resolveHostIdentity(), cont
20742
21165
  );
20743
21166
  try {
20744
21167
  await client.connect(transport2, signal ? { signal } : void 0);
21168
+ connectionAccountIdentity(client, expectedIdentity);
20745
21169
  if (enforceMinimum) assertBridgeCompatible(client.getServerCapabilities(), CLIENT_VERSION);
20746
21170
  else readPlatformBridgePolicy(client.getServerCapabilities());
20747
21171
  return client;
20748
- } catch (error4) {
21172
+ } catch (error5) {
20749
21173
  await client.close().catch(() => {
20750
21174
  });
20751
- throw error4;
21175
+ throw error5;
20752
21176
  }
20753
21177
  }
20754
21178
 
21179
+ // lib/account-bridge.mjs
21180
+ import path9 from "node:path";
21181
+
20755
21182
  // lib/host-context.mjs
20756
- import { createHash as createHash5 } from "node:crypto";
21183
+ import { createHash as createHash6 } from "node:crypto";
20757
21184
 
20758
21185
  // lib/claude-host-session.mjs
20759
- import { constants as constants3 } from "node:fs";
20760
- import { open as open4, mkdir as mkdir3, lstat as lstat4, rename as rename3, unlink as unlink3, rmdir as rmdir2 } from "node:fs/promises";
20761
- import path6 from "node:path";
20762
- import { homedir as homedir3 } from "node:os";
20763
- import { createHash as createHash4, randomBytes as randomBytes3 } from "node:crypto";
21186
+ import { constants as constants4 } from "node:fs";
21187
+ import { open as open5, mkdir as mkdir4, lstat as lstat5, rename as rename4, unlink as unlink4, rmdir as rmdir2 } from "node:fs/promises";
21188
+ import path7 from "node:path";
21189
+ import { homedir as homedir4 } from "node:os";
21190
+ import { createHash as createHash5, randomBytes as randomBytes3 } from "node:crypto";
20764
21191
 
20765
21192
  // lib/claude-host-process.mjs
20766
21193
  import { readFile as readFile3, readlink, stat } from "node:fs/promises";
20767
- import path5 from "node:path";
20768
- import { homedir as homedir2 } from "node:os";
20769
- import { createHash as createHash3 } from "node:crypto";
20770
- var hash = (value2) => createHash3("sha256").update(JSON.stringify(value2)).digest("hex");
21194
+ import path6 from "node:path";
21195
+ import { homedir as homedir3 } from "node:os";
21196
+ import { createHash as createHash4 } from "node:crypto";
21197
+ var hash2 = (value2) => createHash4("sha256").update(JSON.stringify(value2)).digest("hex");
20771
21198
  var bounded = async (file) => {
20772
21199
  const value2 = await readFile3(file);
20773
21200
  if (value2.length > 65536) throw Error("host_process_invalid");
@@ -20782,7 +21209,7 @@ async function processBirth(pid) {
20782
21209
  async function claudeHostProcess({
20783
21210
  pid = process.pid,
20784
21211
  env = process.env,
20785
- home = homedir2(),
21212
+ home = homedir3(),
20786
21213
  readBirth = processBirth,
20787
21214
  readExecutable = stat,
20788
21215
  readBoot = async () => (await bounded("/proc/sys/kernel/random/boot_id")).toString().trim(),
@@ -20798,8 +21225,8 @@ async function claudeHostProcess({
20798
21225
  if (visited.has(child.ppid)) return null;
20799
21226
  visited.add(child.ppid);
20800
21227
  const host = await readBirth(child.ppid);
20801
- const roots2 = [path5.join(home, ".claude", "remote", "ccd-cli"), path5.join(home, ".local", "share", "claude", "versions")];
20802
- if (roots2.some((root) => path5.dirname(host.exe) === root)) {
21228
+ const roots2 = [path6.join(home, ".claude", "remote", "ccd-cli"), path6.join(home, ".local", "share", "claude", "versions")];
21229
+ if (roots2.some((root) => path6.dirname(host.exe) === root)) {
20803
21230
  const executable = await readExecutable(host.exe);
20804
21231
  if (host.uid !== uid || ![uid, 0].includes(executable.uid) || !executable.isFile() || executable.mode & 18 || host.inode !== executable.ino || host.device !== executable.dev) return null;
20805
21232
  if (purpose === "hook") {
@@ -20807,7 +21234,7 @@ async function claudeHostProcess({
20807
21234
  if (!entryFile || !command2.some((arg) => arg.includes(entryFile)) || !command2.some((arg) => arg === "claude-host-hook" || arg.includes(" claude-host-hook"))) return null;
20808
21235
  }
20809
21236
  const binding = { pid: host.pid, birth: host.birth, uid, device: host.device, inode: host.inode, exe: host.exe, boot };
20810
- const digest5 = hash(binding);
21237
+ const digest5 = hash2(binding);
20811
21238
  return { binding, digest: digest5, eventOrder: { birth: child.birth, pid: child.pid }, async isCurrent() {
20812
21239
  try {
20813
21240
  const current = await readBirth(binding.pid);
@@ -20836,22 +21263,22 @@ var canonical = (value2) => {
20836
21263
  return "{" + Object.keys(value2).sort().map((key) => JSON.stringify(key) + ":" + canonical(value2[key])).join(",") + "}";
20837
21264
  throw error2("request_invalid");
20838
21265
  };
20839
- var digest2 = (value2) => createHash4("sha256").update(canonical(value2)).digest("hex");
21266
+ var digest2 = (value2) => createHash5("sha256").update(canonical(value2)).digest("hex");
20840
21267
  var withoutProof = (args2) => Object.fromEntries(Object.entries(args2 ?? {}).filter(([key]) => key !== CLAUDE_HOST_PROOF));
20841
21268
  var later = (a, b2) => BigInt(a.birth) > BigInt(b2.birth) || a.birth === b2.birth && a.pid > b2.pid;
20842
- async function privateDirectory(directory2) {
21269
+ async function privateDirectory(directory3) {
20843
21270
  try {
20844
- await mkdir3(directory2, { mode: 448 });
21271
+ await mkdir4(directory3, { mode: 448 });
20845
21272
  } catch (e) {
20846
21273
  if (e.code !== "EEXIST") throw e;
20847
21274
  }
20848
- const info5 = await lstat4(directory2);
21275
+ const info5 = await lstat5(directory3);
20849
21276
  if (!info5.isDirectory() || info5.isSymbolicLink() || info5.uid !== process.getuid?.() || info5.mode & 63) throw error2("host_identity_unavailable");
20850
21277
  }
20851
21278
  async function privateRead(file) {
20852
21279
  let handle;
20853
21280
  try {
20854
- handle = await open4(file, constants3.O_RDONLY | constants3.O_NOFOLLOW);
21281
+ handle = await open5(file, constants4.O_RDONLY | constants4.O_NOFOLLOW);
20855
21282
  const info5 = await handle.stat();
20856
21283
  if (!info5.isFile() || info5.uid !== process.getuid?.() || info5.mode & 63 || info5.size > 196608) throw error2("host_identity_unavailable");
20857
21284
  return JSON.parse(await handle.readFile("utf8"));
@@ -20864,9 +21291,9 @@ async function privateRead(file) {
20864
21291
  }
20865
21292
  async function createClaudeHostSession({ configFile: configFile2, env = process.env, root, association, hookProcess = false } = {}) {
20866
21293
  const owner = association === void 0 ? await claudeHostProcess({ env, purpose: hookProcess ? "hook" : "bridge" }) : association;
20867
- const base = root ?? path6.join(env.CLAUDE_CONFIG_DIR ?? path6.join(homedir3(), ".claude"), "promptframe-host-sessions");
20868
- const namespace = owner ? path6.join(base, digest2([owner.digest, path6.resolve(configFile2)])) : null;
20869
- const stateFile = namespace && path6.join(namespace, "state.json");
21294
+ const base = root ?? path7.join(env.CLAUDE_CONFIG_DIR ?? path7.join(homedir4(), ".claude"), "promptframe-host-sessions");
21295
+ const namespace = owner ? path7.join(base, digest2([owner.digest, path7.resolve(configFile2)])) : null;
21296
+ const stateFile = namespace && path7.join(namespace, "state.json");
20870
21297
  async function state() {
20871
21298
  if (!owner || !await owner.isCurrent()) return null;
20872
21299
  const value2 = await privateRead(stateFile);
@@ -20878,10 +21305,10 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
20878
21305
  if (!owner || !await owner.isCurrent()) throw error2("host_identity_unavailable");
20879
21306
  await privateDirectory(base);
20880
21307
  await privateDirectory(namespace);
20881
- const lock = path6.join(namespace, "write.lock");
21308
+ const lock = path7.join(namespace, "write.lock");
20882
21309
  let acquired = false;
20883
21310
  for (let count = 0; count < 100; count++) try {
20884
- await mkdir3(lock, { mode: 448 });
21311
+ await mkdir4(lock, { mode: 448 });
20885
21312
  acquired = true;
20886
21313
  break;
20887
21314
  } catch (e) {
@@ -20895,13 +21322,13 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
20895
21322
  const current = await state(), next = await work(current);
20896
21323
  if (next === void 0) return;
20897
21324
  if (next === null) {
20898
- if (current) await unlink3(stateFile);
21325
+ if (current) await unlink4(stateFile);
20899
21326
  return;
20900
21327
  }
20901
21328
  const body = JSON.stringify(next);
20902
21329
  if (Buffer.byteLength(body) > 196608) throw error2("host_identity_unavailable");
20903
- temporary = path6.join(namespace, "state-" + randomBytes3(16).toString("hex") + ".partial");
20904
- const file = await open4(temporary, constants3.O_WRONLY | constants3.O_CREAT | constants3.O_EXCL | constants3.O_NOFOLLOW, 384);
21330
+ temporary = path7.join(namespace, "state-" + randomBytes3(16).toString("hex") + ".partial");
21331
+ const file = await open5(temporary, constants4.O_WRONLY | constants4.O_CREAT | constants4.O_EXCL | constants4.O_NOFOLLOW, 384);
20905
21332
  try {
20906
21333
  await file.writeFile(body);
20907
21334
  await file.sync();
@@ -20909,16 +21336,16 @@ async function createClaudeHostSession({ configFile: configFile2, env = process.
20909
21336
  await file.close();
20910
21337
  }
20911
21338
  if (!await owner.isCurrent()) throw error2("host_identity_unavailable");
20912
- await rename3(temporary, stateFile);
21339
+ await rename4(temporary, stateFile);
20913
21340
  temporary = void 0;
20914
- const directory2 = await open4(namespace, constants3.O_RDONLY | constants3.O_DIRECTORY | constants3.O_NOFOLLOW);
21341
+ const directory3 = await open5(namespace, constants4.O_RDONLY | constants4.O_DIRECTORY | constants4.O_NOFOLLOW);
20915
21342
  try {
20916
- await directory2.sync();
21343
+ await directory3.sync();
20917
21344
  } finally {
20918
- await directory2.close();
21345
+ await directory3.close();
20919
21346
  }
20920
21347
  } finally {
20921
- if (temporary) await unlink3(temporary).catch(() => {
21348
+ if (temporary) await unlink4(temporary).catch(() => {
20922
21349
  });
20923
21350
  await rmdir2(lock);
20924
21351
  }
@@ -21022,18 +21449,18 @@ async function runClaudeHostHook({ configFile: configFile2, input = process.stdi
21022
21449
  }
21023
21450
 
21024
21451
  // lib/development-pairing.mjs
21025
- import { open as open5, stat as stat2 } from "node:fs/promises";
21026
- import { constants as constants4 } from "node:fs";
21027
- import path7 from "node:path";
21452
+ import { open as open6, stat as stat2 } from "node:fs/promises";
21453
+ import { constants as constants5 } from "node:fs";
21454
+ import path8 from "node:path";
21028
21455
  async function readDevelopmentPairingFile(filePath, { signal } = {}) {
21029
21456
  const fail8 = () => {
21030
21457
  throw new CreationClientError("creation.development_pairing.private_file_unavailable");
21031
21458
  };
21032
- if (typeof filePath !== "string" || filePath.length > 4096 || !path7.isAbsolute(filePath)) fail8();
21459
+ if (typeof filePath !== "string" || filePath.length > 4096 || !path8.isAbsolute(filePath)) fail8();
21033
21460
  let file;
21034
21461
  try {
21035
21462
  signal?.throwIfAborted();
21036
- file = await open5(filePath, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
21463
+ file = await open6(filePath, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
21037
21464
  const before = await file.stat();
21038
21465
  if (!before.isFile() || before.size < 2 || before.size > 8192 || process.platform !== "win32" && ((before.mode & 63) !== 0 || before.uid !== process.getuid())) fail8();
21039
21466
  const bytes2 = Buffer.alloc(before.size);
@@ -21060,7 +21487,7 @@ async function readDevelopmentPairingFile(filePath, { signal } = {}) {
21060
21487
  // lib/host-context.mjs
21061
21488
  var digestPattern = /^sha256:[a-f0-9]{64}$/;
21062
21489
  var accesses = /* @__PURE__ */ new Set(["independent-read", "controlled", "authority"]);
21063
- var digest3 = (value2) => "sha256:" + createHash5("sha256").update(value2).digest("hex");
21490
+ var digest3 = (value2) => "sha256:" + createHash6("sha256").update(value2).digest("hex");
21064
21491
  var canonical2 = (value2) => {
21065
21492
  if (value2 === null || typeof value2 === "string" || typeof value2 === "boolean" || typeof value2 === "number" && Number.isFinite(value2)) return JSON.stringify(value2);
21066
21493
  if (Array.isArray(value2)) return "[" + value2.map(canonical2).join(",") + "]";
@@ -21073,6 +21500,20 @@ var boundedSet = (map, key, value2) => {
21073
21500
  if (!map.has(key) && map.size >= 1024) map.delete(map.keys().next().value);
21074
21501
  map.set(key, value2);
21075
21502
  };
21503
+ async function resolveHostCallBinding(raw, { host = resolveHostIdentity(), hostSession } = {}) {
21504
+ for (const field of ["threadId", "controller", "clientDigest", "token", "controlVersion", "developmentPairing"]) if (Object.hasOwn(raw.arguments ?? {}, field))
21505
+ throw new CreationClientError("creation.transport_authority_managed_by_bridge");
21506
+ if (host.kind === "claude-code") {
21507
+ if (hostSession) return hostSession.begin(raw);
21508
+ if (raw.arguments?.[CLAUDE_HOST_PROOF] !== void 0) throw new CreationClientError("creation.host_identity_invalid");
21509
+ return { host: { kind: "claude-code" }, arguments: raw.arguments, assertCurrent: async () => {
21510
+ } };
21511
+ }
21512
+ if (Object.hasOwn(raw.arguments ?? {}, CLAUDE_HOST_PROOF)) throw new CreationClientError("creation.transport_authority_managed_by_bridge");
21513
+ hostParameters(raw, host, "independent-read");
21514
+ return { host, arguments: raw.arguments, assertCurrent: async () => {
21515
+ } };
21516
+ }
21076
21517
  function createHostCallBridge(client, { credentials, host = resolveHostIdentity(), hostSession, localUploads, onCatalogChange = () => {
21077
21518
  }, onKnowledgeChange = () => {
21078
21519
  } } = {}) {
@@ -21080,7 +21521,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
21080
21521
  const installationDigest = digest3(credentials.clientId);
21081
21522
  const versions = /* @__PURE__ */ new Map(), controllers = /* @__PURE__ */ new Map(), catalogs = /* @__PURE__ */ new Map(), inflight = /* @__PURE__ */ new Map();
21082
21523
  const knowledgeVersions = /* @__PURE__ */ new Map(), upstream = client.getServerCapabilities?.() ?? {};
21083
- let platformDigest, accountDigest, directory2, directoryRead, sequence = 0, hostEpoch;
21524
+ let platformDigest, accountDigest, directory3, directoryRead, sequence = 0, hostEpoch;
21084
21525
  function catalog(channel, version3, order) {
21085
21526
  if (typeof version3 !== "string" || !digestPattern.test(version3)) return;
21086
21527
  const old = catalogs.get(channel);
@@ -21115,7 +21556,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
21115
21556
  const key = keyFor(target), c = v2.control;
21116
21557
  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;
21117
21558
  const old = versions.get(key), version3 = c.controlVersion, owned = c.editor.kind === "client" && c.editor.isCurrentClient;
21118
- const authorityRead = directory2?.tools.get(params.name)?._meta?.["promptframe.role"] === "control-read";
21559
+ const authorityRead = directory3?.tools.get(params.name)?._meta?.["promptframe.role"] === "control-read";
21119
21560
  if (!old || version3 > old.version) boundedSet(versions, key, { version: version3, owned, needsRead: false, authorityOrder: order });
21120
21561
  else if (version3 === old.version && order >= (old.authorityOrder ?? 0)) {
21121
21562
  const freshRead = !result.isError && authorityRead && order > (old.invalidatedAt ?? 0);
@@ -21133,7 +21574,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
21133
21574
  async function listTools() {
21134
21575
  const order = ++sequence, result = assertMcpResponseBudget(await client.listTools());
21135
21576
  if (result.tools.some((tool) => !accesses.has(tool._meta?.["promptframe.access"]))) throw new CreationClientError("creation.upgrade_required");
21136
- if (!directory2 || order >= directory2.order) directory2 = { tools: new Map(result.tools.map((t) => [t.name, t])), order };
21577
+ if (!directory3 || order >= directory3.order) directory3 = { tools: new Map(result.tools.map((t) => [t.name, t])), order };
21137
21578
  catalog("outer", result._meta?.["promptframe.catalogVersion"], order);
21138
21579
  return { ...result, tools: result.tools.map((tool) => {
21139
21580
  const local = tool._meta?.["promptframe.localFileUpload"];
@@ -21147,7 +21588,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
21147
21588
  }) };
21148
21589
  }
21149
21590
  async function ensureDirectory() {
21150
- if (!directory2) {
21591
+ if (!directory3) {
21151
21592
  directoryRead ??= listTools().finally(() => {
21152
21593
  directoryRead = void 0;
21153
21594
  });
@@ -21155,7 +21596,7 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
21155
21596
  }
21156
21597
  }
21157
21598
  function role(name) {
21158
- const found = [...directory2.tools.values()].filter((t) => t._meta?.["promptframe.role"] === name);
21599
+ const found = [...directory3.tools.values()].filter((t) => t._meta?.["promptframe.role"] === name);
21159
21600
  if (found.length !== 1) throw new CreationClientError("creation.upgrade_required");
21160
21601
  return found[0].name;
21161
21602
  }
@@ -21202,27 +21643,23 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
21202
21643
  listPrompts: (params) => knowledgeRead("prompts", "listPrompts", params),
21203
21644
  getPrompt: (params) => knowledgeRead("prompts", "getPrompt", params),
21204
21645
  close: () => localUploads?.close(),
21205
- async call(raw, { signal } = {}) {
21646
+ async call(raw, { signal, resolvedBinding } = {}) {
21206
21647
  for (const field of ["threadId", "controller", "clientDigest", "token", "controlVersion", "developmentPairing"]) if (Object.hasOwn(raw.arguments ?? {}, field))
21207
21648
  throw new CreationClientError("creation.transport_authority_managed_by_bridge");
21208
- let binding = { host, arguments: raw.arguments, assertCurrent: async () => {
21209
- } };
21649
+ const binding = resolvedBinding ?? await resolveHostCallBinding(raw, { host, hostSession });
21650
+ if (binding.host.kind !== host.kind) throw new CreationClientError("creation.host_identity_invalid");
21210
21651
  if (host.kind === "claude-code") {
21211
- if (hostSession) binding = await hostSession.begin(raw);
21212
- else if (raw.arguments?.[CLAUDE_HOST_PROOF] !== void 0) throw new CreationClientError("creation.host_identity_invalid");
21213
- else binding = { host: { kind: "claude-code" }, arguments: raw.arguments, assertCurrent: async () => {
21214
- } };
21215
21652
  if (binding.epoch !== hostEpoch) {
21216
21653
  versions.clear();
21217
21654
  controllers.clear();
21218
21655
  inflight.clear();
21219
21656
  hostEpoch = binding.epoch;
21220
21657
  }
21221
- } else if (Object.hasOwn(raw.arguments ?? {}, CLAUDE_HOST_PROOF)) throw new CreationClientError("creation.transport_authority_managed_by_bridge");
21658
+ }
21222
21659
  raw = { ...raw, arguments: binding.arguments };
21223
21660
  await ensureDirectory();
21224
21661
  await binding.assertCurrent();
21225
- const definition = directory2.tools.get(raw.name);
21662
+ const definition = directory3.tools.get(raw.name);
21226
21663
  if (!definition) throw new CreationClientError("creation.tool_unavailable");
21227
21664
  const access2 = definition._meta["promptframe.access"], managed = Object.hasOwn(definition.inputSchema.properties ?? {}, "controlVersion");
21228
21665
  let params = hostParameters(raw, binding.host, "independent-read");
@@ -21303,9 +21740,9 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
21303
21740
  let response;
21304
21741
  try {
21305
21742
  response = await send(outgoing, binding);
21306
- } catch (error4) {
21743
+ } catch (error5) {
21307
21744
  invalidate();
21308
- throw error4;
21745
+ throw error5;
21309
21746
  }
21310
21747
  if (response.result.isError) invalidate();
21311
21748
  return response.result;
@@ -21313,8 +21750,168 @@ function createHostCallBridge(client, { credentials, host = resolveHostIdentity(
21313
21750
  };
21314
21751
  }
21315
21752
 
21753
+ // lib/account-bridge.mjs
21754
+ var listName = "promptframe_local_accounts";
21755
+ var selectName = "promptframe_local_select_account";
21756
+ var error3 = (code) => new CreationClientError("accounts." + code);
21757
+ var sameIdentity = (a, b2) => a && b2 && localAccountKey(a) === localAccountKey(b2);
21758
+ function identityFromKey(key) {
21759
+ if (typeof key !== "string" || !/^[a-f0-9]{64}-[a-f0-9]{64}$/.test(key)) throw error3("identity_invalid");
21760
+ return {
21761
+ contractVersion: "promptframe-account-identity/v1",
21762
+ platformDigest: "sha256:" + key.slice(0, 64),
21763
+ accountDigest: "sha256:" + key.slice(65)
21764
+ };
21765
+ }
21766
+ function localTool(name, host) {
21767
+ const properties = name === selectName ? {
21768
+ identityKey: { type: "string", pattern: "^[a-f0-9]{64}-[a-f0-9]{64}$" },
21769
+ referenceId: { type: "string", pattern: "^sha256:[a-f0-9]{64}$", description: "\u540C\u4E00\u8D26\u53F7\u6709\u591A\u4EFD\u521B\u4F5C\u6388\u6743\u65F6\u53EF\u660E\u786E\u9009\u62E9\u5217\u8868\u4E2D\u7684\u5F15\u7528\u3002" }
21770
+ } : {};
21771
+ if (host.kind === "claude-code") properties[CLAUDE_HOST_PROOF] = { type: "string", pattern: "^[a-f0-9]{64}$", description: "\u7531\u5F53\u524D\u5BBF\u4E3Bhook\u586B\u5165\uFF0C\u4FDD\u7559\u539F\u503C\u3002" };
21772
+ return {
21773
+ name,
21774
+ description: name === listName ? "\u5217\u51FA\u672C\u673A\u5DF2\u767B\u8BB0\u8D26\u53F7\u7684\u5B89\u5168\u6458\u8981\u548C\u7F3A\u5C11\u7684\u6388\u6743\u7C7B\u578B\uFF0C\u4E0D\u8FD4\u56DE\u51ED\u636E\u6216\u672C\u673A\u8DEF\u5F84\u3002" : "\u53EA\u4E3A\u5F53\u524D\u5BBF\u4E3B\u4F1A\u8BDD\u9009\u62E9\u672C\u673A\u5DF2\u6388\u6743\u8D26\u53F7\uFF1B\u4E0D\u5207\u6362\u5176\u5B83Agent\uFF0C\u4E0D\u7533\u8BF7\u7F16\u8F91\u6743\u6216\u91CD\u653E\u4E1A\u52A1\u3002",
21775
+ inputSchema: { type: "object", properties, additionalProperties: false, ...name === selectName ? { required: ["identityKey"] } : {} },
21776
+ annotations: { readOnlyHint: name === listName, destructiveHint: false, openWorldHint: false }
21777
+ };
21778
+ }
21779
+ function createAccountAwareBridge(defaultClient, {
21780
+ credentials,
21781
+ configFile: configFile2,
21782
+ host,
21783
+ hostSession,
21784
+ root = localAccountsRoot(),
21785
+ connect = connectPlatform,
21786
+ connectionOptions = {},
21787
+ localUploads,
21788
+ createLocalUploads,
21789
+ onCatalogChange = () => {
21790
+ },
21791
+ onKnowledgeChange = () => {
21792
+ }
21793
+ } = {}) {
21794
+ const primaryIdentity = connectionAccountIdentity(defaultClient), contexts = /* @__PURE__ */ new Map(), preferences = /* @__PURE__ */ new Map();
21795
+ let switched = false;
21796
+ const makeBridge = (client, creds, uploads) => createHostCallBridge(client, {
21797
+ credentials: creds,
21798
+ host,
21799
+ localUploads: uploads,
21800
+ onCatalogChange,
21801
+ onKnowledgeChange
21802
+ });
21803
+ const primary = { client: defaultClient, bridge: makeBridge(defaultClient, credentials, localUploads), identity: primaryIdentity, owned: false };
21804
+ function caller(raw, binding, required2 = false) {
21805
+ const params = { ...raw, arguments: binding.arguments };
21806
+ hostParameters(params, binding.host, required2 ? "authority" : "independent-read");
21807
+ const sessionId = binding.host.kind === "claude-code" ? binding.host.threadId : params._meta?.threadId;
21808
+ return sessionId ? { kind: binding.host.kind, sessionId } : void 0;
21809
+ }
21810
+ async function context(identity, agent, referenceId) {
21811
+ if (sameIdentity(identity, primaryIdentity) && (!referenceId || referenceId === localReferenceId("creation", path9.resolve(configFile2)))) return primary;
21812
+ const refs = await readLocalAuthorizations({ root, identity, client: "creation" });
21813
+ if (!refs.length) throw error3("creation_authorization_missing");
21814
+ let ref = referenceId ? refs.find((value2) => value2.referenceId === referenceId) : refs.length === 1 ? refs[0] : void 0;
21815
+ if (!ref) throw error3(referenceId ? "reference_unavailable" : "authorization_ambiguous");
21816
+ if (ref.expiresAt && Date.parse(ref.expiresAt) <= Date.now()) throw error3("authorization_expired");
21817
+ const key = [localAccountKey(identity), ref.referenceId, localAgentDigest(agent)].join("|");
21818
+ if (!contexts.has(key)) {
21819
+ const pending = (async () => {
21820
+ const saved = await readCredentials(ref.configFile);
21821
+ if (!saved || localCredentialDigest(saved.token) !== ref.credentialDigest || normalizeEndpoint(saved.endpoint) !== normalizeEndpoint(ref.endpoint)) throw error3("reference_changed");
21822
+ const client = await connect(saved, { ...connectionOptions, host, expectedIdentity: identity });
21823
+ try {
21824
+ connectionAccountIdentity(client, identity);
21825
+ return { client, bridge: makeBridge(client, saved, createLocalUploads?.({ identity, agent, configFile: ref.configFile })), identity, owned: true };
21826
+ } catch (cause) {
21827
+ await client.close().catch(() => {
21828
+ });
21829
+ throw cause;
21830
+ }
21831
+ })();
21832
+ contexts.set(key, pending);
21833
+ pending.catch(() => {
21834
+ if (contexts.get(key) === pending) contexts.delete(key);
21835
+ });
21836
+ }
21837
+ return contexts.get(key);
21838
+ }
21839
+ async function selected(raw, binding) {
21840
+ const agent = caller(raw, binding);
21841
+ if (!agent) {
21842
+ if (switched) throw new CreationClientError("creation.host_identity_required");
21843
+ return { entry: primary };
21844
+ }
21845
+ const choice = await readSelectedLocalAccount({ root, agent });
21846
+ if (!choice) return { entry: primary, agent };
21847
+ const preference = preferences.get(localAgentDigest(agent));
21848
+ const referenceId = preference?.generation === choice.generation ? preference.referenceId : void 0;
21849
+ return { entry: await context(choice.identity, agent, referenceId), agent, choice };
21850
+ }
21851
+ async function knowledge(method, raw = {}) {
21852
+ const binding = await resolveHostCallBinding(raw, { host, hostSession });
21853
+ await binding.assertCurrent();
21854
+ const { entry } = await selected(raw, binding);
21855
+ return entry.bridge[method]({ ...raw, arguments: binding.arguments });
21856
+ }
21857
+ return {
21858
+ knowledgeCapabilities: primary.bridge.knowledgeCapabilities,
21859
+ async listTools(raw = {}) {
21860
+ let entry = primary;
21861
+ if (host.kind === "codex" && raw._meta?.threadId) {
21862
+ const binding = await resolveHostCallBinding(raw, { host, hostSession });
21863
+ entry = (await selected(raw, binding)).entry;
21864
+ }
21865
+ const directory3 = await entry.bridge.listTools();
21866
+ if (directory3.tools.some((tool) => [listName, selectName].includes(tool.name))) throw error3("tool_name_conflict");
21867
+ return { ...directory3, tools: [...directory3.tools, localTool(listName, host), localTool(selectName, host)] };
21868
+ },
21869
+ listResources: (raw) => knowledge("listResources", raw),
21870
+ listResourceTemplates: (raw) => knowledge("listResourceTemplates", raw),
21871
+ readResource: (raw) => knowledge("readResource", raw),
21872
+ listPrompts: (raw) => knowledge("listPrompts", raw),
21873
+ getPrompt: (raw) => knowledge("getPrompt", raw),
21874
+ async call(raw, options = {}) {
21875
+ const binding = await resolveHostCallBinding(raw, { host, hostSession });
21876
+ await binding.assertCurrent();
21877
+ if (raw.name === listName || raw.name === selectName) {
21878
+ const input = binding.arguments ?? {}, allowed = raw.name === selectName ? ["identityKey", "referenceId"] : [];
21879
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key) => !allowed.includes(key))) throw error3("request_invalid");
21880
+ let value2;
21881
+ if (raw.name === listName) value2 = await listLocalAccounts({ root });
21882
+ else {
21883
+ const agent = caller(raw, binding, true), identity = identityFromKey(input.identityKey);
21884
+ if (!agent) throw error3("agent_required");
21885
+ if (input.referenceId !== void 0 && (typeof input.referenceId !== "string" || !/^sha256:[a-f0-9]{64}$/.test(input.referenceId))) throw error3("reference_invalid");
21886
+ await context(identity, agent, input.referenceId);
21887
+ await binding.assertCurrent();
21888
+ const choice = await selectLocalAccount({ root, agent, identity });
21889
+ await binding.assertCurrent();
21890
+ preferences.set(localAgentDigest(agent), { generation: choice.generation, referenceId: input.referenceId });
21891
+ switched = true;
21892
+ Promise.resolve().then(onCatalogChange).catch(() => {
21893
+ });
21894
+ value2 = { selected: true, identityKey: localAccountKey(identity), identity, generation: choice.generation, otherAgentsChanged: 0 };
21895
+ }
21896
+ return { content: [{ type: "text", text: JSON.stringify(value2) }] };
21897
+ }
21898
+ const { entry } = await selected(raw, binding);
21899
+ await binding.assertCurrent();
21900
+ return entry.bridge.call({ ...raw, arguments: binding.arguments }, { ...options, resolvedBinding: binding });
21901
+ },
21902
+ async close() {
21903
+ await primary.bridge.close();
21904
+ for (const result of await Promise.allSettled(contexts.values())) if (result.status === "fulfilled") {
21905
+ await result.value.bridge.close();
21906
+ await result.value.client.close().catch(() => {
21907
+ });
21908
+ }
21909
+ }
21910
+ };
21911
+ }
21912
+
21316
21913
  // lib/runtime-bootstrap.mjs
21317
- import { createHash as createHash7, randomBytes as randomBytes4 } from "node:crypto";
21914
+ import { createHash as createHash8, randomBytes as randomBytes4 } from "node:crypto";
21318
21915
  import { gunzipSync } from "node:zlib";
21319
21916
 
21320
21917
  // node_modules/tar/dist/esm/index.min.js
@@ -24287,28 +24884,28 @@ var To = (s3) => {
24287
24884
  };
24288
24885
 
24289
24886
  // lib/runtime-bootstrap.mjs
24290
- import { lstat as lstat6, mkdir as mkdir4, open as open6, readFile as readFile5, readdir as readdir3, rename as rename4, rm, statfs } from "node:fs/promises";
24887
+ import { lstat as lstat7, mkdir as mkdir5, open as open7, readFile as readFile5, readdir as readdir3, rename as rename5, rm, statfs } from "node:fs/promises";
24291
24888
  import { execFile } from "node:child_process";
24292
24889
  import { promisify } from "node:util";
24293
- import path9 from "node:path";
24890
+ import path11 from "node:path";
24294
24891
 
24295
24892
  // lib/runtime-package.mjs
24296
- import { lstat as lstat5, readdir as readdir2, readFile as readFile4 } from "node:fs/promises";
24297
- import { createHash as createHash6 } from "node:crypto";
24298
- import path8 from "node:path";
24893
+ import { lstat as lstat6, readdir as readdir2, readFile as readFile4 } from "node:fs/promises";
24894
+ import { createHash as createHash7 } from "node:crypto";
24895
+ import path10 from "node:path";
24299
24896
  var RUNTIME_PACKAGE_ENTRIES = Object.freeze(["package.json", "README.md", "LICENSE", "bin", "dist", "lib", "skills", "docs", ".codex-plugin", ".mcp.json"]);
24300
24897
  var OPTIONAL_HOST_ENTRIES = Object.freeze([".claude-plugin", ".claude-mcp.json"]);
24301
- var hash2 = (b2) => createHash6("sha256").update(b2).digest("hex");
24898
+ var hash3 = (b2) => createHash7("sha256").update(b2).digest("hex");
24302
24899
  var invalid = (code) => {
24303
24900
  throw new CreationClientError("installation." + code);
24304
24901
  };
24305
- async function inspectRuntimePackage(root, { entries } = {}) {
24306
- if (!entries) {
24307
- entries = [...RUNTIME_PACKAGE_ENTRIES];
24902
+ async function inspectRuntimePackage(root, { entries: entries2 } = {}) {
24903
+ if (!entries2) {
24904
+ entries2 = [...RUNTIME_PACKAGE_ENTRIES];
24308
24905
  for (const name of OPTIONAL_HOST_ENTRIES) {
24309
24906
  try {
24310
- await lstat5(path8.join(root, name));
24311
- entries.push(name);
24907
+ await lstat6(path10.join(root, name));
24908
+ entries2.push(name);
24312
24909
  } catch (e) {
24313
24910
  if (e.code !== "ENOENT") throw e;
24314
24911
  }
@@ -24319,25 +24916,25 @@ async function inspectRuntimePackage(root, { entries } = {}) {
24319
24916
  async function walk(relative) {
24320
24917
  let s3;
24321
24918
  try {
24322
- s3 = await lstat5(path8.join(root, relative));
24323
- } catch (error4) {
24324
- if (error4.code !== "ENOENT") throw error4;
24919
+ s3 = await lstat6(path10.join(root, relative));
24920
+ } catch (error5) {
24921
+ if (error5.code !== "ENOENT") throw error5;
24325
24922
  }
24326
24923
  if (!s3 || s3.isSymbolicLink()) invalid("package_file_invalid");
24327
24924
  if (s3.isDirectory()) {
24328
- for (const name of (await readdir2(path8.join(root, relative))).sort()) {
24925
+ for (const name of (await readdir2(path10.join(root, relative))).sort()) {
24329
24926
  if (name === "node_modules" || name === "credentials.json" || name.startsWith(".env")) invalid("package_file_invalid");
24330
- await walk(path8.join(relative, name));
24927
+ await walk(path10.join(relative, name));
24331
24928
  }
24332
24929
  } else if (s3.isFile()) {
24333
24930
  if (s3.size > 32 * 1024 * 1024) invalid("package_too_large");
24334
- const body = await readFile4(path8.join(root, relative));
24931
+ const body = await readFile4(path10.join(root, relative));
24335
24932
  bytes2 += body.length;
24336
24933
  if (files.length >= 1024 || bytes2 > 32 * 1024 * 1024) invalid("package_too_large");
24337
- files.push({ path: relative, bytes: body.length, sha256: hash2(body), body });
24934
+ files.push({ path: relative, bytes: body.length, sha256: hash3(body), body });
24338
24935
  } else invalid("package_file_invalid");
24339
24936
  }
24340
- for (const name of entries) await walk(name);
24937
+ for (const name of entries2) await walk(name);
24341
24938
  for (const name of ["dist/cli.mjs", "dist/THIRD_PARTY_NOTICES.txt", "skills/creation-setup/SKILL.md", "skills/video-creation/SKILL.md"])
24342
24939
  if (!files.some((f2) => f2.path === name)) invalid("package_incomplete");
24343
24940
  const pkg = JSON.parse(files.find((f2) => f2.path === "package.json").body), plugin = JSON.parse(files.find((f2) => f2.path === ".codex-plugin/plugin.json").body);
@@ -24348,7 +24945,7 @@ async function inspectRuntimePackage(root, { entries } = {}) {
24348
24945
  files,
24349
24946
  version: pkg.version,
24350
24947
  hosts: claude ? ["codex", "claude-code"] : ["codex"],
24351
- payloadDigest: hash2(JSON.stringify(files.map(({ path: path18, bytes: bytes3, sha256 }) => ({ path: path18, bytes: bytes3, sha256 }))))
24948
+ payloadDigest: hash3(JSON.stringify(files.map(({ path: path20, bytes: bytes3, sha256 }) => ({ path: path20, bytes: bytes3, sha256 }))))
24352
24949
  };
24353
24950
  }
24354
24951
 
@@ -24358,9 +24955,9 @@ var REGISTRY = "https://registry.npmjs.org";
24358
24955
  var MAX_ARCHIVE = 8 * 1024 * 1024;
24359
24956
  var MAX_PAYLOAD = 32 * 1024 * 1024;
24360
24957
  var MAX_TAR = 36 * 1024 * 1024;
24361
- var hash3 = (b2) => createHash7("sha256").update(b2).digest("hex");
24958
+ var hash4 = (b2) => createHash8("sha256").update(b2).digest("hex");
24362
24959
  var execute = promisify(execFile);
24363
- var error3 = (code) => new CreationClientError("creation." + code);
24960
+ var error4 = (code) => new CreationClientError("creation." + code);
24364
24961
  var version2 = (v2) => {
24365
24962
  compareBridgeVersions(v2, v2);
24366
24963
  return v2;
@@ -24378,34 +24975,34 @@ var RuntimeSelectionError = class extends CreationClientError {
24378
24975
  });
24379
24976
  }
24380
24977
  };
24381
- var runtimeErrorDetails = (error4) => error4 instanceof RuntimeSelectionError ? error4.runtimeFacts : void 0;
24978
+ var runtimeErrorDetails = (error5) => error5 instanceof RuntimeSelectionError ? error5.runtimeFacts : void 0;
24382
24979
  var snapshot = (payload) => ({
24383
24980
  version: payload.version,
24384
24981
  hosts: payload.hosts,
24385
24982
  payloadDigest: payload.payloadDigest,
24386
- files: payload.files.map(({ path: path18, bytes: bytes2, sha256 }) => ({ path: path18, bytes: bytes2, sha256 }))
24983
+ files: payload.files.map(({ path: path20, bytes: bytes2, sha256 }) => ({ path: path20, bytes: bytes2, sha256 }))
24387
24984
  });
24388
24985
  async function info(file) {
24389
24986
  try {
24390
- return await lstat6(file);
24987
+ return await lstat7(file);
24391
24988
  } catch (e) {
24392
24989
  if (e.code === "ENOENT") return null;
24393
24990
  throw e;
24394
24991
  }
24395
24992
  }
24396
24993
  async function privateDirectory2(dir) {
24397
- await mkdir4(dir, { recursive: true, mode: 448 });
24398
- const s3 = await lstat6(dir);
24399
- if (!s3.isDirectory() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63) throw error3("runtime_cache_owner_invalid");
24994
+ await mkdir5(dir, { recursive: true, mode: 448 });
24995
+ const s3 = await lstat7(dir);
24996
+ if (!s3.isDirectory() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63) throw error4("runtime_cache_owner_invalid");
24400
24997
  }
24401
24998
  async function privateJSON(file) {
24402
24999
  const s3 = await info(file);
24403
25000
  if (!s3) return null;
24404
- if (!s3.isFile() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63 || s3.size > 512 * 1024) throw error3("runtime_cache_invalid");
25001
+ if (!s3.isFile() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63 || s3.size > 512 * 1024) throw error4("runtime_cache_invalid");
24405
25002
  return JSON.parse(await readFile5(file, "utf8"));
24406
25003
  }
24407
25004
  async function syncDirectory2(dir) {
24408
- const fd = await open6(dir, "r");
25005
+ const fd = await open7(dir, "r");
24409
25006
  try {
24410
25007
  await fd.sync();
24411
25008
  } finally {
@@ -24413,7 +25010,7 @@ async function syncDirectory2(dir) {
24413
25010
  }
24414
25011
  }
24415
25012
  async function exclusiveJSON(file, value2) {
24416
- const fd = await open6(file, "wx", 384);
25013
+ const fd = await open7(file, "wx", 384);
24417
25014
  try {
24418
25015
  await fd.writeFile(JSON.stringify(value2) + "\n");
24419
25016
  await fd.sync();
@@ -24425,9 +25022,9 @@ function checkedRuntimeMetadata(value2, expectedVersion) {
24425
25022
  version2(expectedVersion);
24426
25023
  const tarball = REGISTRY + "/@promptframe/creation/-/creation-" + expectedVersion + ".tgz";
24427
25024
  if (value2?.name !== PACKAGE || value2.version !== expectedVersion || value2.dist?.tarball !== tarball || typeof value2.dist.integrity !== "string" || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(value2.dist.integrity))
24428
- throw error3("runtime_registry_identity_invalid");
25025
+ throw error4("runtime_registry_identity_invalid");
24429
25026
  const encoded = value2.dist.integrity.slice(7);
24430
- if (Buffer.from(encoded, "base64").toString("base64") !== encoded) throw error3("runtime_registry_identity_invalid");
25027
+ if (Buffer.from(encoded, "base64").toString("base64") !== encoded) throw error4("runtime_registry_identity_invalid");
24431
25028
  return { version: expectedVersion, integrity: value2.dist.integrity, tarball };
24432
25029
  }
24433
25030
  async function boundedGet(url2, { fetchImpl = fetch, signal, maxBytes: maxBytes2, timeoutMs }) {
@@ -24437,12 +25034,12 @@ async function boundedGet(url2, { fetchImpl = fetch, signal, maxBytes: maxBytes2
24437
25034
  let response;
24438
25035
  try {
24439
25036
  response = await fetchImpl(url2, { signal: controller.signal, redirect: "error" });
24440
- if (response.status !== 200 || Number(response.headers.get("content-length") ?? 0) > maxBytes2 || !response.body) throw error3("runtime_fetch_unavailable");
25037
+ if (response.status !== 200 || Number(response.headers.get("content-length") ?? 0) > maxBytes2 || !response.body) throw error4("runtime_fetch_unavailable");
24441
25038
  const chunks = [];
24442
25039
  let count = 0;
24443
25040
  for await (const chunk of response.body) {
24444
25041
  count += chunk.length;
24445
- if (count > maxBytes2) throw error3("runtime_download_capacity");
25042
+ if (count > maxBytes2) throw error4("runtime_download_capacity");
24446
25043
  chunks.push(Buffer.from(chunk));
24447
25044
  }
24448
25045
  return Buffer.concat(chunks, count);
@@ -24450,68 +25047,68 @@ async function boundedGet(url2, { fetchImpl = fetch, signal, maxBytes: maxBytes2
24450
25047
  await response?.body?.cancel().catch(() => {
24451
25048
  });
24452
25049
  if (e instanceof CreationClientError) throw e;
24453
- throw error3("runtime_fetch_unavailable");
25050
+ throw error4("runtime_fetch_unavailable");
24454
25051
  } finally {
24455
25052
  clearTimeout(timer);
24456
25053
  signal?.removeEventListener("abort", abort);
24457
25054
  }
24458
25055
  }
24459
25056
  async function readRuntimeArchive(archive, metadata) {
24460
- if (!Buffer.isBuffer(archive) || archive.length > MAX_ARCHIVE || "sha512-" + createHash7("sha512").update(archive).digest("base64") !== metadata.integrity) throw error3("runtime_integrity_invalid");
25057
+ if (!Buffer.isBuffer(archive) || archive.length > MAX_ARCHIVE || "sha512-" + createHash8("sha512").update(archive).digest("base64") !== metadata.integrity) throw error4("runtime_integrity_invalid");
24461
25058
  let raw;
24462
25059
  try {
24463
25060
  raw = gunzipSync(archive, { maxOutputLength: MAX_TAR });
24464
25061
  } catch {
24465
- throw error3("runtime_archive_invalid");
25062
+ throw error4("runtime_archive_invalid");
24466
25063
  }
24467
25064
  const files = [], names = /* @__PURE__ */ new Set();
24468
- let total = 0, entries = 0, failure3;
25065
+ let total = 0, entries2 = 0, failure4;
24469
25066
  const parser = Ct({ strict: true, onReadEntry: (entry) => {
24470
25067
  const name = entry.path;
24471
- 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");
25068
+ if (++entries2 > 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)) failure4 = error4("runtime_archive_invalid");
24472
25069
  const relative = name.slice(8).replace(/\/$/, "");
24473
25070
  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])))
24474
- failure3 = error3("runtime_archive_invalid");
25071
+ failure4 = error4("runtime_archive_invalid");
24475
25072
  const portableName = relative.toLowerCase();
24476
- if (names.has(portableName)) failure3 = error3("runtime_archive_invalid");
25073
+ if (names.has(portableName)) failure4 = error4("runtime_archive_invalid");
24477
25074
  names.add(portableName);
24478
25075
  if (entry.type === "Directory") {
24479
- if (entry.size !== 0) failure3 = error3("runtime_archive_invalid");
25076
+ if (entry.size !== 0) failure4 = error4("runtime_archive_invalid");
24480
25077
  return;
24481
25078
  }
24482
25079
  total += entry.size;
24483
- if (total > MAX_PAYLOAD || files.length >= 1024 || !relative) failure3 = error3("runtime_archive_capacity");
25080
+ if (total > MAX_PAYLOAD || files.length >= 1024 || !relative) failure4 = error4("runtime_archive_capacity");
24484
25081
  const chunks = [];
24485
25082
  let bytes2 = 0;
24486
25083
  entry.on("data", (chunk) => {
24487
25084
  bytes2 += chunk.length;
24488
- if (bytes2 > entry.size) failure3 = error3("runtime_archive_invalid");
24489
- if (!failure3) chunks.push(Buffer.from(chunk));
25085
+ if (bytes2 > entry.size) failure4 = error4("runtime_archive_invalid");
25086
+ if (!failure4) chunks.push(Buffer.from(chunk));
24490
25087
  });
24491
25088
  entry.on("end", () => {
24492
- if (bytes2 !== entry.size) failure3 = error3("runtime_archive_invalid");
24493
- if (!failure3) files.push({ path: relative, body: Buffer.concat(chunks, bytes2) });
25089
+ if (bytes2 !== entry.size) failure4 = error4("runtime_archive_invalid");
25090
+ if (!failure4) files.push({ path: relative, body: Buffer.concat(chunks, bytes2) });
24494
25091
  });
24495
25092
  } });
24496
25093
  await new Promise((resolve, reject) => {
24497
- parser.once("error", () => reject(error3("runtime_archive_invalid")));
25094
+ parser.once("error", () => reject(error4("runtime_archive_invalid")));
24498
25095
  parser.once("end", resolve);
24499
25096
  parser.end(raw);
24500
25097
  });
24501
- if (failure3) throw failure3;
24502
- if (!files.length || files.length > 1024) throw error3("runtime_archive_invalid");
25098
+ if (failure4) throw failure4;
25099
+ if (!files.length || files.length > 1024) throw error4("runtime_archive_invalid");
24503
25100
  return files;
24504
25101
  }
24505
25102
  async function cacheLock(root, signal) {
24506
- const name = path9.join(root, "prepare.lock"), end = Date.now() + 5e3;
25103
+ const name = path11.join(root, "prepare.lock"), end = Date.now() + 5e3;
24507
25104
  let fd;
24508
25105
  while (!fd) {
24509
25106
  signal?.throwIfAborted();
24510
25107
  try {
24511
- fd = await open6(name, "wx", 384);
25108
+ fd = await open7(name, "wx", 384);
24512
25109
  } catch (e) {
24513
25110
  if (e.code !== "EEXIST") throw e;
24514
- if (Date.now() >= end) throw error3("runtime_cache_busy");
25111
+ if (Date.now() >= end) throw error4("runtime_cache_busy");
24515
25112
  await pause(50);
24516
25113
  }
24517
25114
  }
@@ -24529,51 +25126,51 @@ async function cacheLock(root, signal) {
24529
25126
  return async () => {
24530
25127
  const now = await info(name);
24531
25128
  await fd.close();
24532
- if (!now || now.dev !== owned.dev || now.ino !== owned.ino) throw error3("runtime_lock_changed");
25129
+ if (!now || now.dev !== owned.dev || now.ino !== owned.ino) throw error4("runtime_lock_changed");
24533
25130
  await rm(name);
24534
25131
  };
24535
25132
  }
24536
25133
  async function verifyCached(target, metadata, hostKind) {
24537
25134
  if (!await info(target)) return null;
24538
25135
  await privateDirectory2(target);
24539
- const manifest = await privateJSON(path9.join(target, "runtime.json"));
25136
+ const manifest = await privateJSON(path11.join(target, "runtime.json"));
24540
25137
  if (!manifest || manifest.contractVersion !== "creation-verified-runtime/v1" || manifest.version !== metadata.version || manifest.integrity !== metadata.integrity)
24541
- throw error3("runtime_cache_invalid");
25138
+ throw error4("runtime_cache_invalid");
24542
25139
  const names = (await readdir3(target)).filter((name) => name !== "runtime.json").sort();
24543
- if (names.some((name) => !roots.has(name)) || RUNTIME_PACKAGE_ENTRIES.some((name) => !names.includes(name))) throw error3("runtime_cache_invalid");
25140
+ if (names.some((name) => !roots.has(name)) || RUNTIME_PACKAGE_ENTRIES.some((name) => !names.includes(name))) throw error4("runtime_cache_invalid");
24544
25141
  const payload = await inspectRuntimePackage(target, { entries: names });
24545
- if (!payload.hosts.includes(hostKind)) throw error3("runtime_host_unsupported");
24546
- if (JSON.stringify(snapshot(payload)) !== JSON.stringify(manifest.payload)) throw error3("runtime_cache_invalid");
25142
+ if (!payload.hosts.includes(hostKind)) throw error4("runtime_host_unsupported");
25143
+ if (JSON.stringify(snapshot(payload)) !== JSON.stringify(manifest.payload)) throw error4("runtime_cache_invalid");
24547
25144
  return { version: payload.version, root: target, integrity: metadata.integrity, reused: true };
24548
25145
  }
24549
25146
  async function checkedVersionIndex(cacheRoot, metadata) {
24550
- const old = await privateJSON(path9.join(cacheRoot, "version-" + metadata.version + ".json"));
24551
- if (old && JSON.stringify(old) !== JSON.stringify(metadata)) throw error3("runtime_registry_identity_conflict");
25147
+ const old = await privateJSON(path11.join(cacheRoot, "version-" + metadata.version + ".json"));
25148
+ if (old && JSON.stringify(old) !== JSON.stringify(metadata)) throw error4("runtime_registry_identity_conflict");
24552
25149
  return old;
24553
25150
  }
24554
25151
  async function prepareVerifiedRuntime(metadata, { cacheRoot, fetchImpl = fetch, signal, checkRuntime, hostKind = "codex" } = {}) {
24555
- if (!["codex", "claude-code"].includes(hostKind)) throw error3("runtime_host_unsupported");
24556
- if (!path9.isAbsolute(cacheRoot ?? "")) throw error3("runtime_cache_owner_invalid");
25152
+ if (!["codex", "claude-code"].includes(hostKind)) throw error4("runtime_host_unsupported");
25153
+ if (!path11.isAbsolute(cacheRoot ?? "")) throw error4("runtime_cache_owner_invalid");
24557
25154
  metadata = checkedRuntimeMetadata({ name: PACKAGE, version: metadata.version, dist: metadata }, metadata.version);
24558
25155
  await privateDirectory2(cacheRoot);
24559
25156
  await checkedVersionIndex(cacheRoot, metadata);
24560
- const target = path9.join(cacheRoot, metadata.version + "-" + hash3(metadata.integrity)), existing = await verifyCached(target, metadata, hostKind);
25157
+ const target = path11.join(cacheRoot, metadata.version + "-" + hash4(metadata.integrity)), existing = await verifyCached(target, metadata, hostKind);
24561
25158
  if (existing) return existing;
24562
25159
  const archive = await boundedGet(metadata.tarball, { fetchImpl, signal, maxBytes: MAX_ARCHIVE, timeoutMs: 15e3 });
24563
25160
  const files = await readRuntimeArchive(archive, metadata), release = await cacheLock(cacheRoot, signal);
24564
- const temporary = path9.join(cacheRoot, ".partial-" + randomBytes4(12).toString("hex"));
25161
+ const temporary = path11.join(cacheRoot, ".partial-" + randomBytes4(12).toString("hex"));
24565
25162
  try {
24566
25163
  const index = await checkedVersionIndex(cacheRoot, metadata);
24567
25164
  const found = await verifyCached(target, metadata, hostKind);
24568
25165
  if (found) return found;
24569
25166
  const space = await statfs(cacheRoot, { bigint: true }), needed = BigInt(files.reduce((n, f2) => n + f2.body.length, 0) + 4 * 1024 * 1024);
24570
- if (space.bavail * space.bsize < needed) throw error3("runtime_cache_capacity");
24571
- await mkdir4(temporary, { mode: 448 });
25167
+ if (space.bavail * space.bsize < needed) throw error4("runtime_cache_capacity");
25168
+ await mkdir5(temporary, { mode: 448 });
24572
25169
  for (const file of files) {
24573
25170
  signal?.throwIfAborted();
24574
- const dest = path9.join(temporary, ...file.path.split("/"));
24575
- await mkdir4(path9.dirname(dest), { recursive: true, mode: 448 });
24576
- const fd = await open6(dest, "wx", 384);
25171
+ const dest = path11.join(temporary, ...file.path.split("/"));
25172
+ await mkdir5(path11.dirname(dest), { recursive: true, mode: 448 });
25173
+ const fd = await open7(dest, "wx", 384);
24577
25174
  try {
24578
25175
  await fd.writeFile(file.body);
24579
25176
  await fd.sync();
@@ -24581,27 +25178,27 @@ async function prepareVerifiedRuntime(metadata, { cacheRoot, fetchImpl = fetch,
24581
25178
  await fd.close();
24582
25179
  }
24583
25180
  }
24584
- const entries = [...new Set(files.map((file) => file.path.split("/")[0]))].sort();
24585
- if (RUNTIME_PACKAGE_ENTRIES.some((name) => !entries.includes(name))) throw error3("runtime_package_incomplete");
24586
- const payload = await inspectRuntimePackage(temporary, { entries });
24587
- if (!payload.hosts.includes(hostKind)) throw error3("runtime_host_unsupported");
24588
- if (payload.version !== metadata.version) throw error3("runtime_package_version_invalid");
25181
+ const entries2 = [...new Set(files.map((file) => file.path.split("/")[0]))].sort();
25182
+ if (RUNTIME_PACKAGE_ENTRIES.some((name) => !entries2.includes(name))) throw error4("runtime_package_incomplete");
25183
+ const payload = await inspectRuntimePackage(temporary, { entries: entries2 });
25184
+ if (!payload.hosts.includes(hostKind)) throw error4("runtime_host_unsupported");
25185
+ if (payload.version !== metadata.version) throw error4("runtime_package_version_invalid");
24589
25186
  const pkg = JSON.parse(payload.files.find((f2) => f2.path === "package.json").body);
24590
- if (pkg.repository?.url !== "git+https://github.com/ty-teams/promptframe-creation.git" || pkg.private === true) throw error3("runtime_package_identity_invalid");
25187
+ if (pkg.repository?.url !== "git+https://github.com/ty-teams/promptframe-creation.git" || pkg.private === true) throw error4("runtime_package_identity_invalid");
24591
25188
  if (checkRuntime) await checkRuntime(temporary, metadata.version);
24592
25189
  else {
24593
25190
  const result = await execute(
24594
25191
  process.execPath,
24595
- [path9.join(temporary, "bin/promptframe-creation.mjs"), "--version"],
25192
+ [path11.join(temporary, "bin/promptframe-creation.mjs"), "--version"],
24596
25193
  { timeout: 5e3, maxBuffer: 65536, windowsHide: true, signal, env: {
24597
25194
  ...process.env,
24598
- PROMPTFRAME_CREATION_CONFIG: path9.join(temporary, "no-credentials.json")
25195
+ PROMPTFRAME_CREATION_CONFIG: path11.join(temporary, "no-credentials.json")
24599
25196
  } }
24600
25197
  );
24601
- if (result.stdout.trim() !== metadata.version || result.stderr.trim()) throw error3("runtime_package_version_invalid");
25198
+ if (result.stdout.trim() !== metadata.version || result.stderr.trim()) throw error4("runtime_package_version_invalid");
24602
25199
  }
24603
25200
  signal?.throwIfAborted();
24604
- await exclusiveJSON(path9.join(temporary, "runtime.json"), {
25201
+ await exclusiveJSON(path11.join(temporary, "runtime.json"), {
24605
25202
  contractVersion: "creation-verified-runtime/v1",
24606
25203
  version: metadata.version,
24607
25204
  integrity: metadata.integrity,
@@ -24609,10 +25206,10 @@ async function prepareVerifiedRuntime(metadata, { cacheRoot, fetchImpl = fetch,
24609
25206
  });
24610
25207
  await syncDirectory2(temporary);
24611
25208
  if (!index) {
24612
- await exclusiveJSON(path9.join(cacheRoot, "version-" + metadata.version + ".json"), metadata);
25209
+ await exclusiveJSON(path11.join(cacheRoot, "version-" + metadata.version + ".json"), metadata);
24613
25210
  await syncDirectory2(cacheRoot);
24614
25211
  }
24615
- await rename4(temporary, target);
25212
+ await rename5(temporary, target);
24616
25213
  await syncDirectory2(cacheRoot);
24617
25214
  return { version: metadata.version, root: target, integrity: metadata.integrity, reused: false };
24618
25215
  } finally {
@@ -24626,7 +25223,7 @@ async function prepareVerifiedRuntime(metadata, { cacheRoot, fetchImpl = fetch,
24626
25223
  async function selectBridgeRuntime({ policy, currentVersion, lockedVersion, resolvedVersion, cacheRoot, fetchImpl = fetch, signal, checkRuntime, hostKind = "codex" } = {}) {
24627
25224
  version2(currentVersion);
24628
25225
  if (lockedVersion !== void 0) version2(lockedVersion);
24629
- if (resolvedVersion !== void 0 && resolvedVersion !== currentVersion) throw error3("runtime_selection_identity_invalid");
25226
+ if (resolvedVersion !== void 0 && resolvedVersion !== currentVersion) throw error4("runtime_selection_identity_invalid");
24630
25227
  if (!policy) throw new RuntimeSelectionError(
24631
25228
  "platform_bridge_policy_unavailable",
24632
25229
  currentVersion,
@@ -24651,7 +25248,7 @@ async function selectBridgeRuntime({ policy, currentVersion, lockedVersion, reso
24651
25248
  const raw = await boundedGet(REGISTRY + "/@promptframe%2fcreation/" + target, { fetchImpl, signal, maxBytes: 256 * 1024, timeoutMs: 5e3 });
24652
25249
  metadata = checkedRuntimeMetadata(JSON.parse(raw), target);
24653
25250
  } catch (e) {
24654
- const prior = await privateJSON(path9.join(cacheRoot, "version-" + target + ".json"));
25251
+ const prior = await privateJSON(path11.join(cacheRoot, "version-" + target + ".json"));
24655
25252
  if (!prior) throw e;
24656
25253
  metadata = checkedRuntimeMetadata({ name: PACKAGE, version: target, dist: prior }, target);
24657
25254
  metadataSource = "previously-verified-cache";
@@ -24664,29 +25261,29 @@ async function selectBridgeRuntime({ policy, currentVersion, lockedVersion, reso
24664
25261
  metadataSource
24665
25262
  };
24666
25263
  } catch (e) {
24667
- if (signal?.aborted) throw error3("runtime_selection_interrupted");
25264
+ if (signal?.aborted) throw error4("runtime_selection_interrupted");
24668
25265
  if (lockedVersion !== void 0)
24669
25266
  throw new RuntimeSelectionError("bridge_locked_version_unavailable", currentVersion, lockedVersion, policy, "retry_same_fixed_version_in_new_session");
24670
25267
  if (policy && compareBridgeVersions(currentVersion, policy.minBridge) >= 0)
24671
25268
  return { version: currentVersion, current: true, locked: false, status: "update_unavailable_current_compatible" };
24672
25269
  if (policy) assertBridgeCompatible({ experimental: { "promptframe.creation": policy } }, currentVersion);
24673
25270
  if (e instanceof CreationClientError) throw e;
24674
- throw error3("runtime_selection_unavailable");
25271
+ throw error4("runtime_selection_unavailable");
24675
25272
  }
24676
25273
  }
24677
25274
 
24678
25275
  // lib/runtime-launch.mjs
24679
25276
  import { spawn } from "node:child_process";
24680
- import path10 from "node:path";
25277
+ import path12 from "node:path";
24681
25278
  async function launchSelectedBridge(selection, { host, configFile: configFile2, spawnImpl = spawn, env = process.env } = {}) {
24682
- if (!path10.isAbsolute(selection.root ?? "") || !path10.isAbsolute(configFile2 ?? "") || !["codex", "claude-code"].includes(host?.kind))
25279
+ if (!path12.isAbsolute(selection.root ?? "") || !path12.isAbsolute(configFile2 ?? "") || !["codex", "claude-code"].includes(host?.kind))
24683
25280
  throw new CreationClientError("creation.runtime_launch_invalid");
24684
25281
  let child;
24685
25282
  try {
24686
25283
  child = spawnImpl(
24687
25284
  process.execPath,
24688
25285
  [
24689
- path10.join(selection.root, "bin/promptframe-creation.mjs"),
25286
+ path12.join(selection.root, "bin/promptframe-creation.mjs"),
24690
25287
  "bridge",
24691
25288
  "--config",
24692
25289
  configFile2,
@@ -24728,10 +25325,10 @@ async function launchSelectedBridge(selection, { host, configFile: configFile2,
24728
25325
  // lib/user-installation.mjs
24729
25326
  import { execFile as execFile2 } from "node:child_process";
24730
25327
  import { promisify as promisify2 } from "node:util";
24731
- import { createHash as createHash8, randomBytes as randomBytes5 } from "node:crypto";
24732
- import { lstat as lstat7, mkdir as mkdir5, readdir as readdir4, readFile as readFile6, writeFile as writeFile2, rename as rename5, rm as rm2, open as open7 } from "node:fs/promises";
24733
- import { homedir as homedir4 } from "node:os";
24734
- import path11 from "node:path";
25328
+ import { createHash as createHash9, randomBytes as randomBytes5 } from "node:crypto";
25329
+ import { lstat as lstat8, mkdir as mkdir6, readdir as readdir4, readFile as readFile6, writeFile as writeFile2, rename as rename6, rm as rm2, open as open8 } from "node:fs/promises";
25330
+ import { homedir as homedir5 } from "node:os";
25331
+ import path13 from "node:path";
24735
25332
 
24736
25333
  // node_modules/smol-toml/dist/error.js
24737
25334
  function getLineColFromPtr(string4, ptr) {
@@ -24884,55 +25481,55 @@ var TomlDate = class _TomlDate extends Date {
24884
25481
  #hasDate = false;
24885
25482
  #hasTime = false;
24886
25483
  #offset = null;
24887
- constructor(date4, fasttype, unsafeDelim) {
25484
+ constructor(date5, fasttype, unsafeDelim) {
24888
25485
  let hasDate = true;
24889
25486
  let hasTime = true;
24890
25487
  let offset = "Z";
24891
25488
  let c;
24892
- if (typeof date4 === "string") {
25489
+ if (typeof date5 === "string") {
24893
25490
  if (fasttype)
24894
25491
  prep: {
24895
25492
  if (fasttype < 3) {
24896
- if (+date4.slice(11, 13) > 23) {
24897
- date4 = "";
25493
+ if (+date5.slice(11, 13) > 23) {
25494
+ date5 = "";
24898
25495
  break prep;
24899
25496
  }
24900
25497
  if (fasttype === 2) {
24901
25498
  offset = null;
24902
- date4 += "Z";
24903
- } else if ((c = date4.charCodeAt(date4.length - 1)) !== 90 && c !== 122) {
24904
- offset = date4.slice(date4.length - 6);
25499
+ date5 += "Z";
25500
+ } else if ((c = date5.charCodeAt(date5.length - 1)) !== 90 && c !== 122) {
25501
+ offset = date5.slice(date5.length - 6);
24905
25502
  }
24906
25503
  if (unsafeDelim)
24907
- date4 = date4.slice(0, 10) + "T" + date4.slice(11);
25504
+ date5 = date5.slice(0, 10) + "T" + date5.slice(11);
24908
25505
  } else if (fasttype === 4) {
24909
- date4 = +date4.slice(0, 2) > 23 ? "" : `0000-01-01T${date4}Z`;
25506
+ date5 = +date5.slice(0, 2) > 23 ? "" : `0000-01-01T${date5}Z`;
24910
25507
  }
24911
25508
  hasDate = fasttype !== 4;
24912
25509
  hasTime = fasttype !== 3;
24913
25510
  }
24914
25511
  else {
24915
- let match = date4.match(DATE_TIME_RE);
25512
+ let match = date5.match(DATE_TIME_RE);
24916
25513
  if (match) {
24917
25514
  if (!match[1]) {
24918
25515
  hasDate = false;
24919
- date4 = `0000-01-01T${date4}`;
25516
+ date5 = `0000-01-01T${date5}`;
24920
25517
  }
24921
25518
  hasTime = !!match[2];
24922
- hasTime && date4[10] === " " && (date4 = date4.replace(" ", "T"));
25519
+ hasTime && date5[10] === " " && (date5 = date5.replace(" ", "T"));
24923
25520
  if (match[2] && +match[2] > 23) {
24924
- date4 = "";
25521
+ date5 = "";
24925
25522
  } else {
24926
25523
  offset = match[3] || null;
24927
25524
  if (!offset && hasTime)
24928
- date4 += "Z";
25525
+ date5 += "Z";
24929
25526
  }
24930
25527
  } else {
24931
- date4 = "";
25528
+ date5 = "";
24932
25529
  }
24933
25530
  }
24934
25531
  }
24935
- super(date4);
25532
+ super(date5);
24936
25533
  if (!isNaN(this.getTime())) {
24937
25534
  this.#hasDate = hasDate;
24938
25535
  this.#hasTime = hasTime;
@@ -24970,26 +25567,26 @@ var TomlDate = class _TomlDate extends Date {
24970
25567
  return offsetDate.toISOString().slice(0, -1) + this.#offset;
24971
25568
  }
24972
25569
  static wrapAsOffsetDateTime(jsDate, offset = "Z") {
24973
- let date4 = new _TomlDate(jsDate);
24974
- date4.#offset = offset;
24975
- return date4;
25570
+ let date5 = new _TomlDate(jsDate);
25571
+ date5.#offset = offset;
25572
+ return date5;
24976
25573
  }
24977
25574
  static wrapAsLocalDateTime(jsDate) {
24978
- let date4 = new _TomlDate(jsDate);
24979
- date4.#offset = null;
24980
- return date4;
25575
+ let date5 = new _TomlDate(jsDate);
25576
+ date5.#offset = null;
25577
+ return date5;
24981
25578
  }
24982
25579
  static wrapAsLocalDate(jsDate) {
24983
- let date4 = new _TomlDate(jsDate);
24984
- date4.#hasTime = false;
24985
- date4.#offset = null;
24986
- return date4;
25580
+ let date5 = new _TomlDate(jsDate);
25581
+ date5.#hasTime = false;
25582
+ date5.#offset = null;
25583
+ return date5;
24987
25584
  }
24988
25585
  static wrapAsLocalTime(jsDate) {
24989
- let date4 = new _TomlDate(jsDate);
24990
- date4.#hasDate = false;
24991
- date4.#offset = null;
24992
- return date4;
25586
+ let date5 = new _TomlDate(jsDate);
25587
+ date5.#hasDate = false;
25588
+ date5.#offset = null;
25589
+ return date5;
24993
25590
  }
24994
25591
  };
24995
25592
 
@@ -25179,10 +25776,10 @@ function parseTime(ctx, c, endChr) {
25179
25776
  }
25180
25777
  function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
25181
25778
  if (ctx.ld) {
25182
- let date4 = new TomlDate(str, type, unsafeDelim);
25183
- if (!date4.isValid())
25779
+ let date5 = new TomlDate(str, type, unsafeDelim);
25780
+ if (!date5.isValid())
25184
25781
  TomlError.x("invalid date", ctx, errPtr);
25185
- return date4;
25782
+ return date5;
25186
25783
  }
25187
25784
  try {
25188
25785
  if (temporalSuffix)
@@ -25493,7 +26090,7 @@ var HAS_WELLFORMED = !!"".isWellFormed;
25493
26090
 
25494
26091
  // lib/user-installation.mjs
25495
26092
  var execute2 = promisify2(execFile2);
25496
- var hash4 = (b2) => createHash8("sha256").update(b2).digest("hex");
26093
+ var hash5 = (b2) => createHash9("sha256").update(b2).digest("hex");
25497
26094
  var InstallationError = class extends CreationClientError {
25498
26095
  constructor(code, details) {
25499
26096
  super("installation." + code);
@@ -25503,7 +26100,7 @@ var InstallationError = class extends CreationClientError {
25503
26100
  var fail4 = (code, details) => {
25504
26101
  throw new InstallationError(code, details);
25505
26102
  };
25506
- var installationErrorDetails = (error4) => error4 instanceof InstallationError ? error4.details : void 0;
26103
+ var installationErrorDetails = (error5) => error5 instanceof InstallationError ? error5.details : void 0;
25507
26104
  function compareVersions(a, b2) {
25508
26105
  const left = a.split(".").map(BigInt), right = b2.split(".").map(BigInt);
25509
26106
  for (let i = 0; i < 3; i++) {
@@ -25532,8 +26129,8 @@ function validProfile(profile) {
25532
26129
  }
25533
26130
  function profileCredentialsPath(profile = "default", env = process.env) {
25534
26131
  validProfile(profile);
25535
- return profile === "default" ? credentialsPath(env) : path11.resolve(
25536
- env.XDG_CONFIG_HOME ?? path11.join(homedir4(), ".config"),
26132
+ return profile === "default" ? credentialsPath(env) : path13.resolve(
26133
+ env.XDG_CONFIG_HOME ?? path13.join(homedir5(), ".config"),
25537
26134
  "promptframe-creation",
25538
26135
  "profiles",
25539
26136
  profile,
@@ -25542,15 +26139,15 @@ function profileCredentialsPath(profile = "default", env = process.env) {
25542
26139
  }
25543
26140
  async function info2(file) {
25544
26141
  try {
25545
- return await lstat7(file);
26142
+ return await lstat8(file);
25546
26143
  } catch (e) {
25547
26144
  if (e.code === "ENOENT") return null;
25548
26145
  throw e;
25549
26146
  }
25550
26147
  }
25551
26148
  async function privateDirectory3(dir) {
25552
- await mkdir5(dir, { recursive: true, mode: 448 });
25553
- const s3 = await lstat7(dir);
26149
+ await mkdir6(dir, { recursive: true, mode: 448 });
26150
+ const s3 = await lstat8(dir);
25554
26151
  if (!s3.isDirectory() || s3.isSymbolicLink() || s3.uid !== process.getuid?.() || s3.mode & 63) fail4("private_owner_required");
25555
26152
  }
25556
26153
  async function privateRead2(file) {
@@ -25565,20 +26162,20 @@ async function packageJSON(file) {
25565
26162
  return json(file);
25566
26163
  }
25567
26164
  function sameTransport(actual, expected) {
25568
- return actual?.type === "stdio" && actual.command === expected.command && typeof actual.cwd === "string" && path11.resolve(actual.cwd) === path11.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;
26165
+ return actual?.type === "stdio" && actual.command === expected.command && typeof actual.cwd === "string" && path13.resolve(actual.cwd) === path13.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;
25569
26166
  }
25570
26167
  async function managedTransport(installed, versions, serverName, profile, configFile2) {
25571
26168
  if (!installed) return null;
25572
26169
  const root = installed.source?.path;
25573
- if (installed.source?.source !== "local" || typeof root !== "string" || !/^\d+\.\d+\.\d+$/.test(installed.version ?? "") || root !== path11.join(versions, installed.version)) fail4("existing_registration_requires_review");
25574
- const directory2 = await info2(root), definition = await info2(path11.join(root, ".mcp.json"));
25575
- if (!directory2?.isDirectory() || directory2.isSymbolicLink() || !definition?.isFile() || definition.isSymbolicLink()) fail4("installed_files_invalid");
25576
- const ready = await privateRead2(path11.join(root, "installation.json"));
26170
+ if (installed.source?.source !== "local" || typeof root !== "string" || !/^\d+\.\d+\.\d+$/.test(installed.version ?? "") || root !== path13.join(versions, installed.version)) fail4("existing_registration_requires_review");
26171
+ const directory3 = await info2(root), definition = await info2(path13.join(root, ".mcp.json"));
26172
+ if (!directory3?.isDirectory() || directory3.isSymbolicLink() || !definition?.isFile() || definition.isSymbolicLink()) fail4("installed_files_invalid");
26173
+ const ready = await privateRead2(path13.join(root, "installation.json"));
25577
26174
  if (!ready || ready.profile !== profile || ready.configFile !== configFile2 || ready.version !== installed.version) fail4("existing_registration_requires_review");
25578
- const bytes2 = await readFile6(path11.join(root, ".mcp.json")), entry = ready.files?.find((x) => x.path === ".mcp.json");
25579
- if (!entry || entry.bytes !== bytes2.length || entry.sha256 !== hash4(bytes2)) fail4("installed_files_invalid");
26175
+ const bytes2 = await readFile6(path13.join(root, ".mcp.json")), entry = ready.files?.find((x) => x.path === ".mcp.json");
26176
+ if (!entry || entry.bytes !== bytes2.length || entry.sha256 !== hash5(bytes2)) fail4("installed_files_invalid");
25580
26177
  const mcp = JSON.parse(bytes2).mcpServers?.[serverName];
25581
- if (!mcp || typeof mcp.command !== "string" || !mcp.command || mcp.cwd !== root || JSON.stringify(mcp.args) !== JSON.stringify([path11.join(root, "bin/promptframe-creation.mjs"), "bridge", "--config", configFile2])) fail4("existing_registration_requires_review");
26178
+ if (!mcp || typeof mcp.command !== "string" || !mcp.command || mcp.cwd !== root || JSON.stringify(mcp.args) !== JSON.stringify([path13.join(root, "bin/promptframe-creation.mjs"), "bridge", "--config", configFile2])) fail4("existing_registration_requires_review");
25582
26179
  return mcp;
25583
26180
  }
25584
26181
  async function officialNpmInstallation(installed, servers, env, profile, configFile2) {
@@ -25586,12 +26183,12 @@ async function officialNpmInstallation(installed, servers, env, profile, configF
25586
26183
  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));
25587
26184
  if (candidates.length > 1) fail4("existing_registration_requires_review");
25588
26185
  if (!candidates.length) return null;
25589
- const p2 = candidates[0], root = path11.join(path11.resolve(env.CODEX_HOME ?? path11.join(homedir4(), ".codex")), "plugins/cache", p2.marketplaceName, p2.name, p2.version);
25590
- const directory2 = await info2(root);
25591
- if (!directory2?.isDirectory() || directory2.isSymbolicLink()) fail4("installed_files_invalid");
25592
- const pkg = await packageJSON(path11.join(root, "package.json")), manifest = await packageJSON(path11.join(root, ".codex-plugin/plugin.json"));
26186
+ const p2 = candidates[0], root = path13.join(path13.resolve(env.CODEX_HOME ?? path13.join(homedir5(), ".codex")), "plugins/cache", p2.marketplaceName, p2.name, p2.version);
26187
+ const directory3 = await info2(root);
26188
+ if (!directory3?.isDirectory() || directory3.isSymbolicLink()) fail4("installed_files_invalid");
26189
+ const pkg = await packageJSON(path13.join(root, "package.json")), manifest = await packageJSON(path13.join(root, ".codex-plugin/plugin.json"));
25593
26190
  if (pkg.name !== "@promptframe/creation" || pkg.version !== p2.version || manifest.name !== p2.name || manifest.version !== p2.version) fail4("installed_files_invalid");
25594
- const definition = (await packageJSON(path11.join(root, ".mcp.json"))).mcpServers?.promptframe;
26191
+ const definition = (await packageJSON(path13.join(root, ".mcp.json"))).mcpServers?.promptframe;
25595
26192
  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");
25596
26193
  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");
25597
26194
  return {
@@ -25610,32 +26207,32 @@ async function officialNpmInstallation(installed, servers, env, profile, configF
25610
26207
  async function atomicJSON(file, value2) {
25611
26208
  const temp = file + "." + randomBytes5(12).toString("hex") + ".tmp";
25612
26209
  try {
25613
- const out = await open7(temp, "wx", 384);
26210
+ const out = await open8(temp, "wx", 384);
25614
26211
  try {
25615
26212
  await out.writeFile(JSON.stringify(value2, null, 2) + "\n");
25616
26213
  await out.sync();
25617
26214
  } finally {
25618
26215
  await out.close();
25619
26216
  }
25620
- await rename5(temp, file);
25621
- const directory2 = await open7(path11.dirname(file), "r");
26217
+ await rename6(temp, file);
26218
+ const directory3 = await open8(path13.dirname(file), "r");
25622
26219
  try {
25623
- await directory2.sync();
26220
+ await directory3.sync();
25624
26221
  } finally {
25625
- await directory2.close();
26222
+ await directory3.close();
25626
26223
  }
25627
26224
  } finally {
25628
26225
  await rm2(temp, { force: true });
25629
26226
  }
25630
26227
  }
25631
26228
  async function acquire(root, signal) {
25632
- const lock = path11.join(root, "install.lock");
26229
+ const lock = path13.join(root, "install.lock");
25633
26230
  const end = Date.now() + 3e4;
25634
26231
  let owned = false;
25635
26232
  while (!owned) {
25636
26233
  signal?.throwIfAborted();
25637
26234
  try {
25638
- await mkdir5(lock, { mode: 448 });
26235
+ await mkdir6(lock, { mode: 448 });
25639
26236
  owned = true;
25640
26237
  } catch (e) {
25641
26238
  if (e.code !== "EEXIST") throw e;
@@ -25644,7 +26241,7 @@ async function acquire(root, signal) {
25644
26241
  }
25645
26242
  }
25646
26243
  try {
25647
- await writeFile2(path11.join(lock, "owner.json"), JSON.stringify({ pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString() }), { flag: "wx", mode: 384 });
26244
+ await writeFile2(path13.join(lock, "owner.json"), JSON.stringify({ pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString() }), { flag: "wx", mode: 384 });
25648
26245
  } catch (e) {
25649
26246
  await rm2(lock, { recursive: true, force: true });
25650
26247
  throw e;
@@ -25685,7 +26282,7 @@ async function codexJSON(runCodex, args2) {
25685
26282
  }
25686
26283
  }
25687
26284
  async function relatedPlugins(runCodex, pluginName, env) {
25688
- const related = /* @__PURE__ */ new Set(), registered = /* @__PURE__ */ new Set(), pinnedMarketplaces = /* @__PURE__ */ new Map(), config2 = path11.join(path11.resolve(env.CODEX_HOME ?? path11.join(homedir4(), ".codex")), "config.toml");
26285
+ const related = /* @__PURE__ */ new Set(), registered = /* @__PURE__ */ new Set(), pinnedMarketplaces = /* @__PURE__ */ new Map(), config2 = path13.join(path13.resolve(env.CODEX_HOME ?? path13.join(homedir5(), ".codex")), "config.toml");
25689
26286
  try {
25690
26287
  const s3 = await info2(config2);
25691
26288
  if (s3) {
@@ -25705,10 +26302,10 @@ async function relatedPlugins(runCodex, pluginName, env) {
25705
26302
  const state = await codexJSON(runCodex, ["plugin", "marketplace", "list", "--json"]);
25706
26303
  if (!Array.isArray(state?.marketplaces) || state.marketplaces.length > 128) fail4("local_catalog_unconfirmed");
25707
26304
  for (const market of state.marketplaces) {
25708
- if (typeof market.name !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,140}$/.test(market.name) || typeof market.root !== "string" || !path11.isAbsolute(market.root)) fail4("local_catalog_unconfirmed");
26305
+ if (typeof market.name !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,140}$/.test(market.name) || typeof market.root !== "string" || !path13.isAbsolute(market.root)) fail4("local_catalog_unconfirmed");
25709
26306
  let catalog;
25710
26307
  try {
25711
- catalog = await packageJSON(path11.join(market.root, ".agents/plugins/marketplace.json"));
26308
+ catalog = await packageJSON(path13.join(market.root, ".agents/plugins/marketplace.json"));
25712
26309
  } catch {
25713
26310
  fail4("local_catalog_unconfirmed", { phase: "local_check", commandKind: "marketplace_read", localRegistrationState: "unknown", action: "restore_local_marketplace_catalog" });
25714
26311
  }
@@ -25739,7 +26336,7 @@ async function relatedPlugins(runCodex, pluginName, env) {
25739
26336
  }
25740
26337
  async function runNode(root, version3) {
25741
26338
  try {
25742
- const result = await execute2(process.execPath, [path11.join(root, "bin/promptframe-creation.mjs"), "--version"], { encoding: "utf8", timeout: 1e4, maxBuffer: 8192 });
26339
+ const result = await execute2(process.execPath, [path13.join(root, "bin/promptframe-creation.mjs"), "--version"], { encoding: "utf8", timeout: 1e4, maxBuffer: 8192 });
25743
26340
  if (result.stdout.trim() !== version3) fail4("runtime_version_mismatch");
25744
26341
  } catch (e) {
25745
26342
  if (e instanceof CreationClientError) throw e;
@@ -25753,7 +26350,7 @@ async function checkInstalledRuntime(root, version3, command2, { env = process.e
25753
26350
  if (!major || Number(major[1]) < 20) throw Error("unsupported_node");
25754
26351
  const result = await execute2(
25755
26352
  command2,
25756
- [path11.join(root, "bin/promptframe-creation.mjs"), "--version"],
26353
+ [path13.join(root, "bin/promptframe-creation.mjs"), "--version"],
25757
26354
  { env, encoding: "utf8", timeout: 1e4, maxBuffer: 8192 }
25758
26355
  );
25759
26356
  if (result.stdout.trim() !== version3) throw Error("wrong_version");
@@ -25790,20 +26387,20 @@ async function installForUser({
25790
26387
  const versionOutput = await runCodex(["--version"]);
25791
26388
  const match = versionOutput.match(/codex-cli (\d+)\.(\d+)\.(\d+)/);
25792
26389
  if (!match || Number(match[1]) === 0 && Number(match[2]) < 160) fail4("codex_0160_required");
25793
- const payload = await inspectRuntimePackage(path11.resolve(sourceRoot));
25794
- const root = path11.resolve(env.XDG_DATA_HOME ?? path11.join(homedir4(), ".local/share"), "promptframe-creation", profile);
26390
+ const payload = await inspectRuntimePackage(path13.resolve(sourceRoot));
26391
+ const root = path13.resolve(env.XDG_DATA_HOME ?? path13.join(homedir5(), ".local/share"), "promptframe-creation", profile);
25795
26392
  await privateDirectory3(root);
25796
26393
  const release = await acquire(root, signal);
25797
- const versions = path11.join(root, "versions"), currentFile = path11.join(root, "current.json"), pendingFile = path11.join(root, "registration-pending.json");
25798
- const marketplaceFile = path11.join(root, ".agents/plugins/marketplace.json");
26394
+ const versions = path13.join(root, "versions"), currentFile = path13.join(root, "current.json"), pendingFile = path13.join(root, "registration-pending.json");
26395
+ const marketplaceFile = path13.join(root, ".agents/plugins/marketplace.json");
25799
26396
  const pluginName = "promptframe-creation" + (profile === "default" ? "" : "-" + profile), marketplace = "promptframe-creation-user" + (profile === "default" ? "" : "-" + profile);
25800
26397
  const pluginId = pluginName + "@" + marketplace;
25801
- const versionRoot = path11.join(versions, payload.version), temporary = path11.join(versions, ".partial-" + randomBytes5(12).toString("hex"));
26398
+ const versionRoot = path13.join(versions, payload.version), temporary = path13.join(versions, ".partial-" + randomBytes5(12).toString("hex"));
25802
26399
  let previous, registrationStarted = false, newFiles = 0;
25803
26400
  try {
25804
26401
  signal?.throwIfAborted();
25805
26402
  await privateDirectory3(versions);
25806
- await privateDirectory3(path11.dirname(marketplaceFile));
26403
+ await privateDirectory3(path13.dirname(marketplaceFile));
25807
26404
  previous = await privateRead2(currentFile);
25808
26405
  if (previous && (previous.profile !== profile || previous.pluginId !== pluginId || previous.configFile !== configFile2)) fail4("profile_binding_conflict");
25809
26406
  const state = { installed: await relatedPlugins(runCodex, pluginName, env) };
@@ -25814,12 +26411,12 @@ async function installForUser({
25814
26411
  const servers = legacy.filter((x) => x.name === serverName);
25815
26412
  const pending = await privateRead2(pendingFile);
25816
26413
  if (pending) {
25817
- if (pending.profile !== profile || pending.pluginId !== pluginId || pending.configFile !== configFile2 || pending.versionRoot !== path11.join(versions, pending.version)) fail4("profile_binding_conflict");
26414
+ if (pending.profile !== profile || pending.pluginId !== pluginId || pending.configFile !== configFile2 || pending.versionRoot !== path13.join(versions, pending.version)) fail4("profile_binding_conflict");
25818
26415
  if (installed?.version !== pending.version || installed.enabled !== true || installed.source?.path !== pending.versionRoot)
25819
26416
  fail4("registration_unconfirmed_keep_existing", { phase: "registration_observation", localRegistrationState: "unknown", action: "inspect_same_registration_no_second_add" });
25820
26417
  const transport2 = await managedTransport(installed, versions, serverName, profile, configFile2);
25821
26418
  if (servers.length !== 1 || servers[0].enabled === false || !sameTransport(servers[0].transport, transport2)) fail4("registration_unconfirmed_keep_existing");
25822
- const ready = await privateRead2(path11.join(pending.versionRoot, "installation.json"));
26419
+ const ready = await privateRead2(path13.join(pending.versionRoot, "installation.json"));
25823
26420
  if (ready?.payloadDigest !== pending.payloadDigest) fail4("installed_files_invalid");
25824
26421
  previous = pending;
25825
26422
  await atomicJSON(currentFile, pending);
@@ -25874,43 +26471,43 @@ async function installForUser({
25874
26471
  const target = await info2(versionRoot);
25875
26472
  if (target) {
25876
26473
  if (!target.isDirectory() || target.isSymbolicLink()) fail4("version_content_conflict");
25877
- const ready = await privateRead2(path11.join(versionRoot, "installation.json"));
26474
+ const ready = await privateRead2(path13.join(versionRoot, "installation.json"));
25878
26475
  if (!ready || ready.payloadDigest !== payload.payloadDigest || ready.profile !== profile || ready.configFile !== configFile2) fail4("version_content_conflict");
25879
26476
  for (const f2 of ready.files) {
25880
26477
  if (!payload.files.some((p2) => p2.path === f2.path)) fail4("installed_files_invalid");
25881
- const file = path11.join(versionRoot, f2.path), s3 = await info2(file);
25882
- if (!s3?.isFile() || s3.isSymbolicLink() || s3.size !== f2.bytes || hash4(await readFile6(file)) !== f2.sha256) fail4("installed_files_invalid");
26478
+ const file = path13.join(versionRoot, f2.path), s3 = await info2(file);
26479
+ if (!s3?.isFile() || s3.isSymbolicLink() || s3.size !== f2.bytes || hash5(await readFile6(file)) !== f2.sha256) fail4("installed_files_invalid");
25883
26480
  }
25884
26481
  if (ready.files.length !== payload.files.length) fail4("installed_files_invalid");
25885
26482
  } else {
25886
- await mkdir5(temporary, { mode: 448 });
26483
+ await mkdir6(temporary, { mode: 448 });
25887
26484
  for (const f2 of payload.files) {
25888
26485
  signal?.throwIfAborted();
25889
- await mkdir5(path11.dirname(path11.join(temporary, f2.path)), { recursive: true, mode: 448 });
25890
- await writeFile2(path11.join(temporary, f2.path), f2.body, { flag: "wx", mode: 384 });
26486
+ await mkdir6(path13.dirname(path13.join(temporary, f2.path)), { recursive: true, mode: 448 });
26487
+ await writeFile2(path13.join(temporary, f2.path), f2.body, { flag: "wx", mode: 384 });
25891
26488
  }
25892
- const manifest = await json(path11.join(temporary, ".codex-plugin/plugin.json"));
26489
+ const manifest = await json(path13.join(temporary, ".codex-plugin/plugin.json"));
25893
26490
  manifest.name = pluginName;
25894
- await writeFile2(path11.join(temporary, ".codex-plugin/plugin.json"), JSON.stringify(manifest, null, 2) + "\n");
26491
+ await writeFile2(path13.join(temporary, ".codex-plugin/plugin.json"), JSON.stringify(manifest, null, 2) + "\n");
25895
26492
  const mcp = { mcpServers: { ["promptframe" + (profile === "default" ? "" : "-" + profile)]: {
25896
26493
  command: process.execPath,
25897
- args: [path11.join(versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", configFile2],
26494
+ args: [path13.join(versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", configFile2],
25898
26495
  cwd: versionRoot
25899
26496
  } } };
25900
- await writeFile2(path11.join(temporary, ".mcp.json"), JSON.stringify(mcp, null, 2) + "\n");
26497
+ await writeFile2(path13.join(temporary, ".mcp.json"), JSON.stringify(mcp, null, 2) + "\n");
25901
26498
  await checkRuntime(temporary, payload.version);
25902
26499
  const files = [];
25903
26500
  for (const f2 of payload.files) {
25904
- const body = await readFile6(path11.join(temporary, f2.path));
25905
- files.push({ path: f2.path, bytes: body.length, sha256: hash4(body) });
26501
+ const body = await readFile6(path13.join(temporary, f2.path));
26502
+ files.push({ path: f2.path, bytes: body.length, sha256: hash5(body) });
25906
26503
  }
25907
- await atomicJSON(path11.join(temporary, "installation.json"), { version: payload.version, profile, configFile: configFile2, payloadDigest: payload.payloadDigest, files });
26504
+ await atomicJSON(path13.join(temporary, "installation.json"), { version: payload.version, profile, configFile: configFile2, payloadDigest: payload.payloadDigest, files });
25908
26505
  signal?.throwIfAborted();
25909
- await rename5(temporary, versionRoot);
26506
+ await rename6(temporary, versionRoot);
25910
26507
  newFiles = payload.files.length;
25911
26508
  }
25912
26509
  if (newFiles === 0) {
25913
- const launch = (await json(path11.join(versionRoot, ".mcp.json"))).mcpServers?.[serverName];
26510
+ const launch = (await json(path13.join(versionRoot, ".mcp.json"))).mcpServers?.[serverName];
25914
26511
  await verifyInstalledRuntime(versionRoot, payload.version, launch.command, { env });
25915
26512
  }
25916
26513
  const complete = { version: payload.version, profile, configFile: configFile2, pluginId, versionRoot, payloadDigest: payload.payloadDigest };
@@ -25949,16 +26546,16 @@ async function installForUser({
25949
26546
  reloadRequired: !already,
25950
26547
  recordedRuntimeRetained: Boolean(already && recorded && recorded.command !== process.execPath)
25951
26548
  };
25952
- } catch (error4) {
26549
+ } catch (error5) {
25953
26550
  if (registrationStarted) {
25954
26551
  fail4("registration_unconfirmed_keep_existing", {
25955
- ...installationErrorDetails(error4),
26552
+ ...installationErrorDetails(error5),
25956
26553
  phase: "registration_observation",
25957
26554
  localRegistrationState: "unknown",
25958
26555
  action: "inspect_same_registration_no_second_add"
25959
26556
  });
25960
26557
  }
25961
- if (error4 instanceof CreationClientError) throw error4;
26558
+ if (error5 instanceof CreationClientError) throw error5;
25962
26559
  if (signal?.aborted) fail4("interrupted_keep_existing");
25963
26560
  fail4("failed_keep_existing");
25964
26561
  } finally {
@@ -25968,10 +26565,10 @@ async function installForUser({
25968
26565
  }
25969
26566
 
25970
26567
  // lib/claude-installation.mjs
25971
- import { createHash as createHash11, randomBytes as randomBytes7 } from "node:crypto";
25972
- import { mkdir as mkdir7, open as open10, readFile as readFile9, rename as rename7, rm as rm5 } from "node:fs/promises";
25973
- import { homedir as homedir9 } from "node:os";
25974
- import path16 from "node:path";
26568
+ import { createHash as createHash12, randomBytes as randomBytes7 } from "node:crypto";
26569
+ import { mkdir as mkdir8, open as open11, readFile as readFile9, rename as rename8, rm as rm5 } from "node:fs/promises";
26570
+ import { homedir as homedir10 } from "node:os";
26571
+ import path18 from "node:path";
25975
26572
 
25976
26573
  // lib/claude-hook-definition.mjs
25977
26574
  function claudeHostHooks({ pluginName = "promptframe-creation", serverName, configFile: configFile2, nodeCommand = "node", runtimeRoot = "${CLAUDE_PLUGIN_ROOT}" } = {}) {
@@ -25994,10 +26591,10 @@ function claudeHostHooks({ pluginName = "promptframe-creation", serverName, conf
25994
26591
  // lib/claude-command.mjs
25995
26592
  import { execFile as execFile3 } from "node:child_process";
25996
26593
  import { promisify as promisify3 } from "node:util";
25997
- import { access, lstat as lstat8, readdir as readdir5 } from "node:fs/promises";
25998
- import { constants as constants5 } from "node:fs";
25999
- import { homedir as homedir5 } from "node:os";
26000
- import path12 from "node:path";
26594
+ import { access, lstat as lstat9, readdir as readdir5 } from "node:fs/promises";
26595
+ import { constants as constants6 } from "node:fs";
26596
+ import { homedir as homedir6 } from "node:os";
26597
+ import path14 from "node:path";
26001
26598
  var execute3 = promisify3(execFile3);
26002
26599
  var ClaudeCommandError = class extends CreationClientError {
26003
26600
  constructor(code, details) {
@@ -26005,39 +26602,39 @@ var ClaudeCommandError = class extends CreationClientError {
26005
26602
  this.details = details;
26006
26603
  }
26007
26604
  };
26008
- var claudeErrorDetails = (error4) => error4 instanceof ClaudeCommandError ? error4.details : void 0;
26009
- async function resolveClaudeCommand({ env = process.env, homeDirectory = homedir5(), executable } = {}) {
26605
+ var claudeErrorDetails = (error5) => error5 instanceof ClaudeCommandError ? error5.details : void 0;
26606
+ async function resolveClaudeCommand({ env = process.env, homeDirectory = homedir6(), executable } = {}) {
26010
26607
  const selected = executable ?? env.PROMPTFRAME_CLAUDE_BIN;
26011
26608
  if (selected) {
26012
- if (!path12.isAbsolute(selected)) throw new CreationClientError("installation.claude_executable_invalid");
26013
- await access(selected, constants5.X_OK);
26609
+ if (!path14.isAbsolute(selected)) throw new CreationClientError("installation.claude_executable_invalid");
26610
+ await access(selected, constants6.X_OK);
26014
26611
  return selected;
26015
26612
  }
26016
- for (const directory2 of (env.PATH ?? "").split(path12.delimiter).filter(path12.isAbsolute)) {
26017
- const file = path12.join(directory2, process.platform === "win32" ? "claude.exe" : "claude");
26613
+ for (const directory3 of (env.PATH ?? "").split(path14.delimiter).filter(path14.isAbsolute)) {
26614
+ const file = path14.join(directory3, process.platform === "win32" ? "claude.exe" : "claude");
26018
26615
  try {
26019
- await access(file, constants5.X_OK);
26616
+ await access(file, constants6.X_OK);
26020
26617
  return file;
26021
26618
  } catch (e) {
26022
26619
  if (!["ENOENT", "EACCES", "ENOTDIR"].includes(e.code)) throw e;
26023
26620
  }
26024
26621
  }
26025
- const root = path12.join(homeDirectory, ".claude/remote/ccd-cli");
26026
- let entries;
26622
+ const root = path14.join(homeDirectory, ".claude/remote/ccd-cli");
26623
+ let entries2;
26027
26624
  try {
26028
- entries = await readdir5(root);
26625
+ entries2 = await readdir5(root);
26029
26626
  } catch (e) {
26030
26627
  if (e.code === "ENOENT") throw new CreationClientError("installation.claude_required");
26031
26628
  throw e;
26032
26629
  }
26033
- if (entries.length > 32) throw new CreationClientError("installation.claude_executable_unconfirmed");
26630
+ if (entries2.length > 32) throw new CreationClientError("installation.claude_executable_unconfirmed");
26034
26631
  const candidates = [];
26035
- for (const name of entries) {
26632
+ for (const name of entries2) {
26036
26633
  const match = name.match(/^(\d+)\.(\d+)\.(\d+)-[a-f0-9]{6,40}$/);
26037
26634
  if (!match) continue;
26038
- const file = path12.join(root, name), s3 = await lstat8(file);
26635
+ const file = path14.join(root, name), s3 = await lstat9(file);
26039
26636
  if (s3.isFile() && !s3.isSymbolicLink() && s3.uid === process.getuid?.()) {
26040
- await access(file, constants5.X_OK);
26637
+ await access(file, constants6.X_OK);
26041
26638
  candidates.push({ file, version: match.slice(1).map(Number) });
26042
26639
  }
26043
26640
  }
@@ -26073,17 +26670,17 @@ function createClaudeRunner({ env = process.env, executable, signal, resolve = r
26073
26670
  }
26074
26671
 
26075
26672
  // lib/claude-local-state.mjs
26076
- import { readFile as readFile7, lstat as lstat9 } from "node:fs/promises";
26077
- import { homedir as homedir6 } from "node:os";
26078
- import path13 from "node:path";
26673
+ import { readFile as readFile7, lstat as lstat10 } from "node:fs/promises";
26674
+ import { homedir as homedir7 } from "node:os";
26675
+ import path15 from "node:path";
26079
26676
  function claudeConfigRoot(env = process.env) {
26080
- return path13.resolve(env.CLAUDE_CONFIG_DIR ?? path13.join(homedir6(), ".claude"));
26677
+ return path15.resolve(env.CLAUDE_CONFIG_DIR ?? path15.join(homedir7(), ".claude"));
26081
26678
  }
26082
26679
  async function readClaudeUserServer(serverName, env = process.env) {
26083
- const file = env.CLAUDE_CONFIG_DIR ? path13.join(claudeConfigRoot(env), ".claude.json") : path13.join(homedir6(), ".claude.json");
26680
+ const file = env.CLAUDE_CONFIG_DIR ? path15.join(claudeConfigRoot(env), ".claude.json") : path15.join(homedir7(), ".claude.json");
26084
26681
  let info5;
26085
26682
  try {
26086
- info5 = await lstat9(file);
26683
+ info5 = await lstat10(file);
26087
26684
  } catch (e) {
26088
26685
  if (e.code === "ENOENT") return null;
26089
26686
  throw new CreationClientError("installation.claude_local_registration_unconfirmed");
@@ -26103,26 +26700,26 @@ async function readClaudeUserServer(serverName, env = process.env) {
26103
26700
  }
26104
26701
 
26105
26702
  // lib/claude-mcp-installation.mjs
26106
- import { createHash as createHash10, randomBytes as randomBytes6 } from "node:crypto";
26107
- import { mkdir as mkdir6, open as open9, readFile as readFile8, readdir as readdir6, rename as rename6, rm as rm4, lstat as lstat10 } from "node:fs/promises";
26108
- import { homedir as homedir8 } from "node:os";
26109
- import path15 from "node:path";
26703
+ import { createHash as createHash11, randomBytes as randomBytes6 } from "node:crypto";
26704
+ import { mkdir as mkdir7, open as open10, readFile as readFile8, readdir as readdir6, rename as rename7, rm as rm4, lstat as lstat11 } from "node:fs/promises";
26705
+ import { homedir as homedir9 } from "node:os";
26706
+ import path17 from "node:path";
26110
26707
 
26111
26708
  // lib/claude-hook-registration.mjs
26112
- import { createHash as createHash9 } from "node:crypto";
26113
- import { open as open8, rm as rm3 } from "node:fs/promises";
26114
- import { constants as constants6 } from "node:fs";
26115
- import path14 from "node:path";
26116
- import { homedir as homedir7 } from "node:os";
26709
+ import { createHash as createHash10 } from "node:crypto";
26710
+ import { open as open9, rm as rm3 } from "node:fs/promises";
26711
+ import { constants as constants7 } from "node:fs";
26712
+ import path16 from "node:path";
26713
+ import { homedir as homedir8 } from "node:os";
26117
26714
  var { privateDirectory: privateDirectory4, privateRead: privateRead3, atomicJSON: atomicJSON2, acquire: acquire2 } = installationFiles;
26118
- var digest4 = (value2) => createHash9("sha256").update(JSON.stringify(value2)).digest("hex");
26715
+ var digest4 = (value2) => createHash10("sha256").update(JSON.stringify(value2)).digest("hex");
26119
26716
  var fail5 = () => {
26120
26717
  throw new CreationClientError("installation.claude_hooks_require_review");
26121
26718
  };
26122
26719
  async function settings(file) {
26123
26720
  let handle;
26124
26721
  try {
26125
- handle = await open8(file, constants6.O_RDONLY | constants6.O_NOFOLLOW);
26722
+ handle = await open9(file, constants7.O_RDONLY | constants7.O_NOFOLLOW);
26126
26723
  const info5 = await handle.stat();
26127
26724
  if (!info5.isFile() || info5.uid !== process.getuid?.() || info5.size > 512 * 1024) fail5();
26128
26725
  const value2 = JSON.parse(await handle.readFile("utf8"));
@@ -26135,29 +26732,29 @@ async function settings(file) {
26135
26732
  await handle?.close();
26136
26733
  }
26137
26734
  }
26138
- 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));
26735
+ var contains = (value2, entries2) => Object.entries(entries2).every(([event, wanted]) => Array.isArray(value2.hooks?.[event]) && wanted.every((entry) => value2.hooks[event].filter((actual) => digest4(actual) === digest4(entry)).length === 1));
26139
26736
  async function verifyClaudeFallbackHooks(record2, env) {
26140
- if (!record2?.settingsFile || record2.settingsFile !== path14.join(claudeConfigRoot(env), "settings.json") || !record2.entries) fail5();
26737
+ if (!record2?.settingsFile || record2.settingsFile !== path16.join(claudeConfigRoot(env), "settings.json") || !record2.entries) fail5();
26141
26738
  if (!contains(await settings(record2.settingsFile), record2.entries)) fail5();
26142
26739
  return true;
26143
26740
  }
26144
26741
  async function registerClaudeFallbackHooks({ record: record2, root, env, nodeCommand, signal }) {
26145
- const directory2 = claudeConfigRoot(env), file = path14.join(directory2, "settings.json");
26146
- const guard = path14.resolve(
26147
- env.XDG_DATA_HOME ?? path14.join(homedir7(), ".local/share"),
26742
+ const directory3 = claudeConfigRoot(env), file = path16.join(directory3, "settings.json");
26743
+ const guard = path16.resolve(
26744
+ env.XDG_DATA_HOME ?? path16.join(homedir8(), ".local/share"),
26148
26745
  "promptframe-creation",
26149
- "claude-hook-writer-" + digest4(directory2)
26746
+ "claude-hook-writer-" + digest4(directory3)
26150
26747
  );
26151
26748
  await privateDirectory4(guard);
26152
26749
  const release = await acquire2(guard, signal);
26153
- const markerFile = path14.join(root, "hooks-current.json"), pendingFile = path14.join(root, "hooks-pending.json");
26750
+ const markerFile = path16.join(root, "hooks-current.json"), pendingFile = path16.join(root, "hooks-pending.json");
26154
26751
  try {
26155
- await privateDirectory4(directory2);
26156
- const entries = claudeHostHooks({ serverName: record2.serverName, configFile: record2.configFile, nodeCommand, runtimeRoot: record2.versionRoot });
26157
- const expected = { contractVersion: "creation-claude-hooks/v1", settingsFile: file, profile: record2.profile, entries };
26752
+ await privateDirectory4(directory3);
26753
+ const entries2 = claudeHostHooks({ serverName: record2.serverName, configFile: record2.configFile, nodeCommand, runtimeRoot: record2.versionRoot });
26754
+ const expected = { contractVersion: "creation-claude-hooks/v1", settingsFile: file, profile: record2.profile, entries: entries2 };
26158
26755
  const pending = await privateRead3(pendingFile), previous = await privateRead3(markerFile), before = await settings(file);
26159
26756
  if (pending) {
26160
- if (digest4(pending) !== digest4(expected) || !contains(before, entries)) throw new CreationClientError("installation.registration_unconfirmed_keep_existing");
26757
+ if (digest4(pending) !== digest4(expected) || !contains(before, entries2)) throw new CreationClientError("installation.registration_unconfirmed_keep_existing");
26161
26758
  await atomicJSON2(markerFile, expected);
26162
26759
  await rm3(pendingFile);
26163
26760
  return expected;
@@ -26168,7 +26765,7 @@ async function registerClaudeFallbackHooks({ record: record2, root, env, nodeCom
26168
26765
  if (digest4(previous) === digest4(expected)) return previous;
26169
26766
  }
26170
26767
  const next = { ...before, hooks: { ...before.hooks } };
26171
- for (const [event, wanted] of Object.entries(entries)) {
26768
+ for (const [event, wanted] of Object.entries(entries2)) {
26172
26769
  const actual = next.hooks[event] ?? [];
26173
26770
  if (!Array.isArray(actual)) fail5();
26174
26771
  const owned = new Set((previous?.entries[event] ?? []).map(digest4));
@@ -26179,7 +26776,7 @@ async function registerClaudeFallbackHooks({ record: record2, root, env, nodeCom
26179
26776
  await atomicJSON2(pendingFile, expected);
26180
26777
  if (digest4(await settings(file)) !== digest4(before)) fail5();
26181
26778
  await atomicJSON2(file, next);
26182
- if (!contains(await settings(file), entries)) throw new CreationClientError("installation.registration_unconfirmed_keep_existing");
26779
+ if (!contains(await settings(file), entries2)) throw new CreationClientError("installation.registration_unconfirmed_keep_existing");
26183
26780
  await atomicJSON2(markerFile, expected);
26184
26781
  await rm3(pendingFile);
26185
26782
  return expected;
@@ -26190,23 +26787,23 @@ async function registerClaudeFallbackHooks({ record: record2, root, env, nodeCom
26190
26787
 
26191
26788
  // lib/claude-mcp-installation.mjs
26192
26789
  var { info: info3, privateDirectory: privateDirectory5, privateRead: privateRead4, atomicJSON: atomicJSON3, acquire: acquire3, compareVersions: compareVersions2 } = installationFiles;
26193
- var hash5 = (body) => createHash10("sha256").update(body).digest("hex");
26790
+ var hash6 = (body) => createHash11("sha256").update(body).digest("hex");
26194
26791
  var FallbackError = class extends CreationClientError {
26195
26792
  constructor(code, details) {
26196
26793
  super("installation." + code);
26197
26794
  this.details = details;
26198
26795
  }
26199
26796
  };
26200
- var fallbackErrorDetails = (error4) => error4 instanceof FallbackError ? error4.details : void 0;
26797
+ var fallbackErrorDetails = (error5) => error5 instanceof FallbackError ? error5.details : void 0;
26201
26798
  var fail6 = (code, details) => {
26202
26799
  throw new FallbackError(code, details);
26203
26800
  };
26204
26801
  async function claimSkillDirectory(root) {
26205
26802
  try {
26206
- await mkdir6(root, { mode: 448 });
26207
- } catch (error4) {
26208
- if (error4.code === "EEXIST") fail6("claude_skill_requires_review");
26209
- throw error4;
26803
+ await mkdir7(root, { mode: 448 });
26804
+ } catch (error5) {
26805
+ if (error5.code === "EEXIST") fail6("claude_skill_requires_review");
26806
+ throw error5;
26210
26807
  }
26211
26808
  }
26212
26809
  function same(a, b2, depth = 0) {
@@ -26218,15 +26815,15 @@ function same(a, b2, depth = 0) {
26218
26815
  async function atomicText(file, body) {
26219
26816
  const temporary = file + "." + randomBytes6(12).toString("hex") + ".tmp";
26220
26817
  try {
26221
- const fd = await open9(temporary, "wx", 384);
26818
+ const fd = await open10(temporary, "wx", 384);
26222
26819
  try {
26223
26820
  await fd.writeFile(body);
26224
26821
  await fd.sync();
26225
26822
  } finally {
26226
26823
  await fd.close();
26227
26824
  }
26228
- await rename6(temporary, file);
26229
- const dir = await open9(path15.dirname(file), "r");
26825
+ await rename7(temporary, file);
26826
+ const dir = await open10(path17.dirname(file), "r");
26230
26827
  try {
26231
26828
  await dir.sync();
26232
26829
  } finally {
@@ -26237,17 +26834,17 @@ async function atomicText(file, body) {
26237
26834
  }
26238
26835
  }
26239
26836
  async function verifyVersion(root, record2) {
26240
- const directory2 = await info3(root);
26241
- if (!directory2?.isDirectory() || directory2.isSymbolicLink() || directory2.uid !== process.getuid?.() || directory2.mode & 63) fail6("claude_installed_files_invalid");
26242
- const marker = await privateRead4(path15.join(root, "installation.json")), payload = await inspectRuntimePackage(root);
26243
- 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 || !path15.isAbsolute(marker.nodeCommand ?? "")) fail6("claude_installed_files_invalid");
26837
+ const directory3 = await info3(root);
26838
+ if (!directory3?.isDirectory() || directory3.isSymbolicLink() || directory3.uid !== process.getuid?.() || directory3.mode & 63) fail6("claude_installed_files_invalid");
26839
+ const marker = await privateRead4(path17.join(root, "installation.json")), payload = await inspectRuntimePackage(root);
26840
+ 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 || !path17.isAbsolute(marker.nodeCommand ?? "")) fail6("claude_installed_files_invalid");
26244
26841
  return marker;
26245
26842
  }
26246
26843
  function mcpDefinition(record2, nodeCommand) {
26247
26844
  return {
26248
26845
  type: "stdio",
26249
26846
  command: nodeCommand,
26250
- args: [path15.join(record2.versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", record2.configFile, "--host", "claude-code"]
26847
+ args: [path17.join(record2.versionRoot, "bin/promptframe-creation.mjs"), "bridge", "--config", record2.configFile, "--host", "claude-code"]
26251
26848
  };
26252
26849
  }
26253
26850
  function skillBody(payload, sourceName, name) {
@@ -26258,17 +26855,17 @@ function skillBody(payload, sourceName, name) {
26258
26855
  return body.replace("\nname: " + sourceName + "\n", "\nname: " + name + "\n");
26259
26856
  }
26260
26857
  async function observedSkill(plan, record2, { allowBefore = false } = {}) {
26261
- const directory2 = await info3(plan.root);
26262
- if (!directory2) return false;
26263
- if (!directory2.isDirectory() || directory2.isSymbolicLink() || directory2.uid !== process.getuid?.() || directory2.mode & 63) fail6("claude_skill_requires_review");
26858
+ const directory3 = await info3(plan.root);
26859
+ if (!directory3) return false;
26860
+ if (!directory3.isDirectory() || directory3.isSymbolicLink() || directory3.uid !== process.getuid?.() || directory3.mode & 63) fail6("claude_skill_requires_review");
26264
26861
  const names = await readdir6(plan.root);
26265
26862
  if (names.some((n) => !["SKILL.md", "promptframe-installation.json"].includes(n))) fail6("claude_skill_requires_review");
26266
- const marker = await privateRead4(path15.join(plan.root, "promptframe-installation.json")), file = path15.join(plan.root, "SKILL.md"), s3 = await info3(file);
26863
+ const marker = await privateRead4(path17.join(plan.root, "promptframe-installation.json")), file = path17.join(plan.root, "SKILL.md"), s3 = await info3(file);
26267
26864
  if (!marker || marker.host !== "claude-code" || marker.profile !== record2.profile || marker.configFile !== record2.configFile || marker.name !== plan.name)
26268
26865
  fail6("claude_skill_requires_review");
26269
26866
  if (!s3 && allowBefore && plan.beforeSHA === null && marker.sha256 === null) return false;
26270
26867
  if (!s3?.isFile() || s3.isSymbolicLink() || s3.size > 256 * 1024) fail6("claude_skill_requires_review");
26271
- const digest5 = hash5(await readFile8(file));
26868
+ const digest5 = hash6(await readFile8(file));
26272
26869
  if (digest5 === plan.sha256 && marker.sha256 === plan.sha256) return true;
26273
26870
  if (allowBefore && (digest5 === plan.beforeSHA || digest5 === plan.sha256) && marker.sha256 === plan.beforeSHA) return false;
26274
26871
  fail6("claude_skill_requires_review");
@@ -26285,13 +26882,13 @@ async function installClaudeMcpFallback({
26285
26882
  nodeCommand,
26286
26883
  writeSkill = atomicText
26287
26884
  }) {
26288
- const payload = await inspectRuntimePackage(path15.resolve(sourceRoot)), suffix = profile === "default" ? "" : "-" + profile, serverName = "promptframe" + suffix, root = path15.resolve(env.XDG_DATA_HOME ?? path15.join(homedir8(), ".local/share"), "promptframe-creation", profile, "claude-code-mcp");
26885
+ const payload = await inspectRuntimePackage(path17.resolve(sourceRoot)), suffix = profile === "default" ? "" : "-" + profile, serverName = "promptframe" + suffix, root = path17.resolve(env.XDG_DATA_HOME ?? path17.join(homedir9(), ".local/share"), "promptframe-creation", profile, "claude-code-mcp");
26289
26886
  await privateDirectory5(root);
26290
- const release = await acquire3(root, signal), versions = path15.join(root, "versions"), currentFile = path15.join(root, "current.json"), pendingFile = path15.join(root, "registration-pending.json"), versionRoot = path15.join(versions, payload.version), temporary = path15.join(versions, ".partial-" + randomBytes6(12).toString("hex"));
26887
+ const release = await acquire3(root, signal), versions = path17.join(root, "versions"), currentFile = path17.join(root, "current.json"), pendingFile = path17.join(root, "registration-pending.json"), versionRoot = path17.join(versions, payload.version), temporary = path17.join(versions, ".partial-" + randomBytes6(12).toString("hex"));
26291
26888
  let writeStarted = false, newFiles = 0;
26292
26889
  const complete = { host: "claude-code", mode: "mcp-and-skills", profile, configFile: configFile2, serverName, version: payload.version, versionRoot, payloadDigest: payload.payloadDigest };
26293
26890
  const checkBinding = (record2) => {
26294
- 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 !== path15.join(versions, record2.version))) fail6("profile_binding_conflict");
26891
+ 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 !== path17.join(versions, record2.version))) fail6("profile_binding_conflict");
26295
26892
  };
26296
26893
  try {
26297
26894
  await privateDirectory5(versions);
@@ -26308,7 +26905,7 @@ async function installClaudeMcpFallback({
26308
26905
  if (!Array.isArray(record2.skills) || record2.skills.length !== 2) fail6("claude_skill_requires_review");
26309
26906
  for (const [i, skill] of record2.skills.entries()) {
26310
26907
  const name = ["creation-setup", "video-creation"][i] + suffix;
26311
- if (skill.name !== name || skill.root !== path15.join(claudeConfigRoot(env), "skills", name) || !/^[a-f0-9]{64}$/.test(skill.sha256 ?? ""))
26908
+ if (skill.name !== name || skill.root !== path17.join(claudeConfigRoot(env), "skills", name) || !/^[a-f0-9]{64}$/.test(skill.sha256 ?? ""))
26312
26909
  fail6("claude_skill_requires_review");
26313
26910
  if (!await observedSkill(skill, record2)) return false;
26314
26911
  }
@@ -26348,12 +26945,12 @@ async function installClaudeMcpFallback({
26348
26945
  } else if (saved && !pending) fail6("legacy_mcp_entry_requires_review");
26349
26946
  if (await info3(versionRoot)) await verifyVersion(versionRoot, complete);
26350
26947
  else {
26351
- await mkdir6(temporary, { mode: 448 });
26948
+ await mkdir7(temporary, { mode: 448 });
26352
26949
  for (const file of payload.files) {
26353
26950
  signal?.throwIfAborted();
26354
- const dest = path15.join(temporary, file.path);
26355
- await mkdir6(path15.dirname(dest), { recursive: true, mode: 448 });
26356
- const fd = await open9(dest, "wx", 384);
26951
+ const dest = path17.join(temporary, file.path);
26952
+ await mkdir7(path17.dirname(dest), { recursive: true, mode: 448 });
26953
+ const fd = await open10(dest, "wx", 384);
26357
26954
  try {
26358
26955
  await fd.writeFile(file.body);
26359
26956
  await fd.sync();
@@ -26362,21 +26959,21 @@ async function installClaudeMcpFallback({
26362
26959
  }
26363
26960
  }
26364
26961
  await checkRuntime(temporary, payload.version);
26365
- await atomicJSON3(path15.join(temporary, "installation.json"), { ...complete, nodeCommand });
26962
+ await atomicJSON3(path17.join(temporary, "installation.json"), { ...complete, nodeCommand });
26366
26963
  signal?.throwIfAborted();
26367
- await rename6(temporary, versionRoot);
26964
+ await rename7(temporary, versionRoot);
26368
26965
  newFiles = payload.files.length;
26369
26966
  }
26370
26967
  const ready = await verifyVersion(versionRoot, complete);
26371
26968
  complete.server = mcpDefinition(complete, ready.nodeCommand);
26372
26969
  if (newFiles === 0) await verifyInstalledRuntime(versionRoot, payload.version, ready.nodeCommand, { env });
26373
- const skillRoot = path15.join(claudeConfigRoot(env), "skills");
26374
- await mkdir6(skillRoot, { recursive: true, mode: 448 });
26375
- const parent = await lstat10(skillRoot);
26970
+ const skillRoot = path17.join(claudeConfigRoot(env), "skills");
26971
+ await mkdir7(skillRoot, { recursive: true, mode: 448 });
26972
+ const parent = await lstat11(skillRoot);
26376
26973
  if (!parent.isDirectory() || parent.isSymbolicLink() || parent.uid !== process.getuid?.()) fail6("claude_skill_requires_review");
26377
26974
  const plans = [];
26378
26975
  for (const sourceName of ["creation-setup", "video-creation"]) {
26379
- const name = sourceName + suffix, body = skillBody(payload, sourceName, name), skill = { name, root: path15.join(skillRoot, name), sha256: hash5(body) };
26976
+ const name = sourceName + suffix, body = skillBody(payload, sourceName, name), skill = { name, root: path17.join(skillRoot, name), sha256: hash6(body) };
26380
26977
  if (pending) {
26381
26978
  const old = pending.skills?.find((s3) => s3.name === name);
26382
26979
  if (!old || old.root !== skill.root || old.sha256 !== skill.sha256) fail6("registration_unconfirmed_keep_existing");
@@ -26385,7 +26982,7 @@ async function installClaudeMcpFallback({
26385
26982
  const existing = await info3(skill.root);
26386
26983
  let beforeSHA = null;
26387
26984
  if (existing) {
26388
- const marker = await privateRead4(path15.join(skill.root, "promptframe-installation.json"));
26985
+ const marker = await privateRead4(path17.join(skill.root, "promptframe-installation.json"));
26389
26986
  if (!marker || marker.profile !== profile || marker.configFile !== configFile2 || marker.name !== name) fail6("claude_skill_requires_review");
26390
26987
  const old = { ...skill, sha256: marker.sha256 };
26391
26988
  if (!await observedSkill(old, complete)) fail6("claude_skill_requires_review");
@@ -26406,10 +27003,10 @@ async function installClaudeMcpFallback({
26406
27003
  } else {
26407
27004
  if (plan.beforeSHA !== null) fail6("claude_skill_requires_review");
26408
27005
  await claimSkillDirectory(plan.root);
26409
- await atomicJSON3(path15.join(plan.root, "promptframe-installation.json"), { host: "claude-code", profile, configFile: configFile2, name: plan.name, sha256: null });
27006
+ await atomicJSON3(path17.join(plan.root, "promptframe-installation.json"), { host: "claude-code", profile, configFile: configFile2, name: plan.name, sha256: null });
26410
27007
  }
26411
- await writeSkill(path15.join(plan.root, "SKILL.md"), plan.body);
26412
- await atomicJSON3(path15.join(plan.root, "promptframe-installation.json"), { host: "claude-code", profile, configFile: configFile2, name: plan.name, sha256: plan.sha256 });
27008
+ await writeSkill(path17.join(plan.root, "SKILL.md"), plan.body);
27009
+ await atomicJSON3(path17.join(plan.root, "promptframe-installation.json"), { host: "claude-code", profile, configFile: configFile2, name: plan.name, sha256: plan.sha256 });
26413
27010
  }
26414
27011
  signal?.throwIfAborted();
26415
27012
  if (compareVersions2(payload.version, "0.3.1") >= 0) complete.hostHooks = await registerClaudeFallbackHooks({ record: complete, root, env, nodeCommand: ready.nodeCommand, signal });
@@ -26434,9 +27031,9 @@ async function installClaudeMcpFallback({
26434
27031
  requestedVersion: payload.version,
26435
27032
  versionStatus: "current"
26436
27033
  };
26437
- } catch (error4) {
27034
+ } catch (error5) {
26438
27035
  if (writeStarted) fail6("registration_unconfirmed_keep_existing", { phase: "registration_observation", localRegistrationState: "unknown", action: "inspect_same_registration_no_second_add" });
26439
- if (error4 instanceof CreationClientError) throw error4;
27036
+ if (error5 instanceof CreationClientError) throw error5;
26440
27037
  fail6(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
26441
27038
  } finally {
26442
27039
  await rm4(temporary, { recursive: true, force: true });
@@ -26454,7 +27051,7 @@ var ClaudeInstallationError = class extends CreationClientError {
26454
27051
  this.details = details;
26455
27052
  }
26456
27053
  };
26457
- var claudeInstallationDetails = (error4) => error4 instanceof ClaudeInstallationError ? error4.details : void 0;
27054
+ var claudeInstallationDetails = (error5) => error5 instanceof ClaudeInstallationError ? error5.details : void 0;
26458
27055
  var fail7 = (code, details) => {
26459
27056
  throw new ClaudeInstallationError(code, details);
26460
27057
  };
@@ -26478,7 +27075,7 @@ async function registrations(run, pluginName, marketplace, root) {
26478
27075
  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"))
26479
27076
  fail7("claude_local_registration_unconfirmed");
26480
27077
  const related = plugins.filter((p2) => typeof p2?.id === "string" && p2.id.startsWith(pluginName + "@"));
26481
- if (related.length > 1 || related.some((p2) => p2.id !== pluginName + "@" + marketplace || p2.scope !== "user" || typeof p2.enabled !== "boolean" || !/^\d+\.\d+\.\d+$/.test(p2.version ?? "") || !path16.isAbsolute(p2.installPath ?? "") || p2.readFromFolder !== void 0 && (!path16.isAbsolute(p2.readFromFolder) || !/^\d+\.\d+\.\d+$/.test(p2.folderVersion ?? ""))))
27078
+ if (related.length > 1 || related.some((p2) => p2.id !== pluginName + "@" + marketplace || p2.scope !== "user" || typeof p2.enabled !== "boolean" || !/^\d+\.\d+\.\d+$/.test(p2.version ?? "") || !path18.isAbsolute(p2.installPath ?? "") || p2.readFromFolder !== void 0 && (!path18.isAbsolute(p2.readFromFolder) || !/^\d+\.\d+\.\d+$/.test(p2.folderVersion ?? ""))))
26482
27079
  fail7("claude_existing_registration_requires_review");
26483
27080
  const found = markets.filter((p2) => p2?.name === marketplace);
26484
27081
  if (found.length > 1 || found.some((p2) => p2.source !== "directory" || p2.path !== root || p2.installLocation !== root))
@@ -26495,22 +27092,22 @@ function transport(serverName, configFile2, command2 = process.execPath) {
26495
27092
  } } };
26496
27093
  }
26497
27094
  async function verifyVersion2(root, { version: version3, profile, configFile: configFile2, payloadDigest, pluginName, serverName }) {
26498
- const directory2 = await info4(root);
26499
- if (!directory2?.isDirectory() || directory2.isSymbolicLink() || directory2.uid !== process.getuid?.() || directory2.mode & 63)
27095
+ const directory3 = await info4(root);
27096
+ if (!directory3?.isDirectory() || directory3.isSymbolicLink() || directory3.uid !== process.getuid?.() || directory3.mode & 63)
26500
27097
  fail7("claude_installed_files_invalid");
26501
- const ready = await privateRead5(path16.join(root, "installation.json"));
27098
+ const ready = await privateRead5(path18.join(root, "installation.json"));
26502
27099
  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");
26503
27100
  const actual = await inspectRuntimePackage(root);
26504
- if (actual.version !== version3 || JSON.stringify(actual.files.map(({ path: path18, bytes: bytes2, sha256 }) => ({ path: path18, bytes: bytes2, sha256 }))) !== JSON.stringify(ready.files))
27101
+ if (actual.version !== version3 || JSON.stringify(actual.files.map(({ path: path20, bytes: bytes2, sha256 }) => ({ path: path20, bytes: bytes2, sha256 }))) !== JSON.stringify(ready.files))
26505
27102
  fail7("claude_installed_files_invalid");
26506
- const manifest = JSON.parse(await readFile9(path16.join(root, ".claude-plugin/plugin.json"), "utf8"));
27103
+ const manifest = JSON.parse(await readFile9(path18.join(root, ".claude-plugin/plugin.json"), "utf8"));
26507
27104
  if (manifest.name !== pluginName || manifest.version !== version3 || manifest.skills !== "./skills/" || manifest.mcpServers !== "./.claude-mcp.json")
26508
27105
  fail7("claude_installed_files_invalid");
26509
27106
  let runtimeCommand;
26510
27107
  for (const file of [".mcp.json", ".claude-mcp.json"]) {
26511
- const mcp = JSON.parse(await readFile9(path16.join(root, file), "utf8"));
27108
+ const mcp = JSON.parse(await readFile9(path18.join(root, file), "utf8"));
26512
27109
  const command2 = mcp.mcpServers?.[serverName]?.command;
26513
- if (!path16.isAbsolute(command2 ?? "") || runtimeCommand !== void 0 && command2 !== runtimeCommand || JSON.stringify(mcp) !== JSON.stringify(transport(serverName, configFile2, command2))) fail7("claude_installed_files_invalid");
27110
+ if (!path18.isAbsolute(command2 ?? "") || runtimeCommand !== void 0 && command2 !== runtimeCommand || JSON.stringify(mcp) !== JSON.stringify(transport(serverName, configFile2, command2))) fail7("claude_installed_files_invalid");
26514
27111
  runtimeCommand = command2;
26515
27112
  }
26516
27113
  if (compareVersions3(version3, "0.3.1") >= 0 && JSON.stringify(manifest.hooks) !== JSON.stringify(claudeHostHooks({ pluginName, configFile: configFile2, nodeCommand: runtimeCommand })))
@@ -26520,7 +27117,7 @@ async function verifyVersion2(root, { version: version3, profile, configFile: co
26520
27117
  async function installForClaudeUser(options = {}) {
26521
27118
  const profile = options.profile ?? "default", env = options.env ?? process.env;
26522
27119
  validProfile2(profile);
26523
- const modeRoot = path16.resolve(env.XDG_DATA_HOME ?? path16.join(homedir9(), ".local/share"), "promptframe-creation", profile, "claude-code-mode");
27120
+ const modeRoot = path18.resolve(env.XDG_DATA_HOME ?? path18.join(homedir10(), ".local/share"), "promptframe-creation", profile, "claude-code-mode");
26524
27121
  await privateDirectory6(modeRoot);
26525
27122
  const release = await acquire4(modeRoot, options.signal);
26526
27123
  try {
@@ -26542,37 +27139,37 @@ async function installClaudeUserLocked({
26542
27139
  nodeCommand = process.execPath
26543
27140
  } = {}) {
26544
27141
  validProfile2(profile);
26545
- if (!path16.isAbsolute(nodeCommand)) fail7("runtime_command_invalid");
27142
+ if (!path18.isAbsolute(nodeCommand)) fail7("runtime_command_invalid");
26546
27143
  const hostVersion = (await runClaude(["--version"])).trim().match(/^(\d+\.\d+\.\d+) \(Claude Code\)$/);
26547
27144
  if (!hostVersion || compareVersions3(hostVersion[1], "2.1.295") < 0) fail7("claude_21295_required");
26548
27145
  const help = await runClaude(["--help"]);
26549
27146
  if (typeof help !== "string" || Buffer.byteLength(help) > 128 * 1024) fail7("claude_capabilities_unconfirmed");
26550
27147
  const hasPlugin = /^\s+plugin(?:\|plugins)?\s/m.test(help), hasMcp = /^\s+mcp\s/m.test(help);
26551
- const base = path16.resolve(env.XDG_DATA_HOME ?? path16.join(homedir9(), ".local/share"), "promptframe-creation", profile), fallbackRoot = path16.join(base, "claude-code-mcp"), pluginRoot = path16.join(base, "claude-code");
26552
- const pluginPending = await info4(path16.join(pluginRoot, "registration-pending.json")), pluginCurrent = await info4(path16.join(pluginRoot, "current.json")), fallbackState = await info4(path16.join(fallbackRoot, "current.json")) || await info4(path16.join(fallbackRoot, "registration-pending.json"));
27148
+ const base = path18.resolve(env.XDG_DATA_HOME ?? path18.join(homedir10(), ".local/share"), "promptframe-creation", profile), fallbackRoot = path18.join(base, "claude-code-mcp"), pluginRoot = path18.join(base, "claude-code");
27149
+ const pluginPending = await info4(path18.join(pluginRoot, "registration-pending.json")), pluginCurrent = await info4(path18.join(pluginRoot, "current.json")), fallbackState = await info4(path18.join(fallbackRoot, "current.json")) || await info4(path18.join(fallbackRoot, "registration-pending.json"));
26553
27150
  if ((!hasPlugin || fallbackState) && (pluginPending || pluginCurrent)) fail7("registration_unconfirmed_keep_existing");
26554
27151
  if (!hasPlugin || fallbackState) {
26555
27152
  if (!hasMcp) fail7("claude_capabilities_unconfirmed");
26556
27153
  return installClaudeMcpFallback({ sourceRoot, profile, env, configFile: configFile2, signal, runClaude, checkRuntime, verifyInstalledRuntime, nodeCommand });
26557
27154
  }
26558
- const payload = await inspectRuntimePackage(path16.resolve(sourceRoot));
27155
+ const payload = await inspectRuntimePackage(path18.resolve(sourceRoot));
26559
27156
  if (!payload.files.some((f2) => f2.path === ".claude-plugin/plugin.json") || !payload.files.some((f2) => f2.path === ".claude-mcp.json"))
26560
27157
  fail7("claude_package_incomplete");
26561
- const root = path16.resolve(env.XDG_DATA_HOME ?? path16.join(homedir9(), ".local/share"), "promptframe-creation", profile, "claude-code");
27158
+ const root = path18.resolve(env.XDG_DATA_HOME ?? path18.join(homedir10(), ".local/share"), "promptframe-creation", profile, "claude-code");
26562
27159
  await privateDirectory6(root);
26563
27160
  const release = await acquire4(root, signal);
26564
27161
  const suffix = profile === "default" ? "" : "-" + profile, pluginName = "promptframe-creation" + suffix, marketplace = "promptframe-creation-user" + suffix, pluginId = pluginName + "@" + marketplace, serverName = "promptframe" + suffix;
26565
- const versions = path16.join(root, "versions"), currentFile = path16.join(root, "current.json"), pendingFile = path16.join(root, "registration-pending.json"), catalogFile = path16.join(root, ".claude-plugin/marketplace.json"), versionRoot = path16.join(versions, payload.version), temporary = path16.join(versions, ".partial-" + randomBytes7(12).toString("hex"));
27162
+ const versions = path18.join(root, "versions"), currentFile = path18.join(root, "current.json"), pendingFile = path18.join(root, "registration-pending.json"), catalogFile = path18.join(root, ".claude-plugin/marketplace.json"), versionRoot = path18.join(versions, payload.version), temporary = path18.join(versions, ".partial-" + randomBytes7(12).toString("hex"));
26566
27163
  let registrationStarted = false, newFiles = 0;
26567
27164
  try {
26568
27165
  signal?.throwIfAborted();
26569
27166
  await privateDirectory6(versions);
26570
- await privateDirectory6(path16.dirname(catalogFile));
27167
+ await privateDirectory6(path18.dirname(catalogFile));
26571
27168
  await legacyUserMcp(env, serverName);
26572
27169
  let previous = await privateRead5(currentFile), pending = await privateRead5(pendingFile), state = await registrations(runClaude, pluginName, marketplace, root);
26573
27170
  const binding = { profile, configFile: configFile2, pluginId, pluginName, serverName, host: "claude-code" };
26574
27171
  const checkBinding = (record2) => {
26575
- if (record2 && (record2.profile !== profile || record2.configFile !== configFile2 || record2.pluginId !== pluginId || record2.host !== "claude-code" || !/^\d+\.\d+\.\d+$/.test(record2.version ?? "") || record2.versionRoot !== path16.join(versions, record2.version))) fail7("profile_binding_conflict");
27172
+ if (record2 && (record2.profile !== profile || record2.configFile !== configFile2 || record2.pluginId !== pluginId || record2.host !== "claude-code" || !/^\d+\.\d+\.\d+$/.test(record2.version ?? "") || record2.versionRoot !== path18.join(versions, record2.version))) fail7("profile_binding_conflict");
26576
27173
  };
26577
27174
  checkBinding(previous);
26578
27175
  checkBinding(pending);
@@ -26616,12 +27213,12 @@ async function installClaudeUserLocked({
26616
27213
  const ready = await verifyVersion2(versionRoot, { ...complete, pluginName, serverName });
26617
27214
  runtimeCommands.set(versionRoot, ready.runtimeCommand);
26618
27215
  } else {
26619
- await mkdir7(temporary, { mode: 448 });
27216
+ await mkdir8(temporary, { mode: 448 });
26620
27217
  for (const file of payload.files) {
26621
27218
  signal?.throwIfAborted();
26622
- const dest = path16.join(temporary, file.path);
26623
- await mkdir7(path16.dirname(dest), { recursive: true, mode: 448 });
26624
- const fd = await open10(dest, "wx", 384);
27219
+ const dest = path18.join(temporary, file.path);
27220
+ await mkdir8(path18.dirname(dest), { recursive: true, mode: 448 });
27221
+ const fd = await open11(dest, "wx", 384);
26625
27222
  try {
26626
27223
  await fd.writeFile(file.body);
26627
27224
  await fd.sync();
@@ -26629,21 +27226,21 @@ async function installClaudeUserLocked({
26629
27226
  await fd.close();
26630
27227
  }
26631
27228
  }
26632
- const manifest = JSON.parse(await readFile9(path16.join(temporary, ".claude-plugin/plugin.json"), "utf8"));
27229
+ const manifest = JSON.parse(await readFile9(path18.join(temporary, ".claude-plugin/plugin.json"), "utf8"));
26633
27230
  manifest.name = pluginName;
26634
27231
  if (manifest.hooks) manifest.hooks = claudeHostHooks({ pluginName, configFile: configFile2, nodeCommand });
26635
- await atomicJSON4(path16.join(temporary, ".claude-plugin/plugin.json"), manifest);
26636
- for (const file of [".mcp.json", ".claude-mcp.json"]) await atomicJSON4(path16.join(temporary, file), transport(serverName, configFile2, nodeCommand));
27232
+ await atomicJSON4(path18.join(temporary, ".claude-plugin/plugin.json"), manifest);
27233
+ for (const file of [".mcp.json", ".claude-mcp.json"]) await atomicJSON4(path18.join(temporary, file), transport(serverName, configFile2, nodeCommand));
26637
27234
  await checkRuntime(temporary, payload.version);
26638
27235
  const installed = await inspectRuntimePackage(temporary);
26639
- await atomicJSON4(path16.join(temporary, "installation.json"), {
27236
+ await atomicJSON4(path18.join(temporary, "installation.json"), {
26640
27237
  ...binding,
26641
27238
  version: payload.version,
26642
27239
  payloadDigest: payload.payloadDigest,
26643
- files: installed.files.map(({ path: path18, bytes: bytes2, sha256 }) => ({ path: path18, bytes: bytes2, sha256 }))
27240
+ files: installed.files.map(({ path: path20, bytes: bytes2, sha256 }) => ({ path: path20, bytes: bytes2, sha256 }))
26644
27241
  });
26645
27242
  signal?.throwIfAborted();
26646
- await rename7(temporary, versionRoot);
27243
+ await rename8(temporary, versionRoot);
26647
27244
  newFiles = payload.files.length;
26648
27245
  }
26649
27246
  if (newFiles === 0) await verifyInstalledRuntime(versionRoot, payload.version, runtimeCommands.get(versionRoot), { env });
@@ -26678,14 +27275,14 @@ async function installClaudeUserLocked({
26678
27275
  requestedVersion: payload.version,
26679
27276
  recordedRuntimeRetained: runtimeCommands.has(versionRoot) && runtimeCommands.get(versionRoot) !== nodeCommand
26680
27277
  };
26681
- } catch (error4) {
27278
+ } catch (error5) {
26682
27279
  if (registrationStarted) fail7("registration_unconfirmed_keep_existing", {
26683
- ...claudeErrorDetails(error4),
27280
+ ...claudeErrorDetails(error5),
26684
27281
  phase: "registration_observation",
26685
27282
  localRegistrationState: "unknown",
26686
27283
  action: "inspect_same_registration_no_second_add"
26687
27284
  });
26688
- if (error4 instanceof CreationClientError) throw error4;
27285
+ if (error5 instanceof CreationClientError) throw error5;
26689
27286
  fail7(signal?.aborted ? "interrupted_keep_existing" : "failed_keep_existing");
26690
27287
  } finally {
26691
27288
  await rm5(temporary, { recursive: true, force: true });
@@ -26695,7 +27292,7 @@ async function installClaudeUserLocked({
26695
27292
 
26696
27293
  // lib/cli.mjs
26697
27294
  import { fileURLToPath } from "node:url";
26698
- import path17 from "node:path";
27295
+ import path19 from "node:path";
26699
27296
  var args = process.argv.slice(2);
26700
27297
  var command = args.shift();
26701
27298
  var value = (key) => {
@@ -26703,15 +27300,31 @@ var value = (key) => {
26703
27300
  return i < 0 ? void 0 : args[i + 1];
26704
27301
  };
26705
27302
  var log = (value2) => process.stdout.write(JSON.stringify(value2) + "\n");
26706
- var configFile = () => value("--config") ? path17.resolve(value("--config")) : profileCredentialsPath(value("--profile") ?? "default");
27303
+ var configFile = () => value("--config") ? path19.resolve(value("--config")) : profileCredentialsPath(value("--profile") ?? "default");
26707
27304
  async function probe(credentials) {
26708
27305
  const client = await connectPlatform(credentials, { host: resolveHostIdentity({ host: value("--host") }) });
26709
27306
  try {
26710
- return (await client.listTools()).tools.length;
27307
+ return { tools: (await client.listTools()).tools.length, accountIdentity: connectionAccountIdentity(client) };
26711
27308
  } finally {
26712
27309
  await client.close();
26713
27310
  }
26714
27311
  }
27312
+ async function rememberAuthorization(credentials, file, accountIdentity) {
27313
+ if (!accountIdentity) return;
27314
+ try {
27315
+ await recordLocalAuthorization({
27316
+ identity: accountIdentity,
27317
+ client: "creation",
27318
+ configFile: file,
27319
+ endpoint: credentials.endpoint,
27320
+ token: credentials.token,
27321
+ profile: value("--profile") ?? "default"
27322
+ });
27323
+ return { status: "recorded" };
27324
+ } catch (error5) {
27325
+ return { status: "unavailable", reasonCode: error5 instanceof CreationClientError ? error5.message : "accounts.storage_unavailable" };
27326
+ }
27327
+ }
26715
27328
  async function tokenInput() {
26716
27329
  if (args.includes("--token-stdin")) {
26717
27330
  let text = "";
@@ -26773,8 +27386,9 @@ async function setup({ silent = false } = {}) {
26773
27386
  );
26774
27387
  if (existing && !args.includes("--replace")) {
26775
27388
  try {
26776
- const tools2 = await probe(existing);
26777
- const result2 = { connected: true, reused: true, endpoint, tools: tools2 };
27389
+ const { tools: tools2, accountIdentity: accountIdentity2 } = await probe(existing);
27390
+ const accountDirectory2 = await rememberAuthorization(existing, file, accountIdentity2);
27391
+ const result2 = { connected: true, reused: true, endpoint, tools: tools2, ...accountIdentity2 ? { accountIdentity: accountIdentity2, accountDirectory: accountDirectory2 } : {} };
26778
27392
  if (!silent) log(result2);
26779
27393
  return result2;
26780
27394
  } catch {
@@ -26812,9 +27426,10 @@ async function setup({ silent = false } = {}) {
26812
27426
  clientName: value("--name") ?? existing?.clientName ?? (resolveHostIdentity({ host: value("--host") }).kind === "claude-code" ? "Claude Code PromptFrame" : "Codex PromptFrame"),
26813
27427
  createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
26814
27428
  };
26815
- const tools = await probe(credentials);
27429
+ const { tools, accountIdentity } = await probe(credentials);
26816
27430
  await writeCredentials(credentials, file);
26817
- const result = { connected: true, reused: false, endpoint, tools };
27431
+ const accountDirectory = await rememberAuthorization(credentials, file, accountIdentity);
27432
+ const result = { connected: true, reused: false, endpoint, tools, ...accountIdentity ? { accountIdentity, accountDirectory } : {} };
26818
27433
  if (!silent) log(result);
26819
27434
  return result;
26820
27435
  }
@@ -26843,14 +27458,14 @@ async function bridge() {
26843
27458
  resolvedVersion: value("--resolved-runtime-version"),
26844
27459
  signal: startup.signal,
26845
27460
  hostKind: identity.kind,
26846
- cacheRoot: path17.join(path17.dirname(configFile()), "runtime-cache")
27461
+ cacheRoot: path19.join(path19.dirname(configFile()), "runtime-cache")
26847
27462
  });
26848
27463
  startup.signal.throwIfAborted();
26849
- } catch (error4) {
27464
+ } catch (error5) {
26850
27465
  await client?.close().catch(() => {
26851
27466
  });
26852
27467
  if (startup.signal.aborted) throw new CreationClientError("creation.runtime_selection_interrupted");
26853
- throw error4;
27468
+ throw error5;
26854
27469
  } finally {
26855
27470
  process.removeListener("SIGINT", abort);
26856
27471
  process.removeListener("SIGTERM", abort);
@@ -26861,6 +27476,7 @@ async function bridge() {
26861
27476
  process.exitCode = result.code;
26862
27477
  return;
26863
27478
  }
27479
+ await rememberAuthorization(credentials, configFile(), connectionAccountIdentity(client));
26864
27480
  const hostSession = identity.kind === "claude-code" ? await createClaudeHostSession({ configFile: configFile() }) : void 0;
26865
27481
  const server = new Server(
26866
27482
  { name: "promptframe-creation", version: CLIENT_VERSION },
@@ -26870,14 +27486,20 @@ async function bridge() {
26870
27486
  ...upstream.prompts ? { prompts: { listChanged: true } } : {},
26871
27487
  experimental: {
26872
27488
  ...policy ? { "promptframe.creation": policy } : {},
26873
- "promptframe.runtime": { version: selection.version, locked: selection.locked, status: selection.status }
27489
+ "promptframe.runtime": { version: selection.version, locked: selection.locked, status: selection.status },
27490
+ "promptframe.localAccounts": { contractVersion: "promptframe-local-account-directory/v1", selectionScope: "host-session" }
26874
27491
  }
26875
27492
  } }
26876
- ), host = createHostCallBridge(client, {
27493
+ ), host = createAccountAwareBridge(client, {
26877
27494
  credentials,
27495
+ configFile: configFile(),
26878
27496
  host: identity,
26879
27497
  hostSession,
26880
- localUploads: createLocalUploadManager({ stateRoot: path17.join(path17.dirname(configFile()), "local-upload-state") }),
27498
+ connectionOptions: { contentTypes: () => contentTypes, contentSource: () => contentSource },
27499
+ createLocalUploads: ({ identity: account, agent, configFile: file }) => createLocalUploadManager({
27500
+ stateRoot: path19.join(path19.dirname(file), "local-upload-state", "accounts", localAccountKey(account), localAgentDigest(agent).slice(7))
27501
+ }),
27502
+ localUploads: createLocalUploadManager({ stateRoot: path19.join(path19.dirname(configFile()), "local-upload-state") }),
26881
27503
  onCatalogChange: () => server.sendToolListChanged(),
26882
27504
  onKnowledgeChange: (kind) => kind === "resources" ? server.sendResourceListChanged() : server.sendPromptListChanged()
26883
27505
  });
@@ -26892,11 +27514,11 @@ async function bridge() {
26892
27514
  const knowledgeHandler = (schema, method) => server.setRequestHandler(schema, async (request) => {
26893
27515
  try {
26894
27516
  return await host[method](request.params ?? {});
26895
- } catch (error4) {
26896
- const remote = error4?.data?.errorCode;
26897
- const code = error4 instanceof CreationClientError ? error4.message : typeof remote === "string" && /^(?:creation|creative_skill)\.[a-z0-9_.:-]{1,160}$/.test(remote) ? remote : "creation.connection_unresolved";
26898
- const knownRemote = typeof remote === "string" && code === remote && typeof error4.code === "number" && Object.values(ErrorCode).includes(error4.code);
26899
- throw new McpError(knownRemote ? error4.code : error4 instanceof CreationClientError ? ErrorCode.InvalidParams : ErrorCode.InternalError, code, { errorCode: code });
27517
+ } catch (error5) {
27518
+ const remote = error5?.data?.errorCode;
27519
+ const code = error5 instanceof CreationClientError ? error5.message : typeof remote === "string" && /^(?:creation|creative_skill)\.[a-z0-9_.:-]{1,160}$/.test(remote) ? remote : "creation.connection_unresolved";
27520
+ const knownRemote = typeof remote === "string" && code === remote && typeof error5.code === "number" && Object.values(ErrorCode).includes(error5.code);
27521
+ throw new McpError(knownRemote ? error5.code : error5 instanceof CreationClientError ? ErrorCode.InvalidParams : ErrorCode.InternalError, code, { errorCode: code });
26900
27522
  }
26901
27523
  });
26902
27524
  if (upstream.resources) {
@@ -26908,9 +27530,9 @@ async function bridge() {
26908
27530
  knowledgeHandler(ListPromptsRequestSchema, "listPrompts");
26909
27531
  knowledgeHandler(GetPromptRequestSchema, "getPrompt");
26910
27532
  }
26911
- server.setRequestHandler(ListToolsRequestSchema, async () => {
27533
+ server.setRequestHandler(ListToolsRequestSchema, async (request) => {
26912
27534
  try {
26913
- return await host.listTools();
27535
+ return await host.listTools(request.params ?? {});
26914
27536
  } catch {
26915
27537
  throw new Error("creation.connection_unresolved");
26916
27538
  }
@@ -26918,7 +27540,7 @@ async function bridge() {
26918
27540
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
26919
27541
  try {
26920
27542
  return await host.call(request.params, { signal: extra.signal });
26921
- } catch (error4) {
27543
+ } catch (error5) {
26922
27544
  return {
26923
27545
  isError: true,
26924
27546
  content: [
@@ -26926,9 +27548,9 @@ async function bridge() {
26926
27548
  type: "text",
26927
27549
  text: JSON.stringify({
26928
27550
  success: false,
26929
- errorCode: error4 instanceof CreationClientError ? error4.message : "creation.connection_unresolved",
26930
- ...error4 instanceof CreationClientError && error4.message === "creation.host_session_changed" ? { effectStatus: "unknown", automaticReplayAllowed: false } : {},
26931
- action: error4 instanceof CreationClientError ? error4.message === "creation.host_session_changed" ? "read_original_task_without_replaying_business" : error4.message.startsWith("creation.host_") ? "use_supported_host_with_session_identity" : error4.message === "creation.editor_not_current" ? "request_control_and_confirm_in_studio" : "read_current_platform_facts_without_replaying_business" : "read_original_task_or_retry_same_idempotency_key"
27551
+ errorCode: error5 instanceof CreationClientError ? error5.message : "creation.connection_unresolved",
27552
+ ...error5 instanceof CreationClientError && error5.message === "creation.host_session_changed" ? { effectStatus: "unknown", automaticReplayAllowed: false } : {},
27553
+ action: error5 instanceof CreationClientError ? error5.message === "creation.host_session_changed" ? "read_original_task_without_replaying_business" : error5.message.startsWith("creation.host_") ? "use_supported_host_with_session_identity" : error5.message === "creation.editor_not_current" ? "request_control_and_confirm_in_studio" : "read_current_platform_facts_without_replaying_business" : "read_original_task_or_retry_same_idempotency_key"
26932
27554
  })
26933
27555
  }
26934
27556
  ]
@@ -27000,29 +27622,41 @@ try {
27000
27622
  } else if (command === "bridge") await bridge();
27001
27623
  else if (command === "claude-host-hook") await runClaudeHostHook({ configFile: configFile() });
27002
27624
  else if (command === "--version") process.stdout.write(CLIENT_VERSION + "\n");
27003
- else if (command === "status") {
27625
+ else if (command === "accounts") {
27626
+ if (args[0] === "refresh") {
27627
+ const file = configFile(), saved = await readCredentials(file);
27628
+ if (!saved) throw new CreationClientError("setup.required");
27629
+ const { accountIdentity } = await probe(saved);
27630
+ if (!accountIdentity) throw new CreationClientError("accounts.identity_unavailable");
27631
+ const accountDirectory = await rememberAuthorization(saved, file, accountIdentity);
27632
+ if (accountDirectory.status !== "recorded") throw new CreationClientError(accountDirectory.reasonCode);
27633
+ log({ accountIdentity, accountDirectory });
27634
+ } else if (args[0] === void 0 || args[0] === "list") log(await listLocalAccounts());
27635
+ else throw new CreationClientError("command.unknown");
27636
+ } else if (command === "status") {
27004
27637
  const saved = await readCredentials(configFile());
27005
27638
  if (!saved) throw new CreationClientError("setup.required");
27639
+ const observation = await probe(saved);
27006
27640
  log({
27007
27641
  connected: true,
27008
27642
  endpoint: saved.endpoint,
27009
- tools: await probe(saved)
27643
+ ...observation
27010
27644
  });
27011
27645
  } else if (command === "help" || command === "--help" || !command) {
27012
27646
  process.stdout.write(
27013
- "promptframe-creation connect --endpoint <platform-api-base> [--host codex|claude-code] [--profile <environment-account>] [--claude-bin <absolute-file>] [--no-open]\npromptframe-creation setup --endpoint <platform-api-base> [--host codex|claude-code] [--no-open] [--replace] [--name <client-name>]\npromptframe-creation status [--profile <environment-account>] [--host codex|claude-code]\npromptframe-creation bridge [--config <private-file>] [--host codex|claude-code] [--bridge-version <X.Y.Z>]\npromptframe-creation --version\nNode.js >=20 is required. Plugin installation supports Codex >=0.160.0 or Claude Code >=2.1.295 with its structured plugin commands. Token input is masked in a terminal or accepted through --token-stdin; never use a Token command argument.\nBridge startup checks the platform minimum/recommended version. --bridge-version locks one exact compatible version for this new session; active bridges are not replaced.\n"
27647
+ "promptframe-creation connect --endpoint <platform-api-base> [--host codex|claude-code] [--profile <environment-account>] [--claude-bin <absolute-file>] [--no-open]\npromptframe-creation setup --endpoint <platform-api-base> [--host codex|claude-code] [--no-open] [--replace] [--name <client-name>]\npromptframe-creation status [--profile <environment-account>] [--host codex|claude-code]\npromptframe-creation accounts list\npromptframe-creation accounts refresh [--profile <environment-account>] [--host codex|claude-code]\npromptframe-creation bridge [--config <private-file>] [--host codex|claude-code] [--bridge-version <X.Y.Z>]\npromptframe-creation --version\nNode.js >=20 is required. Plugin installation supports Codex >=0.160.0 or Claude Code >=2.1.295 with its structured plugin commands. Token input is masked in a terminal or accepted through --token-stdin; never use a Token command argument.\nBridge startup checks the platform minimum/recommended version. --bridge-version locks one exact compatible version for this new session; active bridges are not replaced.\n"
27014
27648
  );
27015
27649
  } else throw new CreationClientError("command.unknown");
27016
- } catch (error4) {
27650
+ } catch (error5) {
27017
27651
  process.stderr.write(
27018
27652
  JSON.stringify({
27019
- ...installationErrorDetails(error4),
27020
- ...claudeInstallationDetails(error4),
27021
- ...claudeErrorDetails(error4),
27022
- ...fallbackErrorDetails(error4),
27023
- ...bridgeErrorDetails(error4),
27024
- ...runtimeErrorDetails(error4),
27025
- error: error4 instanceof CreationClientError ? error4.message : "creation.connection_failed"
27653
+ ...installationErrorDetails(error5),
27654
+ ...claudeInstallationDetails(error5),
27655
+ ...claudeErrorDetails(error5),
27656
+ ...fallbackErrorDetails(error5),
27657
+ ...bridgeErrorDetails(error5),
27658
+ ...runtimeErrorDetails(error5),
27659
+ error: error5 instanceof CreationClientError ? error5.message : "creation.connection_failed"
27026
27660
  }) + "\n"
27027
27661
  );
27028
27662
  process.exitCode = 1;