@andpipes/cli 0.1.4 → 0.1.6

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/bin.cjs CHANGED
@@ -19,7 +19,7 @@ function readVersion() {
19
19
  }
20
20
 
21
21
  // src/cli.ts
22
- var import_localization13 = require("@andpipes/localization");
22
+ var import_localization14 = require("@andpipes/localization");
23
23
  var import_commander = require("commander");
24
24
 
25
25
  // src/commands/audit-export.ts
@@ -467,6 +467,26 @@ var ConfirmationRequiredError = class extends Error {
467
467
  }
468
468
  };
469
469
 
470
+ // src/lib/publication-review-profile.ts
471
+ var CLI_PUBLICATION_REVIEW_PROFILE = 2;
472
+ var PUBLICATION_ERROR_REASON_CODES = Object.freeze({
473
+ publication_plan_stale: "AP_CONFLICT",
474
+ publication_review_profile_invalid: "AP_INPUT_INVALID",
475
+ publication_schema_review_too_large: "AP_INPUT_INVALID",
476
+ schema_review_receipt_mismatch: "AP_CONFLICT"
477
+ });
478
+ function isPublicationErrorReasonFor(code, reason) {
479
+ return typeof reason === "string" && Object.hasOwn(PUBLICATION_ERROR_REASON_CODES, reason) && PUBLICATION_ERROR_REASON_CODES[reason] === code;
480
+ }
481
+ function parsePublicationErrorReason(status, code, details) {
482
+ if (status < 400 || status > 499) return void 0;
483
+ if (details === null || typeof details !== "object" || Array.isArray(details)) return void 0;
484
+ const record = details;
485
+ const keys = Object.keys(record);
486
+ if (keys.length !== 1 || keys[0] !== "reason") return void 0;
487
+ return isPublicationErrorReasonFor(code, record.reason) ? record.reason : void 0;
488
+ }
489
+
470
490
  // src/lib/backend.ts
471
491
  var ADMIN_API_ORIGIN = "https://api.andpipe.com";
472
492
  var ADMIN_API_TIMEOUT_MS = 1e4;
@@ -496,6 +516,7 @@ var AdminApiClientError = class extends Error {
496
516
  detailsAbsent;
497
517
  scopeRegistrationReason;
498
518
  publishGateToolNames;
519
+ publicationReason;
499
520
  constructor(code, message, status, confirmationRequired, openApiAuthModeMismatch, safeDetails = {}) {
500
521
  super(message);
501
522
  this.name = "AdminApiClientError";
@@ -506,6 +527,7 @@ var AdminApiClientError = class extends Error {
506
527
  this.detailsAbsent = safeDetails.detailsAbsent === true;
507
528
  this.scopeRegistrationReason = safeDetails.scopeRegistrationReason;
508
529
  this.publishGateToolNames = safeDetails.publishGateToolNames === void 0 ? void 0 : Object.freeze([...safeDetails.publishGateToolNames]);
530
+ this.publicationReason = safeDetails.publicationReason;
509
531
  }
510
532
  };
511
533
  function clientError(code, message, status) {
@@ -720,7 +742,8 @@ function withKnownResponseStatus(error, responseStatus) {
720
742
  {
721
743
  detailsAbsent: error.detailsAbsent,
722
744
  ...error.scopeRegistrationReason === void 0 ? {} : { scopeRegistrationReason: error.scopeRegistrationReason },
723
- ...error.publishGateToolNames === void 0 ? {} : { publishGateToolNames: error.publishGateToolNames }
745
+ ...error.publishGateToolNames === void 0 ? {} : { publishGateToolNames: error.publishGateToolNames },
746
+ ...error.publicationReason === void 0 ? {} : { publicationReason: error.publicationReason }
724
747
  }
725
748
  );
726
749
  }
@@ -789,6 +812,7 @@ function safeApiError(status, value) {
789
812
  const code = typeof candidate === "string" && SAFE_AP_CODE_RE.test(candidate) ? candidate : "AP_HTTP_ERROR";
790
813
  const confirmationRequired = code === "AP_CONFIRMATION_REQUIRED" && status === 409 ? parsePublicationConfirmationRequiredDetails(errorRecord?.details) : void 0;
791
814
  const openApiAuthModeMismatch = code === "AP_CONFLICT" && status === 409 ? parseOpenApiImportAuthModeMismatch(errorRecord?.details) : void 0;
815
+ const publicationReason = parsePublicationErrorReason(status, code, errorRecord?.details);
792
816
  return new AdminApiClientError(
793
817
  code,
794
818
  `Admin API request failed (${code}; HTTP ${status})`,
@@ -798,7 +822,8 @@ function safeApiError(status, value) {
798
822
  {
799
823
  // AP error envelopeを受け取れた場合だけ「detailsなし」を判定できる。
800
824
  detailsAbsent: errorRecord !== void 0 && (errorRecord.details === null || errorRecord.details === void 0),
801
- ...parseScopeRegistrationErrorDetails(status, errorRecord?.details)
825
+ ...parseScopeRegistrationErrorDetails(status, errorRecord?.details),
826
+ ...publicationReason === void 0 ? {} : { publicationReason }
802
827
  }
803
828
  );
804
829
  }
@@ -932,6 +957,13 @@ function publicationPlanBody(input) {
932
957
  ...input.templateProvenance === void 0 ? {} : { templateProvenance: input.templateProvenance }
933
958
  };
934
959
  }
960
+ function publicationReviewProfileOption(options) {
961
+ if (options === void 0) return void 0;
962
+ if (options === null || typeof options !== "object" || Object.keys(options).join(",") !== "reviewProfile" || options.reviewProfile !== 2) {
963
+ throw clientError("AP_INPUT_INVALID", "tool publication review profile option is invalid");
964
+ }
965
+ return options.reviewProfile;
966
+ }
935
967
  function publicationApplyBody(input) {
936
968
  const common = publicationPlanBody(input);
937
969
  if (!import_tool_contract.PUBLICATION_SHA256_COMMITMENT_RE.test(input.planCommitment)) {
@@ -1287,6 +1319,10 @@ var AdminApiClient = class {
1287
1319
  this.#sleep = options.sleep ?? ((milliseconds) => new Promise((resolve7) => setTimeout(resolve7, milliseconds)));
1288
1320
  }
1289
1321
  async #request(path, options = {}) {
1322
+ return (await this.#requestWithHeaders(path, options)).value;
1323
+ }
1324
+ /** 2xx bodyと、そのresponse headerを返す。headerはcommand層が必要な値だけを読む。 */
1325
+ async #requestWithHeaders(path, options = {}) {
1290
1326
  const url = buildUrl(path);
1291
1327
  const method = options.method ?? "GET";
1292
1328
  const attempts = method === "GET" ? ADMIN_API_MAX_GET_ATTEMPTS : 1;
@@ -1308,6 +1344,9 @@ var AdminApiClient = class {
1308
1344
  if (options.authenticated !== false) headers.set("Authorization", `Bearer ${this.#token}`);
1309
1345
  if (body !== void 0) headers.set("Content-Type", "application/json");
1310
1346
  if (options.idempotencyKey) headers.set("Idempotency-Key", options.idempotencyKey);
1347
+ if (options.reviewProfile !== void 0) {
1348
+ headers.set(import_tool_contract.PUBLICATION_REVIEW_PROFILE_HEADER, String(options.reviewProfile));
1349
+ }
1311
1350
  response = await this.#fetch(url, {
1312
1351
  method,
1313
1352
  headers,
@@ -1364,8 +1403,8 @@ var AdminApiClient = class {
1364
1403
  }
1365
1404
  throw safeApiError(response.status, errorBody);
1366
1405
  }
1367
- if (options.responseType === "text") return text;
1368
- return parseJson(text);
1406
+ if (options.responseType === "text") return { value: text, headers: response.headers };
1407
+ return { value: parseJson(text), headers: response.headers };
1369
1408
  }
1370
1409
  throw clientError("AP_NETWORK_ERROR", "Admin API request failed");
1371
1410
  }
@@ -1511,24 +1550,41 @@ var AdminApiClient = class {
1511
1550
  status: connector.status
1512
1551
  };
1513
1552
  }
1514
- async planPublication(projectId, body) {
1515
- return this.#request(`/v1/projects/${assertProjectId(projectId)}/tool-publications:plan`, {
1516
- method: "POST",
1517
- body: publicationPlanBody(body),
1518
- maxRequestBytes: ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES,
1519
- maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES
1520
- });
1553
+ async planPublication(projectId, body, options) {
1554
+ const reviewProfile = publicationReviewProfileOption(options);
1555
+ const response = await this.#requestWithHeaders(
1556
+ `/v1/projects/${assertProjectId(projectId)}/tool-publications:plan`,
1557
+ {
1558
+ method: "POST",
1559
+ body: publicationPlanBody(body),
1560
+ maxRequestBytes: ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES,
1561
+ maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES,
1562
+ ...reviewProfile === void 0 ? {} : { reviewProfile }
1563
+ }
1564
+ );
1565
+ if (reviewProfile === void 0) return response.value;
1566
+ const planResponse = {
1567
+ body: response.value,
1568
+ reviewProfileHeader: response.headers.get(import_tool_contract.PUBLICATION_REVIEW_PROFILE_HEADER)
1569
+ };
1570
+ return planResponse;
1521
1571
  }
