@andpipes/cli 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -22,6 +22,9 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  ADMIN_API_MAX_GET_ATTEMPTS: () => ADMIN_API_MAX_GET_ATTEMPTS,
24
24
  ADMIN_API_MAX_RESPONSE_BYTES: () => ADMIN_API_MAX_RESPONSE_BYTES,
25
+ ADMIN_API_OAUTH_SCOPE_REGISTRATION_MAX_APPLY_ATTEMPTS: () => ADMIN_API_OAUTH_SCOPE_REGISTRATION_MAX_APPLY_ATTEMPTS,
26
+ ADMIN_API_OAUTH_SCOPE_REGISTRATION_REQUEST_MAX_BYTES: () => ADMIN_API_OAUTH_SCOPE_REGISTRATION_REQUEST_MAX_BYTES,
27
+ ADMIN_API_OAUTH_SCOPE_REGISTRATION_RESPONSE_MAX_BYTES: () => ADMIN_API_OAUTH_SCOPE_REGISTRATION_RESPONSE_MAX_BYTES,
25
28
  ADMIN_API_ONBOARDING_TEMPLATE_MAX_BYTES: () => ADMIN_API_ONBOARDING_TEMPLATE_MAX_BYTES,
26
29
  ADMIN_API_OPENAPI_IMPORT_MAX_BYTES: () => ADMIN_API_OPENAPI_IMPORT_MAX_BYTES,
27
30
  ADMIN_API_ORIGIN: () => ADMIN_API_ORIGIN,
