@huaweidevtools/aishell-dsh-client-credentials 0.0.1-beta.2 → 0.0.1-beta.4

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/lib/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { createCredentialsStore } from "@huaweidevtools/aishell-dsh-credentials-store";
2
- import { sign } from "@huaweidevtools/aishell-dsh-credentials-store/signer";
2
+ import { clearCredentials, hasStoredPair, readStoredPair, writeHuaweiCloud } from "@huaweidevtools/aishell-dsh-credentials-store/accounts";
3
+ import { verifyCredentials } from "@huaweidevtools/aishell-dsh-credentials-store/verify";
3
4
 
4
5
  //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.5/node_modules/@deepseek-ai/cosmokit/lib/index.js
5
6
  /** Return true when a value is `null` or `undefined`. */
@@ -893,9 +894,377 @@ defineMethod("transform", [
893
894
  "preserve"
894
895
  ], ({ inner }, isInner) => inner.toString(isInner));
895
896
 
897
+ //#endregion
898
+ //#region src/auth-tool.ts
899
+ /** Model-facing name. Prefixed so it cannot collide with another cloud plugin. */
900
+ const AUTH_TOOL_NAME = "aishell__auth";
901
+ /** Region used to route the verification call; IAM is global, see the module note. */
902
+ const VERIFY_REGION$1 = "cn-north-4";
903
+ /** Per-call budget. IAM answers in well under a second when healthy. */
904
+ const AUTH_TIMEOUT_MS = 3e4;
905
+ /**
906
+ * The JSON Schema for `auth`'s parameters: none.
907
+ *
908
+ * Declared as an empty object rather than omitted so the model reads "takes no
909
+ * arguments" explicitly, instead of inferring it from a missing field.
910
+ */
911
+ const AUTH_PARAMETERS = {
912
+ type: "object",
913
+ properties: {},
914
+ additionalProperties: false
915
+ };
916
+ /**
917
+ * Register the `auth` tool on the host's tool registry.
918
+ *
919
+ * @param ctx - host context.
920
+ * @param store - the credential store this package owns.
921
+ */
922
+ function registerAuthTool(ctx, store, deps) {
923
+ ctx.inject(["tools"], (scope) => {
924
+ const dispose = scope.tools.register({
925
+ name: AUTH_TOOL_NAME,
926
+ description: "Verify the stored Huawei Cloud credentials and report the account: its id and name, and every project visible to it (a project's name is a region; its id is what a region-scoped API needs).",
927
+ parameters: AUTH_PARAMETERS,
928
+ output: {
929
+ schema: {
930
+ type: "object",
931
+ properties: {
932
+ authenticated: { type: "boolean" },
933
+ account: {
934
+ type: "object",
935
+ properties: {
936
+ accountId: { type: "string" },
937
+ name: { type: "string" }
938
+ },
939
+ required: ["accountId", "name"]
940
+ },
941
+ projects: {
942
+ type: "array",
943
+ items: {
944
+ type: "object",
945
+ properties: {
946
+ id: { type: "string" },
947
+ name: { type: "string" },
948
+ description: { type: "string" }
949
+ },
950
+ required: ["id", "name"]
951
+ }
952
+ },
953
+ sts: { type: "boolean" }
954
+ },
955
+ required: [
956
+ "authenticated",
957
+ "account",
958
+ "projects",
959
+ "sts"
960
+ ]
961
+ },
962
+ render: (_args, value) => renderAuth(value)
963
+ },
964
+ timeoutMs: AUTH_TIMEOUT_MS,
965
+ async execute(_args, exec) {
966
+ return await runAuth(store, deps, sessionOf(exec), exec.signal);
967
+ }
968
+ });
969
+ return dispose;
970
+ });
971
+ }
972
+ /** The session a tool call runs under, from its execution context. */
973
+ function sessionOf(exec) {
974
+ return exec.agent?.session?.id;
975
+ }
976
+ /**
977
+ * Verify and describe the stored account.
978
+ *
979
+ * Four outcomes, and each one is a different instruction to the model:
980
+ *
981
+ * - **Verified.** The account and its projects.
982
+ * - **The person cancelled.** Terminal: stop, and say what the credential was
983
+ * needed for. Without this the model's only signal is the same failure it
984
+ * got before, and it retries until the turn ends — while the person has
985
+ * already said no.
986
+ * - **Nothing stored, or the stored pair was rejected.** Open the form and
987
+ * fail with the reason. The model calls again once the person is done.
988
+ *
989
+ * The last two both open the form, which is deliberate: a rejected credential is
990
+ * the case where the person most needs to see the form again, and Huawei's own
991
+ * reason is what tells them what to correct.
992
+ *
993
+ * @param store - the credential store to read.
994
+ * @param deps - host controls: open the form and wait for its answer.
995
+ * @param sessionId - the conversation to open the form in; `undefined` when the
996
+ * call carries no agent, in which case no form can be shown.
997
+ * @param signal - the call's cancellation; the way out of a form nobody answers.
998
+ * @returns the account, its projects, and whether the credentials are temporary.
999
+ * @throws when the person cancels, or when no form can be shown at all.
1000
+ */
1001
+ async function runAuth(store, deps, sessionId, signal) {
1002
+ const stored = readStoredPair(store);
1003
+ if (stored !== void 0) {
1004
+ const verified = await verifyCredentials(stored, { region: VERIFY_REGION$1 });
1005
+ if (verified.ok) return describeAccount(verified);
1006
+ }
1007
+ if (sessionId === void 0 || sessionId === "") throw new Error("Not authenticated with Huawei Cloud IAM, and this call is not attached to a conversation, so the credential form cannot be shown. Ask the user to open the credential form themselves, then call auth again.");
1008
+ for (let round = 0; round < MAX_FORM_ROUNDS; round += 1) {
1009
+ const pending = deps.requestForm(sessionId);
1010
+ if (pending === void 0) break;
1011
+ const outcome = await raceCancellation(pending, signal);
1012
+ if (outcome.kind === "cancelled") throw new CredentialEntryCancelled();
1013
+ if (outcome.kind === "aborted") throw new CredentialEntryCancelled();
1014
+ const pair = readStoredPair(store);
1015
+ if (pair === void 0) continue;
1016
+ const result = await verifyCredentials(pair, { region: VERIFY_REGION$1 });
1017
+ if (result.ok) return describeAccount(result);
1018
+ }
1019
+ throw new Error("Not authenticated with Huawei Cloud IAM. The credential form was shown but no usable credential was stored. Ask the user to authenticate, then call auth again.");
1020
+ }
1021
+ /** How many form rounds one call will wait through before giving up. */
1022
+ const MAX_FORM_ROUNDS = 10;
1023
+ /**
1024
+ * The person said no, and the call must end rather than ask again.
1025
+ *
1026
+ * Its own type so the message can be the whole instruction: a model reading a
1027
+ * generic failure has every reason to retry, which is exactly wrong once the
1028
+ * person has answered.
1029
+ */
1030
+ var CredentialEntryCancelled = class extends Error {
1031
+ constructor() {
1032
+ super("The user cancelled credential entry. Stop here and tell them why Huawei Cloud authentication is needed for what they asked. Do not call auth again until they say to.");
1033
+ this.name = "CredentialEntryCancelled";
1034
+ }
1035
+ };
1036
+ /**
1037
+ * Wait for the form's answer, or for the call to be cancelled.
1038
+ *
1039
+ * An abandoned call must not keep a promise alive: the turn is over, and nobody
1040
+ * is going to answer a prompt for it. `aborted` is a separate outcome from
1041
+ * `cancelled` in shape, and treated the same in effect — either way the person
1042
+ * did not supply a credential and asking again would be wrong.
1043
+ *
1044
+ * @param pending - the open form request.
1045
+ * @param signal - the call's cancellation, if any.
1046
+ */
1047
+ async function raceCancellation(pending, signal) {
1048
+ if (signal === void 0) return pending;
1049
+ if (signal.aborted) return { kind: "aborted" };
1050
+ return await new Promise((resolve) => {
1051
+ const onAbort = () => {
1052
+ resolve({ kind: "aborted" });
1053
+ };
1054
+ signal.addEventListener("abort", onAbort, { once: true });
1055
+ pending.then((outcome) => {
1056
+ signal.removeEventListener("abort", onAbort);
1057
+ resolve(outcome);
1058
+ });
1059
+ });
1060
+ }
1061
+ /** Project a successful verification into the tool's canonical value. */
1062
+ function describeAccount(result) {
1063
+ return {
1064
+ authenticated: true,
1065
+ account: {
1066
+ accountId: result.account.accountId,
1067
+ name: result.account.name
1068
+ },
1069
+ projects: result.account.projects.map((project) => ({
1070
+ id: project.id,
1071
+ name: project.name,
1072
+ ...project.description === void 0 ? {} : { description: project.description }
1073
+ })),
1074
+ sts: result.sts
1075
+ };
1076
+ }
1077
+ /**
1078
+ * The text the model reads.
1079
+ *
1080
+ * A short summary then the project table: the summary answers the question the
1081
+ * tool was called with, and the table is what the next call needs. The region
1082
+ * is deliberately absent — IAM does not verify it, so printing it would suggest
1083
+ * it had been checked.
1084
+ *
1085
+ * @param value - the verified account.
1086
+ */
1087
+ function renderAuth(value) {
1088
+ const projects = value.projects.length === 0 ? "No projects are visible to these credentials." : ["Project id region description", ...value.projects.map((project) => `${project.id.padEnd(36)} ${project.name.padEnd(14)} ${project.description ?? ""}`.trimEnd())].join("\n");
1089
+ const kind = value.sts ? "temporary (STS)" : "stored";
1090
+ return [{
1091
+ type: "text",
1092
+ text: `Authenticated with Huawei Cloud as ${value.account.name} (account id ${value.account.accountId}); using ${kind} credentials.\n\n` + projects
1093
+ }];
1094
+ }
1095
+
1096
+ //#endregion
1097
+ //#region src/form-request.ts
1098
+ /**
1099
+ * The credential form's Host-side control.
1100
+ *
1101
+ * ## What this is for
1102
+ *
1103
+ * `aishell__auth` needs credentials that are not there. It cannot collect them
1104
+ * — a credential a tool returns is a credential in the transcript — so it asks
1105
+ * for the form to be put on screen, the person fills it, and the model calls
1106
+ * `auth` again.
1107
+ *
1108
+ * ## Why the settings document carries the request
1109
+ *
1110
+ * The two halves live apart: the tool runs on the host, the form is browser
1111
+ * code. The host cannot reach the browser over the fetch channel — that channel
1112
+ * is browser→host only — so the request has to ride something the browser
1113
+ * already watches. The settings document is exactly that: the browser half
1114
+ * subscribes to this entry's config through `configForms`, and a volatile field
1115
+ * written by the host shows up there.
1116
+ *
1117
+ * The document carries **only** a request token and a session id. Never a
1118
+ * credential, never a verdict — those travel the other way, over the
1119
+ * credential route, and the browser never receives a stored secret at all.
1120
+ *
1121
+ * ## Why the token, not a boolean
1122
+ *
1123
+ * The browser has to tell "a new request" from "the request it already opened".
1124
+ * With a boolean, a second `auth` failure while the form is up would look
1125
+ * identical to the first and the form would not re-open after the person
1126
+ * cancelled it. The token changes on every request, and the browser compares it
1127
+ * to the last one it acted on.
1128
+ *
1129
+ * ## Why nothing is awaited
1130
+ *
1131
+ * The tool cannot wait for the person — a tool call has no way to be paused for
1132
+ * a human. So `auth` fails, the form appears, and the model calls again. That
1133
+ * round trip is the whole protocol, and it is why the failure message and the
1134
+ * form are worded as a pair.
1135
+ *
1136
+ * @module @huaweidevtools/aishell-dsh-client-credentials/form-request
1137
+ */
1138
+ /** Field of this entry's config that carries one pending request. */
1139
+ const FORM_REQUEST_FIELD = "credentialFormRequest";
1140
+ /**
1141
+ * Build a request for one session, minting its token.
1142
+ *
1143
+ * The token is minted here rather than by the caller so a request cannot be
1144
+ * recorded without one — the browser's "is this new?" test would then be
1145
+ * comparing against nothing, and the form would not reopen after a cancel.
1146
+ *
1147
+ * @param sessionId - the conversation the form should render in.
1148
+ * @returns the request, and its encoded form for the settings document.
1149
+ */
1150
+ function formRequest(sessionId) {
1151
+ nextToken += 1;
1152
+ const request = {
1153
+ token: `${Date.now().toString(36)}-${String(nextToken)}`,
1154
+ sessionId
1155
+ };
1156
+ const completion = Promise.withResolvers();
1157
+ return {
1158
+ request,
1159
+ encoded: encodeRequest(request),
1160
+ outcome: completion.promise,
1161
+ settle: (outcome) => {
1162
+ completion.resolve(outcome);
1163
+ }
1164
+ };
1165
+ }
1166
+ /** Source of tokens; module-scoped so it is per-host-process. */
1167
+ let nextToken = 0;
1168
+ /**
1169
+ * Serialize a request for the settings document.
1170
+ *
1171
+ * The document holds strings — a volatile `string` field is what the browser
1172
+ * half reads through `configForms` — so the request is JSON. Encoding rather
1173
+ * than reshaping the config into several fields keeps the request atomic: the
1174
+ * browser cannot observe a new token with an old session.
1175
+ *
1176
+ * @param request - the request to encode.
1177
+ */
1178
+ function encodeRequest(request) {
1179
+ return JSON.stringify(request);
1180
+ }
1181
+
1182
+ //#endregion
1183
+ //#region src/reconcile.ts
1184
+ /**
1185
+ * Build the reconcile state machine.
1186
+ *
1187
+ * Two facts are reconciled independently, because they are independent:
1188
+ * - `credentialsStored` — are AK/SK in the store right now?
1189
+ * - `accessKeyIdHint` — what account name did IAM verification return?
1190
+ *
1191
+ * The hint is re-derived only when the credential material changed since the
1192
+ * last verification. That single trigger covers both reasons to re-verify — a
1193
+ * first-seen credential (the material has never been fingerprinted) and a
1194
+ * rotation (the material differs from the last verified set) — and it keeps a
1195
+ * failing verification (expired STS, IAM outage) from retrying every tick: the
1196
+ * retry keys on the material changing, not on time alone, and a failed verify
1197
+ * still records the fingerprint. Cleared by `resetVerifyBaseline` so a
1198
+ * clear-then-rotate re-verifies from scratch.
1199
+ *
1200
+ * @param deps - collaborators. `readStored`/`readHint` read this plugin's own
1201
+ * mirror so reconcile never depends on config flow-back timing.
1202
+ */
1203
+ function createCredentialReconciler(deps) {
1204
+ const { verify, recordStatus, readStored, readHint, readPair } = deps;
1205
+ let lastVerifyFingerprint = "";
1206
+ const materialFingerprint = (ak, sk, token) => `${ak}\n${sk}\n${token ?? ""}`;
1207
+ return {
1208
+ reconcile: () => {
1209
+ const pair = readPair();
1210
+ const haveKeys = pair !== void 0;
1211
+ const stored = readStored();
1212
+ const hint = readHint();
1213
+ if (!haveKeys && (stored || hint !== null)) recordStatus([{
1214
+ op: "set",
1215
+ path: ["credentialsStored"],
1216
+ value: false
1217
+ }, {
1218
+ op: "unset",
1219
+ path: ["accessKeyIdHint"]
1220
+ }]);
1221
+ else if (haveKeys && !stored) recordStatus([{
1222
+ op: "set",
1223
+ path: ["credentialsStored"],
1224
+ value: true
1225
+ }]);
1226
+ if (!haveKeys) return;
1227
+ const fingerprint = materialFingerprint(pair.ak, pair.sk, pair.securityToken);
1228
+ const materialChanged = fingerprint !== lastVerifyFingerprint;
1229
+ if (!materialChanged) return;
1230
+ lastVerifyFingerprint = fingerprint;
1231
+ verify(pair.ak, pair.sk, pair.securityToken).then((accountName) => {
1232
+ if (readPair()?.ak !== pair.ak) return;
1233
+ recordStatus([{
1234
+ op: "set",
1235
+ path: ["accessKeyIdHint"],
1236
+ value: accountName
1237
+ }]);
1238
+ }).catch(() => {});
1239
+ },
1240
+ resetVerifyBaseline: () => {
1241
+ lastVerifyFingerprint = "";
1242
+ }
1243
+ };
1244
+ }
1245
+
896
1246
  //#endregion