1522
- async applyPublication(projectId, idempotencyKey, body) {
1572
+ /**
1573
+ * 初回apply(confirmation=null)と承認済みapply。options付き (#730) だけreview profile headerを送る。
1574
+ * request bodyとIdempotency-Keyはheaderの有無で変えない。
1575
+ */
1576
+ async applyPublication(projectId, idempotencyKey, body, options) {
1523
1577
  if (!/^[A-Za-z0-9._:-]{22,200}$/u.test(idempotencyKey)) {
1524
1578
  throw clientError("AP_INPUT_INVALID", "tool publication Idempotency-Key is invalid");
1525
1579
  }
1580
+ const reviewProfile = publicationReviewProfileOption(options);
1526
1581
  return this.#request(`/v1/projects/${assertProjectId(projectId)}/tool-publications`, {
1527
1582
  method: "POST",
1528
1583
  body: publicationApplyBody(body),
1529
1584
  idempotencyKey,
1530
1585
  maxRequestBytes: ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES,
1531
- maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES
1586
+ maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES,
1587
+ ...reviewProfile === void 0 ? {} : { reviewProfile }
1532
1588
  });
1533
1589
  }
1534
1590
  async planOpenApiImport(projectId, input) {
@@ -3084,8 +3140,8 @@ async function downloadAuditExportArtifact(input) {
3084
3140
  } finally {
3085
3141
  reader.releaseLock();
3086
3142
  }
3087
- const sha2562 = hash.digest("hex");
3088
- if (bytes !== authorization.manifest.byteCount || sha2562 !== authorization.manifest.contentSha256) {
3143
+ const sha2563 = hash.digest("hex");
3144
+ if (bytes !== authorization.manifest.byteCount || sha2563 !== authorization.manifest.contentSha256) {
3089
3145
  throw new UsageError("\u76E3\u67FB\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8\u306E\u5185\u5BB9\u304C\u7F72\u540Dmanifest\u3068\u4E00\u81F4\u3057\u307E\u305B\u3093");
3090
3146
  }
3091
3147
  await file.sync();
@@ -3104,7 +3160,7 @@ async function downloadAuditExportArtifact(input) {
3104
3160
  } finally {
3105
3161
  await directory.close();
3106
3162
  }
3107
- return { output: canonicalTarget, sha256: sha2562, bytes };
3163
+ return { output: canonicalTarget, sha256: sha2563, bytes };
3108
3164
  } finally {
3109
3165
  clearTimeout(timeout);
3110
3166
  await file.close().catch(() => void 0);
@@ -8346,22 +8402,249 @@ function registerLogs(program, writer, locale = import_localization8.DEFAULT_LOC
8346
8402
  });
8347
8403
  }
8348
8404
 
8349
- // src/commands/oauth.ts
8350
- var import_node_crypto13 = require("crypto");
8351
- var import_node_fs11 = require("fs");
8405
+ // src/commands/muse.ts
8406
+ var import_node_crypto12 = require("crypto");
8407
+ var import_node_fs12 = require("fs");
8408
+ var import_node_path13 = require("path");
8352
8409
  var import_localization10 = require("@andpipes/localization");
8353
- var import_tool_contract10 = require("@andpipes/tool-contract");
8410
+ var import_tool_contract9 = require("@andpipes/tool-contract");
8354
8411
 
8355
- // src/commands/publish.ts
8356
- var import_node_crypto12 = require("crypto");
8412
+ // src/commands/validate.ts
8413
+ var import_node_fs11 = require("fs");
8414
+ var import_node_path12 = require("path");
8357
8415
  var import_localization9 = require("@andpipes/localization");
