@andpipes/cli 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.cjs CHANGED
@@ -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;
@@ -476,6 +496,9 @@ var ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES = 96 * 1024;
476
496
  var ADMIN_API_OPENAPI_IMPORT_MAX_BYTES = 1280 * 1024;
477
497
  var ADMIN_API_ONBOARDING_TEMPLATE_MAX_BYTES = 64 * 1024;
478
498
  var ADMIN_API_MAX_GET_ATTEMPTS = 3;
499
+ var ADMIN_API_OAUTH_SCOPE_REGISTRATION_REQUEST_MAX_BYTES = ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES + 8 * 1024;
500
+ var ADMIN_API_OAUTH_SCOPE_REGISTRATION_RESPONSE_MAX_BYTES = 1024 * 1024;
501
+ var ADMIN_API_OAUTH_SCOPE_REGISTRATION_MAX_APPLY_ATTEMPTS = 3;
479
502
  var PROJECT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
480
503
  var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
481
504
  var SAFE_AP_CODE_RE = /^AP_[A-Z0-9_]{1,64}$/;
@@ -490,13 +513,21 @@ var AdminApiClientError = class extends Error {
490
513
  status;
491
514
  confirmationRequired;
492
515
  openApiAuthModeMismatch;
493
- constructor(code, message, status, confirmationRequired, openApiAuthModeMismatch) {
516
+ detailsAbsent;
517
+ scopeRegistrationReason;
518
+ publishGateToolNames;
519
+ publicationReason;
520
+ constructor(code, message, status, confirmationRequired, openApiAuthModeMismatch, safeDetails = {}) {
494
521
  super(message);
495
522
  this.name = "AdminApiClientError";
496
523
  this.code = code;
497
524
  this.status = status;
498
525
  this.confirmationRequired = confirmationRequired;
499
526
  this.openApiAuthModeMismatch = openApiAuthModeMismatch;
527
+ this.detailsAbsent = safeDetails.detailsAbsent === true;
528
+ this.scopeRegistrationReason = safeDetails.scopeRegistrationReason;
529
+ this.publishGateToolNames = safeDetails.publishGateToolNames === void 0 ? void 0 : Object.freeze([...safeDetails.publishGateToolNames]);
530
+ this.publicationReason = safeDetails.publicationReason;
500
531
  }
501
532
  };
502
533
  function clientError(code, message, status) {
@@ -707,7 +738,13 @@ function withKnownResponseStatus(error, responseStatus) {
707
738
  error.message,
708
739
  responseStatus,
709
740
  error.confirmationRequired,
710
- error.openApiAuthModeMismatch
741
+ error.openApiAuthModeMismatch,
742
+ {
743
+ detailsAbsent: error.detailsAbsent,
744
+ ...error.scopeRegistrationReason === void 0 ? {} : { scopeRegistrationReason: error.scopeRegistrationReason },
745
+ ...error.publishGateToolNames === void 0 ? {} : { publishGateToolNames: error.publishGateToolNames },
746
+ ...error.publicationReason === void 0 ? {} : { publicationReason: error.publicationReason }
747
+ }
711
748
  );
712
749
  }
713
750
  var CONNECTOR_AUTH_MODES = /* @__PURE__ */ new Set([
@@ -727,6 +764,27 @@ function parseOpenApiImportAuthModeMismatch(value) {
727
764
  requestedAuthMode: details.requestedAuthMode
728
765
  };
729
766
  }
767
+ function parseScopeRegistrationErrorDetails(status, value) {
768
+ if (status < 400 || status > 499) return {};
769
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return {};
770
+ const details = value;
771
+ const reason = details.reason;
772
+ if (!(0, import_tool_contract.isOAuthScopeRegistrationErrorReason)(reason)) return {};
773
+ const keys = Object.keys(details).sort().join(",");
774
+ if (reason === "marketplace_managed_tool") {
775
+ return keys === "reason" || keys === "reason,toolName" && (0, import_tool_contract.isSafeToolName)(details.toolName) ? { scopeRegistrationReason: reason } : {};
776
+ }
777
+ if (reason !== "scope_registration_publish_gate_failed") {
778
+ return keys === "reason" ? { scopeRegistrationReason: reason } : {};
779
+ }
780
+ const toolNames = details.toolNames;
781
+ if (keys !== "reason,toolNames" || !Array.isArray(toolNames) || toolNames.length < 1 || toolNames.length > import_tool_contract.OAUTH_SCOPE_REGISTRATION_MAX_TOOLS || !toolNames.every((name) => (0, import_tool_contract.isSafeToolName)(name)) || toolNames.some(
782
+ (name, index) => index > 0 && (0, import_tool_contract.comparePublicationUnicodeCodePoints)(toolNames[index - 1], name) >= 0
783
+ )) {
784
+ return {};
785
+ }
786
+ return { scopeRegistrationReason: reason, publishGateToolNames: toolNames };
787
+ }
730
788
  function unicodeScalarLength(value) {
731
789
  let length = 0;
732
790
  for (const character of value) {
@@ -754,12 +812,19 @@ function safeApiError(status, value) {
754
812
  const code = typeof candidate === "string" && SAFE_AP_CODE_RE.test(candidate) ? candidate : "AP_HTTP_ERROR";
755
813
  const confirmationRequired = code === "AP_CONFIRMATION_REQUIRED" && status === 409 ? parsePublicationConfirmationRequiredDetails(errorRecord?.details) : void 0;
756
814
  const openApiAuthModeMismatch = code === "AP_CONFLICT" && status === 409 ? parseOpenApiImportAuthModeMismatch(errorRecord?.details) : void 0;
815
+ const publicationReason = parsePublicationErrorReason(status, code, errorRecord?.details);
757
816
  return new AdminApiClientError(
758
817
  code,
759
818
  `Admin API request failed (${code}; HTTP ${status})`,
760
819
  status,
761
820
  confirmationRequired,
762
- openApiAuthModeMismatch
821
+ openApiAuthModeMismatch,
822
+ {
823
+ // AP error envelopeを受け取れた場合だけ「detailsなし」を判定できる。
824
+ detailsAbsent: errorRecord !== void 0 && (errorRecord.details === null || errorRecord.details === void 0),
825
+ ...parseScopeRegistrationErrorDetails(status, errorRecord?.details),
826
+ ...publicationReason === void 0 ? {} : { publicationReason }
827
+ }
763
828
  );
764
829
  }
765
830
  function buildUrl(path) {
@@ -892,6 +957,13 @@ function publicationPlanBody(input) {
892
957
  ...input.templateProvenance === void 0 ? {} : { templateProvenance: input.templateProvenance }
893
958
  };
894
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
+ }
895
967
  function publicationApplyBody(input) {
896
968
  const common = publicationPlanBody(input);
897
969
  if (!import_tool_contract.PUBLICATION_SHA256_COMMITMENT_RE.test(input.planCommitment)) {
@@ -911,6 +983,111 @@ function publicationApplyBody(input) {
911
983
  }
912
984
  };
913
985
  }
986
+ function scopeRegistrationSourceInvalid() {
987
+ return clientError("AP_INPUT_INVALID", "OAuth scope registration source is invalid");
988
+ }
989
+ function oauthScopeRegistrationSourceBody(source) {
990
+ if (source.kind === "saved_drafts") {
991
+ const drafts = source.drafts;
992
+ if (!Array.isArray(drafts) || drafts.length < 1 || drafts.length > import_tool_contract.OAUTH_SCOPE_REGISTRATION_MAX_DRAFTS) {
993
+ throw scopeRegistrationSourceInvalid();
994
+ }
995
+ const body = drafts.map((draft) => {
996
+ if (!PUBLICATION_UUID_RE.test(draft.toolId) || !PUBLICATION_UUID_RE.test(draft.versionId)) {
997
+ throw scopeRegistrationSourceInvalid();
998
+ }
999
+ return { toolId: draft.toolId, versionId: draft.versionId };
1000
+ });
1001
+ for (let index = 1; index < body.length; index += 1) {
1002
+ const previous = body[index - 1];
1003
+ const current = body[index];
1004
+ if ((0, import_tool_contract.comparePublicationUnicodeCodePoints)(previous.toolId, current.toolId) >= 0) {
1005
+ throw scopeRegistrationSourceInvalid();
1006
+ }
1007
+ }
1008
+ return { kind: "saved_drafts", drafts: body };
1009
+ }
1010
+ if (source.kind !== "publication_candidate") throw scopeRegistrationSourceInvalid();
1011
+ if (!PUBLICATION_UUID_RE.test(source.connectorId) || source.candidateContract === null || typeof source.candidateContract !== "object" || Array.isArray(source.candidateContract) || !import_tool_contract.PUBLICATION_SHA256_COMMITMENT_RE.test(source.candidateCommitment)) {
1012
+ throw scopeRegistrationSourceInvalid();
1013
+ }
1014
+ try {
1015
+ (0, import_tool_contract.assertCanonicalPublicationSize)(source.candidateContract);
1016
+ } catch {
1017
+ throw clientError("AP_INPUT_INVALID", "OAuth scope registration candidate is too large");
1018
+ }
1019
+ if ((0, import_tool_contract.publicationCommitment)("candidate", source.candidateContract) !== source.candidateCommitment) {
1020
+ throw clientError(
1021
+ "AP_CONFLICT",
1022
+ "OAuth scope registration candidate commitment does not match"
1023
+ );
1024
+ }
1025
+ return {
1026
+ kind: "publication_candidate",
1027
+ connectorId: source.connectorId,
1028
+ candidateContract: source.candidateContract,
1029
+ candidateCommitment: source.candidateCommitment
1030
+ };
1031
+ }
1032
+ function scopeRegistrationResponseInvalid() {
1033
+ return clientError(
1034
+ "AP_RESPONSE_INVALID",
1035
+ "Admin API response oauth scope registration is invalid"
1036
+ );
1037
+ }
1038
+ function parseOAuthScopeRegistration(value, projectId, request) {
1039
+ let parsed;
1040
+ try {
1041
+ parsed = (0, import_tool_contract.parseOAuthScopeRegistrationResponse)(value, { projectId });
1042
+ } catch (error) {
1043
+ if (error instanceof import_tool_contract.OAuthScopeRegistrationDtoError) throw scopeRegistrationResponseInvalid();
1044
+ throw error;
1045
+ }
1046
+ if (parsed.mode !== (request.apply ? "applied" : "preview") || parsed.source.kind !== request.source.kind) {
1047
+ throw scopeRegistrationResponseInvalid();
1048
+ }
1049
+ const source = request.source;
1050
+ if (source.kind === "publication_candidate") {
1051
+ if (parsed.source.connectorId !== source.connectorId || parsed.sourceCommitment !== (0, import_tool_contract.oauthScopeRegistrationSourceCommitment)({
1052
+ projectId,
1053
+ kind: "publication_candidate",
1054
+ connectorId: source.connectorId,
1055
+ candidateCommitment: source.candidateCommitment
1056
+ })) {
1057
+ throw scopeRegistrationResponseInvalid();
1058
+ }
1059
+ } else {
1060
+ const returned = parsed.source.tools.map((tool) => ({ toolId: tool.toolId, versionId: tool.versionId })).sort((left, right) => (0, import_tool_contract.comparePublicationUnicodeCodePoints)(left.toolId, right.toolId));
1061
+ if (returned.length !== source.drafts.length || returned.some(
1062
+ (draft, index) => draft.toolId !== source.drafts[index]?.toolId || draft.versionId !== source.drafts[index]?.versionId
1063
+ )) {
1064
+ throw scopeRegistrationResponseInvalid();
1065
+ }
1066
+ }
1067
+ if (request.apply && (parsed.sourceCommitment !== request.sourceCommitment || parsed.baseRegistryCommitment !== request.baseRegistryCommitment || parsed.planCommitment !== request.planCommitment)) {
1068
+ throw scopeRegistrationResponseInvalid();
1069
+ }
1070
+ return parsed;
1071
+ }
1072
+ var DEFINITIVE_SCOPE_REGISTRATION_APPLY_ERROR_CODES = /* @__PURE__ */ new Set([
1073
+ "AP_AUTH_REQUIRED",
1074
+ "AP_CONFIRMATION_EXPIRED",
1075
+ "AP_CONFLICT",
1076
+ "AP_FORBIDDEN",
1077
+ "AP_IDEMPOTENCY_KEY_CONFLICT",
1078
+ "AP_INPUT_INVALID",
1079
+ "AP_INVALID_SCOPE",
1080
+ "AP_NOT_FOUND",
1081
+ "AP_POLICY_DENIED",
1082
+ "AP_UNAUTHORIZED"
1083
+ ]);
1084
+ function scopeRegistrationApplyResultMayBeUnknown(error) {
1085
+ if (error.status !== void 0 && error.status >= 400 && error.status < 500) return false;
1086
+ if (error.status === void 0 && DEFINITIVE_SCOPE_REGISTRATION_APPLY_ERROR_CODES.has(error.code)) {
1087
+ return false;
1088
+ }
1089
+ return true;
1090
+ }
914
1091
  function openApiImportBody(input) {
915
1092
  if (typeof input.source !== "string" || input.source.length === 0 || !PUBLICATION_UUID_RE.test(input.connectorId) || input.expectedPlanCommitment !== void 0 && !SHA256_HEX_RE.test(input.expectedPlanCommitment) || input.format !== void 0 && input.format !== "json" && input.format !== "yaml" || input.baseUrl !== void 0 && typeof input.baseUrl !== "string" || input.serviceName !== void 0 && !/^[A-Za-z0-9_]{1,48}$/.test(input.serviceName) || input.upstreamAuthMode !== void 0 && !(0, import_tool_contract.isOpenApiImportUpstreamAuthMode)(input.upstreamAuthMode)) {
916
1093
  throw clientError("AP_INPUT_INVALID", "OpenAPI import request is invalid");
@@ -1142,6 +1319,10 @@ var AdminApiClient = class {
1142
1319
  this.#sleep = options.sleep ?? ((milliseconds) => new Promise((resolve7) => setTimeout(resolve7, milliseconds)));
1143
1320
  }
1144
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 = {}) {
1145
1326
  const url = buildUrl(path);
1146
1327
  const method = options.method ?? "GET";
1147
1328
  const attempts = method === "GET" ? ADMIN_API_MAX_GET_ATTEMPTS : 1;
@@ -1163,6 +1344,9 @@ var AdminApiClient = class {
1163
1344
  if (options.authenticated !== false) headers.set("Authorization", `Bearer ${this.#token}`);
1164
1345
  if (body !== void 0) headers.set("Content-Type", "application/json");
1165
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
+ }
1166
1350
  response = await this.#fetch(url, {
1167
1351
  method,
1168
1352
  headers,
@@ -1219,8 +1403,8 @@ var AdminApiClient = class {
1219
1403
  }
1220
1404
  throw safeApiError(response.status, errorBody);
1221
1405
  }
1222
- if (options.responseType === "text") return text;
1223
- return parseJson(text);
1406
+ if (options.responseType === "text") return { value: text, headers: response.headers };
1407
+ return { value: parseJson(text), headers: response.headers };
1224
1408
  }
1225
1409
  throw clientError("AP_NETWORK_ERROR", "Admin API request failed");
1226
1410
  }
@@ -1366,24 +1550,41 @@ var AdminApiClient = class {
1366
1550
  status: connector.status
1367
1551
  };
1368
1552
  }
1369
- async planPublication(projectId, body) {
1370
- return this.#request(`/v1/projects/${assertProjectId(projectId)}/tool-publications:plan`, {
1371
- method: "POST",
1372
- body: publicationPlanBody(body),
1373
- maxRequestBytes: ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES,
1374
- maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES
1375
- });
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;
1376
1571
  }
1377
- 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) {
1378
1577
  if (!/^[A-Za-z0-9._:-]{22,200}$/u.test(idempotencyKey)) {
1379
1578
  throw clientError("AP_INPUT_INVALID", "tool publication Idempotency-Key is invalid");
1380
1579
  }
1580
+ const reviewProfile = publicationReviewProfileOption(options);
1381
1581
  return this.#request(`/v1/projects/${assertProjectId(projectId)}/tool-publications`, {
1382
1582
  method: "POST",
1383
1583
  body: publicationApplyBody(body),
1384
1584
  idempotencyKey,
1385
1585
  maxRequestBytes: ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES,
1386
- maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES
1586
+ maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES,
1587
+ ...reviewProfile === void 0 ? {} : { reviewProfile }
1387
1588
  });
1388
1589
  }
1389
1590
  async planOpenApiImport(projectId, input) {
@@ -1750,6 +1951,75 @@ var AdminApiClient = class {
1750
1951
  planCommitment
1751
1952
  };
1752
1953
  }