897
1247
  //#region src/index.ts
898
1248
  /**
1249
+ * Read the request token out of a save body.
1250
+ *
1251
+ * Parsed leniently: the route validates the body itself and answers 400 for a
1252
+ * malformed one, so this only has to avoid throwing on the way past. A missing
1253
+ * or unreadable token means "not an answer to a request", which is the right
1254
+ * behaviour for a chip-opened form.
1255
+ *
1256
+ * @param body - the raw request body.
1257
+ */
1258
+ function readRequestToken(body) {
1259
+ try {
1260
+ const parsed = JSON.parse(body);
1261
+ const token = parsed?.requestToken;
1262
+ return typeof token === "string" && token !== "" ? token : void 0;
1263
+ } catch {
1264
+ return void 0;
1265
+ }
1266
+ }
1267
+ /**
899
1268
  * Settings schema for this entry. Secrets are deliberately absent: they travel
900
1269
  * over the credential route into the credential store, never through a
901
1270
  * settings document.
@@ -904,57 +1273,68 @@ const Config = Schema.object({
904
1273
  credentialsStored: Schema.boolean().default(false).volatile(),
905
1274
  accessKeyIdHint: Schema.string().default("").volatile(),
906
1275
  lastError: Schema.string().default("").volatile(),
907
- credentialRequestSession: Schema.string().default("").volatile()
1276
+ credentialFormRequest: Schema.string().default("").volatile()
908
1277
  });
909
- /** Credential store account names for Huawei Cloud credentials. */
910
- const AK_ACCOUNT = "HW_ACCESS_KEY";
911
- const SK_ACCOUNT = "HW_SECRET_KEY";
912
- const TOKEN_ACCOUNT = "HW_SECURITY_TOKEN";
913
- /** IAM endpoint host. */
914
- const IAM_HOST = "iam.myhuaweicloud.com";
915
1278
  /** Route the browser half reads status from and saves credentials to. */