@@ -53,6 +56,7 @@ __export(index_exports, {
53
56
  DevProjectPreflightError: () => DevProjectPreflightError,
54
57
  InitLocalUsageError: () => InitLocalUsageError,
55
58
  InitManifestConflictError: () => InitManifestConflictError,
59
+ OAuthScopeRegistrationCommandError: () => OAuthScopeRegistrationCommandError,
56
60
  PACKAGE_NAME: () => PACKAGE_NAME,
57
61
  PublishCommandError: () => PublishCommandError,
58
62
  RISK_LEVELS: () => import_tool_contract4.RISK_LEVELS,
@@ -66,6 +70,7 @@ __export(index_exports, {
66
70
  connectConfigMcp: () => connectConfigMcp,
67
71
  createAdminApiClient: () => createAdminApiClient,
68
72
  createInitCommandRuntime: () => createInitCommandRuntime,
73
+ createOAuthScopeRegisterRuntime: () => createOAuthScopeRegisterRuntime,
69
74
  createOpenApiImportRuntime: () => createOpenApiImportRuntime,
70
75
  createPublishCommandRuntime: () => createPublishCommandRuntime,
71
76
  createS256Challenge: () => createS256Challenge,
@@ -108,6 +113,7 @@ __export(index_exports, {
108
113
  runDevCommand: () => runDevCommand,
109
114
  runDoctor: () => runDoctor,
110
115
  runInitCommand: () => runInitCommand,
116
+ runOAuthScopeRegisterCommand: () => runOAuthScopeRegisterCommand,
111
117
  runOpenApiImportCommand: () => runOpenApiImportCommand,
112
118
  runPublishCommand: () => runPublishCommand,
113
119
  runTemplatePlanOrApply: () => runTemplatePlanOrApply,
@@ -613,6 +619,26 @@ var ConfirmationRequiredError = class extends Error {
613
619
  }
614
620
  };
615
621
 
622
+ // src/lib/publication-review-profile.ts
623
+ var CLI_PUBLICATION_REVIEW_PROFILE = 2;
624
+ var PUBLICATION_ERROR_REASON_CODES = Object.freeze({
625
+ publication_plan_stale: "AP_CONFLICT",
626
+ publication_review_profile_invalid: "AP_INPUT_INVALID",
627
+ publication_schema_review_too_large: "AP_INPUT_INVALID",
628
+ schema_review_receipt_mismatch: "AP_CONFLICT"
629
+ });
630
+ function isPublicationErrorReasonFor(code, reason) {
631
+ return typeof reason === "string" && Object.hasOwn(PUBLICATION_ERROR_REASON_CODES, reason) && PUBLICATION_ERROR_REASON_CODES[reason] === code;
632
+ }
633
+ function parsePublicationErrorReason(status, code, details) {
634
+ if (status < 400 || status > 499) return void 0;
635
+ if (details === null || typeof details !== "object" || Array.isArray(details)) return void 0;
636
+ const record = details;
637
+ const keys = Object.keys(record);
638
+ if (keys.length !== 1 || keys[0] !== "reason") return void 0;
639
+ return isPublicationErrorReasonFor(code, record.reason) ? record.reason : void 0;
640
+ }
641
+
616
642
  // src/lib/backend.ts
617
643
  var ADMIN_API_ORIGIN = "https://api.andpipe.com";
618
644
  var ADMIN_API_TIMEOUT_MS = 1e4;
@@ -622,6 +648,9 @@ var ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES = 96 * 1024;
622
648
  var ADMIN_API_OPENAPI_IMPORT_MAX_BYTES = 1280 * 1024;
623
649
  var ADMIN_API_ONBOARDING_TEMPLATE_MAX_BYTES = 64 * 1024;
624
650
  var ADMIN_API_MAX_GET_ATTEMPTS = 3;
651
+ var ADMIN_API_OAUTH_SCOPE_REGISTRATION_REQUEST_MAX_BYTES = ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES + 8 * 1024;
652
+ var ADMIN_API_OAUTH_SCOPE_REGISTRATION_RESPONSE_MAX_BYTES = 1024 * 1024;
653
+ var ADMIN_API_OAUTH_SCOPE_REGISTRATION_MAX_APPLY_ATTEMPTS = 3;
625
654
  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;
626
655
  var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
627
656
  var SAFE_AP_CODE_RE = /^AP_[A-Z0-9_]{1,64}$/;
@@ -636,13 +665,21 @@ var AdminApiClientError = class extends Error {
636
665
  status;
637
666
  confirmationRequired;
638
667
  openApiAuthModeMismatch;
639
- constructor(code, message, status, confirmationRequired, openApiAuthModeMismatch) {
668
+ detailsAbsent;
669
+ scopeRegistrationReason;
670
+ publishGateToolNames;
671
+ publicationReason;
672
+ constructor(code, message, status, confirmationRequired, openApiAuthModeMismatch, safeDetails = {}) {
640
673
  super(message);
641
674
  this.name = "AdminApiClientError";
642
675
  this.code = code;
643
676
  this.status = status;
644
677
  this.confirmationRequired = confirmationRequired;
645
678
  this.openApiAuthModeMismatch = openApiAuthModeMismatch;
679
+ this.detailsAbsent = safeDetails.detailsAbsent === true;
680
+ this.scopeRegistrationReason = safeDetails.scopeRegistrationReason;
681
+ this.publishGateToolNames = safeDetails.publishGateToolNames === void 0 ? void 0 : Object.freeze([...safeDetails.publishGateToolNames]);
682
+ this.publicationReason = safeDetails.publicationReason;
646
683
  }
647
684
  };
648
685
  function clientError(code, message, status) {
@@ -853,7 +890,13 @@ function withKnownResponseStatus(error, responseStatus) {
853
890
  error.message,
854
891
  responseStatus,
855
892
  error.confirmationRequired,
856
- error.openApiAuthModeMismatch
893
+ error.openApiAuthModeMismatch,
894
+ {
895
+ detailsAbsent: error.detailsAbsent,
896
+ ...error.scopeRegistrationReason === void 0 ? {} : { scopeRegistrationReason: error.scopeRegistrationReason },
897
+ ...error.publishGateToolNames === void 0 ? {} : { publishGateToolNames: error.publishGateToolNames },
898
+ ...error.publicationReason === void 0 ? {} : { publicationReason: error.publicationReason }
899
+ }
857
900
  );
858
901
  }
859
902
  var CONNECTOR_AUTH_MODES = /* @__PURE__ */ new Set([
@@ -873,6 +916,27 @@ function parseOpenApiImportAuthModeMismatch(value) {
873
916
  requestedAuthMode: details.requestedAuthMode
874
917
  };
875
918
  }
919
+ function parseScopeRegistrationErrorDetails(status, value) {
920
+ if (status < 400 || status > 499) return {};
921
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return {};
922
+ const details = value;
923
+ const reason = details.reason;
924
+ if (!(0, import_tool_contract.isOAuthScopeRegistrationErrorReason)(reason)) return {};
925
+ const keys = Object.keys(details).sort().join(",");
926
+ if (reason === "marketplace_managed_tool") {
927
+ return keys === "reason" || keys === "reason,toolName" && (0, import_tool_contract.isSafeToolName)(details.toolName) ? { scopeRegistrationReason: reason } : {};
928
+ }
929
+ if (reason !== "scope_registration_publish_gate_failed") {
930
+ return keys === "reason" ? { scopeRegistrationReason: reason } : {};
931
+ }
932
+ const toolNames = details.toolNames;
933
+ if (keys !== "reason,toolNames" || !Array.isArray(toolNames) || toolNames.length < 1 || toolNames.length > import_tool_contract.OAUTH_SCOPE_REGISTRATION_MAX_TOOLS || !toolNames.every((name) => (0, import_tool_contract.isSafeToolName)(name)) || toolNames.some(
934
+ (name, index) => index > 0 && (0, import_tool_contract.comparePublicationUnicodeCodePoints)(toolNames[index - 1], name) >= 0
935
+ )) {
936
+ return {};
937
+ }
938
+ return { scopeRegistrationReason: reason, publishGateToolNames: toolNames };
939
+ }
876
940
  function unicodeScalarLength(value) {
877
941
  let length = 0;
878
942
  for (const character of value) {
@@ -900,12 +964,19 @@ function safeApiError(status, value) {
900
964
  const code = typeof candidate === "string" && SAFE_AP_CODE_RE.test(candidate) ? candidate : "AP_HTTP_ERROR";
901
965
  const confirmationRequired = code === "AP_CONFIRMATION_REQUIRED" && status === 409 ? parsePublicationConfirmationRequiredDetails(errorRecord?.details) : void 0;
902
966
  const openApiAuthModeMismatch = code === "AP_CONFLICT" && status === 409 ? parseOpenApiImportAuthModeMismatch(errorRecord?.details) : void 0;
967
+ const publicationReason = parsePublicationErrorReason(status, code, errorRecord?.details);
903
968
  return new AdminApiClientError(
904
969
  code,
905
970
  `Admin API request failed (${code}; HTTP ${status})`,
906
971
  status,
907
972
  confirmationRequired,
908
- openApiAuthModeMismatch
973
+ openApiAuthModeMismatch,
974
+ {
975
+ // AP error envelopeを受け取れた場合だけ「detailsなし」を判定できる。
976
+ detailsAbsent: errorRecord !== void 0 && (errorRecord.details === null || errorRecord.details === void 0),
977
+ ...parseScopeRegistrationErrorDetails(status, errorRecord?.details),
978
+ ...publicationReason === void 0 ? {} : { publicationReason }
979
+ }
909
980
  );
910
981
  }
911
982
  function buildUrl(path) {
@@ -1038,6 +1109,13 @@ function publicationPlanBody(input) {
1038
1109
  ...input.templateProvenance === void 0 ? {} : { templateProvenance: input.templateProvenance }
1039
1110
  };
1040
1111
  }
1112
+ function publicationReviewProfileOption(options) {
1113
+ if (options === void 0) return void 0;
1114
+ if (options === null || typeof options !== "object" || Object.keys(options).join(",") !== "reviewProfile" || options.reviewProfile !== 2) {
1115
+ throw clientError("AP_INPUT_INVALID", "tool publication review profile option is invalid");
1116
+ }
1117
+ return options.reviewProfile;
1118
+ }
1041
1119
  function publicationApplyBody(input) {
1042
1120
  const common = publicationPlanBody(input);
1043
1121
  if (!import_tool_contract.PUBLICATION_SHA256_COMMITMENT_RE.test(input.planCommitment)) {
@@ -1057,6 +1135,111 @@ function publicationApplyBody(input) {
1057
1135
  }
1058
1136
  };
1059
1137
  }
1138
+ function scopeRegistrationSourceInvalid() {
1139
+ return clientError("AP_INPUT_INVALID", "OAuth scope registration source is invalid");
1140
+ }
1141
+ function oauthScopeRegistrationSourceBody(source) {
1142
+ if (source.kind === "saved_drafts") {
1143
+ const drafts = source.drafts;
1144
+ if (!Array.isArray(drafts) || drafts.length < 1 || drafts.length > import_tool_contract.OAUTH_SCOPE_REGISTRATION_MAX_DRAFTS) {
1145
+ throw scopeRegistrationSourceInvalid();
1146
+ }
1147
+ const body = drafts.map((draft) => {
1148
+ if (!PUBLICATION_UUID_RE.test(draft.toolId) || !PUBLICATION_UUID_RE.test(draft.versionId)) {
1149
+ throw scopeRegistrationSourceInvalid();
1150
+ }
1151
+ return { toolId: draft.toolId, versionId: draft.versionId };
1152
+ });
1153
+ for (let index = 1; index < body.length; index += 1) {
1154
+ const previous = body[index - 1];
1155
+ const current = body[index];
1156
+ if ((0, import_tool_contract.comparePublicationUnicodeCodePoints)(previous.toolId, current.toolId) >= 0) {
1157
+ throw scopeRegistrationSourceInvalid();
1158
+ }
1159
+ }
1160
+ return { kind: "saved_drafts", drafts: body };
1161
+ }
1162
+ if (source.kind !== "publication_candidate") throw scopeRegistrationSourceInvalid();
1163
+ if (!PUBLICATION_UUID_RE.test(source.connectorId) || source.candidateContract === null || typeof source.candidateContract !== "object" || Array.isArray(source.candidateContract) || !import_tool_contract.PUBLICATION_SHA256_COMMITMENT_RE.test(source.candidateCommitment)) {
1164
+ throw scopeRegistrationSourceInvalid();
1165
+ }
1166
+ try {
1167
+ (0, import_tool_contract.assertCanonicalPublicationSize)(source.candidateContract);
1168
+ } catch {
1169
+ throw clientError("AP_INPUT_INVALID", "OAuth scope registration candidate is too large");
1170
+ }
1171
+ if ((0, import_tool_contract.publicationCommitment)("candidate", source.candidateContract) !== source.candidateCommitment) {
1172
+ throw clientError(
1173
+ "AP_CONFLICT",
1174
+ "OAuth scope registration candidate commitment does not match"
1175
+ );
1176
+ }
1177
+ return {
1178
+ kind: "publication_candidate",
1179
+ connectorId: source.connectorId,
1180
+ candidateContract: source.candidateContract,
1181
+ candidateCommitment: source.candidateCommitment
1182
+ };
1183
+ }
1184
+ function scopeRegistrationResponseInvalid() {
1185
+ return clientError(
1186
+ "AP_RESPONSE_INVALID",
1187
+ "Admin API response oauth scope registration is invalid"
1188
+ );
1189
+ }
1190
+ function parseOAuthScopeRegistration(value, projectId, request) {
1191
+ let parsed;
1192
+ try {
1193
+ parsed = (0, import_tool_contract.parseOAuthScopeRegistrationResponse)(value, { projectId });
1194
+ } catch (error) {
1195
+ if (error instanceof import_tool_contract.OAuthScopeRegistrationDtoError) throw scopeRegistrationResponseInvalid();
1196
+ throw error;
1197
+ }
1198
+ if (parsed.mode !== (request.apply ? "applied" : "preview") || parsed.source.kind !== request.source.kind) {
1199
+ throw scopeRegistrationResponseInvalid();
1200
+ }
1201
+ const source = request.source;
1202
+ if (source.kind === "publication_candidate") {
1203
+ if (parsed.source.connectorId !== source.connectorId || parsed.sourceCommitment !== (0, import_tool_contract.oauthScopeRegistrationSourceCommitment)({
1204
+ projectId,
1205
+ kind: "publication_candidate",
1206
+ connectorId: source.connectorId,
1207
+ candidateCommitment: source.candidateCommitment
1208
+ })) {
1209
+ throw scopeRegistrationResponseInvalid();
1210
+ }
1211
+ } else {
1212
+ const returned = parsed.source.tools.map((tool) => ({ toolId: tool.toolId, versionId: tool.versionId })).sort((left, right) => (0, import_tool_contract.comparePublicationUnicodeCodePoints)(left.toolId, right.toolId));
1213
+ if (returned.length !== source.drafts.length || returned.some(
1214
+ (draft, index) => draft.toolId !== source.drafts[index]?.toolId || draft.versionId !== source.drafts[index]?.versionId
1215
+ )) {
1216
+ throw scopeRegistrationResponseInvalid();
1217
+ }
1218
+ }
1219
+ if (request.apply && (parsed.sourceCommitment !== request.sourceCommitment || parsed.baseRegistryCommitment !== request.baseRegistryCommitment || parsed.planCommitment !== request.planCommitment)) {
1220
+ throw scopeRegistrationResponseInvalid();
1221
+ }
1222
+ return parsed;
1223
+ }
1224
+ var DEFINITIVE_SCOPE_REGISTRATION_APPLY_ERROR_CODES = /* @__PURE__ */ new Set([
1225
+ "AP_AUTH_REQUIRED",
1226
+ "AP_CONFIRMATION_EXPIRED",
1227
+ "AP_CONFLICT",
1228
+ "AP_FORBIDDEN",
1229
+ "AP_IDEMPOTENCY_KEY_CONFLICT",
1230
+ "AP_INPUT_INVALID",
1231
+ "AP_INVALID_SCOPE",
1232
+ "AP_NOT_FOUND",
1233
+ "AP_POLICY_DENIED",
1234
+ "AP_UNAUTHORIZED"
1235
+ ]);
1236
+ function scopeRegistrationApplyResultMayBeUnknown(error) {
1237
+ if (error.status !== void 0 && error.status >= 400 && error.status < 500) return false;
1238
+ if (error.status === void 0 && DEFINITIVE_SCOPE_REGISTRATION_APPLY_ERROR_CODES.has(error.code)) {
1239
+ return false;
1240
+ }
1241
+ return true;
1242
+ }
1060
1243
  function openApiImportBody(input) {
1061
1244
  if (typeof input.source !== "string" || input.source.length === 0 || !PUBLICATION_UUID_RE.test(input.connectorId) || input.expectedPlanCommitment !== void 0 && !SHA256_HEX_RE.test(input.expectedPlanCommitment) || input.format !== void 0 && input.format !== "json" && input.format !== "yaml" || input.baseUrl !== void 0 && typeof input.baseUrl !== "string" || input.serviceName !== void 0 && !/^[A-Za-z0-9_]{1,48}$/.test(input.serviceName) || input.upstreamAuthMode !== void 0 && !(0, import_tool_contract.isOpenApiImportUpstreamAuthMode)(input.upstreamAuthMode)) {
1062
1245
  throw clientError("AP_INPUT_INVALID", "OpenAPI import request is invalid");
@@ -1288,6 +1471,10 @@ var AdminApiClient = class {
1288
1471
  this.#sleep = options.sleep ?? ((milliseconds) => new Promise((resolve7) => setTimeout(resolve7, milliseconds)));
1289
1472
  }
1290
1473
  async #request(path, options = {}) {
1474
+ return (await this.#requestWithHeaders(path, options)).value;
1475
+ }
1476
+ /** 2xx bodyと、そのresponse headerを返す。headerはcommand層が必要な値だけを読む。 */
1477
+ async #requestWithHeaders(path, options = {}) {
1291
1478
  const url = buildUrl(path);
1292
1479
  const method = options.method ?? "GET";
1293
1480
  const attempts = method === "GET" ? ADMIN_API_MAX_GET_ATTEMPTS : 1;
@@ -1309,6 +1496,9 @@ var AdminApiClient = class {
1309
1496
  if (options.authenticated !== false) headers.set("Authorization", `Bearer ${this.#token}`);
1310
1497
  if (body !== void 0) headers.set("Content-Type", "application/json");
1311
1498
  if (options.idempotencyKey) headers.set("Idempotency-Key", options.idempotencyKey);
1499
+ if (options.reviewProfile !== void 0) {
1500
+ headers.set(import_tool_contract.PUBLICATION_REVIEW_PROFILE_HEADER, String(options.reviewProfile));
1501
+ }
1312
1502
  response = await this.#fetch(url, {
1313
1503
  method,
1314
1504
  headers,
@@ -1365,8 +1555,8 @@ var AdminApiClient = class {
1365
1555
  }
1366
1556
  throw safeApiError(response.status, errorBody);
1367
1557
  }
1368
- if (options.responseType === "text") return text;
1369
- return parseJson(text);
1558
+ if (options.responseType === "text") return { value: text, headers: response.headers };
1559
+ return { value: parseJson(text), headers: response.headers };
1370
1560
  }
1371
1561
  throw clientError("AP_NETWORK_ERROR", "Admin API request failed");
1372
1562
  }
@@ -1512,24 +1702,41 @@ var AdminApiClient = class {
1512
1702
  status: connector.status
1513
1703
  };
1514
1704
  }
1515
- async planPublication(projectId, body) {
1516
- return this.#request(`/v1/projects/${assertProjectId(projectId)}/tool-publications:plan`, {
1517
- method: "POST",
1518
- body: publicationPlanBody(body),
1519
- maxRequestBytes: ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES,
1520
- maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES
1521
- });
1705
+ async planPublication(projectId, body, options) {
1706
+ const reviewProfile = publicationReviewProfileOption(options);
1707
+ const response = await this.#requestWithHeaders(
1708
+ `/v1/projects/${assertProjectId(projectId)}/tool-publications:plan`,
1709
+ {
1710
+ method: "POST",
1711
+ body: publicationPlanBody(body),
1712
+ maxRequestBytes: ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES,
1713
+ maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES,
1714
+ ...reviewProfile === void 0 ? {} : { reviewProfile }
1715
+ }
1716
+ );
1717
+ if (reviewProfile === void 0) return response.value;
1718
+ const planResponse = {
1719
+ body: response.value,
1720
+ reviewProfileHeader: response.headers.get(import_tool_contract.PUBLICATION_REVIEW_PROFILE_HEADER)
1721
+ };
1722
+ return planResponse;
1522
1723
  }
1523
- async applyPublication(projectId, idempotencyKey, body) {
1724
+ /**
1725
+ * 初回apply(confirmation=null)と承認済みapply。options付き (#730) だけreview profile headerを送る。
1726
+ * request bodyとIdempotency-Keyはheaderの有無で変えない。
1727
+ */
1728
+ async applyPublication(projectId, idempotencyKey, body, options) {
1524
1729
  if (!/^[A-Za-z0-9._:-]{22,200}$/u.test(idempotencyKey)) {
1525
1730
  throw clientError("AP_INPUT_INVALID", "tool publication Idempotency-Key is invalid");
1526
1731
  }
1732
+ const reviewProfile = publicationReviewProfileOption(options);
1527
1733
  return this.#request(`/v1/projects/${assertProjectId(projectId)}/tool-publications`, {
1528
1734
  method: "POST",
1529
1735
  body: publicationApplyBody(body),
1530
1736
  idempotencyKey,
1531
1737
  maxRequestBytes: ADMIN_API_PUBLICATION_REQUEST_MAX_BYTES,
1532
- maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES
1738
+ maxResponseBytes: ADMIN_API_PUBLICATION_RESPONSE_MAX_BYTES,
1739
+ ...reviewProfile === void 0 ? {} : { reviewProfile }
1533
1740
  });
1534
1741
  }
1535
1742
  async planOpenApiImport(projectId, input) {
@@ -1896,6 +2103,75 @@ var AdminApiClient = class {
1896
2103
  planCommitment
1897
2104
  };
1898
2105
  }
2106
+ /**
2107
+ * `POST /v1/projects/{projectId}/oauth/scopes:register` (#729 / ADR-729)。previewは副作用なしで1回だけ送る。
2108
+ * applyはpreviewの3 commitmentと呼出側のIdempotency-Keyを必須にし、network・timeout・5xx・2xx応答の
2109
+ * 破損という曖昧な失敗だけ、同じkeyとbodyで最大3回まで送る。responseはexact 12 keyと
2110
+ * planCommitmentを再計算して検証し、requestとの束縛が崩れていれば`AP_RESPONSE_INVALID`にする。
2111
+ */
2112
+ async registerOAuthScopes(input) {
2113
+ const projectId = assertProjectId(input.projectId);
2114
+ const source = oauthScopeRegistrationSourceBody(input.source);
2115
+ const path = `/v1/projects/${projectId}/oauth/scopes:register`;
2116
+ const limits = {
2117
+ maxRequestBytes: ADMIN_API_OAUTH_SCOPE_REGISTRATION_REQUEST_MAX_BYTES,
2118
+ maxResponseBytes: ADMIN_API_OAUTH_SCOPE_REGISTRATION_RESPONSE_MAX_BYTES
2119
+ };
2120
+ if (!input.apply) {
2121
+ const value = await this.#request(path, {
2122
+ method: "POST",
2123
+ body: { apply: false, confirmed: false, source },
2124
+ ...limits
2125
+ });
2126
+ return parseOAuthScopeRegistration(value, projectId, input);
2127
+ }
2128
+ for (const commitment of [
2129
+ input.sourceCommitment,
2130
+ input.baseRegistryCommitment,
2131
+ input.planCommitment
2132
+ ]) {
2133
+ if (!import_tool_contract.PUBLICATION_SHA256_COMMITMENT_RE.test(commitment)) {
2134
+ throw clientError("AP_INPUT_INVALID", "OAuth scope registration commitment is invalid");
2135
+ }
2136
+ }
2137
+ if (!/^[A-Za-z0-9._:-]{22,200}$/u.test(input.idempotencyKey)) {
2138
+ throw clientError("AP_INPUT_INVALID", "OAuth scope registration Idempotency-Key is invalid");
2139
+ }
2140
+ const body = {
2141
+ apply: true,
2142
+ confirmed: true,
2143
+ source,
2144
+ sourceCommitment: input.sourceCommitment,
2145
+ baseRegistryCommitment: input.baseRegistryCommitment,
2146
+ planCommitment: input.planCommitment
2147
+ };
2148
+ if (Buffer.byteLength(JSON.stringify(body), "utf8") > limits.maxRequestBytes) {
2149
+ throw clientError("AP_INPUT_INVALID", "Admin API request body exceeds its byte limit");
2150
+ }
2151
+ for (let attempt = 1; ; attempt += 1) {
2152
+ try {
2153
+ const value = await this.#request(path, {
2154
+ method: "POST",
2155
+ body,
2156
+ idempotencyKey: input.idempotencyKey,
2157
+ ...limits
2158
+ });
2159
+ return parseOAuthScopeRegistration(value, projectId, input);
2160
+ } catch (error) {
2161
+ if (!(error instanceof AdminApiClientError) || !scopeRegistrationApplyResultMayBeUnknown(error)) {
2162
+ throw error;
2163
+ }
2164
+ if (attempt >= ADMIN_API_OAUTH_SCOPE_REGISTRATION_MAX_APPLY_ATTEMPTS) {
2165
+ throw clientError(
2166
+ "AP_RESULT_UNKNOWN",
2167
+ "OAuth scope registration result is unknown; review the current state without --apply before retrying",
2168
+ error.status
2169
+ );
2170
+ }
2171
+ await this.#sleep(100 * attempt);
2172
+ }
2173
+ }
2174
+ }
1899
2175
  async testOAuthLogin(projectId, clientRegistryId) {
1900
2176
  const selectedClientRegistryId = assertUuid(clientRegistryId, "OAuth client registry id");
1901
2177
  const value = asObject(
@@ -7472,6 +7748,8 @@ var MANIFEST_KEYS2 = [
7472
7748
  "template_application_commitment"
7473
7749
  ];
7474
7750
  var DEFAULT_INIT_MESSAGES = import_localization7.CLI_MESSAGES.ja.init;
7751
+ var DEFAULT_SCOPE_REGISTRATION_MESSAGES = import_localization7.OAUTH_SCOPE_REGISTRATION_MESSAGES.ja.cli;
7752
+ var CONNECTOR_PLACEHOLDER = "<connector-uuid>";
7475
7753
  function assertTemplateInitOptionShape(options, messages = DEFAULT_INIT_MESSAGES) {
7476
7754
  if (options.openapi !== void 0 && options.project === void 0) {
7477
7755
  throw new UsageError(messages.optionRequires("--openapi", "--project <uuid>"));
@@ -8102,7 +8380,7 @@ function assertIdempotencyKey(value, messages) {
8102
8380
  }
8103
8381
  return canonical;
8104
8382
  }
8105
- async function runInitCommand(options, writer, cwd, runtime, messages = DEFAULT_INIT_MESSAGES) {
8383
+ async function runInitCommand(options, writer, cwd, runtime, messages = DEFAULT_INIT_MESSAGES, scopeRegistrationMessages = DEFAULT_SCOPE_REGISTRATION_MESSAGES) {
8106
8384
  assertTemplateInitOptionShape(options, messages);
8107
8385
  if (options.template !== void 0 && options.project === void 0) {
8108
8386
  throw new UsageError("init --template\u306B\u306Fexport\u5143\u3068\u540C\u3058--project <uuid>\u304C\u5FC5\u9808\u3067\u3059");
@@ -8223,8 +8501,16 @@ async function runInitCommand(options, writer, cwd, runtime, messages = DEFAULT_
8223
8501
  project: { id: project.id, name: project.name, slug: project.slug }
8224
8502
  })
8225
8503
  );
8504
+ if (options.openapi !== void 0) {
8505
+ interactive(
8506
+ writer,
8507
+ scopeRegistrationMessages.initNextSteps(
8508
+ `--connector ${manifest.connector_id ?? CONNECTOR_PLACEHOLDER}`
8509
+ )
8510
+ );
8511
+ }
8226
8512
  }
8227
- 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) {
8513
+ 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) {
8228
8514
  const commandRuntime = runtime ?? createInitCommandRuntime(createClient, messages);
8229
8515
  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(
8230
8516
  "--auth-mode <mode>",
@@ -8239,7 +8525,14 @@ function registerInit(program, writer, cwd, createClient, description2 = "Projec
8239
8525
  "Create the template connector through the existing Admin API policy boundary",
8240
8526
  false
8241
8527
  ).option("--profile <name>", messages.profileOption, DEFAULT_PROFILE_NAME).option("--yes", messages.yesOption, false).action(async (options) => {
8242
- await runInitCommand(options, writer, cwd(), commandRuntime, messages);
8528
+ await runInitCommand(
8529
+ options,
8530
+ writer,
8531
+ cwd(),
8532
+ commandRuntime,
8533
+ messages,
8534
+ scopeRegistrationMessages
8535
+ );
8243
8536
  });
8244
8537
  }
8245
8538
 
@@ -8262,1160 +8555,1617 @@ function registerLogs(program, writer, locale = import_localization8.DEFAULT_LOC
8262
8555
  }
8263
8556
 
8264
8557
  // src/commands/oauth.ts
8558
+ var import_node_crypto13 = require("crypto");
8265
8559
  var import_node_fs11 = require("fs");
8560
+ var import_localization10 = require("@andpipes/localization");
8561
+ var import_tool_contract10 = require("@andpipes/tool-contract");
8562
+
8563
+ // src/commands/publish.ts
8564
+ var import_node_crypto12 = require("crypto");
8266
8565
  var import_localization9 = require("@andpipes/localization");
8267
- function isUrl(value) {
8268
- if (typeof value !== "string") {
8269
- return false;
8566
+ var import_tool_contract9 = require("@andpipes/tool-contract");
8567
+ 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;
8568
+ var SAFE_AP_CODE_RE2 = /^AP_[A-Z0-9_]{1,64}$/u;
8569
+ var PUBLICATION_RESPONSE_MAX_BYTES = 96 * 1024;
8570
+ var INITIAL_APPLY_MAX_ATTEMPTS = 3;
8571
+ var DEFAULT_PUBLISH_MESSAGES = import_localization9.CLI_MESSAGES.ja.publish;
8572
+ var DEFAULT_SCOPE_REGISTRATION_MESSAGES2 = import_localization9.OAUTH_SCOPE_REGISTRATION_MESSAGES.ja.cli;
8573
+ var DEFAULT_SCHEMA_REVIEW_MESSAGES = import_localization9.PUBLICATION_SCHEMA_REVIEW_CLI_MESSAGES.ja;
8574
+ var REVIEW_PROFILE_REQUEST = Object.freeze({
8575
+ reviewProfile: CLI_PUBLICATION_REVIEW_PROFILE
8576
+ });
8577
+ var PLAN_KEYS = [
8578
+ "requestId",
8579
+ "environment",
8580
+ "connectorId",
8581
+ "connectorRevision",
8582
+ "connectorCommitment",
8583
+ "policyCommitment",
8584
+ "candidateCommitment",
8585
+ "baseCommitment",
8586
+ "planCommitment",
8587
+ "tools",
8588
+ "retainedTools",
8589
+ "warnings",
8590
+ "applyAllowed",
8591
+ "blockedReasons"
8592
+ ];
8593
+ var APPLY_RESULT_KEYS = ["requestId", "publicationId", "state", "tools", "warnings"];
8594
+ var STATUS_KEYS = [
8595
+ "requestId",
8596
+ "publicationId",
8597
+ "durableState",
8598
+ "effectiveState",
8599
+ "expiresAt",
8600
+ "confirmation",
8601
+ "result"
8602
+ ];
8603
+ var BLOCKED_REASONS = /* @__PURE__ */ new Set([
8604
+ "project_not_active",
8605
+ "connector_not_active",
8606
+ "connector_mismatch",
8607
+ "tool_deprecated",
8608
+ "tool_plan_limit_exceeded",
8609
+ "production_capability_required",
8610
+ "write_tool_mode_not_confirmed",
8611
+ "production_oauth_broker_required",
8612
+ "oauth_scope_registry_missing",
8613
+ "oauth_scope_registry_risk_insufficient",
8614
+ "publish_gate_failed",
8615
+ "opaque_change",
8616
+ "retention_policy_blocked",
8617
+ "descriptor_name_conflict"
8618
+ ]);
8619
+ var TOOL_BLOCKED_REASONS = [
8620
+ "connector_mismatch",
8621
+ "opaque_change",
8622
+ "publish_gate_failed",
8623
+ "tool_deprecated"
8624
+ ];
8625
+ var DURABLE_STATES = /* @__PURE__ */ new Set(["pending", "approved", "rejected", "expired", "consumed"]);
8626
+ var EFFECTIVE_STATES = /* @__PURE__ */ new Set([
8627
+ "pending",
8628
+ "approved",
8629
+ "rejected",
8630
+ "expired",
8631
+ "consumed",
8632
+ "stale"
8633
+ ]);
8634
+ var DEFINITIVE_APPLY_ERROR_CODES = /* @__PURE__ */ new Set([
8635
+ "AP_AUTH_REQUIRED",
8636
+ "AP_CONFIRMATION_EXPIRED",
8637
+ "AP_CONFLICT",
8638
+ "AP_FORBIDDEN",
8639
+ "AP_IDEMPOTENCY_KEY_CONFLICT",
8640
+ "AP_INPUT_INVALID",
8641
+ "AP_INVALID_SCOPE",
8642
+ "AP_NOT_FOUND",
8643
+ "AP_POLICY_DENIED",
8644
+ "AP_UNAUTHORIZED"
8645
+ ]);
8646
+ var PublishCommandError = class extends Error {
8647
+ constructor(code, reason, message, status) {
8648
+ super(message);
8649
+ this.code = code;
8650
+ this.reason = reason;
8651
+ this.status = status;
8652
+ this.name = "PublishCommandError";
8653
+ }
8654
+ code;
8655
+ reason;
8656
+ status;
8657
+ };
8658
+ function createPublishCommandRuntime(createClient) {
8659
+ return {
8660
+ createClient,
8661
+ loadProject: loadDevProject,
8662
+ randomUuid: () => (0, import_node_crypto12.randomUUID)(),
8663
+ monotonicNow: () => Number(process.hrtime.bigint() / 1000000n),
8664
+ wallNow: () => Date.now(),
8665
+ sleep: (milliseconds) => new Promise((resolve7) => setTimeout(resolve7, milliseconds))
8666
+ };
8667
+ }
8668
+ function canonicalUuidOption(value, option, messages = DEFAULT_PUBLISH_MESSAGES) {
8669
+ const canonical = value.toLowerCase();
8670
+ if (!UUID_RE6.test(canonical)) {
8671
+ throw new UsageError(messages.invalidOption(option, "a canonical RFC 4122 UUID"));
8672
+ }
8673
+ return canonical;
8674
+ }
8675
+ function normalizePublishOptions(options, messages = DEFAULT_PUBLISH_MESSAGES) {
8676
+ if (options.dryRun === true && options.apply === true) {
8677
+ throw new UsageError(messages.incompatibleOptions("--dry-run / --apply"));
8678
+ }
8679
+ if (options.yes === true && options.apply !== true) {
8680
+ throw new UsageError(messages.optionRequires("--yes", "--apply"));
8681
+ }
8682
+ if (options.apply === true && options.yes !== true) {
8683
+ throw new ConfirmationRequiredError(
8684
+ "andpipe publish --apply",
8685
+ messages.applyConfirmationRequired
8686
+ );
8270
8687
  }
8688
+ const projectId = options.project === void 0 ? void 0 : canonicalUuidOption(options.project, "--project", messages);
8689
+ return {
8690
+ mode: options.apply === true ? "apply" : "dry-run",
8691
+ ...options.connector === void 0 ? {} : { connectorId: canonicalUuidOption(options.connector, "--connector", messages) },
8692
+ profile: options.profile ?? DEFAULT_PROFILE_NAME,
8693
+ ...projectId === void 0 ? {} : { projectId }
8694
+ };
8695
+ }
8696
+ function asRecord4(value) {
8697
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
8698
+ }
8699
+ function hasExactKeys3(record, keys) {
8700
+ const actual = Object.keys(record);
8701
+ return actual.length === keys.length && actual.every((key) => keys.includes(key));
8702
+ }
8703
+ function responseInvalid(reason, messages) {
8704
+ return new PublishCommandError("AP_RESPONSE_INVALID", reason, messages.failure(reason));
8705
+ }
8706
+ function assertCanonicalResponseSize(value, reason, messages, maxBytes = PUBLICATION_RESPONSE_MAX_BYTES) {
8271
8707
  try {
8272
- const u = new URL(value);
8273
- return u.protocol === "http:" || u.protocol === "https:";
8708
+ (0, import_tool_contract9.assertCanonicalPublicationSize)(value, maxBytes);
8274
8709
  } catch {
8275
- return false;
8710
+ throw responseInvalid(reason, messages);
8276
8711
  }
8277
8712
  }
8278
- function field(meta, snake, camel) {
8279
- return snake in meta ? meta[snake] : meta[camel];
8713
+ function isCanonicalUuid(value) {
8714
+ return typeof value === "string" && UUID_RE6.test(value);
8280
8715
  }
8281
- function validateOAuthMetadata(meta, locale = import_localization9.DEFAULT_LOCALE) {
8282
- const messages = import_localization9.CLI_MESSAGES[locale].oauth;
8283
- const results = [];
8284
- if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
8285
- return {
8286
- ok: false,
8287
- results: [
8288
- {
8289
- id: "metadata",
8290
- label: "metadata",
8291
- status: "fail",
8292
- detail: messages.metadataNotObject
8293
- }
8294
- ]
8295
- };
8716
+ function isCommitment(value) {
8717
+ return typeof value === "string" && import_tool_contract9.PUBLICATION_SHA256_COMMITMENT_RE.test(value);
8718
+ }
8719
+ function isCanonicalTimestamp(value) {
8720
+ if (typeof value !== "string" || value.length > 64) return false;
8721
+ const milliseconds = Date.parse(value);
8722
+ return Number.isFinite(milliseconds) && new Date(milliseconds).toISOString() === value;
8723
+ }
8724
+ function isStrictlySorted(values) {
8725
+ return values.every(
8726
+ (value, index) => index === 0 || (0, import_tool_contract9.comparePublicationUnicodeCodePoints)(values[index - 1], value) < 0
8727
+ );
8728
+ }
8729
+ function parseWarnings(value, messages) {
8730
+ try {
8731
+ return (0, import_tool_contract9.parsePublicationWarningsDto)(value);
8732
+ } catch {
8733
+ throw responseInvalid("publication_warnings_invalid", messages);
8296
8734
  }
8297
- const m = meta;
8298
- const urlFields = [
8299
- ["issuer", "issuer", "issuer"],
8300
- ["authorization_endpoint", "authorization_endpoint", "authorizationEndpoint"],
8301
- ["token_endpoint", "token_endpoint", "tokenEndpoint"],
8302
- ["jwks_uri", "jwks_uri", "jwksUri"]
8303
- ];
8304
- for (const [id, snake, camel] of urlFields) {
8305
- const value = field(m, snake, camel);
8306
- const ok = isUrl(value);
8307
- results.push({
8308
- id,
8309
- label: id,
8310
- status: ok ? "pass" : "fail",
8311
- detail: ok ? messages.urlOk : messages.invalidUrl(id)
8735
+ }
8736
+ function schemaReviewFailure(code, reason, text, status) {
8737
+ return new PublishCommandError(code, reason, `${text} (${reason})`, status);
8738
+ }
8739
+ function negotiateReviewProfile(response, messages, schemaReviewMessages) {
8740
+ const envelope = asRecord4(response);
8741
+ if (!envelope || !hasExactKeys3(envelope, ["body", "reviewProfileHeader"]) || envelope.reviewProfileHeader !== null && typeof envelope.reviewProfileHeader !== "string") {
8742
+ throw responseInvalid("publication_plan_invalid", messages);
8743
+ }
8744
+ const header = envelope.reviewProfileHeader;
8745
+ if (header !== null && header !== "1" && header !== "2") {
8746
+ throw schemaReviewFailure(
8747
+ "AP_RESPONSE_INVALID",
8748
+ "publication_review_profile_header_invalid",
8749
+ schemaReviewMessages.reviewProfileHeaderInvalid
8750
+ );
8751
+ }
8752
+ const body = asRecord4(envelope.body);
8753
+ const bodyDeclaresProfile = body !== null && Object.hasOwn(body, "reviewProfile");
8754
+ const profile = header === "2" ? 2 : 1;
8755
+ if (profile === 2 ? !bodyDeclaresProfile || body?.reviewProfile !== 2 : bodyDeclaresProfile) {
8756
+ throw schemaReviewFailure(
8757
+ "AP_CONFLICT",
8758
+ "publication_review_profile_mismatch",
8759
+ schemaReviewMessages.reviewProfileMismatch
8760
+ );
8761
+ }
8762
+ return {
8763
+ session: header === null ? { kind: "legacy", profile: 1 } : { kind: "negotiated", profile },
8764
+ body: envelope.body
8765
+ };
8766
+ }
8767
+ function parsePlan(value, connectorId, candidateCommitment, expectedToolNames, profile, messages) {
8768
+ assertCanonicalResponseSize(value, "publication_plan_too_large", messages);
8769
+ const plan = asRecord4(value);
8770
+ 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(
8771
+ (reason) => typeof reason === "string" && BLOCKED_REASONS.has(reason)
8772
+ ) || !isStrictlySorted(plan.blockedReasons) || plan.applyAllowed !== (plan.blockedReasons.length === 0)) {
8773
+ throw responseInvalid("publication_plan_invalid", messages);
8774
+ }
8775
+ const blockedReasons = plan.blockedReasons;
8776
+ let safeDiff;
8777
+ try {
8778
+ safeDiff = (0, import_tool_contract9.parsePublicationSafeDiffDto)({
8779
+ ...profile === 2 ? { reviewProfile: 2 } : {},
8780
+ tools: plan.tools,
8781
+ retainedTools: plan.retainedTools,
8782
+ warnings: plan.warnings
8312
8783
  });
8784
+ } catch {
8785
+ throw responseInvalid("publication_safe_diff_invalid", messages);
8313
8786
  }
8314
- const responseTypes = field(m, "response_types_supported", "responseTypesSupported");
8315
- results.push({
8316
- id: "response_types_supported",
8317
- label: "response_types_supported",
8318
- status: Array.isArray(responseTypes) && responseTypes.length > 0 ? "pass" : "fail",
8319
- detail: Array.isArray(responseTypes) ? messages.present : messages.arrayMissing
8320
- });
8321
- const scopes = field(m, "scopes_supported", "scopesSupported");
8322
- results.push({
8323
- id: "scopes_supported",
8324
- label: "scopes_supported",
8325
- // 推奨項目。欠落は致命ではないため pending 扱いで明示する。
8326
- status: Array.isArray(scopes) && scopes.length > 0 ? "pass" : "pending",
8327
- detail: Array.isArray(scopes) ? messages.present : messages.scopesMissing
8787
+ if (safeDiff.reviewProfile === 2 !== (profile === 2)) {
8788
+ throw responseInvalid("publication_safe_diff_invalid", messages);
8789
+ }
8790
+ const tools = safeDiff.tools;
8791
+ const toolNames = tools.map((tool) => tool.toolName);
8792
+ if (!isStrictlySorted(toolNames) || JSON.stringify(toolNames) !== JSON.stringify(expectedToolNames)) {
8793
+ throw responseInvalid("publication_plan_tools_order_invalid", messages);
8794
+ }
8795
+ const warnings = safeDiff.warnings;
8796
+ const expectedPlanCommitment = (0, import_tool_contract9.publicationCommitment)(profile === 2 ? "planV2" : "plan", {
8797
+ candidateCommitment,
8798
+ baseCommitment: plan.baseCommitment,
8799
+ connectorId,
8800
+ connectorRevision: plan.connectorRevision,
8801
+ connectorCommitment: plan.connectorCommitment,
8802
+ policyCommitment: plan.policyCommitment,
8803
+ environment: "production",
8804
+ safeDiff
8328
8805
  });
8329
- return { ok: results.every((r) => r.status !== "fail"), results };
8330
- }
8331
- function buildInitTemplate(provider) {
8806
+ if (plan.planCommitment !== expectedPlanCommitment) {
8807
+ throw new PublishCommandError(
8808
+ "AP_CONFLICT",
8809
+ "publication_plan_commitment_mismatch",
8810
+ messages.failure("publication_plan_commitment_mismatch")
8811
+ );
8812
+ }
8813
+ const toolBlockedReasons = new Set(tools.flatMap((tool) => tool.blockedReasons));
8814
+ if (tools.some((tool) => !tool.gate.ok) && plan.applyAllowed || tools.some((tool) => tool.opaqueChanged) && (plan.applyAllowed || !blockedReasons.includes("opaque_change")) || TOOL_BLOCKED_REASONS.some(
8815
+ (reason) => (
8816
+ // connector_mismatchはtool単位(既存toolの別connector束縛)に加え、candidateの
8817
+ // upstream.auth.modeとconnector方式の不一致としてtop-levelだけにも出る (#456 / #724)。
8818
+ reason === "connector_mismatch" ? toolBlockedReasons.has(reason) && !blockedReasons.includes(reason) : blockedReasons.includes(reason) !== toolBlockedReasons.has(reason)
8819
+ )
8820
+ )) {
8821
+ throw responseInvalid("publication_plan_gate_inconsistent", messages);
8822
+ }
8332
8823
  return {
8333
- provider,
8334
- issuer: "https://auth.example.com",
8335
- authorizationEndpoint: "https://auth.example.com/oauth/authorize",
8336
- tokenEndpoint: "https://auth.example.com/oauth/token",
8337
- jwksUri: "https://auth.example.com/.well-known/jwks.json",
8338
- clientId: "<client id>",
8339
- // secret は config に直書きせず env 参照にする (No secret in repo / stdout)。
8340
- clientSecretEnv: "ANDPIPE_OAUTH_CLIENT_SECRET",
8341
- redirectUri: "https://<your-andpipe-gateway>/oauth/callback",
8342
- scopes: ["openid", "profile"]
8824
+ ...profile === 2 ? { reviewProfile: 2 } : {},
8825
+ requestId: plan.requestId,
8826
+ environment: "production",
8827
+ connectorId,
8828
+ connectorRevision: plan.connectorRevision,
8829
+ connectorCommitment: plan.connectorCommitment,
8830
+ policyCommitment: plan.policyCommitment,
8831
+ candidateCommitment,
8832
+ baseCommitment: plan.baseCommitment,
8833
+ planCommitment: plan.planCommitment,
8834
+ tools,
8835
+ retainedTools: safeDiff.retainedTools,
8836
+ warnings,
8837
+ applyAllowed: plan.applyAllowed,
8838
+ blockedReasons
8343
8839
  };
8344
8840
  }
8345
- function upstreamOAuthWizardUrl(profile, projectId, connectorId) {
8346
- const record = getProfile(profile);
8347
- if (!record)
8348
- throw new UsageError(`\u8A8D\u8A3Cprofile ${profile} \u304C\u3042\u308A\u307E\u305B\u3093\u3002andpipe login\u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044`);
8349
- const url = new URL(`/projects/${projectId}/oauth`, new URL(record.verificationUriBase).origin);
8350
- url.searchParams.set("connector", connectorId);
8351
- return url.toString();
8841
+ function sameWarnings(left, right) {
8842
+ return JSON.stringify(left) === JSON.stringify(right);
8352
8843
  }
8353
- async function loadOAuthMetadata(opts, locale) {
8354
- const messages = import_localization9.CLI_MESSAGES[locale];
8355
- if (opts.file && opts.issuer) {
8356
- throw new UsageError("--file \u3068 --issuer \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");
8844
+ function parseToolResults(value, messages) {
8845
+ if (!Array.isArray(value)) {
8846
+ throw responseInvalid("publication_result_tools_invalid", messages);
8357
8847
  }
8358
- if (opts.issuer) {
8359
- return fetchOAuthMetadata(opts.issuer);
8848
+ const tools = value.map((candidate) => {
8849
+ const tool = asRecord4(candidate);
8850
+ if (!tool || !hasExactKeys3(tool, ["toolName", "operation", "toolId", "versionId", "version"]) || !(0, import_tool_contract9.isSafeToolName)(tool.toolName) || tool.operation !== "create" && tool.operation !== "update" || !isCanonicalUuid(tool.toolId) || !isCanonicalUuid(tool.versionId) || typeof tool.version !== "number" || !Number.isSafeInteger(tool.version) || tool.version < 1) {
8851
+ throw responseInvalid("publication_result_tool_invalid", messages);
8852
+ }
8853
+ const operation = tool.operation;
8854
+ return {
8855
+ toolName: tool.toolName,
8856
+ operation,
8857
+ toolId: tool.toolId,
8858
+ versionId: tool.versionId,
8859
+ version: tool.version
8860
+ };
8861
+ });
8862
+ if (!isStrictlySorted(tools.map((tool) => tool.toolName))) {
8863
+ throw responseInvalid("publication_result_tools_order_invalid", messages);
8360
8864
  }
8361
- if (!opts.file) {
8362
- throw new UsageError(messages.oauth.fileRequired);
8865
+ return tools;
8866
+ }
8867
+ function parsePublicationResult(value, plan, messages, expectedPublicationId) {
8868
+ assertCanonicalResponseSize(value, "publication_apply_result_too_large", messages);
8869
+ const result = asRecord4(value);
8870
+ if (!result || !hasExactKeys3(result, APPLY_RESULT_KEYS) || !isCanonicalUuid(result.requestId) || result.state !== "noop" && result.state !== "consumed") {
8871
+ throw responseInvalid("publication_apply_result_invalid", messages);
8363
8872
  }
8364
- try {
8365
- return JSON.parse((0, import_node_fs11.readFileSync)(opts.file, "utf8"));
8366
- } catch (error) {
8367
- throw new UsageError(messages.oauth.metadataReadFailed(error.message));
8873
+ const warnings = parseWarnings(result.warnings, messages);
8874
+ if (!sameWarnings(warnings, plan.warnings)) {
8875
+ throw responseInvalid("publication_apply_warning_mismatch", messages);
8876
+ }
8877
+ const tools = parseToolResults(result.tools, messages);
8878
+ const changedToolNames = plan.tools.filter((tool) => tool.changed).map((tool) => tool.toolName);
8879
+ if (result.state === "noop") {
8880
+ if (result.publicationId !== null || tools.length !== 0 || changedToolNames.length !== 0) {
8881
+ throw responseInvalid("publication_noop_invalid", messages);
8882
+ }
8883
+ return {
8884
+ requestId: result.requestId,
8885
+ publicationId: null,
8886
+ state: "noop",
8887
+ tools,
8888
+ warnings
8889
+ };
8890
+ }
8891
+ 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(
8892
+ (tool) => plan.tools.find((planned) => planned.toolName === tool.toolName)?.operation !== tool.operation
8893
+ )) {
8894
+ throw responseInvalid("publication_consumed_result_invalid", messages);
8368
8895
  }
8896
+ return {
8897
+ requestId: result.requestId,
8898
+ publicationId: result.publicationId,
8899
+ state: "consumed",
8900
+ tools,
8901
+ warnings
8902
+ };
8369
8903
  }
8370
- async function runOAuthMetadataValidate(opts, writer, locale) {
8371
- const messages = import_localization9.CLI_MESSAGES[locale];
8372
- const parsed = await loadOAuthMetadata(opts, locale);
8373
- const report = validateOAuthMetadata(parsed, locale);
8374
- json(writer, report.results);
8375
- if (!report.ok) {
8376
- process.exitCode = 1;
8377
- info(writer, messages.oauth.metadataFailed);
8378
- } else {
8379
- info(writer, messages.oauth.metadataOk);
8904
+ function parseConfirmation(value, messages) {
8905
+ if (value === null) return null;
8906
+ const confirmation = asRecord4(value);
8907
+ if (!confirmation || !hasExactKeys3(confirmation, ["confirmationId", "signature", "confirmed"]) || !isCanonicalUuid(confirmation.confirmationId) || typeof confirmation.signature !== "string" || !import_tool_contract9.PUBLICATION_CONFIRMATION_SIGNATURE_RE.test(confirmation.signature) || confirmation.confirmed !== true) {
8908
+ throw responseInvalid("publication_confirmation_invalid", messages);
8380
8909
  }
8910
+ return {
8911
+ confirmationId: confirmation.confirmationId,
8912
+ signature: confirmation.signature,
8913
+ confirmed: true
8914
+ };
8381
8915
  }
8382
- function registerOauth(program, writer, locale = import_localization9.DEFAULT_LOCALE, dependencies = {}) {
8383
- const messages = import_localization9.CLI_MESSAGES[locale];
8384
- const oauth = program.command("oauth").description(messages.oauth.commandDescription);
8385
- oauth.command("init").description(messages.oauth.initDescription).requiredOption("--provider <name>", messages.oauth.providerOption).action((opts) => {
8386
- info(writer, messages.oauth.templateHeading(opts.provider));
8387
- json(writer, buildInitTemplate(opts.provider));
8388
- info(writer, messages.oauth.clientSecretEnvNotice);
8389
- });
8390
- 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) => {
8391
- if (opts.project) {
8392
- if (opts.file || opts.issuer) {
8393
- throw new UsageError("--project \u306F --file / --issuer \u3068\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");
8394
- }
8395
- const projectId = assertProjectId(opts.project);
8396
- const result = await createAdminApiClient({ profile: opts.profile }).getOAuthSetup(
8397
- projectId
8398
- );
8399
- json(writer, result);
8400
- if (result.metadata.status !== "valid" || result.alignment.issues.length > 0) {
8401
- process.exitCode = 1;
8402
- }
8403
- return;
8404
- }
8405
- await runOAuthMetadataValidate(opts, writer, locale);
8406
- });
8407
- const scopes = oauth.command("scopes").description(messages.oauth.scopesDescription);
8408
- 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) => {
8409
- const operation = "andpipe oauth scopes sync";
8410
- if (opts.apply && !opts.yes) {
8411
- throw new ConfirmationRequiredError(
8412
- operation,
8413
- messages.common.confirmationRequiredMessage(operation)
8414
- );
8415
- }
8416
- if (!opts.apply && opts.yes) {
8417
- throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8418
- }
8419
- const projectId = assertProjectId(opts.project);
8420
- const result = await createAdminApiClient({ profile: opts.profile }).syncOAuthScopes({
8421
- projectId,
8422
- apply: opts.apply
8423
- });
8424
- json(writer, result);
8425
- });
8426
- const clients = oauth.command("clients").description("OAuth client\u306Escope\u5272\u5F53\u3092\u7BA1\u7406\u3059\u308B");
8427
- 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(
8428
- async (opts) => {
8429
- const operation = "andpipe oauth clients map-scopes";
8430
- if (opts.apply && !opts.yes) {
8431
- throw new ConfirmationRequiredError(
8432
- operation,
8433
- messages.common.confirmationRequiredMessage(operation)
8434
- );
8435
- }
8436
- if (!opts.apply && opts.yes) {
8437
- throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8438
- }
8439
- const client = createAdminApiClient({ profile: opts.profile });
8440
- const preview = await client.mapOAuthClientScopes({
8441
- projectId: assertProjectId(opts.project),
8442
- clientRegistryId: opts.client,
8443
- apply: false
8444
- });
8445
- json(writer, preview);
8446
- if (!opts.apply) return;
8447
- const applied = await client.mapOAuthClientScopes({
8448
- projectId: assertProjectId(opts.project),
8449
- clientRegistryId: opts.client,
8450
- apply: true,
8451
- requiredScopesCommitment: preview.requiredScopesCommitment,
8452
- baseClientGrantCommitment: preview.baseClientGrantCommitment,
8453
- candidateClientGrantCommitment: preview.candidateClientGrantCommitment,
8454
- planCommitment: preview.planCommitment
8455
- });
8456
- json(writer, applied);
8457
- }
8458
- );
8459
- const metadata = oauth.command("metadata").description(messages.oauth.metadataDescription);
8460
- metadata.command("validate").description(messages.oauth.validateDescription).option("--file <path>", messages.common.metadataFileOption).option("--issuer <url>", messages.common.issuerOption).action(async (opts) => {
8461
- await runOAuthMetadataValidate(opts, writer, locale);
8462
- });
8463
- const connect = oauth.command("connect").description(
8464
- 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"
8465
- );
8466
- connect.command("status").description(
8467
- locale === "ja" ? "\u63A5\u7D9A\u72B6\u614B\u3068\u6B21\u306E\u64CD\u4F5C\u3092\u8868\u793A" : "Show connection state and next action"
8468
- ).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) => {
8469
- const state = await createAdminApiClient({
8470
- profile: opts.profile
8471
- }).getUpstreamOAuthConnectionState(assertProjectId(opts.project), opts.connector);
8472
- json(writer, state);
8473
- if (!state.allGreen) process.exitCode = 1;
8474
- });
8475
- connect.command("open").description(
8476
- 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"
8477
- ).requiredOption("--project <project>", messages.common.projectOption).requiredOption("--connector <connector>", "\u63A5\u7D9A\u5BFE\u8C61connector UUID").option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).option(
8478
- "--no-browser",
8479
- locale === "ja" ? "\u65E2\u5B9A\u30D6\u30E9\u30A6\u30B6\u3092\u958B\u304B\u305AURL\u3060\u3051\u8868\u793A" : "Print the URL without opening a browser"
8480
- ).action(
8481
- async (opts) => {
8482
- const projectId = assertProjectId(opts.project);
8483
- const state = await createAdminApiClient({
8484
- profile: opts.profile
8485
- }).getUpstreamOAuthConnectionState(projectId, opts.connector);
8486
- json(writer, state);
8487
- const url = upstreamOAuthWizardUrl(opts.profile, projectId, opts.connector);
8488
- info(
8489
- writer,
8490
- locale === "ja" ? `Web Admin\u3067\u7D9A\u3051\u3066\u304F\u3060\u3055\u3044: ${url}` : `Continue in Web Admin: ${url}`
8491
- );
8492
- if (opts.browser) {
8493
- try {
8494
- (dependencies.openBrowser ?? openBrowser)(url);
8495
- } catch {
8496
- }
8497
- }
8498
- }
8499
- );
8500
- 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) => {
8501
- const projectId = assertProjectId(opts.project);
8502
- const result = await createAdminApiClient({ profile: opts.profile }).testOAuthLogin(
8503
- projectId,
8504
- opts.client
8505
- );
8506
- json(writer, result);
8507
- if (result.status === "blocked") process.exitCode = 1;
8508
- });
8509
- }
8510
-
8511
- // src/commands/openapi.ts
8512
- var import_node_crypto12 = require("crypto");
8513
- var import_node_path12 = require("path");
8514
- var import_tool_contract9 = require("@andpipes/tool-contract");
8515
- function createOpenApiImportRuntime(createClient = (profile) => createAdminApiClient({ profile })) {
8516
- return { createClient, idempotencyKey: import_node_crypto12.randomUUID };
8517
- }
8518
- function normalizedOptions(options) {
8519
- if (!options.file || !options.project || !options.connector) {
8520
- throw new UsageError("--file\u3001--project\u3001--connector \u306F\u5FC5\u9808\u3067\u3059");
8521
- }
8522
- if (options.format !== void 0 && options.format !== "json" && options.format !== "yaml") {
8523
- throw new UsageError("--format \u306F json \u307E\u305F\u306F yaml \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8524
- }
8525
- if (options.serviceName !== void 0 && !/^[A-Za-z0-9_]{1,48}$/.test(options.serviceName)) {
8526
- throw new UsageError("--service-name \u306F\u82F1\u6570\u5B57\u3068 underscore \u306E1..48\u6587\u5B57\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8527
- }
8528
- const apply = options.apply === true;
8529
- const yes = options.yes === true;
8530
- if (yes && !apply) {
8531
- throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8532
- }
8533
- if (options.idempotencyKey !== void 0 && !apply) {
8534
- throw new UsageError("--idempotency-key \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8916
+ function parseStatus(value, publicationId, plan, messages) {
8917
+ assertCanonicalResponseSize(value, "publication_status_too_large", messages);
8918
+ const status = asRecord4(value);
8919
+ 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)) {
8920
+ throw responseInvalid("publication_status_invalid", messages);
8535
8921
  }
8536
- if (!apply && options.planCommitment !== void 0) {
8537
- throw new UsageError("--plan-commitment \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
8922
+ const confirmation = parseConfirmation(status.confirmation, messages);
8923
+ const result = status.result === null ? null : parsePublicationResult(status.result, plan, messages, publicationId);
8924
+ const durableState = status.durableState;
8925
+ const effectiveState = status.effectiveState;
8926
+ const isPending = durableState === "pending";
8927
+ const isApproved = durableState === "approved";
8928
+ const isTerminal = durableState === "rejected" || durableState === "expired" || durableState === "consumed";
8929
+ 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)) {
8930
+ throw responseInvalid("publication_status_inconsistent", messages);
8538
8931
  }
8539
8932
  return {
8540
- file: options.file,
8541
- project: assertProjectId(options.project),
8542
- connectorId: assertProjectId(options.connector),
8543
- profile: options.profile ?? DEFAULT_PROFILE_NAME,
8544
- ...options.format !== void 0 ? { format: options.format } : {},
8545
- ...options.baseUrl !== void 0 ? { baseUrl: options.baseUrl } : {},
8546
- ...options.serviceName !== void 0 ? { serviceName: options.serviceName } : {},
8547
- apply,
8548
- yes,
8549
- ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {},
8550
- ...options.planCommitment !== void 0 ? { planCommitment: options.planCommitment } : {},
8551
- ...options.authMode !== void 0 ? { upstreamAuthMode: parseAuthModeOption(options.authMode) } : {},
8552
- sideEffectFree: parseSideEffectFreeOptions(options.sideEffectFree)
8933
+ requestId: status.requestId,
8934
+ publicationId,
8935
+ durableState,
8936
+ effectiveState,
8937
+ expiresAt: status.expiresAt,
8938
+ confirmation,
8939
+ result
8553
8940
  };
8554
8941
  }
8555
- function rethrowWithAuthModeGuidance(error) {
8556
- if (error instanceof AdminApiClientError && error.openApiAuthModeMismatch) {
8557
- throw new UsageError(authModeMismatchGuidance(error.openApiAuthModeMismatch));
8558
- }
8559
- throw error;
8942
+ function typedCode2(error) {
8943
+ if (error === null || typeof error !== "object") return void 0;
8944
+ const code = error.code;
8945
+ return typeof code === "string" && SAFE_AP_CODE_RE2.test(code) ? code : void 0;
8560
8946
  }
8561
- async function runOpenApiImportCommand(options, writer, cwd, runtime = createOpenApiImportRuntime()) {
8562
- const normalized = normalizedOptions(options);
8563
- if (normalized.apply && !normalized.yes) {
8564
- throw new ConfirmationRequiredError(
8565
- "andpipe openapi import --apply",
8566
- "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"
8947
+ function typedStatus2(error) {
8948
+ if (error === null || typeof error !== "object") return void 0;
8949
+ const status = error.status;
8950
+ return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599 ? status : void 0;
8951
+ }
8952
+ function typedPublicationReason(error, code) {
8953
+ if (error === null || typeof error !== "object") return void 0;
8954
+ const status = typedStatus2(error);
8955
+ if (status === void 0 || status < 400 || status > 499) return void 0;
8956
+ const reason = error.publicationReason;
8957
+ return isPublicationErrorReasonFor(code, reason) ? reason : void 0;
8958
+ }
8959
+ function publicationReasonText(reason, schemaReviewMessages) {
8960
+ switch (reason) {
8961
+ case "publication_schema_review_too_large":
8962
+ return schemaReviewMessages.schemaReviewTooLarge;
8963
+ case "publication_review_profile_invalid":
8964
+ return schemaReviewMessages.reviewProfileInvalid;
8965
+ case "schema_review_receipt_mismatch":
8966
+ return schemaReviewMessages.receiptMismatch;
8967
+ case "publication_plan_stale":
8968
+ return schemaReviewMessages.planStale;
8969
+ }
8970
+ }
8971
+ function remoteError(error, phase, messages, schemaReviewMessages) {
8972
+ const code = typedCode2(error) ?? "AP_NETWORK_ERROR";
8973
+ const publicationReason = schemaReviewMessages === void 0 ? void 0 : typedPublicationReason(error, code);
8974
+ if (publicationReason !== void 0 && schemaReviewMessages !== void 0) {
8975
+ return schemaReviewFailure(
8976
+ code,
8977
+ publicationReason,
8978
+ publicationReasonText(publicationReason, schemaReviewMessages),
8979
+ typedStatus2(error)
8567
8980
  );
8568
8981
  }
8569
- if (normalized.apply && !/^[a-f0-9]{64}$/.test(normalized.planCommitment ?? "")) {
8570
- throw new UsageError("--apply \u306B\u306Fpreview\u3067\u5F97\u305F --plan-commitment \u304C\u5FC5\u9808\u3067\u3059");
8982
+ return new PublishCommandError(
8983
+ code,
8984
+ `${phase}_failed`,
8985
+ messages.remoteFailure(phase, code),
8986
+ typedStatus2(error)
8987
+ );
8988
+ }
8989
+ function parseConfirmationRequired(error, projectId, messages) {
8990
+ if (typedCode2(error) !== "AP_CONFIRMATION_REQUIRED") return null;
8991
+ if (typedStatus2(error) !== 409 || error === null || typeof error !== "object") {
8992
+ throw responseInvalid("publication_confirmation_required_error_invalid", messages);
8571
8993
  }
8572
- const snapshot = readBoundedLocalFileSnapshot((0, import_node_path12.resolve)(cwd, normalized.file), {
8573
- maxBytes: import_tool_contract9.OPENAPI_IMPORT_MAX_SOURCE_BYTES,
8574
- root: cwd
8575
- });
8576
- const baseRequest = {
8577
- source: snapshot.text,
8578
- connectorId: normalized.connectorId,
8579
- ...normalized.format !== void 0 ? { format: normalized.format } : {},
8580
- ...normalized.baseUrl !== void 0 ? { baseUrl: normalized.baseUrl } : {},
8581
- ...normalized.serviceName !== void 0 ? { serviceName: normalized.serviceName } : {},
8582
- ...normalized.upstreamAuthMode !== void 0 ? { upstreamAuthMode: normalized.upstreamAuthMode } : {}
8583
- };
8584
- const client = runtime.createClient(normalized.profile);
8585
- const assertSource = (sourceCommitment) => {
8586
- if (sourceCommitment !== snapshot.sha256) {
8587
- throw new UsageError("Admin API\u306Esource commitment\u304Clocal file\u3068\u4E00\u81F4\u3057\u307E\u305B\u3093");
8588
- }
8589
- };
8590
- let overrides = [];
8591
- if (normalized.sideEffectFree.length > 0) {
8592
- if (normalized.apply) {
8593
- try {
8594
- const unclassified = (0, import_tool_contract9.importOpenApi)(snapshot.text, {
8595
- format: normalized.format,
8596
- baseUrl: normalized.baseUrl,
8597
- serviceName: normalized.serviceName,
8598
- upstreamAuthMode: normalized.upstreamAuthMode
8599
- });
8600
- overrides = resolveOperationRiskOverrides(
8601
- normalized.sideEffectFree,
8602
- unclassified.operations
8603
- );
8604
- } catch (error) {
8605
- if (error instanceof import_tool_contract9.OpenApiImportError) {
8606
- throw new UsageError(`OpenAPI\u304B\u3089Tool Contract\u3092\u751F\u6210\u3067\u304D\u307E\u305B\u3093: ${error.message}`);
8607
- }
8608
- throw error;
8609
- }
8610
- } else {
8611
- const unclassified = await client.planOpenApiImport(normalized.project, baseRequest).catch(rethrowWithAuthModeGuidance);
8612
- assertSource(unclassified.sourceCommitment);
8613
- overrides = resolveOperationRiskOverrides(normalized.sideEffectFree, unclassified.operations);
8614
- }
8994
+ const details = asRecord4(error.confirmationRequired);
8995
+ if (!details || !hasExactKeys3(details, [
8996
+ "requestId",
8997
+ "publicationId",
8998
+ "verificationUri",
8999
+ "expiresIn",
9000
+ "pollInterval"
9001
+ ]) || !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) {
9002
+ throw responseInvalid("publication_confirmation_required_details_invalid", messages);
8615
9003
  }
8616
- const request = {
8617
- ...baseRequest,
8618
- ...overrides.length > 0 ? { operationRiskOverrides: overrides } : {},
8619
- ...normalized.planCommitment !== void 0 ? { expectedPlanCommitment: normalized.planCommitment } : {}
8620
- };
8621
- const classification = {
8622
- upstreamAuthMode: normalized.upstreamAuthMode ?? "token_exchange",
8623
- operationRiskOverrides: overrides
8624
- };
8625
- if (!normalized.apply) {
8626
- const result2 = await client.planOpenApiImport(normalized.project, request).catch(rethrowWithAuthModeGuidance);
8627
- assertSource(result2.sourceCommitment);
8628
- json(writer, { mode: "preview", ...classification, ...result2 });
8629
- const guidance = sideEffectFreeGuidance(result2.operations);
8630
- if (guidance) interactive(writer, guidance);
8631
- return;
9004
+ let uri;
9005
+ try {
9006
+ uri = new URL(details.verificationUri);
9007
+ } catch {
9008
+ throw responseInvalid("publication_verification_uri_invalid", messages);
8632
9009
  }
8633
- const result = await client.applyOpenApiImport(
8634
- normalized.project,
8635
- normalized.idempotencyKey ?? runtime.idempotencyKey(),
8636
- request
8637
- ).catch(rethrowWithAuthModeGuidance);
8638
- assertSource(result.sourceCommitment);
8639
- json(writer, { mode: "draft_created", ...classification, ...result });
8640
- }
8641
- function collect(value, previous) {
8642
- return [...previous, value];
9010
+ const expectedPath = `/projects/${projectId}/tools/publications/${details.publicationId}`;
9011
+ if (uri.origin !== "https://admin.andpipe.com" || uri.pathname !== expectedPath || uri.username !== "" || uri.password !== "" || uri.search !== "" || uri.hash !== "" || uri.toString() !== details.verificationUri) {
9012
+ throw responseInvalid("publication_verification_uri_invalid", messages);
9013
+ }
9014
+ return {
9015
+ requestId: details.requestId,
9016
+ publicationId: details.publicationId,
9017
+ verificationUri: details.verificationUri,
9018
+ expiresIn: 600,
9019
+ pollInterval: details.pollInterval
9020
+ };
8643
9021
  }
8644
- function registerOpenApi(program, writer, cwd, runtime = createOpenApiImportRuntime()) {
8645
- const openapi = program.command("openapi").description("OpenAPI\u304B\u3089Tool Contract draft\u3092\u63D0\u6848\u3059\u308B");
8646
- 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(
8647
- "--auth-mode <mode>",
8648
- "connector\u3068\u540C\u3058\u8A8D\u8A3C\u65B9\u5F0F\uFF08existing_oauth \u307E\u305F\u306F token_exchange\u3002\u7701\u7565\u6642\u306Ftoken_exchange\uFF09"
8649
- ).option(
8650
- "--side-effect-free <toolName=level>",
8651
- "\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",
8652
- collect,
8653
- []
8654
- ).action(
8655
- (options) => runOpenApiImportCommand(options, writer, cwd(), runtime)
8656
- );
9022
+ function approvedApplyResultMayBeUnknown(error) {
9023
+ const status = typedStatus2(error);
9024
+ if (status !== void 0 && status >= 400 && status < 500) return false;
9025
+ const code = typedCode2(error);
9026
+ return code === void 0 || !DEFINITIVE_APPLY_ERROR_CODES.has(code);
8657
9027
  }
8658
-
8659
- // src/commands/publish.ts
8660
- var import_node_crypto13 = require("crypto");
8661
- var import_localization10 = require("@andpipes/localization");
8662
- var import_tool_contract10 = require("@andpipes/tool-contract");
8663
- 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;
8664
- var SAFE_AP_CODE_RE2 = /^AP_[A-Z0-9_]{1,64}$/u;
8665
- var PUBLICATION_RESPONSE_MAX_BYTES = 96 * 1024;
8666
- var INITIAL_APPLY_MAX_ATTEMPTS = 3;
8667
- var DEFAULT_PUBLISH_MESSAGES = import_localization10.CLI_MESSAGES.ja.publish;
8668
- var PLAN_KEYS = [
8669
- "requestId",
8670
- "environment",
8671
- "connectorId",
8672
- "connectorRevision",
8673
- "connectorCommitment",
8674
- "policyCommitment",
8675
- "candidateCommitment",
8676
- "baseCommitment",
8677
- "planCommitment",
8678
- "tools",
8679
- "retainedTools",
8680
- "warnings",
8681
- "applyAllowed",
8682
- "blockedReasons"
8683
- ];
8684
- var APPLY_RESULT_KEYS = ["requestId", "publicationId", "state", "tools", "warnings"];
8685
- var STATUS_KEYS = [
8686
- "requestId",
8687
- "publicationId",
8688
- "durableState",
8689
- "effectiveState",
8690
- "expiresAt",
8691
- "confirmation",
8692
- "result"
8693
- ];
8694
- var BLOCKED_REASONS = /* @__PURE__ */ new Set([
8695
- "project_not_active",
8696
- "connector_not_active",
8697
- "connector_mismatch",
8698
- "tool_deprecated",
8699
- "tool_plan_limit_exceeded",
8700
- "production_capability_required",
8701
- "write_tool_mode_not_confirmed",
8702
- "production_oauth_broker_required",
8703
- "oauth_scope_registry_missing",
8704
- "oauth_scope_registry_risk_insufficient",
8705
- "publish_gate_failed",
8706
- "opaque_change",
8707
- "retention_policy_blocked",
8708
- "descriptor_name_conflict"
8709
- ]);
8710
- var TOOL_BLOCKED_REASONS = [
8711
- "connector_mismatch",
8712
- "opaque_change",
8713
- "publish_gate_failed",
8714
- "tool_deprecated"
8715
- ];
8716
- var DURABLE_STATES = /* @__PURE__ */ new Set(["pending", "approved", "rejected", "expired", "consumed"]);
8717
- var EFFECTIVE_STATES = /* @__PURE__ */ new Set([
8718
- "pending",
8719
- "approved",
8720
- "rejected",
8721
- "expired",
8722
- "consumed",
8723
- "stale"
8724
- ]);
8725
- var DEFINITIVE_APPLY_ERROR_CODES = /* @__PURE__ */ new Set([
8726
- "AP_AUTH_REQUIRED",
8727
- "AP_CONFIRMATION_EXPIRED",
8728
- "AP_CONFLICT",
8729
- "AP_FORBIDDEN",
8730
- "AP_IDEMPOTENCY_KEY_CONFLICT",
8731
- "AP_INPUT_INVALID",
8732
- "AP_INVALID_SCOPE",
8733
- "AP_NOT_FOUND",
8734
- "AP_POLICY_DENIED",
8735
- "AP_UNAUTHORIZED"
8736
- ]);
8737
- var PublishCommandError = class extends Error {
8738
- constructor(code, reason, message, status) {
8739
- super(message);
8740
- this.code = code;
8741
- this.reason = reason;
8742
- this.status = status;
8743
- this.name = "PublishCommandError";
9028
+ function initialApplyResultMayBeUnknown(error) {
9029
+ const status = typedStatus2(error);
9030
+ if (status !== void 0 && status >= 400 && status < 500) return false;
9031
+ const code = typedCode2(error);
9032
+ if (status === void 0 && code !== void 0 && DEFINITIVE_APPLY_ERROR_CODES.has(code)) {
9033
+ return false;
8744
9034
  }
8745
- code;
8746
- reason;
8747
- status;
8748
- };
8749
- function createPublishCommandRuntime(createClient) {
9035
+ return true;
9036
+ }
9037
+ function writeSafeJson(writer, value) {
9038
+ json(writer, terminalSafeValue(value));
9039
+ }
9040
+ function writePlan(writer, plan) {
9041
+ writeSafeJson(writer, { phase: "plan", ...plan });
9042
+ }
9043
+ function writeSchemaReviewSummary(writer, plan, schemaReviewMessages) {
9044
+ if (plan.reviewProfile !== 2) return;
9045
+ const reviewed = plan.tools.filter((tool) => (tool.schemaReview?.enums.length ?? 0) > 0);
9046
+ if (reviewed.length === 0) return;
9047
+ interactive(writer, schemaReviewMessages.heading);
9048
+ for (const tool of reviewed) {
9049
+ const review = tool.schemaReview;
9050
+ if (!review) continue;
9051
+ const count = (change) => review.enums.filter((entry) => entry.change === change).length;
9052
+ interactive(
9053
+ writer,
9054
+ schemaReviewMessages.toolSummary({
9055
+ toolName: terminalSafeText(tool.toolName),
9056
+ total: review.enums.length,
9057
+ added: count("added"),
9058
+ changed: count("changed"),
9059
+ removed: count("removed"),
9060
+ unchanged: count("unchanged"),
9061
+ valueReviewRequired: review.humanValueReviewRequired
9062
+ })
9063
+ );
9064
+ }
9065
+ if (reviewed.some((tool) => tool.schemaReview?.humanValueReviewRequired === true)) {
9066
+ interactive(writer, schemaReviewMessages.valueReviewInWebAdmin);
9067
+ }
9068
+ }
9069
+ function candidateNeedsReviewProfile2(candidateContract) {
9070
+ return (0, import_tool_contract9.selectPublicationReviewProfile)({
9071
+ requestedProfile: CLI_PUBLICATION_REVIEW_PROFILE,
9072
+ candidateContract,
9073
+ currentTools: []
9074
+ }) === 2;
9075
+ }
9076
+ function applyPublicationWithProfile(client, projectId, idempotencyKey, body, session) {
9077
+ return session.kind === "negotiated" ? client.applyPublication(projectId, idempotencyKey, body, REVIEW_PROFILE_REQUEST) : client.applyPublication(projectId, idempotencyKey, body);
9078
+ }
9079
+ function writeResult(writer, result) {
9080
+ writeSafeJson(writer, { phase: "result", ...result });
9081
+ }
9082
+ function freezeJson(value) {
9083
+ if (Array.isArray(value)) {
9084
+ for (const item of value) freezeJson(item);
9085
+ return Object.freeze(value);
9086
+ }
9087
+ if (value !== null && typeof value === "object") {
9088
+ for (const item of Object.values(value)) freezeJson(item);
9089
+ return Object.freeze(value);
9090
+ }
9091
+ return value;
9092
+ }
9093
+ function prepareCandidate(project) {
9094
+ const canonical = (0, import_tool_contract9.assertCanonicalPublicationSize)(project.contract.root);
9095
+ const candidateContract = freezeJson(JSON.parse(canonical));
8750
9096
  return {
8751
- createClient,
8752
- loadProject: loadDevProject,
8753
- randomUuid: () => (0, import_node_crypto13.randomUUID)(),
8754
- monotonicNow: () => Number(process.hrtime.bigint() / 1000000n),
8755
- wallNow: () => Date.now(),
8756
- sleep: (milliseconds) => new Promise((resolve7) => setTimeout(resolve7, milliseconds))
9097
+ candidateContract,
9098
+ candidateCommitment: (0, import_tool_contract9.publicationCommitment)("candidate", candidateContract)
8757
9099
  };
8758
9100
  }
8759
- function canonicalUuid(value, option, messages) {
8760
- const canonical = value.toLowerCase();
8761
- if (!UUID_RE6.test(canonical)) {
8762
- throw new UsageError(messages.invalidOption(option, "a canonical RFC 4122 UUID"));
9101
+ function loadPublicationProject(loadProject, cwd, messages = DEFAULT_PUBLISH_MESSAGES) {
9102
+ try {
9103
+ return loadProject(cwd);
9104
+ } catch (error) {
9105
+ if (error instanceof LocalFilePolicyError) {
9106
+ throw new PublishCommandError(
9107
+ "AP_POLICY_DENIED",
9108
+ error.reason,
9109
+ messages.failure(error.reason)
9110
+ );
9111
+ }
9112
+ const reason = error instanceof DevProjectLoadError ? error.reason : "local_project_invalid";
9113
+ if (error instanceof DevProjectLoadError || error instanceof UsageError) {
9114
+ throw new PublishCommandError("AP_INPUT_INVALID", reason, messages.failure(reason));
9115
+ }
9116
+ throw error;
8763
9117
  }
8764
- return canonical;
8765
9118
  }
8766
- function normalizePublishOptions(options, messages = DEFAULT_PUBLISH_MESSAGES) {
8767
- if (options.dryRun === true && options.apply === true) {
8768
- throw new UsageError(messages.incompatibleOptions("--dry-run / --apply"));
8769
- }
8770
- if (options.yes === true && options.apply !== true) {
8771
- throw new UsageError(messages.optionRequires("--yes", "--apply"));
9119
+ function assertManifestProject(project, requestedProjectId, messages = DEFAULT_PUBLISH_MESSAGES) {
9120
+ const projectId = project.manifest.project_id;
9121
+ if (requestedProjectId !== void 0 && requestedProjectId !== projectId) {
9122
+ throw new PublishCommandError(
9123
+ "AP_CONFLICT",
9124
+ "manifest_project_mismatch",
9125
+ messages.failure("manifest_project_mismatch")
9126
+ );
8772
9127
  }
8773
- if (options.apply === true && options.yes !== true) {
8774
- throw new ConfirmationRequiredError(
8775
- "andpipe publish --apply",
8776
- messages.applyConfirmationRequired
9128
+ return projectId;
9129
+ }
9130
+ function buildLocalPublicationCandidate(project, connectorId, messages = DEFAULT_PUBLISH_MESSAGES) {
9131
+ const candidate = prepareCandidate(project);
9132
+ const localToolNames = project.contract.tools.map((tool) => (0, import_tool_contract9.toolName)(tool));
9133
+ if (localToolNames.some((name) => !(0, import_tool_contract9.isSafeToolName)(name))) {
9134
+ throw new PublishCommandError(
9135
+ "AP_INPUT_INVALID",
9136
+ "publication_candidate_tool_invalid",
9137
+ messages.failure("publication_candidate_tool_invalid")
8777
9138
  );
8778
9139
  }
8779
- const projectId = options.project === void 0 ? void 0 : canonicalUuid(options.project, "--project", messages);
9140
+ const expectedToolNames = localToolNames.sort(import_tool_contract9.comparePublicationUnicodeCodePoints);
8780
9141
  return {
8781
- mode: options.apply === true ? "apply" : "dry-run",
8782
- ...options.connector === void 0 ? {} : { connectorId: canonicalUuid(options.connector, "--connector", messages) },
8783
- profile: options.profile ?? DEFAULT_PROFILE_NAME,
8784
- ...projectId === void 0 ? {} : { projectId }
9142
+ planRequest: {
9143
+ environment: "production",
9144
+ connectorId,
9145
+ candidateContract: candidate.candidateContract,
9146
+ candidateCommitment: candidate.candidateCommitment,
9147
+ ...project.manifest.template_id && project.manifest.template_application_commitment ? {
9148
+ templateProvenance: {
9149
+ templateId: project.manifest.template_id,
9150
+ applicationCommitment: project.manifest.template_application_commitment
9151
+ }
9152
+ } : {}
9153
+ },
9154
+ expectedToolNames
8785
9155
  };
8786
9156
  }
8787
- function asRecord4(value) {
8788
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
9157
+ function assertIdempotencyKey2(value, messages) {
9158
+ if (!UUID_RE6.test(value)) {
9159
+ throw new PublishCommandError(
9160
+ "AP_NETWORK_ERROR",
9161
+ "secure_random_invalid",
9162
+ messages.failure("secure_random_invalid")
9163
+ );
9164
+ }
9165
+ return value;
8789
9166
  }
8790
- function hasExactKeys3(record, keys) {
8791
- const actual = Object.keys(record);
8792
- return actual.length === keys.length && actual.every((key) => keys.includes(key));
9167
+ async function sendInitialApplyWithSameAnchorRetry(input) {
9168
+ for (let attempt = 0; attempt < INITIAL_APPLY_MAX_ATTEMPTS; attempt += 1) {
9169
+ try {
9170
+ const result = parsePublicationResult(
9171
+ await applyPublicationWithProfile(
9172
+ input.client,
9173
+ input.projectId,
9174
+ input.idempotencyKey,
9175
+ input.body,
9176
+ input.session
9177
+ ),
9178
+ input.plan,
9179
+ input.messages
9180
+ );
9181
+ if (result.state !== "noop") {
9182
+ throw responseInvalid("publication_initial_apply_state_invalid", input.messages);
9183
+ }
9184
+ return {
9185
+ kind: "response",
9186
+ result
9187
+ };
9188
+ } catch (error) {
9189
+ let malformedConfirmationAnchor = false;
9190
+ let confirmationRequired = null;
9191
+ try {
9192
+ confirmationRequired = parseConfirmationRequired(error, input.projectId, input.messages);
9193
+ } catch (parseError) {
9194
+ if (typedCode2(error) !== "AP_CONFIRMATION_REQUIRED" || !(parseError instanceof PublishCommandError) || parseError.code !== "AP_RESPONSE_INVALID") {
9195
+ throw parseError;
9196
+ }
9197
+ malformedConfirmationAnchor = true;
9198
+ }
9199
+ if (confirmationRequired) {
9200
+ return { kind: "confirmation_required", details: confirmationRequired };
9201
+ }
9202
+ if (!malformedConfirmationAnchor && !initialApplyResultMayBeUnknown(error)) {
9203
+ throw remoteError(error, "initial_apply", input.messages, input.schemaReviewMessages);
9204
+ }
9205
+ if (attempt === INITIAL_APPLY_MAX_ATTEMPTS - 1) {
9206
+ throw new PublishCommandError(
9207
+ "AP_RESULT_UNKNOWN",
9208
+ "publication_anchor_result_unknown",
9209
+ input.messages.proposalResultUnknown
9210
+ );
9211
+ }
9212
+ }
9213
+ }
9214
+ throw new PublishCommandError(
9215
+ "AP_RESULT_UNKNOWN",
9216
+ "publication_anchor_result_unknown",
9217
+ input.messages.proposalResultUnknown
9218
+ );
8793
9219
  }
8794
- function responseInvalid(reason, messages) {
8795
- return new PublishCommandError("AP_RESPONSE_INVALID", reason, messages.failure(reason));
9220
+ function confirmationStopped(code, reason, messages) {
9221
+ return new PublishCommandError(code, reason, messages.confirmationStopped(reason));
8796
9222
  }
8797
- function assertCanonicalResponseSize(value, reason, messages, maxBytes = PUBLICATION_RESPONSE_MAX_BYTES) {
9223
+ function pollFailureIsDefinitive(error) {
9224
+ const status = typedStatus2(error);
9225
+ if (status !== void 0 && status >= 400 && status < 500) return true;
9226
+ const code = typedCode2(error);
9227
+ return code === "AP_RESPONSE_INVALID" || code === "AP_OUTPUT_INVALID" || code !== void 0 && DEFINITIVE_APPLY_ERROR_CODES.has(code);
9228
+ }
9229
+ async function sleepForPoll(runtime, milliseconds, mode, messages) {
8798
9230
  try {
8799
- (0, import_tool_contract10.assertCanonicalPublicationSize)(value, maxBytes);
9231
+ await runtime.sleep(milliseconds);
8800
9232
  } catch {
8801
- throw responseInvalid(reason, messages);
9233
+ throw new PublishCommandError(
9234
+ mode === "recover-result" ? "AP_RESULT_UNKNOWN" : "AP_NETWORK_ERROR",
9235
+ "publication_poll_sleep_failed",
9236
+ messages.pollingUnavailable
9237
+ );
9238
+ }
9239
+ }
9240
+ async function pollPublication(client, projectId, details, plan, writer, runtime, mode, messages, knownExpiresAt) {
9241
+ const startedAt = runtime.monotonicNow();
9242
+ let deadline = startedAt + details.expiresIn * 1e3;
9243
+ let expiresAt = knownExpiresAt;
9244
+ if (knownExpiresAt !== void 0) {
9245
+ deadline = Math.min(
9246
+ deadline,
9247
+ startedAt + Math.max(0, Date.parse(knownExpiresAt) - runtime.wallNow())
9248
+ );
9249
+ }
9250
+ const maxAttempts = Math.ceil(details.expiresIn / details.pollInterval) + 2;
9251
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
9252
+ let rawStatus;
9253
+ try {
9254
+ rawStatus = await client.getPublication(projectId, details.publicationId);
9255
+ } catch (error) {
9256
+ if (pollFailureIsDefinitive(error)) {
9257
+ throw remoteError(error, mode === "recover-result" ? "result_recovery" : "poll", messages);
9258
+ }
9259
+ const remainingMilliseconds2 = Math.max(0, deadline - runtime.monotonicNow());
9260
+ if (remainingMilliseconds2 <= 0 || attempt === maxAttempts - 1) {
9261
+ throw new PublishCommandError(
9262
+ mode === "recover-result" ? "AP_RESULT_UNKNOWN" : "AP_NETWORK_ERROR",
9263
+ "publication_poll_unavailable",
9264
+ messages.pollingUnavailable
9265
+ );
9266
+ }
9267
+ await sleepForPoll(
9268
+ runtime,
9269
+ Math.min(details.pollInterval * 1e3, remainingMilliseconds2),
9270
+ mode,
9271
+ messages
9272
+ );
9273
+ continue;
9274
+ }
9275
+ const status = parseStatus(rawStatus, details.publicationId, plan, messages);
9276
+ if (expiresAt !== void 0 && status.expiresAt !== expiresAt) {
9277
+ throw responseInvalid("publication_expiry_changed", messages);
9278
+ }
9279
+ expiresAt = status.expiresAt;
9280
+ const now = runtime.monotonicNow();
9281
+ const wallRemaining = Math.max(0, Date.parse(status.expiresAt) - runtime.wallNow());
9282
+ deadline = Math.min(deadline, now + wallRemaining);
9283
+ const remainingMilliseconds = Math.max(0, deadline - now);
9284
+ writeSafeJson(writer, {
9285
+ phase: mode === "recover-result" ? "result_recovery" : "confirmation",
9286
+ requestId: status.requestId,
9287
+ publicationId: status.publicationId,
9288
+ durableState: status.durableState,
9289
+ effectiveState: status.effectiveState,
9290
+ expiresAt: status.expiresAt,
9291
+ remainingSeconds: Math.ceil(remainingMilliseconds / 1e3)
9292
+ });
9293
+ if (status.durableState === "consumed") {
9294
+ return { kind: "consumed", result: status.result };
9295
+ }
9296
+ if (status.durableState === "rejected") {
9297
+ throw confirmationStopped("AP_POLICY_DENIED", "publication_rejected", messages);
9298
+ }
9299
+ if (status.durableState === "expired") {
9300
+ throw confirmationStopped(
9301
+ "AP_CONFIRMATION_EXPIRED",
9302
+ "publication_confirmation_expired",
9303
+ messages
9304
+ );
9305
+ }
9306
+ if (status.effectiveState === "stale") {
9307
+ throw confirmationStopped("AP_CONFLICT", "publication_confirmation_stale", messages);
9308
+ }
9309
+ if (mode === "await-approval" && status.durableState === "approved" && status.confirmation !== null) {
9310
+ return {
9311
+ kind: "approved",
9312
+ confirmation: status.confirmation,
9313
+ expiresAt: status.expiresAt
9314
+ };
9315
+ }
9316
+ if (remainingMilliseconds <= 0) {
9317
+ throw confirmationStopped(
9318
+ "AP_CONFIRMATION_EXPIRED",
9319
+ "publication_confirmation_timeout",
9320
+ messages
9321
+ );
9322
+ }
9323
+ const sleepMilliseconds = Math.min(details.pollInterval * 1e3, remainingMilliseconds);
9324
+ await sleepForPoll(runtime, sleepMilliseconds, mode, messages);
8802
9325
  }
9326
+ throw confirmationStopped("AP_CONFIRMATION_EXPIRED", "publication_poll_attempt_limit", messages);
8803
9327
  }
8804
- function isCanonicalUuid(value) {
8805
- return typeof value === "string" && UUID_RE6.test(value);
8806
- }
8807
- function isCommitment(value) {
8808
- return typeof value === "string" && import_tool_contract10.PUBLICATION_SHA256_COMMITMENT_RE.test(value);
8809
- }
8810
- function isCanonicalTimestamp(value) {
8811
- if (typeof value !== "string" || value.length > 64) return false;
8812
- const milliseconds = Date.parse(value);
8813
- return Number.isFinite(milliseconds) && new Date(milliseconds).toISOString() === value;
8814
- }
8815
- function isStrictlySorted(values) {
8816
- return values.every(
8817
- (value, index) => index === 0 || (0, import_tool_contract10.comparePublicationUnicodeCodePoints)(values[index - 1], value) < 0
9328
+ async function runPublishCommand(options, writer, cwd, runtime, messages = DEFAULT_PUBLISH_MESSAGES, scopeRegistrationMessages = DEFAULT_SCOPE_REGISTRATION_MESSAGES2, schemaReviewMessages = DEFAULT_SCHEMA_REVIEW_MESSAGES) {
9329
+ const normalized = normalizePublishOptions(options, messages);
9330
+ const project = loadPublicationProject(runtime.loadProject, cwd, messages);
9331
+ const projectId = project.manifest.project_id;
9332
+ const connectorId = normalized.connectorId ?? project.manifest.connector_id;
9333
+ if (connectorId === void 0) {
9334
+ throw new PublishCommandError(
9335
+ "AP_INPUT_INVALID",
9336
+ "publication_connector_required",
9337
+ messages.optionRequires("publish", "--connector UUID")
9338
+ );
9339
+ }
9340
+ assertManifestProject(project, normalized.projectId, messages);
9341
+ const { planRequest, expectedToolNames } = buildLocalPublicationCandidate(
9342
+ project,
9343
+ connectorId,
9344
+ messages
8818
9345
  );
8819
- }
8820
- function parseWarnings(value, messages) {
9346
+ const client = runtime.createClient(normalized.profile);
9347
+ let rawPlan;
8821
9348
  try {
8822
- return (0, import_tool_contract10.parsePublicationWarningsDto)(value);
8823
- } catch {
8824
- throw responseInvalid("publication_warnings_invalid", messages);
9349
+ rawPlan = await client.planPublication(projectId, planRequest, REVIEW_PROFILE_REQUEST);
9350
+ } catch (error) {
9351
+ throw remoteError(error, "plan", messages, schemaReviewMessages);
8825
9352
  }
8826
- }
8827
- function parsePlan(value, connectorId, candidateCommitment, expectedToolNames, messages) {
8828
- assertCanonicalResponseSize(value, "publication_plan_too_large", messages);
8829
- const plan = asRecord4(value);
8830
- 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(
8831
- (reason) => typeof reason === "string" && BLOCKED_REASONS.has(reason)
8832
- ) || !isStrictlySorted(plan.blockedReasons) || plan.applyAllowed !== (plan.blockedReasons.length === 0)) {
8833
- throw responseInvalid("publication_plan_invalid", messages);
9353
+ const negotiated = negotiateReviewProfile(rawPlan, messages, schemaReviewMessages);
9354
+ const session = negotiated.session;
9355
+ const plan = parsePlan(
9356
+ negotiated.body,
9357
+ connectorId,
9358
+ planRequest.candidateCommitment,
9359
+ expectedToolNames,
9360
+ session.profile,
9361
+ messages
9362
+ );
9363
+ writePlan(writer, plan);
9364
+ writeSchemaReviewSummary(writer, plan, schemaReviewMessages);
9365
+ if (session.kind === "legacy" && plan.blockedReasons.includes("opaque_change") && candidateNeedsReviewProfile2(planRequest.candidateContract)) {
9366
+ interactive(writer, schemaReviewMessages.adminApiUpdatePending);
8834
9367
  }
8835
- const blockedReasons = plan.blockedReasons;
8836
- let safeDiff;
8837
- try {
8838
- safeDiff = (0, import_tool_contract10.parsePublicationSafeDiffDto)({
8839
- tools: plan.tools,
8840
- retainedTools: plan.retainedTools,
8841
- warnings: plan.warnings
8842
- });
8843
- } catch {
8844
- throw responseInvalid("publication_safe_diff_invalid", messages);
9368
+ if (plan.blockedReasons.includes("connector_mismatch")) {
9369
+ interactive(writer, messages.connectorMismatchRemediation);
8845
9370
  }
8846
- const tools = safeDiff.tools;
8847
- const toolNames = tools.map((tool) => tool.toolName);
8848
- if (!isStrictlySorted(toolNames) || JSON.stringify(toolNames) !== JSON.stringify(expectedToolNames)) {
8849
- throw responseInvalid("publication_plan_tools_order_invalid", messages);
9371
+ if (plan.blockedReasons.includes("oauth_scope_registry_missing") || plan.blockedReasons.includes("oauth_scope_registry_risk_insufficient")) {
9372
+ interactive(
9373
+ writer,
9374
+ planRequest.templateProvenance ? scopeRegistrationMessages.publishTemplateRemediation(projectId) : scopeRegistrationMessages.publishRemediation(connectorId)
9375
+ );
8850
9376
  }
8851
- const warnings = safeDiff.warnings;
8852
- const expectedPlanCommitment = (0, import_tool_contract10.publicationCommitment)("plan", {
8853
- candidateCommitment,
8854
- baseCommitment: plan.baseCommitment,
8855
- connectorId,
8856
- connectorRevision: plan.connectorRevision,
8857
- connectorCommitment: plan.connectorCommitment,
8858
- policyCommitment: plan.policyCommitment,
8859
- environment: "production",
8860
- safeDiff
8861
- });
8862
- if (plan.planCommitment !== expectedPlanCommitment) {
9377
+ if (normalized.mode === "dry-run") return;
9378
+ if (!plan.applyAllowed) {
8863
9379
  throw new PublishCommandError(
8864
- "AP_CONFLICT",
8865
- "publication_plan_commitment_mismatch",
8866
- messages.failure("publication_plan_commitment_mismatch")
9380
+ "AP_POLICY_DENIED",
9381
+ "publication_plan_blocked",
9382
+ messages.planBlocked(plan.blockedReasons)
8867
9383
  );
8868
9384
  }
8869
- const toolBlockedReasons = new Set(tools.flatMap((tool) => tool.blockedReasons));
8870
- if (tools.some((tool) => !tool.gate.ok) && plan.applyAllowed || tools.some((tool) => tool.opaqueChanged) && (plan.applyAllowed || !blockedReasons.includes("opaque_change")) || TOOL_BLOCKED_REASONS.some(
8871
- (reason) => (
8872
- // connector_mismatchはtool単位(既存toolの別connector束縛)に加え、candidateの
8873
- // upstream.auth.modeとconnector方式の不一致としてtop-levelだけにも出る (#456 / #724)。
8874
- reason === "connector_mismatch" ? toolBlockedReasons.has(reason) && !blockedReasons.includes(reason) : blockedReasons.includes(reason) !== toolBlockedReasons.has(reason)
8875
- )
8876
- )) {
8877
- throw responseInvalid("publication_plan_gate_inconsistent", messages);
8878
- }
8879
- return {
8880
- requestId: plan.requestId,
8881
- environment: "production",
8882
- connectorId,
8883
- connectorRevision: plan.connectorRevision,
8884
- connectorCommitment: plan.connectorCommitment,
8885
- policyCommitment: plan.policyCommitment,
8886
- candidateCommitment,
8887
- baseCommitment: plan.baseCommitment,
9385
+ const idempotencyKey = assertIdempotencyKey2(runtime.randomUuid(), messages);
9386
+ const applyRequest = (confirmation) => ({
9387
+ ...planRequest,
8888
9388
  planCommitment: plan.planCommitment,
8889
- tools,
8890
- retainedTools: safeDiff.retainedTools,
8891
- warnings,
8892
- applyAllowed: plan.applyAllowed,
8893
- blockedReasons
8894
- };
9389
+ confirmation
9390
+ });
9391
+ const initialApplyRequest = freezeJson(applyRequest(null));
9392
+ const initial = await sendInitialApplyWithSameAnchorRetry({
9393
+ client,
9394
+ projectId,
9395
+ idempotencyKey,
9396
+ body: initialApplyRequest,
9397
+ plan,
9398
+ session,
9399
+ messages,
9400
+ schemaReviewMessages
9401
+ });
9402
+ let details;
9403
+ if (initial.kind === "response") {
9404
+ writeResult(writer, initial.result);
9405
+ return;
9406
+ } else {
9407
+ if (plan.tools.every((tool) => !tool.changed)) {
9408
+ throw responseInvalid("publication_noop_confirmation_invalid", messages);
9409
+ }
9410
+ details = initial.details;
9411
+ }
9412
+ writeSafeJson(writer, { phase: "confirmation_required", ...details });
9413
+ const decision = await pollPublication(
9414
+ client,
9415
+ projectId,
9416
+ details,
9417
+ plan,
9418
+ writer,
9419
+ runtime,
9420
+ "await-approval",
9421
+ messages
9422
+ );
9423
+ if (decision.kind === "consumed") {
9424
+ writeResult(writer, decision.result);
9425
+ return;
9426
+ }
9427
+ try {
9428
+ const result = parsePublicationResult(
9429
+ await applyPublicationWithProfile(
9430
+ client,
9431
+ projectId,
9432
+ idempotencyKey,
9433
+ applyRequest(decision.confirmation),
9434
+ session
9435
+ ),
9436
+ plan,
9437
+ messages,
9438
+ details.publicationId
9439
+ );
9440
+ writeResult(writer, result);
9441
+ return;
9442
+ } catch (error) {
9443
+ if (error instanceof PublishCommandError && error.code === "AP_RESPONSE_INVALID") {
9444
+ } else if (!approvedApplyResultMayBeUnknown(error)) {
9445
+ throw remoteError(error, "approved_apply", messages, schemaReviewMessages);
9446
+ }
9447
+ }
9448
+ const recovered = await pollPublication(
9449
+ client,
9450
+ projectId,
9451
+ details,
9452
+ plan,
9453
+ writer,
9454
+ runtime,
9455
+ "recover-result",
9456
+ messages,
9457
+ decision.expiresAt
9458
+ );
9459
+ if (recovered.kind !== "consumed") {
9460
+ throw new PublishCommandError(
9461
+ "AP_RESULT_UNKNOWN",
9462
+ "publication_result_unknown",
9463
+ messages.resultUnknown
9464
+ );
9465
+ }
9466
+ writeResult(writer, recovered.result);
8895
9467
  }
8896
- function sameWarnings(left, right) {
8897
- return JSON.stringify(left) === JSON.stringify(right);
9468
+ 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) {
9469
+ 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) => {
9470
+ await runPublishCommand(
9471
+ commandOptions,
9472
+ writer,
9473
+ cwd(),
9474
+ runtime,
9475
+ messages,
9476
+ scopeRegistrationMessages,
9477
+ schemaReviewMessages
9478
+ );
9479
+ });
8898
9480
  }
8899
- function parseToolResults(value, messages) {
8900
- if (!Array.isArray(value)) {
8901
- throw responseInvalid("publication_result_tools_invalid", messages);
9481
+
9482
+ // src/commands/oauth.ts
9483
+ function isUrl(value) {
9484
+ if (typeof value !== "string") {
9485
+ return false;
8902
9486
  }
8903
- const tools = value.map((candidate) => {
8904
- const tool = asRecord4(candidate);
8905
- if (!tool || !hasExactKeys3(tool, ["toolName", "operation", "toolId", "versionId", "version"]) || !(0, import_tool_contract10.isSafeToolName)(tool.toolName) || tool.operation !== "create" && tool.operation !== "update" || !isCanonicalUuid(tool.toolId) || !isCanonicalUuid(tool.versionId) || typeof tool.version !== "number" || !Number.isSafeInteger(tool.version) || tool.version < 1) {
8906
- throw responseInvalid("publication_result_tool_invalid", messages);
8907
- }
8908
- const operation = tool.operation;
9487
+ try {
9488
+ const u = new URL(value);
9489
+ return u.protocol === "http:" || u.protocol === "https:";
9490
+ } catch {
9491
+ return false;
9492
+ }
9493
+ }
9494
+ function field(meta, snake, camel) {
9495
+ return snake in meta ? meta[snake] : meta[camel];
9496
+ }
9497
+ function validateOAuthMetadata(meta, locale = import_localization10.DEFAULT_LOCALE) {
9498
+ const messages = import_localization10.CLI_MESSAGES[locale].oauth;
9499
+ const results = [];
9500
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
8909
9501
  return {
8910
- toolName: tool.toolName,
8911
- operation,
8912
- toolId: tool.toolId,
8913
- versionId: tool.versionId,
8914
- version: tool.version
9502
+ ok: false,
9503
+ results: [
9504
+ {
9505
+ id: "metadata",
9506
+ label: "metadata",
9507
+ status: "fail",
9508
+ detail: messages.metadataNotObject
9509
+ }
9510
+ ]
8915
9511
  };
9512
+ }
9513
+ const m = meta;
9514
+ const urlFields = [
9515
+ ["issuer", "issuer", "issuer"],
9516
+ ["authorization_endpoint", "authorization_endpoint", "authorizationEndpoint"],
9517
+ ["token_endpoint", "token_endpoint", "tokenEndpoint"],
9518
+ ["jwks_uri", "jwks_uri", "jwksUri"]
9519
+ ];
9520
+ for (const [id, snake, camel] of urlFields) {
9521
+ const value = field(m, snake, camel);
9522
+ const ok = isUrl(value);
9523
+ results.push({
9524
+ id,
9525
+ label: id,
9526
+ status: ok ? "pass" : "fail",
9527
+ detail: ok ? messages.urlOk : messages.invalidUrl(id)
9528
+ });
9529
+ }
9530
+ const responseTypes = field(m, "response_types_supported", "responseTypesSupported");
9531
+ results.push({
9532
+ id: "response_types_supported",
9533
+ label: "response_types_supported",
9534
+ status: Array.isArray(responseTypes) && responseTypes.length > 0 ? "pass" : "fail",
9535
+ detail: Array.isArray(responseTypes) ? messages.present : messages.arrayMissing
9536
+ });
9537
+ const scopes = field(m, "scopes_supported", "scopesSupported");
9538
+ results.push({
9539
+ id: "scopes_supported",
9540
+ label: "scopes_supported",
9541
+ // 推奨項目。欠落は致命ではないため pending 扱いで明示する。
9542
+ status: Array.isArray(scopes) && scopes.length > 0 ? "pass" : "pending",
9543
+ detail: Array.isArray(scopes) ? messages.present : messages.scopesMissing
8916
9544
  });
8917
- if (!isStrictlySorted(tools.map((tool) => tool.toolName))) {
8918
- throw responseInvalid("publication_result_tools_order_invalid", messages);
8919
- }
8920
- return tools;
9545
+ return { ok: results.every((r) => r.status !== "fail"), results };
8921
9546
  }
8922
- function parsePublicationResult(value, plan, messages, expectedPublicationId) {
8923
- assertCanonicalResponseSize(value, "publication_apply_result_too_large", messages);
8924
- const result = asRecord4(value);
8925
- if (!result || !hasExactKeys3(result, APPLY_RESULT_KEYS) || !isCanonicalUuid(result.requestId) || result.state !== "noop" && result.state !== "consumed") {
8926
- throw responseInvalid("publication_apply_result_invalid", messages);
9547
+ function buildInitTemplate(provider) {
9548
+ return {
9549
+ provider,
9550
+ issuer: "https://auth.example.com",
9551
+ authorizationEndpoint: "https://auth.example.com/oauth/authorize",
9552
+ tokenEndpoint: "https://auth.example.com/oauth/token",
9553
+ jwksUri: "https://auth.example.com/.well-known/jwks.json",
9554
+ clientId: "<client id>",
9555
+ // secret は config に直書きせず env 参照にする (No secret in repo / stdout)。
9556
+ clientSecretEnv: "ANDPIPE_OAUTH_CLIENT_SECRET",
9557
+ redirectUri: "https://<your-andpipe-gateway>/oauth/callback",
9558
+ scopes: ["openid", "profile"]
9559
+ };
9560
+ }
9561
+ var SCOPE_REGISTER_OPERATION = "andpipe oauth scopes register";
9562
+ 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;
9563
+ var RESOURCE_NOT_FOUND_CODES = /* @__PURE__ */ new Set([
9564
+ "AP_NOT_FOUND",
9565
+ "AP_TOOL_NOT_FOUND",
9566
+ "AP_TOOL_VERSION_NOT_FOUND"
9567
+ ]);
9568
+ function createOAuthScopeRegisterRuntime(createClient = (profile) => createAdminApiClient({ profile })) {
9569
+ return { createClient, loadProject: loadDevProject, randomUuid: () => (0, import_node_crypto13.randomUUID)() };
9570
+ }
9571
+ var OAuthScopeRegistrationCommandError = class extends Error {
9572
+ constructor(code, reason, message, status) {
9573
+ super(message);
9574
+ this.code = code;
9575
+ this.reason = reason;
9576
+ this.status = status;
9577
+ this.name = "OAuthScopeRegistrationCommandError";
8927
9578
  }
8928
- const warnings = parseWarnings(result.warnings, messages);
8929
- if (!sameWarnings(warnings, plan.warnings)) {
8930
- throw responseInvalid("publication_apply_warning_mismatch", messages);
9579
+ code;
9580
+ reason;
9581
+ status;
9582
+ };
9583
+ function parseDraftOption(value, messages) {
9584
+ const parts = value.split(":");
9585
+ const toolId = parts[0]?.toLowerCase() ?? "";
9586
+ const versionId = parts[1]?.toLowerCase() ?? "";
9587
+ if (parts.length !== 2 || !RFC_UUID_RE.test(toolId) || !RFC_UUID_RE.test(versionId)) {
9588
+ throw new UsageError(messages.draftFormat);
9589
+ }
9590
+ return { toolId, versionId };
9591
+ }
9592
+ function normalizeOAuthScopeRegisterOptions(options, locale = import_localization10.DEFAULT_LOCALE) {
9593
+ const messages = import_localization10.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9594
+ const cliMessages = import_localization10.CLI_MESSAGES[locale];
9595
+ const apply = options.apply === true;
9596
+ if (options.yes === true && !apply) throw new UsageError(messages.yesRequiresApply);
9597
+ if (apply && options.yes !== true) {
9598
+ throw new ConfirmationRequiredError(
9599
+ SCOPE_REGISTER_OPERATION,
9600
+ cliMessages.common.confirmationRequiredMessage(SCOPE_REGISTER_OPERATION)
9601
+ );
8931
9602
  }
8932
- const tools = parseToolResults(result.tools, messages);
8933
- const changedToolNames = plan.tools.filter((tool) => tool.changed).map((tool) => tool.toolName);
8934
- if (result.state === "noop") {
8935
- if (result.publicationId !== null || tools.length !== 0 || changedToolNames.length !== 0) {
8936
- throw responseInvalid("publication_noop_invalid", messages);
8937
- }
9603
+ const profile = options.profile ?? DEFAULT_PROFILE_NAME;
9604
+ const rawDrafts = options.draft ?? [];
9605
+ if (rawDrafts.length === 0) {
8938
9606
  return {
8939
- requestId: result.requestId,
8940
- publicationId: null,
8941
- state: "noop",
8942
- tools,
8943
- warnings
9607
+ kind: "publication_candidate",
9608
+ ...options.project === void 0 ? {} : {
9609
+ projectId: canonicalUuidOption(options.project, "--project", cliMessages.publish)
9610
+ },
9611
+ ...options.connector === void 0 ? {} : {
9612
+ connectorId: canonicalUuidOption(options.connector, "--connector", cliMessages.publish)
9613
+ },
9614
+ apply,
9615
+ profile
8944
9616
  };
8945
9617
  }
8946
- 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(
8947
- (tool) => plan.tools.find((planned) => planned.toolName === tool.toolName)?.operation !== tool.operation
8948
- )) {
8949
- throw responseInvalid("publication_consumed_result_invalid", messages);
9618
+ if (options.connector !== void 0) throw new UsageError(messages.draftConnectorConflict);
9619
+ if (options.project === void 0) throw new UsageError(messages.draftRequiresProject);
9620
+ const projectId = canonicalUuidOption(options.project, "--project", cliMessages.publish);
9621
+ const drafts = rawDrafts.map((value) => parseDraftOption(value, messages)).sort((left, right) => (0, import_tool_contract10.comparePublicationUnicodeCodePoints)(left.toolId, right.toolId));
9622
+ if (drafts.length > import_tool_contract10.OAUTH_SCOPE_REGISTRATION_MAX_DRAFTS || drafts.some((draft, index) => index > 0 && drafts[index - 1]?.toolId === draft.toolId)) {
9623
+ throw new UsageError(messages.draftInvalid);
8950
9624
  }
8951
- return {
8952
- requestId: result.requestId,
8953
- publicationId: result.publicationId,
8954
- state: "consumed",
8955
- tools,
8956
- warnings
8957
- };
9625
+ return { kind: "saved_drafts", projectId, drafts, apply, profile };
8958
9626
  }
8959
- function parseConfirmation(value, messages) {
8960
- if (value === null) return null;
8961
- const confirmation = asRecord4(value);
8962
- if (!confirmation || !hasExactKeys3(confirmation, ["confirmationId", "signature", "confirmed"]) || !isCanonicalUuid(confirmation.confirmationId) || typeof confirmation.signature !== "string" || !import_tool_contract10.PUBLICATION_CONFIRMATION_SIGNATURE_RE.test(confirmation.signature) || confirmation.confirmed !== true) {
8963
- throw responseInvalid("publication_confirmation_invalid", messages);
9627
+ function riskLabel(messages, level) {
9628
+ return messages.riskLabels[level];
9629
+ }
9630
+ function blockedGuidance(cli, reason) {
9631
+ switch (reason) {
9632
+ case "scope_in_use_risk_upgrade_forbidden":
9633
+ return cli.blocked.scopeInUse;
9634
+ case "template_scope_requires_sync":
9635
+ return cli.blocked.templateScope;
9636
+ case "reserved_scope_name":
9637
+ return cli.blocked.reservedName;
8964
9638
  }
8965
- return {
8966
- confirmationId: confirmation.confirmationId,
8967
- signature: confirmation.signature,
8968
- confirmed: true
8969
- };
8970
9639
  }
8971
- function parseStatus(value, publicationId, plan, messages) {
8972
- assertCanonicalResponseSize(value, "publication_status_too_large", messages);
8973
- const status = asRecord4(value);
8974
- 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)) {
8975
- throw responseInvalid("publication_status_invalid", messages);
9640
+ function writeRegistrationSummary(writer, response, applyRequested, messages) {
9641
+ const cli = messages.cli;
9642
+ const name = (value) => terminalSafeText(value);
9643
+ const lines = [response.mode === "preview" ? cli.previewHeading : cli.appliedHeading];
9644
+ for (const row of response.added) {
9645
+ lines.push(` ${cli.addedLabel} ${name(row.name)} ${riskLabel(messages, row.riskLevel)}`);
8976
9646
  }
8977
- const confirmation = parseConfirmation(status.confirmation, messages);
8978
- const result = status.result === null ? null : parsePublicationResult(status.result, plan, messages, publicationId);
8979
- const durableState = status.durableState;
8980
- const effectiveState = status.effectiveState;
8981
- const isPending = durableState === "pending";
8982
- const isApproved = durableState === "approved";
8983
- const isTerminal = durableState === "rejected" || durableState === "expired" || durableState === "consumed";
8984
- 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)) {
8985
- throw responseInvalid("publication_status_inconsistent", messages);
9647
+ for (const row of response.updated) {
9648
+ lines.push(
9649
+ ` ${cli.updatedLabel} ${name(row.name)} ${riskLabel(messages, row.fromRisk)} \u2192 ${riskLabel(messages, row.toRisk)}`
9650
+ );
8986
9651
  }
8987
- return {
8988
- requestId: status.requestId,
8989
- publicationId,
8990
- durableState,
8991
- effectiveState,
8992
- expiresAt: status.expiresAt,
8993
- confirmation,
8994
- result
8995
- };
8996
- }
8997
- function typedCode2(error) {
8998
- if (error === null || typeof error !== "object") return void 0;
8999
- const code = error.code;
9000
- return typeof code === "string" && SAFE_AP_CODE_RE2.test(code) ? code : void 0;
9001
- }
9002
- function typedStatus2(error) {
9003
- if (error === null || typeof error !== "object") return void 0;
9004
- const status = error.status;
9005
- return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599 ? status : void 0;
9006
- }
9007
- function remoteError(error, phase, messages) {
9008
- const code = typedCode2(error) ?? "AP_NETWORK_ERROR";
9009
- return new PublishCommandError(
9010
- code,
9011
- `${phase}_failed`,
9012
- messages.remoteFailure(phase, code),
9013
- typedStatus2(error)
9014
- );
9015
- }
9016
- function parseConfirmationRequired(error, projectId, messages) {
9017
- if (typedCode2(error) !== "AP_CONFIRMATION_REQUIRED") return null;
9018
- if (typedStatus2(error) !== 409 || error === null || typeof error !== "object") {
9019
- throw responseInvalid("publication_confirmation_required_error_invalid", messages);
9652
+ for (const existing of response.existing) {
9653
+ lines.push(` ${cli.existingLabel} ${name(existing)}`);
9020
9654
  }
9021
- const details = asRecord4(error.confirmationRequired);
9022
- if (!details || !hasExactKeys3(details, [
9023
- "requestId",
9024
- "publicationId",
9025
- "verificationUri",
9026
- "expiresIn",
9027
- "pollInterval"
9028
- ]) || !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) {
9029
- throw responseInvalid("publication_confirmation_required_details_invalid", messages);
9655
+ for (const row of response.blocked) {
9656
+ const from = row.fromRisk === null ? "" : `${riskLabel(messages, row.fromRisk)} \u2192 `;
9657
+ lines.push(
9658
+ ` ${cli.blockedLabel} ${name(row.name)} ${from}${riskLabel(messages, row.toRisk)}`
9659
+ );
9660
+ lines.push(` ${blockedGuidance(cli, row.reason)}`);
9661
+ }
9662
+ if (response.unchanged && response.blocked.length === 0) lines.push(cli.nothingToRegister);
9663
+ lines.push(cli.separationNotice);
9664
+ if (response.mode === "preview" && !applyRequested && response.applyAllowed && !response.unchanged) {
9665
+ lines.push(cli.applyHint);
9666
+ }
9667
+ if (response.mode === "applied") lines.push(cli.nextPublish);
9668
+ for (const line of lines) interactive(writer, line);
9669
+ }
9670
+ function writeRegistrationJson(writer, response) {
9671
+ json(writer, terminalSafeValue(response));
9672
+ }
9673
+ function isDetailsAbsentPolicyDenial(error) {
9674
+ return error.status === 403 && error.code === "AP_POLICY_DENIED" && error.detailsAbsent;
9675
+ }
9676
+ function isUnsupportedAdminApi(error, projectAccessible) {
9677
+ if (error.status === 404) return !RESOURCE_NOT_FOUND_CODES.has(error.code);
9678
+ return isDetailsAbsentPolicyDenial(error) && projectAccessible === true;
9679
+ }
9680
+ function registrationFailure(error, phase, messages, projectAccessible) {
9681
+ if (!(error instanceof AdminApiClientError)) return error;
9682
+ const stop = (reason2, message) => new OAuthScopeRegistrationCommandError(error.code, reason2, message, error.status);
9683
+ if (phase === "preview" && isUnsupportedAdminApi(error, projectAccessible)) {
9684
+ return stop("oauth_scope_registration_unsupported", messages.unsupportedAdminApi);
9685
+ }
9686
+ if (phase === "preview" && (isDetailsAbsentPolicyDenial(error) && projectAccessible === false || error.code === "AP_INVALID_SCOPE")) {
9687
+ return stop("oauth_scope_registration_project_access_denied", messages.projectAccessDenied);
9688
+ }
9689
+ const reason = error.scopeRegistrationReason;
9690
+ switch (reason) {
9691
+ case "oauth_scope_registration_source_stale":
9692
+ case "oauth_scope_registration_registry_changed":
9693
+ case "oauth_scope_registration_plan_stale":
9694
+ return stop(reason, messages.stale);
9695
+ case "scope_registration_publish_gate_failed":
9696
+ return error.publishGateToolNames === void 0 ? error : stop(
9697
+ reason,
9698
+ messages.publishGateFailed(
9699
+ error.publishGateToolNames.map((name) => terminalSafeText(name))
9700
+ )
9701
+ );
9702
+ case "saved_draft_not_latest":
9703
+ return stop(reason, messages.draftNotLatest);
9704
+ case "saved_drafts_mixed_connectors":
9705
+ return stop(reason, messages.draftsMixedConnectors);
9706
+ case "saved_draft_fields_inconsistent":
9707
+ return stop(reason, messages.draftFieldsInconsistent);
9708
+ case "marketplace_managed_tool":
9709
+ return stop(reason, messages.marketplaceManaged);
9710
+ case "publication_candidate_commitment_mismatch":
9711
+ return stop(reason, messages.candidateMismatch);
9712
+ case "publication_candidate_too_large":
9713
+ return stop(reason, messages.candidateTooLarge);
9714
+ case "oauth_scope_registration_blocked":
9715
+ return stop(reason, messages.blockedNotApplied);
9716
+ default:
9717
+ break;
9718
+ }
9719
+ if (phase === "apply" && error.code === "AP_RESULT_UNKNOWN") {
9720
+ return stop("oauth_scope_registration_result_unknown", messages.resultUnknown);
9721
+ }
9722
+ if (phase === "apply" && reason === void 0 && (error.code === "AP_POLICY_DENIED" || error.code === "AP_INVALID_SCOPE")) {
9723
+ return stop("oauth_scope_registration_write_role_required", messages.writeRoleRequired);
9724
+ }
9725
+ return error;
9726
+ }
9727
+ async function projectAccessibility(client, projectId, error) {
9728
+ if (!(error instanceof AdminApiClientError) || !isDetailsAbsentPolicyDenial(error)) {
9729
+ return void 0;
9030
9730
  }
9031
- let uri;
9032
9731
  try {
9033
- uri = new URL(details.verificationUri);
9732
+ await client.getOAuthSetup(projectId);
9733
+ return true;
9034
9734
  } catch {
9035
- throw responseInvalid("publication_verification_uri_invalid", messages);
9036
- }
9037
- const expectedPath = `/projects/${projectId}/tools/publications/${details.publicationId}`;
9038
- if (uri.origin !== "https://admin.andpipe.com" || uri.pathname !== expectedPath || uri.username !== "" || uri.password !== "" || uri.search !== "" || uri.hash !== "" || uri.toString() !== details.verificationUri) {
9039
- throw responseInvalid("publication_verification_uri_invalid", messages);
9040
- }
9041
- return {
9042
- requestId: details.requestId,
9043
- publicationId: details.publicationId,
9044
- verificationUri: details.verificationUri,
9045
- expiresIn: 600,
9046
- pollInterval: details.pollInterval
9047
- };
9048
- }
9049
- function approvedApplyResultMayBeUnknown(error) {
9050
- const status = typedStatus2(error);
9051
- if (status !== void 0 && status >= 400 && status < 500) return false;
9052
- const code = typedCode2(error);
9053
- return code === void 0 || !DEFINITIVE_APPLY_ERROR_CODES.has(code);
9054
- }
9055
- function initialApplyResultMayBeUnknown(error) {
9056
- const status = typedStatus2(error);
9057
- if (status !== void 0 && status >= 400 && status < 500) return false;
9058
- const code = typedCode2(error);
9059
- if (status === void 0 && code !== void 0 && DEFINITIVE_APPLY_ERROR_CODES.has(code)) {
9060
9735
  return false;
9061
9736
  }
9062
- return true;
9063
- }
9064
- function writeSafeJson(writer, value) {
9065
- json(writer, terminalSafeValue(value));
9066
- }
9067
- function writePlan(writer, plan) {
9068
- writeSafeJson(writer, { phase: "plan", ...plan });
9069
9737
  }
9070
- function writeResult(writer, result) {
9071
- writeSafeJson(writer, { phase: "result", ...result });
9072
- }
9073
- function freezeJson(value) {
9074
- if (Array.isArray(value)) {
9075
- for (const item of value) freezeJson(item);
9076
- return Object.freeze(value);
9077
- }
9078
- if (value !== null && typeof value === "object") {
9079
- for (const item of Object.values(value)) freezeJson(item);
9080
- return Object.freeze(value);
9738
+ function localCandidateSource(normalized, cwd, runtime, locale) {
9739
+ const messages = import_localization10.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9740
+ const publishMessages = import_localization10.CLI_MESSAGES[locale].publish;
9741
+ const project = loadPublicationProject(runtime.loadProject, cwd, publishMessages);
9742
+ const projectId = assertManifestProject(project, normalized.projectId, publishMessages);
9743
+ const connectorId = normalized.connectorId ?? project.manifest.connector_id;
9744
+ if (connectorId === void 0) throw new UsageError(messages.connectorRequired);
9745
+ let candidate;
9746
+ try {
9747
+ candidate = buildLocalPublicationCandidate(project, connectorId, publishMessages);
9748
+ } catch (error) {
9749
+ if (error instanceof import_tool_contract10.PublicationCanonicalizationError && error.reason === "publication_value_too_large") {
9750
+ throw new OAuthScopeRegistrationCommandError(
9751
+ "AP_INPUT_INVALID",
9752
+ "publication_candidate_too_large",
9753
+ messages.candidateTooLarge
9754
+ );
9755
+ }
9756
+ throw error;
9081
9757
  }
9082
- return value;
9083
- }
9084
- function prepareCandidate(project) {
9085
- const canonical = (0, import_tool_contract10.assertCanonicalPublicationSize)(project.contract.root);
9086
- const candidateContract = freezeJson(JSON.parse(canonical));
9087
9758
  return {
9088
- candidateContract,
9089
- candidateCommitment: (0, import_tool_contract10.publicationCommitment)("candidate", candidateContract)
9759
+ projectId,
9760
+ source: {
9761
+ kind: "publication_candidate",
9762
+ connectorId,
9763
+ candidateContract: candidate.planRequest.candidateContract,
9764
+ candidateCommitment: candidate.planRequest.candidateCommitment
9765
+ },
9766
+ expectedToolNames: candidate.expectedToolNames
9090
9767
  };
9091
9768
  }
9092
- function assertIdempotencyKey2(value, messages) {
9093
- if (!UUID_RE6.test(value)) {
9094
- throw new PublishCommandError(
9095
- "AP_NETWORK_ERROR",
9096
- "secure_random_invalid",
9097
- messages.failure("secure_random_invalid")
9769
+ async function runOAuthScopeRegisterCommand(options, writer, cwd, runtime, locale = import_localization10.DEFAULT_LOCALE) {
9770
+ const messages = import_localization10.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale];
9771
+ const normalized = normalizeOAuthScopeRegisterOptions(options, locale);
9772
+ const target = normalized.kind === "saved_drafts" ? {
9773
+ projectId: normalized.projectId,
9774
+ source: { kind: "saved_drafts", drafts: normalized.drafts },
9775
+ expectedToolNames: void 0
9776
+ } : localCandidateSource(normalized, cwd, runtime, locale);
9777
+ const client = runtime.createClient(normalized.profile);
9778
+ let preview;
9779
+ try {
9780
+ preview = await client.registerOAuthScopes({
9781
+ projectId: target.projectId,
9782
+ source: target.source,
9783
+ apply: false
9784
+ });
9785
+ } catch (error) {
9786
+ throw registrationFailure(
9787
+ error,
9788
+ "preview",
9789
+ messages.cli,
9790
+ await projectAccessibility(client, target.projectId, error)
9098
9791
  );
9099
9792
  }
9100
- return value;
9101
- }
9102
- async function sendInitialApplyWithSameAnchorRetry(input) {
9103
- for (let attempt = 0; attempt < INITIAL_APPLY_MAX_ATTEMPTS; attempt += 1) {
9104
- try {
9105
- const result = parsePublicationResult(
9106
- await input.client.applyPublication(input.projectId, input.idempotencyKey, input.body),
9107
- input.plan,
9108
- input.messages
9793
+ if (target.expectedToolNames !== void 0 && JSON.stringify(preview.source.tools.map((tool) => tool.toolName)) !== JSON.stringify(target.expectedToolNames)) {
9794
+ throw new OAuthScopeRegistrationCommandError(
9795
+ "AP_RESPONSE_INVALID",
9796
+ "oauth_scope_registration_tools_mismatch",
9797
+ messages.cli.responseMismatch
9798
+ );
9799
+ }
9800
+ writeRegistrationJson(writer, preview);
9801
+ writeRegistrationSummary(writer, preview, normalized.apply, messages);
9802
+ if (!preview.applyAllowed) {
9803
+ if (normalized.apply) {
9804
+ throw new OAuthScopeRegistrationCommandError(
9805
+ "AP_POLICY_DENIED",
9806
+ "oauth_scope_registration_blocked",
9807
+ messages.cli.blockedNotApplied
9109
9808
  );
9110
- if (result.state !== "noop") {
9111
- throw responseInvalid("publication_initial_apply_state_invalid", input.messages);
9112
- }
9113
- return {
9114
- kind: "response",
9115
- result
9116
- };
9117
- } catch (error) {
9118
- let malformedConfirmationAnchor = false;
9119
- let confirmationRequired = null;
9120
- try {
9121
- confirmationRequired = parseConfirmationRequired(error, input.projectId, input.messages);
9122
- } catch (parseError) {
9123
- if (typedCode2(error) !== "AP_CONFIRMATION_REQUIRED" || !(parseError instanceof PublishCommandError) || parseError.code !== "AP_RESPONSE_INVALID") {
9124
- throw parseError;
9125
- }
9126
- malformedConfirmationAnchor = true;
9127
- }
9128
- if (confirmationRequired) {
9129
- return { kind: "confirmation_required", details: confirmationRequired };
9130
- }
9131
- if (!malformedConfirmationAnchor && !initialApplyResultMayBeUnknown(error)) {
9132
- throw remoteError(error, "initial_apply", input.messages);
9133
- }
9134
- if (attempt === INITIAL_APPLY_MAX_ATTEMPTS - 1) {
9135
- throw new PublishCommandError(
9136
- "AP_RESULT_UNKNOWN",
9137
- "publication_anchor_result_unknown",
9138
- input.messages.proposalResultUnknown
9139
- );
9140
- }
9141
9809
  }
9810
+ return { ok: false };
9811
+ }
9812
+ if (!normalized.apply) return { ok: true };
9813
+ const idempotencyKey = runtime.randomUuid().toLowerCase();
9814
+ if (!RFC_UUID_RE.test(idempotencyKey)) {
9815
+ throw new OAuthScopeRegistrationCommandError(
9816
+ "AP_NETWORK_ERROR",
9817
+ "secure_random_invalid",
9818
+ import_localization10.CLI_MESSAGES[locale].publish.failure("secure_random_invalid")
9819
+ );
9142
9820
  }
9143
- throw new PublishCommandError(
9144
- "AP_RESULT_UNKNOWN",
9145
- "publication_anchor_result_unknown",
9146
- input.messages.proposalResultUnknown
9147
- );
9148
- }
9149
- function confirmationStopped(code, reason, messages) {
9150
- return new PublishCommandError(code, reason, messages.confirmationStopped(reason));
9821
+ let applied;
9822
+ try {
9823
+ applied = await client.registerOAuthScopes({
9824
+ projectId: target.projectId,
9825
+ source: target.source,
9826
+ apply: true,
9827
+ sourceCommitment: preview.sourceCommitment,
9828
+ baseRegistryCommitment: preview.baseRegistryCommitment,
9829
+ planCommitment: preview.planCommitment,
9830
+ idempotencyKey
9831
+ });
9832
+ } catch (error) {
9833
+ throw registrationFailure(error, "apply", messages.cli);
9834
+ }
9835
+ writeRegistrationJson(writer, applied);
9836
+ writeRegistrationSummary(writer, applied, true, messages);
9837
+ return { ok: true };
9151
9838
  }
9152
- function pollFailureIsDefinitive(error) {
9153
- const status = typedStatus2(error);
9154
- if (status !== void 0 && status >= 400 && status < 500) return true;
9155
- const code = typedCode2(error);
9156
- return code === "AP_RESPONSE_INVALID" || code === "AP_OUTPUT_INVALID" || code !== void 0 && DEFINITIVE_APPLY_ERROR_CODES.has(code);
9839
+ function upstreamOAuthWizardUrl(profile, projectId, connectorId) {
9840
+ const record = getProfile(profile);
9841
+ if (!record)
9842
+ throw new UsageError(`\u8A8D\u8A3Cprofile ${profile} \u304C\u3042\u308A\u307E\u305B\u3093\u3002andpipe login\u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044`);
9843
+ const url = new URL(`/projects/${projectId}/oauth`, new URL(record.verificationUriBase).origin);
9844
+ url.searchParams.set("connector", connectorId);
9845
+ return url.toString();
9157
9846
  }
9158
- async function sleepForPoll(runtime, milliseconds, mode, messages) {
9847
+ async function loadOAuthMetadata(opts, locale) {
9848
+ const messages = import_localization10.CLI_MESSAGES[locale];
9849
+ if (opts.file && opts.issuer) {
9850
+ throw new UsageError("--file \u3068 --issuer \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");
9851
+ }
9852
+ if (opts.issuer) {
9853
+ return fetchOAuthMetadata(opts.issuer);
9854
+ }
9855
+ if (!opts.file) {
9856
+ throw new UsageError(messages.oauth.fileRequired);
9857
+ }
9159
9858
  try {
9160
- await runtime.sleep(milliseconds);
9161
- } catch {
9162
- throw new PublishCommandError(
9163
- mode === "recover-result" ? "AP_RESULT_UNKNOWN" : "AP_NETWORK_ERROR",
9164
- "publication_poll_sleep_failed",
9165
- messages.pollingUnavailable
9166
- );
9859
+ return JSON.parse((0, import_node_fs11.readFileSync)(opts.file, "utf8"));
9860
+ } catch (error) {
9861
+ throw new UsageError(messages.oauth.metadataReadFailed(error.message));
9167
9862
  }
9168
9863
  }
9169
- async function pollPublication(client, projectId, details, plan, writer, runtime, mode, messages, knownExpiresAt) {
9170
- const startedAt = runtime.monotonicNow();
9171
- let deadline = startedAt + details.expiresIn * 1e3;
9172
- let expiresAt = knownExpiresAt;
9173
- if (knownExpiresAt !== void 0) {
9174
- deadline = Math.min(
9175
- deadline,
9176
- startedAt + Math.max(0, Date.parse(knownExpiresAt) - runtime.wallNow())
9177
- );
9864
+ async function runOAuthMetadataValidate(opts, writer, locale) {
9865
+ const messages = import_localization10.CLI_MESSAGES[locale];
9866
+ const parsed = await loadOAuthMetadata(opts, locale);
9867
+ const report = validateOAuthMetadata(parsed, locale);
9868
+ json(writer, report.results);
9869
+ if (!report.ok) {
9870
+ process.exitCode = 1;
9871
+ info(writer, messages.oauth.metadataFailed);
9872
+ } else {
9873
+ info(writer, messages.oauth.metadataOk);
9178
9874
  }
9179
- const maxAttempts = Math.ceil(details.expiresIn / details.pollInterval) + 2;
9180
- for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
9181
- let rawStatus;
9182
- try {
9183
- rawStatus = await client.getPublication(projectId, details.publicationId);
9184
- } catch (error) {
9185
- if (pollFailureIsDefinitive(error)) {
9186
- throw remoteError(error, mode === "recover-result" ? "result_recovery" : "poll", messages);
9187
- }
9188
- const remainingMilliseconds2 = Math.max(0, deadline - runtime.monotonicNow());
9189
- if (remainingMilliseconds2 <= 0 || attempt === maxAttempts - 1) {
9190
- throw new PublishCommandError(
9191
- mode === "recover-result" ? "AP_RESULT_UNKNOWN" : "AP_NETWORK_ERROR",
9192
- "publication_poll_unavailable",
9193
- messages.pollingUnavailable
9194
- );
9875
+ }
9876
+ function registerOauth(program, writer, locale = import_localization10.DEFAULT_LOCALE, dependencies = {}) {
9877
+ const messages = import_localization10.CLI_MESSAGES[locale];
9878
+ const oauth = program.command("oauth").description(messages.oauth.commandDescription);
9879
+ oauth.command("init").description(messages.oauth.initDescription).requiredOption("--provider <name>", messages.oauth.providerOption).action((opts) => {
9880
+ info(writer, messages.oauth.templateHeading(opts.provider));
9881
+ json(writer, buildInitTemplate(opts.provider));
9882
+ info(writer, messages.oauth.clientSecretEnvNotice);
9883
+ });
9884
+ 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) => {
9885
+ if (opts.project) {
9886
+ if (opts.file || opts.issuer) {
9887
+ throw new UsageError("--project \u306F --file / --issuer \u3068\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");
9195
9888
  }
9196
- await sleepForPoll(
9197
- runtime,
9198
- Math.min(details.pollInterval * 1e3, remainingMilliseconds2),
9199
- mode,
9200
- messages
9889
+ const projectId = assertProjectId(opts.project);
9890
+ const result = await createAdminApiClient({ profile: opts.profile }).getOAuthSetup(
9891
+ projectId
9201
9892
  );
9202
- continue;
9203
- }
9204
- const status = parseStatus(rawStatus, details.publicationId, plan, messages);
9205
- if (expiresAt !== void 0 && status.expiresAt !== expiresAt) {
9206
- throw responseInvalid("publication_expiry_changed", messages);
9207
- }
9208
- expiresAt = status.expiresAt;
9209
- const now = runtime.monotonicNow();
9210
- const wallRemaining = Math.max(0, Date.parse(status.expiresAt) - runtime.wallNow());
9211
- deadline = Math.min(deadline, now + wallRemaining);
9212
- const remainingMilliseconds = Math.max(0, deadline - now);
9213
- writeSafeJson(writer, {
9214
- phase: mode === "recover-result" ? "result_recovery" : "confirmation",
9215
- requestId: status.requestId,
9216
- publicationId: status.publicationId,
9217
- durableState: status.durableState,
9218
- effectiveState: status.effectiveState,
9219
- expiresAt: status.expiresAt,
9220
- remainingSeconds: Math.ceil(remainingMilliseconds / 1e3)
9221
- });
9222
- if (status.durableState === "consumed") {
9223
- return { kind: "consumed", result: status.result };
9224
- }
9225
- if (status.durableState === "rejected") {
9226
- throw confirmationStopped("AP_POLICY_DENIED", "publication_rejected", messages);
9893
+ json(writer, result);
9894
+ if (result.metadata.status !== "valid" || result.alignment.issues.length > 0) {
9895
+ process.exitCode = 1;
9896
+ }
9897
+ return;
9227
9898
  }
9228
- if (status.durableState === "expired") {
9229
- throw confirmationStopped(
9230
- "AP_CONFIRMATION_EXPIRED",
9231
- "publication_confirmation_expired",
9232
- messages
9899
+ await runOAuthMetadataValidate(opts, writer, locale);
9900
+ });
9901
+ const scopes = oauth.command("scopes").description(messages.oauth.scopesDescription);
9902
+ 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) => {
9903
+ const operation = "andpipe oauth scopes sync";
9904
+ if (opts.apply && !opts.yes) {
9905
+ throw new ConfirmationRequiredError(
9906
+ operation,
9907
+ messages.common.confirmationRequiredMessage(operation)
9233
9908
  );
9234
9909
  }
9235
- if (status.effectiveState === "stale") {
9236
- throw confirmationStopped("AP_CONFLICT", "publication_confirmation_stale", messages);
9237
- }
9238
- if (mode === "await-approval" && status.durableState === "approved" && status.confirmation !== null) {
9239
- return {
9240
- kind: "approved",
9241
- confirmation: status.confirmation,
9242
- expiresAt: status.expiresAt
9243
- };
9910
+ if (!opts.apply && opts.yes) {
9911
+ throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9244
9912
  }
9245
- if (remainingMilliseconds <= 0) {
9246
- throw confirmationStopped(
9247
- "AP_CONFIRMATION_EXPIRED",
9248
- "publication_confirmation_timeout",
9249
- messages
9250
- );
9913
+ const projectId = assertProjectId(opts.project);
9914
+ const result = await createAdminApiClient({ profile: opts.profile }).syncOAuthScopes({
9915
+ projectId,
9916
+ apply: opts.apply
9917
+ });
9918
+ json(writer, result);
9919
+ });
9920
+ const registration = import_localization10.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9921
+ const scopeRegisterRuntime = dependencies.scopeRegisterRuntime ?? createOAuthScopeRegisterRuntime();
9922
+ const cwd = dependencies.cwd ?? (() => process.cwd());
9923
+ scopes.command("register").description(registration.commandDescription).option("--project <project-uuid>", registration.projectOption).option("--connector <connector-uuid>", registration.connectorOption).option(
9924
+ "--draft <toolId:versionId>",
9925
+ registration.draftOption,
9926
+ (value, previous) => [...previous, value],
9927
+ []
9928
+ ).option("--apply", registration.applyOption, false).option("--yes", registration.yesOption, false).option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).action(async (opts) => {
9929
+ const result = await runOAuthScopeRegisterCommand(
9930
+ opts,
9931
+ writer,
9932
+ cwd(),
9933
+ scopeRegisterRuntime,
9934
+ locale
9935
+ );
9936
+ if (!result.ok) process.exitCode = 1;
9937
+ });
9938
+ const clients = oauth.command("clients").description("OAuth client\u306Escope\u5272\u5F53\u3092\u7BA1\u7406\u3059\u308B");
9939
+ 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(
9940
+ async (opts) => {
9941
+ const operation = "andpipe oauth clients map-scopes";
9942
+ if (opts.apply && !opts.yes) {
9943
+ throw new ConfirmationRequiredError(
9944
+ operation,
9945
+ messages.common.confirmationRequiredMessage(operation)
9946
+ );
9947
+ }
9948
+ if (!opts.apply && opts.yes) {
9949
+ throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9950
+ }
9951
+ const client = createAdminApiClient({ profile: opts.profile });
9952
+ const preview = await client.mapOAuthClientScopes({
9953
+ projectId: assertProjectId(opts.project),
9954
+ clientRegistryId: opts.client,
9955
+ apply: false
9956
+ });
9957
+ json(writer, preview);
9958
+ if (!opts.apply) return;
9959
+ const applied = await client.mapOAuthClientScopes({
9960
+ projectId: assertProjectId(opts.project),
9961
+ clientRegistryId: opts.client,
9962
+ apply: true,
9963
+ requiredScopesCommitment: preview.requiredScopesCommitment,
9964
+ baseClientGrantCommitment: preview.baseClientGrantCommitment,
9965
+ candidateClientGrantCommitment: preview.candidateClientGrantCommitment,
9966
+ planCommitment: preview.planCommitment
9967
+ });
9968
+ json(writer, applied);
9251
9969
  }
9252
- const sleepMilliseconds = Math.min(details.pollInterval * 1e3, remainingMilliseconds);
9253
- await sleepForPoll(runtime, sleepMilliseconds, mode, messages);
9254
- }
9255
- throw confirmationStopped("AP_CONFIRMATION_EXPIRED", "publication_poll_attempt_limit", messages);
9256
- }
9257
- async function runPublishCommand(options, writer, cwd, runtime, messages = DEFAULT_PUBLISH_MESSAGES) {
9258
- const normalized = normalizePublishOptions(options, messages);
9259
- let project;
9260
- try {
9261
- project = runtime.loadProject(cwd);
9262
- } catch (error) {
9263
- if (error instanceof LocalFilePolicyError) {
9264
- throw new PublishCommandError(
9265
- "AP_POLICY_DENIED",
9266
- error.reason,
9267
- messages.failure(error.reason)
9970
+ );
9971
+ const metadata = oauth.command("metadata").description(messages.oauth.metadataDescription);
9972
+ metadata.command("validate").description(messages.oauth.validateDescription).option("--file <path>", messages.common.metadataFileOption).option("--issuer <url>", messages.common.issuerOption).action(async (opts) => {
9973
+ await runOAuthMetadataValidate(opts, writer, locale);
9974
+ });
9975
+ const connect = oauth.command("connect").description(
9976
+ 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"
9977
+ );
9978
+ connect.command("status").description(
9979
+ locale === "ja" ? "\u63A5\u7D9A\u72B6\u614B\u3068\u6B21\u306E\u64CD\u4F5C\u3092\u8868\u793A" : "Show connection state and next action"
9980
+ ).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) => {
9981
+ const state = await createAdminApiClient({
9982
+ profile: opts.profile
9983
+ }).getUpstreamOAuthConnectionState(assertProjectId(opts.project), opts.connector);
9984
+ json(writer, state);
9985
+ if (!state.allGreen) process.exitCode = 1;
9986
+ });
9987
+ connect.command("open").description(
9988
+ 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"
9989
+ ).requiredOption("--project <project>", messages.common.projectOption).requiredOption("--connector <connector>", "\u63A5\u7D9A\u5BFE\u8C61connector UUID").option("--profile <name>", messages.common.targetProfileOption, DEFAULT_PROFILE_NAME).option(
9990
+ "--no-browser",
9991
+ locale === "ja" ? "\u65E2\u5B9A\u30D6\u30E9\u30A6\u30B6\u3092\u958B\u304B\u305AURL\u3060\u3051\u8868\u793A" : "Print the URL without opening a browser"
9992
+ ).action(
9993
+ async (opts) => {
9994
+ const projectId = assertProjectId(opts.project);
9995
+ const state = await createAdminApiClient({
9996
+ profile: opts.profile
9997
+ }).getUpstreamOAuthConnectionState(projectId, opts.connector);
9998
+ json(writer, state);
9999
+ const url = upstreamOAuthWizardUrl(opts.profile, projectId, opts.connector);
10000
+ info(
10001
+ writer,
10002
+ locale === "ja" ? `Web Admin\u3067\u7D9A\u3051\u3066\u304F\u3060\u3055\u3044: ${url}` : `Continue in Web Admin: ${url}`
9268
10003
  );
10004
+ if (opts.browser) {
10005
+ try {
10006
+ (dependencies.openBrowser ?? openBrowser)(url);
10007
+ } catch {
10008
+ }
10009
+ }
9269
10010
  }
9270
- const reason = error instanceof DevProjectLoadError ? error.reason : "local_project_invalid";
9271
- if (error instanceof DevProjectLoadError || error instanceof UsageError) {
9272
- throw new PublishCommandError("AP_INPUT_INVALID", reason, messages.failure(reason));
9273
- }
9274
- throw error;
9275
- }
9276
- const projectId = project.manifest.project_id;
9277
- const connectorId = normalized.connectorId ?? project.manifest.connector_id;
9278
- if (connectorId === void 0) {
9279
- throw new PublishCommandError(
9280
- "AP_INPUT_INVALID",
9281
- "publication_connector_required",
9282
- messages.optionRequires("publish", "--connector UUID")
10011
+ );
10012
+ 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) => {
10013
+ const projectId = assertProjectId(opts.project);
10014
+ const result = await createAdminApiClient({ profile: opts.profile }).testOAuthLogin(
10015
+ projectId,
10016
+ opts.client
9283
10017
  );
10018
+ json(writer, result);
10019
+ if (result.status === "blocked") process.exitCode = 1;
10020
+ });
10021
+ }
10022
+
10023
+ // src/commands/openapi.ts
10024
+ var import_node_crypto14 = require("crypto");
10025
+ var import_node_path12 = require("path");
10026
+ var import_tool_contract11 = require("@andpipes/tool-contract");
10027
+ function createOpenApiImportRuntime(createClient = (profile) => createAdminApiClient({ profile })) {
10028
+ return { createClient, idempotencyKey: import_node_crypto14.randomUUID };
10029
+ }
10030
+ function normalizedOptions(options) {
10031
+ if (!options.file || !options.project || !options.connector) {
10032
+ throw new UsageError("--file\u3001--project\u3001--connector \u306F\u5FC5\u9808\u3067\u3059");
9284
10033
  }
9285
- if (normalized.projectId !== void 0 && normalized.projectId !== projectId) {
9286
- throw new PublishCommandError(
9287
- "AP_CONFLICT",
9288
- "manifest_project_mismatch",
9289
- messages.failure("manifest_project_mismatch")
9290
- );
10034
+ if (options.format !== void 0 && options.format !== "json" && options.format !== "yaml") {
10035
+ throw new UsageError("--format \u306F json \u307E\u305F\u306F yaml \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9291
10036
  }
9292
- const candidate = prepareCandidate(project);
9293
- const localToolNames = project.contract.tools.map((tool) => (0, import_tool_contract10.toolName)(tool));
9294
- if (localToolNames.some((name) => !(0, import_tool_contract10.isSafeToolName)(name))) {
9295
- throw new PublishCommandError(
9296
- "AP_INPUT_INVALID",
9297
- "publication_candidate_tool_invalid",
9298
- messages.failure("publication_candidate_tool_invalid")
9299
- );
10037
+ if (options.serviceName !== void 0 && !/^[A-Za-z0-9_]{1,48}$/.test(options.serviceName)) {
10038
+ throw new UsageError("--service-name \u306F\u82F1\u6570\u5B57\u3068 underscore \u306E1..48\u6587\u5B57\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9300
10039
  }
9301
- const expectedToolNames = localToolNames.sort(import_tool_contract10.comparePublicationUnicodeCodePoints);
9302
- const planRequest = {
9303
- environment: "production",
9304
- connectorId,
9305
- candidateContract: candidate.candidateContract,
9306
- candidateCommitment: candidate.candidateCommitment,
9307
- ...project.manifest.template_id && project.manifest.template_application_commitment ? {
9308
- templateProvenance: {
9309
- templateId: project.manifest.template_id,
9310
- applicationCommitment: project.manifest.template_application_commitment
9311
- }
9312
- } : {}
9313
- };
9314
- const client = runtime.createClient(normalized.profile);
9315
- let rawPlan;
9316
- try {
9317
- rawPlan = await client.planPublication(projectId, planRequest);
9318
- } catch (error) {
9319
- throw remoteError(error, "plan", messages);
10040
+ const apply = options.apply === true;
10041
+ const yes = options.yes === true;
10042
+ if (yes && !apply) {
10043
+ throw new UsageError("--yes \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9320
10044
  }
9321
- const plan = parsePlan(
9322
- rawPlan,
9323
- connectorId,
9324
- candidate.candidateCommitment,
9325
- expectedToolNames,
9326
- messages
9327
- );
9328
- writePlan(writer, plan);
9329
- if (plan.blockedReasons.includes("connector_mismatch")) {
9330
- interactive(writer, messages.connectorMismatchRemediation);
10045
+ if (options.idempotencyKey !== void 0 && !apply) {
10046
+ throw new UsageError("--idempotency-key \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
9331
10047
  }
9332
- if (normalized.mode === "dry-run") return;
9333
- if (!plan.applyAllowed) {
9334
- throw new PublishCommandError(
9335
- "AP_POLICY_DENIED",
9336
- "publication_plan_blocked",
9337
- messages.planBlocked(plan.blockedReasons)
10048
+ if (!apply && options.planCommitment !== void 0) {
10049
+ throw new UsageError("--plan-commitment \u306F --apply \u3068\u4E00\u7DD2\u306B\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
10050
+ }
10051
+ return {
10052
+ file: options.file,
10053
+ project: assertProjectId(options.project),
10054
+ connectorId: assertProjectId(options.connector),
10055
+ profile: options.profile ?? DEFAULT_PROFILE_NAME,
10056
+ ...options.format !== void 0 ? { format: options.format } : {},
10057
+ ...options.baseUrl !== void 0 ? { baseUrl: options.baseUrl } : {},
10058
+ ...options.serviceName !== void 0 ? { serviceName: options.serviceName } : {},
10059
+ apply,
10060
+ yes,
10061
+ ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {},
10062
+ ...options.planCommitment !== void 0 ? { planCommitment: options.planCommitment } : {},
10063
+ ...options.authMode !== void 0 ? { upstreamAuthMode: parseAuthModeOption(options.authMode) } : {},
10064
+ sideEffectFree: parseSideEffectFreeOptions(options.sideEffectFree)
10065
+ };
10066
+ }
10067
+ function rethrowWithAuthModeGuidance(error) {
10068
+ if (error instanceof AdminApiClientError && error.openApiAuthModeMismatch) {
10069
+ throw new UsageError(authModeMismatchGuidance(error.openApiAuthModeMismatch));
10070
+ }
10071
+ throw error;
10072
+ }
10073
+ async function runOpenApiImportCommand(options, writer, cwd, runtime = createOpenApiImportRuntime()) {
10074
+ const normalized = normalizedOptions(options);
10075
+ if (normalized.apply && !normalized.yes) {
10076
+ throw new ConfirmationRequiredError(
10077
+ "andpipe openapi import --apply",
10078
+ "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"
9338
10079
  );
9339
10080
  }
9340
- const idempotencyKey = assertIdempotencyKey2(runtime.randomUuid(), messages);
9341
- const applyRequest = (confirmation) => ({
9342
- ...planRequest,
9343
- planCommitment: plan.planCommitment,
9344
- confirmation
9345
- });
9346
- const initialApplyRequest = freezeJson(applyRequest(null));
9347
- const initial = await sendInitialApplyWithSameAnchorRetry({
9348
- client,
9349
- projectId,
9350
- idempotencyKey,
9351
- body: initialApplyRequest,
9352
- plan,
9353
- messages
10081
+ if (normalized.apply && !/^[a-f0-9]{64}$/.test(normalized.planCommitment ?? "")) {
10082
+ throw new UsageError("--apply \u306B\u306Fpreview\u3067\u5F97\u305F --plan-commitment \u304C\u5FC5\u9808\u3067\u3059");
10083
+ }
10084
+ const snapshot = readBoundedLocalFileSnapshot((0, import_node_path12.resolve)(cwd, normalized.file), {
10085
+ maxBytes: import_tool_contract11.OPENAPI_IMPORT_MAX_SOURCE_BYTES,
10086
+ root: cwd
9354
10087
  });
9355
- let details;
9356
- if (initial.kind === "response") {
9357
- writeResult(writer, initial.result);
9358
- return;
9359
- } else {
9360
- if (plan.tools.every((tool) => !tool.changed)) {
9361
- throw responseInvalid("publication_noop_confirmation_invalid", messages);
10088
+ const baseRequest = {
10089
+ source: snapshot.text,
10090
+ connectorId: normalized.connectorId,
10091
+ ...normalized.format !== void 0 ? { format: normalized.format } : {},
10092
+ ...normalized.baseUrl !== void 0 ? { baseUrl: normalized.baseUrl } : {},
10093
+ ...normalized.serviceName !== void 0 ? { serviceName: normalized.serviceName } : {},
10094
+ ...normalized.upstreamAuthMode !== void 0 ? { upstreamAuthMode: normalized.upstreamAuthMode } : {}
10095
+ };
10096
+ const client = runtime.createClient(normalized.profile);
10097
+ const assertSource = (sourceCommitment) => {
10098
+ if (sourceCommitment !== snapshot.sha256) {
10099
+ throw new UsageError("Admin API\u306Esource commitment\u304Clocal file\u3068\u4E00\u81F4\u3057\u307E\u305B\u3093");
9362
10100
  }
9363
- details = initial.details;
9364
- }
9365
- writeSafeJson(writer, { phase: "confirmation_required", ...details });
9366
- const decision = await pollPublication(
9367
- client,
9368
- projectId,
9369
- details,
9370
- plan,
9371
- writer,
9372
- runtime,
9373
- "await-approval",
9374
- messages
9375
- );
9376
- if (decision.kind === "consumed") {
9377
- writeResult(writer, decision.result);
9378
- return;
9379
- }
9380
- try {
9381
- const result = parsePublicationResult(
9382
- await client.applyPublication(projectId, idempotencyKey, applyRequest(decision.confirmation)),
9383
- plan,
9384
- messages,
9385
- details.publicationId
9386
- );
9387
- writeResult(writer, result);
9388
- return;
9389
- } catch (error) {
9390
- if (error instanceof PublishCommandError && error.code === "AP_RESPONSE_INVALID") {
9391
- } else if (!approvedApplyResultMayBeUnknown(error)) {
9392
- throw remoteError(error, "approved_apply", messages);
10101
+ };
10102
+ let overrides = [];
10103
+ if (normalized.sideEffectFree.length > 0) {
10104
+ if (normalized.apply) {
10105
+ try {
10106
+ const unclassified = (0, import_tool_contract11.importOpenApi)(snapshot.text, {
10107
+ format: normalized.format,
10108
+ baseUrl: normalized.baseUrl,
10109
+ serviceName: normalized.serviceName,
10110
+ upstreamAuthMode: normalized.upstreamAuthMode
10111
+ });
10112
+ overrides = resolveOperationRiskOverrides(
10113
+ normalized.sideEffectFree,
10114
+ unclassified.operations
10115
+ );
10116
+ } catch (error) {
10117
+ if (error instanceof import_tool_contract11.OpenApiImportError) {
10118
+ throw new UsageError(`OpenAPI\u304B\u3089Tool Contract\u3092\u751F\u6210\u3067\u304D\u307E\u305B\u3093: ${error.message}`);
10119
+ }
10120
+ throw error;
10121
+ }
10122
+ } else {
10123
+ const unclassified = await client.planOpenApiImport(normalized.project, baseRequest).catch(rethrowWithAuthModeGuidance);
10124
+ assertSource(unclassified.sourceCommitment);
10125
+ overrides = resolveOperationRiskOverrides(normalized.sideEffectFree, unclassified.operations);
9393
10126
  }
9394
10127
  }
9395
- const recovered = await pollPublication(
9396
- client,
9397
- projectId,
9398
- details,
9399
- plan,
9400
- writer,
9401
- runtime,
9402
- "recover-result",
9403
- messages,
9404
- decision.expiresAt
9405
- );
9406
- if (recovered.kind !== "consumed") {
9407
- throw new PublishCommandError(
9408
- "AP_RESULT_UNKNOWN",
9409
- "publication_result_unknown",
9410
- messages.resultUnknown
9411
- );
10128
+ const request = {
10129
+ ...baseRequest,
10130
+ ...overrides.length > 0 ? { operationRiskOverrides: overrides } : {},
10131
+ ...normalized.planCommitment !== void 0 ? { expectedPlanCommitment: normalized.planCommitment } : {}
10132
+ };
10133
+ const classification = {
10134
+ upstreamAuthMode: normalized.upstreamAuthMode ?? "token_exchange",
10135
+ operationRiskOverrides: overrides
10136
+ };
10137
+ if (!normalized.apply) {
10138
+ const result2 = await client.planOpenApiImport(normalized.project, request).catch(rethrowWithAuthModeGuidance);
10139
+ assertSource(result2.sourceCommitment);
10140
+ json(writer, { mode: "preview", ...classification, ...result2 });
10141
+ const guidance = sideEffectFreeGuidance(result2.operations);
10142
+ if (guidance) interactive(writer, guidance);
10143
+ return;
9412
10144
  }
9413
- writeResult(writer, recovered.result);
10145
+ const result = await client.applyOpenApiImport(
10146
+ normalized.project,
10147
+ normalized.idempotencyKey ?? runtime.idempotencyKey(),
10148
+ request
10149
+ ).catch(rethrowWithAuthModeGuidance);
10150
+ assertSource(result.sourceCommitment);
10151
+ json(writer, { mode: "draft_created", ...classification, ...result });
9414
10152
  }
9415
- 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) {
9416
- 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) => {
9417
- await runPublishCommand(commandOptions, writer, cwd(), runtime, messages);
9418
- });
10153
+ function collect(value, previous) {
10154
+ return [...previous, value];
10155
+ }
10156
+ function registerOpenApi(program, writer, cwd, runtime = createOpenApiImportRuntime()) {
10157
+ const openapi = program.command("openapi").description("OpenAPI\u304B\u3089Tool Contract draft\u3092\u63D0\u6848\u3059\u308B");
10158
+ 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(
10159
+ "--auth-mode <mode>",
10160
+ "connector\u3068\u540C\u3058\u8A8D\u8A3C\u65B9\u5F0F\uFF08existing_oauth \u307E\u305F\u306F token_exchange\u3002\u7701\u7565\u6642\u306Ftoken_exchange\uFF09"
10161
+ ).option(
10162
+ "--side-effect-free <toolName=level>",
10163
+ "\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",
10164
+ collect,
10165
+ []
10166
+ ).action(
10167
+ (options) => runOpenApiImportCommand(options, writer, cwd(), runtime)
10168
+ );
9419
10169
  }
9420
10170
 
9421
10171
  // src/commands/review-package.ts
@@ -9544,6 +10294,7 @@ function registerValidate(program, writer, cwd, locale = import_localization12.D
9544
10294
  function buildProgram(writer = defaultWriter, cwd = () => process.cwd(), locale = (0, import_localization13.normalizeLocale)(process.env.ANDPIPE_LOCALE ?? process.env.LANG)) {
9545
10295
  const text = import_localization13.LOCALIZED_TEXT[locale].cli;
9546
10296
  const messages = import_localization13.CLI_MESSAGES[locale];
10297
+ const scopeRegistrationMessages = import_localization13.OAUTH_SCOPE_REGISTRATION_MESSAGES[locale].cli;
9547
10298
  const program = new import_commander.Command();
9548
10299
  program.name(CLI_NAME).description(text.description).option("--locale <locale>", messages.localeOption, import_localization13.DEFAULT_LOCALE).version(readVersion());
9549
10300
  registerAuth(program, writer, locale);
@@ -9555,13 +10306,14 @@ function buildProgram(writer = defaultWriter, cwd = () => process.cwd(), locale
9555
10306
  (profile) => createAdminApiClient({ profile }),
9556
10307
  text.initDescription,
9557
10308
  void 0,
9558
- messages.init
10309
+ messages.init,
10310
+ scopeRegistrationMessages
9559
10311
  );
9560
10312
  registerDev(program, writer, cwd, void 0, text.devDescription, messages.dev);
9561
10313
  registerValidate(program, writer, cwd, locale);
9562
10314
  registerReviewPackage(program, writer, locale, cwd);
9563
10315
  registerDomain(program, writer, locale);
9564
- registerOauth(program, writer, locale);
10316
+ registerOauth(program, writer, locale, { cwd });
9565
10317
  registerOpenApi(program, writer, cwd);
9566
10318
  registerConfigMcp(program, writer, locale);
9567
10319
  registerDoctor(program, writer, locale);
@@ -9574,7 +10326,9 @@ function buildProgram(writer = defaultWriter, cwd = () => process.cwd(), locale
9574
10326
  (profile) => createAdminApiClient({ profile }),
9575
10327
  text.publishDescription,
9576
10328
  void 0,
9577
- messages.publish
10329
+ messages.publish,
10330
+ scopeRegistrationMessages,
10331
+ import_localization13.PUBLICATION_SCHEMA_REVIEW_CLI_MESSAGES[locale]
9578
10332
  );
9579
10333
  return program;
9580
10334
  }
@@ -9599,6 +10353,9 @@ var packageName = PACKAGE_NAME;
9599
10353
  0 && (module.exports = {
9600
10354
  ADMIN_API_MAX_GET_ATTEMPTS,
9601
10355
  ADMIN_API_MAX_RESPONSE_BYTES,
10356
+ ADMIN_API_OAUTH_SCOPE_REGISTRATION_MAX_APPLY_ATTEMPTS,
10357
+ ADMIN_API_OAUTH_SCOPE_REGISTRATION_REQUEST_MAX_BYTES,
10358
+ ADMIN_API_OAUTH_SCOPE_REGISTRATION_RESPONSE_MAX_BYTES,
9602
10359
  ADMIN_API_ONBOARDING_TEMPLATE_MAX_BYTES,
9603
10360
  ADMIN_API_OPENAPI_IMPORT_MAX_BYTES,
9604
10361
  ADMIN_API_ORIGIN,
@@ -9630,6 +10387,7 @@ var packageName = PACKAGE_NAME;
9630
10387
  DevProjectPreflightError,
9631
10388
  InitLocalUsageError,
9632
10389
  InitManifestConflictError,
10390
+ OAuthScopeRegistrationCommandError,
9633
10391
  PACKAGE_NAME,
9634
10392
  PublishCommandError,
9635
10393
  RISK_LEVELS,
@@ -9643,6 +10401,7 @@ var packageName = PACKAGE_NAME;
9643
10401
  connectConfigMcp,
9644
10402
  createAdminApiClient,
9645
10403
  createInitCommandRuntime,
10404
+ createOAuthScopeRegisterRuntime,
9646
10405
  createOpenApiImportRuntime,
9647
10406
  createPublishCommandRuntime,
9648
10407
  createS256Challenge,
@@ -9685,6 +10444,7 @@ var packageName = PACKAGE_NAME;
9685
10444
  runDevCommand,
9686
10445
  runDoctor,
9687
10446
  runInitCommand,
10447
+ runOAuthScopeRegisterCommand,
9688
10448
  runOpenApiImportCommand,
9689
10449
  runPublishCommand,
9690
10450
  runTemplatePlanOrApply,