1954
+ /**
1955
+ * `POST /v1/projects/{projectId}/oauth/scopes:register` (#729 / ADR-729)。previewは副作用なしで1回だけ送る。
1956
+ * applyはpreviewの3 commitmentと呼出側のIdempotency-Keyを必須にし、network・timeout・5xx・2xx応答の
1957
+ * 破損という曖昧な失敗だけ、同じkeyとbodyで最大3回まで送る。responseはexact 12 keyと
1958
+ * planCommitmentを再計算して検証し、requestとの束縛が崩れていれば`AP_RESPONSE_INVALID`にする。
1959
+ */
1960
+ async registerOAuthScopes(input) {
1961
+ const projectId = assertProjectId(input.projectId);
1962
+ const source = oauthScopeRegistrationSourceBody(input.source);
1963
+ const path = `/v1/projects/${projectId}/oauth/scopes:register`;
1964
+ const limits = {
1965
+ maxRequestBytes: ADMIN_API_OAUTH_SCOPE_REGISTRATION_REQUEST_MAX_BYTES,
1966
+ maxResponseBytes: ADMIN_API_OAUTH_SCOPE_REGISTRATION_RESPONSE_MAX_BYTES
1967
+ };
1968
+ if (!input.apply) {
1969
+ const value = await this.#request(path, {
1970
+ method: "POST",
1971
+ body: { apply: false, confirmed: false, source },
1972
+ ...limits
1973
+ });
1974
+ return parseOAuthScopeRegistration(value, projectId, input);
1975
+ }
1976
+ for (const commitment of [
1977
+ input.sourceCommitment,
1978
+ input.baseRegistryCommitment,
1979
+ input.planCommitment
1980
+ ]) {
1981
+ if (!import_tool_contract.PUBLICATION_SHA256_COMMITMENT_RE.test(commitment)) {
1982
+ throw clientError("AP_INPUT_INVALID", "OAuth scope registration commitment is invalid");
1983
+ }
1984
+ }
1985
+ if (!/^[A-Za-z0-9._:-]{22,200}$/u.test(input.idempotencyKey)) {
1986
+ throw clientError("AP_INPUT_INVALID", "OAuth scope registration Idempotency-Key is invalid");
1987
+ }
1988
+ const body = {
1989
+ apply: true,
1990
+ confirmed: true,
1991
+ source,
1992
+ sourceCommitment: input.sourceCommitment,
1993
+ baseRegistryCommitment: input.baseRegistryCommitment,
1994
+ planCommitment: input.planCommitment
1995
+ };
1996
+ if (Buffer.byteLength(JSON.stringify(body), "utf8") > limits.maxRequestBytes) {
1997
+ throw clientError("AP_INPUT_INVALID", "Admin API request body exceeds its byte limit");
1998
+ }
1999
+ for (let attempt = 1; ; attempt += 1) {
2000
+ try {
2001
+ const value = await this.#request(path, {
2002
+ method: "POST",
2003
+ body,
2004
+ idempotencyKey: input.idempotencyKey,
2005
+ ...limits
2006
+ });
2007
+ return parseOAuthScopeRegistration(value, projectId, input);
2008
+ } catch (error) {
2009
+ if (!(error instanceof AdminApiClientError) || !scopeRegistrationApplyResultMayBeUnknown(error)) {
2010
+ throw error;
2011
+ }
2012
+ if (attempt >= ADMIN_API_OAUTH_SCOPE_REGISTRATION_MAX_APPLY_ATTEMPTS) {
2013
+ throw clientError(
2014
+ "AP_RESULT_UNKNOWN",
2015
+ "OAuth scope registration result is unknown; review the current state without --apply before retrying",
2016
+ error.status
2017
+ );
2018
+ }
2019
+ await this.#sleep(100 * attempt);
2020
+ }
2021
+ }
2022
+ }
1753
2023
  async testOAuthLogin(projectId, clientRegistryId) {
1754
2024
  const selectedClientRegistryId = assertUuid(clientRegistryId, "OAuth client registry id");
1755
2025
  const value = asObject(
@@ -7326,6 +7596,8 @@ var MANIFEST_KEYS2 = [
7326
7596
  "template_application_commitment"
7327
7597
  ];
7328
7598
  var DEFAULT_INIT_MESSAGES = import_localization7.CLI_MESSAGES.ja.init;
7599
+ var DEFAULT_SCOPE_REGISTRATION_MESSAGES = import_localization7.OAUTH_SCOPE_REGISTRATION_MESSAGES.ja.cli;
7600
+ var CONNECTOR_PLACEHOLDER = "<connector-uuid>";
7329
7601
  function assertTemplateInitOptionShape(options, messages = DEFAULT_INIT_MESSAGES) {
7330
7602
  if (options.openapi !== void 0 && options.project === void 0) {
7331
7603
  throw new UsageError(messages.optionRequires("--openapi", "--project <uuid>"));
@@ -7956,7 +8228,7 @@ function assertIdempotencyKey(value, messages) {
7956
8228
  }
7957
8229
  return canonical;
7958
8230
  }
7959
- async function runInitCommand(options, writer, cwd, runtime, messages = DEFAULT_INIT_MESSAGES) {
8231
+ async function runInitCommand(options, writer, cwd, runtime, messages = DEFAULT_INIT_MESSAGES, scopeRegistrationMessages = DEFAULT_SCOPE_REGISTRATION_MESSAGES) {
7960
8232
  assertTemplateInitOptionShape(options, messages);
7961
8233
  if (options.template !== void 0 && options.project === void 0) {
7962
8234
  throw new UsageError("init --template\u306B\u306Fexport\u5143\u3068\u540C\u3058--project <uuid>\u304C\u5FC5\u9808\u3067\u3059");
@@ -8077,8 +8349,16 @@ async function runInitCommand(options, writer, cwd, runtime, messages = DEFAULT_
8077
8349
  project: { id: project.id, name: project.name, slug: project.slug }
8078
8350
  })
8079
8351
  );
8352
+ if (options.openapi !== void 0) {
8353
+ interactive(
8354
+ writer,
8355
+ scopeRegistrationMessages.initNextSteps(
8356
+ `--connector ${manifest.connector_id ?? CONNECTOR_PLACEHOLDER}`
8357
+ )
8358
+ );
8359
+ }
8080
8360
  }
8081
- function registerInit(program, writer, cwd, createClient, description2 = "Project\u3092\u660E\u793A\u9078\u629E\u307E\u305F\u306F\u4F5C\u6210\u3057\u3001\u5B89\u5168\u306Alocal manifest\u3078bind\u3057\u307E\u3059", runtime = void 0, messages = DEFAULT_INIT_MESSAGES) {
8361
+ function registerInit(program, writer, cwd, createClient, description2 = "Project\u3092\u660E\u793A\u9078\u629E\u307E\u305F\u306F\u4F5C\u6210\u3057\u3001\u5B89\u5168\u306Alocal manifest\u3078bind\u3057\u307E\u3059", runtime = void 0, messages = DEFAULT_INIT_MESSAGES, scopeRegistrationMessages = DEFAULT_SCOPE_REGISTRATION_MESSAGES) {
8082
8362
  const commandRuntime = runtime ?? createInitCommandRuntime(createClient, messages);
8083
8363
  program.command("init").description(description2).option("--project <project-uuid>", messages.projectOption).option("--create", messages.createOption).option("--name <name>", messages.nameOption).option("--slug <slug>", messages.slugOption).option("--contract <root-file>", messages.contractOption).option("--template <export-file>", "External SaaS template export artifact").option("--openapi <file>", messages.openApiOption).option("--base-url <https-url>", messages.openApiBaseUrlOption).option("--service-name <name>", messages.openApiServiceNameOption).option(
8084
8364
  "--auth-mode <mode>",
@@ -8093,7 +8373,14 @@ function registerInit(program, writer, cwd, createClient, description2 = "Projec
8093
8373
  "Create the template connector through the existing Admin API policy boundary",
8094
8374
  false
8095
8375
  ).option("--profile <name>", messages.profileOption, DEFAULT_PROFILE_NAME).option("--yes", messages.yesOption, false).action(async (options) => {
8096
- await runInitCommand(options, writer, cwd(), commandRuntime, messages);
8376
+ await runInitCommand(
8377
+ options,
8378
+ writer,
8379
+ cwd(),
8380
+ commandRuntime,
8381
+ messages,
8382
+ scopeRegistrationMessages
8383
+ );
8097
8384
  });
8098
8385
  }
8099
8386
 
@@ -8116,1160 +8403,1617 @@ function registerLogs(program, writer, locale = import_localization8.DEFAULT_LOC
8116
8403
  }
8117
8404
 
8118
8405
  // src/commands/oauth.ts
8406
+ var import_node_crypto13 = require("crypto");
8119
8407
  var import_node_fs11 = require("fs");
8408
+ var import_localization10 = require("@andpipes/localization");
8409
+ var import_tool_contract10 = require("@andpipes/tool-contract");
8410
+
8411
+ // src/commands/publish.ts
8412
+ var import_node_crypto12 = require("crypto");
8120
8413
  var import_localization9 = require("@andpipes/localization");
8121
- function isUrl(value) {
8122
- if (typeof value !== "string") {
8123
- return false;
8414
+ var import_tool_contract9 = require("@andpipes/tool-contract");
8415
+ 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;
8416
+ var SAFE_AP_CODE_RE2 = /^AP_[A-Z0-9_]{1,64}$/u;
8417
+ var PUBLICATION_RESPONSE_MAX_BYTES = 96 * 1024;
8418
+ var INITIAL_APPLY_MAX_ATTEMPTS = 3;
8419
+ var DEFAULT_PUBLISH_MESSAGES = import_localization9.CLI_MESSAGES.ja.publish;
8420
+ var DEFAULT_SCOPE_REGISTRATION_MESSAGES2 = import_localization9.OAUTH_SCOPE_REGISTRATION_MESSAGES.ja.cli;
8421
+ var DEFAULT_SCHEMA_REVIEW_MESSAGES = import_localization9.PUBLICATION_SCHEMA_REVIEW_CLI_MESSAGES.ja;
8422
+ var REVIEW_PROFILE_REQUEST = Object.freeze({
8423
+ reviewProfile: CLI_PUBLICATION_REVIEW_PROFILE
8424
+ });
8425
+ var PLAN_KEYS = [
8426
+ "requestId",
8427
+ "environment",
8428
+ "connectorId",
8429
+ "connectorRevision",
8430
+ "connectorCommitment",
8431
+ "policyCommitment",
8432
+ "candidateCommitment",
8433
+ "baseCommitment",
8434
+ "planCommitment",
8435
+ "tools",
8436
+ "retainedTools",
8437
+ "warnings",
8438
+ "applyAllowed",
8439
+ "blockedReasons"
8440
+ ];
8441
+ var APPLY_RESULT_KEYS = ["requestId", "publicationId", "state", "tools", "warnings"];
8442
+ var STATUS_KEYS = [
8443
+ "requestId",
8444
+ "publicationId",
8445
+ "durableState",
8446
+ "effectiveState",
8447
+ "expiresAt",
8448
+ "confirmation",
8449
+ "result"
8450
+ ];
8451
+ var BLOCKED_REASONS = /* @__PURE__ */ new Set([
8452
+ "project_not_active",
8453
+ "connector_not_active",
8454
+ "connector_mismatch",
8455
+ "tool_deprecated",
8456
+ "tool_plan_limit_exceeded",
8457
+ "production_capability_required",
8458
+ "write_tool_mode_not_confirmed",
8459
+ "production_oauth_broker_required",
8460
+ "oauth_scope_registry_missing",
8461
+ "oauth_scope_registry_risk_insufficient",
8462
+ "publish_gate_failed",
8463
+ "opaque_change",
8464
+ "retention_policy_blocked",
8465
+ "descriptor_name_conflict"
8466
+ ]);
8467
+ var TOOL_BLOCKED_REASONS = [
8468
+ "connector_mismatch",
8469
+ "opaque_change",
8470
+ "publish_gate_failed",
8471
+ "tool_deprecated"
8472
+ ];
8473
+ var DURABLE_STATES = /* @__PURE__ */ new Set(["pending", "approved", "rejected", "expired", "consumed"]);
8474
+ var EFFECTIVE_STATES = /* @__PURE__ */ new Set([
8475
+ "pending",
8476
+ "approved",
8477
+ "rejected",
8478
+ "expired",
8479
+ "consumed",
8480
+ "stale"
8481
+ ]);
8482
+ var DEFINITIVE_APPLY_ERROR_CODES = /* @__PURE__ */ new Set([
8483
+ "AP_AUTH_REQUIRED",
8484
+ "AP_CONFIRMATION_EXPIRED",
8485
+ "AP_CONFLICT",
8486
+ "AP_FORBIDDEN",
8487
+ "AP_IDEMPOTENCY_KEY_CONFLICT",
8488
+ "AP_INPUT_INVALID",
8489
+ "AP_INVALID_SCOPE",
8490
+ "AP_NOT_FOUND",
8491
+ "AP_POLICY_DENIED",
8492
+ "AP_UNAUTHORIZED"
8493
+ ]);
8494
+ var PublishCommandError = class extends Error {
8495
+ constructor(code, reason, message, status) {
8496
+ super(message);
8497
+ this.code = code;
8498
+ this.reason = reason;
8499
+ this.status = status;
8500
+ this.name = "PublishCommandError";
8501
+ }
8502
+ code;
8503
+ reason;
8504
+ status;
8505
+ };
8506
+ function createPublishCommandRuntime(createClient) {
8507
+ return {
8508
+ createClient,
8509
+ loadProject: loadDevProject,
8510
+ randomUuid: () => (0, import_node_crypto12.randomUUID)(),
8511
+ monotonicNow: () => Number(process.hrtime.bigint() / 1000000n),
8512
+ wallNow: () => Date.now(),
8513
+ sleep: (milliseconds) => new Promise((resolve7) => setTimeout(resolve7, milliseconds))
8514
+ };
8515
+ }
8516
+ function canonicalUuidOption(value, option, messages = DEFAULT_PUBLISH_MESSAGES) {
8517
+ const canonical = value.toLowerCase();
8518
+ if (!UUID_RE6.test(canonical)) {
8519
+ throw new UsageError(messages.invalidOption(option, "a canonical RFC 4122 UUID"));
8520
+ }
8521
+ return canonical;
8522
+ }
8523
+ function normalizePublishOptions(options, messages = DEFAULT_PUBLISH_MESSAGES) {
8524
+ if (options.dryRun === true && options.apply === true) {
8525
+ throw new UsageError(messages.incompatibleOptions("--dry-run / --apply"));
8526
+ }
8527
+ if (options.yes === true && options.apply !== true) {
8528
+ throw new UsageError(messages.optionRequires("--yes", "--apply"));
8529
+ }
8530
+ if (options.apply === true && options.yes !== true) {
8531
+ throw new ConfirmationRequiredError(
8532
+ "andpipe publish --apply",
8533
+ messages.applyConfirmationRequired
8534
+ );
8124
8535
  }
8536
+ const projectId = options.project === void 0 ? void 0 : canonicalUuidOption(options.project, "--project", messages);
8537
+ return {
8538
+ mode: options.apply === true ? "apply" : "dry-run",
8539
+ ...options.connector === void 0 ? {} : { connectorId: canonicalUuidOption(options.connector, "--connector", messages) },
8540
+ profile: options.profile ?? DEFAULT_PROFILE_NAME,
8541
+ ...projectId === void 0 ? {} : { projectId }
8542
+ };
8543
+ }
8544
+ function asRecord4(value) {
8545
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
8546
+ }
8547
+ function hasExactKeys3(record, keys) {
8548
+ const actual = Object.keys(record);
8549
+ return actual.length === keys.length && actual.every((key) => keys.includes(key));
8550
+ }
8551
+ function responseInvalid(reason, messages) {
8552
+ return new PublishCommandError("AP_RESPONSE_INVALID", reason, messages.failure(reason));
8553
+ }
8554
+ function assertCanonicalResponseSize(value, reason, messages, maxBytes = PUBLICATION_RESPONSE_MAX_BYTES) {
8125
8555
  try {
8126
- const u = new URL(value);
8127
- return u.protocol === "http:" || u.protocol === "https:";
8556
+ (0, import_tool_contract9.assertCanonicalPublicationSize)(value, maxBytes);
8128
8557
  } catch {
8129
- return false;
8558
+ throw responseInvalid(reason, messages);
8130
8559
  }
8131
8560
  }
8132
- function field(meta, snake, camel) {
8133
- return snake in meta ? meta[snake] : meta[camel];
8561
+ function isCanonicalUuid(value) {
8562
+ return typeof value === "string" && UUID_RE6.test(value);
8134
8563
  }
8135
- function validateOAuthMetadata(meta, locale = import_localization9.DEFAULT_LOCALE) {
8136
- const messages = import_localization9.CLI_MESSAGES[locale].oauth;
8137
- const results = [];
8138
- if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
8139
- return {
8140
- ok: false,
8141
- results: [
8142
- {
8143
- id: "metadata",
8144
- label: "metadata",
8145
- status: "fail",
8146
- detail: messages.metadataNotObject
8147
- }
8148
- ]
8149
- };
8564
+ function isCommitment(value) {
8565
+ return typeof value === "string" && import_tool_contract9.PUBLICATION_SHA256_COMMITMENT_RE.test(value);
8566
+ }
8567
+ function isCanonicalTimestamp(value) {
8568
+ if (typeof value !== "string" || value.length > 64) return false;
8569
+ const milliseconds = Date.parse(value);
8570
+ return Number.isFinite(milliseconds) && new Date(milliseconds).toISOString() === value;
8571
+ }
8572
+ function isStrictlySorted(values) {
8573
+ return values.every(
8574
+ (value, index) => index === 0 || (0, import_tool_contract9.comparePublicationUnicodeCodePoints)(values[index - 1], value) < 0
8575
+ );
8576
+ }
8577
+ function parseWarnings(value, messages) {
8578
+ try {
8579
+ return (0, import_tool_contract9.parsePublicationWarningsDto)(value);
8580
+ } catch {
8581
+ throw responseInvalid("publication_warnings_invalid", messages);
8150
8582
  }
8151
- const m = meta;
8152
- const urlFields = [
8153
- ["issuer", "issuer", "issuer"],
8154
- ["authorization_endpoint", "authorization_endpoint", "authorizationEndpoint"],
8155
- ["token_endpoint", "token_endpoint", "tokenEndpoint"],
8156
- ["jwks_uri", "jwks_uri", "jwksUri"]
8157
- ];
8158
- for (const [id, snake, camel] of urlFields) {
8159
- const value = field(m, snake, camel);
8160
- const ok = isUrl(value);
8161
- results.push({
8162
- id,
8163
- label: id,
8164
- status: ok ? "pass" : "fail",
8165
- detail: ok ? messages.urlOk : messages.invalidUrl(id)
8583
+ }
8584
+ function schemaReviewFailure(code, reason, text, status) {
8585
+ return new PublishCommandError(code, reason, `${text} (${reason})`, status);
8586
+ }
8587
+ function negotiateReviewProfile(response, messages, schemaReviewMessages) {
8588
+ const envelope = asRecord4(response);
8589
+ if (!envelope || !hasExactKeys3(envelope, ["body", "reviewProfileHeader"]) || envelope.reviewProfileHeader !== null && typeof envelope.reviewProfileHeader !== "string") {
8590
+ throw responseInvalid("publication_plan_invalid", messages);
8591
+ }
8592
+ const header = envelope.reviewProfileHeader;
8593
+ if (header !== null && header !== "1" && header !== "2") {
8594
+ throw schemaReviewFailure(
8595
+ "AP_RESPONSE_INVALID",
8596
+ "publication_review_profile_header_invalid",
8597
+ schemaReviewMessages.reviewProfileHeaderInvalid
8598
+ );
8599
+ }
8600
+ const body = asRecord4(envelope.body);
8601
+ const bodyDeclaresProfile = body !== null && Object.hasOwn(body, "reviewProfile");
8602
+ const profile = header === "2" ? 2 : 1;
8603
+ if (profile === 2 ? !bodyDeclaresProfile || body?.reviewProfile !== 2 : bodyDeclaresProfile) {
8604
+ throw schemaReviewFailure(
8605
+ "AP_CONFLICT",
8606
+ "publication_review_profile_mismatch",
8607
+ schemaReviewMessages.reviewProfileMismatch
8608
+ );
8609
+ }
8610
+ return {
8611
+ session: header === null ? { kind: "legacy", profile: 1 } : { kind: "negotiated", profile },
8612
+ body: envelope.body
8613
+ };
8614
+ }
8615
+ function parsePlan(value, connectorId, candidateCommitment, expectedToolNames, profile, messages) {
8616
+ assertCanonicalResponseSize(value, "publication_plan_too_large", messages);
8617
+ const plan = asRecord4(value);
8618
+ 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(
8619
+ (reason) => typeof reason === "string" && BLOCKED_REASONS.has(reason)
8620
+ ) || !isStrictlySorted(plan.blockedReasons) || plan.applyAllowed !== (plan.blockedReasons.length === 0)) {
8621
+ throw responseInvalid("publication_plan_invalid", messages);
8622
+ }
8623
+ const blockedReasons = plan.blockedReasons;
8624
+ let safeDiff;
8625
+ try {
8626
+ safeDiff = (0, import_tool_contract9.parsePublicationSafeDiffDto)({
8627
+ ...profile === 2 ? { reviewProfile: 2 } : {},
8628
+ tools: plan.tools,
8629
+ retainedTools: plan.retainedTools,
8630
+ warnings: plan.warnings
8166
8631
  });
8632
+ } catch {
8633
+ throw responseInvalid("publication_safe_diff_invalid", messages);
8167
8634
  }
8168
- const responseTypes = field(m, "response_types_supported", "responseTypesSupported");
8169
- results.push({
8170
- id: "response_types_supported",
8171
- label: "response_types_supported",
8172
- status: Array.isArray(responseTypes) && responseTypes.length > 0 ? "pass" : "fail",
8173
- detail: Array.isArray(responseTypes) ? messages.present : messages.arrayMissing
8174
- });
8175
- const scopes = field(m, "scopes_supported", "scopesSupported");
8176
- results.push({
8177
- id: "scopes_supported",
8178
- label: "scopes_supported",
8179
- // 推奨項目。欠落は致命ではないため pending 扱いで明示する。
8180
- status: Array.isArray(scopes) && scopes.length > 0 ? "pass" : "pending",
8181
- detail: Array.isArray(scopes) ? messages.present : messages.scopesMissing
8635
+ if (safeDiff.reviewProfile === 2 !== (profile === 2)) {
8636
+ throw responseInvalid("publication_safe_diff_invalid", messages);
8637
+ }
8638
+ const tools = safeDiff.tools;
8639
+ const toolNames = tools.map((tool) => tool.toolName);
8640
+ if (!isStrictlySorted(toolNames) || JSON.stringify(toolNames) !== JSON.stringify(expectedToolNames)) {
8641
+ throw responseInvalid("publication_plan_tools_order_invalid", messages);
8642
+ }
8643
+ const warnings = safeDiff.warnings;
8644
+ const expectedPlanCommitment = (0, import_tool_contract9.publicationCommitment)(profile === 2 ? "planV2" : "plan", {
8645
+ candidateCommitment,
8646
+ baseCommitment: plan.baseCommitment,
8647
+ connectorId,
8648
+ connectorRevision: plan.connectorRevision,
8649
+ connectorCommitment: plan.connectorCommitment,
8650
+ policyCommitment: plan.policyCommitment,
8651
+ environment: "production",
8652
+ safeDiff
8182
8653
  });
8183
- return { ok: results.every((r) => r.status !== "fail"), results };
8184
- }
8185
- function buildInitTemplate(provider) {
8654
+ if (plan.planCommitment !== expectedPlanCommitment) {
8655
+ throw new PublishCommandError(
8656
+ "AP_CONFLICT",
8657
+ "publication_plan_commitment_mismatch",
8658
+ messages.failure("publication_plan_commitment_mismatch")
8659
+ );
8660
+ }
8661
+ const toolBlockedReasons = new Set(tools.flatMap((tool) => tool.blockedReasons));
8662
+ if (tools.some((tool) => !tool.gate.ok) && plan.applyAllowed || tools.some((tool) => tool.opaqueChanged) && (plan.applyAllowed || !blockedReasons.includes("opaque_change")) || TOOL_BLOCKED_REASONS.some(
8663
+ (reason) => (
8664
+ // connector_mismatchはtool単位(既存toolの別connector束縛)に加え、candidateの
8665
+ // upstream.auth.modeとconnector方式の不一致としてtop-levelだけにも出る (#456 / #724)。
8666
+ reason === "connector_mismatch" ? toolBlockedReasons.has(reason) && !blockedReasons.includes(reason) : blockedReasons.includes(reason) !== toolBlockedReasons.has(reason)
8667
+ )
8668
+ )) {
8669
+ throw responseInvalid("publication_plan_gate_inconsistent", messages);
8670
+ }
8186
8671
  return {
8187
- provider,
8188
- issuer: "https://auth.example.com",
8189
- authorizationEndpoint: "https://auth.example.com/oauth/authorize",
8190
- tokenEndpoint: "https://auth.example.com/oauth/token",
8191
- jwksUri: "https://auth.example.com/.well-known/jwks.json",
8192
- clientId: "<client id>",
8193
- // secret は config に直書きせず env 参照にする (No secret in repo / stdout)。
8194
- clientSecretEnv: "ANDPIPE_OAUTH_CLIENT_SECRET",
8195
- redirectUri: "https://<your-andpipe-gateway>/oauth/callback",
8196
- scopes: ["openid", "profile"]
8672
+ ...profile === 2 ? { reviewProfile: 2 } : {},
8673
+ requestId: plan.requestId,
8674
+ environment: "production",
8675
+ connectorId,
8676
+ connectorRevision: plan.connectorRevision,
8677
+ connectorCommitment: plan.connectorCommitment,
8678
+ policyCommitment: plan.policyCommitment,
8679
+ candidateCommitment,
8680
+ baseCommitment: plan.baseCommitment,
8681
+ planCommitment: plan.planCommitment,
8682
+ tools,
8683
+ retainedTools: safeDiff.retainedTools,
8684
+ warnings,
8685
+ applyAllowed: plan.applyAllowed,
8686
+ blockedReasons
8197
8687
  };
8198
8688
  }
8199
- function upstreamOAuthWizardUrl(profile, projectId, connectorId) {
8200
- const record = getProfile(profile);
8201
- if (!record)
8202
- throw new UsageError(`\u8A8D\u8A3Cprofile ${profile} \u304C\u3042\u308A\u307E\u305B\u3093\u3002andpipe login\u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044`);
8203
- const url = new URL(`/projects/${projectId}/oauth`, new URL(record.verificationUriBase).origin);
8204
- url.searchParams.set("connector", connectorId);
8205
- return url.toString();
8689
+ function sameWarnings(left, right) {
8690
+ return JSON.stringify(left) === JSON.stringify(right);
8206
8691
  }
8207
- async function loadOAuthMetadata(opts, locale) {
8208
- const messages = import_localization9.CLI_MESSAGES[locale];
8209
- if (opts.file && opts.issuer) {
8210
- throw new UsageError("--file \u3068 --issuer \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");
8692
+ function parseToolResults(value, messages) {
8693
+ if (!Array.isArray(value)) {
8694
+ throw responseInvalid("publication_result_tools_invalid", messages);
8211
8695
  }
8212
- if (opts.issuer) {
8213
- return fetchOAuthMetadata(opts.issuer);
8696
+ const tools = value.map((candidate) => {
8697
+ const tool = asRecord4(candidate);
8698
+ 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) {
8699
+ throw responseInvalid("publication_result_tool_invalid", messages);
8700
+ }
8701
+ const operation = tool.operation;
8702
+ return {
8703
+ toolName: tool.toolName,
8704
+ operation,
8705
+ toolId: tool.toolId,
8706
+ versionId: tool.versionId,
8707
+ version: tool.version
8708
+ };
8709
+ });
8710
+ if (!isStrictlySorted(tools.map((tool) => tool.toolName))) {
8711
+ throw responseInvalid("publication_result_tools_order_invalid", messages);
8214
8712
  }
8215
- if (!opts.file) {
8216
- throw new UsageError(messages.oauth.fileRequired);
8713
+ return tools;
8714
+ }
8715
+ function parsePublicationResult(value, plan, messages, expectedPublicationId) {
8716
+ assertCanonicalResponseSize(value, "publication_apply_result_too_large", messages);
8717
+ const result = asRecord4(value);
8718
+ if (!result || !hasExactKeys3(result, APPLY_RESULT_KEYS) || !isCanonicalUuid(result.requestId) || result.state !== "noop" && result.state !== "consumed") {
8719
+ throw responseInvalid("publication_apply_result_invalid", messages);
8217
8720
  }
8218
- try {
8219
- return JSON.parse((0, import_node_fs11.readFileSync)(opts.file, "utf8"));
8220
- } catch (error) {
8221
- throw new UsageError(messages.oauth.metadataReadFailed(error.message));
8721
+ const warnings = parseWarnings(result.warnings, messages);
8722
+ if (!sameWarnings(warnings, plan.warnings)) {
8723
+ throw responseInvalid("publication_apply_warning_mismatch", messages);
8724
+ }
8725
+ const tools = parseToolResults(result.tools, messages);
8726
+ const changedToolNames = plan.tools.filter((tool) => tool.changed).map((tool) => tool.toolName);
8727
+ if (result.state === "noop") {
8728
+ if (result.publicationId !== null || tools.length !== 0 || changedToolNames.length !== 0) {
8729
+ throw responseInvalid("publication_noop_invalid", messages);
8730
+ }
8731
+ return {
8732
+ requestId: result.requestId,
8733
+ publicationId: null,
8734
+ state: "noop",
8735
+ tools,
8736
+ warnings
8737
+ };
8738
+ }
8739
+ if (!isCanonicalUuid(result.publicationId) || expectedPublicationId !== void 0 && result.publicationId !== expectedPublicationId || changedToolNames.length === 0 || JSON.stringify(tools.map((tool) => tool.toolName)) !== JSON.stringify(changedToolNames) || tools.some(
8740
+ (tool) => plan.tools.find((planned) => planned.toolName === tool.toolName)?.operation !== tool.operation
8741
+ )) {
8742
+ throw responseInvalid("publication_consumed_result_invalid", messages);
8222
8743
  }
8744
+ return {
8745
+ requestId: result.requestId,
8746
+ publicationId: result.publicationId,
8747
+ state: "consumed",
8748
+ tools,
8749
+ warnings
8750
+ };
8223
8751
  }
8224
- async function runOAuthMetadataValidate(opts, writer, locale) {
8225
- const messages = import_localization9.CLI_MESSAGES[locale];
8226
- const parsed = await loadOAuthMetadata(opts, locale);
8227
- const report = validateOAuthMetadata(parsed, locale);
8228
- json(writer, report.results);
8229
- if (!report.ok) {
8230
- process.exitCode = 1;
8231
- info(writer, messages.oauth.metadataFailed);
8232
- } else {
8233
- info(writer, messages.oauth.metadataOk);
8752
+ function parseConfirmation(value, messages) {
8753
+ if (value === null) return null;
8754
+ const confirmation = asRecord4(value);
8755
+ 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) {
8756
+ throw responseInvalid("publication_confirmation_invalid", messages);
8234
8757
  }
8758
+ return {
8759
+ confirmationId: confirmation.confirmationId,
8760
+ signature: confirmation.signature,
8761
+ confirmed: true
8762
+ };
8235
8763
  }
8236
- function registerOauth(program, writer, locale = import_localization9.DEFAULT_LOCALE, dependencies = {}) {
8237
- const messages = import_localization9.CLI_MESSAGES[locale];
8238
- const oauth = program.command("oauth").description(messages.oauth.commandDescription);
8239
- oauth.command("init").description(messages.oauth.initDescription).requiredOption("--provider <name>", messages.oauth.providerOption).action((opts) => {
8240
- info(writer, messages.oauth.templateHeading(opts.provider));
8241
- json(writer, buildInitTemplate(opts.provider));
8242
- info(writer, messages.oauth.clientSecretEnvNotice);
8243
- });
8244
- oauth.command("validate").description(messages.oauth.validateDescription).option("--file <path>", messages.common.metadataFileOption).option("--issuer <url>", messages.common.issuerOption).option("--project <project>", messages.common.projectOption).option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).action(async (opts) => {
8245
- if (opts.project) {
8246
- if (opts.file || opts.issuer) {
8247
- throw new UsageError("--project \u306F --file / --issuer \u3068\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");
8248
- }
8249
- const projectId = assertProjectId(opts.project);
8250
- const result = await createAdminApiClient({ profile: opts.profile }).getOAuthSetup(
8251
- projectId
8252
- );
8253
- json(writer, result);
8254
- if (result.metadata.status !== "valid" || result.alignment.issues.length > 0) {
8255
- process.exitCode = 1;
8256
- }
8257
- return;
8258
- }
8259
- await runOAuthMetadataValidate(opts, writer, locale);
8260
- });
8261
- const scopes = oauth.command("scopes").description(messages.oauth.scopesDescription);
8262
- scopes.command("sync").description(messages.oauth.scopesSyncDescription).requiredOption("--project <project>", messages.common.projectOption).option("--apply", "preview\u7D50\u679C\u3092production\u3078\u53CD\u6620\u3059\u308B", false).option("--yes", messages.domain.yesOption, false).option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).action(async (opts) => {
8263
- const operation = "andpipe oauth scopes sync";
8264
- if (opts.apply && !opts.yes) {
8265
- throw new ConfirmationRequiredError(
8266
- operation,
8267
- messages.common.confirmationRequiredMessage(operation)
8268
- );
8269
- }
8270
- if (!opts.apply && opts.yes) {
8271
- throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8272
- }
8273
- const projectId = assertProjectId(opts.project);
8274
- const result = await createAdminApiClient({ profile: opts.profile }).syncOAuthScopes({
8275
- projectId,
8276
- apply: opts.apply
8277
- });
8278
- json(writer, result);
8279
- });
8280
- const clients = oauth.command("clients").description("OAuth client\u306Escope\u5272\u5F53\u3092\u7BA1\u7406\u3059\u308B");
8281
- clients.command("map-scopes").description("\u9078\u629E\u3057\u305Fproject client\u3078\u5FC5\u8981scope\u3092preview\u307E\u305F\u306F\u660E\u793A\u9069\u7528\u3059\u308B").requiredOption("--project <project>", messages.common.projectOption).requiredOption("--client <client-registry-uuid>", "oauth-setup\u306B\u8868\u793A\u3055\u308C\u305Fclient registry ID").option("--apply", "preview\u7D50\u679C\u3092\u9078\u629Eclient\u3078\u53CD\u6620\u3059\u308B", false).option("--yes", messages.domain.yesOption, false).option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).action(
8282
- async (opts) => {
8283
- const operation = "andpipe oauth clients map-scopes";
8284
- if (opts.apply && !opts.yes) {
8285
- throw new ConfirmationRequiredError(
8286
- operation,
8287
- messages.common.confirmationRequiredMessage(operation)
8288
- );
8289
- }
8290
- if (!opts.apply && opts.yes) {
8291
- throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8292
- }
8293
- const client = createAdminApiClient({ profile: opts.profile });
8294
- const preview = await client.mapOAuthClientScopes({
8295
- projectId: assertProjectId(opts.project),
8296
- clientRegistryId: opts.client,
8297
- apply: false
8298
- });
8299
- json(writer, preview);
8300
- if (!opts.apply) return;
8301
- const applied = await client.mapOAuthClientScopes({
8302
- projectId: assertProjectId(opts.project),
8303
- clientRegistryId: opts.client,
8304
- apply: true,
8305
- requiredScopesCommitment: preview.requiredScopesCommitment,
8306
- baseClientGrantCommitment: preview.baseClientGrantCommitment,
8307
- candidateClientGrantCommitment: preview.candidateClientGrantCommitment,
8308
- planCommitment: preview.planCommitment
8309
- });
8310
- json(writer, applied);
8311
- }
8312
- );
8313
- const metadata = oauth.command("metadata").description(messages.oauth.metadataDescription);
8314
- metadata.command("validate").description(messages.oauth.validateDescription).option("--file <path>", messages.common.metadataFileOption).option("--issuer <url>", messages.common.issuerOption).action(async (opts) => {
8315
- await runOAuthMetadataValidate(opts, writer, locale);
8316
- });
8317
- const connect = oauth.command("connect").description(
8318
- locale === "ja" ? "\u9867\u5BA2SaaS\u306EOAuth account linking\u3092Web Admin\u3068\u540C\u3058\u72B6\u614B\u3067\u8A2D\u5B9A" : "Configure customer SaaS OAuth account linking with shared Web Admin state"
8319
- );
8320
- connect.command("status").description(
8321
- locale === "ja" ? "\u63A5\u7D9A\u72B6\u614B\u3068\u6B21\u306E\u64CD\u4F5C\u3092\u8868\u793A" : "Show connection state and next action"
8322
- ).requiredOption("--project <project>", messages.common.projectOption).requiredOption("--connector <connector>", "\u63A5\u7D9A\u5BFE\u8C61connector UUID").option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).action(async (opts) => {
8323
- const state = await createAdminApiClient({
8324
- profile: opts.profile
8325
- }).getUpstreamOAuthConnectionState(assertProjectId(opts.project), opts.connector);
8326
- json(writer, state);
8327
- if (!state.allGreen) process.exitCode = 1;
8328
- });
8329
- connect.command("open").description(
8330
- locale === "ja" ? "\u540C\u3058\u63A5\u7D9A\u72B6\u614B\u3092\u78BA\u8A8D\u3057\u3066Web Admin\u30A6\u30A3\u30B6\u30FC\u30C9\u3092\u958B\u304F" : "Check shared state and open the Web Admin wizard"
8331
- ).requiredOption("--project <project>", messages.common.projectOption).requiredOption("--connector <connector>", "\u63A5\u7D9A\u5BFE\u8C61connector UUID").option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).option(
8332
- "--no-browser",
8333
- locale === "ja" ? "\u65E2\u5B9A\u30D6\u30E9\u30A6\u30B6\u3092\u958B\u304B\u305AURL\u3060\u3051\u8868\u793A" : "Print the URL without opening a browser"
8334
- ).action(
8335
- async (opts) => {
8336
- const projectId = assertProjectId(opts.project);
8337
- const state = await createAdminApiClient({
8338
- profile: opts.profile
8339
- }).getUpstreamOAuthConnectionState(projectId, opts.connector);
8340
- json(writer, state);
8341
- const url = upstreamOAuthWizardUrl(opts.profile, projectId, opts.connector);
8342
- info(
8343
- writer,
8344
- locale === "ja" ? `Web Admin\u3067\u7D9A\u3051\u3066\u304F\u3060\u3055\u3044: ${url}` : `Continue in Web Admin: ${url}`
8345
- );
8346
- if (opts.browser) {
8347
- try {
8348
- (dependencies.openBrowser ?? openBrowser)(url);
8349
- } catch {
8350
- }
8351
- }
8352
- }
8353
- );
8354
- oauth.command("test-login").description(messages.oauth.testLoginDescription).requiredOption("--project <project>", messages.common.projectOption).requiredOption("--client <client-registry-uuid>", "\u691C\u67FB\u5BFE\u8C61\u306Eproject OAuth client registry ID").option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).action(async (opts) => {
8355
- const projectId = assertProjectId(opts.project);
8356
- const result = await createAdminApiClient({ profile: opts.profile }).testOAuthLogin(
8357
- projectId,
8358
- opts.client
8359
- );
8360
- json(writer, result);
8361
- if (result.status === "blocked") process.exitCode = 1;
8362
- });
8363
- }
8364
-
8365
- // src/commands/openapi.ts
8366
- var import_node_crypto12 = require("crypto");
8367
- var import_node_path12 = require("path");
8368
- var import_tool_contract9 = require("@andpipes/tool-contract");
8369
- function createOpenApiImportRuntime(createClient = (profile) => createAdminApiClient({ profile })) {
8370
- return { createClient, idempotencyKey: import_node_crypto12.randomUUID };
8371
- }
8372
- function normalizedOptions(options) {
8373
- if (!options.file || !options.project || !options.connector) {
8374
- throw new UsageError("--file\u3001--project\u3001--connector \u306F\u5FC5\u9808\u3067\u3059");
8375
- }
8376
- if (options.format !== void 0 && options.format !== "json" && options.format !== "yaml") {
8377
- throw new UsageError("--format \u306F json \u307E\u305F\u306F yaml \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8378
- }
8379
- if (options.serviceName !== void 0 && !/^[A-Za-z0-9_]{1,48}$/.test(options.serviceName)) {
8380
- throw new UsageError("--service-name \u306F\u82F1\u6570\u5B57\u3068 underscore \u306E1..48\u6587\u5B57\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8381
- }
8382
- const apply = options.apply === true;
8383
- const yes = options.yes === true;
8384
- if (yes && !apply) {
8385
- throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8386
- }
8387
- if (options.idempotencyKey !== void 0 && !apply) {
8388
- throw new UsageError("--idempotency-key \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8764
+ function parseStatus(value, publicationId, plan, messages) {
8765
+ assertCanonicalResponseSize(value, "publication_status_too_large", messages);
8766
+ const status = asRecord4(value);
8767
+ if (!status || !hasExactKeys3(status, STATUS_KEYS) || !isCanonicalUuid(status.requestId) || status.publicationId !== publicationId || typeof status.durableState !== "string" || !DURABLE_STATES.has(status.durableState) || typeof status.effectiveState !== "string" || !EFFECTIVE_STATES.has(status.effectiveState) || !isCanonicalTimestamp(status.expiresAt)) {
8768
+ throw responseInvalid("publication_status_invalid", messages);
8389
8769
  }
8390
- if (!apply && options.planCommitment !== void 0) {
8391
- throw new UsageError("--plan-commitment \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8770
+ const confirmation = parseConfirmation(status.confirmation, messages);
8771
+ const result = status.result === null ? null : parsePublicationResult(status.result, plan, messages, publicationId);
8772
+ const durableState = status.durableState;
8773
+ const effectiveState = status.effectiveState;
8774
+ const isPending = durableState === "pending";
8775
+ const isApproved = durableState === "approved";
8776
+ const isTerminal = durableState === "rejected" || durableState === "expired" || durableState === "consumed";
8777
+ if (isPending && effectiveState !== "pending" && effectiveState !== "stale" || isApproved && effectiveState !== "approved" && effectiveState !== "stale" || isTerminal && effectiveState !== durableState || isPending && confirmation !== null || isApproved && effectiveState === "approved" && confirmation === null || isApproved && effectiveState === "stale" && confirmation !== null || isTerminal && confirmation !== null || (durableState === "consumed" ? result === null : result !== null)) {
8778
+ throw responseInvalid("publication_status_inconsistent", messages);
8392
8779
  }
8393
8780
  return {
8394
- file: options.file,
8395
- project: assertProjectId(options.project),
8396
- connectorId: assertProjectId(options.connector),
8397
- profile: options.profile ?? DEFAULT_PROFILE_NAME,
8398
- ...options.format !== void 0 ? { format: options.format } : {},
8399
- ...options.baseUrl !== void 0 ? { baseUrl: options.baseUrl } : {},
8400
- ...options.serviceName !== void 0 ? { serviceName: options.serviceName } : {},
8401
- apply,
8402
- yes,
8403
- ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {},
8404
- ...options.planCommitment !== void 0 ? { planCommitment: options.planCommitment } : {},
8405
- ...options.authMode !== void 0 ? { upstreamAuthMode: parseAuthModeOption(options.authMode) } : {},
8406
- sideEffectFree: parseSideEffectFreeOptions(options.sideEffectFree)
8781
+ requestId: status.requestId,
8782
+ publicationId,
8783
+ durableState,
8784
+ effectiveState,
8785
+ expiresAt: status.expiresAt,
8786
+ confirmation,
8787
+ result
8407
8788
  };
8408
8789
  }
8409
- function rethrowWithAuthModeGuidance(error) {
8410
- if (error instanceof AdminApiClientError && error.openApiAuthModeMismatch) {
8411
- throw new UsageError(authModeMismatchGuidance(error.openApiAuthModeMismatch));
8412
- }
8413
- throw error;
8790
+ function typedCode2(error) {
8791
+ if (error === null || typeof error !== "object") return void 0;
8792
+ const code = error.code;
8793
+ return typeof code === "string" && SAFE_AP_CODE_RE2.test(code) ? code : void 0;
8414
8794
  }
8415
- async function runOpenApiImportCommand(options, writer, cwd, runtime = createOpenApiImportRuntime()) {
8416
- const normalized = normalizedOptions(options);
8417
- if (normalized.apply && !normalized.yes) {
8418
- throw new ConfirmationRequiredError(
8419
- "andpipe openapi import --apply",
8420
- "draft\u4F5C\u6210\u306B\u306F --apply --yes \u306E\u4E21\u65B9\u304C\u5FC5\u8981\u3067\u3059\u3002preview\u7D50\u679C\u3092\u78BA\u8A8D\u3057\u3066\u304B\u3089\u518D\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044"
8795
+ function typedStatus2(error) {
8796
+ if (error === null || typeof error !== "object") return void 0;
8797
+ const status = error.status;
8798
+ return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599 ? status : void 0;
8799
+ }
8800
+ function typedPublicationReason(error, code) {
8801
+ if (error === null || typeof error !== "object") return void 0;
8802
+ const status = typedStatus2(error);
8803
+ if (status === void 0 || status < 400 || status > 499) return void 0;
8804
+ const reason = error.publicationReason;
8805
+ return isPublicationErrorReasonFor(code, reason) ? reason : void 0;
8806
+ }
8807
+ function publicationReasonText(reason, schemaReviewMessages) {
8808
+ switch (reason) {
8809
+ case "publication_schema_review_too_large":
8810
+ return schemaReviewMessages.schemaReviewTooLarge;
8811
+ case "publication_review_profile_invalid":
8812
+ return schemaReviewMessages.reviewProfileInvalid;
8813
+ case "schema_review_receipt_mismatch":
8814
+ return schemaReviewMessages.receiptMismatch;
8815
+ case "publication_plan_stale":
8816
+ return schemaReviewMessages.planStale;
8817
+ }
8818
+ }
8819
+ function remoteError(error, phase, messages, schemaReviewMessages) {
8820
+ const code = typedCode2(error) ?? "AP_NETWORK_ERROR";
8821
+ const publicationReason = schemaReviewMessages === void 0 ? void 0 : typedPublicationReason(error, code);
8822
+ if (publicationReason !== void 0 && schemaReviewMessages !== void 0) {
8823
+ return schemaReviewFailure(
8824
+ code,
8825
+ publicationReason,
8826
+ publicationReasonText(publicationReason, schemaReviewMessages),
8827
+ typedStatus2(error)
8421
8828
  );
8422
8829
  }
8423
- if (normalized.apply && !/^[a-f0-9]{64}$/.test(normalized.planCommitment ?? "")) {
8424
- throw new UsageError("--apply \u306B\u306Fpreview\u3067\u5F97\u305F --plan-commitment \u304C\u5FC5\u9808\u3067\u3059");
8830
+ return new PublishCommandError(
8831
+ code,
8832
+ `${phase}_failed`,
8833
+ messages.remoteFailure(phase, code),
8834
+ typedStatus2(error)
8835
+ );
8836
+ }
8837
+ function parseConfirmationRequired(error, projectId, messages) {
8838
+ if (typedCode2(error) !== "AP_CONFIRMATION_REQUIRED") return null;
8839
+ if (typedStatus2(error) !== 409 || error === null || typeof error !== "object") {
8840
+ throw responseInvalid("publication_confirmation_required_error_invalid", messages);
8425
8841
  }
8426
- const snapshot = readBoundedLocalFileSnapshot((0, import_node_path12.resolve)(cwd, normalized.file), {
8427
- maxBytes: import_tool_contract9.OPENAPI_IMPORT_MAX_SOURCE_BYTES,
8428
- root: cwd
8429
- });
8430
- const baseRequest = {
8431
- source: snapshot.text,
8432
- connectorId: normalized.connectorId,
8433
- ...normalized.format !== void 0 ? { format: normalized.format } : {},
8434
- ...normalized.baseUrl !== void 0 ? { baseUrl: normalized.baseUrl } : {},
8435
- ...normalized.serviceName !== void 0 ? { serviceName: normalized.serviceName } : {},
8436
- ...normalized.upstreamAuthMode !== void 0 ? { upstreamAuthMode: normalized.upstreamAuthMode } : {}
8437
- };
8438
- const client = runtime.createClient(normalized.profile);
8439
- const assertSource = (sourceCommitment) => {
8440
- if (sourceCommitment !== snapshot.sha256) {
8441
- throw new UsageError("Admin API\u306Esource commitment\u304Clocal file\u3068\u4E00\u81F4\u3057\u307E\u305B\u3093");
8442
- }
8443
- };
8444
- let overrides = [];
8445
- if (normalized.sideEffectFree.length > 0) {
8446
- if (normalized.apply) {
8447
- try {
8448
- const unclassified = (0, import_tool_contract9.importOpenApi)(snapshot.text, {
8449
- format: normalized.format,
8450
- baseUrl: normalized.baseUrl,
8451
- serviceName: normalized.serviceName,
8452
- upstreamAuthMode: normalized.upstreamAuthMode
8453
- });
8454
- overrides = resolveOperationRiskOverrides(
8455
- normalized.sideEffectFree,
8456
- unclassified.operations
8457
- );
8458
- } catch (error) {
8459
- if (error instanceof import_tool_contract9.OpenApiImportError) {
8460
- throw new UsageError(`OpenAPI\u304B\u3089Tool Contract\u3092\u751F\u6210\u3067\u304D\u307E\u305B\u3093: ${error.message}`);
8461
- }
8462
- throw error;
8463
- }
8464
- } else {
8465
- const unclassified = await client.planOpenApiImport(normalized.project, baseRequest).catch(rethrowWithAuthModeGuidance);
8466
- assertSource(unclassified.sourceCommitment);
8467
- overrides = resolveOperationRiskOverrides(normalized.sideEffectFree, unclassified.operations);
8468
- }
8842
+ const details = asRecord4(error.confirmationRequired);
8843
+ if (!details || !hasExactKeys3(details, [
8844
+ "requestId",
8845
+ "publicationId",
8846
+ "verificationUri",
8847
+ "expiresIn",
8848
+ "pollInterval"
8849
+ ]) || !isCanonicalUuid(details.requestId) || !isCanonicalUuid(details.publicationId) || typeof details.verificationUri !== "string" || details.expiresIn !== 600 || typeof details.pollInterval !== "number" || !Number.isInteger(details.pollInterval) || details.pollInterval < 1 || details.pollInterval > 30) {
8850
+ throw responseInvalid("publication_confirmation_required_details_invalid", messages);
8469
8851
  }
8470
- const request = {
8471
- ...baseRequest,
8472
- ...overrides.length > 0 ? { operationRiskOverrides: overrides } : {},
8473
- ...normalized.planCommitment !== void 0 ? { expectedPlanCommitment: normalized.planCommitment } : {}
8474
- };
8475
- const classification = {
8476
- upstreamAuthMode: normalized.upstreamAuthMode ?? "token_exchange",
8477
- operationRiskOverrides: overrides
8478
- };
8479
- if (!normalized.apply) {
8480
- const result2 = await client.planOpenApiImport(normalized.project, request).catch(rethrowWithAuthModeGuidance);
8481
- assertSource(result2.sourceCommitment);
8482
- json(writer, { mode: "preview", ...classification, ...result2 });
8483
- const guidance = sideEffectFreeGuidance(result2.operations);
8484
- if (guidance) interactive(writer, guidance);
8485
- return;
8852
+ let uri;
8853
+ try {
8854
+ uri = new URL(details.verificationUri);
8855
+ } catch {
8856
+ throw responseInvalid("publication_verification_uri_invalid", messages);
8486
8857
  }
8487
- const result = await client.applyOpenApiImport(
8488
- normalized.project,
8489
- normalized.idempotencyKey ?? runtime.idempotencyKey(),
8490
- request
8491
- ).catch(rethrowWithAuthModeGuidance);
8492
- assertSource(result.sourceCommitment);
8493
- json(writer, { mode: "draft_created", ...classification, ...result });
8494
- }
8495
- function collect(value, previous) {
8496
- return [...previous, value];
8858
+ const expectedPath = `/projects/${projectId}/tools/publications/${details.publicationId}`;
8859
+ if (uri.origin !== "https://admin.andpipe.com" || uri.pathname !== expectedPath || uri.username !== "" || uri.password !== "" || uri.search !== "" || uri.hash !== "" || uri.toString() !== details.verificationUri) {
8860
+ throw responseInvalid("publication_verification_uri_invalid", messages);
8861
+ }
8862
+ return {
8863
+ requestId: details.requestId,
8864
+ publicationId: details.publicationId,
8865
+ verificationUri: details.verificationUri,
8866
+ expiresIn: 600,
8867
+ pollInterval: details.pollInterval
8868
+ };
8497
8869
  }
8498
- function registerOpenApi(program, writer, cwd, runtime = createOpenApiImportRuntime()) {
8499
- const openapi = program.command("openapi").description("OpenAPI\u304B\u3089Tool Contract draft\u3092\u63D0\u6848\u3059\u308B");
8500
- openapi.command("import").description("OpenAPI 3.0/3.1 file\u3092\u5B89\u5168\u306Bpreview\u307E\u305F\u306Fdraft\u5316\u3059\u308B").requiredOption("--file <path>", "project root\u5185\u306EOpenAPI JSON/YAML file").requiredOption("--project <uuid>", "\u5BFE\u8C61project UUID").requiredOption("--connector <uuid>", "draft\u3092\u675F\u7E1B\u3059\u308Bactive connector UUID").option("--profile <name>", "Admin CLI profile", DEFAULT_PROFILE_NAME).option("--format <format>", "json\u307E\u305F\u306Fyaml\uFF08\u7701\u7565\u6642\u306F\u81EA\u52D5\u5224\u5B9A\uFF09").option("--base-url <url>", "document servers\u3092\u4E0A\u66F8\u304D\u3059\u308BHTTPS public base URL").option("--service-name <name>", "fallback tool/scope\u306Eservice\u540D").option("--apply", "preview\u6E08\u307Fproposal\u3092draft\u3068\u3057\u3066\u4FDD\u5B58\u3059\u308B", false).option("--yes", "draft\u4F5C\u6210\u3092\u660E\u793A\u78BA\u8A8D\u3059\u308B", false).option("--idempotency-key <key>", "\u518D\u9001\u7528Idempotency-Key").option("--plan-commitment <sha256>", "preview\u3067\u5F97\u305Fsafe plan commitment").option(
8501
- "--auth-mode <mode>",
8502
- "connector\u3068\u540C\u3058\u8A8D\u8A3C\u65B9\u5F0F\uFF08existing_oauth \u307E\u305F\u306F token_exchange\u3002\u7701\u7565\u6642\u306Ftoken_exchange\uFF09"
8503
- ).option(
8504
- "--side-effect-free <toolName=level>",
8505
- "\u30C7\u30FC\u30BF\u3092\u4FDD\u5B58\u30FB\u5909\u66F4\u30FB\u9001\u4FE1\u3057\u306A\u3044POST\u3060\u3051\u3092read\u307E\u305F\u306Fdraft\u3078\u660E\u793A\u5206\u985E\u3059\u308B\uFF08\u7E70\u308A\u8FD4\u3057\u6307\u5B9A\u53EF\uFF09",
8506
- collect,
8507
- []
8508
- ).action(
8509
- (options) => runOpenApiImportCommand(options, writer, cwd(), runtime)
8510
- );
8870
+ function approvedApplyResultMayBeUnknown(error) {
8871
+ const status = typedStatus2(error);
8872
+ if (status !== void 0 && status >= 400 && status < 500) return false;
8873
+ const code = typedCode2(error);
8874
+ return code === void 0 || !DEFINITIVE_APPLY_ERROR_CODES.has(code);
8511
8875
  }
8512
-
8513
- // src/commands/publish.ts
8514
- var import_node_crypto13 = require("crypto");
8515
- var import_localization10 = require("@andpipes/localization");
8516
- var import_tool_contract10 = require("@andpipes/tool-contract");
8517
- 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;
8518
- var SAFE_AP_CODE_RE2 = /^AP_[A-Z0-9_]{1,64}$/u;
8519
- var PUBLICATION_RESPONSE_MAX_BYTES = 96 * 1024;
8520
- var INITIAL_APPLY_MAX_ATTEMPTS = 3;
8521
- var DEFAULT_PUBLISH_MESSAGES = import_localization10.CLI_MESSAGES.ja.publish;
8522
- var PLAN_KEYS = [
8523
- "requestId",
8524
- "environment",
8525
- "connectorId",
8526
- "connectorRevision",
8527
- "connectorCommitment",
8528
- "policyCommitment",
8529
- "candidateCommitment",
8530
- "baseCommitment",
8531
- "planCommitment",
8532
- "tools",
8533
- "retainedTools",
8534
- "warnings",
8535
- "applyAllowed",
8536
- "blockedReasons"
8537
- ];
8538
- var APPLY_RESULT_KEYS = ["requestId", "publicationId", "state", "tools", "warnings"];
8539
- var STATUS_KEYS = [
8540
- "requestId",
8541
- "publicationId",
8542
- "durableState",
8543
- "effectiveState",
8544
- "expiresAt",
8545
- "confirmation",
8546
- "result"
8547
- ];
8548
- var BLOCKED_REASONS = /* @__PURE__ */ new Set([
8549
- "project_not_active",
8550
- "connector_not_active",
8551
- "connector_mismatch",
8552
- "tool_deprecated",
8553
- "tool_plan_limit_exceeded",
8554
- "production_capability_required",
8555
- "write_tool_mode_not_confirmed",
8556
- "production_oauth_broker_required",
8557
- "oauth_scope_registry_missing",
8558
- "oauth_scope_registry_risk_insufficient",
8559
- "publish_gate_failed",
8560
- "opaque_change",
8561
- "retention_policy_blocked",
8562
- "descriptor_name_conflict"
8563
- ]);
8564
- var TOOL_BLOCKED_REASONS = [
8565
- "connector_mismatch",
8566
- "opaque_change",
8567
- "publish_gate_failed",
8568
- "tool_deprecated"
8569
- ];
8570
- var DURABLE_STATES = /* @__PURE__ */ new Set(["pending", "approved", "rejected", "expired", "consumed"]);
8571
- var EFFECTIVE_STATES = /* @__PURE__ */ new Set([
8572
- "pending",
8573
- "approved",
8574
- "rejected",
8575
- "expired",
8576
- "consumed",
8577
- "stale"
8578
- ]);
8579
- var DEFINITIVE_APPLY_ERROR_CODES = /* @__PURE__ */ new Set([
8580
- "AP_AUTH_REQUIRED",
8581
- "AP_CONFIRMATION_EXPIRED",
8582
- "AP_CONFLICT",
8583
- "AP_FORBIDDEN",
8584
- "AP_IDEMPOTENCY_KEY_CONFLICT",
8585
- "AP_INPUT_INVALID",
8586
- "AP_INVALID_SCOPE",
8587
- "AP_NOT_FOUND",
8588
- "AP_POLICY_DENIED",
8589
- "AP_UNAUTHORIZED"
8590
- ]);
8591
- var PublishCommandError = class extends Error {
8592
- constructor(code, reason, message, status) {
8593
- super(message);
8594
- this.code = code;
8595
- this.reason = reason;
8596
- this.status = status;
8597
- this.name = "PublishCommandError";
8876
+ function initialApplyResultMayBeUnknown(error) {
8877
+ const status = typedStatus2(error);
8878
+ if (status !== void 0 && status >= 400 && status < 500) return false;
8879
+ const code = typedCode2(error);
8880
+ if (status === void 0 && code !== void 0 && DEFINITIVE_APPLY_ERROR_CODES.has(code)) {
8881
+ return false;
8598
8882
  }
8599
- code;
8600
- reason;
8601
- status;
8602
- };
8603
- function createPublishCommandRuntime(createClient) {
8883
+ return true;
8884
+ }
8885
+ function writeSafeJson(writer, value) {
8886
+ json(writer, terminalSafeValue(value));
8887
+ }
8888
+ function writePlan(writer, plan) {
8889
+ writeSafeJson(writer, { phase: "plan", ...plan });
8890
+ }
8891
+ function writeSchemaReviewSummary(writer, plan, schemaReviewMessages) {
8892
+ if (plan.reviewProfile !== 2) return;
8893
+ const reviewed = plan.tools.filter((tool) => (tool.schemaReview?.enums.length ?? 0) > 0);
8894
+ if (reviewed.length === 0) return;
8895
+ interactive(writer, schemaReviewMessages.heading);
8896
+ for (const tool of reviewed) {
8897
+ const review = tool.schemaReview;
8898
+ if (!review) continue;
8899
+ const count = (change) => review.enums.filter((entry) => entry.change === change).length;
8900
+ interactive(
8901
+ writer,
8902
+ schemaReviewMessages.toolSummary({
8903
+ toolName: terminalSafeText(tool.toolName),
8904
+ total: review.enums.length,
8905
+ added: count("added"),
8906
+ changed: count("changed"),
8907
+ removed: count("removed"),
8908
+ unchanged: count("unchanged"),
8909
+ valueReviewRequired: review.humanValueReviewRequired
8910
+ })
8911
+ );
8912
+ }
8913
+ if (reviewed.some((tool) => tool.schemaReview?.humanValueReviewRequired === true)) {
8914
+ interactive(writer, schemaReviewMessages.valueReviewInWebAdmin);
8915
+ }
8916
+ }
8917
+ function candidateNeedsReviewProfile2(candidateContract) {
8918
+ return (0, import_tool_contract9.selectPublicationReviewProfile)({
8919
+ requestedProfile: CLI_PUBLICATION_REVIEW_PROFILE,
8920
+ candidateContract,
8921
+ currentTools: []
8922
+ }) === 2;
8923
+ }
8924
+ function applyPublicationWithProfile(client, projectId, idempotencyKey, body, session) {
8925
+ return session.kind === "negotiated" ? client.applyPublication(projectId, idempotencyKey, body, REVIEW_PROFILE_REQUEST) : client.applyPublication(projectId, idempotencyKey, body);
8926
+ }
8927
+ function writeResult(writer, result) {
8928
+ writeSafeJson(writer, { phase: "result", ...result });
8929
+ }
8930
+ function freezeJson(value) {
8931
+ if (Array.isArray(value)) {
8932
+ for (const item of value) freezeJson(item);
8933
+ return Object.freeze(value);
8934
+ }
8935
+ if (value !== null && typeof value === "object") {
8936
+ for (const item of Object.values(value)) freezeJson(item);
8937
+ return Object.freeze(value);
8938
+ }
8939
+ return value;
8940
+ }
8941
+ function prepareCandidate(project) {
8942
+ const canonical = (0, import_tool_contract9.assertCanonicalPublicationSize)(project.contract.root);
8943
+ const candidateContract = freezeJson(JSON.parse(canonical));
8604
8944
  return {
8605
- createClient,
8606
- loadProject: loadDevProject,
8607
- randomUuid: () => (0, import_node_crypto13.randomUUID)(),
8608
- monotonicNow: () => Number(process.hrtime.bigint() / 1000000n),
8609
- wallNow: () => Date.now(),
8610
- sleep: (milliseconds) => new Promise((resolve7) => setTimeout(resolve7, milliseconds))
8945
+ candidateContract,
8946
+ candidateCommitment: (0, import_tool_contract9.publicationCommitment)("candidate", candidateContract)
8611
8947
  };
8612
8948
  }
8613
- function canonicalUuid(value, option, messages) {
8614
- const canonical = value.toLowerCase();
8615
- if (!UUID_RE6.test(canonical)) {
8616
- throw new UsageError(messages.invalidOption(option, "a canonical RFC 4122 UUID"));
8949
+ function loadPublicationProject(loadProject, cwd, messages = DEFAULT_PUBLISH_MESSAGES) {
8950
+ try {
8951
+ return loadProject(cwd);
8952
+ } catch (error) {
8953
+ if (error instanceof LocalFilePolicyError) {
8954
+ throw new PublishCommandError(
8955
+ "AP_POLICY_DENIED",
8956
+ error.reason,
8957
+ messages.failure(error.reason)
8958
+ );
8959
+ }
8960
+ const reason = error instanceof DevProjectLoadError ? error.reason : "local_project_invalid";
8961
+ if (error instanceof DevProjectLoadError || error instanceof UsageError) {
8962
+ throw new PublishCommandError("AP_INPUT_INVALID", reason, messages.failure(reason));
8963
+ }
8964
+ throw error;
8617
8965
  }
8618
- return canonical;
8619
8966
  }
8620
- function normalizePublishOptions(options, messages = DEFAULT_PUBLISH_MESSAGES) {
8621
- if (options.dryRun === true && options.apply === true) {
8622
- throw new UsageError(messages.incompatibleOptions("--dry-run / --apply"));
8623
- }
8624
- if (options.yes === true && options.apply !== true) {
8625
- throw new UsageError(messages.optionRequires("--yes", "--apply"));
8967
+ function assertManifestProject(project, requestedProjectId, messages = DEFAULT_PUBLISH_MESSAGES) {
8968
+ const projectId = project.manifest.project_id;
8969
+ if (requestedProjectId !== void 0 && requestedProjectId !== projectId) {
8970
+ throw new PublishCommandError(
8971
+ "AP_CONFLICT",
8972
+ "manifest_project_mismatch",
8973
+ messages.failure("manifest_project_mismatch")
8974
+ );
8626
8975
  }
8627
- if (options.apply === true && options.yes !== true) {
8628
- throw new ConfirmationRequiredError(
8629
- "andpipe publish --apply",
8630
- messages.applyConfirmationRequired
8976
+ return projectId;
8977
+ }
8978
+ function buildLocalPublicationCandidate(project, connectorId, messages = DEFAULT_PUBLISH_MESSAGES) {
8979
+ const candidate = prepareCandidate(project);
8980
+ const localToolNames = project.contract.tools.map((tool) => (0, import_tool_contract9.toolName)(tool));
8981
+ if (localToolNames.some((name) => !(0, import_tool_contract9.isSafeToolName)(name))) {
8982
+ throw new PublishCommandError(
8983
+ "AP_INPUT_INVALID",
8984
+ "publication_candidate_tool_invalid",
8985
+ messages.failure("publication_candidate_tool_invalid")
8631
8986
  );
8632
8987
  }
8633
- const projectId = options.project === void 0 ? void 0 : canonicalUuid(options.project, "--project", messages);
8988
+ const expectedToolNames = localToolNames.sort(import_tool_contract9.comparePublicationUnicodeCodePoints);
8634
8989
  return {
8635
- mode: options.apply === true ? "apply" : "dry-run",
8636
- ...options.connector === void 0 ? {} : { connectorId: canonicalUuid(options.connector, "--connector", messages) },
8637
- profile: options.profile ?? DEFAULT_PROFILE_NAME,
8638
- ...projectId === void 0 ? {} : { projectId }
8990
+ planRequest: {
8991
+ environment: "production",
8992
+ connectorId,
8993
+ candidateContract: candidate.candidateContract,
8994
+ candidateCommitment: candidate.candidateCommitment,
8995
+ ...project.manifest.template_id && project.manifest.template_application_commitment ? {
8996
+ templateProvenance: {
8997
+ templateId: project.manifest.template_id,
8998
+ applicationCommitment: project.manifest.template_application_commitment
8999
+ }
9000
+ } : {}
9001
+ },
9002
+ expectedToolNames
8639
9003
  };
8640
9004
  }
8641
- function asRecord4(value) {
8642
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
9005
+ function assertIdempotencyKey2(value, messages) {
9006
+ if (!UUID_RE6.test(value)) {
9007
+ throw new PublishCommandError(
9008
+ "AP_NETWORK_ERROR",
9009
+ "secure_random_invalid",
9010
+ messages.failure("secure_random_invalid")
9011
+ );
9012
+ }
9013
+ return value;
8643
9014
  }
8644
- function hasExactKeys3(record, keys) {
8645
- const actual = Object.keys(record);
8646
- return actual.length === keys.length && actual.every((key) => keys.includes(key));
9015
+ async function sendInitialApplyWithSameAnchorRetry(input) {
9016
+ for (let attempt = 0; attempt < INITIAL_APPLY_MAX_ATTEMPTS; attempt += 1) {
9017
+ try {
9018
+ const result = parsePublicationResult(
9019
+ await applyPublicationWithProfile(
9020
+ input.client,
9021
+ input.projectId,
9022
+ input.idempotencyKey,
9023
+ input.body,
9024
+ input.session
9025
+ ),
9026
+ input.plan,
9027
+ input.messages
9028
+ );
9029
+ if (result.state !== "noop") {
9030
+ throw responseInvalid("publication_initial_apply_state_invalid", input.messages);
9031
+ }
9032
+ return {
9033
+ kind: "response",
9034
+ result
9035
+ };
9036
+ } catch (error) {
9037
+ let malformedConfirmationAnchor = false;
9038
+ let confirmationRequired = null;
9039
+ try {
9040
+ confirmationRequired = parseConfirmationRequired(error, input.projectId, input.messages);
9041
+ } catch (parseError) {
9042
+ if (typedCode2(error) !== "AP_CONFIRMATION_REQUIRED" || !(parseError instanceof PublishCommandError) || parseError.code !== "AP_RESPONSE_INVALID") {
9043
+ throw parseError;
9044
+ }
9045
+ malformedConfirmationAnchor = true;
9046
+ }
9047
+ if (confirmationRequired) {
9048
+ return { kind: "confirmation_required", details: confirmationRequired };
9049
+ }
9050
+ if (!malformedConfirmationAnchor && !initialApplyResultMayBeUnknown(error)) {
9051
+ throw remoteError(error, "initial_apply", input.messages, input.schemaReviewMessages);
9052
+ }
9053
+ if (attempt === INITIAL_APPLY_MAX_ATTEMPTS - 1) {
9054
+ throw new PublishCommandError(
9055
+ "AP_RESULT_UNKNOWN",
9056
+ "publication_anchor_result_unknown",
9057
+ input.messages.proposalResultUnknown
9058
+ );
9059
+ }
9060
+ }
9061
+ }
9062
+ throw new PublishCommandError(
9063
+ "AP_RESULT_UNKNOWN",
9064
+ "publication_anchor_result_unknown",
9065
+ input.messages.proposalResultUnknown
9066
+ );
8647
9067
  }
8648
- function responseInvalid(reason, messages) {
8649
- return new PublishCommandError("AP_RESPONSE_INVALID", reason, messages.failure(reason));
9068
+ function confirmationStopped(code, reason, messages) {
9069
+ return new PublishCommandError(code, reason, messages.confirmationStopped(reason));
8650
9070
  }
8651
- function assertCanonicalResponseSize(value, reason, messages, maxBytes = PUBLICATION_RESPONSE_MAX_BYTES) {
9071
+ function pollFailureIsDefinitive(error) {
9072
+ const status = typedStatus2(error);
9073
+ if (status !== void 0 && status >= 400 && status < 500) return true;
9074
+ const code = typedCode2(error);
9075
+ return code === "AP_RESPONSE_INVALID" || code === "AP_OUTPUT_INVALID" || code !== void 0 && DEFINITIVE_APPLY_ERROR_CODES.has(code);
9076
+ }
9077
+ async function sleepForPoll(runtime, milliseconds, mode, messages) {
8652
9078
  try {
8653
- (0, import_tool_contract10.assertCanonicalPublicationSize)(value, maxBytes);
9079
+ await runtime.sleep(milliseconds);
8654
9080
  } catch {
8655
- throw responseInvalid(reason, messages);
9081
+ throw new PublishCommandError(
9082
+ mode === "recover-result" ? "AP_RESULT_UNKNOWN" : "AP_NETWORK_ERROR",
9083
+ "publication_poll_sleep_failed",
9084
+ messages.pollingUnavailable
9085
+ );
9086
+ }
9087
+ }
9088
+ async function pollPublication(client, projectId, details, plan, writer, runtime, mode, messages, knownExpiresAt) {
9089
+ const startedAt = runtime.monotonicNow();
9090
+ let deadline = startedAt + details.expiresIn * 1e3;
9091
+ let expiresAt = knownExpiresAt;
9092
+ if (knownExpiresAt !== void 0) {
9093
+ deadline = Math.min(
9094
+ deadline,
9095
+ startedAt + Math.max(0, Date.parse(knownExpiresAt) - runtime.wallNow())
9096
+ );
9097
+ }
9098
+ const maxAttempts = Math.ceil(details.expiresIn / details.pollInterval) + 2;
9099
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
9100
+ let rawStatus;
9101
+ try {
9102
+ rawStatus = await client.getPublication(projectId, details.publicationId);
9103
+ } catch (error) {
9104
+ if (pollFailureIsDefinitive(error)) {
9105
+ throw remoteError(error, mode === "recover-result" ? "result_recovery" : "poll", messages);
9106
+ }
9107
+ const remainingMilliseconds2 = Math.max(0, deadline - runtime.monotonicNow());
9108
+ if (remainingMilliseconds2 <= 0 || attempt === maxAttempts - 1) {
9109
+ throw new PublishCommandError(
9110
+ mode === "recover-result" ? "AP_RESULT_UNKNOWN" : "AP_NETWORK_ERROR",
9111
+ "publication_poll_unavailable",
9112
+ messages.pollingUnavailable
9113
+ );
9114
+ }
9115
+ await sleepForPoll(
9116
+ runtime,
9117
+ Math.min(details.pollInterval * 1e3, remainingMilliseconds2),
9118
+ mode,
9119
+ messages
9120
+ );
9121
+ continue;
9122
+ }
9123
+ const status = parseStatus(rawStatus, details.publicationId, plan, messages);
9124
+ if (expiresAt !== void 0 && status.expiresAt !== expiresAt) {
9125
+ throw responseInvalid("publication_expiry_changed", messages);
9126
+ }
9127
+ expiresAt = status.expiresAt;
9128
+ const now = runtime.monotonicNow();
9129
+ const wallRemaining = Math.max(0, Date.parse(status.expiresAt) - runtime.wallNow());
9130
+ deadline = Math.min(deadline, now + wallRemaining);
9131
+ const remainingMilliseconds = Math.max(0, deadline - now);
9132
+ writeSafeJson(writer, {
9133
+ phase: mode === "recover-result" ? "result_recovery" : "confirmation",
9134
+ requestId: status.requestId,
9135
+ publicationId: status.publicationId,
9136
+ durableState: status.durableState,
9137
+ effectiveState: status.effectiveState,
9138
+ expiresAt: status.expiresAt,
9139
+ remainingSeconds: Math.ceil(remainingMilliseconds / 1e3)
9140
+ });
9141
+ if (status.durableState === "consumed") {
9142
+ return { kind: "consumed", result: status.result };
9143
+ }
9144
+ if (status.durableState === "rejected") {
9145
+ throw confirmationStopped("AP_POLICY_DENIED", "publication_rejected", messages);
9146
+ }
9147
+ if (status.durableState === "expired") {
9148
+ throw confirmationStopped(
9149
+ "AP_CONFIRMATION_EXPIRED",
9150
+ "publication_confirmation_expired",
9151
+ messages
9152
+ );
9153
+ }
9154
+ if (status.effectiveState === "stale") {
9155
+ throw confirmationStopped("AP_CONFLICT", "publication_confirmation_stale", messages);
9156
+ }
9157
+ if (mode === "await-approval" && status.durableState === "approved" && status.confirmation !== null) {
9158
+ return {
9159
+ kind: "approved",
9160
+ confirmation: status.confirmation,
9161
+ expiresAt: status.expiresAt
9162
+ };
9163
+ }
9164
+ if (remainingMilliseconds <= 0) {
9165
+ throw confirmationStopped(
9166
+ "AP_CONFIRMATION_EXPIRED",
9167
+ "publication_confirmation_timeout",
9168
+ messages
9169
+ );
9170
+ }
9171
+ const sleepMilliseconds = Math.min(details.pollInterval * 1e3, remainingMilliseconds);
9172
+ await sleepForPoll(runtime, sleepMilliseconds, mode, messages);
8656
9173
  }
9174
+ throw confirmationStopped("AP_CONFIRMATION_EXPIRED", "publication_poll_attempt_limit", messages);
8657
9175
  }
8658
- function isCanonicalUuid(value) {
8659
- return typeof value === "string" && UUID_RE6.test(value);
8660
- }
8661
- function isCommitment(value) {
8662
- return typeof value === "string" && import_tool_contract10.PUBLICATION_SHA256_COMMITMENT_RE.test(value);
8663
- }
8664
- function isCanonicalTimestamp(value) {
8665
- if (typeof value !== "string" || value.length > 64) return false;
8666
- const milliseconds = Date.parse(value);
8667
- return Number.isFinite(milliseconds) && new Date(milliseconds).toISOString() === value;
8668
- }
8669
- function isStrictlySorted(values) {
8670
- return values.every(
8671
- (value, index) => index === 0 || (0, import_tool_contract10.comparePublicationUnicodeCodePoints)(values[index - 1], value) < 0
9176
+ async function runPublishCommand(options, writer, cwd, runtime, messages = DEFAULT_PUBLISH_MESSAGES, scopeRegistrationMessages = DEFAULT_SCOPE_REGISTRATION_MESSAGES2, schemaReviewMessages = DEFAULT_SCHEMA_REVIEW_MESSAGES) {
9177
+ const normalized = normalizePublishOptions(options, messages);
9178
+ const project = loadPublicationProject(runtime.loadProject, cwd, messages);
9179
+ const projectId = project.manifest.project_id;
9180
+ const connectorId = normalized.connectorId ?? project.manifest.connector_id;
9181
+ if (connectorId === void 0) {
9182
+ throw new PublishCommandError(
9183
+ "AP_INPUT_INVALID",
9184
+ "publication_connector_required",
9185
+ messages.optionRequires("publish", "--connector UUID")
9186
+ );
9187
+ }
9188
+ assertManifestProject(project, normalized.projectId, messages);
9189
+ const { planRequest, expectedToolNames } = buildLocalPublicationCandidate(
9190
+ project,
9191
+ connectorId,
9192
+ messages
8672
9193
  );
8673
- }
8674
- function parseWarnings(value, messages) {
9194
+ const client = runtime.createClient(normalized.profile);
9195
+ let rawPlan;
8675
9196
  try {
8676
- return (0, import_tool_contract10.parsePublicationWarningsDto)(value);
8677
- } catch {
8678
- throw responseInvalid("publication_warnings_invalid", messages);
9197
+ rawPlan = await client.planPublication(projectId, planRequest, REVIEW_PROFILE_REQUEST);
9198
+ } catch (error) {
9199
+ throw remoteError(error, "plan", messages, schemaReviewMessages);
8679
9200
  }
8680
- }
8681
- function parsePlan(value, connectorId, candidateCommitment, expectedToolNames, messages) {
8682
- assertCanonicalResponseSize(value, "publication_plan_too_large", messages);
8683
- const plan = asRecord4(value);
8684
- 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(
8685
- (reason) => typeof reason === "string" && BLOCKED_REASONS.has(reason)
8686
- ) || !isStrictlySorted(plan.blockedReasons) || plan.applyAllowed !== (plan.blockedReasons.length === 0)) {
8687
- throw responseInvalid("publication_plan_invalid", messages);
9201
+ const negotiated = negotiateReviewProfile(rawPlan, messages, schemaReviewMessages);
9202
+ const session = negotiated.session;
9203
+ const plan = parsePlan(
9204
+ negotiated.body,
9205
+ connectorId,
9206
+ planRequest.candidateCommitment,
9207
+ expectedToolNames,
9208
+ session.profile,
9209
+ messages
9210
+ );
9211
+ writePlan(writer, plan);
9212
+ writeSchemaReviewSummary(writer, plan, schemaReviewMessages);
9213
+ if (session.kind === "legacy" && plan.blockedReasons.includes("opaque_change") && candidateNeedsReviewProfile2(planRequest.candidateContract)) {
9214
+ interactive(writer, schemaReviewMessages.adminApiUpdatePending);
8688
9215
  }
8689
- const blockedReasons = plan.blockedReasons;
8690
- let safeDiff;
8691
- try {
8692
- safeDiff = (0, import_tool_contract10.parsePublicationSafeDiffDto)({
8693
- tools: plan.tools,
8694
- retainedTools: plan.retainedTools,
8695
- warnings: plan.warnings
8696
- });
8697
- } catch {
8698
- throw responseInvalid("publication_safe_diff_invalid", messages);
9216
+ if (plan.blockedReasons.includes("connector_mismatch")) {
9217
+ interactive(writer, messages.connectorMismatchRemediation);
8699
9218
  }
8700
- const tools = safeDiff.tools;
8701
- const toolNames = tools.map((tool) => tool.toolName);
8702
- if (!isStrictlySorted(toolNames) || JSON.stringify(toolNames) !== JSON.stringify(expectedToolNames)) {
8703
- throw responseInvalid("publication_plan_tools_order_invalid", messages);
9219
+ if (plan.blockedReasons.includes("oauth_scope_registry_missing") || plan.blockedReasons.includes("oauth_scope_registry_risk_insufficient")) {
9220
+ interactive(
9221
+ writer,
9222
+ planRequest.templateProvenance ? scopeRegistrationMessages.publishTemplateRemediation(projectId) : scopeRegistrationMessages.publishRemediation(connectorId)
9223
+ );
8704
9224
  }
8705
- const warnings = safeDiff.warnings;
8706
- const expectedPlanCommitment = (0, import_tool_contract10.publicationCommitment)("plan", {
8707
- candidateCommitment,
8708
- baseCommitment: plan.baseCommitment,
8709
- connectorId,
8710
- connectorRevision: plan.connectorRevision,
8711
- connectorCommitment: plan.connectorCommitment,
8712
- policyCommitment: plan.policyCommitment,
8713
- environment: "production",
8714
- safeDiff
8715
- });
8716
- if (plan.planCommitment !== expectedPlanCommitment) {
9225
+ if (normalized.mode === "dry-run") return;
9226
+ if (!plan.applyAllowed) {
8717
9227
  throw new PublishCommandError(
8718
- "AP_CONFLICT",
8719
- "publication_plan_commitment_mismatch",
8720
- messages.failure("publication_plan_commitment_mismatch")
9228
+ "AP_POLICY_DENIED",
9229
+ "publication_plan_blocked",
9230
+ messages.planBlocked(plan.blockedReasons)
8721
9231
  );
8722
9232
  }
8723
- const toolBlockedReasons = new Set(tools.flatMap((tool) => tool.blockedReasons));
8724
- if (tools.some((tool) => !tool.gate.ok) && plan.applyAllowed || tools.some((tool) => tool.opaqueChanged) && (plan.applyAllowed || !blockedReasons.includes("opaque_change")) || TOOL_BLOCKED_REASONS.some(
8725
- (reason) => (
8726
- // connector_mismatchはtool単位(既存toolの別connector束縛)に加え、candidateの
8727
- // upstream.auth.modeとconnector方式の不一致としてtop-levelだけにも出る (#456 / #724)。
8728
- reason === "connector_mismatch" ? toolBlockedReasons.has(reason) && !blockedReasons.includes(reason) : blockedReasons.includes(reason) !== toolBlockedReasons.has(reason)
8729
- )
8730
- )) {
8731
- throw responseInvalid("publication_plan_gate_inconsistent", messages);
8732
- }
8733
- return {
8734
- requestId: plan.requestId,
8735
- environment: "production",
8736
- connectorId,
8737
- connectorRevision: plan.connectorRevision,
8738
- connectorCommitment: plan.connectorCommitment,
8739
- policyCommitment: plan.policyCommitment,
8740
- candidateCommitment,
8741
- baseCommitment: plan.baseCommitment,
9233
+ const idempotencyKey = assertIdempotencyKey2(runtime.randomUuid(), messages);
9234
+ const applyRequest = (confirmation) => ({
9235
+ ...planRequest,
8742
9236
  planCommitment: plan.planCommitment,
8743
- tools,
8744
- retainedTools: safeDiff.retainedTools,
8745
- warnings,
8746
- applyAllowed: plan.applyAllowed,
8747
- blockedReasons
8748
- };
9237
+ confirmation
9238
+ });
9239
+ const initialApplyRequest = freezeJson(applyRequest(null));
9240
+ const initial = await sendInitialApplyWithSameAnchorRetry({
9241
+ client,
9242
+ projectId,
9243
+ idempotencyKey,
9244
+ body: initialApplyRequest,
9245
+ plan,
9246
+ session,
9247
+ messages,
9248
+ schemaReviewMessages
9249
+ });
9250
+ let details;
9251
+ if (initial.kind === "response") {
9252
+ writeResult(writer, initial.result);
9253
+ return;
9254
+ } else {
9255
+ if (plan.tools.every((tool) => !tool.changed)) {
9256
+ throw responseInvalid("publication_noop_confirmation_invalid", messages);
9257
+ }
9258
+ details = initial.details;
9259
+ }
9260
+ writeSafeJson(writer, { phase: "confirmation_required", ...details });
9261
+ const decision = await pollPublication(
9262
+ client,
9263
+ projectId,
9264
+ details,
9265
+ plan,
9266
+ writer,
9267
+ runtime,
9268
+ "await-approval",
9269
+ messages
9270
+ );
9271
+ if (decision.kind === "consumed") {
9272
+ writeResult(writer, decision.result);
9273
+ return;
9274
+ }
9275
+ try {
9276
+ const result = parsePublicationResult(
9277
+ await applyPublicationWithProfile(
9278
+ client,
9279
+ projectId,
9280
+ idempotencyKey,
9281
+ applyRequest(decision.confirmation),
9282
+ session
9283
+ ),
9284
+ plan,
9285
+ messages,
9286
+ details.publicationId
9287
+ );
9288
+ writeResult(writer, result);
9289
+ return;
9290
+ } catch (error) {
9291
+ if (error instanceof PublishCommandError && error.code === "AP_RESPONSE_INVALID") {
9292
+ } else if (!approvedApplyResultMayBeUnknown(error)) {
9293
+ throw remoteError(error, "approved_apply", messages, schemaReviewMessages);
9294
+ }
9295
+ }
9296
+ const recovered = await pollPublication(
9297
+ client,
9298
+ projectId,
9299
+ details,
9300
+ plan,
9301
+ writer,
9302
+ runtime,
9303
+ "recover-result",
9304
+ messages,
9305
+ decision.expiresAt
9306
+ );
9307
+ if (recovered.kind !== "consumed") {
9308
+ throw new PublishCommandError(
9309
+ "AP_RESULT_UNKNOWN",
9310
+ "publication_result_unknown",
9311
+ messages.resultUnknown
9312
+ );
9313
+ }
9314
+ writeResult(writer, recovered.result);
8749
9315
  }
8750
- function sameWarnings(left, right) {
8751
- return JSON.stringify(left) === JSON.stringify(right);
9316
+ 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) {
9317
+ 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) => {
9318
+ await runPublishCommand(
9319
+ commandOptions,
9320
+ writer,
9321
+ cwd(),
9322
+ runtime,
9323
+ messages,
9324
+ scopeRegistrationMessages,
9325
+ schemaReviewMessages
9326
+ );
9327
+ });
8752
9328
  }
8753
- function parseToolResults(value, messages) {
8754
- if (!Array.isArray(value)) {
8755
- throw responseInvalid("publication_result_tools_invalid", messages);
9329
+
9330
+ // src/commands/oauth.ts
9331
+ function isUrl(value) {
9332
+ if (typeof value !== "string") {
9333
+ return false;
8756
9334
  }
8757
- const tools = value.map((candidate) => {
8758
- const tool = asRecord4(candidate);
8759
- 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) {
8760
- throw responseInvalid("publication_result_tool_invalid", messages);
8761
- }
8762
- const operation = tool.operation;
9335
+ try {
9336
+ const u = new URL(value);
9337
+ return u.protocol === "http:" || u.protocol === "https:";
9338
+ } catch {
9339
+ return false;
9340
+ }
9341
+ }
9342
+ function field(meta, snake, camel) {
9343
+ return snake in meta ? meta[snake] : meta[camel];
9344
+ }
9345
+ function validateOAuthMetadata(meta, locale = import_localization10.DEFAULT_LOCALE) {
9346
+ const messages = import_localization10.CLI_MESSAGES[locale].oauth;
9347
+ const results = [];
9348
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
8763
9349
  return {
8764
- toolName: tool.toolName,
8765
- operation,
8766
- toolId: tool.toolId,
8767
- versionId: tool.versionId,
8768
- version: tool.version
9350
+ ok: false,
9351
+ results: [
9352
+ {
9353
+ id: "metadata",
9354
+ label: "metadata",
9355
+ status: "fail",
9356
+ detail: messages.metadataNotObject
9357
+ }
9358
+ ]
8769
9359
  };
9360
+ }
9361
+ const m = meta;
9362
+ const urlFields = [
9363
+ ["issuer", "issuer", "issuer"],
9364
+ ["authorization_endpoint", "authorization_endpoint", "authorizationEndpoint"],
9365
+ ["token_endpoint", "token_endpoint", "tokenEndpoint"],
9366
+ ["jwks_uri", "jwks_uri", "jwksUri"]
9367
+ ];
9368
+ for (const [id, snake, camel] of urlFields) {
9369
+ const value = field(m, snake, camel);
9370
+ const ok = isUrl(value);
9371
+ results.push({
9372
+ id,
9373
+ label: id,
9374
+ status: ok ? "pass" : "fail",
9375
+ detail: ok ? messages.urlOk : messages.invalidUrl(id)
9376
+ });
9377
+ }
9378
+ const responseTypes = field(m, "response_types_supported", "responseTypesSupported");
9379
+ results.push({
9380
+ id: "response_types_supported",
9381
+ label: "response_types_supported",
9382
+ status: Array.isArray(responseTypes) && responseTypes.length > 0 ? "pass" : "fail",
9383
+ detail: Array.isArray(responseTypes) ? messages.present : messages.arrayMissing
9384
+ });
9385
+ const scopes = field(m, "scopes_supported", "scopesSupported");
9386
+ results.push({
9387
+ id: "scopes_supported",
9388
+ label: "scopes_supported",
9389
+ // 推奨項目。欠落は致命ではないため pending 扱いで明示する。
9390
+ status: Array.isArray(scopes) && scopes.length > 0 ? "pass" : "pending",
9391
+ detail: Array.isArray(scopes) ? messages.present : messages.scopesMissing
8770
9392
  });
8771
- if (!isStrictlySorted(tools.map((tool) => tool.toolName))) {
8772
- throw responseInvalid("publication_result_tools_order_invalid", messages);
8773
- }
8774
- return tools;
9393
+ return { ok: results.every((r) => r.status !== "fail"), results };
8775
9394
  }
8776
- function parsePublicationResult(value, plan, messages, expectedPublicationId) {
8777
- assertCanonicalResponseSize(value, "publication_apply_result_too_large", messages);
8778
- const result = asRecord4(value);
8779
- if (!result || !hasExactKeys3(result, APPLY_RESULT_KEYS) || !isCanonicalUuid(result.requestId) || result.state !== "noop" && result.state !== "consumed") {
8780
- throw responseInvalid("publication_apply_result_invalid", messages);
9395
+ function buildInitTemplate(provider) {
9396
+ return {
9397
+ provider,
9398
+ issuer: "https://auth.example.com",
9399
+ authorizationEndpoint: "https://auth.example.com/oauth/authorize",
9400
+ tokenEndpoint: "https://auth.example.com/oauth/token",
9401
+ jwksUri: "https://auth.example.com/.well-known/jwks.json",
9402
+ clientId: "<client id>",
9403
+ // secret は config に直書きせず env 参照にする (No secret in repo / stdout)。
9404
+ clientSecretEnv: "ANDPIPE_OAUTH_CLIENT_SECRET",
9405
+ redirectUri: "https://<your-andpipe-gateway>/oauth/callback",
9406
+ scopes: ["openid", "profile"]
9407
+ };
9408
+ }
9409
+ var SCOPE_REGISTER_OPERATION = "andpipe oauth scopes register";
9410
+ var RFC_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
9411
+ var RESOURCE_NOT_FOUND_CODES = /* @__PURE__ */ new Set([
9412
+ "AP_NOT_FOUND",
9413
+ "AP_TOOL_NOT_FOUND",
9414
+ "AP_TOOL_VERSION_NOT_FOUND"
9415
+ ]);
9416
+ function createOAuthScopeRegisterRuntime(createClient = (profile) => createAdminApiClient({ profile })) {
9417
+ return { createClient, loadProject: loadDevProject, randomUuid: () => (0, import_node_crypto13.randomUUID)() };
9418
+ }
9419
+ var OAuthScopeRegistrationCommandError = class extends Error {
9420
+ constructor(code, reason, message, status) {
9421
+ super(message);
9422
+ this.code = code;
9423
+ this.reason = reason;
9424
+ this.status = status;
9425
+ this.name = "OAuthScopeRegistrationCommandError";
8781
9426
  }
8782
- const warnings = parseWarnings(result.warnings, messages);
8783
- if (!sameWarnings(warnings, plan.warnings)) {
8784
- throw responseInvalid("publication_apply_warning_mismatch", messages);
9427
+ code;
9428
+ reason;
9429
+ status;
9430
+ };
9431
+ function parseDraftOption(value, messages) {
9432
+ const parts = value.split(":");
9433
+ const toolId = parts[0]?.toLowerCase() ?? "";
9434
+ const versionId = parts[1]?.toLowerCase() ?? "";
9435
+ if (parts.length !== 2 || !RFC_UUID_RE.test(toolId) || !RFC_UUID_RE.test(versionId)) {
9436
+ throw new UsageError(messages.draftFormat);
9437
+ }
9438
+ return { toolId, versionId };
9439
+ }
9440
+ function normalizeOAuthScopeRegisterOptions(options, locale = import_localization10.DEFAULT_LOCALE) {
9441
+ const messages = import_localization10.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9442
+ const cliMessages = import_localization10.CLI_MESSAGES[locale];
9443
+ const apply = options.apply === true;
9444
+ if (options.yes === true && !apply) throw new UsageError(messages.yesRequiresApply);
9445
+ if (apply && options.yes !== true) {
9446
+ throw new ConfirmationRequiredError(
9447
+ SCOPE_REGISTER_OPERATION,
9448
+ cliMessages.common.confirmationRequiredMessage(SCOPE_REGISTER_OPERATION)
9449
+ );
8785
9450
  }
8786
- const tools = parseToolResults(result.tools, messages);
8787
- const changedToolNames = plan.tools.filter((tool) => tool.changed).map((tool) => tool.toolName);
8788
- if (result.state === "noop") {
8789
- if (result.publicationId !== null || tools.length !== 0 || changedToolNames.length !== 0) {
8790
- throw responseInvalid("publication_noop_invalid", messages);
8791
- }
9451
+ const profile = options.profile ?? DEFAULT_PROFILE_NAME;
9452
+ const rawDrafts = options.draft ?? [];
9453
+ if (rawDrafts.length === 0) {
8792
9454
  return {
8793
- requestId: result.requestId,
8794
- publicationId: null,
8795
- state: "noop",
8796
- tools,
8797
- warnings
9455
+ kind: "publication_candidate",
9456
+ ...options.project === void 0 ? {} : {
9457
+ projectId: canonicalUuidOption(options.project, "--project", cliMessages.publish)
9458
+ },
9459
+ ...options.connector === void 0 ? {} : {
9460
+ connectorId: canonicalUuidOption(options.connector, "--connector", cliMessages.publish)
9461
+ },
9462
+ apply,
9463
+ profile
8798
9464
  };
8799
9465
  }
8800
- if (!isCanonicalUuid(result.publicationId) || expectedPublicationId !== void 0 && result.publicationId !== expectedPublicationId || changedToolNames.length === 0 || JSON.stringify(tools.map((tool) => tool.toolName)) !== JSON.stringify(changedToolNames) || tools.some(
8801
- (tool) => plan.tools.find((planned) => planned.toolName === tool.toolName)?.operation !== tool.operation
8802
- )) {
8803
- throw responseInvalid("publication_consumed_result_invalid", messages);
9466
+ if (options.connector !== void 0) throw new UsageError(messages.draftConnectorConflict);
9467
+ if (options.project === void 0) throw new UsageError(messages.draftRequiresProject);
9468
+ const projectId = canonicalUuidOption(options.project, "--project", cliMessages.publish);
9469
+ const drafts = rawDrafts.map((value) => parseDraftOption(value, messages)).sort((left, right) => (0, import_tool_contract10.comparePublicationUnicodeCodePoints)(left.toolId, right.toolId));
9470
+ if (drafts.length > import_tool_contract10.OAUTH_SCOPE_REGISTRATION_MAX_DRAFTS || drafts.some((draft, index) => index > 0 && drafts[index - 1]?.toolId === draft.toolId)) {
9471
+ throw new UsageError(messages.draftInvalid);
8804
9472
  }
8805
- return {
8806
- requestId: result.requestId,
8807
- publicationId: result.publicationId,
8808
- state: "consumed",
8809
- tools,
8810
- warnings
8811
- };
9473
+ return { kind: "saved_drafts", projectId, drafts, apply, profile };
8812
9474
  }
8813
- function parseConfirmation(value, messages) {
8814
- if (value === null) return null;
8815
- const confirmation = asRecord4(value);
8816
- 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) {
8817
- throw responseInvalid("publication_confirmation_invalid", messages);
9475
+ function riskLabel(messages, level) {
9476
+ return messages.riskLabels[level];
9477
+ }
9478
+ function blockedGuidance(cli, reason) {
9479
+ switch (reason) {
9480
+ case "scope_in_use_risk_upgrade_forbidden":
9481
+ return cli.blocked.scopeInUse;
9482
+ case "template_scope_requires_sync":
9483
+ return cli.blocked.templateScope;
9484
+ case "reserved_scope_name":
9485
+ return cli.blocked.reservedName;
8818
9486
  }
8819
- return {
8820
- confirmationId: confirmation.confirmationId,
8821
- signature: confirmation.signature,
8822
- confirmed: true
8823
- };
8824
9487
  }
8825
- function parseStatus(value, publicationId, plan, messages) {
8826
- assertCanonicalResponseSize(value, "publication_status_too_large", messages);
8827
- const status = asRecord4(value);
8828
- if (!status || !hasExactKeys3(status, STATUS_KEYS) || !isCanonicalUuid(status.requestId) || status.publicationId !== publicationId || typeof status.durableState !== "string" || !DURABLE_STATES.has(status.durableState) || typeof status.effectiveState !== "string" || !EFFECTIVE_STATES.has(status.effectiveState) || !isCanonicalTimestamp(status.expiresAt)) {
8829
- throw responseInvalid("publication_status_invalid", messages);
9488
+ function writeRegistrationSummary(writer, response, applyRequested, messages) {
9489
+ const cli = messages.cli;
9490
+ const name = (value) => terminalSafeText(value);
9491
+ const lines = [response.mode === "preview" ? cli.previewHeading : cli.appliedHeading];
9492
+ for (const row of response.added) {
9493
+ lines.push(` ${cli.addedLabel} ${name(row.name)} ${riskLabel(messages, row.riskLevel)}`);
8830
9494
  }
8831
- const confirmation = parseConfirmation(status.confirmation, messages);
8832
- const result = status.result === null ? null : parsePublicationResult(status.result, plan, messages, publicationId);
8833
- const durableState = status.durableState;
8834
- const effectiveState = status.effectiveState;
8835
- const isPending = durableState === "pending";
8836
- const isApproved = durableState === "approved";
8837
- const isTerminal = durableState === "rejected" || durableState === "expired" || durableState === "consumed";
8838
- if (isPending && effectiveState !== "pending" && effectiveState !== "stale" || isApproved && effectiveState !== "approved" && effectiveState !== "stale" || isTerminal && effectiveState !== durableState || isPending && confirmation !== null || isApproved && effectiveState === "approved" && confirmation === null || isApproved && effectiveState === "stale" && confirmation !== null || isTerminal && confirmation !== null || (durableState === "consumed" ? result === null : result !== null)) {
8839
- throw responseInvalid("publication_status_inconsistent", messages);
9495
+ for (const row of response.updated) {
9496
+ lines.push(
9497
+ ` ${cli.updatedLabel} ${name(row.name)} ${riskLabel(messages, row.fromRisk)} \u2192 ${riskLabel(messages, row.toRisk)}`
9498
+ );
8840
9499
  }
8841
- return {
8842
- requestId: status.requestId,
8843
- publicationId,
8844
- durableState,
8845
- effectiveState,
8846
- expiresAt: status.expiresAt,
8847
- confirmation,
8848
- result
8849
- };
8850
- }
8851
- function typedCode2(error) {
8852
- if (error === null || typeof error !== "object") return void 0;
8853
- const code = error.code;
8854
- return typeof code === "string" && SAFE_AP_CODE_RE2.test(code) ? code : void 0;
8855
- }
8856
- function typedStatus2(error) {
8857
- if (error === null || typeof error !== "object") return void 0;
8858
- const status = error.status;
8859
- return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599 ? status : void 0;
8860
- }
8861
- function remoteError(error, phase, messages) {
8862
- const code = typedCode2(error) ?? "AP_NETWORK_ERROR";
8863
- return new PublishCommandError(
8864
- code,
8865
- `${phase}_failed`,
8866
- messages.remoteFailure(phase, code),
8867
- typedStatus2(error)
8868
- );
8869
- }
8870
- function parseConfirmationRequired(error, projectId, messages) {
8871
- if (typedCode2(error) !== "AP_CONFIRMATION_REQUIRED") return null;
8872
- if (typedStatus2(error) !== 409 || error === null || typeof error !== "object") {
8873
- throw responseInvalid("publication_confirmation_required_error_invalid", messages);
9500
+ for (const existing of response.existing) {
9501
+ lines.push(` ${cli.existingLabel} ${name(existing)}`);
8874
9502
  }
8875
- const details = asRecord4(error.confirmationRequired);
8876
- if (!details || !hasExactKeys3(details, [
8877
- "requestId",
8878
- "publicationId",
8879
- "verificationUri",
8880
- "expiresIn",
8881
- "pollInterval"
8882
- ]) || !isCanonicalUuid(details.requestId) || !isCanonicalUuid(details.publicationId) || typeof details.verificationUri !== "string" || details.expiresIn !== 600 || typeof details.pollInterval !== "number" || !Number.isInteger(details.pollInterval) || details.pollInterval < 1 || details.pollInterval > 30) {
8883
- throw responseInvalid("publication_confirmation_required_details_invalid", messages);
9503
+ for (const row of response.blocked) {
9504
+ const from = row.fromRisk === null ? "" : `${riskLabel(messages, row.fromRisk)} \u2192 `;
9505
+ lines.push(
9506
+ ` ${cli.blockedLabel} ${name(row.name)} ${from}${riskLabel(messages, row.toRisk)}`
9507
+ );
9508
+ lines.push(` ${blockedGuidance(cli, row.reason)}`);
9509
+ }
9510
+ if (response.unchanged && response.blocked.length === 0) lines.push(cli.nothingToRegister);
9511
+ lines.push(cli.separationNotice);
9512
+ if (response.mode === "preview" && !applyRequested && response.applyAllowed && !response.unchanged) {
9513
+ lines.push(cli.applyHint);
9514
+ }
9515
+ if (response.mode === "applied") lines.push(cli.nextPublish);
9516
+ for (const line of lines) interactive(writer, line);
9517
+ }
9518
+ function writeRegistrationJson(writer, response) {
9519
+ json(writer, terminalSafeValue(response));
9520
+ }
9521
+ function isDetailsAbsentPolicyDenial(error) {
9522
+ return error.status === 403 && error.code === "AP_POLICY_DENIED" && error.detailsAbsent;
9523
+ }
9524
+ function isUnsupportedAdminApi(error, projectAccessible) {
9525
+ if (error.status === 404) return !RESOURCE_NOT_FOUND_CODES.has(error.code);
9526
+ return isDetailsAbsentPolicyDenial(error) && projectAccessible === true;
9527
+ }
9528
+ function registrationFailure(error, phase, messages, projectAccessible) {
9529
+ if (!(error instanceof AdminApiClientError)) return error;
9530
+ const stop = (reason2, message) => new OAuthScopeRegistrationCommandError(error.code, reason2, message, error.status);
9531
+ if (phase === "preview" && isUnsupportedAdminApi(error, projectAccessible)) {
9532
+ return stop("oauth_scope_registration_unsupported", messages.unsupportedAdminApi);
9533
+ }
9534
+ if (phase === "preview" && (isDetailsAbsentPolicyDenial(error) && projectAccessible === false || error.code === "AP_INVALID_SCOPE")) {
9535
+ return stop("oauth_scope_registration_project_access_denied", messages.projectAccessDenied);
9536
+ }
9537
+ const reason = error.scopeRegistrationReason;
9538
+ switch (reason) {
9539
+ case "oauth_scope_registration_source_stale":
9540
+ case "oauth_scope_registration_registry_changed":
9541
+ case "oauth_scope_registration_plan_stale":
9542
+ return stop(reason, messages.stale);
9543
+ case "scope_registration_publish_gate_failed":
9544
+ return error.publishGateToolNames === void 0 ? error : stop(
9545
+ reason,
9546
+ messages.publishGateFailed(
9547
+ error.publishGateToolNames.map((name) => terminalSafeText(name))
9548
+ )
9549
+ );
9550
+ case "saved_draft_not_latest":
9551
+ return stop(reason, messages.draftNotLatest);
9552
+ case "saved_drafts_mixed_connectors":
9553
+ return stop(reason, messages.draftsMixedConnectors);
9554
+ case "saved_draft_fields_inconsistent":
9555
+ return stop(reason, messages.draftFieldsInconsistent);
9556
+ case "marketplace_managed_tool":
9557
+ return stop(reason, messages.marketplaceManaged);
9558
+ case "publication_candidate_commitment_mismatch":
9559
+ return stop(reason, messages.candidateMismatch);
9560
+ case "publication_candidate_too_large":
9561
+ return stop(reason, messages.candidateTooLarge);
9562
+ case "oauth_scope_registration_blocked":
9563
+ return stop(reason, messages.blockedNotApplied);
9564
+ default:
9565
+ break;
9566
+ }
9567
+ if (phase === "apply" && error.code === "AP_RESULT_UNKNOWN") {
9568
+ return stop("oauth_scope_registration_result_unknown", messages.resultUnknown);
9569
+ }
9570
+ if (phase === "apply" && reason === void 0 && (error.code === "AP_POLICY_DENIED" || error.code === "AP_INVALID_SCOPE")) {
9571
+ return stop("oauth_scope_registration_write_role_required", messages.writeRoleRequired);
9572
+ }
9573
+ return error;
9574
+ }
9575
+ async function projectAccessibility(client, projectId, error) {
9576
+ if (!(error instanceof AdminApiClientError) || !isDetailsAbsentPolicyDenial(error)) {
9577
+ return void 0;
8884
9578
  }
8885
- let uri;
8886
9579
  try {
8887
- uri = new URL(details.verificationUri);
9580
+ await client.getOAuthSetup(projectId);
9581
+ return true;
8888
9582
  } catch {
8889
- throw responseInvalid("publication_verification_uri_invalid", messages);
8890
- }
8891
- const expectedPath = `/projects/${projectId}/tools/publications/${details.publicationId}`;
8892
- if (uri.origin !== "https://admin.andpipe.com" || uri.pathname !== expectedPath || uri.username !== "" || uri.password !== "" || uri.search !== "" || uri.hash !== "" || uri.toString() !== details.verificationUri) {
8893
- throw responseInvalid("publication_verification_uri_invalid", messages);
8894
- }
8895
- return {
8896
- requestId: details.requestId,
8897
- publicationId: details.publicationId,
8898
- verificationUri: details.verificationUri,
8899
- expiresIn: 600,
8900
- pollInterval: details.pollInterval
8901
- };
8902
- }
8903
- function approvedApplyResultMayBeUnknown(error) {
8904
- const status = typedStatus2(error);
8905
- if (status !== void 0 && status >= 400 && status < 500) return false;
8906
- const code = typedCode2(error);
8907
- return code === void 0 || !DEFINITIVE_APPLY_ERROR_CODES.has(code);
8908
- }
8909
- function initialApplyResultMayBeUnknown(error) {
8910
- const status = typedStatus2(error);
8911
- if (status !== void 0 && status >= 400 && status < 500) return false;
8912
- const code = typedCode2(error);
8913
- if (status === void 0 && code !== void 0 && DEFINITIVE_APPLY_ERROR_CODES.has(code)) {
8914
9583
  return false;
8915
9584
  }
8916
- return true;
8917
- }
8918
- function writeSafeJson(writer, value) {
8919
- json(writer, terminalSafeValue(value));
8920
- }
8921
- function writePlan(writer, plan) {
8922
- writeSafeJson(writer, { phase: "plan", ...plan });
8923
9585
  }
8924
- function writeResult(writer, result) {
8925
- writeSafeJson(writer, { phase: "result", ...result });
8926
- }
8927
- function freezeJson(value) {
8928
- if (Array.isArray(value)) {
8929
- for (const item of value) freezeJson(item);
8930
- return Object.freeze(value);
8931
- }
8932
- if (value !== null && typeof value === "object") {
8933
- for (const item of Object.values(value)) freezeJson(item);
8934
- return Object.freeze(value);
9586
+ function localCandidateSource(normalized, cwd, runtime, locale) {
9587
+ const messages = import_localization10.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9588
+ const publishMessages = import_localization10.CLI_MESSAGES[locale].publish;
9589
+ const project = loadPublicationProject(runtime.loadProject, cwd, publishMessages);
9590
+ const projectId = assertManifestProject(project, normalized.projectId, publishMessages);
9591
+ const connectorId = normalized.connectorId ?? project.manifest.connector_id;
9592
+ if (connectorId === void 0) throw new UsageError(messages.connectorRequired);
9593
+ let candidate;
9594
+ try {
9595
+ candidate = buildLocalPublicationCandidate(project, connectorId, publishMessages);
9596
+ } catch (error) {
9597
+ if (error instanceof import_tool_contract10.PublicationCanonicalizationError && error.reason === "publication_value_too_large") {
9598
+ throw new OAuthScopeRegistrationCommandError(
9599
+ "AP_INPUT_INVALID",
9600
+ "publication_candidate_too_large",
9601
+ messages.candidateTooLarge
9602
+ );
9603
+ }
9604
+ throw error;
8935
9605
  }
8936
- return value;
8937
- }
8938
- function prepareCandidate(project) {
8939
- const canonical = (0, import_tool_contract10.assertCanonicalPublicationSize)(project.contract.root);
8940
- const candidateContract = freezeJson(JSON.parse(canonical));
8941
9606
  return {
8942
- candidateContract,
8943
- candidateCommitment: (0, import_tool_contract10.publicationCommitment)("candidate", candidateContract)
9607
+ projectId,
9608
+ source: {
9609
+ kind: "publication_candidate",
9610
+ connectorId,
9611
+ candidateContract: candidate.planRequest.candidateContract,
9612
+ candidateCommitment: candidate.planRequest.candidateCommitment
9613
+ },
9614
+ expectedToolNames: candidate.expectedToolNames
8944
9615
  };
8945
9616
  }
8946
- function assertIdempotencyKey2(value, messages) {
8947
- if (!UUID_RE6.test(value)) {
8948
- throw new PublishCommandError(
8949
- "AP_NETWORK_ERROR",
8950
- "secure_random_invalid",
8951
- messages.failure("secure_random_invalid")
9617
+ async function runOAuthScopeRegisterCommand(options, writer, cwd, runtime, locale = import_localization10.DEFAULT_LOCALE) {
9618
+ const messages = import_localization10.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale];
9619
+ const normalized = normalizeOAuthScopeRegisterOptions(options, locale);
9620
+ const target = normalized.kind === "saved_drafts" ? {
9621
+ projectId: normalized.projectId,
9622
+ source: { kind: "saved_drafts", drafts: normalized.drafts },
9623
+ expectedToolNames: void 0
9624
+ } : localCandidateSource(normalized, cwd, runtime, locale);
9625
+ const client = runtime.createClient(normalized.profile);
9626
+ let preview;
9627
+ try {
9628
+ preview = await client.registerOAuthScopes({
9629
+ projectId: target.projectId,
9630
+ source: target.source,
9631
+ apply: false
9632
+ });
9633
+ } catch (error) {
9634
+ throw registrationFailure(
9635
+ error,
9636
+ "preview",
9637
+ messages.cli,
9638
+ await projectAccessibility(client, target.projectId, error)
8952
9639
  );
8953
9640
  }
8954
- return value;
8955
- }
8956
- async function sendInitialApplyWithSameAnchorRetry(input) {
8957
- for (let attempt = 0; attempt < INITIAL_APPLY_MAX_ATTEMPTS; attempt += 1) {
8958
- try {
8959
- const result = parsePublicationResult(
8960
- await input.client.applyPublication(input.projectId, input.idempotencyKey, input.body),
8961
- input.plan,
8962
- input.messages
9641
+ if (target.expectedToolNames !== void 0 && JSON.stringify(preview.source.tools.map((tool) => tool.toolName)) !== JSON.stringify(target.expectedToolNames)) {
9642
+ throw new OAuthScopeRegistrationCommandError(
9643
+ "AP_RESPONSE_INVALID",
9644
+ "oauth_scope_registration_tools_mismatch",
9645
+ messages.cli.responseMismatch
9646
+ );
9647
+ }
9648
+ writeRegistrationJson(writer, preview);
9649
+ writeRegistrationSummary(writer, preview, normalized.apply, messages);
9650
+ if (!preview.applyAllowed) {
9651
+ if (normalized.apply) {
9652
+ throw new OAuthScopeRegistrationCommandError(
9653
+ "AP_POLICY_DENIED",
9654
+ "oauth_scope_registration_blocked",
9655
+ messages.cli.blockedNotApplied
8963
9656
  );
8964
- if (result.state !== "noop") {
8965
- throw responseInvalid("publication_initial_apply_state_invalid", input.messages);
8966
- }
8967
- return {
8968
- kind: "response",
8969
- result
8970
- };
8971
- } catch (error) {
8972
- let malformedConfirmationAnchor = false;
8973
- let confirmationRequired = null;
8974
- try {
8975
- confirmationRequired = parseConfirmationRequired(error, input.projectId, input.messages);
8976
- } catch (parseError) {
8977
- if (typedCode2(error) !== "AP_CONFIRMATION_REQUIRED" || !(parseError instanceof PublishCommandError) || parseError.code !== "AP_RESPONSE_INVALID") {
8978
- throw parseError;
8979
- }
8980
- malformedConfirmationAnchor = true;
8981
- }
8982
- if (confirmationRequired) {
8983
- return { kind: "confirmation_required", details: confirmationRequired };
8984
- }
8985
- if (!malformedConfirmationAnchor && !initialApplyResultMayBeUnknown(error)) {
8986
- throw remoteError(error, "initial_apply", input.messages);
8987
- }
8988
- if (attempt === INITIAL_APPLY_MAX_ATTEMPTS - 1) {
8989
- throw new PublishCommandError(
8990
- "AP_RESULT_UNKNOWN",
8991
- "publication_anchor_result_unknown",
8992
- input.messages.proposalResultUnknown
8993
- );
8994
- }
8995
9657
  }
9658
+ return { ok: false };
9659
+ }
9660
+ if (!normalized.apply) return { ok: true };
9661
+ const idempotencyKey = runtime.randomUuid().toLowerCase();
9662
+ if (!RFC_UUID_RE.test(idempotencyKey)) {
9663
+ throw new OAuthScopeRegistrationCommandError(
9664
+ "AP_NETWORK_ERROR",
9665
+ "secure_random_invalid",
9666
+ import_localization10.CLI_MESSAGES[locale].publish.failure("secure_random_invalid")
9667
+ );
8996
9668
  }
8997
- throw new PublishCommandError(
8998
- "AP_RESULT_UNKNOWN",
8999
- "publication_anchor_result_unknown",
9000
- input.messages.proposalResultUnknown
9001
- );
9002
- }
9003
- function confirmationStopped(code, reason, messages) {
9004
- return new PublishCommandError(code, reason, messages.confirmationStopped(reason));
9669
+ let applied;
9670
+ try {
9671
+ applied = await client.registerOAuthScopes({
9672
+ projectId: target.projectId,
9673
+ source: target.source,
9674
+ apply: true,
9675
+ sourceCommitment: preview.sourceCommitment,
9676
+ baseRegistryCommitment: preview.baseRegistryCommitment,
9677
+ planCommitment: preview.planCommitment,
9678
+ idempotencyKey
9679
+ });
9680
+ } catch (error) {
9681
+ throw registrationFailure(error, "apply", messages.cli);
9682
+ }
9683
+ writeRegistrationJson(writer, applied);
9684
+ writeRegistrationSummary(writer, applied, true, messages);
9685
+ return { ok: true };
9005
9686
  }
9006
- function pollFailureIsDefinitive(error) {
9007
- const status = typedStatus2(error);
9008
- if (status !== void 0 && status >= 400 && status < 500) return true;
9009
- const code = typedCode2(error);
9010
- return code === "AP_RESPONSE_INVALID" || code === "AP_OUTPUT_INVALID" || code !== void 0 && DEFINITIVE_APPLY_ERROR_CODES.has(code);
9687
+ function upstreamOAuthWizardUrl(profile, projectId, connectorId) {
9688
+ const record = getProfile(profile);
9689
+ if (!record)
9690
+ throw new UsageError(`\u8A8D\u8A3Cprofile ${profile} \u304C\u3042\u308A\u307E\u305B\u3093\u3002andpipe login\u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044`);
9691
+ const url = new URL(`/projects/${projectId}/oauth`, new URL(record.verificationUriBase).origin);
9692
+ url.searchParams.set("connector", connectorId);
9693
+ return url.toString();
9011
9694
  }
9012
- async function sleepForPoll(runtime, milliseconds, mode, messages) {
9695
+ async function loadOAuthMetadata(opts, locale) {
9696
+ const messages = import_localization10.CLI_MESSAGES[locale];
9697
+ if (opts.file && opts.issuer) {
9698
+ throw new UsageError("--file \u3068 --issuer \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");
9699
+ }
9700
+ if (opts.issuer) {
9701
+ return fetchOAuthMetadata(opts.issuer);
9702
+ }
9703
+ if (!opts.file) {
9704
+ throw new UsageError(messages.oauth.fileRequired);
9705
+ }
9013
9706
  try {
9014
- await runtime.sleep(milliseconds);
9015
- } catch {
9016
- throw new PublishCommandError(
9017
- mode === "recover-result" ? "AP_RESULT_UNKNOWN" : "AP_NETWORK_ERROR",
9018
- "publication_poll_sleep_failed",
9019
- messages.pollingUnavailable
9020
- );
9707
+ return JSON.parse((0, import_node_fs11.readFileSync)(opts.file, "utf8"));
9708
+ } catch (error) {
9709
+ throw new UsageError(messages.oauth.metadataReadFailed(error.message));
9021
9710
  }
9022
9711
  }
9023
- async function pollPublication(client, projectId, details, plan, writer, runtime, mode, messages, knownExpiresAt) {
9024
- const startedAt = runtime.monotonicNow();
9025
- let deadline = startedAt + details.expiresIn * 1e3;
9026
- let expiresAt = knownExpiresAt;
9027
- if (knownExpiresAt !== void 0) {
9028
- deadline = Math.min(
9029
- deadline,
9030
- startedAt + Math.max(0, Date.parse(knownExpiresAt) - runtime.wallNow())
9031
- );
9712
+ async function runOAuthMetadataValidate(opts, writer, locale) {
9713
+ const messages = import_localization10.CLI_MESSAGES[locale];
9714
+ const parsed = await loadOAuthMetadata(opts, locale);
9715
+ const report = validateOAuthMetadata(parsed, locale);
9716
+ json(writer, report.results);
9717
+ if (!report.ok) {
9718
+ process.exitCode = 1;
9719
+ info(writer, messages.oauth.metadataFailed);
9720
+ } else {
9721
+ info(writer, messages.oauth.metadataOk);
9032
9722
  }
9033
- const maxAttempts = Math.ceil(details.expiresIn / details.pollInterval) + 2;
9034
- for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
9035
- let rawStatus;
9036
- try {
9037
- rawStatus = await client.getPublication(projectId, details.publicationId);
9038
- } catch (error) {
9039
- if (pollFailureIsDefinitive(error)) {
9040
- throw remoteError(error, mode === "recover-result" ? "result_recovery" : "poll", messages);
9041
- }
9042
- const remainingMilliseconds2 = Math.max(0, deadline - runtime.monotonicNow());
9043
- if (remainingMilliseconds2 <= 0 || attempt === maxAttempts - 1) {
9044
- throw new PublishCommandError(
9045
- mode === "recover-result" ? "AP_RESULT_UNKNOWN" : "AP_NETWORK_ERROR",
9046
- "publication_poll_unavailable",
9047
- messages.pollingUnavailable
9048
- );
9723
+ }
9724
+ function registerOauth(program, writer, locale = import_localization10.DEFAULT_LOCALE, dependencies = {}) {
9725
+ const messages = import_localization10.CLI_MESSAGES[locale];
9726
+ const oauth = program.command("oauth").description(messages.oauth.commandDescription);
9727
+ oauth.command("init").description(messages.oauth.initDescription).requiredOption("--provider <name>", messages.oauth.providerOption).action((opts) => {
9728
+ info(writer, messages.oauth.templateHeading(opts.provider));
9729
+ json(writer, buildInitTemplate(opts.provider));
9730
+ info(writer, messages.oauth.clientSecretEnvNotice);
9731
+ });
9732
+ oauth.command("validate").description(messages.oauth.validateDescription).option("--file <path>", messages.common.metadataFileOption).option("--issuer <url>", messages.common.issuerOption).option("--project <project>", messages.common.projectOption).option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).action(async (opts) => {
9733
+ if (opts.project) {
9734
+ if (opts.file || opts.issuer) {
9735
+ throw new UsageError("--project \u306F --file / --issuer \u3068\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");
9049
9736
  }
9050
- await sleepForPoll(
9051
- runtime,
9052
- Math.min(details.pollInterval * 1e3, remainingMilliseconds2),
9053
- mode,
9054
- messages
9737
+ const projectId = assertProjectId(opts.project);
9738
+ const result = await createAdminApiClient({ profile: opts.profile }).getOAuthSetup(
9739
+ projectId
9055
9740
  );
9056
- continue;
9057
- }
9058
- const status = parseStatus(rawStatus, details.publicationId, plan, messages);
9059
- if (expiresAt !== void 0 && status.expiresAt !== expiresAt) {
9060
- throw responseInvalid("publication_expiry_changed", messages);
9061
- }
9062
- expiresAt = status.expiresAt;
9063
- const now = runtime.monotonicNow();
9064
- const wallRemaining = Math.max(0, Date.parse(status.expiresAt) - runtime.wallNow());
9065
- deadline = Math.min(deadline, now + wallRemaining);
9066
- const remainingMilliseconds = Math.max(0, deadline - now);
9067
- writeSafeJson(writer, {
9068
- phase: mode === "recover-result" ? "result_recovery" : "confirmation",
9069
- requestId: status.requestId,
9070
- publicationId: status.publicationId,
9071
- durableState: status.durableState,
9072
- effectiveState: status.effectiveState,
9073
- expiresAt: status.expiresAt,
9074
- remainingSeconds: Math.ceil(remainingMilliseconds / 1e3)
9075
- });
9076
- if (status.durableState === "consumed") {
9077
- return { kind: "consumed", result: status.result };
9078
- }
9079
- if (status.durableState === "rejected") {
9080
- throw confirmationStopped("AP_POLICY_DENIED", "publication_rejected", messages);
9741
+ json(writer, result);
9742
+ if (result.metadata.status !== "valid" || result.alignment.issues.length > 0) {
9743
+ process.exitCode = 1;
9744
+ }
9745
+ return;
9081
9746
  }
9082
- if (status.durableState === "expired") {
9083
- throw confirmationStopped(
9084
- "AP_CONFIRMATION_EXPIRED",
9085
- "publication_confirmation_expired",
9086
- messages
9747
+ await runOAuthMetadataValidate(opts, writer, locale);
9748
+ });
9749
+ const scopes = oauth.command("scopes").description(messages.oauth.scopesDescription);
9750
+ scopes.command("sync").description(messages.oauth.scopesSyncDescription).requiredOption("--project <project>", messages.common.projectOption).option("--apply", "preview\u7D50\u679C\u3092production\u3078\u53CD\u6620\u3059\u308B", false).option("--yes", messages.domain.yesOption, false).option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).action(async (opts) => {
9751
+ const operation = "andpipe oauth scopes sync";
9752
+ if (opts.apply && !opts.yes) {
9753
+ throw new ConfirmationRequiredError(
9754
+ operation,
9755
+ messages.common.confirmationRequiredMessage(operation)
9087
9756
  );
9088
9757
  }
9089
- if (status.effectiveState === "stale") {
9090
- throw confirmationStopped("AP_CONFLICT", "publication_confirmation_stale", messages);
9091
- }
9092
- if (mode === "await-approval" && status.durableState === "approved" && status.confirmation !== null) {
9093
- return {
9094
- kind: "approved",
9095
- confirmation: status.confirmation,
9096
- expiresAt: status.expiresAt
9097
- };
9758
+ if (!opts.apply && opts.yes) {
9759
+ throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9098
9760
  }
9099
- if (remainingMilliseconds <= 0) {
9100
- throw confirmationStopped(
9101
- "AP_CONFIRMATION_EXPIRED",
9102
- "publication_confirmation_timeout",
9103
- messages
9104
- );
9761
+ const projectId = assertProjectId(opts.project);
9762
+ const result = await createAdminApiClient({ profile: opts.profile }).syncOAuthScopes({
9763
+ projectId,
9764
+ apply: opts.apply
9765
+ });
9766
+ json(writer, result);
9767
+ });
9768
+ const registration = import_localization10.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9769
+ const scopeRegisterRuntime = dependencies.scopeRegisterRuntime ?? createOAuthScopeRegisterRuntime();
9770
+ const cwd = dependencies.cwd ?? (() => process.cwd());
9771
+ scopes.command("register").description(registration.commandDescription).option("--project <project-uuid>", registration.projectOption).option("--connector <connector-uuid>", registration.connectorOption).option(
9772
+ "--draft <toolId:versionId>",
9773
+ registration.draftOption,
9774
+ (value, previous) => [...previous, value],
9775
+ []
9776
+ ).option("--apply", registration.applyOption, false).option("--yes", registration.yesOption, false).option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).action(async (opts) => {
9777
+ const result = await runOAuthScopeRegisterCommand(
9778
+ opts,
9779
+ writer,
9780
+ cwd(),
9781
+ scopeRegisterRuntime,
9782
+ locale
9783
+ );
9784
+ if (!result.ok) process.exitCode = 1;
9785
+ });
9786
+ const clients = oauth.command("clients").description("OAuth client\u306Escope\u5272\u5F53\u3092\u7BA1\u7406\u3059\u308B");
9787
+ clients.command("map-scopes").description("\u9078\u629E\u3057\u305Fproject client\u3078\u5FC5\u8981scope\u3092preview\u307E\u305F\u306F\u660E\u793A\u9069\u7528\u3059\u308B").requiredOption("--project <project>", messages.common.projectOption).requiredOption("--client <client-registry-uuid>", "oauth-setup\u306B\u8868\u793A\u3055\u308C\u305Fclient registry ID").option("--apply", "preview\u7D50\u679C\u3092\u9078\u629Eclient\u3078\u53CD\u6620\u3059\u308B", false).option("--yes", messages.domain.yesOption, false).option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).action(
9788
+ async (opts) => {
9789
+ const operation = "andpipe oauth clients map-scopes";
9790
+ if (opts.apply && !opts.yes) {
9791
+ throw new ConfirmationRequiredError(
9792
+ operation,
9793
+ messages.common.confirmationRequiredMessage(operation)
9794
+ );
9795
+ }
9796
+ if (!opts.apply && opts.yes) {
9797
+ throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9798
+ }
9799
+ const client = createAdminApiClient({ profile: opts.profile });
9800
+ const preview = await client.mapOAuthClientScopes({
9801
+ projectId: assertProjectId(opts.project),
9802
+ clientRegistryId: opts.client,
9803
+ apply: false
9804
+ });
9805
+ json(writer, preview);
9806
+ if (!opts.apply) return;
9807
+ const applied = await client.mapOAuthClientScopes({
9808
+ projectId: assertProjectId(opts.project),
9809
+ clientRegistryId: opts.client,
9810
+ apply: true,
9811
+ requiredScopesCommitment: preview.requiredScopesCommitment,
9812
+ baseClientGrantCommitment: preview.baseClientGrantCommitment,
9813
+ candidateClientGrantCommitment: preview.candidateClientGrantCommitment,
9814
+ planCommitment: preview.planCommitment
9815
+ });
9816
+ json(writer, applied);
9105
9817
  }
9106
- const sleepMilliseconds = Math.min(details.pollInterval * 1e3, remainingMilliseconds);
9107
- await sleepForPoll(runtime, sleepMilliseconds, mode, messages);
9108
- }
9109
- throw confirmationStopped("AP_CONFIRMATION_EXPIRED", "publication_poll_attempt_limit", messages);
9110
- }
9111
- async function runPublishCommand(options, writer, cwd, runtime, messages = DEFAULT_PUBLISH_MESSAGES) {
9112
- const normalized = normalizePublishOptions(options, messages);
9113
- let project;
9114
- try {
9115
- project = runtime.loadProject(cwd);
9116
- } catch (error) {
9117
- if (error instanceof LocalFilePolicyError) {
9118
- throw new PublishCommandError(
9119
- "AP_POLICY_DENIED",
9120
- error.reason,
9121
- messages.failure(error.reason)
9818
+ );
9819
+ const metadata = oauth.command("metadata").description(messages.oauth.metadataDescription);
9820
+ metadata.command("validate").description(messages.oauth.validateDescription).option("--file <path>", messages.common.metadataFileOption).option("--issuer <url>", messages.common.issuerOption).action(async (opts) => {
9821
+ await runOAuthMetadataValidate(opts, writer, locale);
9822
+ });
9823
+ const connect = oauth.command("connect").description(
9824
+ locale === "ja" ? "\u9867\u5BA2SaaS\u306EOAuth account linking\u3092Web Admin\u3068\u540C\u3058\u72B6\u614B\u3067\u8A2D\u5B9A" : "Configure customer SaaS OAuth account linking with shared Web Admin state"
9825
+ );
9826
+ connect.command("status").description(
9827
+ locale === "ja" ? "\u63A5\u7D9A\u72B6\u614B\u3068\u6B21\u306E\u64CD\u4F5C\u3092\u8868\u793A" : "Show connection state and next action"
9828
+ ).requiredOption("--project <project>", messages.common.projectOption).requiredOption("--connector <connector>", "\u63A5\u7D9A\u5BFE\u8C61connector UUID").option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).action(async (opts) => {
9829
+ const state = await createAdminApiClient({
9830
+ profile: opts.profile
9831
+ }).getUpstreamOAuthConnectionState(assertProjectId(opts.project), opts.connector);
9832
+ json(writer, state);
9833
+ if (!state.allGreen) process.exitCode = 1;
9834
+ });
9835
+ connect.command("open").description(
9836
+ locale === "ja" ? "\u540C\u3058\u63A5\u7D9A\u72B6\u614B\u3092\u78BA\u8A8D\u3057\u3066Web Admin\u30A6\u30A3\u30B6\u30FC\u30C9\u3092\u958B\u304F" : "Check shared state and open the Web Admin wizard"
9837
+ ).requiredOption("--project <project>", messages.common.projectOption).requiredOption("--connector <connector>", "\u63A5\u7D9A\u5BFE\u8C61connector UUID").option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).option(
9838
+ "--no-browser",
9839
+ locale === "ja" ? "\u65E2\u5B9A\u30D6\u30E9\u30A6\u30B6\u3092\u958B\u304B\u305AURL\u3060\u3051\u8868\u793A" : "Print the URL without opening a browser"
9840
+ ).action(
9841
+ async (opts) => {
9842
+ const projectId = assertProjectId(opts.project);
9843
+ const state = await createAdminApiClient({
9844
+ profile: opts.profile
9845
+ }).getUpstreamOAuthConnectionState(projectId, opts.connector);
9846
+ json(writer, state);
9847
+ const url = upstreamOAuthWizardUrl(opts.profile, projectId, opts.connector);
9848
+ info(
9849
+ writer,
9850
+ locale === "ja" ? `Web Admin\u3067\u7D9A\u3051\u3066\u304F\u3060\u3055\u3044: ${url}` : `Continue in Web Admin: ${url}`
9122
9851
  );
9852
+ if (opts.browser) {
9853
+ try {
9854
+ (dependencies.openBrowser ?? openBrowser)(url);
9855
+ } catch {
9856
+ }
9857
+ }
9123
9858
  }
9124
- const reason = error instanceof DevProjectLoadError ? error.reason : "local_project_invalid";
9125
- if (error instanceof DevProjectLoadError || error instanceof UsageError) {
9126
- throw new PublishCommandError("AP_INPUT_INVALID", reason, messages.failure(reason));
9127
- }
9128
- throw error;
9129
- }
9130
- const projectId = project.manifest.project_id;
9131
- const connectorId = normalized.connectorId ?? project.manifest.connector_id;
9132
- if (connectorId === void 0) {
9133
- throw new PublishCommandError(
9134
- "AP_INPUT_INVALID",
9135
- "publication_connector_required",
9136
- messages.optionRequires("publish", "--connector UUID")
9859
+ );
9860
+ oauth.command("test-login").description(messages.oauth.testLoginDescription).requiredOption("--project <project>", messages.common.projectOption).requiredOption("--client <client-registry-uuid>", "\u691C\u67FB\u5BFE\u8C61\u306Eproject OAuth client registry ID").option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).action(async (opts) => {
9861
+ const projectId = assertProjectId(opts.project);
9862
+ const result = await createAdminApiClient({ profile: opts.profile }).testOAuthLogin(
9863
+ projectId,
9864
+ opts.client
9137
9865
  );
9866
+ json(writer, result);
9867
+ if (result.status === "blocked") process.exitCode = 1;
9868
+ });
9869
+ }
9870
+
9871
+ // src/commands/openapi.ts
9872
+ var import_node_crypto14 = require("crypto");
9873
+ var import_node_path12 = require("path");
9874
+ var import_tool_contract11 = require("@andpipes/tool-contract");
9875
+ function createOpenApiImportRuntime(createClient = (profile) => createAdminApiClient({ profile })) {
9876
+ return { createClient, idempotencyKey: import_node_crypto14.randomUUID };
9877
+ }
9878
+ function normalizedOptions(options) {
9879
+ if (!options.file || !options.project || !options.connector) {
9880
+ throw new UsageError("--file\u3001--project\u3001--connector \u306F\u5FC5\u9808\u3067\u3059");
9138
9881
  }
9139
- if (normalized.projectId !== void 0 && normalized.projectId !== projectId) {
9140
- throw new PublishCommandError(
9141
- "AP_CONFLICT",
9142
- "manifest_project_mismatch",
9143
- messages.failure("manifest_project_mismatch")
9144
- );
9882
+ if (options.format !== void 0 && options.format !== "json" && options.format !== "yaml") {
9883
+ throw new UsageError("--format \u306F json \u307E\u305F\u306F yaml \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9145
9884
  }
9146
- const candidate = prepareCandidate(project);
9147
- const localToolNames = project.contract.tools.map((tool) => (0, import_tool_contract10.toolName)(tool));
9148
- if (localToolNames.some((name) => !(0, import_tool_contract10.isSafeToolName)(name))) {
9149
- throw new PublishCommandError(
9150
- "AP_INPUT_INVALID",
9151
- "publication_candidate_tool_invalid",
9152
- messages.failure("publication_candidate_tool_invalid")
9153
- );
9885
+ if (options.serviceName !== void 0 && !/^[A-Za-z0-9_]{1,48}$/.test(options.serviceName)) {
9886
+ throw new UsageError("--service-name \u306F\u82F1\u6570\u5B57\u3068 underscore \u306E1..48\u6587\u5B57\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9154
9887
  }
9155
- const expectedToolNames = localToolNames.sort(import_tool_contract10.comparePublicationUnicodeCodePoints);
9156
- const planRequest = {
9157
- environment: "production",
9158
- connectorId,
9159
- candidateContract: candidate.candidateContract,
9160
- candidateCommitment: candidate.candidateCommitment,
9161
- ...project.manifest.template_id && project.manifest.template_application_commitment ? {
9162
- templateProvenance: {
9163
- templateId: project.manifest.template_id,
9164
- applicationCommitment: project.manifest.template_application_commitment
9165
- }
9166
- } : {}
9167
- };
9168
- const client = runtime.createClient(normalized.profile);
9169
- let rawPlan;
9170
- try {
9171
- rawPlan = await client.planPublication(projectId, planRequest);
9172
- } catch (error) {
9173
- throw remoteError(error, "plan", messages);
9888
+ const apply = options.apply === true;
9889
+ const yes = options.yes === true;
9890
+ if (yes && !apply) {
9891
+ throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9174
9892
  }
9175
- const plan = parsePlan(
9176
- rawPlan,
9177
- connectorId,
9178
- candidate.candidateCommitment,
9179
- expectedToolNames,
9180
- messages
9181
- );
9182
- writePlan(writer, plan);
9183
- if (plan.blockedReasons.includes("connector_mismatch")) {
9184
- interactive(writer, messages.connectorMismatchRemediation);
9893
+ if (options.idempotencyKey !== void 0 && !apply) {
9894
+ throw new UsageError("--idempotency-key \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9185
9895
  }
9186
- if (normalized.mode === "dry-run") return;
9187
- if (!plan.applyAllowed) {
9188
- throw new PublishCommandError(
9189
- "AP_POLICY_DENIED",
9190
- "publication_plan_blocked",
9191
- messages.planBlocked(plan.blockedReasons)
9896
+ if (!apply && options.planCommitment !== void 0) {
9897
+ throw new UsageError("--plan-commitment \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9898
+ }
9899
+ return {
9900
+ file: options.file,
9901
+ project: assertProjectId(options.project),
9902
+ connectorId: assertProjectId(options.connector),
9903
+ profile: options.profile ?? DEFAULT_PROFILE_NAME,
9904
+ ...options.format !== void 0 ? { format: options.format } : {},
9905
+ ...options.baseUrl !== void 0 ? { baseUrl: options.baseUrl } : {},
9906
+ ...options.serviceName !== void 0 ? { serviceName: options.serviceName } : {},
9907
+ apply,
9908
+ yes,
9909
+ ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {},
9910
+ ...options.planCommitment !== void 0 ? { planCommitment: options.planCommitment } : {},
9911
+ ...options.authMode !== void 0 ? { upstreamAuthMode: parseAuthModeOption(options.authMode) } : {},
9912
+ sideEffectFree: parseSideEffectFreeOptions(options.sideEffectFree)
9913
+ };
9914
+ }
9915
+ function rethrowWithAuthModeGuidance(error) {
9916
+ if (error instanceof AdminApiClientError && error.openApiAuthModeMismatch) {
9917
+ throw new UsageError(authModeMismatchGuidance(error.openApiAuthModeMismatch));
9918
+ }
9919
+ throw error;
9920
+ }
9921
+ async function runOpenApiImportCommand(options, writer, cwd, runtime = createOpenApiImportRuntime()) {
9922
+ const normalized = normalizedOptions(options);
9923
+ if (normalized.apply && !normalized.yes) {
9924
+ throw new ConfirmationRequiredError(
9925
+ "andpipe openapi import --apply",
9926
+ "draft\u4F5C\u6210\u306B\u306F --apply --yes \u306E\u4E21\u65B9\u304C\u5FC5\u8981\u3067\u3059\u3002preview\u7D50\u679C\u3092\u78BA\u8A8D\u3057\u3066\u304B\u3089\u518D\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044"
9192
9927
  );
9193
9928
  }
9194
- const idempotencyKey = assertIdempotencyKey2(runtime.randomUuid(), messages);
9195
- const applyRequest = (confirmation) => ({
9196
- ...planRequest,
9197
- planCommitment: plan.planCommitment,
9198
- confirmation
9199
- });
9200
- const initialApplyRequest = freezeJson(applyRequest(null));
9201
- const initial = await sendInitialApplyWithSameAnchorRetry({
9202
- client,
9203
- projectId,
9204
- idempotencyKey,
9205
- body: initialApplyRequest,
9206
- plan,
9207
- messages
9929
+ if (normalized.apply && !/^[a-f0-9]{64}$/.test(normalized.planCommitment ?? "")) {
9930
+ throw new UsageError("--apply \u306B\u306Fpreview\u3067\u5F97\u305F --plan-commitment \u304C\u5FC5\u9808\u3067\u3059");
9931
+ }
9932
+ const snapshot = readBoundedLocalFileSnapshot((0, import_node_path12.resolve)(cwd, normalized.file), {
9933
+ maxBytes: import_tool_contract11.OPENAPI_IMPORT_MAX_SOURCE_BYTES,
9934
+ root: cwd
9208
9935
  });
9209
- let details;
9210
- if (initial.kind === "response") {
9211
- writeResult(writer, initial.result);
9212
- return;
9213
- } else {
9214
- if (plan.tools.every((tool) => !tool.changed)) {
9215
- throw responseInvalid("publication_noop_confirmation_invalid", messages);
9936
+ const baseRequest = {
9937
+ source: snapshot.text,
9938
+ connectorId: normalized.connectorId,
9939
+ ...normalized.format !== void 0 ? { format: normalized.format } : {},
9940
+ ...normalized.baseUrl !== void 0 ? { baseUrl: normalized.baseUrl } : {},
9941
+ ...normalized.serviceName !== void 0 ? { serviceName: normalized.serviceName } : {},
9942
+ ...normalized.upstreamAuthMode !== void 0 ? { upstreamAuthMode: normalized.upstreamAuthMode } : {}
9943
+ };
9944
+ const client = runtime.createClient(normalized.profile);
9945
+ const assertSource = (sourceCommitment) => {
9946
+ if (sourceCommitment !== snapshot.sha256) {
9947
+ throw new UsageError("Admin API\u306Esource commitment\u304Clocal file\u3068\u4E00\u81F4\u3057\u307E\u305B\u3093");
9216
9948
  }
9217
- details = initial.details;
9218
- }
9219
- writeSafeJson(writer, { phase: "confirmation_required", ...details });
9220
- const decision = await pollPublication(
9221
- client,
9222
- projectId,
9223
- details,
9224
- plan,
9225
- writer,
9226
- runtime,
9227
- "await-approval",
9228
- messages
9229
- );
9230
- if (decision.kind === "consumed") {
9231
- writeResult(writer, decision.result);
9232
- return;
9233
- }
9234
- try {
9235
- const result = parsePublicationResult(
9236
- await client.applyPublication(projectId, idempotencyKey, applyRequest(decision.confirmation)),
9237
- plan,
9238
- messages,
9239
- details.publicationId
9240
- );
9241
- writeResult(writer, result);
9242
- return;
9243
- } catch (error) {
9244
- if (error instanceof PublishCommandError && error.code === "AP_RESPONSE_INVALID") {
9245
- } else if (!approvedApplyResultMayBeUnknown(error)) {
9246
- throw remoteError(error, "approved_apply", messages);
9949
+ };
9950
+ let overrides = [];
9951
+ if (normalized.sideEffectFree.length > 0) {
9952
+ if (normalized.apply) {
9953
+ try {
9954
+ const unclassified = (0, import_tool_contract11.importOpenApi)(snapshot.text, {
9955
+ format: normalized.format,
9956
+ baseUrl: normalized.baseUrl,
9957
+ serviceName: normalized.serviceName,
9958
+ upstreamAuthMode: normalized.upstreamAuthMode
9959
+ });
9960
+ overrides = resolveOperationRiskOverrides(
9961
+ normalized.sideEffectFree,
9962
+ unclassified.operations
9963
+ );
9964
+ } catch (error) {
9965
+ if (error instanceof import_tool_contract11.OpenApiImportError) {
9966
+ throw new UsageError(`OpenAPI\u304B\u3089Tool Contract\u3092\u751F\u6210\u3067\u304D\u307E\u305B\u3093: ${error.message}`);
9967
+ }
9968
+ throw error;
9969
+ }
9970
+ } else {
9971
+ const unclassified = await client.planOpenApiImport(normalized.project, baseRequest).catch(rethrowWithAuthModeGuidance);
9972
+ assertSource(unclassified.sourceCommitment);
9973
+ overrides = resolveOperationRiskOverrides(normalized.sideEffectFree, unclassified.operations);
9247
9974
  }
9248
9975
  }
9249
- const recovered = await pollPublication(
9250
- client,
9251
- projectId,
9252
- details,
9253
- plan,
9254
- writer,
9255
- runtime,
9256
- "recover-result",
9257
- messages,
9258
- decision.expiresAt
9259
- );
9260
- if (recovered.kind !== "consumed") {
9261
- throw new PublishCommandError(
9262
- "AP_RESULT_UNKNOWN",
9263
- "publication_result_unknown",
9264
- messages.resultUnknown
9265
- );
9976
+ const request = {
9977
+ ...baseRequest,
9978
+ ...overrides.length > 0 ? { operationRiskOverrides: overrides } : {},
9979
+ ...normalized.planCommitment !== void 0 ? { expectedPlanCommitment: normalized.planCommitment } : {}
9980
+ };
9981
+ const classification = {
9982
+ upstreamAuthMode: normalized.upstreamAuthMode ?? "token_exchange",
9983
+ operationRiskOverrides: overrides
9984
+ };
9985
+ if (!normalized.apply) {
9986
+ const result2 = await client.planOpenApiImport(normalized.project, request).catch(rethrowWithAuthModeGuidance);
9987
+ assertSource(result2.sourceCommitment);
9988
+ json(writer, { mode: "preview", ...classification, ...result2 });
9989
+ const guidance = sideEffectFreeGuidance(result2.operations);
9990
+ if (guidance) interactive(writer, guidance);
9991
+ return;
9266
9992
  }
9267
- writeResult(writer, recovered.result);
9993
+ const result = await client.applyOpenApiImport(
9994
+ normalized.project,
9995
+ normalized.idempotencyKey ?? runtime.idempotencyKey(),
9996
+ request
9997
+ ).catch(rethrowWithAuthModeGuidance);
9998
+ assertSource(result.sourceCommitment);
9999
+ json(writer, { mode: "draft_created", ...classification, ...result });
9268
10000
  }
9269
- 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) {
9270
- 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) => {
9271
- await runPublishCommand(commandOptions, writer, cwd(), runtime, messages);
9272
- });
10001
+ function collect(value, previous) {
10002
+ return [...previous, value];
10003
+ }
10004
+ function registerOpenApi(program, writer, cwd, runtime = createOpenApiImportRuntime()) {
10005
+ const openapi = program.command("openapi").description("OpenAPI\u304B\u3089Tool Contract draft\u3092\u63D0\u6848\u3059\u308B");
10006
+ openapi.command("import").description("OpenAPI 3.0/3.1 file\u3092\u5B89\u5168\u306Bpreview\u307E\u305F\u306Fdraft\u5316\u3059\u308B").requiredOption("--file <path>", "project root\u5185\u306EOpenAPI JSON/YAML file").requiredOption("--project <uuid>", "\u5BFE\u8C61project UUID").requiredOption("--connector <uuid>", "draft\u3092\u675F\u7E1B\u3059\u308Bactive connector UUID").option("--profile <name>", "Admin CLI profile", DEFAULT_PROFILE_NAME).option("--format <format>", "json\u307E\u305F\u306Fyaml\uFF08\u7701\u7565\u6642\u306F\u81EA\u52D5\u5224\u5B9A\uFF09").option("--base-url <url>", "document servers\u3092\u4E0A\u66F8\u304D\u3059\u308BHTTPS public base URL").option("--service-name <name>", "fallback tool/scope\u306Eservice\u540D").option("--apply", "preview\u6E08\u307Fproposal\u3092draft\u3068\u3057\u3066\u4FDD\u5B58\u3059\u308B", false).option("--yes", "draft\u4F5C\u6210\u3092\u660E\u793A\u78BA\u8A8D\u3059\u308B", false).option("--idempotency-key <key>", "\u518D\u9001\u7528Idempotency-Key").option("--plan-commitment <sha256>", "preview\u3067\u5F97\u305Fsafe plan commitment").option(
10007
+ "--auth-mode <mode>",
10008
+ "connector\u3068\u540C\u3058\u8A8D\u8A3C\u65B9\u5F0F\uFF08existing_oauth \u307E\u305F\u306F token_exchange\u3002\u7701\u7565\u6642\u306Ftoken_exchange\uFF09"
10009
+ ).option(
10010
+ "--side-effect-free <toolName=level>",
10011
+ "\u30C7\u30FC\u30BF\u3092\u4FDD\u5B58\u30FB\u5909\u66F4\u30FB\u9001\u4FE1\u3057\u306A\u3044POST\u3060\u3051\u3092read\u307E\u305F\u306Fdraft\u3078\u660E\u793A\u5206\u985E\u3059\u308B\uFF08\u7E70\u308A\u8FD4\u3057\u6307\u5B9A\u53EF\uFF09",
10012
+ collect,
10013
+ []
10014
+ ).action(
10015
+ (options) => runOpenApiImportCommand(options, writer, cwd(), runtime)
10016
+ );
9273
10017
  }
9274
10018
 
9275
10019
  // src/commands/review-package.ts
@@ -9394,6 +10138,7 @@ function registerValidate(program, writer, cwd, locale = import_localization12.D
9394
10138
  function buildProgram(writer = defaultWriter, cwd = () => process.cwd(), locale = (0, import_localization13.normalizeLocale)(process.env.ANDPIPE_LOCALE ?? process.env.LANG)) {
9395
10139
  const text = import_localization13.LOCALIZED_TEXT[locale].cli;
9396
10140
  const messages = import_localization13.CLI_MESSAGES[locale];
10141
+ const scopeRegistrationMessages = import_localization13.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9397
10142
  const program = new import_commander.Command();
9398
10143
  program.name(CLI_NAME).description(text.description).option("--locale <locale>", messages.localeOption, import_localization13.DEFAULT_LOCALE).version(readVersion());
9399
10144
  registerAuth(program, writer, locale);
@@ -9405,13 +10150,14 @@ function buildProgram(writer = defaultWriter, cwd = () => process.cwd(), locale
9405
10150
  (profile) => createAdminApiClient({ profile }),
9406
10151
  text.initDescription,
9407
10152
  void 0,
9408
- messages.init
10153
+ messages.init,
10154
+ scopeRegistrationMessages
9409
10155
  );
9410
10156
  registerDev(program, writer, cwd, void 0, text.devDescription, messages.dev);
9411
10157
  registerValidate(program, writer, cwd, locale);
9412
10158
  registerReviewPackage(program, writer, locale, cwd);
9413
10159
  registerDomain(program, writer, locale);
9414
- registerOauth(program, writer, locale);
10160
+ registerOauth(program, writer, locale, { cwd });
9415
10161
  registerOpenApi(program, writer, cwd);
9416
10162
  registerConfigMcp(program, writer, locale);
9417
10163
  registerDoctor(program, writer, locale);
@@ -9424,7 +10170,9 @@ function buildProgram(writer = defaultWriter, cwd = () => process.cwd(), locale
9424
10170
  (profile) => createAdminApiClient({ profile }),
9425
10171
  text.publishDescription,
9426
10172
  void 0,
9427
- messages.publish
10173
+ messages.publish,
10174
+ scopeRegistrationMessages,
10175
+ import_localization13.PUBLICATION_SCHEMA_REVIEW_CLI_MESSAGES[locale]
9428
10176
  );
9429
10177
  return program;
9430
10178
  }