916
1279
  const CREDENTIALS_PATH = "/api/aishell/credentials";
917
1280
  /** Route the browser half clears credentials through (fetch routes have no DELETE). */
918
1281
  const CLEAR_PATH = "/api/aishell/credentials/clear";
919
1282
  /**
920
- * Route the browser calls to decline the credential form.
1283
+ * Route the browser calls when the person cancels the credential form.
921
1284
  *
922
- * Separate from `clear`: clearing removes stored credentials, while this ends a
923
- * request without touching the store — a person who already has credentials for
924
- * something else, or who would rather set them up in Settings, must be able to
925
- * say "not now" without wiping anything.
1285
+ * Separate from `clear`: cancelling says "not now" without touching the store.
1286
+ * What it does record is the cancel itself, so the next `auth` call can tell an
1287
+ * unanswered request from a refused one and stop asking.
926
1288
  */
927
- const DISMISS_PATH = "/api/aishell/credentials/dismiss";
1289
+ const CANCEL_PATH = "/api/aishell/credentials/cancel";
928
1290
  /** Largest credential body accepted; a real payload is well under 1 KiB. */
929
1291
  const MAX_BODY_BYTES = 8 * 1024;
930
1292
  /**
931
1293
  * Verify credentials against Huawei Cloud IAM and return the account name.
932
1294
  *
933
- * Calls `GET https://iam.myhuaweicloud.com/v3/auth/domains` signed with the
934
- * AK/SK (and SecurityToken if present — STS temporary credentials carry the
935
- * same full IAM scope as the permanent credential that minted them). A 200
936
- * proves the credentials are valid and returns the domain (account) name;
937
- * a 401/403 rejects them.
1295
+ * Delegates to the shared `verify` module, so the form, the ops `auth` tool
1296
+ * and anything else that asks "are these credentials valid?" get the same
1297
+ * answer from the same endpoint (profile: `GET /v3/projects`, with the account
1298
+ * name read best-effort from `/v3/auth/domains`).
1299
+ *
1300
+ * ## Why not a local domains-only call
1301
+ *
1302
+ * This used to call `/v3/auth/domains` directly, because the only fact this
1303
+ * route needed was the account name shown in the composer chip. That made it a
1304
+ * second, narrower notion of validity: `/v3/projects` rejects a credential with
1305
+ * no visible project, while `/v3/auth/domains` accepts it — so the form said
1306
+ * "saved" for credentials the tools would then refuse. One verifier removes
1307
+ * that gap, and the project list it returns is exactly what a caller needs
1308
+ * before planning a deployment.
938
1309
  *
939
- * @returns the account name (domain name).
1310
+ * ## The region
1311
+ *
1312
+ * IAM is global: the region only routes to a regional replica and does not
1313
+ * scope the result. The chip's copy is fixed at `cn-north-4` for routing
1314
+ * purposes rather than configured, because verification must succeed even
1315
+ * before a person has chosen a region — and because a wrong region here would
1316
+ * report "invalid credentials" for what is really a typo'd region setting
1317
+ * elsewhere.
1318
+ *
1319
+ * @returns the account name (domain name), falling back to the account id.
940
1320
  * @throws Error with a user-readable message when verification fails.
941
1321
  */
