@huaweidevtools/aishell-dsh-client-credentials 0.0.1-beta.3 → 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/client.js CHANGED
@@ -949,11 +949,12 @@ async function postJson(route, t, body) {
949
949
  * empty string as absent anyway, so sending it would only make the wire shape
950
950
  * depend on which form was used.
951
951
  */
952
- function saveCredential(t, accessKeyId, secretAccessKey, securityToken) {
952
+ function saveCredential(t, accessKeyId, secretAccessKey, securityToken, requestToken) {
953
953
  return postJson(CREDENTIALS_ROUTE, t, {
954
954
  accessKeyId,
955
955
  secretAccessKey,
956
- ...securityToken === void 0 ? {} : { securityToken }
956
+ ...securityToken === void 0 ? {} : { securityToken },
957
+ ...requestToken === void 0 ? {} : { requestToken }
957
958
  });
958
959
  }
959
960
  /**
@@ -1005,15 +1006,23 @@ function apply(ctx) {
1005
1006
  derive();
1006
1007
  const publishCredentialForm = ctx.uiSession.registerPendingInteraction(() => 0);
1007
1008
  const visibility = createCredentialFormVisibility((interaction) => publishCredentialForm(interaction, () => Promise.resolve()));
1009
+ /** The last request the browser acted on, so a re-read is not a re-open. */
1008
1010
  let lastRequestToken;
1011
+ /**
1012
+ * The token of the request this form is currently answering, if any.
1013
+ *
1014
+ * A chip-opened form has none: nothing asked for it, so a cancel must not
1015
+ * report one — a submit or cancel names a request, and there is no request to
1016
+ * name.
1017
+ */
1018
+ let pendingRequestToken;
1009
1019
  const applyFormRequest = () => {
1010
1020
  const request = decodeRequest(form.getSnapshot().value?.credentialFormRequest);
1011
1021
  if (request === void 0 || request.token === lastRequestToken) return;
1012
1022
  lastRequestToken = request.token;
1013
- visibility.open(request.sessionId);
1014
1023
  pendingRequestToken = request.token;
1024
+ visibility.open(request.sessionId);
1015
1025
  };
1016
- let pendingRequestToken;
1017
1026
  ctx.effect(() => form.subscribe(applyFormRequest), "aishell-credentials: form requests");
1018
1027
  applyFormRequest();
1019
1028
  ctx.effect(() => () => {
@@ -1070,7 +1079,7 @@ function apply(ctx) {
1070
1079
  locale: NS,
1071
1080
  inject: () => ({
1072
1081
  hooks: { credentials: status },
1073
- save: (ak, sk, token) => saveCredential(t, ak, sk, token),
1082
+ save: (ak, sk, token) => saveCredential(t, ak, sk, token, pendingRequestToken),
1074
1083
  clear: () => clearBothStores(t),
1075
1084
  close: () => {
1076
1085
  visibility.close();
package/lib/index.js CHANGED
@@ -963,7 +963,7 @@ function registerAuthTool(ctx, store, deps) {
963
963
  },
964
964
  timeoutMs: AUTH_TIMEOUT_MS,
965
965
  async execute(_args, exec) {
966
- return await runAuth(store, deps, sessionOf(exec));
966
+ return await runAuth(store, deps, sessionOf(exec), exec.signal);
967
967
  }
968
968
  });
969
969
  return dispose;
@@ -991,24 +991,75 @@ function sessionOf(exec) {
991
991
  * reason is what tells them what to correct.
992
992
  *
993
993
  * @param store - the credential store to read.
994
- * @param deps - host controls: open the form, take a cancellation.
994
+ * @param deps - host controls: open the form and wait for its answer.
995
995
  * @param sessionId - the conversation to open the form in; `undefined` when the
996
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.
997
998
  * @returns the account, its projects, and whether the credentials are temporary.
998
- * @throws with an actionable message in every other case.
999
+ * @throws when the person cancels, or when no form can be shown at all.
999
1000
  */
1000
- async function runAuth(store, deps, sessionId) {
1001
- const pair = readStoredPair(store);
1002
- if (deps.takeCancellation() !== void 0) throw new Error("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.");
1003
- if (pair === void 0) {
1004
- openForm(deps, sessionId);
1005
- throw new Error("Not authenticated with Huawei Cloud IAM. The credential form has been opened — ask the user to enter an access key and secret key there, then call auth again.");
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
1006
  }
1007
- const result = await verifyCredentials(pair, { region: VERIFY_REGION$1 });
1008
- if (!result.ok) {
1009
- openForm(deps, sessionId);
1010
- throw new Error(`The stored credentials were rejected and the credential form has been opened again. Huawei Cloud said: ${result.message}`);
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);
1011
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) {
1012
1063
  return {
1013
1064
  authenticated: true,
1014
1065
  account: {
@@ -1024,21 +1075,6 @@ async function runAuth(store, deps, sessionId) {
1024
1075
  };
1025
1076
  }
1026
1077
  /**
1027
- * Ask for the form, when there is a conversation to put it in.
1028
- *
1029
- * A call with no agent has no session, and `conversation.composer` is
1030
- * session-scoped — a form without a session has nowhere to render. The failure
1031
- * message still tells the user what to do, so this is a best-effort improvement
1032
- * rather than the remedy.
1033
- *
1034
- * @param deps - host controls.
1035
- * @param sessionId - the conversation, or `undefined`.
1036
- */
1037
- function openForm(deps, sessionId) {
1038
- if (sessionId === void 0 || sessionId === "") return;
1039
- deps.requestForm({ sessionId });
1040
- }
1041
- /**
1042
1078
  * The text the model reads.
1043
1079
  *
1044
1080
  * A short summary then the project table: the summary answers the question the
@@ -1117,9 +1153,14 @@ function formRequest(sessionId) {
1117
1153
  token: `${Date.now().toString(36)}-${String(nextToken)}`,
1118
1154
  sessionId
1119
1155
  };
1156
+ const completion = Promise.withResolvers();
1120
1157
  return {
1121
1158
  request,
1122
- encoded: encodeRequest(request)
1159
+ encoded: encodeRequest(request),
1160
+ outcome: completion.promise,
1161
+ settle: (outcome) => {
1162
+ completion.resolve(outcome);
1163
+ }
1123
1164
  };
1124
1165
  }
1125
1166
  /** Source of tokens; module-scoped so it is per-host-process. */
@@ -1205,6 +1246,25 @@ function createCredentialReconciler(deps) {
1205
1246
  //#endregion
1206
1247
  //#region src/index.ts
1207
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
+ /**
1208
1268
  * Settings schema for this entry. Secrets are deliberately absent: they travel
1209
1269
  * over the credential route into the credential store, never through a
1210
1270
  * settings document.
@@ -1213,8 +1273,7 @@ const Config = Schema.object({
1213
1273
  credentialsStored: Schema.boolean().default(false).volatile(),
1214
1274
  accessKeyIdHint: Schema.string().default("").volatile(),
1215
1275
  lastError: Schema.string().default("").volatile(),
1216
- credentialFormRequest: Schema.string().default("").volatile(),
1217
- credentialFormCancelled: Schema.string().default("").volatile()
1276
+ credentialFormRequest: Schema.string().default("").volatile()
1218
1277
  });
1219
1278
  /** Route the browser half reads status from and saves credentials to. */
1220
1279
  const CREDENTIALS_PATH = "/api/aishell/credentials";
@@ -1408,14 +1467,13 @@ function apply(ctx, config) {
1408
1467
  let recordedStored = config.credentialsStored.get() === true;
1409
1468
  let recordedHint = config.accessKeyIdHint.get() || null;
1410
1469
  /**
1411
- * The token of the last form request the person cancelled.
1470
+ * The form request a tool call is currently blocked on.
1412
1471
  *
1413
- * Kept here rather than read back from the document: `mutate` is async, so a
1414
- * read would race the write that recorded the cancel, and a token that
1415
- * outlived its read would answer a later `auth` call instead of the one that
1416
- * asked.
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.
1417
1475
  */
1418
- let pendingCancellation;
1476
+ let pendingForm;
1419
1477
  /** Apply one batch of ops to the mirror. */
1420
1478
  const mirrorOps = (ops) => {
1421
1479
  for (const op of ops) if (op.path[0] === "credentialsStored") recordedStored = op.op === "set" && op.value === true;
@@ -1464,7 +1522,22 @@ function apply(ctx, config) {
1464
1522
  path: CREDENTIALS_PATH,
1465
1523
  methods: ["GET", "POST"],
1466
1524
  requestBody: "buffered",
1467
- fetch: (request) => request.method === "GET" ? (reconciler.reconcile(), 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
+ }
1468
1541
  }), "aishell-credentials: credentials route");
1469
1542
  ctx.effect(() => ctx.connection.fetch.register({
1470
1543
  path: CANCEL_PATH,
@@ -1485,15 +1558,11 @@ function apply(ctx, config) {
1485
1558
  ok: false,
1486
1559
  error: "token is required."
1487
1560
  }, { status: 400 });
1488
- pendingCancellation = token;
1489
- if (ns === void 0) return Response.json({ ok: true });
1490
- ctx.settings.mutate(ns, [{
1491
- op: "set",
1492
- path: ["credentialFormCancelled"],
1493
- value: token
1494
- }]).catch((error) => {
1495
- ctx.logger.warn(error);
1496
- });
1561
+ if (pendingForm !== void 0 && pendingForm.request.token === token) {
1562
+ const pending = pendingForm;
1563
+ pendingForm = void 0;
1564
+ pending.settle({ kind: "cancelled" });
1565
+ }
1497
1566
  return Response.json({ ok: true });
1498
1567
  }
1499
1568
  }), "aishell-credentials: cancel route");
@@ -1509,24 +1578,21 @@ function apply(ctx, config) {
1509
1578
  reconciler.reconcile();
1510
1579
  const reconcileTimer = setInterval(reconciler.reconcile, 3e4);
1511
1580
  ctx.effect(() => () => clearInterval(reconcileTimer), "aishell-credentials: status reconcile timer");
1512
- registerAuthTool(ctx, store, {
1513
- requestForm: ({ sessionId }) => {
1514
- const { encoded } = formRequest(sessionId);
1515
- if (ns === void 0) return;
1516
- ctx.settings.mutate(ns, [{
1517
- op: "set",
1518
- path: [FORM_REQUEST_FIELD],
1519
- value: encoded
1520
- }]).catch((error) => {
1521
- ctx.logger.warn(error);
1522
- });
1523
- },
1524
- takeCancellation: () => {
1525
- const token = pendingCancellation;
1526
- pendingCancellation = void 0;
1527
- return token;
1528
- }
1529
- });
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, [{
1587
+ op: "set",
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
+ } });
1530
1596
  ctx.effect(() => ctx.settings.configure({ auto: false }, ctx.fiber));
1531
1597
  }
1532
1598
 
@@ -58,6 +58,7 @@
58
58
  * @module @huaweidevtools/aishell-dsh-client-credentials/auth-tool
59
59
  */
60
60
  import type { Context } from '@deepseek-ai/cordis';
61
+ import type { FormOutcome } from './form-request.ts';
61
62
  import type { CredentialsStore } from '@huaweidevtools/aishell-dsh-credentials-store';
62
63
  /** Model-facing name. Prefixed so it cannot collide with another cloud plugin. */
63
64
  export declare const AUTH_TOOL_NAME = "aishell__auth";
@@ -71,22 +72,17 @@ export declare const AUTH_TOOL_NAME = "aishell__auth";
71
72
  */
72
73
  export interface AuthToolDeps {
73
74
  /**
74
- * Ask the browser to open the credential form in one session.
75
+ * Open the credential form in one session and wait for the person.
75
76
  *
76
- * Fire-and-forget: a tool call cannot be paused for a human, so this opens the
77
- * form and the tool fails. The model calls again once the person is done.
78
- */
79
- readonly requestForm: (request: {
80
- readonly sessionId: string;
81
- }) => void;
82
- /**
83
- * Take the token of the last cancelled form request, clearing it.
77
+ * Resolves when they submit or cancel — never on a timeout. A person may be
78
+ * fetching a key from the console; a form that gives up while they are typing
79
+ * is worse than a call that waits. The call's own cancellation is the way out,
80
+ * and the caller passes its signal for that.
84
81
  *
85
- * Clearing on read is what makes it a message rather than a state: a cancel
86
- * answers the one call that asked, and a later call must not inherit the
87
- * refusal.
82
+ * `undefined` when there is no session to render the form in, which is the
83
+ * case a call running outside an agent hits.
88
84
  */
89
- readonly takeCancellation: () => string | undefined;
85
+ readonly requestForm: (sessionId: string) => Promise<FormOutcome> | undefined;
90
86
  }
91
87
  /**
92
88
  * Register the `auth` tool on the host's tool registry.
@@ -52,6 +52,23 @@ export interface CredentialFormRequest {
52
52
  }
53
53
  /** Writes one path-addressed edit into this entry's settings document. */
54
54
  export type RecordField = (value: string) => void;
55
+ /**
56
+ * How one form request ended.
57
+ *
58
+ * `submitted` carries no credential: the form posts to the credential route,
59
+ * which verifies and writes the store, so the tool reads the store afterwards.
60
+ * Nothing about this answer is secret, which is what lets it cross the host
61
+ * without a second review of the leak surface.
62
+ */
63
+ export type FormOutcome =
64
+ /** The person submitted. The store may or may not hold a usable pair. */
65
+ {
66
+ readonly kind: 'submitted';
67
+ }
68
+ /** The person cancelled. */
69
+ | {
70
+ readonly kind: 'cancelled';
71
+ };
55
72
  /**
56
73
  * Build a request for one session, minting its token.
57
74
  *
@@ -62,10 +79,21 @@ export type RecordField = (value: string) => void;
62
79
  * @param sessionId - the conversation the form should render in.
63
80
  * @returns the request, and its encoded form for the settings document.
64
81
  */
65
- export declare function formRequest(sessionId: string): {
82
+ export declare function formRequest(sessionId: string): PendingFormRequest;
83
+ /**
84
+ * One request, and the promise its waiting caller is blocked on.
85
+ *
86
+ * The token is what a submit or a cancel names when it answers, so an answer
87
+ * for a superseded request cannot settle the current one.
88
+ */
89
+ export interface PendingFormRequest {
66
90
  readonly request: CredentialFormRequest;
67
91
  readonly encoded: string;
68
- };
92
+ /** Resolves when the person submits or cancels. */
93
+ readonly outcome: Promise<FormOutcome>;
94
+ /** Answer this request. Idempotent: a second call is ignored by `Promise`. */
95
+ readonly settle: (outcome: FormOutcome) => void;
96
+ }
69
97
  /**
70
98
  * Serialize a request for the settings document.
71
99
  *
@@ -40,15 +40,6 @@ export interface Config {
40
40
  * channel.
41
41
  */
42
42
  credentialFormRequest: Volatile<string>;
43
- /**
44
- * Token of the form request the person cancelled, or `''`.
45
- *
46
- * Written by the cancel route, read (and cleared) by `aishell__auth`. It
47
- * exists so a model whose call failed does not retry forever: without it, the
48
- * only observable difference between "the person said no" and "the person has
49
- * not answered yet" is nothing.
50
- */
51
- credentialFormCancelled: Volatile<string>;
52
43
  }
53
44
  /**
54
45
  * Settings schema for this entry. Secrets are deliberately absent: they travel
@@ -60,13 +51,11 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
60
51
  accessKeyIdHint: z<string, string, "volatile-defined">;
61
52
  lastError: z<string, string, "volatile-defined">;
62
53
  credentialFormRequest: z<string, string, "volatile-defined">;
63
- credentialFormCancelled: z<string, string, "volatile-defined">;
64
54
  }>>, Schemastery.ObjectT<NoInfer<{
65
55
  credentialsStored: z<boolean, boolean, "volatile-defined">;
66
56
  accessKeyIdHint: z<string, string, "volatile-defined">;
67
57
  lastError: z<string, string, "volatile-defined">;
68
58
  credentialFormRequest: z<string, string, "volatile-defined">;
69
- credentialFormCancelled: z<string, string, "volatile-defined">;
70
59
  }>>, "plain">;
71
60
  declare module '@deepseek-ai/cordis' {
72
61
  interface Events {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@huaweidevtools/aishell-dsh-client-credentials",
3
3
  "description": "AI Shell credentials — chip-opened web form for storing Huawei Cloud AK/SK in the credential store",
4
- "version": "0.0.1-beta.3",
4
+ "version": "0.0.1-beta.4",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -41,7 +41,7 @@
41
41
  },
42
42
  "license": "Apache-2.0",
43
43
  "dependencies": {
44
- "@huaweidevtools/aishell-dsh-credentials-store": "0.0.1-beta.3"
44
+ "@huaweidevtools/aishell-dsh-credentials-store": "0.0.1-beta.4"
45
45
  },
46
46
  "peerDependencies": {
47
47
  "@deepseek-ai/cordis": "^4.0.4",