8358
- var import_tool_contract9 = require("@andpipes/tool-contract");
8416
+ function resolveContractPath(file, cwd, locale = import_localization9.DEFAULT_LOCALE) {
8417
+ const messages = import_localization9.CLI_MESSAGES[locale].validate;
8418
+ if (file) {
8419
+ const abs = (0, import_node_path12.resolve)(cwd, file);
8420
+ if (!(0, import_node_fs11.existsSync)(abs)) {
8421
+ throw new UsageError(messages.fileNotFound(file));
8422
+ }
8423
+ return abs;
8424
+ }
8425
+ for (const candidate of import_tool_contract4.CONTRACT_FILENAMES) {
8426
+ const abs = (0, import_node_path12.resolve)(cwd, candidate);
8427
+ if ((0, import_node_fs11.existsSync)(abs)) {
8428
+ return abs;
8429
+ }
8430
+ }
8431
+ throw new UsageError(messages.defaultFileNotFound(import_tool_contract4.CONTRACT_FILENAMES));
8432
+ }
8433
+ function registerValidate(program, writer, cwd, locale = import_localization9.DEFAULT_LOCALE) {
8434
+ const text = import_localization9.LOCALIZED_TEXT[locale].cli;
8435
+ const messages = import_localization9.CLI_MESSAGES[locale].validate;
8436
+ program.command("validate").description(`${text.validateDescription} (10 checks)`).option("--file <path>", messages.fileOption).action((opts) => {
8437
+ const path = resolveContractPath(opts.file, cwd(), locale);
8438
+ const loaded = loadContractFile(path);
8439
+ const report = loaded.report;
8440
+ const publishGate = loaded.publishGate;
8441
+ json(writer, { checks: report.results, publishGate });
8442
+ const fail2 = report.results.filter((r) => r.status === "fail").length;
8443
+ const pending = report.results.filter((r) => r.status === "pending").length;
8444
+ const pass = report.results.filter((r) => r.status === "pass").length;
8445
+ info(
8446
+ writer,
8447
+ `${text.resultLabel}: pass=${pass} fail=${fail2} pending=${pending} (pending=${text.backendPending})`
8448
+ );
8449
+ info(
8450
+ writer,
8451
+ messages.publishGateSummary(publishGate.errors.length, publishGate.warnings.length)
8452
+ );
8453
+ if (!report.ok || !publishGate.ok) {
8454
+ process.exitCode = 1;
8455
+ info(writer, messages.failed);
8456
+ }
8457
+ });
8458
+ }
8459
+
8460
+ // src/commands/muse.ts
8461
+ var DEFAULT_MUSE_OUTPUT_DIR = "andpipe-muse-preparation";
8462
+ var OUTPUT_DIR_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
8463
+ var MAX_MUSE_FILE_BYTES = 8 * 1024 * 1024;
8464
+ var MUSE_PREPARATION_FILE_KEYS = Object.freeze(
8465
+ {
8466
+ "muse/connector.internal.json": "connector",
8467
+ "muse/openapi.json": "openapi",
8468
+ "muse/SKILL.md": "skill",
8469
+ "muse/setup.md": "setup",
8470
+ "muse/compatibility.json": "compatibility",
8471
+ "provenance/build.json": "provenance"
8472
+ }
8473
+ );
8474
+ var REASON_KEYS = {
8475
+ invalid_input: "invalid_input",
8476
+ selection_required: "selection_required",
8477
+ selection_invalid: "selection_invalid",
8478
+ contract_invalid: "contract_invalid",
8479
+ schema_unsupported: "schema_unsupported",
8480
+ sensitive_content: "sensitive_content",
8481
+ risk_unsupported: "risk_unsupported"
8482
+ };
8483
+ function parseToolNames(value, locale) {
8484
+ const names = (value ?? "").split(",").map((name) => name.trim()).filter((name) => name.length > 0);
8485
+ if (names.length === 0) throw new UsageError(import_localization10.MUSE_SETUP_MESSAGES[locale].cli.toolsRequired);
8486
+ return names;
8487
+ }
8488
+ function parseOutputDir(value, locale) {
8489
+ const output = value ?? DEFAULT_MUSE_OUTPUT_DIR;
8490
+ if (!OUTPUT_DIR_RE.test(output) || output === "." || output === "..") {
8491
+ throw new UsageError(import_localization10.MUSE_SETUP_MESSAGES[locale].cli.outputInvalid);
8492
+ }
8493
+ return output;
8494
+ }
8495
+ function sha2562(text) {
8496
+ return `sha256:${(0, import_node_crypto12.createHash)("sha256").update(text, "utf8").digest("hex")}`;
8497
+ }
8498
+ function createOwnedDirectory(path) {
8499
+ (0, import_node_fs12.mkdirSync)(path, { mode: 448 });
8500
+ return ownedDirectoryIdentity(path);
8501
+ }
8502
+ function ownedDirectoryIdentity(path) {
8503
+ let stat2;
8504
+ try {
8505
+ stat2 = (0, import_node_fs12.lstatSync)(path);
8506
+ } catch {
8507
+ throw new LocalFilePolicyError("local_file_changed", "output directory changed after create");
8508
+ }
8509
+ const identity = localRootIdentityFromStat(stat2, "local_file_changed", "output directory");
8510
+ assertOwnerOnlyLocalWrite(identity, "output directory");
8511
+ return identity;
8512
+ }
8513
+ function errorCode(error) {
8514
+ const code = typeof error === "object" && error !== null ? error.code : null;
8515
+ return typeof code === "string" && /^[A-Z][A-Z0-9_]{1,31}$/u.test(code) ? code : null;
8516
+ }
8517
+ function museWriteOrder(paths) {
8518
+ const isProvenance = (path) => path.startsWith("provenance/");
8519
+ return [...paths].sort(
8520
+ (left, right) => isProvenance(left) === isProvenance(right) ? left < right ? -1 : 1 : isProvenance(left) ? 1 : -1
8521
+ );
8522
+ }
8523
+ function writeBundle(root, output, files, locale) {
8524
+ const messages = import_localization10.MUSE_SETUP_MESSAGES[locale].cli;
8525
+ const target = (0, import_node_path13.join)(root, output);
8526
+ const ordered = museWriteOrder(Object.keys(files));
8527
+ const directoryNames = /* @__PURE__ */ new Set();
8528
+ for (const path of ordered) {
8529
+ const [directory, name, ...rest] = path.split("/");
8530
+ if (!directory || !name || rest.length > 0 || !MUSE_PREPARATION_FILE_KEYS[path]) {
8531
+ throw new LocalFilePolicyError("local_file_invalid", "unexpected preparation file path");
8532
+ }
8533
+ directoryNames.add(directory);
8534
+ }
8535
+ try {
8536
+ (0, import_node_fs12.mkdirSync)(target, { mode: 448 });
8537
+ } catch (error) {
8538
+ const code = errorCode(error);
8539
+ if (code === "EEXIST") throw new UsageError(messages.outputExists(output));
8540
+ throw new UsageError(`${messages.outputCreateFailed(output)}${code ? ` (${code})` : ""}`);
8541
+ }
8542
+ try {
8543
+ const targetIdentity = ownedDirectoryIdentity(target);
8544
+ const directories = /* @__PURE__ */ new Map();
8545
+ for (const directory of directoryNames) {
8546
+ assertLocalRootSecurityIdentity(target, targetIdentity, "muse output directory");
8547
+ directories.set(directory, createOwnedDirectory((0, import_node_path13.join)(target, directory)));
8548
+ }
8549
+ for (const path of ordered) {
8550
+ const [directory, name] = path.split("/");
8551
+ const expected = directories.get(directory);
8552
+ assertLocalRootSecurityIdentity(target, targetIdentity, "muse output directory");
8553
+ const delta = writePrivateFileNoReplace(
8554
+ name,
8555
+ (0, import_node_path13.join)(target, directory),
8556
+ files[path],
8557
+ MAX_MUSE_FILE_BYTES,
8558
+ { expectedRootIdentity: expected }
8559
+ );
8560
+ directories.set(directory, localRootIdentityWithNlink(expected, expected.nlink + delta));
8561
+ }
8562
+ } catch (error) {
8563
+ const reason = error instanceof LocalFilePolicyError ? ` (${error.reason})` : "";
8564
+ throw new UsageError(`${messages.outputIncomplete(output)}${reason}`);
8565
+ }
8566
+ }
8567
+ function runMusePrepare(options, writer, cwd, locale = import_localization10.DEFAULT_LOCALE) {
8568
+ const messages = import_localization10.MUSE_SETUP_MESSAGES[locale];
8569
+ const toolNames = parseToolNames(options.tools, locale);
8570
+ const output = parseOutputDir(options.output, locale);
8571
+ const anchor = captureLocalRootPath(cwd);
8572
+ const loaded = loadContractFile(resolveContractPath(options.file, cwd, locale));
8573
+ const selected = new Set(toolNames);
8574
+ const result = (0, import_tool_contract9.prepareMuseBundle)(
8575
+ loaded.tools.filter((tool) => selected.has(tool.tool)),
8576
+ { toolNames }
8577
+ );
8578
+ const flags = {
8579
+ enabled: result.enabled,
8580
+ liveVerified: result.liveVerified,
8581
+ submissionReady: result.submissionReady
8582
+ };
8583
+ if (result.status === "blocked") {
8584
+ const reason = messages.reasons[REASON_KEYS[result.reason]];
8585
+ json(writer, { status: "blocked", reason: result.reason, ...flags });
8586
+ info(writer, messages.cli.blocked);
8587
+ info(writer, `${messages.cli.reasonLabel}: ${reason.cause}`);
8588
+ info(writer, `${messages.cli.fixLabel}: ${reason.fix}`);
8589
+ process.exitCode = 1;
8590
+ return;
8591
+ }
8592
+ assertLocalRootSecurityIdentity(anchor.root, anchor.rootIdentity, "muse output");
8593
+ writeBundle(anchor.root, output, result.files, locale);
8594
+ const paths = Object.keys(result.files).sort();
8595
+ json(writer, {
8596
+ status: "prepared",
8597
+ output,
8598
+ contentHash: result.contentHash,
8599
+ ...flags,
8600
+ files: paths.map((path) => ({ path, sha256: sha2562(result.files[path]) }))
8601
+ });
8602
+ info(writer, messages.cli.prepared(output));
8603
+ info(writer, messages.cli.notConnected);
8604
+ for (const path of paths) {
8605
+ const key = MUSE_PREPARATION_FILE_KEYS[path];
8606
+ if (key) info(writer, ` ${output}/${path}: ${messages.files[key]}`);
8607
+ }
8608
+ info(writer, `${messages.cli.statesHeading}:`);
8609
+ for (const key of import_localization10.MUSE_SETUP_STATE_KEYS) {
8610
+ const state = messages.states[key];
8611
+ info(
8612
+ writer,
8613
+ `- ${state.title}: ${key === "prepared" ? messages.cli.preparedNow : state.status}`
8614
+ );
8615
+ }
8616
+ info(writer, messages.cli.nextStep);
8617
+ }
8618
+ function registerMuse(program, writer, cwd, locale = import_localization10.DEFAULT_LOCALE) {
8619
+ const messages = import_localization10.MUSE_SETUP_MESSAGES[locale].cli;
8620
+ const muse = program.command("muse").description(messages.groupDescription);
8621
+ muse.command("prepare").description(messages.prepareDescription).option(
8622
+ "--tools <names>",
8623
+ messages.toolsOption,
8624
+ (value, previous) => previous === void 0 ? value : `${previous},${value}`
8625
+ ).option("--file <path>", messages.fileOption).option("--output <dir>", messages.outputOption, DEFAULT_MUSE_OUTPUT_DIR).action((options) => runMusePrepare(options, writer, cwd(), locale));
8626
+ }
8627
+
8628
+ // src/commands/oauth.ts
8629
+ var import_node_crypto14 = require("crypto");
8630
+ var import_node_fs13 = require("fs");
8631
+ var import_localization12 = require("@andpipes/localization");
8632
+ var import_tool_contract11 = require("@andpipes/tool-contract");
8633
+
8634
+ // src/commands/publish.ts
8635
+ var import_node_crypto13 = require("crypto");
8636
+ var import_localization11 = require("@andpipes/localization");
8637
+ var import_tool_contract10 = require("@andpipes/tool-contract");
8359
8638
  var UUID_RE6 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
8360
8639
  var SAFE_AP_CODE_RE2 = /^AP_[A-Z0-9_]{1,64}$/u;
8361
8640
  var PUBLICATION_RESPONSE_MAX_BYTES = 96 * 1024;
8362
8641
  var INITIAL_APPLY_MAX_ATTEMPTS = 3;