942
- async function verifyCredentials(ak, sk, securityToken) {
943
- const path = "/v3/auth/domains";
944
- const signed = sign("GET", IAM_HOST, path, {}, "", {
1322
+ async function verifyCredentials$1(ak, sk, securityToken) {
1323
+ const result = await verifyCredentials({
945
1324
  ak,
946
1325
  sk,
947
- ...securityToken ? { securityToken } : {}
948
- });
949
- const resp = await fetch(`https://${IAM_HOST}${path}`, { headers: { ...signed } });
950
- if (resp.status === 401) throw new Error("凭据验证失败:华为云返回未授权(401),请检查 AK/SK 或 Security Token 是否正确");
951
- if (resp.status === 403) throw new Error("凭据验证失败:该凭据无 IAM 读取权限(403)");
952
- if (!resp.ok) throw new Error(`凭据验证失败:华为云返回 ${resp.status}`);
953
- const body = await resp.json();
954
- const name$1 = body.domains?.[0]?.name;
955
- if (!name$1) throw new Error("验证成功但未返回账号名");
956
- return name$1;
1326
+ ...securityToken === void 0 ? {} : { securityToken }
1327
+ }, { region: VERIFY_REGION });
1328
+ if (!result.ok) throw new Error(result.message);
1329
+ return result.account.name;
957
1330
  }
1331
+ /**
1332
+ * Region used to route the verification call.
1333
+ *
1334
+ * Not a setting: see {@link verifyCredentials}. Any region replica answers the
1335
+ * same question.
1336
+ */
1337
+ const VERIFY_REGION = "cn-north-4";
958
1338
  /** One JSON error response the browser half renders verbatim. */
959
1339
  function jsonError(status, message) {
960
1340
  return Response.json({
@@ -965,14 +1345,14 @@ function jsonError(status, message) {
965
1345
  /** Read a bounded JSON object body, or throw a user-readable message. */
966
1346
  async function readJsonBody(request) {
967
1347
  const text = await request.text();
968
- if (text.length > MAX_BODY_BYTES) throw new Error("请求体过大");
1348
+ if (text.length > MAX_BODY_BYTES) throw new Error("Request body too large.");
969
1349
  let parsed;
970
1350
  try {
971
1351
  parsed = JSON.parse(text);
972
1352
  } catch {
973
- throw new Error("请求体不是合法 JSON");
1353
+ throw new Error("Request body is not valid JSON.");
974
1354
  }
975
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("请求体必须是 JSON 对象");
1355
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("Request body must be a JSON object.");
976
1356
  return parsed;
977
1357
  }
978
1358
  /** Narrow one optional string field; absent and empty both read as undefined. */
@@ -991,7 +1371,7 @@ function createCredentialRoutes(deps) {
991
1371
  const { store, verify, recordStatus, hint, notifyChanged } = deps;
992
1372
  return {
993
1373
  get: () => Promise.resolve(Response.json({
994
- configured: Boolean(store.get(AK_ACCOUNT) && store.get(SK_ACCOUNT)),
1374
+ configured: hasStoredPair(store),
995
1375
  accountName: hint()
996
1376
  }, { headers: { "cache-control": "no-store" } })),
997
1377
  save: async (request) => {
@@ -1004,7 +1384,7 @@ function createCredentialRoutes(deps) {
1004
1384
  const ak = optionalString(body.accessKeyId);
1005
1385
  const sk = optionalString(body.secretAccessKey);
1006
1386
  const token = optionalString(body.securityToken);
1007
- if (!ak || !sk) return jsonError(400, "Access Key 与 Secret Key 均为必填");
1387
+ if (!ak || !sk) return jsonError(400, "Access Key and Secret Key are both required.");
1008
1388
  let accountName;
1009
1389
  try {
1010
1390
  accountName = await verify(ak, sk, token);
@@ -1021,14 +1401,13 @@ function createCredentialRoutes(deps) {
1021
1401
  }, { status: 422 });
1022
1402
  }
1023
1403
  try {
1024
- store.delete(AK_ACCOUNT);
1025
- store.delete(SK_ACCOUNT);
1026
- store.delete(TOKEN_ACCOUNT);
1027
- store.set(AK_ACCOUNT, ak);
1028
- store.set(SK_ACCOUNT, sk);
1029
- if (token) store.set(TOKEN_ACCOUNT, token);
1404
+ writeHuaweiCloud(store, {
1405
+ ak,
1406
+ sk,
1407
+ ...token === void 0 ? {} : { securityToken: token }
1408
+ });
1030
1409
  } catch (error) {
1031
- const message = `凭据已验证,但写入凭据存储失败:${error instanceof Error ? error.message : String(error)}`;
1410
+ const message = `Credential verified, but storing it failed: ${error instanceof Error ? error.message : String(error)}`;
1032
1411
  recordStatus([{
1033
1412
  op: "set",
1034
1413
  path: ["lastError"],
@@ -1059,9 +1438,7 @@ function createCredentialRoutes(deps) {
1059
1438
  });
1060
1439
  },
1061
1440
  clear: () => {
1062
- store.delete(AK_ACCOUNT);
1063
- store.delete(SK_ACCOUNT);
1064
- store.delete(TOKEN_ACCOUNT);
1441
+ clearCredentials(store);
1065
1442
  recordStatus([
1066
1443
  {
1067
1444
  op: "set",
@@ -1087,105 +1464,135 @@ const inject = ["settings", "connection"];
1087
1464
  function apply(ctx, config) {
1088
1465
  const store = createCredentialsStore();
1089
1466
  const ns = ctx.fiber.entry?.options.id;
1090
- /** Record the non-secret status the browser half reads; a refused write only logs. */
1467
+ let recordedStored = config.credentialsStored.get() === true;
1468
+ let recordedHint = config.accessKeyIdHint.get() || null;
1469
+ /**
1470
+ * The form request a tool call is currently blocked on.
1471
+ *
1472
+ * Held here rather than read from the document: the answer arrives over the
1473
+ * credential and cancel routes, and those need the same object the tool is
1474
+ * awaiting.
1475
+ */
1476
+ let pendingForm;
1477
+ /** Apply one batch of ops to the mirror. */
1478
+ const mirrorOps = (ops) => {
1479
+ for (const op of ops) if (op.path[0] === "credentialsStored") recordedStored = op.op === "set" && op.value === true;
1480
+ else if (op.path[0] === "accessKeyIdHint") recordedHint = op.op === "set" && typeof op.value === "string" && op.value.length > 0 ? op.value : null;
1481
+ };
1482
+ /** Record the non-secret status the browser half reads; a refused write is rolled back. */
1091
1483
  const recordStatus = (ops) => {
1092
- if (ns === void 0) return;
1484
+ if (ns === void 0) {
1485
+ mirrorOps(ops);
1486
+ return;
1487
+ }
1488
+ const before = {
1489
+ stored: recordedStored,
1490
+ hint: recordedHint
1491
+ };
1492
+ mirrorOps(ops);
1493
+ const after = {
1494
+ stored: recordedStored,
1495
+ hint: recordedHint
1496
+ };
1093
1497
  ctx.settings.mutate(ns, ops).catch((error) => {
1498
+ if (recordedStored === after.stored && recordedHint === after.hint) {
1499
+ recordedStored = before.stored;
1500
+ recordedHint = before.hint;
1501
+ }
1094
1502
  ctx.logger.warn(error);
1095
1503
  });
1096
1504
  };
1097
1505
  const routes = createCredentialRoutes({
1098
1506
  store,
1099
- verify: verifyCredentials,
1507
+ verify: verifyCredentials$1,
1100
1508
  recordStatus,
1101
- hint: () => config.accessKeyIdHint.get(),
1509
+ hint: () => recordedHint ?? "",
1102
1510
  notifyChanged: () => {
1103
1511
  ctx.emit("aishell/credentials-updated");
1104
1512
  }
1105
1513
  });
1106
- let settlePrompt;
1107
- /**
1108
- * End the open form, if any: clear the flag the browser renders from and
1109
- * hand the credential back to the waiting call.
1110
- */
1111
- const settleCredentialForm = (credentials) => {
1112
- const settle = settlePrompt;
1113
- settlePrompt = void 0;
1114
- recordStatus([{
1115
- op: "set",
1116
- path: ["credentialRequestSession"],
1117
- value: ""
1118
- }]);
1119
- settle?.(credentials);
1120
- };
1121
- ctx.effect(() => ctx.on("aishell/credential-request", (request) => {
1122
- settlePrompt?.(void 0);
1123
- settlePrompt = request.settle;
1124
- recordStatus([{
1125
- op: "set",
1126
- path: ["credentialRequestSession"],
1127
- value: request.sessionId ?? ""
1128
- }]);
1129
- request.signal?.addEventListener("abort", () => {
1130
- if (settlePrompt === request.settle) settleCredentialForm(void 0);
1131
- }, { once: true });
1132
- }), "aishell-credentials: credential form requests");
1133
- ctx.effect(() => ctx.on("aishell/credentials-updated", () => {
1134
- if (settlePrompt === void 0) return;
1135
- const ak$1 = store.get(AK_ACCOUNT);
1136
- const sk$1 = store.get(SK_ACCOUNT);
1137
- if (!ak$1 || !sk$1) return;
1138
- const securityToken = store.get(TOKEN_ACCOUNT);
1139
- settleCredentialForm({
1140
- ak: ak$1,
1141
- sk: sk$1,
1142
- ...securityToken === void 0 ? {} : { securityToken }
1143
- });
1144
- }), "aishell-credentials: resume the waiting call");
1514
+ const reconciler = createCredentialReconciler({
1515
+ verify: verifyCredentials$1,
1516
+ recordStatus,
1517
+ readStored: () => recordedStored,
1518
+ readHint: () => recordedHint,
1519
+ readPair: () => readStoredPair(store)
1520
+ });
1145
1521
  ctx.effect(() => ctx.connection.fetch.register({
1146
1522
  path: CREDENTIALS_PATH,
1147
1523
  methods: ["GET", "POST"],
1148
1524
  requestBody: "buffered",
1149
- fetch: (request) => request.method === "GET" ? routes.get() : routes.save(request)
1525
+ fetch: async (request) => {
1526
+ if (request.method === "GET") return reconciler.reconcile(), routes.get();
1527
+ const body = await request.text();
1528
+ const requestToken = readRequestToken(body);
1529
+ const response = await routes.save(new Request(request.url, {
1530
+ method: "POST",
1531
+ headers: request.headers,
1532
+ body
1533
+ }));
1534
+ if (response.ok && requestToken !== void 0 && pendingForm !== void 0 && pendingForm.request.token === requestToken) {
1535
+ const pending = pendingForm;
1536
+ pendingForm = void 0;
1537
+ pending.settle({ kind: "submitted" });
1538
+ }
1539
+ return response;
1540
+ }
1150
1541
  }), "aishell-credentials: credentials route");
1151
1542
  ctx.effect(() => ctx.connection.fetch.register({
1152
- path: CLEAR_PATH,
1543
+ path: CANCEL_PATH,
1153
1544
  methods: ["POST"],
1154
1545
  requestBody: "buffered",
1155
- fetch: routes.clear
1156
- }), "aishell-credentials: clear route");
1546
+ fetch: async (request) => {
1547
+ let body;
1548
+ try {
1549
+ body = await request.json();
1550
+ } catch {
1551
+ return Response.json({
1552
+ ok: false,
1553
+ error: "Request body is not valid JSON."
1554
+ }, { status: 400 });
1555
+ }
1556
+ const token = body?.token;
1557
+ if (typeof token !== "string" || token === "") return Response.json({
1558
+ ok: false,
1559
+ error: "token is required."
1560
+ }, { status: 400 });
1561
+ if (pendingForm !== void 0 && pendingForm.request.token === token) {
1562
+ const pending = pendingForm;
1563
+ pendingForm = void 0;
1564
+ pending.settle({ kind: "cancelled" });
1565
+ }
1566
+ return Response.json({ ok: true });
1567
+ }
1568
+ }), "aishell-credentials: cancel route");
1157
1569
  ctx.effect(() => ctx.connection.fetch.register({
1158
- path: DISMISS_PATH,
1570
+ path: CLEAR_PATH,
1159
1571
  methods: ["POST"],
1160
1572
  requestBody: "buffered",
1161
1573
  fetch: () => {
1162
- settleCredentialForm(void 0);
1163
- return Promise.resolve(Response.json({ ok: true }));
1574
+ reconciler.resetVerifyBaseline();
1575
+ return routes.clear();
1164
1576
  }
1165
- }), "aishell-credentials: dismiss route");
1166
- const stored = config.credentialsStored.get();
1167
- const ak = store.get(AK_ACCOUNT);
1168
- const sk = store.get(SK_ACCOUNT);
1169
- if (stored && !(ak && sk)) recordStatus([{
1170
- op: "set",
1171
- path: ["credentialsStored"],
1172
- value: false
1173
- }, {
1174
- op: "unset",
1175
- path: ["accessKeyIdHint"]
1176
- }]);
1177
- else if (!stored && ak && sk) recordStatus([{
1178
- op: "set",
1179
- path: ["credentialsStored"],
1180
- value: true
1181
- }]);
1182
- else if (ak && sk && config.accessKeyIdHint.get() === "") verifyCredentials(ak, sk, store.get(TOKEN_ACCOUNT)).then((accountName) => {
1183
- recordStatus([{
1577
+ }), "aishell-credentials: clear route");
1578
+ reconciler.reconcile();
1579
+ const reconcileTimer = setInterval(reconciler.reconcile, 3e4);
1580
+ ctx.effect(() => () => clearInterval(reconcileTimer), "aishell-credentials: status reconcile timer");
1581
+ registerAuthTool(ctx, store, { requestForm: (sessionId) => {
1582
+ if (ns === void 0) return void 0;
1583
+ pendingForm?.settle({ kind: "cancelled" });
1584
+ const pending = formRequest(sessionId);
1585
+ pendingForm = pending;
1586
+ ctx.settings.mutate(ns, [{
1184
1587
  op: "set",
1185
- path: ["accessKeyIdHint"],
1186
- value: accountName
1187
- }]);
1188
- }).catch(() => {});
1588
+ path: [FORM_REQUEST_FIELD],
1589
+ value: pending.encoded
1590
+ }]).catch((error) => {
1591
+ ctx.logger.warn(error);
1592
+ if (pendingForm === pending) pending.settle({ kind: "cancelled" });
1593
+ });
1594
+ return pending.outcome;
1595
+ } });
1189
1596
  ctx.effect(() => ctx.settings.configure({ auto: false }, ctx.fiber));
1190
1597
  }
1191
1598