@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.
@@ -34,7 +34,9 @@ import {
34
34
  CLI_MESSAGES as CLI_MESSAGES12,
35
35
  DEFAULT_LOCALE as DEFAULT_LOCALE10,
36
36
  LOCALIZED_TEXT as LOCALIZED_TEXT4,
37
- normalizeLocale
37
+ normalizeLocale,
38
+ OAUTH_SCOPE_REGISTRATION_MESSAGES as OAUTH_SCOPE_REGISTRATION_MESSAGES4,
39
+ PUBLICATION_SCHEMA_REVIEW_CLI_MESSAGES as PUBLICATION_SCHEMA_REVIEW_CLI_MESSAGES2
38
40
  } from "@andpipes/localization";
39
41
  import { Command } from "commander";
40
42
 
@@ -51,14 +53,22 @@ import {
51
53
  comparePublicationUnicodeCodePoints,
52
54
  EXTERNAL_SAAS_TEMPLATE_COMMITMENT_RE,
53
55
  externalSaasTemplateCommitment,
56
+ isOAuthScopeRegistrationErrorReason,
54
57
  isOpenApiImportUpstreamAuthMode,
58
+ isSafeToolName,
59
+ OAUTH_SCOPE_REGISTRATION_MAX_DRAFTS,
60
+ OAUTH_SCOPE_REGISTRATION_MAX_TOOLS,
61
+ OAuthScopeRegistrationDtoError,
55
62
  OpenApiImportError,
56
63
  oauthClientScopeMapPlanCommitment,
64
+ oauthScopeRegistrationSourceCommitment,
57
65
  onboardingTemplateApplicationCommitment,
58
66
  onboardingTemplateBindingCommitment,
59
67
  PUBLICATION_CONFIRMATION_SIGNATURE_RE,
68
+ PUBLICATION_REVIEW_PROFILE_HEADER,
60
69
  PUBLICATION_SHA256_COMMITMENT_RE,
61
70
  parseExternalSaasTemplate,
71
+ parseOAuthScopeRegistrationResponse,
62
72
  parseOnboardingTemplateApplyDto,
63
73
  parseOnboardingTemplateBindings,
64
74
  parseOnboardingTemplateExportDto,
@@ -542,6 +552,26 @@ var ConfirmationRequiredError = class extends Error {
542
552
  }
543
553
  };
544
554
 
555
+ // src/lib/publication-review-profile.ts
556
+ var CLI_PUBLICATION_REVIEW_PROFILE = 2;
557
+ var PUBLICATION_ERROR_REASON_CODES = Object.freeze({
558
+ publication_plan_stale: "AP_CONFLICT",
559
+ publication_review_profile_invalid: "AP_INPUT_INVALID",
560
+ publication_schema_review_too_large: "AP_INPUT_INVALID",
561
+ schema_review_receipt_mismatch: "AP_CONFLICT"
562
+ });
563
+ function isPublicationErrorReasonFor(code, reason) {
564
+ return typeof reason === "string" && Object.hasOwn(PUBLICATION_ERROR_REASON_CODES, reason) && PUBLICATION_ERROR_REASON_CODES[reason] === code;
565
+ }
566
+ function parsePublicationErrorReason(status, code, details) {
567
+ if (status < 400 || status > 499) return void 0;
568
+ if (details === null || typeof details !== "object" || Array.isArray(details)) return void 0;
569
+ const record = details;
570
+ const keys = Object.keys(record);
571
+ if (keys.length !== 1 || keys[0] !== "reason") return void 0;
572
+ return isPublicationErrorReasonFor(code, record.reason) ? record.reason : void 0;
573
+ }
574
+
545
575
  // src/lib/backend.ts
546
576
  var ADMIN_API_ORIGIN = "https://api.andpipe.com";
547
577
  var ADMIN_API_TIMEOUT_MS = 1e4;
@@ -551,6 +581,9 @@ var ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES = 96 * 1024;
551
581
  var ADMIN_API_OPENAPI_IMPORT_MAX_BYTES = 1280 * 1024;
552
582
  var ADMIN_API_ONBOARDING_TEMPLATE_MAX_BYTES = 64 * 1024;
553
583
  var ADMIN_API_MAX_GET_ATTEMPTS = 3;
584
+ var ADMIN_API_OAUTH_SCOPE_REGISTRATION_REQUEST_MAX_BYTES = ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES + 8 * 1024;
585
+ var ADMIN_API_OAUTH_SCOPE_REGISTRATION_RESPONSE_MAX_BYTES = 1024 * 1024;
586
+ var ADMIN_API_OAUTH_SCOPE_REGISTRATION_MAX_APPLY_ATTEMPTS = 3;
554
587
  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;
555
588
  var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
556
589
  var SAFE_AP_CODE_RE = /^AP_[A-Z0-9_]{1,64}$/;
@@ -565,13 +598,21 @@ var AdminApiClientError = class extends Error {
565
598
  status;
566
599
  confirmationRequired;
567
600
  openApiAuthModeMismatch;
568
- constructor(code, message, status, confirmationRequired, openApiAuthModeMismatch) {
601
+ detailsAbsent;
602
+ scopeRegistrationReason;
603
+ publishGateToolNames;
604
+ publicationReason;
605
+ constructor(code, message, status, confirmationRequired, openApiAuthModeMismatch, safeDetails = {}) {
569
606
  super(message);
570
607
  this.name = "AdminApiClientError";
571
608
  this.code = code;
572
609
  this.status = status;
573
610
  this.confirmationRequired = confirmationRequired;
574
611
  this.openApiAuthModeMismatch = openApiAuthModeMismatch;
612
+ this.detailsAbsent = safeDetails.detailsAbsent === true;
613
+ this.scopeRegistrationReason = safeDetails.scopeRegistrationReason;
614
+ this.publishGateToolNames = safeDetails.publishGateToolNames === void 0 ? void 0 : Object.freeze([...safeDetails.publishGateToolNames]);
615
+ this.publicationReason = safeDetails.publicationReason;
575
616
  }
576
617
  };
577
618
  function clientError(code, message, status) {
@@ -782,7 +823,13 @@ function withKnownResponseStatus(error, responseStatus) {
782
823
  error.message,
783
824
  responseStatus,
784
825
  error.confirmationRequired,
785
- error.openApiAuthModeMismatch
826
+ error.openApiAuthModeMismatch,
827
+ {
828
+ detailsAbsent: error.detailsAbsent,
829
+ ...error.scopeRegistrationReason === void 0 ? {} : { scopeRegistrationReason: error.scopeRegistrationReason },
830
+ ...error.publishGateToolNames === void 0 ? {} : { publishGateToolNames: error.publishGateToolNames },
831
+ ...error.publicationReason === void 0 ? {} : { publicationReason: error.publicationReason }
832
+ }
786
833
  );
787
834
  }
788
835
  var CONNECTOR_AUTH_MODES = /* @__PURE__ */ new Set([
@@ -802,6 +849,27 @@ function parseOpenApiImportAuthModeMismatch(value) {
802
849
  requestedAuthMode: details.requestedAuthMode
803
850
  };
804
851
  }
852
+ function parseScopeRegistrationErrorDetails(status, value) {
853
+ if (status < 400 || status > 499) return {};
854
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return {};
855
+ const details = value;
856
+ const reason = details.reason;
857
+ if (!isOAuthScopeRegistrationErrorReason(reason)) return {};
858
+ const keys = Object.keys(details).sort().join(",");
859
+ if (reason === "marketplace_managed_tool") {
860
+ return keys === "reason" || keys === "reason,toolName" && isSafeToolName(details.toolName) ? { scopeRegistrationReason: reason } : {};
861
+ }
862
+ if (reason !== "scope_registration_publish_gate_failed") {
863
+ return keys === "reason" ? { scopeRegistrationReason: reason } : {};
864
+ }
865
+ const toolNames = details.toolNames;
866
+ if (keys !== "reason,toolNames" || !Array.isArray(toolNames) || toolNames.length < 1 || toolNames.length > OAUTH_SCOPE_REGISTRATION_MAX_TOOLS || !toolNames.every((name) => isSafeToolName(name)) || toolNames.some(
867
+ (name, index) => index > 0 && comparePublicationUnicodeCodePoints(toolNames[index - 1], name) >= 0
868
+ )) {
869
+ return {};
870
+ }
871
+ return { scopeRegistrationReason: reason, publishGateToolNames: toolNames };
872
+ }
805
873
  function unicodeScalarLength(value) {
806
874
  let length = 0;
807
875
  for (const character of value) {
@@ -829,12 +897,19 @@ function safeApiError(status, value) {
829
897
  const code = typeof candidate === "string" && SAFE_AP_CODE_RE.test(candidate) ? candidate : "AP_HTTP_ERROR";
830
898
  const confirmationRequired = code === "AP_CONFIRMATION_REQUIRED" && status === 409 ? parsePublicationConfirmationRequiredDetails(errorRecord?.details) : void 0;
831
899
  const openApiAuthModeMismatch = code === "AP_CONFLICT" && status === 409 ? parseOpenApiImportAuthModeMismatch(errorRecord?.details) : void 0;
900
+ const publicationReason = parsePublicationErrorReason(status, code, errorRecord?.details);
832
901
  return new AdminApiClientError(
833
902
  code,
834
903
  `Admin API request failed (${code}; HTTP ${status})`,
835
904
  status,
836
905
  confirmationRequired,
837
- openApiAuthModeMismatch
906
+ openApiAuthModeMismatch,
907
+ {
908
+ // AP error envelopeを受け取れた場合だけ「detailsなし」を判定できる。
909
+ detailsAbsent: errorRecord !== void 0 && (errorRecord.details === null || errorRecord.details === void 0),
910
+ ...parseScopeRegistrationErrorDetails(status, errorRecord?.details),
911
+ ...publicationReason === void 0 ? {} : { publicationReason }
912
+ }
838
913
  );
839
914
  }
840
915
  function buildUrl(path) {
@@ -967,6 +1042,13 @@ function publicationPlanBody(input) {
967
1042
  ...input.templateProvenance === void 0 ? {} : { templateProvenance: input.templateProvenance }
968
1043
  };
969
1044
  }
1045
+ function publicationReviewProfileOption(options) {
1046
+ if (options === void 0) return void 0;
1047
+ if (options === null || typeof options !== "object" || Object.keys(options).join(",") !== "reviewProfile" || options.reviewProfile !== 2) {
1048
+ throw clientError("AP_INPUT_INVALID", "tool publication review profile option is invalid");
1049
+ }
1050
+ return options.reviewProfile;
1051
+ }
970
1052
  function publicationApplyBody(input) {
971
1053
  const common = publicationPlanBody(input);
972
1054
  if (!PUBLICATION_SHA256_COMMITMENT_RE.test(input.planCommitment)) {
@@ -986,6 +1068,111 @@ function publicationApplyBody(input) {
986
1068
  }
987
1069
  };
988
1070
  }
1071
+ function scopeRegistrationSourceInvalid() {
1072
+ return clientError("AP_INPUT_INVALID", "OAuth scope registration source is invalid");
1073
+ }
1074
+ function oauthScopeRegistrationSourceBody(source) {
1075
+ if (source.kind === "saved_drafts") {
1076
+ const drafts = source.drafts;
1077
+ if (!Array.isArray(drafts) || drafts.length < 1 || drafts.length > OAUTH_SCOPE_REGISTRATION_MAX_DRAFTS) {
1078
+ throw scopeRegistrationSourceInvalid();
1079
+ }
1080
+ const body = drafts.map((draft) => {
1081
+ if (!PUBLICATION_UUID_RE.test(draft.toolId) || !PUBLICATION_UUID_RE.test(draft.versionId)) {
1082
+ throw scopeRegistrationSourceInvalid();
1083
+ }
1084
+ return { toolId: draft.toolId, versionId: draft.versionId };
1085
+ });
1086
+ for (let index = 1; index < body.length; index += 1) {
1087
+ const previous = body[index - 1];
1088
+ const current = body[index];
1089
+ if (comparePublicationUnicodeCodePoints(previous.toolId, current.toolId) >= 0) {
1090
+ throw scopeRegistrationSourceInvalid();
1091
+ }
1092
+ }
1093
+ return { kind: "saved_drafts", drafts: body };
1094
+ }
1095
+ if (source.kind !== "publication_candidate") throw scopeRegistrationSourceInvalid();
1096
+ if (!PUBLICATION_UUID_RE.test(source.connectorId) || source.candidateContract === null || typeof source.candidateContract !== "object" || Array.isArray(source.candidateContract) || !PUBLICATION_SHA256_COMMITMENT_RE.test(source.candidateCommitment)) {
1097
+ throw scopeRegistrationSourceInvalid();
1098
+ }
1099
+ try {
1100
+ assertCanonicalPublicationSize(source.candidateContract);
1101
+ } catch {
1102
+ throw clientError("AP_INPUT_INVALID", "OAuth scope registration candidate is too large");
1103
+ }
1104
+ if (publicationCommitment("candidate", source.candidateContract) !== source.candidateCommitment) {
1105
+ throw clientError(
1106
+ "AP_CONFLICT",
1107
+ "OAuth scope registration candidate commitment does not match"
1108
+ );
1109
+ }
1110
+ return {
1111
+ kind: "publication_candidate",
1112
+ connectorId: source.connectorId,
1113
+ candidateContract: source.candidateContract,
1114
+ candidateCommitment: source.candidateCommitment
1115
+ };
1116
+ }
1117
+ function scopeRegistrationResponseInvalid() {
1118
+ return clientError(
1119
+ "AP_RESPONSE_INVALID",
1120
+ "Admin API response oauth scope registration is invalid"
1121
+ );
1122
+ }
1123
+ function parseOAuthScopeRegistration(value, projectId, request) {
1124
+ let parsed;
1125
+ try {
1126
+ parsed = parseOAuthScopeRegistrationResponse(value, { projectId });
1127
+ } catch (error) {
1128
+ if (error instanceof OAuthScopeRegistrationDtoError) throw scopeRegistrationResponseInvalid();
1129
+ throw error;
1130
+ }
1131
+ if (parsed.mode !== (request.apply ? "applied" : "preview") || parsed.source.kind !== request.source.kind) {
1132
+ throw scopeRegistrationResponseInvalid();
1133
+ }
1134
+ const source = request.source;
1135
+ if (source.kind === "publication_candidate") {
1136
+ if (parsed.source.connectorId !== source.connectorId || parsed.sourceCommitment !== oauthScopeRegistrationSourceCommitment({
1137
+ projectId,
1138
+ kind: "publication_candidate",
1139
+ connectorId: source.connectorId,
1140
+ candidateCommitment: source.candidateCommitment
1141
+ })) {
1142
+ throw scopeRegistrationResponseInvalid();
1143
+ }
1144
+ } else {
1145
+ const returned = parsed.source.tools.map((tool) => ({ toolId: tool.toolId, versionId: tool.versionId })).sort((left, right) => comparePublicationUnicodeCodePoints(left.toolId, right.toolId));
1146
+ if (returned.length !== source.drafts.length || returned.some(
1147
+ (draft, index) => draft.toolId !== source.drafts[index]?.toolId || draft.versionId !== source.drafts[index]?.versionId
1148
+ )) {
1149
+ throw scopeRegistrationResponseInvalid();
1150
+ }
1151
+ }
1152
+ if (request.apply && (parsed.sourceCommitment !== request.sourceCommitment || parsed.baseRegistryCommitment !== request.baseRegistryCommitment || parsed.planCommitment !== request.planCommitment)) {
1153
+ throw scopeRegistrationResponseInvalid();
1154
+ }
1155
+ return parsed;
1156
+ }
1157
+ var DEFINITIVE_SCOPE_REGISTRATION_APPLY_ERROR_CODES = /* @__PURE__ */ new Set([
1158
+ "AP_AUTH_REQUIRED",
1159
+ "AP_CONFIRMATION_EXPIRED",
1160
+ "AP_CONFLICT",
1161
+ "AP_FORBIDDEN",
1162
+ "AP_IDEMPOTENCY_KEY_CONFLICT",
1163
+ "AP_INPUT_INVALID",
1164
+ "AP_INVALID_SCOPE",
1165
+ "AP_NOT_FOUND",
1166
+ "AP_POLICY_DENIED",
1167
+ "AP_UNAUTHORIZED"
1168
+ ]);
1169
+ function scopeRegistrationApplyResultMayBeUnknown(error) {
1170
+ if (error.status !== void 0 && error.status >= 400 && error.status < 500) return false;
1171
+ if (error.status === void 0 && DEFINITIVE_SCOPE_REGISTRATION_APPLY_ERROR_CODES.has(error.code)) {
1172
+ return false;
1173
+ }
1174
+ return true;
1175
+ }
989
1176
  function openApiImportBody(input) {
990
1177
  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 && !isOpenApiImportUpstreamAuthMode(input.upstreamAuthMode)) {
991
1178
  throw clientError("AP_INPUT_INVALID", "OpenAPI import request is invalid");
@@ -1217,6 +1404,10 @@ var AdminApiClient = class {
1217
1404
  this.#sleep = options.sleep ?? ((milliseconds) => new Promise((resolve6) => setTimeout(resolve6, milliseconds)));
1218
1405
  }
1219
1406
  async #request(path, options = {}) {
1407
+ return (await this.#requestWithHeaders(path, options)).value;
1408
+ }
1409
+ /** 2xx bodyと、そのresponse headerを返す。headerはcommand層が必要な値だけを読む。 */
1410
+ async #requestWithHeaders(path, options = {}) {
1220
1411
  const url = buildUrl(path);
1221
1412
  const method = options.method ?? "GET";
1222
1413
  const attempts = method === "GET" ? ADMIN_API_MAX_GET_ATTEMPTS : 1;
@@ -1238,6 +1429,9 @@ var AdminApiClient = class {
1238
1429
  if (options.authenticated !== false) headers.set("Authorization", `Bearer ${this.#token}`);
1239
1430
  if (body !== void 0) headers.set("Content-Type", "application/json");
1240
1431
  if (options.idempotencyKey) headers.set("Idempotency-Key", options.idempotencyKey);
1432
+ if (options.reviewProfile !== void 0) {
1433
+ headers.set(PUBLICATION_REVIEW_PROFILE_HEADER, String(options.reviewProfile));
1434
+ }
1241
1435
  response = await this.#fetch(url, {
1242
1436
  method,
1243
1437
  headers,
@@ -1294,8 +1488,8 @@ var AdminApiClient = class {
1294
1488
  }
1295
1489
  throw safeApiError(response.status, errorBody);
1296
1490
  }
1297
- if (options.responseType === "text") return text;
1298
- return parseJson(text);
1491
+ if (options.responseType === "text") return { value: text, headers: response.headers };
1492
+ return { value: parseJson(text), headers: response.headers };
1299
1493
  }
1300
1494
  throw clientError("AP_NETWORK_ERROR", "Admin API request failed");
1301
1495
  }
@@ -1441,24 +1635,41 @@ var AdminApiClient = class {
1441
1635
  status: connector.status
1442
1636
  };
1443
1637
  }
1444
- async planPublication(projectId, body) {
1445
- return this.#request(`/v1/projects/${assertProjectId(projectId)}/tool-publications:plan`, {
1446
- method: "POST",
1447
- body: publicationPlanBody(body),
1448
- maxRequestBytes: ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES,
1449
- maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES
1450
- });
1638
+ async planPublication(projectId, body, options) {
1639
+ const reviewProfile = publicationReviewProfileOption(options);
1640
+ const response = await this.#requestWithHeaders(
1641
+ `/v1/projects/${assertProjectId(projectId)}/tool-publications:plan`,
1642
+ {
1643
+ method: "POST",
1644
+ body: publicationPlanBody(body),
1645
+ maxRequestBytes: ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES,
1646
+ maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES,
1647
+ ...reviewProfile === void 0 ? {} : { reviewProfile }
1648
+ }
1649
+ );
1650
+ if (reviewProfile === void 0) return response.value;
1651
+ const planResponse = {
1652
+ body: response.value,
1653
+ reviewProfileHeader: response.headers.get(PUBLICATION_REVIEW_PROFILE_HEADER)
1654
+ };
1655
+ return planResponse;
1451
1656
  }
1452
- async applyPublication(projectId, idempotencyKey, body) {
1657
+ /**
1658
+ * 初回apply(confirmation=null)と承認済みapply。options付き (#730) だけreview profile headerを送る。
1659
+ * request bodyとIdempotency-Keyはheaderの有無で変えない。
1660
+ */
1661
+ async applyPublication(projectId, idempotencyKey, body, options) {
1453
1662
  if (!/^[A-Za-z0-9._:-]{22,200}$/u.test(idempotencyKey)) {
1454
1663
  throw clientError("AP_INPUT_INVALID", "tool publication Idempotency-Key is invalid");
1455
1664
  }
1665
+ const reviewProfile = publicationReviewProfileOption(options);
1456
1666
  return this.#request(`/v1/projects/${assertProjectId(projectId)}/tool-publications`, {
1457
1667
  method: "POST",
1458
1668
  body: publicationApplyBody(body),
1459
1669
  idempotencyKey,
1460
1670
  maxRequestBytes: ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES,
1461
- maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES
1671
+ maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES,
1672
+ ...reviewProfile === void 0 ? {} : { reviewProfile }
1462
1673
  });