8363
- var DEFAULT_PUBLISH_MESSAGES = import_localization9.CLI_MESSAGES.ja.publish;
8364
- var DEFAULT_SCOPE_REGISTRATION_MESSAGES2 = import_localization9.OAUTH_SCOPE_REGISTRATION_MESSAGES.ja.cli;
8642
+ var DEFAULT_PUBLISH_MESSAGES = import_localization11.CLI_MESSAGES.ja.publish;
8643
+ var DEFAULT_SCOPE_REGISTRATION_MESSAGES2 = import_localization11.OAUTH_SCOPE_REGISTRATION_MESSAGES.ja.cli;
8644
+ var DEFAULT_SCHEMA_REVIEW_MESSAGES = import_localization11.PUBLICATION_SCHEMA_REVIEW_CLI_MESSAGES.ja;
8645
+ var REVIEW_PROFILE_REQUEST = Object.freeze({
8646
+ reviewProfile: CLI_PUBLICATION_REVIEW_PROFILE
8647
+ });
8365
8648
  var PLAN_KEYS = [
8366
8649
  "requestId",
8367
8650
  "environment",
@@ -8447,7 +8730,7 @@ function createPublishCommandRuntime(createClient) {
8447
8730
  return {
8448
8731
  createClient,
8449
8732
  loadProject: loadDevProject,
8450
- randomUuid: () => (0, import_node_crypto12.randomUUID)(),
8733
+ randomUuid: () => (0, import_node_crypto13.randomUUID)(),
8451
8734
  monotonicNow: () => Number(process.hrtime.bigint() / 1000000n),
8452
8735
  wallNow: () => Date.now(),
8453
8736
  sleep: (milliseconds) => new Promise((resolve7) => setTimeout(resolve7, milliseconds))
@@ -8493,7 +8776,7 @@ function responseInvalid(reason, messages) {
8493
8776
  }
8494
8777
  function assertCanonicalResponseSize(value, reason, messages, maxBytes = PUBLICATION_RESPONSE_MAX_BYTES) {
8495
8778
  try {
8496
- (0, import_tool_contract9.assertCanonicalPublicationSize)(value, maxBytes);
8779
+ (0, import_tool_contract10.assertCanonicalPublicationSize)(value, maxBytes);
8497
8780
  } catch {
8498
8781
  throw responseInvalid(reason, messages);
8499
8782
  }
@@ -8502,7 +8785,7 @@ function isCanonicalUuid(value) {
8502
8785
  return typeof value === "string" && UUID_RE6.test(value);
8503
8786
  }
8504
8787
  function isCommitment(value) {
8505
- return typeof value === "string" && import_tool_contract9.PUBLICATION_SHA256_COMMITMENT_RE.test(value);
8788
+ return typeof value === "string" && import_tool_contract10.PUBLICATION_SHA256_COMMITMENT_RE.test(value);
8506
8789
  }
8507
8790
  function isCanonicalTimestamp(value) {
8508
8791
  if (typeof value !== "string" || value.length > 64) return false;
@@ -8511,20 +8794,51 @@ function isCanonicalTimestamp(value) {
8511
8794
  }
8512
8795
  function isStrictlySorted(values) {
8513
8796
  return values.every(
8514
- (value, index) => index === 0 || (0, import_tool_contract9.comparePublicationUnicodeCodePoints)(values[index - 1], value) < 0
8797
+ (value, index) => index === 0 || (0, import_tool_contract10.comparePublicationUnicodeCodePoints)(values[index - 1], value) < 0
8515
8798
  );
8516
8799
  }
8517
8800
  function parseWarnings(value, messages) {
8518
8801
  try {
8519
- return (0, import_tool_contract9.parsePublicationWarningsDto)(value);
8802
+ return (0, import_tool_contract10.parsePublicationWarningsDto)(value);
8520
8803
  } catch {
8521
8804
  throw responseInvalid("publication_warnings_invalid", messages);
8522
8805
  }
8523
8806
  }
8524
- function parsePlan(value, connectorId, candidateCommitment, expectedToolNames, messages) {
8807
+ function schemaReviewFailure(code, reason, text, status) {
8808
+ return new PublishCommandError(code, reason, `${text} (${reason})`, status);
8809
+ }
8810
+ function negotiateReviewProfile(response, messages, schemaReviewMessages) {
8811
+ const envelope = asRecord4(response);
8812
+ if (!envelope || !hasExactKeys3(envelope, ["body", "reviewProfileHeader"]) || envelope.reviewProfileHeader !== null && typeof envelope.reviewProfileHeader !== "string") {
8813
+ throw responseInvalid("publication_plan_invalid", messages);
8814
+ }
8815
+ const header = envelope.reviewProfileHeader;
8816
+ if (header !== null && header !== "1" && header !== "2") {
8817
+ throw schemaReviewFailure(
8818
+ "AP_RESPONSE_INVALID",
8819
+ "publication_review_profile_header_invalid",
8820
+ schemaReviewMessages.reviewProfileHeaderInvalid
8821
+ );
8822
+ }
8823
+ const body = asRecord4(envelope.body);
8824
+ const bodyDeclaresProfile = body !== null && Object.hasOwn(body, "reviewProfile");
8825
+ const profile = header === "2" ? 2 : 1;
8826
+ if (profile === 2 ? !bodyDeclaresProfile || body?.reviewProfile !== 2 : bodyDeclaresProfile) {
8827
+ throw schemaReviewFailure(
8828
+ "AP_CONFLICT",
8829
+ "publication_review_profile_mismatch",
8830
+ schemaReviewMessages.reviewProfileMismatch
8831
+ );
8832
+ }
8833
+ return {
8834
+ session: header === null ? { kind: "legacy", profile: 1 } : { kind: "negotiated", profile },
8835
+ body: envelope.body
8836
+ };
8837
+ }
8838
+ function parsePlan(value, connectorId, candidateCommitment, expectedToolNames, profile, messages) {
8525
8839
  assertCanonicalResponseSize(value, "publication_plan_too_large", messages);
8526
8840
  const plan = asRecord4(value);
8527
- if (!plan || !hasExactKeys3(plan, PLAN_KEYS) || !isCanonicalUuid(plan.requestId) || plan.environment !== "production" || plan.connectorId !== connectorId || !isCanonicalTimestamp(plan.connectorRevision) || !isCommitment(plan.connectorCommitment) || !isCommitment(plan.policyCommitment) || plan.candidateCommitment !== candidateCommitment || !isCommitment(plan.candidateCommitment) || !isCommitment(plan.baseCommitment) || !isCommitment(plan.planCommitment) || !Array.isArray(plan.tools) || typeof plan.applyAllowed !== "boolean" || !Array.isArray(plan.blockedReasons) || !plan.blockedReasons.every(
8841
+ if (!plan || !hasExactKeys3(plan, profile === 2 ? [...PLAN_KEYS, "reviewProfile"] : PLAN_KEYS) || profile === 2 && plan.reviewProfile !== 2 || !isCanonicalUuid(plan.requestId) || plan.environment !== "production" || plan.connectorId !== connectorId || !isCanonicalTimestamp(plan.connectorRevision) || !isCommitment(plan.connectorCommitment) || !isCommitment(plan.policyCommitment) || plan.candidateCommitment !== candidateCommitment || !isCommitment(plan.candidateCommitment) || !isCommitment(plan.baseCommitment) || !isCommitment(plan.planCommitment) || !Array.isArray(plan.tools) || typeof plan.applyAllowed !== "boolean" || !Array.isArray(plan.blockedReasons) || !plan.blockedReasons.every(
8528
8842
  (reason) => typeof reason === "string" && BLOCKED_REASONS.has(reason)
8529
8843
  ) || !isStrictlySorted(plan.blockedReasons) || plan.applyAllowed !== (plan.blockedReasons.length === 0)) {
8530
8844
  throw responseInvalid("publication_plan_invalid", messages);
@@ -8532,7 +8846,8 @@ function parsePlan(value, connectorId, candidateCommitment, expectedToolNames, m
8532
8846
  const blockedReasons = plan.blockedReasons;
8533
8847
  let safeDiff;
8534
8848
  try {
8535
- safeDiff = (0, import_tool_contract9.parsePublicationSafeDiffDto)({
8849
+ safeDiff = (0, import_tool_contract10.parsePublicationSafeDiffDto)({
8850
+ ...profile === 2 ? { reviewProfile: 2 } : {},
8536
8851
  tools: plan.tools,
8537
8852
  retainedTools: plan.retainedTools,
8538
8853
  warnings: plan.warnings
@@ -8540,13 +8855,16 @@ function parsePlan(value, connectorId, candidateCommitment, expectedToolNames, m
8540
8855
  } catch {
8541
8856
  throw responseInvalid("publication_safe_diff_invalid", messages);
8542
8857
  }
8858
+ if (safeDiff.reviewProfile === 2 !== (profile === 2)) {
8859
+ throw responseInvalid("publication_safe_diff_invalid", messages);
8860
+ }
8543
8861
  const tools = safeDiff.tools;
8544
8862
  const toolNames = tools.map((tool) => tool.toolName);
8545
8863
  if (!isStrictlySorted(toolNames) || JSON.stringify(toolNames) !== JSON.stringify(expectedToolNames)) {
8546
8864
  throw responseInvalid("publication_plan_tools_order_invalid", messages);
8547
8865
  }
8548
8866
  const warnings = safeDiff.warnings;
8549
- const expectedPlanCommitment = (0, import_tool_contract9.publicationCommitment)("plan", {
8867
+ const expectedPlanCommitment = (0, import_tool_contract10.publicationCommitment)(profile === 2 ? "planV2" : "plan", {
8550
8868
  candidateCommitment,
8551
8869
  baseCommitment: plan.baseCommitment,
8552
8870
  connectorId,
@@ -8574,6 +8892,7 @@ function parsePlan(value, connectorId, candidateCommitment, expectedToolNames, m
8574
8892
  throw responseInvalid("publication_plan_gate_inconsistent", messages);
8575
8893
  }
8576
8894
  return {
8895
+ ...profile === 2 ? { reviewProfile: 2 } : {},
8577
8896
  requestId: plan.requestId,
8578
8897
  environment: "production",
8579
8898
  connectorId,
@@ -8599,7 +8918,7 @@ function parseToolResults(value, messages) {
8599
8918
  }
8600
8919
  const tools = value.map((candidate) => {
8601
8920
  const tool = asRecord4(candidate);
8602
- if (!tool || !hasExactKeys3(tool, ["toolName", "operation", "toolId", "versionId", "version"]) || !(0, import_tool_contract9.isSafeToolName)(tool.toolName) || tool.operation !== "create" && tool.operation !== "update" || !isCanonicalUuid(tool.toolId) || !isCanonicalUuid(tool.versionId) || typeof tool.version !== "number" || !Number.isSafeInteger(tool.version) || tool.version < 1) {
8921
+ if (!tool || !hasExactKeys3(tool, ["toolName", "operation", "toolId", "versionId", "version"]) || !(0, import_tool_contract10.isSafeToolName)(tool.toolName) || tool.operation !== "create" && tool.operation !== "update" || !isCanonicalUuid(tool.toolId) || !isCanonicalUuid(tool.versionId) || typeof tool.version !== "number" || !Number.isSafeInteger(tool.version) || tool.version < 1) {
8603
8922
  throw responseInvalid("publication_result_tool_invalid", messages);
8604
8923
  }
8605
8924
  const operation = tool.operation;
@@ -8656,7 +8975,7 @@ function parsePublicationResult(value, plan, messages, expectedPublicationId) {
8656
8975
  function parseConfirmation(value, messages) {
8657
8976
  if (value === null) return null;
8658
8977
  const confirmation = asRecord4(value);
8659
- if (!confirmation || !hasExactKeys3(confirmation, ["confirmationId", "signature", "confirmed"]) || !isCanonicalUuid(confirmation.confirmationId) || typeof confirmation.signature !== "string" || !import_tool_contract9.PUBLICATION_CONFIRMATION_SIGNATURE_RE.test(confirmation.signature) || confirmation.confirmed !== true) {
8978
+ if (!confirmation || !hasExactKeys3(confirmation, ["confirmationId", "signature", "confirmed"]) || !isCanonicalUuid(confirmation.confirmationId) || typeof confirmation.signature !== "string" || !import_tool_contract10.PUBLICATION_CONFIRMATION_SIGNATURE_RE.test(confirmation.signature) || confirmation.confirmed !== true) {
8660
8979
  throw responseInvalid("publication_confirmation_invalid", messages);
8661
8980
  }
8662
8981
  return {
@@ -8701,8 +9020,36 @@ function typedStatus2(error) {
8701
9020
  const status = error.status;
8702
9021
  return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599 ? status : void 0;
8703
9022
  }
8704
- function remoteError(error, phase, messages) {
9023
+ function typedPublicationReason(error, code) {
9024
+ if (error === null || typeof error !== "object") return void 0;
9025
+ const status = typedStatus2(error);
9026
+ if (status === void 0 || status < 400 || status > 499) return void 0;
9027
+ const reason = error.publicationReason;
9028
+ return isPublicationErrorReasonFor(code, reason) ? reason : void 0;
9029
+ }
9030
+ function publicationReasonText(reason, schemaReviewMessages) {
9031
+ switch (reason) {
9032
+ case "publication_schema_review_too_large":
9033
+ return schemaReviewMessages.schemaReviewTooLarge;
9034
+ case "publication_review_profile_invalid":
9035
+ return schemaReviewMessages.reviewProfileInvalid;
9036
+ case "schema_review_receipt_mismatch":
9037
+ return schemaReviewMessages.receiptMismatch;
9038
+ case "publication_plan_stale":
9039
+ return schemaReviewMessages.planStale;
9040
+ }
9041
+ }
9042
+ function remoteError(error, phase, messages, schemaReviewMessages) {
8705
9043
  const code = typedCode2(error) ?? "AP_NETWORK_ERROR";
9044
+ const publicationReason = schemaReviewMessages === void 0 ? void 0 : typedPublicationReason(error, code);
9045
+ if (publicationReason !== void 0 && schemaReviewMessages !== void 0) {
9046
+ return schemaReviewFailure(
9047
+ code,
9048
+ publicationReason,
9049
+ publicationReasonText(publicationReason, schemaReviewMessages),
9050
+ typedStatus2(error)
9051
+ );
9052
+ }
8706
9053
  return new PublishCommandError(
8707
9054
  code,
8708
9055
  `${phase}_failed`,
@@ -8764,6 +9111,42 @@ function writeSafeJson(writer, value) {
8764
9111
  function writePlan(writer, plan) {
8765
9112
  writeSafeJson(writer, { phase: "plan", ...plan });
8766
9113
  }
9114
+ function writeSchemaReviewSummary(writer, plan, schemaReviewMessages) {
9115
+ if (plan.reviewProfile !== 2) return;
9116
+ const reviewed = plan.tools.filter((tool) => (tool.schemaReview?.enums.length ?? 0) > 0);
9117
+ if (reviewed.length === 0) return;
9118
+ interactive(writer, schemaReviewMessages.heading);
9119
+ for (const tool of reviewed) {
9120
+ const review = tool.schemaReview;
9121
+ if (!review) continue;
9122
+ const count = (change) => review.enums.filter((entry) => entry.change === change).length;
9123
+ interactive(
9124
+ writer,
9125
+ schemaReviewMessages.toolSummary({
9126
+ toolName: terminalSafeText(tool.toolName),
9127
+ total: review.enums.length,
9128
+ added: count("added"),
9129
+ changed: count("changed"),
9130
+ removed: count("removed"),
9131
+ unchanged: count("unchanged"),
9132
+ valueReviewRequired: review.humanValueReviewRequired
9133
+ })
9134
+ );
9135
+ }
9136
+ if (reviewed.some((tool) => tool.schemaReview?.humanValueReviewRequired === true)) {
9137
+ interactive(writer, schemaReviewMessages.valueReviewInWebAdmin);
9138
+ }
9139
+ }
9140
+ function candidateNeedsReviewProfile2(candidateContract) {
9141
+ return (0, import_tool_contract10.selectPublicationReviewProfile)({
9142
+ requestedProfile: CLI_PUBLICATION_REVIEW_PROFILE,
9143
+ candidateContract,
9144
+ currentTools: []
9145
+ }) === 2;
9146
+ }
9147
+ function applyPublicationWithProfile(client, projectId, idempotencyKey, body, session) {
9148
+ return session.kind === "negotiated" ? client.applyPublication(projectId, idempotencyKey, body, REVIEW_PROFILE_REQUEST) : client.applyPublication(projectId, idempotencyKey, body);
9149
+ }
8767
9150
  function writeResult(writer, result) {
8768
9151
  writeSafeJson(writer, { phase: "result", ...result });
8769
9152
  }
@@ -8779,11 +9162,11 @@ function freezeJson(value) {
8779
9162
  return value;
8780
9163
  }
8781
9164
  function prepareCandidate(project) {
8782
- const canonical = (0, import_tool_contract9.assertCanonicalPublicationSize)(project.contract.root);
9165
+ const canonical = (0, import_tool_contract10.assertCanonicalPublicationSize)(project.contract.root);
8783
9166
  const candidateContract = freezeJson(JSON.parse(canonical));
8784
9167
  return {
8785
9168
  candidateContract,
8786
- candidateCommitment: (0, import_tool_contract9.publicationCommitment)("candidate", candidateContract)
9169
+ candidateCommitment: (0, import_tool_contract10.publicationCommitment)("candidate", candidateContract)
8787
9170
  };
8788
9171
  }
8789
9172
  function loadPublicationProject(loadProject, cwd, messages = DEFAULT_PUBLISH_MESSAGES) {
@@ -8817,15 +9200,15 @@ function assertManifestProject(project, requestedProjectId, messages = DEFAULT_P
8817
9200
  }
8818
9201
  function buildLocalPublicationCandidate(project, connectorId, messages = DEFAULT_PUBLISH_MESSAGES) {
8819
9202
  const candidate = prepareCandidate(project);
8820
- const localToolNames = project.contract.tools.map((tool) => (0, import_tool_contract9.toolName)(tool));
8821
- if (localToolNames.some((name) => !(0, import_tool_contract9.isSafeToolName)(name))) {
9203
+ const localToolNames = project.contract.tools.map((tool) => (0, import_tool_contract10.toolName)(tool));
9204
+ if (localToolNames.some((name) => !(0, import_tool_contract10.isSafeToolName)(name))) {
8822
9205
  throw new PublishCommandError(
8823
9206
  "AP_INPUT_INVALID",
8824
9207
  "publication_candidate_tool_invalid",
8825
9208
  messages.failure("publication_candidate_tool_invalid")
8826
9209
  );
8827
9210
  }
8828
- const expectedToolNames = localToolNames.sort(import_tool_contract9.comparePublicationUnicodeCodePoints);
9211
+ const expectedToolNames = localToolNames.sort(import_tool_contract10.comparePublicationUnicodeCodePoints);
8829
9212
  return {
8830
9213
  planRequest: {
8831
9214
  environment: "production",
@@ -8856,7 +9239,13 @@ async function sendInitialApplyWithSameAnchorRetry(input) {
8856
9239
  for (let attempt = 0; attempt < INITIAL_APPLY_MAX_ATTEMPTS; attempt += 1) {
8857
9240
  try {
8858
9241
  const result = parsePublicationResult(
8859
- await input.client.applyPublication(input.projectId, input.idempotencyKey, input.body),
9242
+ await applyPublicationWithProfile(
9243
+ input.client,
9244
+ input.projectId,
9245
+ input.idempotencyKey,
9246
+ input.body,
9247
+ input.session
9248
+ ),
8860
9249
  input.plan,
8861
9250
  input.messages
8862
9251
  );
@@ -8882,7 +9271,7 @@ async function sendInitialApplyWithSameAnchorRetry(input) {
8882
9271
  return { kind: "confirmation_required", details: confirmationRequired };
8883
9272
  }
8884
9273
  if (!malformedConfirmationAnchor && !initialApplyResultMayBeUnknown(error)) {
8885
- throw remoteError(error, "initial_apply", input.messages);
9274
+ throw remoteError(error, "initial_apply", input.messages, input.schemaReviewMessages);
8886
9275
  }
8887
9276
  if (attempt === INITIAL_APPLY_MAX_ATTEMPTS - 1) {
8888
9277
  throw new PublishCommandError(
@@ -9007,7 +9396,7 @@ async function pollPublication(client, projectId, details, plan, writer, runtime
9007
9396
  }
9008
9397
  throw confirmationStopped("AP_CONFIRMATION_EXPIRED", "publication_poll_attempt_limit", messages);
9009
9398
  }
9010
- async function runPublishCommand(options, writer, cwd, runtime, messages = DEFAULT_PUBLISH_MESSAGES, scopeRegistrationMessages = DEFAULT_SCOPE_REGISTRATION_MESSAGES2) {
9399
+ async function runPublishCommand(options, writer, cwd, runtime, messages = DEFAULT_PUBLISH_MESSAGES, scopeRegistrationMessages = DEFAULT_SCOPE_REGISTRATION_MESSAGES2, schemaReviewMessages = DEFAULT_SCHEMA_REVIEW_MESSAGES) {
9011
9400
  const normalized = normalizePublishOptions(options, messages);
9012
9401
  const project = loadPublicationProject(runtime.loadProject, cwd, messages);
9013
9402
  const projectId = project.manifest.project_id;
@@ -9028,18 +9417,25 @@ async function runPublishCommand(options, writer, cwd, runtime, messages = DEFAU
9028
9417
  const client = runtime.createClient(normalized.profile);
9029
9418
  let rawPlan;
9030
9419
  try {
9031
- rawPlan = await client.planPublication(projectId, planRequest);
9420
+ rawPlan = await client.planPublication(projectId, planRequest, REVIEW_PROFILE_REQUEST);
9032
9421
  } catch (error) {
9033
- throw remoteError(error, "plan", messages);
9422
+ throw remoteError(error, "plan", messages, schemaReviewMessages);
9034
9423
  }
9424
+ const negotiated = negotiateReviewProfile(rawPlan, messages, schemaReviewMessages);
9425
+ const session = negotiated.session;
9035
9426
  const plan = parsePlan(
9036
- rawPlan,
9427
+ negotiated.body,
9037
9428
  connectorId,
9038
9429
  planRequest.candidateCommitment,
9039
9430
  expectedToolNames,
9431
+ session.profile,
9040
9432
  messages
9041
9433
  );
9042
9434
  writePlan(writer, plan);
9435
+ writeSchemaReviewSummary(writer, plan, schemaReviewMessages);
9436
+ if (session.kind === "legacy" && plan.blockedReasons.includes("opaque_change") && candidateNeedsReviewProfile2(planRequest.candidateContract)) {
9437
+ interactive(writer, schemaReviewMessages.adminApiUpdatePending);
9438
+ }
9043
9439
  if (plan.blockedReasons.includes("connector_mismatch")) {
9044
9440
  interactive(writer, messages.connectorMismatchRemediation);
9045
9441
  }
@@ -9070,7 +9466,9 @@ async function runPublishCommand(options, writer, cwd, runtime, messages = DEFAU
9070
9466
  idempotencyKey,
9071
9467
  body: initialApplyRequest,
9072
9468
  plan,
9073
- messages
9469
+ session,
9470
+ messages,
9471
+ schemaReviewMessages
9074
9472
  });
9075
9473
  let details;
9076
9474
  if (initial.kind === "response") {
@@ -9099,7 +9497,13 @@ async function runPublishCommand(options, writer, cwd, runtime, messages = DEFAU
9099
9497
  }
9100
9498
  try {
9101
9499
  const result = parsePublicationResult(
9102
- await client.applyPublication(projectId, idempotencyKey, applyRequest(decision.confirmation)),
9500
+ await applyPublicationWithProfile(
9501
+ client,
9502
+ projectId,
9503
+ idempotencyKey,
9504
+ applyRequest(decision.confirmation),
9505
+ session
9506
+ ),
9103
9507
  plan,
9104
9508
  messages,
9105
9509
  details.publicationId
@@ -9109,7 +9513,7 @@ async function runPublishCommand(options, writer, cwd, runtime, messages = DEFAU
9109
9513
  } catch (error) {
9110
9514
  if (error instanceof PublishCommandError && error.code === "AP_RESPONSE_INVALID") {
9111
9515
  } else if (!approvedApplyResultMayBeUnknown(error)) {
9112
- throw remoteError(error, "approved_apply", messages);
9516
+ throw remoteError(error, "approved_apply", messages, schemaReviewMessages);
9113
9517
  }
9114
9518
  }
9115
9519
  const recovered = await pollPublication(
@@ -9132,7 +9536,7 @@ async function runPublishCommand(options, writer, cwd, runtime, messages = DEFAU
9132
9536
  }
9133
9537
  writeResult(writer, recovered.result);
9134
9538
  }
9135
- function registerPublish(program, writer, cwd, createClient, description2 = "Tool Contract\u3092production publication workflow\u3067\u5B89\u5168\u306B\u516C\u958B\u3057\u307E\u3059", runtime = createPublishCommandRuntime(createClient), messages = DEFAULT_PUBLISH_MESSAGES, scopeRegistrationMessages = DEFAULT_SCOPE_REGISTRATION_MESSAGES2) {
9539
+ function registerPublish(program, writer, cwd, createClient, description2 = "Tool Contract\u3092production publication workflow\u3067\u5B89\u5168\u306B\u516C\u958B\u3057\u307E\u3059", runtime = createPublishCommandRuntime(createClient), messages = DEFAULT_PUBLISH_MESSAGES, scopeRegistrationMessages = DEFAULT_SCOPE_REGISTRATION_MESSAGES2, schemaReviewMessages = DEFAULT_SCHEMA_REVIEW_MESSAGES) {
9136
9540
  program.command("publish").description(description2).option("--connector <connector-uuid>", messages.connectorOption).option("--dry-run", messages.dryRunOption, false).option("--apply", messages.applyOption, false).option("--yes", messages.yesOption, false).option("--profile <name>", messages.profileOption, DEFAULT_PROFILE_NAME).option("--project <project-uuid>", messages.projectOption).action(async (commandOptions) => {
9137
9541
  await runPublishCommand(
9138
9542
  commandOptions,
@@ -9140,7 +9544,8 @@ function registerPublish(program, writer, cwd, createClient, description2 = "Too
9140
9544
  cwd(),
9141
9545
  runtime,
9142
9546
  messages,
9143
- scopeRegistrationMessages
9547
+ scopeRegistrationMessages,
9548
+ schemaReviewMessages
9144
9549
  );
9145
9550
  });
9146
9551
  }
@@ -9160,8 +9565,8 @@ function isUrl(value) {
9160
9565
  function field(meta, snake, camel) {
9161
9566
  return snake in meta ? meta[snake] : meta[camel];
9162
9567
  }
9163
- function validateOAuthMetadata(meta, locale = import_localization10.DEFAULT_LOCALE) {
9164
- const messages = import_localization10.CLI_MESSAGES[locale].oauth;
9568
+ function validateOAuthMetadata(meta, locale = import_localization12.DEFAULT_LOCALE) {
9569
+ const messages = import_localization12.CLI_MESSAGES[locale].oauth;
9165
9570
  const results = [];
9166
9571
  if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
9167
9572
  return {
@@ -9232,7 +9637,7 @@ var RESOURCE_NOT_FOUND_CODES = /* @__PURE__ */ new Set([
9232
9637
  "AP_TOOL_VERSION_NOT_FOUND"
9233
9638
  ]);
9234
9639
  function createOAuthScopeRegisterRuntime(createClient = (profile) => createAdminApiClient({ profile })) {
9235
- return { createClient, loadProject: loadDevProject, randomUuid: () => (0, import_node_crypto13.randomUUID)() };
9640
+ return { createClient, loadProject: loadDevProject, randomUuid: () => (0, import_node_crypto14.randomUUID)() };
9236
9641
  }
9237
9642
  var OAuthScopeRegistrationCommandError = class extends Error {
9238
9643
  constructor(code, reason, message, status) {
@@ -9255,9 +9660,9 @@ function parseDraftOption(value, messages) {
9255
9660
  }
9256
9661
  return { toolId, versionId };
9257
9662
  }
9258
- function normalizeOAuthScopeRegisterOptions(options, locale = import_localization10.DEFAULT_LOCALE) {
9259
- const messages = import_localization10.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9260
- const cliMessages = import_localization10.CLI_MESSAGES[locale];
9663
+ function normalizeOAuthScopeRegisterOptions(options, locale = import_localization12.DEFAULT_LOCALE) {
9664
+ const messages = import_localization12.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9665
+ const cliMessages = import_localization12.CLI_MESSAGES[locale];
9261
9666
  const apply = options.apply === true;
9262
9667
  if (options.yes === true && !apply) throw new UsageError(messages.yesRequiresApply);
9263
9668
  if (apply && options.yes !== true) {
@@ -9284,8 +9689,8 @@ function normalizeOAuthScopeRegisterOptions(options, locale = import_localizatio
9284
9689
  if (options.connector !== void 0) throw new UsageError(messages.draftConnectorConflict);
9285
9690
  if (options.project === void 0) throw new UsageError(messages.draftRequiresProject);
9286
9691
  const projectId = canonicalUuidOption(options.project, "--project", cliMessages.publish);
9287
- const drafts = rawDrafts.map((value) => parseDraftOption(value, messages)).sort((left, right) => (0, import_tool_contract10.comparePublicationUnicodeCodePoints)(left.toolId, right.toolId));
9288
- if (drafts.length > import_tool_contract10.OAUTH_SCOPE_REGISTRATION_MAX_DRAFTS || drafts.some((draft, index) => index > 0 && drafts[index - 1]?.toolId === draft.toolId)) {
9692
+ const drafts = rawDrafts.map((value) => parseDraftOption(value, messages)).sort((left, right) => (0, import_tool_contract11.comparePublicationUnicodeCodePoints)(left.toolId, right.toolId));
9693
+ if (drafts.length > import_tool_contract11.OAUTH_SCOPE_REGISTRATION_MAX_DRAFTS || drafts.some((draft, index) => index > 0 && drafts[index - 1]?.toolId === draft.toolId)) {
9289
9694
  throw new UsageError(messages.draftInvalid);
9290
9695
  }
9291
9696
  return { kind: "saved_drafts", projectId, drafts, apply, profile };
@@ -9402,8 +9807,8 @@ async function projectAccessibility(client, projectId, error) {
9402
9807
  }
9403
9808
  }
9404
9809
  function localCandidateSource(normalized, cwd, runtime, locale) {
9405
- const messages = import_localization10.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9406
- const publishMessages = import_localization10.CLI_MESSAGES[locale].publish;
9810
+ const messages = import_localization12.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9811
+ const publishMessages = import_localization12.CLI_MESSAGES[locale].publish;
9407
9812
  const project = loadPublicationProject(runtime.loadProject, cwd, publishMessages);
9408
9813
  const projectId = assertManifestProject(project, normalized.projectId, publishMessages);
9409
9814
  const connectorId = normalized.connectorId ?? project.manifest.connector_id;
@@ -9412,7 +9817,7 @@ function localCandidateSource(normalized, cwd, runtime, locale) {
9412
9817
  try {
9413
9818
  candidate = buildLocalPublicationCandidate(project, connectorId, publishMessages);
9414
9819
  } catch (error) {
9415
- if (error instanceof import_tool_contract10.PublicationCanonicalizationError && error.reason === "publication_value_too_large") {
9820
+ if (error instanceof import_tool_contract11.PublicationCanonicalizationError && error.reason === "publication_value_too_large") {
9416
9821
  throw new OAuthScopeRegistrationCommandError(
9417
9822
  "AP_INPUT_INVALID",
9418
9823
  "publication_candidate_too_large",
@@ -9432,8 +9837,8 @@ function localCandidateSource(normalized, cwd, runtime, locale) {
9432
9837
  expectedToolNames: candidate.expectedToolNames
9433
9838
  };
9434
9839
  }
9435
- async function runOAuthScopeRegisterCommand(options, writer, cwd, runtime, locale = import_localization10.DEFAULT_LOCALE) {
9436
- const messages = import_localization10.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale];
9840
+ async function runOAuthScopeRegisterCommand(options, writer, cwd, runtime, locale = import_localization12.DEFAULT_LOCALE) {
9841
+ const messages = import_localization12.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale];
9437
9842
  const normalized = normalizeOAuthScopeRegisterOptions(options, locale);
9438
9843
  const target = normalized.kind === "saved_drafts" ? {
9439
9844
  projectId: normalized.projectId,
@@ -9481,7 +9886,7 @@ async function runOAuthScopeRegisterCommand(options, writer, cwd, runtime, local
9481
9886
  throw new OAuthScopeRegistrationCommandError(
9482
9887
  "AP_NETWORK_ERROR",
9483
9888
  "secure_random_invalid",
9484
- import_localization10.CLI_MESSAGES[locale].publish.failure("secure_random_invalid")
9889
+ import_localization12.CLI_MESSAGES[locale].publish.failure("secure_random_invalid")
9485
9890
  );
9486
9891
  }
9487
9892
  let applied;
@@ -9511,7 +9916,7 @@ function upstreamOAuthWizardUrl(profile, projectId, connectorId) {
9511
9916
  return url.toString();
9512
9917
  }
9513
9918
  async function loadOAuthMetadata(opts, locale) {
9514
- const messages = import_localization10.CLI_MESSAGES[locale];
9919
+ const messages = import_localization12.CLI_MESSAGES[locale];
9515
9920
  if (opts.file && opts.issuer) {
9516
9921
  throw new UsageError("--file \u3068 --issuer \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");
9517
9922
  }
@@ -9522,13 +9927,13 @@ async function loadOAuthMetadata(opts, locale) {
9522
9927
  throw new UsageError(messages.oauth.fileRequired);
9523
9928
  }
9524
9929
  try {
9525
- return JSON.parse((0, import_node_fs11.readFileSync)(opts.file, "utf8"));
9930
+ return JSON.parse((0, import_node_fs13.readFileSync)(opts.file, "utf8"));
9526
9931
  } catch (error) {
9527
9932
  throw new UsageError(messages.oauth.metadataReadFailed(error.message));
9528
9933
  }
9529
9934
  }
9530
9935
  async function runOAuthMetadataValidate(opts, writer, locale) {
9531
- const messages = import_localization10.CLI_MESSAGES[locale];
9936
+ const messages = import_localization12.CLI_MESSAGES[locale];
9532
9937
  const parsed = await loadOAuthMetadata(opts, locale);
9533
9938
  const report = validateOAuthMetadata(parsed, locale);
9534
9939
  json(writer, report.results);
@@ -9539,8 +9944,8 @@ async function runOAuthMetadataValidate(opts, writer, locale) {
9539
9944
  info(writer, messages.oauth.metadataOk);
9540
9945
  }
9541
9946
  }
9542
- function registerOauth(program, writer, locale = import_localization10.DEFAULT_LOCALE, dependencies = {}) {
9543
- const messages = import_localization10.CLI_MESSAGES[locale];
9947
+ function registerOauth(program, writer, locale = import_localization12.DEFAULT_LOCALE, dependencies = {}) {
9948
+ const messages = import_localization12.CLI_MESSAGES[locale];
9544
9949
  const oauth = program.command("oauth").description(messages.oauth.commandDescription);
9545
9950
  oauth.command("init").description(messages.oauth.initDescription).requiredOption("--provider <name>", messages.oauth.providerOption).action((opts) => {
9546
9951
  info(writer, messages.oauth.templateHeading(opts.provider));
@@ -9583,7 +9988,7 @@ function registerOauth(program, writer, locale = import_localization10.DEFAULT_L
9583
9988
  });
9584
9989
  json(writer, result);
9585
9990
  });
9586
- const registration = import_localization10.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9991
+ const registration = import_localization12.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9587
9992
  const scopeRegisterRuntime = dependencies.scopeRegisterRuntime ?? createOAuthScopeRegisterRuntime();
9588
9993
  const cwd = dependencies.cwd ?? (() => process.cwd());
9589
9994
  scopes.command("register").description(registration.commandDescription).option("--project <project-uuid>", registration.projectOption).option("--connector <connector-uuid>", registration.connectorOption).option(
@@ -9687,11 +10092,11 @@ function registerOauth(program, writer, locale = import_localization10.DEFAULT_L
9687
10092
  }
9688
10093
 
9689
10094
  // src/commands/openapi.ts
9690
- var import_node_crypto14 = require("crypto");
9691
- var import_node_path12 = require("path");
9692
- var import_tool_contract11 = require("@andpipes/tool-contract");
10095
+ var import_node_crypto15 = require("crypto");
10096
+ var import_node_path14 = require("path");
10097
+ var import_tool_contract12 = require("@andpipes/tool-contract");
9693
10098
  function createOpenApiImportRuntime(createClient = (profile) => createAdminApiClient({ profile })) {
9694
- return { createClient, idempotencyKey: import_node_crypto14.randomUUID };
10099
+ return { createClient, idempotencyKey: import_node_crypto15.randomUUID };
9695
10100
  }
9696
10101
  function normalizedOptions(options) {
9697
10102
  if (!options.file || !options.project || !options.connector) {
@@ -9747,8 +10152,8 @@ async function runOpenApiImportCommand(options, writer, cwd, runtime = createOpe
9747
10152
  if (normalized.apply && !/^[a-f0-9]{64}$/.test(normalized.planCommitment ?? "")) {
9748
10153
  throw new UsageError("--apply \u306B\u306Fpreview\u3067\u5F97\u305F --plan-commitment \u304C\u5FC5\u9808\u3067\u3059");
9749
10154
  }
9750
- const snapshot = readBoundedLocalFileSnapshot((0, import_node_path12.resolve)(cwd, normalized.file), {
9751
- maxBytes: import_tool_contract11.OPENAPI_IMPORT_MAX_SOURCE_BYTES,
10155
+ const snapshot = readBoundedLocalFileSnapshot((0, import_node_path14.resolve)(cwd, normalized.file), {
10156
+ maxBytes: import_tool_contract12.OPENAPI_IMPORT_MAX_SOURCE_BYTES,
9752
10157
  root: cwd
9753
10158
  });
9754
10159
  const baseRequest = {
@@ -9769,7 +10174,7 @@ async function runOpenApiImportCommand(options, writer, cwd, runtime = createOpe
9769
10174
  if (normalized.sideEffectFree.length > 0) {
9770
10175
  if (normalized.apply) {
9771
10176
  try {
9772
- const unclassified = (0, import_tool_contract11.importOpenApi)(snapshot.text, {
10177
+ const unclassified = (0, import_tool_contract12.importOpenApi)(snapshot.text, {
9773
10178
  format: normalized.format,
9774
10179
  baseUrl: normalized.baseUrl,
9775
10180
  serviceName: normalized.serviceName,
@@ -9780,7 +10185,7 @@ async function runOpenApiImportCommand(options, writer, cwd, runtime = createOpe
9780
10185
  unclassified.operations
9781
10186
  );
9782
10187
  } catch (error) {
9783
- if (error instanceof import_tool_contract11.OpenApiImportError) {
10188
+ if (error instanceof import_tool_contract12.OpenApiImportError) {
9784
10189
  throw new UsageError(`OpenAPI\u304B\u3089Tool Contract\u3092\u751F\u6210\u3067\u304D\u307E\u305B\u3093: ${error.message}`);
9785
10190
  }
9786
10191
  throw error;
@@ -9835,15 +10240,15 @@ function registerOpenApi(program, writer, cwd, runtime = createOpenApiImportRunt
9835
10240
  }
9836
10241
 
9837
10242
  // src/commands/review-package.ts
9838
- var import_localization11 = require("@andpipes/localization");
10243
+ var import_localization13 = require("@andpipes/localization");
9839
10244
  var TARGETS = ["chatgpt", "claude", "generic_mcp"];
9840
- function assertTarget(value, locale = import_localization11.DEFAULT_LOCALE) {
10245
+ function assertTarget(value, locale = import_localization13.DEFAULT_LOCALE) {
9841
10246
  if (!TARGETS.includes(value)) {
9842
- throw new UsageError(import_localization11.CLI_MESSAGES[locale].reviewPackage.invalidTarget(value, TARGETS));
10247
+ throw new UsageError(import_localization13.CLI_MESSAGES[locale].reviewPackage.invalidTarget(value, TARGETS));
9843
10248
  }
9844
10249
  }
9845
- function registerReviewPackage(program, writer, locale = import_localization11.DEFAULT_LOCALE, cwd = () => process.cwd()) {
9846
- const messages = import_localization11.CLI_MESSAGES[locale];
10250
+ function registerReviewPackage(program, writer, locale = import_localization13.DEFAULT_LOCALE, cwd = () => process.cwd()) {
10251
+ const messages = import_localization13.CLI_MESSAGES[locale];
9847
10252
  const reviewPackage = program.command("review-package").description(messages.reviewPackage.commandDescription);
9848
10253
  reviewPackage.command("generate").description(messages.reviewPackage.generateDescription).requiredOption("--project <project>", messages.common.projectOption).requiredOption("--package-version <version>", messages.reviewPackage.packageVersionOption).option("--target <target>", messages.reviewPackage.targetOption).option(
9849
10254
  "--from-template",
@@ -9904,61 +10309,13 @@ function registerReviewPackage(program, writer, locale = import_localization11.D
9904
10309
  });
9905
10310
  }
9906
10311
 
9907
- // src/commands/validate.ts
9908
- var import_node_fs12 = require("fs");
9909
- var import_node_path13 = require("path");
9910
- var import_localization12 = require("@andpipes/localization");
9911
- function resolveContractPath(file, cwd, locale = import_localization12.DEFAULT_LOCALE) {
9912
- const messages = import_localization12.CLI_MESSAGES[locale].validate;
9913
- if (file) {
9914
- const abs = (0, import_node_path13.resolve)(cwd, file);
9915
- if (!(0, import_node_fs12.existsSync)(abs)) {
9916
- throw new UsageError(messages.fileNotFound(file));
9917
- }
9918
- return abs;
9919
- }
9920
- for (const candidate of import_tool_contract4.CONTRACT_FILENAMES) {
9921
- const abs = (0, import_node_path13.resolve)(cwd, candidate);
9922
- if ((0, import_node_fs12.existsSync)(abs)) {
9923
- return abs;
9924
- }
9925
- }
9926
- throw new UsageError(messages.defaultFileNotFound(import_tool_contract4.CONTRACT_FILENAMES));
9927
- }
9928
- function registerValidate(program, writer, cwd, locale = import_localization12.DEFAULT_LOCALE) {
9929
- const text = import_localization12.LOCALIZED_TEXT[locale].cli;
9930
- const messages = import_localization12.CLI_MESSAGES[locale].validate;
9931
- program.command("validate").description(`${text.validateDescription} (10 checks)`).option("--file <path>", messages.fileOption).action((opts) => {
9932
- const path = resolveContractPath(opts.file, cwd(), locale);
9933
- const loaded = loadContractFile(path);
9934
- const report = loaded.report;
9935
- const publishGate = loaded.publishGate;
9936
- json(writer, { checks: report.results, publishGate });
9937
- const fail2 = report.results.filter((r) => r.status === "fail").length;
9938
- const pending = report.results.filter((r) => r.status === "pending").length;
9939
- const pass = report.results.filter((r) => r.status === "pass").length;
9940
- info(
9941
- writer,
9942
- `${text.resultLabel}: pass=${pass} fail=${fail2} pending=${pending} (pending=${text.backendPending})`
9943
- );
9944
- info(
9945
- writer,
9946
- messages.publishGateSummary(publishGate.errors.length, publishGate.warnings.length)
9947
- );
9948
- if (!report.ok || !publishGate.ok) {
9949
- process.exitCode = 1;
9950
- info(writer, messages.failed);
9951
- }
9952
- });
9953
- }
9954
-
9955
10312
  // src/cli.ts
9956
- function buildProgram(writer = defaultWriter, cwd = () => process.cwd(), locale = (0, import_localization13.normalizeLocale)(process.env.ANDPIPE_LOCALE ?? process.env.LANG)) {
9957
- const text = import_localization13.LOCALIZED_TEXT[locale].cli;
9958
- const messages = import_localization13.CLI_MESSAGES[locale];
9959
- const scopeRegistrationMessages = import_localization13.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
10313
+ function buildProgram(writer = defaultWriter, cwd = () => process.cwd(), locale = (0, import_localization14.normalizeLocale)(process.env.ANDPIPE_LOCALE ?? process.env.LANG)) {
10314
+ const text = import_localization14.LOCALIZED_TEXT[locale].cli;
10315
+ const messages = import_localization14.CLI_MESSAGES[locale];
10316
+ const scopeRegistrationMessages = import_localization14.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9960
10317
  const program = new import_commander.Command();
9961
- program.name(CLI_NAME).description(text.description).option("--locale <locale>", messages.localeOption, import_localization13.DEFAULT_LOCALE).version(readVersion());
10318
+ program.name(CLI_NAME).description(text.description).option("--locale <locale>", messages.localeOption, import_localization14.DEFAULT_LOCALE).version(readVersion());
9962
10319
  registerAuth(program, writer, locale);
9963
10320
  registerAuditExport(program, writer, locale);
9964
10321
  registerInit(
@@ -9981,6 +10338,7 @@ function buildProgram(writer = defaultWriter, cwd = () => process.cwd(), locale
9981
10338
  registerDoctor(program, writer, locale);
9982
10339
  registerLogs(program, writer, locale);
9983
10340
  registerTemplate(program, writer, cwd);
10341
+ registerMuse(program, writer, cwd, locale);
9984
10342
  registerPublish(
9985
10343
  program,
9986
10344
  writer,
@@ -9989,20 +10347,21 @@ function buildProgram(writer = defaultWriter, cwd = () => process.cwd(), locale
9989
10347
  text.publishDescription,
9990
10348
  void 0,
9991
10349
  messages.publish,
9992
- scopeRegistrationMessages
10350
+ scopeRegistrationMessages,
10351
+ import_localization14.PUBLICATION_SCHEMA_REVIEW_CLI_MESSAGES[locale]
9993
10352
  );
9994
10353
  return program;
9995
10354
  }
9996
10355
  function localeFromArgv(argv) {
9997
10356
  const localeIndex = argv.indexOf("--locale");
9998
10357
  if (localeIndex >= 0) {
9999
- return (0, import_localization13.normalizeLocale)(argv[localeIndex + 1]);
10358
+ return (0, import_localization14.normalizeLocale)(argv[localeIndex + 1]);
10000
10359
  }
10001
10360
  const inlineLocale = argv.find((arg) => arg.startsWith("--locale="));
10002
10361
  if (inlineLocale) {
10003
- return (0, import_localization13.normalizeLocale)(inlineLocale.slice("--locale=".length));
10362
+ return (0, import_localization14.normalizeLocale)(inlineLocale.slice("--locale=".length));
10004
10363
  }
10005
- return (0, import_localization13.normalizeLocale)(process.env.ANDPIPE_LOCALE ?? process.env.LANG);
10364
+ return (0, import_localization14.normalizeLocale)(process.env.ANDPIPE_LOCALE ?? process.env.LANG);
10006
10365
  }
10007
10366
  async function runCli(argv, writer = defaultWriter) {
10008
10367
  await buildProgram(writer, () => process.cwd(), localeFromArgv(argv)).parseAsync(argv);