1463
1674
  }
1464
1675
  async planOpenApiImport(projectId, input) {
@@ -1825,6 +2036,75 @@ var AdminApiClient = class {
1825
2036
  planCommitment
1826
2037
  };
1827
2038
  }
2039
+ /**
2040
+ * `POST /v1/projects/{projectId}/oauth/scopes:register` (#729 / ADR-729)。previewは副作用なしで1回だけ送る。
2041
+ * applyはpreviewの3 commitmentと呼出側のIdempotency-Keyを必須にし、network・timeout・5xx・2xx応答の
2042
+ * 破損という曖昧な失敗だけ、同じkeyとbodyで最大3回まで送る。responseはexact 12 keyと
2043
+ * planCommitmentを再計算して検証し、requestとの束縛が崩れていれば`AP_RESPONSE_INVALID`にする。
2044
+ */
2045
+ async registerOAuthScopes(input) {
2046
+ const projectId = assertProjectId(input.projectId);
2047
+ const source = oauthScopeRegistrationSourceBody(input.source);
2048
+ const path = `/v1/projects/${projectId}/oauth/scopes:register`;
2049
+ const limits = {
2050
+ maxRequestBytes: ADMIN_API_OAUTH_SCOPE_REGISTRATION_REQUEST_MAX_BYTES,
2051
+ maxResponseBytes: ADMIN_API_OAUTH_SCOPE_REGISTRATION_RESPONSE_MAX_BYTES
2052
+ };
2053
+ if (!input.apply) {
2054
+ const value = await this.#request(path, {
2055
+ method: "POST",
2056
+ body: { apply: false, confirmed: false, source },
2057
+ ...limits
2058
+ });
2059
+ return parseOAuthScopeRegistration(value, projectId, input);
2060
+ }
2061
+ for (const commitment of [
2062
+ input.sourceCommitment,
2063
+ input.baseRegistryCommitment,
2064
+ input.planCommitment
2065
+ ]) {
2066
+ if (!PUBLICATION_SHA256_COMMITMENT_RE.test(commitment)) {
2067
+ throw clientError("AP_INPUT_INVALID", "OAuth scope registration commitment is invalid");
2068
+ }
2069
+ }
2070
+ if (!/^[A-Za-z0-9._:-]{22,200}$/u.test(input.idempotencyKey)) {
2071
+ throw clientError("AP_INPUT_INVALID", "OAuth scope registration Idempotency-Key is invalid");
2072
+ }
2073
+ const body = {
2074
+ apply: true,
2075
+ confirmed: true,
2076
+ source,
2077
+ sourceCommitment: input.sourceCommitment,
2078
+ baseRegistryCommitment: input.baseRegistryCommitment,
2079
+ planCommitment: input.planCommitment
2080
+ };
2081
+ if (Buffer.byteLength(JSON.stringify(body), "utf8") > limits.maxRequestBytes) {
2082
+ throw clientError("AP_INPUT_INVALID", "Admin API request body exceeds its byte limit");
2083
+ }
2084
+ for (let attempt = 1; ; attempt += 1) {
2085
+ try {
2086
+ const value = await this.#request(path, {
2087
+ method: "POST",
2088
+ body,
2089
+ idempotencyKey: input.idempotencyKey,
2090
+ ...limits
2091
+ });
2092
+ return parseOAuthScopeRegistration(value, projectId, input);
2093
+ } catch (error) {
2094
+ if (!(error instanceof AdminApiClientError) || !scopeRegistrationApplyResultMayBeUnknown(error)) {
2095
+ throw error;
2096
+ }
2097
+ if (attempt >= ADMIN_API_OAUTH_SCOPE_REGISTRATION_MAX_APPLY_ATTEMPTS) {
2098
+ throw clientError(
2099
+ "AP_RESULT_UNKNOWN",
2100
+ "OAuth scope registration result is unknown; review the current state without --apply before retrying",
2101
+ error.status
2102
+ );
2103
+ }
2104
+ await this.#sleep(100 * attempt);
2105
+ }
2106
+ }
2107
+ }
1828
2108
  async testOAuthLogin(projectId, clientRegistryId) {
1829
2109
  const selectedClientRegistryId = assertUuid(clientRegistryId, "OAuth client registry id");
1830
2110
  const value = asObject(
@@ -4857,7 +5137,7 @@ import { basename as basename2, join as join3 } from "path";
4857
5137
  import {
4858
5138
  asRecord as asRecord2,
4859
5139
  evaluatePublishGate,
4860
- isSafeToolName,
5140
+ isSafeToolName as isSafeToolName2,
4861
5141
  parseToolContract as parseToolContract3,
4862
5142
  selectTools,
4863
5143
  toolName,
@@ -4877,7 +5157,7 @@ function inspectContract(contract) {
4877
5157
  throw new UsageError(selected.error ?? "Tool Contract\u306Btool\u304C\u3042\u308A\u307E\u305B\u3093");
4878
5158
  }
4879
5159
  const names = selected.tools.map((tool) => toolName(tool));
4880
- if (names.some((name) => !isSafeToolName(name))) {
5160
+ if (names.some((name) => !isSafeToolName2(name))) {
4881
5161
  throw new UsageError(
4882
5162
  "Tool Contract\u306E\u5168tool name\u306F\u82F1\u6570\u5B57\u3067\u958B\u59CB\u3057\u3001\u82F1\u6570\u5B57\u30FB._:-\u306E200\u6587\u5B57\u4EE5\u5185\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"
4883
5163
  );
@@ -5820,7 +6100,10 @@ function registerDomain(program, writer, locale = DEFAULT_LOCALE5) {
5820
6100
  import { randomUUID as randomUUID5 } from "crypto";
5821
6101
  import { resolve as resolve3 } from "path";
5822
6102
  import { createInterface } from "readline/promises";
5823
- import { CLI_MESSAGES as CLI_MESSAGES6 } from "@andpipes/localization";
6103
+ import {
6104
+ CLI_MESSAGES as CLI_MESSAGES6,
6105
+ OAUTH_SCOPE_REGISTRATION_MESSAGES
6106
+ } from "@andpipes/localization";
5824
6107
  import {
5825
6108
  canonicalizePublicationJson,
5826
6109
  EXTERNAL_SAAS_TEMPLATE_MAX_BYTES,
@@ -6813,6 +7096,8 @@ var MANIFEST_KEYS2 = [
6813
7096
  "template_application_commitment"
6814
7097
  ];
6815
7098
  var DEFAULT_INIT_MESSAGES = CLI_MESSAGES6.ja.init;
7099
+ var DEFAULT_SCOPE_REGISTRATION_MESSAGES = OAUTH_SCOPE_REGISTRATION_MESSAGES.ja.cli;
7100
+ var CONNECTOR_PLACEHOLDER = "<connector-uuid>";
6816
7101
  function assertTemplateInitOptionShape(options, messages = DEFAULT_INIT_MESSAGES) {
6817
7102
  if (options.openapi !== void 0 && options.project === void 0) {
6818
7103
  throw new UsageError(messages.optionRequires("--openapi", "--project <uuid>"));
@@ -7443,7 +7728,7 @@ function assertIdempotencyKey(value, messages) {
7443
7728
  }
7444
7729
  return canonical;
7445
7730
  }
7446
- async function runInitCommand(options, writer, cwd, runtime, messages = DEFAULT_INIT_MESSAGES) {
7731
+ async function runInitCommand(options, writer, cwd, runtime, messages = DEFAULT_INIT_MESSAGES, scopeRegistrationMessages = DEFAULT_SCOPE_REGISTRATION_MESSAGES) {
7447
7732
  assertTemplateInitOptionShape(options, messages);
7448
7733
  if (options.template !== void 0 && options.project === void 0) {
7449
7734
  throw new UsageError("init --template\u306B\u306Fexport\u5143\u3068\u540C\u3058--project <uuid>\u304C\u5FC5\u9808\u3067\u3059");
@@ -7564,8 +7849,16 @@ async function runInitCommand(options, writer, cwd, runtime, messages = DEFAULT_
7564
7849
  project: { id: project.id, name: project.name, slug: project.slug }
7565
7850
  })
7566
7851
  );
7852
+ if (options.openapi !== void 0) {
7853
+ interactive(
7854
+ writer,
7855
+ scopeRegistrationMessages.initNextSteps(
7856
+ `--connector ${manifest.connector_id ?? CONNECTOR_PLACEHOLDER}`
7857
+ )
7858
+ );
7859
+ }
7567
7860
  }
7568
- 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) {
7861
+ 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) {
7569
7862
  const commandRuntime = runtime ?? createInitCommandRuntime(createClient, messages);
7570
7863
  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(
7571
7864
  "--auth-mode <mode>",
@@ -7580,7 +7873,14 @@ function registerInit(program, writer, cwd, createClient, description2 = "Projec
7580
7873
  "Create the template connector through the existing Admin API policy boundary",
7581
7874
  false
7582
7875
  ).option("--profile <name>", messages.profileOption, DEFAULT_PROFILE_NAME).option("--yes", messages.yesOption, false).action(async (options) => {
7583
- await runInitCommand(options, writer, cwd(), commandRuntime, messages);
7876
+ await runInitCommand(
7877
+ options,
7878
+ writer,
7879
+ cwd(),
7880
+ commandRuntime,
7881
+ messages,
7882
+ scopeRegistrationMessages
7883
+ );
7584
7884
  });
7585
7885
  }
7586
7886
 
@@ -7603,1174 +7903,1644 @@ function registerLogs(program, writer, locale = DEFAULT_LOCALE6) {
7603
7903
  }
7604
7904
 
7605
7905
  // src/commands/oauth.ts
7906
+ import { randomUUID as randomUUID7 } from "crypto";
7606
7907
  import { readFileSync as readFileSync2 } from "fs";
7607
- import { CLI_MESSAGES as CLI_MESSAGES8, DEFAULT_LOCALE as DEFAULT_LOCALE7 } from "@andpipes/localization";
7608
- function isUrl(value) {
7609
- if (typeof value !== "string") {
7610
- return false;
7611
- }
7612
- try {
7613
- const u = new URL(value);
7614
- return u.protocol === "http:" || u.protocol === "https:";
7615
- } catch {
7616
- return false;
7908
+ import {
7909
+ CLI_MESSAGES as CLI_MESSAGES9,
7910
+ DEFAULT_LOCALE as DEFAULT_LOCALE7,
7911
+ OAUTH_SCOPE_REGISTRATION_MESSAGES as OAUTH_SCOPE_REGISTRATION_MESSAGES3
7912
+ } from "@andpipes/localization";
7913
+ import {
7914
+ comparePublicationUnicodeCodePoints as comparePublicationUnicodeCodePoints3,
7915
+ OAUTH_SCOPE_REGISTRATION_MAX_DRAFTS as OAUTH_SCOPE_REGISTRATION_MAX_DRAFTS2,
7916
+ PublicationCanonicalizationError
7917
+ } from "@andpipes/tool-contract";
7918
+
7919
+ // src/commands/publish.ts
7920
+ import { randomUUID as randomUUID6 } from "crypto";
7921
+ import {
7922
+ CLI_MESSAGES as CLI_MESSAGES8,
7923
+ OAUTH_SCOPE_REGISTRATION_MESSAGES as OAUTH_SCOPE_REGISTRATION_MESSAGES2,
7924
+ PUBLICATION_SCHEMA_REVIEW_CLI_MESSAGES
7925
+ } from "@andpipes/localization";
7926
+ import {
7927
+ assertCanonicalPublicationSize as assertCanonicalPublicationSize2,
7928
+ comparePublicationUnicodeCodePoints as comparePublicationUnicodeCodePoints2,
7929
+ isSafeToolName as isSafeToolName3,
7930
+ PUBLICATION_CONFIRMATION_SIGNATURE_RE as PUBLICATION_CONFIRMATION_SIGNATURE_RE2,
7931
+ PUBLICATION_SHA256_COMMITMENT_RE as PUBLICATION_SHA256_COMMITMENT_RE2,
7932
+ parsePublicationSafeDiffDto,
7933
+ parsePublicationWarningsDto,
7934
+ publicationCommitment as publicationCommitment2,
7935
+ selectPublicationReviewProfile,
7936
+ toolName as toolName2
7937
+ } from "@andpipes/tool-contract";
7938
+ 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;
7939
+ var SAFE_AP_CODE_RE2 = /^AP_[A-Z0-9_]{1,64}$/u;
7940
+ var PUBLICATION_RESPONSE_MAX_BYTES = 96 * 1024;
7941
+ var INITIAL_APPLY_MAX_ATTEMPTS = 3;
7942
+ var DEFAULT_PUBLISH_MESSAGES = CLI_MESSAGES8.ja.publish;
7943
+ var DEFAULT_SCOPE_REGISTRATION_MESSAGES2 = OAUTH_SCOPE_REGISTRATION_MESSAGES2.ja.cli;
7944
+ var DEFAULT_SCHEMA_REVIEW_MESSAGES = PUBLICATION_SCHEMA_REVIEW_CLI_MESSAGES.ja;
7945
+ var REVIEW_PROFILE_REQUEST = Object.freeze({
7946
+ reviewProfile: CLI_PUBLICATION_REVIEW_PROFILE
7947
+ });
7948
+ var PLAN_KEYS = [
7949
+ "requestId",
7950
+ "environment",
7951
+ "connectorId",
7952
+ "connectorRevision",
7953
+ "connectorCommitment",
7954
+ "policyCommitment",
7955
+ "candidateCommitment",
7956
+ "baseCommitment",
7957
+ "planCommitment",
7958
+ "tools",
7959
+ "retainedTools",
7960
+ "warnings",
7961
+ "applyAllowed",
7962
+ "blockedReasons"
7963
+ ];
7964
+ var APPLY_RESULT_KEYS = ["requestId", "publicationId", "state", "tools", "warnings"];
7965
+ var STATUS_KEYS = [
7966
+ "requestId",
7967
+ "publicationId",
7968
+ "durableState",
7969
+ "effectiveState",
7970
+ "expiresAt",
7971
+ "confirmation",
7972
+ "result"
7973
+ ];
7974
+ var BLOCKED_REASONS = /* @__PURE__ */ new Set([
7975
+ "project_not_active",
7976
+ "connector_not_active",
7977
+ "connector_mismatch",
7978
+ "tool_deprecated",
7979
+ "tool_plan_limit_exceeded",
7980
+ "production_capability_required",
7981
+ "write_tool_mode_not_confirmed",
7982
+ "production_oauth_broker_required",
7983
+ "oauth_scope_registry_missing",
7984
+ "oauth_scope_registry_risk_insufficient",
7985
+ "publish_gate_failed",
7986
+ "opaque_change",
7987
+ "retention_policy_blocked",
7988
+ "descriptor_name_conflict"
7989
+ ]);
7990
+ var TOOL_BLOCKED_REASONS = [
7991
+ "connector_mismatch",
7992
+ "opaque_change",
7993
+ "publish_gate_failed",
7994
+ "tool_deprecated"
7995
+ ];
7996
+ var DURABLE_STATES = /* @__PURE__ */ new Set(["pending", "approved", "rejected", "expired", "consumed"]);
7997
+ var EFFECTIVE_STATES = /* @__PURE__ */ new Set([
7998
+ "pending",
7999
+ "approved",
8000
+ "rejected",
8001
+ "expired",
8002
+ "consumed",
8003
+ "stale"
8004
+ ]);
8005
+ var DEFINITIVE_APPLY_ERROR_CODES = /* @__PURE__ */ new Set([
8006
+ "AP_AUTH_REQUIRED",
8007
+ "AP_CONFIRMATION_EXPIRED",
8008
+ "AP_CONFLICT",
8009
+ "AP_FORBIDDEN",
8010
+ "AP_IDEMPOTENCY_KEY_CONFLICT",
8011
+ "AP_INPUT_INVALID",
8012
+ "AP_INVALID_SCOPE",
8013
+ "AP_NOT_FOUND",
8014
+ "AP_POLICY_DENIED",
8015
+ "AP_UNAUTHORIZED"
8016
+ ]);
8017
+ var PublishCommandError = class extends Error {
8018
+ constructor(code, reason, message, status) {
8019
+ super(message);
8020
+ this.code = code;
8021
+ this.reason = reason;
8022
+ this.status = status;
8023
+ this.name = "PublishCommandError";
7617
8024
  }
8025
+ code;
8026
+ reason;
8027
+ status;
8028
+ };
8029
+ function createPublishCommandRuntime(createClient) {
8030
+ return {
8031
+ createClient,
8032
+ loadProject: loadDevProject,
8033
+ randomUuid: () => randomUUID6(),
8034
+ monotonicNow: () => Number(process.hrtime.bigint() / 1000000n),
8035
+ wallNow: () => Date.now(),
8036
+ sleep: (milliseconds) => new Promise((resolve6) => setTimeout(resolve6, milliseconds))
8037
+ };
7618
8038
  }
7619
- function field(meta, snake, camel) {
7620
- return snake in meta ? meta[snake] : meta[camel];
8039
+ function canonicalUuidOption(value, option, messages = DEFAULT_PUBLISH_MESSAGES) {
8040
+ const canonical = value.toLowerCase();
8041
+ if (!UUID_RE6.test(canonical)) {
8042
+ throw new UsageError(messages.invalidOption(option, "a canonical RFC 4122 UUID"));
8043
+ }
8044
+ return canonical;
7621
8045
  }
7622
- function validateOAuthMetadata(meta, locale = DEFAULT_LOCALE7) {
7623
- const messages = CLI_MESSAGES8[locale].oauth;
7624
- const results = [];
7625
- if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
7626
- return {
7627
- ok: false,
7628
- results: [
7629
- {
7630
- id: "metadata",
7631
- label: "metadata",
7632
- status: "fail",
7633
- detail: messages.metadataNotObject
7634
- }
7635
- ]
7636
- };
8046
+ function normalizePublishOptions(options, messages = DEFAULT_PUBLISH_MESSAGES) {
8047
+ if (options.dryRun === true && options.apply === true) {
8048
+ throw new UsageError(messages.incompatibleOptions("--dry-run / --apply"));
7637
8049
  }
7638
- const m = meta;
7639
- const urlFields = [
7640
- ["issuer", "issuer", "issuer"],
7641
- ["authorization_endpoint", "authorization_endpoint", "authorizationEndpoint"],
7642
- ["token_endpoint", "token_endpoint", "tokenEndpoint"],
7643
- ["jwks_uri", "jwks_uri", "jwksUri"]
7644
- ];
7645
- for (const [id, snake, camel] of urlFields) {
7646
- const value = field(m, snake, camel);
7647
- const ok = isUrl(value);
7648
- results.push({
7649
- id,
7650
- label: id,
7651
- status: ok ? "pass" : "fail",
7652
- detail: ok ? messages.urlOk : messages.invalidUrl(id)
7653
- });
8050
+ if (options.yes === true && options.apply !== true) {
8051
+ throw new UsageError(messages.optionRequires("--yes", "--apply"));
7654
8052
  }
7655
- const responseTypes = field(m, "response_types_supported", "responseTypesSupported");
7656
- results.push({
7657
- id: "response_types_supported",
7658
- label: "response_types_supported",
7659
- status: Array.isArray(responseTypes) && responseTypes.length > 0 ? "pass" : "fail",
7660
- detail: Array.isArray(responseTypes) ? messages.present : messages.arrayMissing
7661
- });
7662
- const scopes = field(m, "scopes_supported", "scopesSupported");
7663
- results.push({
7664
- id: "scopes_supported",
7665
- label: "scopes_supported",
7666
- // 推奨項目。欠落は致命ではないため pending 扱いで明示する。
7667
- status: Array.isArray(scopes) && scopes.length > 0 ? "pass" : "pending",
7668
- detail: Array.isArray(scopes) ? messages.present : messages.scopesMissing
7669
- });
7670
- return { ok: results.every((r) => r.status !== "fail"), results };
7671
- }
7672
- function buildInitTemplate(provider) {
8053
+ if (options.apply === true && options.yes !== true) {
8054
+ throw new ConfirmationRequiredError(
8055
+ "andpipe publish --apply",
8056
+ messages.applyConfirmationRequired
8057
+ );
8058
+ }
8059
+ const projectId = options.project === void 0 ? void 0 : canonicalUuidOption(options.project, "--project", messages);
7673
8060
  return {
7674
- provider,
7675
- issuer: "https://auth.example.com",
7676
- authorizationEndpoint: "https://auth.example.com/oauth/authorize",
7677
- tokenEndpoint: "https://auth.example.com/oauth/token",
7678
- jwksUri: "https://auth.example.com/.well-known/jwks.json",
7679
- clientId: "<client id>",
7680
- // secret は config に直書きせず env 参照にする (No secret in repo / stdout)。
7681
- clientSecretEnv: "ANDPIPE_OAUTH_CLIENT_SECRET",
7682
- redirectUri: "https://<your-andpipe-gateway>/oauth/callback",
7683
- scopes: ["openid", "profile"]
8061
+ mode: options.apply === true ? "apply" : "dry-run",
8062
+ ...options.connector === void 0 ? {} : { connectorId: canonicalUuidOption(options.connector, "--connector", messages) },
8063
+ profile: options.profile ?? DEFAULT_PROFILE_NAME,
8064
+ ...projectId === void 0 ? {} : { projectId }
7684
8065
  };
7685
8066
  }
7686
- function upstreamOAuthWizardUrl(profile, projectId, connectorId) {
7687
- const record = getProfile(profile);
7688
- if (!record)
7689
- throw new UsageError(`\u8A8D\u8A3Cprofile ${profile} \u304C\u3042\u308A\u307E\u305B\u3093\u3002andpipe login\u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044`);
7690
- const url = new URL(`/projects/${projectId}/oauth`, new URL(record.verificationUriBase).origin);
7691
- url.searchParams.set("connector", connectorId);
7692
- return url.toString();
8067
+ function asRecord4(value) {
8068
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
7693
8069
  }
7694
- async function loadOAuthMetadata(opts, locale) {
7695
- const messages = CLI_MESSAGES8[locale];
7696
- if (opts.file && opts.issuer) {
7697
- throw new UsageError("--file \u3068 --issuer \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");
7698
- }
7699
- if (opts.issuer) {
7700
- return fetchOAuthMetadata(opts.issuer);
7701
- }
7702
- if (!opts.file) {
7703
- throw new UsageError(messages.oauth.fileRequired);
8070
+ function hasExactKeys3(record, keys) {
8071
+ const actual = Object.keys(record);
8072
+ return actual.length === keys.length && actual.every((key) => keys.includes(key));
8073
+ }
8074
+ function responseInvalid(reason, messages) {
8075
+ return new PublishCommandError("AP_RESPONSE_INVALID", reason, messages.failure(reason));
8076
+ }
8077
+ function assertCanonicalResponseSize(value, reason, messages, maxBytes = PUBLICATION_RESPONSE_MAX_BYTES) {
8078
+ try {
8079
+ assertCanonicalPublicationSize2(value, maxBytes);
8080
+ } catch {
8081
+ throw responseInvalid(reason, messages);
7704
8082
  }
8083
+ }
8084
+ function isCanonicalUuid(value) {
8085
+ return typeof value === "string" && UUID_RE6.test(value);
8086
+ }
8087
+ function isCommitment(value) {
8088
+ return typeof value === "string" && PUBLICATION_SHA256_COMMITMENT_RE2.test(value);
8089
+ }
8090
+ function isCanonicalTimestamp(value) {
8091
+ if (typeof value !== "string" || value.length > 64) return false;
8092
+ const milliseconds = Date.parse(value);
8093
+ return Number.isFinite(milliseconds) && new Date(milliseconds).toISOString() === value;
8094
+ }
8095
+ function isStrictlySorted(values) {
8096
+ return values.every(
8097
+ (value, index) => index === 0 || comparePublicationUnicodeCodePoints2(values[index - 1], value) < 0
8098
+ );
8099
+ }
8100
+ function parseWarnings(value, messages) {
7705
8101
  try {
7706
- return JSON.parse(readFileSync2(opts.file, "utf8"));
7707
- } catch (error) {
7708
- throw new UsageError(messages.oauth.metadataReadFailed(error.message));
8102
+ return parsePublicationWarningsDto(value);
8103
+ } catch {
8104
+ throw responseInvalid("publication_warnings_invalid", messages);
7709
8105
  }
7710
8106
  }
7711
- async function runOAuthMetadataValidate(opts, writer, locale) {
7712
- const messages = CLI_MESSAGES8[locale];
7713
- const parsed = await loadOAuthMetadata(opts, locale);
7714
- const report = validateOAuthMetadata(parsed, locale);
7715
- json(writer, report.results);
7716
- if (!report.ok) {
7717
- process.exitCode = 1;
7718
- info(writer, messages.oauth.metadataFailed);
7719
- } else {
7720
- info(writer, messages.oauth.metadataOk);
8107
+ function schemaReviewFailure(code, reason, text, status) {
8108
+ return new PublishCommandError(code, reason, `${text} (${reason})`, status);
8109
+ }
8110
+ function negotiateReviewProfile(response, messages, schemaReviewMessages) {
8111
+ const envelope = asRecord4(response);
8112
+ if (!envelope || !hasExactKeys3(envelope, ["body", "reviewProfileHeader"]) || envelope.reviewProfileHeader !== null && typeof envelope.reviewProfileHeader !== "string") {
8113
+ throw responseInvalid("publication_plan_invalid", messages);
8114
+ }
8115
+ const header = envelope.reviewProfileHeader;
8116
+ if (header !== null && header !== "1" && header !== "2") {
8117
+ throw schemaReviewFailure(
8118
+ "AP_RESPONSE_INVALID",
8119
+ "publication_review_profile_header_invalid",
8120
+ schemaReviewMessages.reviewProfileHeaderInvalid
8121
+ );
8122
+ }
8123
+ const body = asRecord4(envelope.body);
8124
+ const bodyDeclaresProfile = body !== null && Object.hasOwn(body, "reviewProfile");
8125
+ const profile = header === "2" ? 2 : 1;
8126
+ if (profile === 2 ? !bodyDeclaresProfile || body?.reviewProfile !== 2 : bodyDeclaresProfile) {
8127
+ throw schemaReviewFailure(
8128
+ "AP_CONFLICT",
8129
+ "publication_review_profile_mismatch",
8130
+ schemaReviewMessages.reviewProfileMismatch
8131
+ );
7721
8132
  }
8133
+ return {
8134
+ session: header === null ? { kind: "legacy", profile: 1 } : { kind: "negotiated", profile },
8135
+ body: envelope.body
8136
+ };
7722
8137
  }
7723
- function registerOauth(program, writer, locale = DEFAULT_LOCALE7, dependencies = {}) {
7724
- const messages = CLI_MESSAGES8[locale];
7725
- const oauth = program.command("oauth").description(messages.oauth.commandDescription);
7726
- oauth.command("init").description(messages.oauth.initDescription).requiredOption("--provider <name>", messages.oauth.providerOption).action((opts) => {
7727
- info(writer, messages.oauth.templateHeading(opts.provider));
7728
- json(writer, buildInitTemplate(opts.provider));
7729
- info(writer, messages.oauth.clientSecretEnvNotice);
8138
+ function parsePlan(value, connectorId, candidateCommitment, expectedToolNames, profile, messages) {
8139
+ assertCanonicalResponseSize(value, "publication_plan_too_large", messages);
8140
+ const plan = asRecord4(value);
8141
+ 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(
8142
+ (reason) => typeof reason === "string" && BLOCKED_REASONS.has(reason)
8143
+ ) || !isStrictlySorted(plan.blockedReasons) || plan.applyAllowed !== (plan.blockedReasons.length === 0)) {
8144
+ throw responseInvalid("publication_plan_invalid", messages);
8145
+ }
8146
+ const blockedReasons = plan.blockedReasons;
8147
+ let safeDiff;
8148
+ try {
8149
+ safeDiff = parsePublicationSafeDiffDto({
8150
+ ...profile === 2 ? { reviewProfile: 2 } : {},
8151
+ tools: plan.tools,
8152
+ retainedTools: plan.retainedTools,
8153
+ warnings: plan.warnings
8154
+ });
8155
+ } catch {
8156
+ throw responseInvalid("publication_safe_diff_invalid", messages);
8157
+ }
8158
+ if (safeDiff.reviewProfile === 2 !== (profile === 2)) {
8159
+ throw responseInvalid("publication_safe_diff_invalid", messages);
8160
+ }
8161
+ const tools = safeDiff.tools;
8162
+ const toolNames = tools.map((tool) => tool.toolName);
8163
+ if (!isStrictlySorted(toolNames) || JSON.stringify(toolNames) !== JSON.stringify(expectedToolNames)) {
8164
+ throw responseInvalid("publication_plan_tools_order_invalid", messages);
8165
+ }
8166
+ const warnings = safeDiff.warnings;
8167
+ const expectedPlanCommitment = publicationCommitment2(profile === 2 ? "planV2" : "plan", {
8168
+ candidateCommitment,
8169
+ baseCommitment: plan.baseCommitment,
8170
+ connectorId,
8171
+ connectorRevision: plan.connectorRevision,
8172
+ connectorCommitment: plan.connectorCommitment,
8173
+ policyCommitment: plan.policyCommitment,
8174
+ environment: "production",
8175
+ safeDiff
7730
8176
  });
7731
- 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) => {
7732
- if (opts.project) {
7733
- if (opts.file || opts.issuer) {
7734
- throw new UsageError("--project \u306F --file / --issuer \u3068\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");
7735
- }
7736
- const projectId = assertProjectId(opts.project);
7737
- const result = await createAdminApiClient({ profile: opts.profile }).getOAuthSetup(
7738
- projectId
7739
- );
7740
- json(writer, result);
7741
- if (result.metadata.status !== "valid" || result.alignment.issues.length > 0) {
7742
- process.exitCode = 1;
7743
- }
7744
- return;
8177
+ if (plan.planCommitment !== expectedPlanCommitment) {
8178
+ throw new PublishCommandError(
8179
+ "AP_CONFLICT",
8180
+ "publication_plan_commitment_mismatch",
8181
+ messages.failure("publication_plan_commitment_mismatch")
8182
+ );
8183
+ }
8184
+ const toolBlockedReasons = new Set(tools.flatMap((tool) => tool.blockedReasons));
8185
+ if (tools.some((tool) => !tool.gate.ok) && plan.applyAllowed || tools.some((tool) => tool.opaqueChanged) && (plan.applyAllowed || !blockedReasons.includes("opaque_change")) || TOOL_BLOCKED_REASONS.some(
8186
+ (reason) => (
8187
+ // connector_mismatchはtool単位(既存toolの別connector束縛)に加え、candidateの
8188
+ // upstream.auth.modeとconnector方式の不一致としてtop-levelだけにも出る (#456 / #724)。
8189
+ reason === "connector_mismatch" ? toolBlockedReasons.has(reason) && !blockedReasons.includes(reason) : blockedReasons.includes(reason) !== toolBlockedReasons.has(reason)
8190
+ )
8191
+ )) {
8192
+ throw responseInvalid("publication_plan_gate_inconsistent", messages);
8193
+ }
8194
+ return {
8195
+ ...profile === 2 ? { reviewProfile: 2 } : {},
8196
+ requestId: plan.requestId,
8197
+ environment: "production",
8198
+ connectorId,
8199
+ connectorRevision: plan.connectorRevision,
8200
+ connectorCommitment: plan.connectorCommitment,
8201
+ policyCommitment: plan.policyCommitment,
8202
+ candidateCommitment,
8203
+ baseCommitment: plan.baseCommitment,
8204
+ planCommitment: plan.planCommitment,
8205
+ tools,
8206
+ retainedTools: safeDiff.retainedTools,
8207
+ warnings,
8208
+ applyAllowed: plan.applyAllowed,
8209
+ blockedReasons
8210
+ };
8211
+ }
8212
+ function sameWarnings(left, right) {
8213
+ return JSON.stringify(left) === JSON.stringify(right);
8214
+ }
8215
+ function parseToolResults(value, messages) {
8216
+ if (!Array.isArray(value)) {
8217
+ throw responseInvalid("publication_result_tools_invalid", messages);
8218
+ }
8219
+ const tools = value.map((candidate) => {
8220
+ const tool = asRecord4(candidate);
8221
+ if (!tool || !hasExactKeys3(tool, ["toolName", "operation", "toolId", "versionId", "version"]) || !isSafeToolName3(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) {
8222
+ throw responseInvalid("publication_result_tool_invalid", messages);
7745
8223
  }
7746
- await runOAuthMetadataValidate(opts, writer, locale);
8224
+ const operation = tool.operation;
8225
+ return {
8226
+ toolName: tool.toolName,
8227
+ operation,
8228
+ toolId: tool.toolId,
8229
+ versionId: tool.versionId,
8230
+ version: tool.version
8231
+ };
7747
8232
  });
7748
- const scopes = oauth.command("scopes").description(messages.oauth.scopesDescription);
7749
- 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) => {
7750
- const operation = "andpipe oauth scopes sync";
7751
- if (opts.apply && !opts.yes) {
7752
- throw new ConfirmationRequiredError(
7753
- operation,
7754
- messages.common.confirmationRequiredMessage(operation)
7755
- );
8233
+ if (!isStrictlySorted(tools.map((tool) => tool.toolName))) {
8234
+ throw responseInvalid("publication_result_tools_order_invalid", messages);
8235
+ }
8236
+ return tools;
8237
+ }
8238
+ function parsePublicationResult(value, plan, messages, expectedPublicationId) {
8239
+ assertCanonicalResponseSize(value, "publication_apply_result_too_large", messages);
8240
+ const result = asRecord4(value);
8241
+ if (!result || !hasExactKeys3(result, APPLY_RESULT_KEYS) || !isCanonicalUuid(result.requestId) || result.state !== "noop" && result.state !== "consumed") {
8242
+ throw responseInvalid("publication_apply_result_invalid", messages);
8243
+ }
8244
+ const warnings = parseWarnings(result.warnings, messages);
8245
+ if (!sameWarnings(warnings, plan.warnings)) {
8246
+ throw responseInvalid("publication_apply_warning_mismatch", messages);
8247
+ }
8248
+ const tools = parseToolResults(result.tools, messages);
8249
+ const changedToolNames = plan.tools.filter((tool) => tool.changed).map((tool) => tool.toolName);
8250
+ if (result.state === "noop") {
8251
+ if (result.publicationId !== null || tools.length !== 0 || changedToolNames.length !== 0) {
8252
+ throw responseInvalid("publication_noop_invalid", messages);
7756
8253
  }
7757
- if (!opts.apply && opts.yes) {
7758
- throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
7759
- }
7760
- const projectId = assertProjectId(opts.project);
7761
- const result = await createAdminApiClient({ profile: opts.profile }).syncOAuthScopes({
7762
- projectId,
7763
- apply: opts.apply
7764
- });
7765
- json(writer, result);
7766
- });
7767
- const clients = oauth.command("clients").description("OAuth client\u306Escope\u5272\u5F53\u3092\u7BA1\u7406\u3059\u308B");
7768
- 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(
7769
- async (opts) => {
7770
- const operation = "andpipe oauth clients map-scopes";
7771
- if (opts.apply && !opts.yes) {
7772
- throw new ConfirmationRequiredError(
7773
- operation,
7774
- messages.common.confirmationRequiredMessage(operation)
7775
- );
7776
- }
7777
- if (!opts.apply && opts.yes) {
7778
- throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
7779
- }
7780
- const client = createAdminApiClient({ profile: opts.profile });
7781
- const preview = await client.mapOAuthClientScopes({
7782
- projectId: assertProjectId(opts.project),
7783
- clientRegistryId: opts.client,
7784
- apply: false
7785
- });
7786
- json(writer, preview);
7787
- if (!opts.apply) return;
7788
- const applied = await client.mapOAuthClientScopes({
7789
- projectId: assertProjectId(opts.project),
7790
- clientRegistryId: opts.client,
7791
- apply: true,
7792
- requiredScopesCommitment: preview.requiredScopesCommitment,
7793
- baseClientGrantCommitment: preview.baseClientGrantCommitment,
7794
- candidateClientGrantCommitment: preview.candidateClientGrantCommitment,
7795
- planCommitment: preview.planCommitment
7796
- });
7797
- json(writer, applied);
7798
- }
7799
- );
7800
- const metadata = oauth.command("metadata").description(messages.oauth.metadataDescription);
7801
- metadata.command("validate").description(messages.oauth.validateDescription).option("--file <path>", messages.common.metadataFileOption).option("--issuer <url>", messages.common.issuerOption).action(async (opts) => {
7802
- await runOAuthMetadataValidate(opts, writer, locale);
7803
- });
7804
- const connect = oauth.command("connect").description(
7805
- 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"
7806
- );
7807
- connect.command("status").description(
7808
- locale === "ja" ? "\u63A5\u7D9A\u72B6\u614B\u3068\u6B21\u306E\u64CD\u4F5C\u3092\u8868\u793A" : "Show connection state and next action"
7809
- ).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) => {
7810
- const state = await createAdminApiClient({
7811
- profile: opts.profile
7812
- }).getUpstreamOAuthConnectionState(assertProjectId(opts.project), opts.connector);
7813
- json(writer, state);
7814
- if (!state.allGreen) process.exitCode = 1;
7815
- });
7816
- connect.command("open").description(
7817
- 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"
7818
- ).requiredOption("--project <project>", messages.common.projectOption).requiredOption("--connector <connector>", "\u63A5\u7D9A\u5BFE\u8C61connector UUID").option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).option(
7819
- "--no-browser",
7820
- locale === "ja" ? "\u65E2\u5B9A\u30D6\u30E9\u30A6\u30B6\u3092\u958B\u304B\u305AURL\u3060\u3051\u8868\u793A" : "Print the URL without opening a browser"
7821
- ).action(
7822
- async (opts) => {
7823
- const projectId = assertProjectId(opts.project);
7824
- const state = await createAdminApiClient({
7825
- profile: opts.profile
7826
- }).getUpstreamOAuthConnectionState(projectId, opts.connector);
7827
- json(writer, state);
7828
- const url = upstreamOAuthWizardUrl(opts.profile, projectId, opts.connector);
7829
- info(
7830
- writer,
7831
- locale === "ja" ? `Web Admin\u3067\u7D9A\u3051\u3066\u304F\u3060\u3055\u3044: ${url}` : `Continue in Web Admin: ${url}`
7832
- );
7833
- if (opts.browser) {
7834
- try {
7835
- (dependencies.openBrowser ?? openBrowser)(url);
7836
- } catch {
7837
- }
7838
- }
7839
- }
7840
- );
7841
- 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) => {
7842
- const projectId = assertProjectId(opts.project);
7843
- const result = await createAdminApiClient({ profile: opts.profile }).testOAuthLogin(
7844
- projectId,
7845
- opts.client
7846
- );
7847
- json(writer, result);
7848
- if (result.status === "blocked") process.exitCode = 1;
7849
- });
8254
+ return {
8255
+ requestId: result.requestId,
8256
+ publicationId: null,
8257
+ state: "noop",
8258
+ tools,
8259
+ warnings
8260
+ };
8261
+ }
8262
+ 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(
8263
+ (tool) => plan.tools.find((planned) => planned.toolName === tool.toolName)?.operation !== tool.operation
8264
+ )) {
8265
+ throw responseInvalid("publication_consumed_result_invalid", messages);
8266
+ }
8267
+ return {
8268
+ requestId: result.requestId,
8269
+ publicationId: result.publicationId,
8270
+ state: "consumed",
8271
+ tools,
8272
+ warnings
8273
+ };
7850
8274
  }
7851
-
7852
- // src/commands/openapi.ts
7853
- import { randomUUID as randomUUID6 } from "crypto";
7854
- import { resolve as resolve4 } from "path";
7855
- import {
7856
- importOpenApi as importOpenApi2,
7857
- OPENAPI_IMPORT_MAX_SOURCE_BYTES as OPENAPI_IMPORT_MAX_SOURCE_BYTES2,
7858
- OpenApiImportError as OpenApiImportError3
7859
- } from "@andpipes/tool-contract";
7860
- function createOpenApiImportRuntime(createClient = (profile) => createAdminApiClient({ profile })) {
7861
- return { createClient, idempotencyKey: randomUUID6 };
8275
+ function parseConfirmation(value, messages) {
8276
+ if (value === null) return null;
8277
+ const confirmation = asRecord4(value);
8278
+ if (!confirmation || !hasExactKeys3(confirmation, ["confirmationId", "signature", "confirmed"]) || !isCanonicalUuid(confirmation.confirmationId) || typeof confirmation.signature !== "string" || !PUBLICATION_CONFIRMATION_SIGNATURE_RE2.test(confirmation.signature) || confirmation.confirmed !== true) {
8279
+ throw responseInvalid("publication_confirmation_invalid", messages);
8280
+ }
8281
+ return {
8282
+ confirmationId: confirmation.confirmationId,
8283
+ signature: confirmation.signature,
8284
+ confirmed: true
8285
+ };
7862
8286
  }
7863
- function normalizedOptions(options) {
7864
- if (!options.file || !options.project || !options.connector) {
7865
- throw new UsageError("--file\u3001--project\u3001--connector \u306F\u5FC5\u9808\u3067\u3059");
8287
+ function parseStatus(value, publicationId, plan, messages) {
8288
+ assertCanonicalResponseSize(value, "publication_status_too_large", messages);
8289
+ const status = asRecord4(value);
8290
+ 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)) {
8291
+ throw responseInvalid("publication_status_invalid", messages);
7866
8292
  }
7867
- if (options.format !== void 0 && options.format !== "json" && options.format !== "yaml") {
7868
- throw new UsageError("--format \u306F json \u307E\u305F\u306F yaml \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8293
+ const confirmation = parseConfirmation(status.confirmation, messages);
8294
+ const result = status.result === null ? null : parsePublicationResult(status.result, plan, messages, publicationId);
8295
+ const durableState = status.durableState;
8296
+ const effectiveState = status.effectiveState;
8297
+ const isPending = durableState === "pending";
8298
+ const isApproved = durableState === "approved";
8299
+ const isTerminal = durableState === "rejected" || durableState === "expired" || durableState === "consumed";
8300
+ 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)) {
8301
+ throw responseInvalid("publication_status_inconsistent", messages);
7869
8302
  }
7870
- if (options.serviceName !== void 0 && !/^[A-Za-z0-9_]{1,48}$/.test(options.serviceName)) {
7871
- throw new UsageError("--service-name \u306F\u82F1\u6570\u5B57\u3068 underscore \u306E1..48\u6587\u5B57\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8303
+ return {
8304
+ requestId: status.requestId,
8305
+ publicationId,
8306
+ durableState,
8307
+ effectiveState,
8308
+ expiresAt: status.expiresAt,
8309
+ confirmation,
8310
+ result
8311
+ };
8312
+ }
8313
+ function typedCode2(error) {
8314
+ if (error === null || typeof error !== "object") return void 0;
8315
+ const code = error.code;
8316
+ return typeof code === "string" && SAFE_AP_CODE_RE2.test(code) ? code : void 0;
8317
+ }
8318
+ function typedStatus2(error) {
8319
+ if (error === null || typeof error !== "object") return void 0;
8320
+ const status = error.status;
8321
+ return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599 ? status : void 0;
8322
+ }
8323
+ function typedPublicationReason(error, code) {
8324
+ if (error === null || typeof error !== "object") return void 0;
8325
+ const status = typedStatus2(error);
8326
+ if (status === void 0 || status < 400 || status > 499) return void 0;
8327
+ const reason = error.publicationReason;
8328
+ return isPublicationErrorReasonFor(code, reason) ? reason : void 0;
8329
+ }
8330
+ function publicationReasonText(reason, schemaReviewMessages) {
8331
+ switch (reason) {
8332
+ case "publication_schema_review_too_large":
8333
+ return schemaReviewMessages.schemaReviewTooLarge;
8334
+ case "publication_review_profile_invalid":
8335
+ return schemaReviewMessages.reviewProfileInvalid;
8336
+ case "schema_review_receipt_mismatch":
8337
+ return schemaReviewMessages.receiptMismatch;
8338
+ case "publication_plan_stale":
8339
+ return schemaReviewMessages.planStale;
8340
+ }
8341
+ }
8342
+ function remoteError(error, phase, messages, schemaReviewMessages) {
8343
+ const code = typedCode2(error) ?? "AP_NETWORK_ERROR";
8344
+ const publicationReason = schemaReviewMessages === void 0 ? void 0 : typedPublicationReason(error, code);
8345
+ if (publicationReason !== void 0 && schemaReviewMessages !== void 0) {
8346
+ return schemaReviewFailure(
8347
+ code,
8348
+ publicationReason,
8349
+ publicationReasonText(publicationReason, schemaReviewMessages),
8350
+ typedStatus2(error)
8351
+ );
7872
8352
  }
7873
- const apply = options.apply === true;
7874
- const yes = options.yes === true;
7875
- if (yes && !apply) {
7876
- throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8353
+ return new PublishCommandError(
8354
+ code,
8355
+ `${phase}_failed`,
8356
+ messages.remoteFailure(phase, code),
8357
+ typedStatus2(error)
8358
+ );
8359
+ }
8360
+ function parseConfirmationRequired(error, projectId, messages) {
8361
+ if (typedCode2(error) !== "AP_CONFIRMATION_REQUIRED") return null;
8362
+ if (typedStatus2(error) !== 409 || error === null || typeof error !== "object") {
8363
+ throw responseInvalid("publication_confirmation_required_error_invalid", messages);
7877
8364
  }
7878
- if (options.idempotencyKey !== void 0 && !apply) {
7879
- throw new UsageError("--idempotency-key \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8365
+ const details = asRecord4(error.confirmationRequired);
8366
+ if (!details || !hasExactKeys3(details, [
8367
+ "requestId",
8368
+ "publicationId",
8369
+ "verificationUri",
8370
+ "expiresIn",
8371
+ "pollInterval"
8372
+ ]) || !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) {
8373
+ throw responseInvalid("publication_confirmation_required_details_invalid", messages);
7880
8374
  }
7881
- if (!apply && options.planCommitment !== void 0) {
7882
- throw new UsageError("--plan-commitment \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8375
+ let uri;
8376
+ try {
8377
+ uri = new URL(details.verificationUri);
8378
+ } catch {
8379
+ throw responseInvalid("publication_verification_uri_invalid", messages);
8380
+ }
8381
+ const expectedPath = `/projects/${projectId}/tools/publications/${details.publicationId}`;
8382
+ if (uri.origin !== "https://admin.andpipe.com" || uri.pathname !== expectedPath || uri.username !== "" || uri.password !== "" || uri.search !== "" || uri.hash !== "" || uri.toString() !== details.verificationUri) {
8383
+ throw responseInvalid("publication_verification_uri_invalid", messages);
7883
8384
  }
7884
8385
  return {
7885
- file: options.file,
7886
- project: assertProjectId(options.project),
7887
- connectorId: assertProjectId(options.connector),
7888
- profile: options.profile ?? DEFAULT_PROFILE_NAME,
7889
- ...options.format !== void 0 ? { format: options.format } : {},
7890
- ...options.baseUrl !== void 0 ? { baseUrl: options.baseUrl } : {},
7891
- ...options.serviceName !== void 0 ? { serviceName: options.serviceName } : {},
7892
- apply,
7893
- yes,
7894
- ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {},
7895
- ...options.planCommitment !== void 0 ? { planCommitment: options.planCommitment } : {},
7896
- ...options.authMode !== void 0 ? { upstreamAuthMode: parseAuthModeOption(options.authMode) } : {},
7897
- sideEffectFree: parseSideEffectFreeOptions(options.sideEffectFree)
8386
+ requestId: details.requestId,
8387
+ publicationId: details.publicationId,
8388
+ verificationUri: details.verificationUri,
8389
+ expiresIn: 600,
8390
+ pollInterval: details.pollInterval
7898
8391
  };
7899
8392
  }
7900
- function rethrowWithAuthModeGuidance(error) {
7901
- if (error instanceof AdminApiClientError && error.openApiAuthModeMismatch) {
7902
- throw new UsageError(authModeMismatchGuidance(error.openApiAuthModeMismatch));
8393
+ function approvedApplyResultMayBeUnknown(error) {
8394
+ const status = typedStatus2(error);
8395
+ if (status !== void 0 && status >= 400 && status < 500) return false;
8396
+ const code = typedCode2(error);
8397
+ return code === void 0 || !DEFINITIVE_APPLY_ERROR_CODES.has(code);
8398
+ }
8399
+ function initialApplyResultMayBeUnknown(error) {
8400
+ const status = typedStatus2(error);
8401
+ if (status !== void 0 && status >= 400 && status < 500) return false;
8402
+ const code = typedCode2(error);
8403
+ if (status === void 0 && code !== void 0 && DEFINITIVE_APPLY_ERROR_CODES.has(code)) {
8404
+ return false;
7903
8405
  }
7904
- throw error;
8406
+ return true;
7905
8407
  }
7906
- async function runOpenApiImportCommand(options, writer, cwd, runtime = createOpenApiImportRuntime()) {
7907
- const normalized = normalizedOptions(options);
7908
- if (normalized.apply && !normalized.yes) {
7909
- throw new ConfirmationRequiredError(
7910
- "andpipe openapi import --apply",
7911
- "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"
8408
+ function writeSafeJson(writer, value) {
8409
+ json(writer, terminalSafeValue(value));
8410
+ }
8411
+ function writePlan(writer, plan) {
8412
+ writeSafeJson(writer, { phase: "plan", ...plan });
8413
+ }
8414
+ function writeSchemaReviewSummary(writer, plan, schemaReviewMessages) {
8415
+ if (plan.reviewProfile !== 2) return;
8416
+ const reviewed = plan.tools.filter((tool) => (tool.schemaReview?.enums.length ?? 0) > 0);
8417
+ if (reviewed.length === 0) return;
8418
+ interactive(writer, schemaReviewMessages.heading);
8419
+ for (const tool of reviewed) {
8420
+ const review = tool.schemaReview;
8421
+ if (!review) continue;
8422
+ const count = (change) => review.enums.filter((entry) => entry.change === change).length;
8423
+ interactive(
8424
+ writer,
8425
+ schemaReviewMessages.toolSummary({
8426
+ toolName: terminalSafeText(tool.toolName),
8427
+ total: review.enums.length,
8428
+ added: count("added"),
8429
+ changed: count("changed"),
8430
+ removed: count("removed"),
8431
+ unchanged: count("unchanged"),
8432
+ valueReviewRequired: review.humanValueReviewRequired
8433
+ })
7912
8434
  );
7913
8435
  }
7914
- if (normalized.apply && !/^[a-f0-9]{64}$/.test(normalized.planCommitment ?? "")) {
7915
- throw new UsageError("--apply \u306B\u306Fpreview\u3067\u5F97\u305F --plan-commitment \u304C\u5FC5\u9808\u3067\u3059");
8436
+ if (reviewed.some((tool) => tool.schemaReview?.humanValueReviewRequired === true)) {
8437
+ interactive(writer, schemaReviewMessages.valueReviewInWebAdmin);
7916
8438
  }
7917
- const snapshot = readBoundedLocalFileSnapshot(resolve4(cwd, normalized.file), {
7918
- maxBytes: OPENAPI_IMPORT_MAX_SOURCE_BYTES2,
7919
- root: cwd
7920
- });
7921
- const baseRequest = {
7922
- source: snapshot.text,
7923
- connectorId: normalized.connectorId,
7924
- ...normalized.format !== void 0 ? { format: normalized.format } : {},
7925
- ...normalized.baseUrl !== void 0 ? { baseUrl: normalized.baseUrl } : {},
7926
- ...normalized.serviceName !== void 0 ? { serviceName: normalized.serviceName } : {},
7927
- ...normalized.upstreamAuthMode !== void 0 ? { upstreamAuthMode: normalized.upstreamAuthMode } : {}
8439
+ }
8440
+ function candidateNeedsReviewProfile2(candidateContract) {
8441
+ return selectPublicationReviewProfile({
8442
+ requestedProfile: CLI_PUBLICATION_REVIEW_PROFILE,
8443
+ candidateContract,
8444
+ currentTools: []
8445
+ }) === 2;
8446
+ }
8447
+ function applyPublicationWithProfile(client, projectId, idempotencyKey, body, session) {
8448
+ return session.kind === "negotiated" ? client.applyPublication(projectId, idempotencyKey, body, REVIEW_PROFILE_REQUEST) : client.applyPublication(projectId, idempotencyKey, body);
8449
+ }
8450
+ function writeResult(writer, result) {
8451
+ writeSafeJson(writer, { phase: "result", ...result });
8452
+ }
8453
+ function freezeJson(value) {
8454
+ if (Array.isArray(value)) {
8455
+ for (const item of value) freezeJson(item);
8456
+ return Object.freeze(value);
8457
+ }
8458
+ if (value !== null && typeof value === "object") {
8459
+ for (const item of Object.values(value)) freezeJson(item);
8460
+ return Object.freeze(value);
8461
+ }
8462
+ return value;
8463
+ }
8464
+ function prepareCandidate(project) {
8465
+ const canonical = assertCanonicalPublicationSize2(project.contract.root);
8466
+ const candidateContract = freezeJson(JSON.parse(canonical));
8467
+ return {
8468
+ candidateContract,
8469
+ candidateCommitment: publicationCommitment2("candidate", candidateContract)
7928
8470
  };
7929
- const client = runtime.createClient(normalized.profile);
7930
- const assertSource = (sourceCommitment) => {
7931
- if (sourceCommitment !== snapshot.sha256) {
7932
- throw new UsageError("Admin API\u306Esource commitment\u304Clocal file\u3068\u4E00\u81F4\u3057\u307E\u305B\u3093");
8471
+ }
8472
+ function loadPublicationProject(loadProject, cwd, messages = DEFAULT_PUBLISH_MESSAGES) {
8473
+ try {
8474
+ return loadProject(cwd);
8475
+ } catch (error) {
8476
+ if (error instanceof LocalFilePolicyError) {
8477
+ throw new PublishCommandError(
8478
+ "AP_POLICY_DENIED",
8479
+ error.reason,
8480
+ messages.failure(error.reason)
8481
+ );
8482
+ }
8483
+ const reason = error instanceof DevProjectLoadError ? error.reason : "local_project_invalid";
8484
+ if (error instanceof DevProjectLoadError || error instanceof UsageError) {
8485
+ throw new PublishCommandError("AP_INPUT_INVALID", reason, messages.failure(reason));
7933
8486
  }
8487
+ throw error;
8488
+ }
8489
+ }
8490
+ function assertManifestProject(project, requestedProjectId, messages = DEFAULT_PUBLISH_MESSAGES) {
8491
+ const projectId = project.manifest.project_id;
8492
+ if (requestedProjectId !== void 0 && requestedProjectId !== projectId) {
8493
+ throw new PublishCommandError(
8494
+ "AP_CONFLICT",
8495
+ "manifest_project_mismatch",
8496
+ messages.failure("manifest_project_mismatch")
8497
+ );
8498
+ }
8499
+ return projectId;
8500
+ }
8501
+ function buildLocalPublicationCandidate(project, connectorId, messages = DEFAULT_PUBLISH_MESSAGES) {
8502
+ const candidate = prepareCandidate(project);
8503
+ const localToolNames = project.contract.tools.map((tool) => toolName2(tool));
8504
+ if (localToolNames.some((name) => !isSafeToolName3(name))) {
8505
+ throw new PublishCommandError(
8506
+ "AP_INPUT_INVALID",
8507
+ "publication_candidate_tool_invalid",
8508
+ messages.failure("publication_candidate_tool_invalid")
8509
+ );
8510
+ }
8511
+ const expectedToolNames = localToolNames.sort(comparePublicationUnicodeCodePoints2);
8512
+ return {
8513
+ planRequest: {
8514
+ environment: "production",
8515
+ connectorId,
8516
+ candidateContract: candidate.candidateContract,
8517
+ candidateCommitment: candidate.candidateCommitment,
8518
+ ...project.manifest.template_id && project.manifest.template_application_commitment ? {
8519
+ templateProvenance: {
8520
+ templateId: project.manifest.template_id,
8521
+ applicationCommitment: project.manifest.template_application_commitment
8522
+ }
8523
+ } : {}
8524
+ },
8525
+ expectedToolNames
7934
8526
  };
7935
- let overrides = [];
7936
- if (normalized.sideEffectFree.length > 0) {
7937
- if (normalized.apply) {
8527
+ }
8528
+ function assertIdempotencyKey2(value, messages) {
8529
+ if (!UUID_RE6.test(value)) {
8530
+ throw new PublishCommandError(
8531
+ "AP_NETWORK_ERROR",
8532
+ "secure_random_invalid",
8533
+ messages.failure("secure_random_invalid")
8534
+ );
8535
+ }
8536
+ return value;
8537
+ }
8538
+ async function sendInitialApplyWithSameAnchorRetry(input) {
8539
+ for (let attempt = 0; attempt < INITIAL_APPLY_MAX_ATTEMPTS; attempt += 1) {
8540
+ try {
8541
+ const result = parsePublicationResult(
8542
+ await applyPublicationWithProfile(
8543
+ input.client,
8544
+ input.projectId,
8545
+ input.idempotencyKey,
8546
+ input.body,
8547
+ input.session
8548
+ ),
8549
+ input.plan,
8550
+ input.messages
8551
+ );
8552
+ if (result.state !== "noop") {
8553
+ throw responseInvalid("publication_initial_apply_state_invalid", input.messages);
8554
+ }
8555
+ return {
8556
+ kind: "response",
8557
+ result
8558
+ };
8559
+ } catch (error) {
8560
+ let malformedConfirmationAnchor = false;
8561
+ let confirmationRequired = null;
7938
8562
  try {
7939
- const unclassified = importOpenApi2(snapshot.text, {
7940
- format: normalized.format,
7941
- baseUrl: normalized.baseUrl,
7942
- serviceName: normalized.serviceName,
7943
- upstreamAuthMode: normalized.upstreamAuthMode
7944
- });
7945
- overrides = resolveOperationRiskOverrides(
7946
- normalized.sideEffectFree,
7947
- unclassified.operations
7948
- );
7949
- } catch (error) {
7950
- if (error instanceof OpenApiImportError3) {
7951
- throw new UsageError(`OpenAPI\u304B\u3089Tool Contract\u3092\u751F\u6210\u3067\u304D\u307E\u305B\u3093: ${error.message}`);
8563
+ confirmationRequired = parseConfirmationRequired(error, input.projectId, input.messages);
8564
+ } catch (parseError) {
8565
+ if (typedCode2(error) !== "AP_CONFIRMATION_REQUIRED" || !(parseError instanceof PublishCommandError) || parseError.code !== "AP_RESPONSE_INVALID") {
8566
+ throw parseError;
7952
8567
  }
7953
- throw error;
8568
+ malformedConfirmationAnchor = true;
8569
+ }
8570
+ if (confirmationRequired) {
8571
+ return { kind: "confirmation_required", details: confirmationRequired };
8572
+ }
8573
+ if (!malformedConfirmationAnchor && !initialApplyResultMayBeUnknown(error)) {
8574
+ throw remoteError(error, "initial_apply", input.messages, input.schemaReviewMessages);
8575
+ }
8576
+ if (attempt === INITIAL_APPLY_MAX_ATTEMPTS - 1) {
8577
+ throw new PublishCommandError(
8578
+ "AP_RESULT_UNKNOWN",
8579
+ "publication_anchor_result_unknown",
8580
+ input.messages.proposalResultUnknown
8581
+ );
7954
8582
  }
7955
- } else {
7956
- const unclassified = await client.planOpenApiImport(normalized.project, baseRequest).catch(rethrowWithAuthModeGuidance);
7957
- assertSource(unclassified.sourceCommitment);
7958
- overrides = resolveOperationRiskOverrides(normalized.sideEffectFree, unclassified.operations);
7959
8583
  }
7960
8584
  }
7961
- const request = {
7962
- ...baseRequest,
7963
- ...overrides.length > 0 ? { operationRiskOverrides: overrides } : {},
7964
- ...normalized.planCommitment !== void 0 ? { expectedPlanCommitment: normalized.planCommitment } : {}
7965
- };
7966
- const classification = {
7967
- upstreamAuthMode: normalized.upstreamAuthMode ?? "token_exchange",
7968
- operationRiskOverrides: overrides
7969
- };
7970
- if (!normalized.apply) {
7971
- const result2 = await client.planOpenApiImport(normalized.project, request).catch(rethrowWithAuthModeGuidance);
7972
- assertSource(result2.sourceCommitment);
7973
- json(writer, { mode: "preview", ...classification, ...result2 });
7974
- const guidance = sideEffectFreeGuidance(result2.operations);
7975
- if (guidance) interactive(writer, guidance);
7976
- return;
7977
- }
7978
- const result = await client.applyOpenApiImport(
7979
- normalized.project,
7980
- normalized.idempotencyKey ?? runtime.idempotencyKey(),
7981
- request
7982
- ).catch(rethrowWithAuthModeGuidance);
7983
- assertSource(result.sourceCommitment);
7984
- json(writer, { mode: "draft_created", ...classification, ...result });
8585
+ throw new PublishCommandError(
8586
+ "AP_RESULT_UNKNOWN",
8587
+ "publication_anchor_result_unknown",
8588
+ input.messages.proposalResultUnknown
8589
+ );
7985
8590
  }
7986
- function collect(value, previous) {
7987
- return [...previous, value];
8591
+ function confirmationStopped(code, reason, messages) {
8592
+ return new PublishCommandError(code, reason, messages.confirmationStopped(reason));
7988
8593
  }
7989
- function registerOpenApi(program, writer, cwd, runtime = createOpenApiImportRuntime()) {
7990
- const openapi = program.command("openapi").description("OpenAPI\u304B\u3089Tool Contract draft\u3092\u63D0\u6848\u3059\u308B");
7991
- 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(
7992
- "--auth-mode <mode>",
7993
- "connector\u3068\u540C\u3058\u8A8D\u8A3C\u65B9\u5F0F\uFF08existing_oauth \u307E\u305F\u306F token_exchange\u3002\u7701\u7565\u6642\u306Ftoken_exchange\uFF09"
7994
- ).option(
7995
- "--side-effect-free <toolName=level>",
7996
- "\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",
7997
- collect,
7998
- []
7999
- ).action(
8000
- (options) => runOpenApiImportCommand(options, writer, cwd(), runtime)
8001
- );
8594
+ function pollFailureIsDefinitive(error) {
8595
+ const status = typedStatus2(error);
8596
+ if (status !== void 0 && status >= 400 && status < 500) return true;
8597
+ const code = typedCode2(error);
8598
+ return code === "AP_RESPONSE_INVALID" || code === "AP_OUTPUT_INVALID" || code !== void 0 && DEFINITIVE_APPLY_ERROR_CODES.has(code);
8002
8599
  }
8003
-
8004
- // src/commands/publish.ts
8005
- import { randomUUID as randomUUID7 } from "crypto";
8006
- import { CLI_MESSAGES as CLI_MESSAGES9 } from "@andpipes/localization";
8007
- import {
8008
- assertCanonicalPublicationSize as assertCanonicalPublicationSize2,
8009
- comparePublicationUnicodeCodePoints as comparePublicationUnicodeCodePoints2,
8010
- isSafeToolName as isSafeToolName2,
8011
- PUBLICATION_CONFIRMATION_SIGNATURE_RE as PUBLICATION_CONFIRMATION_SIGNATURE_RE2,
8012
- PUBLICATION_SHA256_COMMITMENT_RE as PUBLICATION_SHA256_COMMITMENT_RE2,
8013
- parsePublicationSafeDiffDto,
8014
- parsePublicationWarningsDto,
8015
- publicationCommitment as publicationCommitment2,
8016
- toolName as toolName2
8017
- } from "@andpipes/tool-contract";
8018
- 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;
8019
- var SAFE_AP_CODE_RE2 = /^AP_[A-Z0-9_]{1,64}$/u;
8020
- var PUBLICATION_RESPONSE_MAX_BYTES = 96 * 1024;
8021
- var INITIAL_APPLY_MAX_ATTEMPTS = 3;
8022
- var DEFAULT_PUBLISH_MESSAGES = CLI_MESSAGES9.ja.publish;
8023
- var PLAN_KEYS = [
8024
- "requestId",
8025
- "environment",
8026
- "connectorId",
8027
- "connectorRevision",
8028
- "connectorCommitment",
8029
- "policyCommitment",
8030
- "candidateCommitment",
8031
- "baseCommitment",
8032
- "planCommitment",
8033
- "tools",
8034
- "retainedTools",
8035
- "warnings",
8036
- "applyAllowed",
8037
- "blockedReasons"
8038
- ];
8039
- var APPLY_RESULT_KEYS = ["requestId", "publicationId", "state", "tools", "warnings"];
8040
- var STATUS_KEYS = [
8041
- "requestId",
8042
- "publicationId",
8043
- "durableState",
8044
- "effectiveState",
8045
- "expiresAt",
8046
- "confirmation",
8047
- "result"
8048
- ];
8049
- var BLOCKED_REASONS = /* @__PURE__ */ new Set([
8050
- "project_not_active",
8051
- "connector_not_active",
8052
- "connector_mismatch",
8053
- "tool_deprecated",
8054
- "tool_plan_limit_exceeded",
8055
- "production_capability_required",
8056
- "write_tool_mode_not_confirmed",
8057
- "production_oauth_broker_required",
8058
- "oauth_scope_registry_missing",
8059
- "oauth_scope_registry_risk_insufficient",
8060
- "publish_gate_failed",
8061
- "opaque_change",
8062
- "retention_policy_blocked",
8063
- "descriptor_name_conflict"
8064
- ]);
8065
- var TOOL_BLOCKED_REASONS = [
8066
- "connector_mismatch",
8067
- "opaque_change",
8068
- "publish_gate_failed",
8069
- "tool_deprecated"
8070
- ];
8071
- var DURABLE_STATES = /* @__PURE__ */ new Set(["pending", "approved", "rejected", "expired", "consumed"]);
8072
- var EFFECTIVE_STATES = /* @__PURE__ */ new Set([
8073
- "pending",
8074
- "approved",
8075
- "rejected",
8076
- "expired",
8077
- "consumed",
8078
- "stale"
8079
- ]);
8080
- var DEFINITIVE_APPLY_ERROR_CODES = /* @__PURE__ */ new Set([
8081
- "AP_AUTH_REQUIRED",
8082
- "AP_CONFIRMATION_EXPIRED",
8083
- "AP_CONFLICT",
8084
- "AP_FORBIDDEN",
8085
- "AP_IDEMPOTENCY_KEY_CONFLICT",
8086
- "AP_INPUT_INVALID",
8087
- "AP_INVALID_SCOPE",
8088
- "AP_NOT_FOUND",
8089
- "AP_POLICY_DENIED",
8090
- "AP_UNAUTHORIZED"
8091
- ]);
8092
- var PublishCommandError = class extends Error {
8093
- constructor(code, reason, message, status) {
8094
- super(message);
8095
- this.code = code;
8096
- this.reason = reason;
8097
- this.status = status;
8098
- this.name = "PublishCommandError";
8600
+ async function sleepForPoll(runtime, milliseconds, mode, messages) {
8601
+ try {
8602
+ await runtime.sleep(milliseconds);
8603
+ } catch {
8604
+ throw new PublishCommandError(
8605
+ mode === "recover-result" ? "AP_RESULT_UNKNOWN" : "AP_NETWORK_ERROR",
8606
+ "publication_poll_sleep_failed",
8607
+ messages.pollingUnavailable
8608
+ );
8099
8609
  }
8100
- code;
8101
- reason;
8102
- status;
8103
- };
8104
- function createPublishCommandRuntime(createClient) {
8105
- return {
8106
- createClient,
8107
- loadProject: loadDevProject,
8108
- randomUuid: () => randomUUID7(),
8109
- monotonicNow: () => Number(process.hrtime.bigint() / 1000000n),
8110
- wallNow: () => Date.now(),
8111
- sleep: (milliseconds) => new Promise((resolve6) => setTimeout(resolve6, milliseconds))
8112
- };
8113
8610
  }
8114
- function canonicalUuid(value, option, messages) {
8115
- const canonical = value.toLowerCase();
8116
- if (!UUID_RE6.test(canonical)) {
8117
- throw new UsageError(messages.invalidOption(option, "a canonical RFC 4122 UUID"));
8611
+ async function pollPublication(client, projectId, details, plan, writer, runtime, mode, messages, knownExpiresAt) {
8612
+ const startedAt = runtime.monotonicNow();
8613
+ let deadline = startedAt + details.expiresIn * 1e3;
8614
+ let expiresAt = knownExpiresAt;
8615
+ if (knownExpiresAt !== void 0) {
8616
+ deadline = Math.min(
8617
+ deadline,
8618
+ startedAt + Math.max(0, Date.parse(knownExpiresAt) - runtime.wallNow())
8619
+ );
8620
+ }
8621
+ const maxAttempts = Math.ceil(details.expiresIn / details.pollInterval) + 2;
8622
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
8623
+ let rawStatus;
8624
+ try {
8625
+ rawStatus = await client.getPublication(projectId, details.publicationId);
8626
+ } catch (error) {
8627
+ if (pollFailureIsDefinitive(error)) {
8628
+ throw remoteError(error, mode === "recover-result" ? "result_recovery" : "poll", messages);
8629
+ }
8630
+ const remainingMilliseconds2 = Math.max(0, deadline - runtime.monotonicNow());
8631
+ if (remainingMilliseconds2 <= 0 || attempt === maxAttempts - 1) {
8632
+ throw new PublishCommandError(
8633
+ mode === "recover-result" ? "AP_RESULT_UNKNOWN" : "AP_NETWORK_ERROR",
8634
+ "publication_poll_unavailable",
8635
+ messages.pollingUnavailable
8636
+ );
8637
+ }
8638
+ await sleepForPoll(
8639
+ runtime,
8640
+ Math.min(details.pollInterval * 1e3, remainingMilliseconds2),
8641
+ mode,
8642
+ messages
8643
+ );
8644
+ continue;
8645
+ }
8646
+ const status = parseStatus(rawStatus, details.publicationId, plan, messages);
8647
+ if (expiresAt !== void 0 && status.expiresAt !== expiresAt) {
8648
+ throw responseInvalid("publication_expiry_changed", messages);
8649
+ }
8650
+ expiresAt = status.expiresAt;
8651
+ const now = runtime.monotonicNow();
8652
+ const wallRemaining = Math.max(0, Date.parse(status.expiresAt) - runtime.wallNow());
8653
+ deadline = Math.min(deadline, now + wallRemaining);
8654
+ const remainingMilliseconds = Math.max(0, deadline - now);
8655
+ writeSafeJson(writer, {
8656
+ phase: mode === "recover-result" ? "result_recovery" : "confirmation",
8657
+ requestId: status.requestId,
8658
+ publicationId: status.publicationId,
8659
+ durableState: status.durableState,
8660
+ effectiveState: status.effectiveState,
8661
+ expiresAt: status.expiresAt,
8662
+ remainingSeconds: Math.ceil(remainingMilliseconds / 1e3)
8663
+ });
8664
+ if (status.durableState === "consumed") {
8665
+ return { kind: "consumed", result: status.result };
8666
+ }
8667
+ if (status.durableState === "rejected") {
8668
+ throw confirmationStopped("AP_POLICY_DENIED", "publication_rejected", messages);
8669
+ }
8670
+ if (status.durableState === "expired") {
8671
+ throw confirmationStopped(
8672
+ "AP_CONFIRMATION_EXPIRED",
8673
+ "publication_confirmation_expired",
8674
+ messages
8675
+ );
8676
+ }
8677
+ if (status.effectiveState === "stale") {
8678
+ throw confirmationStopped("AP_CONFLICT", "publication_confirmation_stale", messages);
8679
+ }
8680
+ if (mode === "await-approval" && status.durableState === "approved" && status.confirmation !== null) {
8681
+ return {
8682
+ kind: "approved",
8683
+ confirmation: status.confirmation,
8684
+ expiresAt: status.expiresAt
8685
+ };
8686
+ }
8687
+ if (remainingMilliseconds <= 0) {
8688
+ throw confirmationStopped(
8689
+ "AP_CONFIRMATION_EXPIRED",
8690
+ "publication_confirmation_timeout",
8691
+ messages
8692
+ );
8693
+ }
8694
+ const sleepMilliseconds = Math.min(details.pollInterval * 1e3, remainingMilliseconds);
8695
+ await sleepForPoll(runtime, sleepMilliseconds, mode, messages);
8696
+ }
8697
+ throw confirmationStopped("AP_CONFIRMATION_EXPIRED", "publication_poll_attempt_limit", messages);
8698
+ }
8699
+ async function runPublishCommand(options, writer, cwd, runtime, messages = DEFAULT_PUBLISH_MESSAGES, scopeRegistrationMessages = DEFAULT_SCOPE_REGISTRATION_MESSAGES2, schemaReviewMessages = DEFAULT_SCHEMA_REVIEW_MESSAGES) {
8700
+ const normalized = normalizePublishOptions(options, messages);
8701
+ const project = loadPublicationProject(runtime.loadProject, cwd, messages);
8702
+ const projectId = project.manifest.project_id;
8703
+ const connectorId = normalized.connectorId ?? project.manifest.connector_id;
8704
+ if (connectorId === void 0) {
8705
+ throw new PublishCommandError(
8706
+ "AP_INPUT_INVALID",
8707
+ "publication_connector_required",
8708
+ messages.optionRequires("publish", "--connector UUID")
8709
+ );
8710
+ }
8711
+ assertManifestProject(project, normalized.projectId, messages);
8712
+ const { planRequest, expectedToolNames } = buildLocalPublicationCandidate(
8713
+ project,
8714
+ connectorId,
8715
+ messages
8716
+ );
8717
+ const client = runtime.createClient(normalized.profile);
8718
+ let rawPlan;
8719
+ try {
8720
+ rawPlan = await client.planPublication(projectId, planRequest, REVIEW_PROFILE_REQUEST);
8721
+ } catch (error) {
8722
+ throw remoteError(error, "plan", messages, schemaReviewMessages);
8723
+ }
8724
+ const negotiated = negotiateReviewProfile(rawPlan, messages, schemaReviewMessages);
8725
+ const session = negotiated.session;
8726
+ const plan = parsePlan(
8727
+ negotiated.body,
8728
+ connectorId,
8729
+ planRequest.candidateCommitment,
8730
+ expectedToolNames,
8731
+ session.profile,
8732
+ messages
8733
+ );
8734
+ writePlan(writer, plan);
8735
+ writeSchemaReviewSummary(writer, plan, schemaReviewMessages);
8736
+ if (session.kind === "legacy" && plan.blockedReasons.includes("opaque_change") && candidateNeedsReviewProfile2(planRequest.candidateContract)) {
8737
+ interactive(writer, schemaReviewMessages.adminApiUpdatePending);
8738
+ }
8739
+ if (plan.blockedReasons.includes("connector_mismatch")) {
8740
+ interactive(writer, messages.connectorMismatchRemediation);
8741
+ }
8742
+ if (plan.blockedReasons.includes("oauth_scope_registry_missing") || plan.blockedReasons.includes("oauth_scope_registry_risk_insufficient")) {
8743
+ interactive(
8744
+ writer,
8745
+ planRequest.templateProvenance ? scopeRegistrationMessages.publishTemplateRemediation(projectId) : scopeRegistrationMessages.publishRemediation(connectorId)
8746
+ );
8747
+ }
8748
+ if (normalized.mode === "dry-run") return;
8749
+ if (!plan.applyAllowed) {
8750
+ throw new PublishCommandError(
8751
+ "AP_POLICY_DENIED",
8752
+ "publication_plan_blocked",
8753
+ messages.planBlocked(plan.blockedReasons)
8754
+ );
8755
+ }
8756
+ const idempotencyKey = assertIdempotencyKey2(runtime.randomUuid(), messages);
8757
+ const applyRequest = (confirmation) => ({
8758
+ ...planRequest,
8759
+ planCommitment: plan.planCommitment,
8760
+ confirmation
8761
+ });
8762
+ const initialApplyRequest = freezeJson(applyRequest(null));
8763
+ const initial = await sendInitialApplyWithSameAnchorRetry({
8764
+ client,
8765
+ projectId,
8766
+ idempotencyKey,
8767
+ body: initialApplyRequest,
8768
+ plan,
8769
+ session,
8770
+ messages,
8771
+ schemaReviewMessages
8772
+ });
8773
+ let details;
8774
+ if (initial.kind === "response") {
8775
+ writeResult(writer, initial.result);
8776
+ return;
8777
+ } else {
8778
+ if (plan.tools.every((tool) => !tool.changed)) {
8779
+ throw responseInvalid("publication_noop_confirmation_invalid", messages);
8780
+ }
8781
+ details = initial.details;
8118
8782
  }
8119
- return canonical;
8120
- }
8121
- function normalizePublishOptions(options, messages = DEFAULT_PUBLISH_MESSAGES) {
8122
- if (options.dryRun === true && options.apply === true) {
8123
- throw new UsageError(messages.incompatibleOptions("--dry-run / --apply"));
8783
+ writeSafeJson(writer, { phase: "confirmation_required", ...details });
8784
+ const decision = await pollPublication(
8785
+ client,
8786
+ projectId,
8787
+ details,
8788
+ plan,
8789
+ writer,
8790
+ runtime,
8791
+ "await-approval",
8792
+ messages
8793
+ );
8794
+ if (decision.kind === "consumed") {
8795
+ writeResult(writer, decision.result);
8796
+ return;
8124
8797
  }
8125
- if (options.yes === true && options.apply !== true) {
8126
- throw new UsageError(messages.optionRequires("--yes", "--apply"));
8798
+ try {
8799
+ const result = parsePublicationResult(
8800
+ await applyPublicationWithProfile(
8801
+ client,
8802
+ projectId,
8803
+ idempotencyKey,
8804
+ applyRequest(decision.confirmation),
8805
+ session
8806
+ ),
8807
+ plan,
8808
+ messages,
8809
+ details.publicationId
8810
+ );
8811
+ writeResult(writer, result);
8812
+ return;
8813
+ } catch (error) {
8814
+ if (error instanceof PublishCommandError && error.code === "AP_RESPONSE_INVALID") {
8815
+ } else if (!approvedApplyResultMayBeUnknown(error)) {
8816
+ throw remoteError(error, "approved_apply", messages, schemaReviewMessages);
8817
+ }
8127
8818
  }
8128
- if (options.apply === true && options.yes !== true) {
8129
- throw new ConfirmationRequiredError(
8130
- "andpipe publish --apply",
8131
- messages.applyConfirmationRequired
8819
+ const recovered = await pollPublication(
8820
+ client,
8821
+ projectId,
8822
+ details,
8823
+ plan,
8824
+ writer,
8825
+ runtime,
8826
+ "recover-result",
8827
+ messages,
8828
+ decision.expiresAt
8829
+ );
8830
+ if (recovered.kind !== "consumed") {
8831
+ throw new PublishCommandError(
8832
+ "AP_RESULT_UNKNOWN",
8833
+ "publication_result_unknown",
8834
+ messages.resultUnknown
8132
8835
  );
8133
8836
  }
8134
- const projectId = options.project === void 0 ? void 0 : canonicalUuid(options.project, "--project", messages);
8135
- return {
8136
- mode: options.apply === true ? "apply" : "dry-run",
8137
- ...options.connector === void 0 ? {} : { connectorId: canonicalUuid(options.connector, "--connector", messages) },
8138
- profile: options.profile ?? DEFAULT_PROFILE_NAME,
8139
- ...projectId === void 0 ? {} : { projectId }
8140
- };
8141
- }
8142
- function asRecord4(value) {
8143
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
8144
- }
8145
- function hasExactKeys3(record, keys) {
8146
- const actual = Object.keys(record);
8147
- return actual.length === keys.length && actual.every((key) => keys.includes(key));
8837
+ writeResult(writer, recovered.result);
8148
8838
  }
8149
- function responseInvalid(reason, messages) {
8150
- return new PublishCommandError("AP_RESPONSE_INVALID", reason, messages.failure(reason));
8839
+ 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) {
8840
+ 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) => {
8841
+ await runPublishCommand(
8842
+ commandOptions,
8843
+ writer,
8844
+ cwd(),
8845
+ runtime,
8846
+ messages,
8847
+ scopeRegistrationMessages,
8848
+ schemaReviewMessages
8849
+ );
8850
+ });
8151
8851
  }
8152
- function assertCanonicalResponseSize(value, reason, messages, maxBytes = PUBLICATION_RESPONSE_MAX_BYTES) {
8153
- try {
8154
- assertCanonicalPublicationSize2(value, maxBytes);
8155
- } catch {
8156
- throw responseInvalid(reason, messages);
8852
+
8853
+ // src/commands/oauth.ts
8854
+ function isUrl(value) {
8855
+ if (typeof value !== "string") {
8856
+ return false;
8157
8857
  }
8158
- }
8159
- function isCanonicalUuid(value) {
8160
- return typeof value === "string" && UUID_RE6.test(value);
8161
- }
8162
- function isCommitment(value) {
8163
- return typeof value === "string" && PUBLICATION_SHA256_COMMITMENT_RE2.test(value);
8164
- }
8165
- function isCanonicalTimestamp(value) {
8166
- if (typeof value !== "string" || value.length > 64) return false;
8167
- const milliseconds = Date.parse(value);
8168
- return Number.isFinite(milliseconds) && new Date(milliseconds).toISOString() === value;
8169
- }
8170
- function isStrictlySorted(values) {
8171
- return values.every(
8172
- (value, index) => index === 0 || comparePublicationUnicodeCodePoints2(values[index - 1], value) < 0
8173
- );
8174
- }
8175
- function parseWarnings(value, messages) {
8176
8858
  try {
8177
- return parsePublicationWarningsDto(value);
8859
+ const u = new URL(value);
8860
+ return u.protocol === "http:" || u.protocol === "https:";
8178
8861
  } catch {
8179
- throw responseInvalid("publication_warnings_invalid", messages);
8862
+ return false;
8180
8863
  }
8181
8864
  }
8182
- function parsePlan(value, connectorId, candidateCommitment, expectedToolNames, messages) {
8183
- assertCanonicalResponseSize(value, "publication_plan_too_large", messages);
8184
- const plan = asRecord4(value);
8185
- 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(
8186
- (reason) => typeof reason === "string" && BLOCKED_REASONS.has(reason)
8187
- ) || !isStrictlySorted(plan.blockedReasons) || plan.applyAllowed !== (plan.blockedReasons.length === 0)) {
8188
- throw responseInvalid("publication_plan_invalid", messages);
8865
+ function field(meta, snake, camel) {
8866
+ return snake in meta ? meta[snake] : meta[camel];
8867
+ }
8868
+ function validateOAuthMetadata(meta, locale = DEFAULT_LOCALE7) {
8869
+ const messages = CLI_MESSAGES9[locale].oauth;
8870
+ const results = [];
8871
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
8872
+ return {
8873
+ ok: false,
8874
+ results: [
8875
+ {
8876
+ id: "metadata",
8877
+ label: "metadata",
8878
+ status: "fail",
8879
+ detail: messages.metadataNotObject
8880
+ }
8881
+ ]
8882
+ };
8189
8883
  }
8190
- const blockedReasons = plan.blockedReasons;
8191
- let safeDiff;
8192
- try {
8193
- safeDiff = parsePublicationSafeDiffDto({
8194
- tools: plan.tools,
8195
- retainedTools: plan.retainedTools,
8196
- warnings: plan.warnings
8884
+ const m = meta;
8885
+ const urlFields = [
8886
+ ["issuer", "issuer", "issuer"],
8887
+ ["authorization_endpoint", "authorization_endpoint", "authorizationEndpoint"],
8888
+ ["token_endpoint", "token_endpoint", "tokenEndpoint"],
8889
+ ["jwks_uri", "jwks_uri", "jwksUri"]
8890
+ ];
8891
+ for (const [id, snake, camel] of urlFields) {
8892
+ const value = field(m, snake, camel);
8893
+ const ok = isUrl(value);
8894
+ results.push({
8895
+ id,
8896
+ label: id,
8897
+ status: ok ? "pass" : "fail",
8898
+ detail: ok ? messages.urlOk : messages.invalidUrl(id)
8197
8899
  });
8198
- } catch {
8199
- throw responseInvalid("publication_safe_diff_invalid", messages);
8200
- }
8201
- const tools = safeDiff.tools;
8202
- const toolNames = tools.map((tool) => tool.toolName);
8203
- if (!isStrictlySorted(toolNames) || JSON.stringify(toolNames) !== JSON.stringify(expectedToolNames)) {
8204
- throw responseInvalid("publication_plan_tools_order_invalid", messages);
8205
8900
  }
8206
- const warnings = safeDiff.warnings;
8207
- const expectedPlanCommitment = publicationCommitment2("plan", {
8208
- candidateCommitment,
8209
- baseCommitment: plan.baseCommitment,
8210
- connectorId,
8211
- connectorRevision: plan.connectorRevision,
8212
- connectorCommitment: plan.connectorCommitment,
8213
- policyCommitment: plan.policyCommitment,
8214
- environment: "production",
8215
- safeDiff
8901
+ const responseTypes = field(m, "response_types_supported", "responseTypesSupported");
8902
+ results.push({
8903
+ id: "response_types_supported",
8904
+ label: "response_types_supported",
8905
+ status: Array.isArray(responseTypes) && responseTypes.length > 0 ? "pass" : "fail",
8906
+ detail: Array.isArray(responseTypes) ? messages.present : messages.arrayMissing
8216
8907
  });
8217
- if (plan.planCommitment !== expectedPlanCommitment) {
8218
- throw new PublishCommandError(
8219
- "AP_CONFLICT",
8220
- "publication_plan_commitment_mismatch",
8221
- messages.failure("publication_plan_commitment_mismatch")
8222
- );
8223
- }
8224
- const toolBlockedReasons = new Set(tools.flatMap((tool) => tool.blockedReasons));
8225
- if (tools.some((tool) => !tool.gate.ok) && plan.applyAllowed || tools.some((tool) => tool.opaqueChanged) && (plan.applyAllowed || !blockedReasons.includes("opaque_change")) || TOOL_BLOCKED_REASONS.some(
8226
- (reason) => (
8227
- // connector_mismatchはtool単位(既存toolの別connector束縛)に加え、candidateの
8228
- // upstream.auth.modeとconnector方式の不一致としてtop-levelだけにも出る (#456 / #724)。
8229
- reason === "connector_mismatch" ? toolBlockedReasons.has(reason) && !blockedReasons.includes(reason) : blockedReasons.includes(reason) !== toolBlockedReasons.has(reason)
8230
- )
8231
- )) {
8232
- throw responseInvalid("publication_plan_gate_inconsistent", messages);
8233
- }
8234
- return {
8235
- requestId: plan.requestId,
8236
- environment: "production",
8237
- connectorId,
8238
- connectorRevision: plan.connectorRevision,
8239
- connectorCommitment: plan.connectorCommitment,
8240
- policyCommitment: plan.policyCommitment,
8241
- candidateCommitment,
8242
- baseCommitment: plan.baseCommitment,
8243
- planCommitment: plan.planCommitment,
8244
- tools,
8245
- retainedTools: safeDiff.retainedTools,
8246
- warnings,
8247
- applyAllowed: plan.applyAllowed,
8248
- blockedReasons
8249
- };
8250
- }
8251
- function sameWarnings(left, right) {
8252
- return JSON.stringify(left) === JSON.stringify(right);
8253
- }
8254
- function parseToolResults(value, messages) {
8255
- if (!Array.isArray(value)) {
8256
- throw responseInvalid("publication_result_tools_invalid", messages);
8257
- }
8258
- const tools = value.map((candidate) => {
8259
- const tool = asRecord4(candidate);
8260
- if (!tool || !hasExactKeys3(tool, ["toolName", "operation", "toolId", "versionId", "version"]) || !isSafeToolName2(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) {
8261
- throw responseInvalid("publication_result_tool_invalid", messages);
8262
- }
8263
- const operation = tool.operation;
8264
- return {
8265
- toolName: tool.toolName,
8266
- operation,
8267
- toolId: tool.toolId,
8268
- versionId: tool.versionId,
8269
- version: tool.version
8270
- };
8908
+ const scopes = field(m, "scopes_supported", "scopesSupported");
8909
+ results.push({
8910
+ id: "scopes_supported",
8911
+ label: "scopes_supported",
8912
+ // 推奨項目。欠落は致命ではないため pending 扱いで明示する。
8913
+ status: Array.isArray(scopes) && scopes.length > 0 ? "pass" : "pending",
8914
+ detail: Array.isArray(scopes) ? messages.present : messages.scopesMissing
8271
8915
  });
8272
- if (!isStrictlySorted(tools.map((tool) => tool.toolName))) {
8273
- throw responseInvalid("publication_result_tools_order_invalid", messages);
8274
- }
8275
- return tools;
8916
+ return { ok: results.every((r) => r.status !== "fail"), results };
8917
+ }
8918
+ function buildInitTemplate(provider) {
8919
+ return {
8920
+ provider,
8921
+ issuer: "https://auth.example.com",
8922
+ authorizationEndpoint: "https://auth.example.com/oauth/authorize",
8923
+ tokenEndpoint: "https://auth.example.com/oauth/token",
8924
+ jwksUri: "https://auth.example.com/.well-known/jwks.json",
8925
+ clientId: "<client id>",
8926
+ // secret は config に直書きせず env 参照にする (No secret in repo / stdout)。
8927
+ clientSecretEnv: "ANDPIPE_OAUTH_CLIENT_SECRET",
8928
+ redirectUri: "https://<your-andpipe-gateway>/oauth/callback",
8929
+ scopes: ["openid", "profile"]
8930
+ };
8276
8931
  }
8277
- function parsePublicationResult(value, plan, messages, expectedPublicationId) {
8278
- assertCanonicalResponseSize(value, "publication_apply_result_too_large", messages);
8279
- const result = asRecord4(value);
8280
- if (!result || !hasExactKeys3(result, APPLY_RESULT_KEYS) || !isCanonicalUuid(result.requestId) || result.state !== "noop" && result.state !== "consumed") {
8281
- throw responseInvalid("publication_apply_result_invalid", messages);
8932
+ var SCOPE_REGISTER_OPERATION = "andpipe oauth scopes register";
8933
+ 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;
8934
+ var RESOURCE_NOT_FOUND_CODES = /* @__PURE__ */ new Set([
8935
+ "AP_NOT_FOUND",
8936
+ "AP_TOOL_NOT_FOUND",
8937
+ "AP_TOOL_VERSION_NOT_FOUND"
8938
+ ]);
8939
+ function createOAuthScopeRegisterRuntime(createClient = (profile) => createAdminApiClient({ profile })) {
8940
+ return { createClient, loadProject: loadDevProject, randomUuid: () => randomUUID7() };
8941
+ }
8942
+ var OAuthScopeRegistrationCommandError = class extends Error {
8943
+ constructor(code, reason, message, status) {
8944
+ super(message);
8945
+ this.code = code;
8946
+ this.reason = reason;
8947
+ this.status = status;
8948
+ this.name = "OAuthScopeRegistrationCommandError";
8282
8949
  }
8283
- const warnings = parseWarnings(result.warnings, messages);
8284
- if (!sameWarnings(warnings, plan.warnings)) {
8285
- throw responseInvalid("publication_apply_warning_mismatch", messages);
8950
+ code;
8951
+ reason;
8952
+ status;
8953
+ };
8954
+ function parseDraftOption(value, messages) {
8955
+ const parts = value.split(":");
8956
+ const toolId = parts[0]?.toLowerCase() ?? "";
8957
+ const versionId = parts[1]?.toLowerCase() ?? "";
8958
+ if (parts.length !== 2 || !RFC_UUID_RE.test(toolId) || !RFC_UUID_RE.test(versionId)) {
8959
+ throw new UsageError(messages.draftFormat);
8960
+ }
8961
+ return { toolId, versionId };
8962
+ }
8963
+ function normalizeOAuthScopeRegisterOptions(options, locale = DEFAULT_LOCALE7) {
8964
+ const messages = OAUTH_SCOPE_REGISTRATION_MESSAGES3[locale].cli;
8965
+ const cliMessages = CLI_MESSAGES9[locale];
8966
+ const apply = options.apply === true;
8967
+ if (options.yes === true && !apply) throw new UsageError(messages.yesRequiresApply);
8968
+ if (apply && options.yes !== true) {
8969
+ throw new ConfirmationRequiredError(
8970
+ SCOPE_REGISTER_OPERATION,
8971
+ cliMessages.common.confirmationRequiredMessage(SCOPE_REGISTER_OPERATION)
8972
+ );
8286
8973
  }
8287
- const tools = parseToolResults(result.tools, messages);
8288
- const changedToolNames = plan.tools.filter((tool) => tool.changed).map((tool) => tool.toolName);
8289
- if (result.state === "noop") {
8290
- if (result.publicationId !== null || tools.length !== 0 || changedToolNames.length !== 0) {
8291
- throw responseInvalid("publication_noop_invalid", messages);
8292
- }
8974
+ const profile = options.profile ?? DEFAULT_PROFILE_NAME;
8975
+ const rawDrafts = options.draft ?? [];
8976
+ if (rawDrafts.length === 0) {
8293
8977
  return {
8294
- requestId: result.requestId,
8295
- publicationId: null,
8296
- state: "noop",
8297
- tools,
8298
- warnings
8978
+ kind: "publication_candidate",
8979
+ ...options.project === void 0 ? {} : {
8980
+ projectId: canonicalUuidOption(options.project, "--project", cliMessages.publish)
8981
+ },
8982
+ ...options.connector === void 0 ? {} : {
8983
+ connectorId: canonicalUuidOption(options.connector, "--connector", cliMessages.publish)
8984
+ },
8985
+ apply,
8986
+ profile
8299
8987
  };
8300
8988
  }
8301
- 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(
8302
- (tool) => plan.tools.find((planned) => planned.toolName === tool.toolName)?.operation !== tool.operation
8303
- )) {
8304
- throw responseInvalid("publication_consumed_result_invalid", messages);
8989
+ if (options.connector !== void 0) throw new UsageError(messages.draftConnectorConflict);
8990
+ if (options.project === void 0) throw new UsageError(messages.draftRequiresProject);
8991
+ const projectId = canonicalUuidOption(options.project, "--project", cliMessages.publish);
8992
+ const drafts = rawDrafts.map((value) => parseDraftOption(value, messages)).sort((left, right) => comparePublicationUnicodeCodePoints3(left.toolId, right.toolId));
8993
+ if (drafts.length > OAUTH_SCOPE_REGISTRATION_MAX_DRAFTS2 || drafts.some((draft, index) => index > 0 && drafts[index - 1]?.toolId === draft.toolId)) {
8994
+ throw new UsageError(messages.draftInvalid);
8305
8995
  }
8306
- return {
8307
- requestId: result.requestId,
8308
- publicationId: result.publicationId,
8309
- state: "consumed",
8310
- tools,
8311
- warnings
8312
- };
8996
+ return { kind: "saved_drafts", projectId, drafts, apply, profile };
8313
8997
  }
8314
- function parseConfirmation(value, messages) {
8315
- if (value === null) return null;
8316
- const confirmation = asRecord4(value);
8317
- if (!confirmation || !hasExactKeys3(confirmation, ["confirmationId", "signature", "confirmed"]) || !isCanonicalUuid(confirmation.confirmationId) || typeof confirmation.signature !== "string" || !PUBLICATION_CONFIRMATION_SIGNATURE_RE2.test(confirmation.signature) || confirmation.confirmed !== true) {
8318
- throw responseInvalid("publication_confirmation_invalid", messages);
8998
+ function riskLabel(messages, level) {
8999
+ return messages.riskLabels[level];
9000
+ }
9001
+ function blockedGuidance(cli, reason) {
9002
+ switch (reason) {
9003
+ case "scope_in_use_risk_upgrade_forbidden":
9004
+ return cli.blocked.scopeInUse;
9005
+ case "template_scope_requires_sync":
9006
+ return cli.blocked.templateScope;
9007
+ case "reserved_scope_name":
9008
+ return cli.blocked.reservedName;
8319
9009
  }
8320
- return {
8321
- confirmationId: confirmation.confirmationId,
8322
- signature: confirmation.signature,
8323
- confirmed: true
8324
- };
8325
9010
  }
8326
- function parseStatus(value, publicationId, plan, messages) {
8327
- assertCanonicalResponseSize(value, "publication_status_too_large", messages);
8328
- const status = asRecord4(value);
8329
- 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)) {
8330
- throw responseInvalid("publication_status_invalid", messages);
9011
+ function writeRegistrationSummary(writer, response, applyRequested, messages) {
9012
+ const cli = messages.cli;
9013
+ const name = (value) => terminalSafeText(value);
9014
+ const lines = [response.mode === "preview" ? cli.previewHeading : cli.appliedHeading];
9015
+ for (const row of response.added) {
9016
+ lines.push(` ${cli.addedLabel} ${name(row.name)} ${riskLabel(messages, row.riskLevel)}`);
8331
9017
  }
8332
- const confirmation = parseConfirmation(status.confirmation, messages);
8333
- const result = status.result === null ? null : parsePublicationResult(status.result, plan, messages, publicationId);
8334
- const durableState = status.durableState;
8335
- const effectiveState = status.effectiveState;
8336
- const isPending = durableState === "pending";
8337
- const isApproved = durableState === "approved";
8338
- const isTerminal = durableState === "rejected" || durableState === "expired" || durableState === "consumed";
8339
- 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)) {
8340
- throw responseInvalid("publication_status_inconsistent", messages);
9018
+ for (const row of response.updated) {
9019
+ lines.push(
9020
+ ` ${cli.updatedLabel} ${name(row.name)} ${riskLabel(messages, row.fromRisk)} \u2192 ${riskLabel(messages, row.toRisk)}`
9021
+ );
8341
9022
  }
8342
- return {
8343
- requestId: status.requestId,
8344
- publicationId,
8345
- durableState,
8346
- effectiveState,
8347
- expiresAt: status.expiresAt,
8348
- confirmation,
8349
- result
8350
- };
8351
- }
8352
- function typedCode2(error) {
8353
- if (error === null || typeof error !== "object") return void 0;
8354
- const code = error.code;
8355
- return typeof code === "string" && SAFE_AP_CODE_RE2.test(code) ? code : void 0;
8356
- }
8357
- function typedStatus2(error) {
8358
- if (error === null || typeof error !== "object") return void 0;
8359
- const status = error.status;
8360
- return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599 ? status : void 0;
8361
- }
8362
- function remoteError(error, phase, messages) {
8363
- const code = typedCode2(error) ?? "AP_NETWORK_ERROR";
8364
- return new PublishCommandError(
8365
- code,
8366
- `${phase}_failed`,
8367
- messages.remoteFailure(phase, code),
8368
- typedStatus2(error)
8369
- );
8370
- }
8371
- function parseConfirmationRequired(error, projectId, messages) {
8372
- if (typedCode2(error) !== "AP_CONFIRMATION_REQUIRED") return null;
8373
- if (typedStatus2(error) !== 409 || error === null || typeof error !== "object") {
8374
- throw responseInvalid("publication_confirmation_required_error_invalid", messages);
9023
+ for (const existing of response.existing) {
9024
+ lines.push(` ${cli.existingLabel} ${name(existing)}`);
8375
9025
  }
8376
- const details = asRecord4(error.confirmationRequired);
8377
- if (!details || !hasExactKeys3(details, [
8378
- "requestId",
8379
- "publicationId",
8380
- "verificationUri",
8381
- "expiresIn",
8382
- "pollInterval"
8383
- ]) || !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) {
8384
- throw responseInvalid("publication_confirmation_required_details_invalid", messages);
9026
+ for (const row of response.blocked) {
9027
+ const from = row.fromRisk === null ? "" : `${riskLabel(messages, row.fromRisk)} \u2192 `;
9028
+ lines.push(
9029
+ ` ${cli.blockedLabel} ${name(row.name)} ${from}${riskLabel(messages, row.toRisk)}`
9030
+ );
9031
+ lines.push(` ${blockedGuidance(cli, row.reason)}`);
9032
+ }
9033
+ if (response.unchanged && response.blocked.length === 0) lines.push(cli.nothingToRegister);
9034
+ lines.push(cli.separationNotice);
9035
+ if (response.mode === "preview" && !applyRequested && response.applyAllowed && !response.unchanged) {
9036
+ lines.push(cli.applyHint);
9037
+ }
9038
+ if (response.mode === "applied") lines.push(cli.nextPublish);
9039
+ for (const line of lines) interactive(writer, line);
9040
+ }
9041
+ function writeRegistrationJson(writer, response) {
9042
+ json(writer, terminalSafeValue(response));
9043
+ }
9044
+ function isDetailsAbsentPolicyDenial(error) {
9045
+ return error.status === 403 && error.code === "AP_POLICY_DENIED" && error.detailsAbsent;
9046
+ }
9047
+ function isUnsupportedAdminApi(error, projectAccessible) {
9048
+ if (error.status === 404) return !RESOURCE_NOT_FOUND_CODES.has(error.code);
9049
+ return isDetailsAbsentPolicyDenial(error) && projectAccessible === true;
9050
+ }
9051
+ function registrationFailure(error, phase, messages, projectAccessible) {
9052
+ if (!(error instanceof AdminApiClientError)) return error;
9053
+ const stop = (reason2, message) => new OAuthScopeRegistrationCommandError(error.code, reason2, message, error.status);
9054
+ if (phase === "preview" && isUnsupportedAdminApi(error, projectAccessible)) {
9055
+ return stop("oauth_scope_registration_unsupported", messages.unsupportedAdminApi);
9056
+ }
9057
+ if (phase === "preview" && (isDetailsAbsentPolicyDenial(error) && projectAccessible === false || error.code === "AP_INVALID_SCOPE")) {
9058
+ return stop("oauth_scope_registration_project_access_denied", messages.projectAccessDenied);
9059
+ }
9060
+ const reason = error.scopeRegistrationReason;
9061
+ switch (reason) {
9062
+ case "oauth_scope_registration_source_stale":
9063
+ case "oauth_scope_registration_registry_changed":
9064
+ case "oauth_scope_registration_plan_stale":
9065
+ return stop(reason, messages.stale);
9066
+ case "scope_registration_publish_gate_failed":
9067
+ return error.publishGateToolNames === void 0 ? error : stop(
9068
+ reason,
9069
+ messages.publishGateFailed(
9070
+ error.publishGateToolNames.map((name) => terminalSafeText(name))
9071
+ )
9072
+ );
9073
+ case "saved_draft_not_latest":
9074
+ return stop(reason, messages.draftNotLatest);
9075
+ case "saved_drafts_mixed_connectors":
9076
+ return stop(reason, messages.draftsMixedConnectors);
9077
+ case "saved_draft_fields_inconsistent":
9078
+ return stop(reason, messages.draftFieldsInconsistent);
9079
+ case "marketplace_managed_tool":
9080
+ return stop(reason, messages.marketplaceManaged);
9081
+ case "publication_candidate_commitment_mismatch":
9082
+ return stop(reason, messages.candidateMismatch);
9083
+ case "publication_candidate_too_large":
9084
+ return stop(reason, messages.candidateTooLarge);
9085
+ case "oauth_scope_registration_blocked":
9086
+ return stop(reason, messages.blockedNotApplied);
9087
+ default:
9088
+ break;
9089
+ }
9090
+ if (phase === "apply" && error.code === "AP_RESULT_UNKNOWN") {
9091
+ return stop("oauth_scope_registration_result_unknown", messages.resultUnknown);
9092
+ }
9093
+ if (phase === "apply" && reason === void 0 && (error.code === "AP_POLICY_DENIED" || error.code === "AP_INVALID_SCOPE")) {
9094
+ return stop("oauth_scope_registration_write_role_required", messages.writeRoleRequired);
9095
+ }
9096
+ return error;
9097
+ }
9098
+ async function projectAccessibility(client, projectId, error) {
9099
+ if (!(error instanceof AdminApiClientError) || !isDetailsAbsentPolicyDenial(error)) {
9100
+ return void 0;
8385
9101
  }
8386
- let uri;
8387
9102
  try {
8388
- uri = new URL(details.verificationUri);
9103
+ await client.getOAuthSetup(projectId);
9104
+ return true;
8389
9105
  } catch {
8390
- throw responseInvalid("publication_verification_uri_invalid", messages);
9106
+ return false;
8391
9107
  }
8392
- const expectedPath = `/projects/${projectId}/tools/publications/${details.publicationId}`;
8393
- if (uri.origin !== "https://admin.andpipe.com" || uri.pathname !== expectedPath || uri.username !== "" || uri.password !== "" || uri.search !== "" || uri.hash !== "" || uri.toString() !== details.verificationUri) {
8394
- throw responseInvalid("publication_verification_uri_invalid", messages);
9108
+ }
9109
+ function localCandidateSource(normalized, cwd, runtime, locale) {
9110
+ const messages = OAUTH_SCOPE_REGISTRATION_MESSAGES3[locale].cli;
9111
+ const publishMessages = CLI_MESSAGES9[locale].publish;
9112
+ const project = loadPublicationProject(runtime.loadProject, cwd, publishMessages);
9113
+ const projectId = assertManifestProject(project, normalized.projectId, publishMessages);
9114
+ const connectorId = normalized.connectorId ?? project.manifest.connector_id;
9115
+ if (connectorId === void 0) throw new UsageError(messages.connectorRequired);
9116
+ let candidate;
9117
+ try {
9118
+ candidate = buildLocalPublicationCandidate(project, connectorId, publishMessages);
9119
+ } catch (error) {
9120
+ if (error instanceof PublicationCanonicalizationError && error.reason === "publication_value_too_large") {
9121
+ throw new OAuthScopeRegistrationCommandError(
9122
+ "AP_INPUT_INVALID",
9123
+ "publication_candidate_too_large",
9124
+ messages.candidateTooLarge
9125
+ );
9126
+ }
9127
+ throw error;
8395
9128
  }
8396
9129
  return {
8397
- requestId: details.requestId,
8398
- publicationId: details.publicationId,
8399
- verificationUri: details.verificationUri,
8400
- expiresIn: 600,
8401
- pollInterval: details.pollInterval
9130
+ projectId,
9131
+ source: {
9132
+ kind: "publication_candidate",
9133
+ connectorId,
9134
+ candidateContract: candidate.planRequest.candidateContract,
9135
+ candidateCommitment: candidate.planRequest.candidateCommitment
9136
+ },
9137
+ expectedToolNames: candidate.expectedToolNames
8402
9138
  };
8403
9139
  }
8404
- function approvedApplyResultMayBeUnknown(error) {
8405
- const status = typedStatus2(error);
8406
- if (status !== void 0 && status >= 400 && status < 500) return false;
8407
- const code = typedCode2(error);
8408
- return code === void 0 || !DEFINITIVE_APPLY_ERROR_CODES.has(code);
8409
- }
8410
- function initialApplyResultMayBeUnknown(error) {
8411
- const status = typedStatus2(error);
8412
- if (status !== void 0 && status >= 400 && status < 500) return false;
8413
- const code = typedCode2(error);
8414
- if (status === void 0 && code !== void 0 && DEFINITIVE_APPLY_ERROR_CODES.has(code)) {
8415
- return false;
9140
+ async function runOAuthScopeRegisterCommand(options, writer, cwd, runtime, locale = DEFAULT_LOCALE7) {
9141
+ const messages = OAUTH_SCOPE_REGISTRATION_MESSAGES3[locale];
9142
+ const normalized = normalizeOAuthScopeRegisterOptions(options, locale);
9143
+ const target = normalized.kind === "saved_drafts" ? {
9144
+ projectId: normalized.projectId,
9145
+ source: { kind: "saved_drafts", drafts: normalized.drafts },
9146
+ expectedToolNames: void 0
9147
+ } : localCandidateSource(normalized, cwd, runtime, locale);
9148
+ const client = runtime.createClient(normalized.profile);
9149
+ let preview;
9150
+ try {
9151
+ preview = await client.registerOAuthScopes({
9152
+ projectId: target.projectId,
9153
+ source: target.source,
9154
+ apply: false
9155
+ });
9156
+ } catch (error) {
9157
+ throw registrationFailure(
9158
+ error,
9159
+ "preview",
9160
+ messages.cli,
9161
+ await projectAccessibility(client, target.projectId, error)
9162
+ );
8416
9163
  }
8417
- return true;
8418
- }
8419
- function writeSafeJson(writer, value) {
8420
- json(writer, terminalSafeValue(value));
8421
- }
8422
- function writePlan(writer, plan) {
8423
- writeSafeJson(writer, { phase: "plan", ...plan });
8424
- }
8425
- function writeResult(writer, result) {
8426
- writeSafeJson(writer, { phase: "result", ...result });
8427
- }
8428
- function freezeJson(value) {
8429
- if (Array.isArray(value)) {
8430
- for (const item of value) freezeJson(item);
8431
- return Object.freeze(value);
9164
+ if (target.expectedToolNames !== void 0 && JSON.stringify(preview.source.tools.map((tool) => tool.toolName)) !== JSON.stringify(target.expectedToolNames)) {
9165
+ throw new OAuthScopeRegistrationCommandError(
9166
+ "AP_RESPONSE_INVALID",
9167
+ "oauth_scope_registration_tools_mismatch",
9168
+ messages.cli.responseMismatch
9169
+ );
8432
9170
  }
8433
- if (value !== null && typeof value === "object") {
8434
- for (const item of Object.values(value)) freezeJson(item);
8435
- return Object.freeze(value);
9171
+ writeRegistrationJson(writer, preview);
9172
+ writeRegistrationSummary(writer, preview, normalized.apply, messages);
9173
+ if (!preview.applyAllowed) {
9174
+ if (normalized.apply) {
9175
+ throw new OAuthScopeRegistrationCommandError(
9176
+ "AP_POLICY_DENIED",
9177
+ "oauth_scope_registration_blocked",
9178
+ messages.cli.blockedNotApplied
9179
+ );
9180
+ }
9181
+ return { ok: false };
8436
9182
  }
8437
- return value;
8438
- }
8439
- function prepareCandidate(project) {
8440
- const canonical = assertCanonicalPublicationSize2(project.contract.root);
8441
- const candidateContract = freezeJson(JSON.parse(canonical));
8442
- return {
8443
- candidateContract,
8444
- candidateCommitment: publicationCommitment2("candidate", candidateContract)
8445
- };
8446
- }
8447
- function assertIdempotencyKey2(value, messages) {
8448
- if (!UUID_RE6.test(value)) {
8449
- throw new PublishCommandError(
9183
+ if (!normalized.apply) return { ok: true };
9184
+ const idempotencyKey = runtime.randomUuid().toLowerCase();
9185
+ if (!RFC_UUID_RE.test(idempotencyKey)) {
9186
+ throw new OAuthScopeRegistrationCommandError(
8450
9187
  "AP_NETWORK_ERROR",
8451
9188
  "secure_random_invalid",
8452
- messages.failure("secure_random_invalid")
9189
+ CLI_MESSAGES9[locale].publish.failure("secure_random_invalid")
8453
9190
  );
8454
9191
  }
8455
- return value;
8456
- }
8457
- async function sendInitialApplyWithSameAnchorRetry(input) {
8458
- for (let attempt = 0; attempt < INITIAL_APPLY_MAX_ATTEMPTS; attempt += 1) {
8459
- try {
8460
- const result = parsePublicationResult(
8461
- await input.client.applyPublication(input.projectId, input.idempotencyKey, input.body),
8462
- input.plan,
8463
- input.messages
8464
- );
8465
- if (result.state !== "noop") {
8466
- throw responseInvalid("publication_initial_apply_state_invalid", input.messages);
8467
- }
8468
- return {
8469
- kind: "response",
8470
- result
8471
- };
8472
- } catch (error) {
8473
- let malformedConfirmationAnchor = false;
8474
- let confirmationRequired = null;
8475
- try {
8476
- confirmationRequired = parseConfirmationRequired(error, input.projectId, input.messages);
8477
- } catch (parseError) {
8478
- if (typedCode2(error) !== "AP_CONFIRMATION_REQUIRED" || !(parseError instanceof PublishCommandError) || parseError.code !== "AP_RESPONSE_INVALID") {
8479
- throw parseError;
8480
- }
8481
- malformedConfirmationAnchor = true;
8482
- }
8483
- if (confirmationRequired) {
8484
- return { kind: "confirmation_required", details: confirmationRequired };
8485
- }
8486
- if (!malformedConfirmationAnchor && !initialApplyResultMayBeUnknown(error)) {
8487
- throw remoteError(error, "initial_apply", input.messages);
8488
- }
8489
- if (attempt === INITIAL_APPLY_MAX_ATTEMPTS - 1) {
8490
- throw new PublishCommandError(
8491
- "AP_RESULT_UNKNOWN",
8492
- "publication_anchor_result_unknown",
8493
- input.messages.proposalResultUnknown
8494
- );
8495
- }
8496
- }
9192
+ let applied;
9193
+ try {
9194
+ applied = await client.registerOAuthScopes({
9195
+ projectId: target.projectId,
9196
+ source: target.source,
9197
+ apply: true,
9198
+ sourceCommitment: preview.sourceCommitment,
9199
+ baseRegistryCommitment: preview.baseRegistryCommitment,
9200
+ planCommitment: preview.planCommitment,
9201
+ idempotencyKey
9202
+ });
9203
+ } catch (error) {
9204
+ throw registrationFailure(error, "apply", messages.cli);
8497
9205
  }
8498
- throw new PublishCommandError(
8499
- "AP_RESULT_UNKNOWN",
8500
- "publication_anchor_result_unknown",
8501
- input.messages.proposalResultUnknown
8502
- );
9206
+ writeRegistrationJson(writer, applied);
9207
+ writeRegistrationSummary(writer, applied, true, messages);
9208
+ return { ok: true };
8503
9209
  }
8504
- function confirmationStopped(code, reason, messages) {
8505
- return new PublishCommandError(code, reason, messages.confirmationStopped(reason));
8506
- }
8507
- function pollFailureIsDefinitive(error) {
8508
- const status = typedStatus2(error);
8509
- if (status !== void 0 && status >= 400 && status < 500) return true;
8510
- const code = typedCode2(error);
8511
- return code === "AP_RESPONSE_INVALID" || code === "AP_OUTPUT_INVALID" || code !== void 0 && DEFINITIVE_APPLY_ERROR_CODES.has(code);
9210
+ function upstreamOAuthWizardUrl(profile, projectId, connectorId) {
9211
+ const record = getProfile(profile);
9212
+ if (!record)
9213
+ throw new UsageError(`\u8A8D\u8A3Cprofile ${profile} \u304C\u3042\u308A\u307E\u305B\u3093\u3002andpipe login\u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044`);
9214
+ const url = new URL(`/projects/${projectId}/oauth`, new URL(record.verificationUriBase).origin);
9215
+ url.searchParams.set("connector", connectorId);
9216
+ return url.toString();
8512
9217
  }
8513
- async function sleepForPoll(runtime, milliseconds, mode, messages) {
9218
+ async function loadOAuthMetadata(opts, locale) {
9219
+ const messages = CLI_MESSAGES9[locale];
9220
+ if (opts.file && opts.issuer) {
9221
+ throw new UsageError("--file \u3068 --issuer \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");
9222
+ }
9223
+ if (opts.issuer) {
9224
+ return fetchOAuthMetadata(opts.issuer);
9225
+ }
9226
+ if (!opts.file) {
9227
+ throw new UsageError(messages.oauth.fileRequired);
9228
+ }
8514
9229
  try {
8515
- await runtime.sleep(milliseconds);
8516
- } catch {
8517
- throw new PublishCommandError(
8518
- mode === "recover-result" ? "AP_RESULT_UNKNOWN" : "AP_NETWORK_ERROR",
8519
- "publication_poll_sleep_failed",
8520
- messages.pollingUnavailable
8521
- );
9230
+ return JSON.parse(readFileSync2(opts.file, "utf8"));
9231
+ } catch (error) {
9232
+ throw new UsageError(messages.oauth.metadataReadFailed(error.message));
8522
9233
  }
8523
9234
  }
8524
- async function pollPublication(client, projectId, details, plan, writer, runtime, mode, messages, knownExpiresAt) {
8525
- const startedAt = runtime.monotonicNow();
8526
- let deadline = startedAt + details.expiresIn * 1e3;
8527
- let expiresAt = knownExpiresAt;
8528
- if (knownExpiresAt !== void 0) {
8529
- deadline = Math.min(
8530
- deadline,
8531
- startedAt + Math.max(0, Date.parse(knownExpiresAt) - runtime.wallNow())
8532
- );
9235
+ async function runOAuthMetadataValidate(opts, writer, locale) {
9236
+ const messages = CLI_MESSAGES9[locale];
9237
+ const parsed = await loadOAuthMetadata(opts, locale);
9238
+ const report = validateOAuthMetadata(parsed, locale);
9239
+ json(writer, report.results);
9240
+ if (!report.ok) {
9241
+ process.exitCode = 1;
9242
+ info(writer, messages.oauth.metadataFailed);
9243
+ } else {
9244
+ info(writer, messages.oauth.metadataOk);
8533
9245
  }
8534
- const maxAttempts = Math.ceil(details.expiresIn / details.pollInterval) + 2;
8535
- for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
8536
- let rawStatus;
8537
- try {
8538
- rawStatus = await client.getPublication(projectId, details.publicationId);
8539
- } catch (error) {
8540
- if (pollFailureIsDefinitive(error)) {
8541
- throw remoteError(error, mode === "recover-result" ? "result_recovery" : "poll", messages);
8542
- }
8543
- const remainingMilliseconds2 = Math.max(0, deadline - runtime.monotonicNow());
8544
- if (remainingMilliseconds2 <= 0 || attempt === maxAttempts - 1) {
8545
- throw new PublishCommandError(
8546
- mode === "recover-result" ? "AP_RESULT_UNKNOWN" : "AP_NETWORK_ERROR",
8547
- "publication_poll_unavailable",
8548
- messages.pollingUnavailable
8549
- );
9246
+ }
9247
+ function registerOauth(program, writer, locale = DEFAULT_LOCALE7, dependencies = {}) {
9248
+ const messages = CLI_MESSAGES9[locale];
9249
+ const oauth = program.command("oauth").description(messages.oauth.commandDescription);
9250
+ oauth.command("init").description(messages.oauth.initDescription).requiredOption("--provider <name>", messages.oauth.providerOption).action((opts) => {
9251
+ info(writer, messages.oauth.templateHeading(opts.provider));
9252
+ json(writer, buildInitTemplate(opts.provider));
9253
+ info(writer, messages.oauth.clientSecretEnvNotice);
9254
+ });
9255
+ 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) => {
9256
+ if (opts.project) {
9257
+ if (opts.file || opts.issuer) {
9258
+ throw new UsageError("--project \u306F --file / --issuer \u3068\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");
8550
9259
  }
8551
- await sleepForPoll(
8552
- runtime,
8553
- Math.min(details.pollInterval * 1e3, remainingMilliseconds2),
8554
- mode,
8555
- messages
9260
+ const projectId = assertProjectId(opts.project);
9261
+ const result = await createAdminApiClient({ profile: opts.profile }).getOAuthSetup(
9262
+ projectId
8556
9263
  );
8557
- continue;
8558
- }
8559
- const status = parseStatus(rawStatus, details.publicationId, plan, messages);
8560
- if (expiresAt !== void 0 && status.expiresAt !== expiresAt) {
8561
- throw responseInvalid("publication_expiry_changed", messages);
8562
- }
8563
- expiresAt = status.expiresAt;
8564
- const now = runtime.monotonicNow();
8565
- const wallRemaining = Math.max(0, Date.parse(status.expiresAt) - runtime.wallNow());
8566
- deadline = Math.min(deadline, now + wallRemaining);
8567
- const remainingMilliseconds = Math.max(0, deadline - now);
8568
- writeSafeJson(writer, {
8569
- phase: mode === "recover-result" ? "result_recovery" : "confirmation",
8570
- requestId: status.requestId,
8571
- publicationId: status.publicationId,
8572
- durableState: status.durableState,
8573
- effectiveState: status.effectiveState,
8574
- expiresAt: status.expiresAt,
8575
- remainingSeconds: Math.ceil(remainingMilliseconds / 1e3)
8576
- });
8577
- if (status.durableState === "consumed") {
8578
- return { kind: "consumed", result: status.result };
8579
- }
8580
- if (status.durableState === "rejected") {
8581
- throw confirmationStopped("AP_POLICY_DENIED", "publication_rejected", messages);
9264
+ json(writer, result);
9265
+ if (result.metadata.status !== "valid" || result.alignment.issues.length > 0) {
9266
+ process.exitCode = 1;
9267
+ }
9268
+ return;
8582
9269
  }
8583
- if (status.durableState === "expired") {
8584
- throw confirmationStopped(
8585
- "AP_CONFIRMATION_EXPIRED",
8586
- "publication_confirmation_expired",
8587
- messages
9270
+ await runOAuthMetadataValidate(opts, writer, locale);
9271
+ });
9272
+ const scopes = oauth.command("scopes").description(messages.oauth.scopesDescription);
9273
+ 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) => {
9274
+ const operation = "andpipe oauth scopes sync";
9275
+ if (opts.apply && !opts.yes) {
9276
+ throw new ConfirmationRequiredError(
9277
+ operation,
9278
+ messages.common.confirmationRequiredMessage(operation)
8588
9279
  );
8589
9280
  }
8590
- if (status.effectiveState === "stale") {
8591
- throw confirmationStopped("AP_CONFLICT", "publication_confirmation_stale", messages);
8592
- }
8593
- if (mode === "await-approval" && status.durableState === "approved" && status.confirmation !== null) {
8594
- return {
8595
- kind: "approved",
8596
- confirmation: status.confirmation,
8597
- expiresAt: status.expiresAt
8598
- };
9281
+ if (!opts.apply && opts.yes) {
9282
+ throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8599
9283
  }
8600
- if (remainingMilliseconds <= 0) {
8601
- throw confirmationStopped(
8602
- "AP_CONFIRMATION_EXPIRED",
8603
- "publication_confirmation_timeout",
8604
- messages
8605
- );
9284
+ const projectId = assertProjectId(opts.project);
9285
+ const result = await createAdminApiClient({ profile: opts.profile }).syncOAuthScopes({
9286
+ projectId,
9287
+ apply: opts.apply
9288
+ });
9289
+ json(writer, result);
9290
+ });
9291
+ const registration = OAUTH_SCOPE_REGISTRATION_MESSAGES3[locale].cli;
9292
+ const scopeRegisterRuntime = dependencies.scopeRegisterRuntime ?? createOAuthScopeRegisterRuntime();
9293
+ const cwd = dependencies.cwd ?? (() => process.cwd());
9294
+ scopes.command("register").description(registration.commandDescription).option("--project <project-uuid>", registration.projectOption).option("--connector <connector-uuid>", registration.connectorOption).option(
9295
+ "--draft <toolId:versionId>",
9296
+ registration.draftOption,
9297
+ (value, previous) => [...previous, value],
9298
+ []
9299
+ ).option("--apply", registration.applyOption, false).option("--yes", registration.yesOption, false).option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).action(async (opts) => {
9300
+ const result = await runOAuthScopeRegisterCommand(
9301
+ opts,
9302
+ writer,
9303
+ cwd(),
9304
+ scopeRegisterRuntime,
9305
+ locale
9306
+ );
9307
+ if (!result.ok) process.exitCode = 1;
9308
+ });
9309
+ const clients = oauth.command("clients").description("OAuth client\u306Escope\u5272\u5F53\u3092\u7BA1\u7406\u3059\u308B");
9310
+ 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(
9311
+ async (opts) => {
9312
+ const operation = "andpipe oauth clients map-scopes";
9313
+ if (opts.apply && !opts.yes) {
9314
+ throw new ConfirmationRequiredError(
9315
+ operation,
9316
+ messages.common.confirmationRequiredMessage(operation)
9317
+ );
9318
+ }
9319
+ if (!opts.apply && opts.yes) {
9320
+ throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9321
+ }
9322
+ const client = createAdminApiClient({ profile: opts.profile });
9323
+ const preview = await client.mapOAuthClientScopes({
9324
+ projectId: assertProjectId(opts.project),
9325
+ clientRegistryId: opts.client,
9326
+ apply: false
9327
+ });
9328
+ json(writer, preview);
9329
+ if (!opts.apply) return;
9330
+ const applied = await client.mapOAuthClientScopes({
9331
+ projectId: assertProjectId(opts.project),
9332
+ clientRegistryId: opts.client,
9333
+ apply: true,
9334
+ requiredScopesCommitment: preview.requiredScopesCommitment,
9335
+ baseClientGrantCommitment: preview.baseClientGrantCommitment,
9336
+ candidateClientGrantCommitment: preview.candidateClientGrantCommitment,
9337
+ planCommitment: preview.planCommitment
9338
+ });
9339
+ json(writer, applied);
8606
9340
  }
8607
- const sleepMilliseconds = Math.min(details.pollInterval * 1e3, remainingMilliseconds);
8608
- await sleepForPoll(runtime, sleepMilliseconds, mode, messages);
8609
- }
8610
- throw confirmationStopped("AP_CONFIRMATION_EXPIRED", "publication_poll_attempt_limit", messages);
8611
- }
8612
- async function runPublishCommand(options, writer, cwd, runtime, messages = DEFAULT_PUBLISH_MESSAGES) {
8613
- const normalized = normalizePublishOptions(options, messages);
8614
- let project;
8615
- try {
8616
- project = runtime.loadProject(cwd);
8617
- } catch (error) {
8618
- if (error instanceof LocalFilePolicyError) {
8619
- throw new PublishCommandError(
8620
- "AP_POLICY_DENIED",
8621
- error.reason,
8622
- messages.failure(error.reason)
9341
+ );
9342
+ const metadata = oauth.command("metadata").description(messages.oauth.metadataDescription);
9343
+ metadata.command("validate").description(messages.oauth.validateDescription).option("--file <path>", messages.common.metadataFileOption).option("--issuer <url>", messages.common.issuerOption).action(async (opts) => {
9344
+ await runOAuthMetadataValidate(opts, writer, locale);
9345
+ });
9346
+ const connect = oauth.command("connect").description(
9347
+ 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"
9348
+ );
9349
+ connect.command("status").description(
9350
+ locale === "ja" ? "\u63A5\u7D9A\u72B6\u614B\u3068\u6B21\u306E\u64CD\u4F5C\u3092\u8868\u793A" : "Show connection state and next action"
9351
+ ).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) => {
9352
+ const state = await createAdminApiClient({
9353
+ profile: opts.profile
9354
+ }).getUpstreamOAuthConnectionState(assertProjectId(opts.project), opts.connector);
9355
+ json(writer, state);
9356
+ if (!state.allGreen) process.exitCode = 1;
9357
+ });
9358
+ connect.command("open").description(
9359
+ 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"
9360
+ ).requiredOption("--project <project>", messages.common.projectOption).requiredOption("--connector <connector>", "\u63A5\u7D9A\u5BFE\u8C61connector UUID").option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).option(
9361
+ "--no-browser",
9362
+ locale === "ja" ? "\u65E2\u5B9A\u30D6\u30E9\u30A6\u30B6\u3092\u958B\u304B\u305AURL\u3060\u3051\u8868\u793A" : "Print the URL without opening a browser"
9363
+ ).action(
9364
+ async (opts) => {
9365
+ const projectId = assertProjectId(opts.project);
9366
+ const state = await createAdminApiClient({
9367
+ profile: opts.profile
9368
+ }).getUpstreamOAuthConnectionState(projectId, opts.connector);
9369
+ json(writer, state);
9370
+ const url = upstreamOAuthWizardUrl(opts.profile, projectId, opts.connector);
9371
+ info(
9372
+ writer,
9373
+ locale === "ja" ? `Web Admin\u3067\u7D9A\u3051\u3066\u304F\u3060\u3055\u3044: ${url}` : `Continue in Web Admin: ${url}`
8623
9374
  );
9375
+ if (opts.browser) {
9376
+ try {
9377
+ (dependencies.openBrowser ?? openBrowser)(url);
9378
+ } catch {
9379
+ }
9380
+ }
8624
9381
  }
8625
- const reason = error instanceof DevProjectLoadError ? error.reason : "local_project_invalid";
8626
- if (error instanceof DevProjectLoadError || error instanceof UsageError) {
8627
- throw new PublishCommandError("AP_INPUT_INVALID", reason, messages.failure(reason));
8628
- }
8629
- throw error;
8630
- }
8631
- const projectId = project.manifest.project_id;
8632
- const connectorId = normalized.connectorId ?? project.manifest.connector_id;
8633
- if (connectorId === void 0) {
8634
- throw new PublishCommandError(
8635
- "AP_INPUT_INVALID",
8636
- "publication_connector_required",
8637
- messages.optionRequires("publish", "--connector UUID")
9382
+ );
9383
+ 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) => {
9384
+ const projectId = assertProjectId(opts.project);
9385
+ const result = await createAdminApiClient({ profile: opts.profile }).testOAuthLogin(
9386
+ projectId,
9387
+ opts.client
8638
9388
  );
9389
+ json(writer, result);
9390
+ if (result.status === "blocked") process.exitCode = 1;
9391
+ });
9392
+ }
9393
+
9394
+ // src/commands/openapi.ts
9395
+ import { randomUUID as randomUUID8 } from "crypto";
9396
+ import { resolve as resolve4 } from "path";
9397
+ import {
9398
+ importOpenApi as importOpenApi2,
9399
+ OPENAPI_IMPORT_MAX_SOURCE_BYTES as OPENAPI_IMPORT_MAX_SOURCE_BYTES2,
9400
+ OpenApiImportError as OpenApiImportError3
9401
+ } from "@andpipes/tool-contract";
9402
+ function createOpenApiImportRuntime(createClient = (profile) => createAdminApiClient({ profile })) {
9403
+ return { createClient, idempotencyKey: randomUUID8 };
9404
+ }
9405
+ function normalizedOptions(options) {
9406
+ if (!options.file || !options.project || !options.connector) {
9407
+ throw new UsageError("--file\u3001--project\u3001--connector \u306F\u5FC5\u9808\u3067\u3059");
8639
9408
  }
8640
- if (normalized.projectId !== void 0 && normalized.projectId !== projectId) {
8641
- throw new PublishCommandError(
8642
- "AP_CONFLICT",
8643
- "manifest_project_mismatch",
8644
- messages.failure("manifest_project_mismatch")
8645
- );
9409
+ if (options.format !== void 0 && options.format !== "json" && options.format !== "yaml") {
9410
+ throw new UsageError("--format \u306F json \u307E\u305F\u306F yaml \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8646
9411
  }
8647
- const candidate = prepareCandidate(project);
8648
- const localToolNames = project.contract.tools.map((tool) => toolName2(tool));
8649
- if (localToolNames.some((name) => !isSafeToolName2(name))) {
8650
- throw new PublishCommandError(
8651
- "AP_INPUT_INVALID",
8652
- "publication_candidate_tool_invalid",
8653
- messages.failure("publication_candidate_tool_invalid")
8654
- );
9412
+ if (options.serviceName !== void 0 && !/^[A-Za-z0-9_]{1,48}$/.test(options.serviceName)) {
9413
+ throw new UsageError("--service-name \u306F\u82F1\u6570\u5B57\u3068 underscore \u306E1..48\u6587\u5B57\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8655
9414
  }
8656
- const expectedToolNames = localToolNames.sort(comparePublicationUnicodeCodePoints2);
8657
- const planRequest = {
8658
- environment: "production",
8659
- connectorId,
8660
- candidateContract: candidate.candidateContract,
8661
- candidateCommitment: candidate.candidateCommitment,
8662
- ...project.manifest.template_id && project.manifest.template_application_commitment ? {
8663
- templateProvenance: {
8664
- templateId: project.manifest.template_id,
8665
- applicationCommitment: project.manifest.template_application_commitment
8666
- }
8667
- } : {}
8668
- };
8669
- const client = runtime.createClient(normalized.profile);
8670
- let rawPlan;
8671
- try {
8672
- rawPlan = await client.planPublication(projectId, planRequest);
8673
- } catch (error) {
8674
- throw remoteError(error, "plan", messages);
9415
+ const apply = options.apply === true;
9416
+ const yes = options.yes === true;
9417
+ if (yes && !apply) {
9418
+ throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8675
9419
  }
8676
- const plan = parsePlan(
8677
- rawPlan,
8678
- connectorId,
8679
- candidate.candidateCommitment,
8680
- expectedToolNames,
8681
- messages
8682
- );
8683
- writePlan(writer, plan);
8684
- if (plan.blockedReasons.includes("connector_mismatch")) {
8685
- interactive(writer, messages.connectorMismatchRemediation);
9420
+ if (options.idempotencyKey !== void 0 && !apply) {
9421
+ throw new UsageError("--idempotency-key \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8686
9422
  }
8687
- if (normalized.mode === "dry-run") return;
8688
- if (!plan.applyAllowed) {
8689
- throw new PublishCommandError(
8690
- "AP_POLICY_DENIED",
8691
- "publication_plan_blocked",
8692
- messages.planBlocked(plan.blockedReasons)
9423
+ if (!apply && options.planCommitment !== void 0) {
9424
+ throw new UsageError("--plan-commitment \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9425
+ }
9426
+ return {
9427
+ file: options.file,
9428
+ project: assertProjectId(options.project),
9429
+ connectorId: assertProjectId(options.connector),
9430
+ profile: options.profile ?? DEFAULT_PROFILE_NAME,
9431
+ ...options.format !== void 0 ? { format: options.format } : {},
9432
+ ...options.baseUrl !== void 0 ? { baseUrl: options.baseUrl } : {},
9433
+ ...options.serviceName !== void 0 ? { serviceName: options.serviceName } : {},
9434
+ apply,
9435
+ yes,
9436
+ ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {},
9437
+ ...options.planCommitment !== void 0 ? { planCommitment: options.planCommitment } : {},
9438
+ ...options.authMode !== void 0 ? { upstreamAuthMode: parseAuthModeOption(options.authMode) } : {},
9439
+ sideEffectFree: parseSideEffectFreeOptions(options.sideEffectFree)
9440
+ };
9441
+ }
9442
+ function rethrowWithAuthModeGuidance(error) {
9443
+ if (error instanceof AdminApiClientError && error.openApiAuthModeMismatch) {
9444
+ throw new UsageError(authModeMismatchGuidance(error.openApiAuthModeMismatch));
9445
+ }
9446
+ throw error;
9447
+ }
9448
+ async function runOpenApiImportCommand(options, writer, cwd, runtime = createOpenApiImportRuntime()) {
9449
+ const normalized = normalizedOptions(options);
9450
+ if (normalized.apply && !normalized.yes) {
9451
+ throw new ConfirmationRequiredError(
9452
+ "andpipe openapi import --apply",
9453
+ "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"
8693
9454
  );
8694
9455
  }
8695
- const idempotencyKey = assertIdempotencyKey2(runtime.randomUuid(), messages);
8696
- const applyRequest = (confirmation) => ({
8697
- ...planRequest,
8698
- planCommitment: plan.planCommitment,
8699
- confirmation
8700
- });
8701
- const initialApplyRequest = freezeJson(applyRequest(null));
8702
- const initial = await sendInitialApplyWithSameAnchorRetry({
8703
- client,
8704
- projectId,
8705
- idempotencyKey,
8706
- body: initialApplyRequest,
8707
- plan,
8708
- messages
9456
+ if (normalized.apply && !/^[a-f0-9]{64}$/.test(normalized.planCommitment ?? "")) {
9457
+ throw new UsageError("--apply \u306B\u306Fpreview\u3067\u5F97\u305F --plan-commitment \u304C\u5FC5\u9808\u3067\u3059");
9458
+ }
9459
+ const snapshot = readBoundedLocalFileSnapshot(resolve4(cwd, normalized.file), {
9460
+ maxBytes: OPENAPI_IMPORT_MAX_SOURCE_BYTES2,
9461
+ root: cwd
8709
9462
  });
8710
- let details;
8711
- if (initial.kind === "response") {
8712
- writeResult(writer, initial.result);
8713
- return;
8714
- } else {
8715
- if (plan.tools.every((tool) => !tool.changed)) {
8716
- throw responseInvalid("publication_noop_confirmation_invalid", messages);
9463
+ const baseRequest = {
9464
+ source: snapshot.text,
9465
+ connectorId: normalized.connectorId,
9466
+ ...normalized.format !== void 0 ? { format: normalized.format } : {},
9467
+ ...normalized.baseUrl !== void 0 ? { baseUrl: normalized.baseUrl } : {},
9468
+ ...normalized.serviceName !== void 0 ? { serviceName: normalized.serviceName } : {},
9469
+ ...normalized.upstreamAuthMode !== void 0 ? { upstreamAuthMode: normalized.upstreamAuthMode } : {}
9470
+ };
9471
+ const client = runtime.createClient(normalized.profile);
9472
+ const assertSource = (sourceCommitment) => {
9473
+ if (sourceCommitment !== snapshot.sha256) {
9474
+ throw new UsageError("Admin API\u306Esource commitment\u304Clocal file\u3068\u4E00\u81F4\u3057\u307E\u305B\u3093");
8717
9475
  }
8718
- details = initial.details;
8719
- }
8720
- writeSafeJson(writer, { phase: "confirmation_required", ...details });
8721
- const decision = await pollPublication(
8722
- client,
8723
- projectId,
8724
- details,
8725
- plan,
8726
- writer,
8727
- runtime,
8728
- "await-approval",
8729
- messages
8730
- );
8731
- if (decision.kind === "consumed") {
8732
- writeResult(writer, decision.result);
8733
- return;
8734
- }
8735
- try {
8736
- const result = parsePublicationResult(
8737
- await client.applyPublication(projectId, idempotencyKey, applyRequest(decision.confirmation)),
8738
- plan,
8739
- messages,
8740
- details.publicationId
8741
- );
8742
- writeResult(writer, result);
8743
- return;
8744
- } catch (error) {
8745
- if (error instanceof PublishCommandError && error.code === "AP_RESPONSE_INVALID") {
8746
- } else if (!approvedApplyResultMayBeUnknown(error)) {
8747
- throw remoteError(error, "approved_apply", messages);
9476
+ };
9477
+ let overrides = [];
9478
+ if (normalized.sideEffectFree.length > 0) {
9479
+ if (normalized.apply) {
9480
+ try {
9481
+ const unclassified = importOpenApi2(snapshot.text, {
9482
+ format: normalized.format,
9483
+ baseUrl: normalized.baseUrl,
9484
+ serviceName: normalized.serviceName,
9485
+ upstreamAuthMode: normalized.upstreamAuthMode
9486
+ });
9487
+ overrides = resolveOperationRiskOverrides(
9488
+ normalized.sideEffectFree,
9489
+ unclassified.operations
9490
+ );
9491
+ } catch (error) {
9492
+ if (error instanceof OpenApiImportError3) {
9493
+ throw new UsageError(`OpenAPI\u304B\u3089Tool Contract\u3092\u751F\u6210\u3067\u304D\u307E\u305B\u3093: ${error.message}`);
9494
+ }
9495
+ throw error;
9496
+ }
9497
+ } else {
9498
+ const unclassified = await client.planOpenApiImport(normalized.project, baseRequest).catch(rethrowWithAuthModeGuidance);
9499
+ assertSource(unclassified.sourceCommitment);
9500
+ overrides = resolveOperationRiskOverrides(normalized.sideEffectFree, unclassified.operations);
8748
9501
  }
8749
9502
  }
8750
- const recovered = await pollPublication(
8751
- client,
8752
- projectId,
8753
- details,
8754
- plan,
8755
- writer,
8756
- runtime,
8757
- "recover-result",
8758
- messages,
8759
- decision.expiresAt
8760
- );
8761
- if (recovered.kind !== "consumed") {
8762
- throw new PublishCommandError(
8763
- "AP_RESULT_UNKNOWN",
8764
- "publication_result_unknown",
8765
- messages.resultUnknown
8766
- );
9503
+ const request = {
9504
+ ...baseRequest,
9505
+ ...overrides.length > 0 ? { operationRiskOverrides: overrides } : {},
9506
+ ...normalized.planCommitment !== void 0 ? { expectedPlanCommitment: normalized.planCommitment } : {}
9507
+ };
9508
+ const classification = {
9509
+ upstreamAuthMode: normalized.upstreamAuthMode ?? "token_exchange",
9510
+ operationRiskOverrides: overrides
9511
+ };
9512
+ if (!normalized.apply) {
9513
+ const result2 = await client.planOpenApiImport(normalized.project, request).catch(rethrowWithAuthModeGuidance);
9514
+ assertSource(result2.sourceCommitment);
9515
+ json(writer, { mode: "preview", ...classification, ...result2 });
9516
+ const guidance = sideEffectFreeGuidance(result2.operations);
9517
+ if (guidance) interactive(writer, guidance);
9518
+ return;
8767
9519
  }
8768
- writeResult(writer, recovered.result);
9520
+ const result = await client.applyOpenApiImport(
9521
+ normalized.project,
9522
+ normalized.idempotencyKey ?? runtime.idempotencyKey(),
9523
+ request
9524
+ ).catch(rethrowWithAuthModeGuidance);
9525
+ assertSource(result.sourceCommitment);
9526
+ json(writer, { mode: "draft_created", ...classification, ...result });
8769
9527
  }
8770
- 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) {
8771
- 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) => {
8772
- await runPublishCommand(commandOptions, writer, cwd(), runtime, messages);
8773
- });
9528
+ function collect(value, previous) {
9529
+ return [...previous, value];
9530
+ }
9531
+ function registerOpenApi(program, writer, cwd, runtime = createOpenApiImportRuntime()) {
9532
+ const openapi = program.command("openapi").description("OpenAPI\u304B\u3089Tool Contract draft\u3092\u63D0\u6848\u3059\u308B");
9533
+ 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(
9534
+ "--auth-mode <mode>",
9535
+ "connector\u3068\u540C\u3058\u8A8D\u8A3C\u65B9\u5F0F\uFF08existing_oauth \u307E\u305F\u306F token_exchange\u3002\u7701\u7565\u6642\u306Ftoken_exchange\uFF09"
9536
+ ).option(
9537
+ "--side-effect-free <toolName=level>",
9538
+ "\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",
9539
+ collect,
9540
+ []
9541
+ ).action(
9542
+ (options) => runOpenApiImportCommand(options, writer, cwd(), runtime)
9543
+ );
8774
9544
  }
8775
9545
 
8776
9546
  // src/commands/review-package.ts
@@ -8903,6 +9673,7 @@ function registerValidate(program, writer, cwd, locale = DEFAULT_LOCALE9) {
8903
9673
  function buildProgram(writer = defaultWriter, cwd = () => process.cwd(), locale = normalizeLocale(process.env.ANDPIPE_LOCALE ?? process.env.LANG)) {
8904
9674
  const text = LOCALIZED_TEXT4[locale].cli;
8905
9675
  const messages = CLI_MESSAGES12[locale];
9676
+ const scopeRegistrationMessages = OAUTH_SCOPE_REGISTRATION_MESSAGES4[locale].cli;
8906
9677
  const program = new Command();
8907
9678
  program.name(CLI_NAME).description(text.description).option("--locale <locale>", messages.localeOption, DEFAULT_LOCALE10).version(readVersion());
8908
9679
  registerAuth(program, writer, locale);
@@ -8914,13 +9685,14 @@ function buildProgram(writer = defaultWriter, cwd = () => process.cwd(), locale
8914
9685
  (profile) => createAdminApiClient({ profile }),
8915
9686
  text.initDescription,
8916
9687
  void 0,
8917
- messages.init
9688
+ messages.init,
9689
+ scopeRegistrationMessages
8918
9690
  );
8919
9691
  registerDev(program, writer, cwd, void 0, text.devDescription, messages.dev);
8920
9692
  registerValidate(program, writer, cwd, locale);
8921
9693
  registerReviewPackage(program, writer, locale, cwd);
8922
9694
  registerDomain(program, writer, locale);
8923
- registerOauth(program, writer, locale);
9695
+ registerOauth(program, writer, locale, { cwd });
8924
9696
  registerOpenApi(program, writer, cwd);
8925
9697
  registerConfigMcp(program, writer, locale);
8926
9698
  registerDoctor(program, writer, locale);
@@ -8933,7 +9705,9 @@ function buildProgram(writer = defaultWriter, cwd = () => process.cwd(), locale
8933
9705
  (profile) => createAdminApiClient({ profile }),
8934
9706
  text.publishDescription,
8935
9707
  void 0,
8936
- messages.publish
9708
+ messages.publish,
9709
+ scopeRegistrationMessages,
9710
+ PUBLICATION_SCHEMA_REVIEW_CLI_MESSAGES2[locale]
8937
9711
  );
8938
9712
  return program;
8939
9713
  }
@@ -8984,6 +9758,9 @@ export {
8984
9758
  ADMIN_API_OPENAPI_IMPORT_MAX_BYTES,
8985
9759
  ADMIN_API_ONBOARDING_TEMPLATE_MAX_BYTES,
8986
9760
  ADMIN_API_MAX_GET_ATTEMPTS,
9761
+ ADMIN_API_OAUTH_SCOPE_REGISTRATION_REQUEST_MAX_BYTES,
9762
+ ADMIN_API_OAUTH_SCOPE_REGISTRATION_RESPONSE_MAX_BYTES,
9763
+ ADMIN_API_OAUTH_SCOPE_REGISTRATION_MAX_APPLY_ATTEMPTS,
8987
9764
  AdminApiClientError,
8988
9765
  assertProjectId,
8989
9766
  assertResourceId,
@@ -9039,15 +9816,18 @@ export {
9039
9816
  normalizeInitOptions,
9040
9817
  runInitCommand,
9041
9818
  registerInit,
9042
- validateOAuthMetadata,
9043
- createOpenApiImportRuntime,
9044
- runOpenApiImportCommand,
9045
- registerOpenApi,
9046
9819
  PublishCommandError,
9047
9820
  createPublishCommandRuntime,
9048
9821
  normalizePublishOptions,
9049
9822
  runPublishCommand,
9050
9823
  registerPublish,
9824
+ validateOAuthMetadata,
9825
+ createOAuthScopeRegisterRuntime,
9826
+ OAuthScopeRegistrationCommandError,
9827
+ runOAuthScopeRegisterCommand,
9828
+ createOpenApiImportRuntime,
9829
+ runOpenApiImportCommand,
9830
+ registerOpenApi,
9051
9831
  resolveContractPath,
9052
9832
  loadContract,
9053
9833
  buildProgram,