@aliyunrds/ctxdb-dsh 0.0.1-beta.0 → 0.0.1-beta.3

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/README.md CHANGED
@@ -13,30 +13,40 @@
13
13
 
14
14
  打开 **设置 → ContextDB**,在 **Site** 选择工作空间所在站点,再选择一种认证方式。
15
15
 
16
- - 选择 **Device Code(浏览器登录)** 后,点击 **Start authorization**,在浏览器里选择工作空间并确认授权。如果浏览器未自动打开,点击 **Open authorization page**。授权成功后,设置页会显示工作空间和授权成员的 ID,同一站点可点 **Reauthorize** 重新授权。
16
+ - 选择 **Device Code(浏览器登录)** 后,点击 **Start authorization**,在浏览器里选择工作空间并确认授权。如果浏览器未自动打开,点击 **Open authorization page**。从 API Key 切换时,原连接会一直可用,直到浏览器授权成功。授权成功后,设置页会显示工作空间和授权成员的 ID,同一站点可点 **Reauthorize** 重新授权。
17
17
  - 已有工作空间的 API Key 时,选择 **API Key**,粘贴并点击 **Save API Key**。DSH 会在本机保存凭据。更换时输入新 Key,再点 **Replace API Key**。
18
18
 
19
19
  Device Code 模式下,也可以在对话中输入 `/ctxdb-login`(中国站)或 `/ctxdb-login intl`(国际站)。插件会尝试打开系统浏览器,并在对话里显示授权链接和设备码。
20
20
 
21
21
  ## 在终端使用
22
22
 
23
- 把插件装到独立的 `headless` profile,运行一次配置命令。中国站用 `--site cn`,国际站用 `--site intl`。
23
+ 在 `--profile` 后填要连接 ContextDB 的 DSH profile 名。下面以 `web` 为例,也可以指定 `headless` 或自建 profile。配置 `desktop` 时,先打开一次桌面客户端完成初始化,再完全退出,使用 Desktop 自带的 `dsh` 命令。
24
24
 
25
25
  ```sh
26
- dsh plugin --profile headless add /path/to/aliyunrds-ctxdb-dsh-0.0.1-beta.0.tgz
27
- dsh plugin --profile headless exec ctxdb-dsh configure --site cn
28
- dsh headless '用 ContextDB 列出可访问的知识库'
26
+ dsh plugin --profile web add /path/to/aliyunrds-ctxdb-dsh-0.0.1-beta.3.tgz
29
27
  ```
30
28
 
31
- 按提示输入 ContextDB API Key。输入时终端不会回显,DSH 会保存凭据,之后直接运行 `dsh headless` 即可。再次运行配置命令可以更换 Key。CI 可以用 `--key-stdin` 从管道传入 Key,例如 `printf '%s\n' "$CONTEXTDB_API_KEY" | dsh plugin --profile headless exec ctxdb-dsh configure --site cn --key-stdin`。
29
+ **Device Code 登录**。中国站用 `cn`,国际站用 `intl`。
32
30
 
33
- 也可以用 Device Code 连接。
31
+ ```sh
32
+ dsh plugin --profile web exec ctxdb-dsh configure --site cn --device-code
33
+ ```
34
+
35
+ 命令会尝试打开浏览器,并在终端显示授权链接和用户码。也可以在另一台设备上打开链接。授权成功后,登录会话保存在所选 profile 里。按 Ctrl+C 可取消并保留原连接。
36
+
37
+ **API Key 配置**。运行下面的命令,根据提示输入 Key,终端会隐藏输入。再次运行可以更换该 profile 的 Key。
38
+
39
+ ```sh
40
+ dsh plugin --profile web exec ctxdb-dsh configure --site cn
41
+ ```
42
+
43
+ 脚本或 CI 可以通过标准输入传入 Key。
34
44
 
35
45
  ```sh
36
- dsh plugin --profile headless exec ctxdb-dsh configure --site cn --device-code
46
+ printf '%s\n' "$CONTEXTDB_API_KEY" | dsh plugin --profile web exec ctxdb-dsh configure --site cn --key-stdin
37
47
  ```
38
48
 
39
- 命令会显示授权链接和用户码,并尝试打开浏览器。也可以在另一台设备上打开链接,选择工作空间并确认授权。命令会等待授权完成,然后切换到 Device Code。等待期间可以按 Ctrl+C 取消。
49
+ API Key 由 DSH 原生凭据服务保存,每个 profile 和站点使用独立的凭据引用。如果 `ctxdb-dsh` 已在 PATH 中,也可以直接运行 `ctxdb-dsh configure --profile web --site cn --device-code`,或用同一写法输入 API Key。
40
50
 
41
51
  ## 在对话中使用
42
52
 
@@ -59,7 +69,7 @@ dsh plugin --profile headless exec ctxdb-dsh configure --site cn --device-code
59
69
 
60
70
  默认开启自动召回。你发出消息时,插件会用消息文本在 ContextDB 查找相关记忆,把找到的片段补充给助手,供本轮回答参考。你也可以让助手按需查知识库。ContextDB 按当前授权返回可访问的内容。
61
71
 
62
- 自动采集默认开启。连接工作空间后,插件会在符合条件的对话轮次结束时,将用户和助手的对话文字发送到 ContextDB,用于生成今后可检索的记忆。可随时在 **设置 → ContextDB → Context settings** 中关闭自动采集或自动召回。
72
+ 自动采集默认开启。连接工作空间后,插件会在符合条件的对话轮次结束时,将用户和助手的对话文字发送到 ContextDB,用于生成今后可检索的记忆。调用 ContextDB 写入工具的轮次会跳过自动采集,例如删除记忆、上传文档或编辑 Wiki。可随时在 **设置 → ContextDB → Context settings** 中关闭自动采集或自动召回。
63
73
 
64
74
  在 **Memory scope** 可以设置采集写入的标识。`user_id` 默认为 `default`,`agent_id` 默认为 `dsh`,`app_id` 默认使用当前 DSH 工作区名称。填写自定义的 `app_id` 后点击 **Save memory scope** 生效。清空输入框再保存会恢复默认。
65
75
 
package/dist/client.js CHANGED
@@ -325,7 +325,7 @@ function SettingsPage({ request }) {
325
325
  setStatus(result.status);
326
326
  if (result.prompt || !result.status.login.pendingId) setPrompt(result.prompt);
327
327
  if (result.prompt && result.prompt.id === result.status.login.pendingId) authorizationPage?.open(result.prompt.url);
328
- if (["save-key", "use-login", "start"].includes(input.action)) setDraft(void 0);
328
+ if (["save-key", "use-login"].includes(input.action)) setDraft(void 0);
329
329
  } catch (failure) {
330
330
  if (!signal.aborted) setError(failure.message);
331
331
  } finally {
@@ -340,9 +340,9 @@ function SettingsPage({ request }) {
340
340
  password.current.value = "";
341
341
  void change({ action: "save-key", site, apiKey });
342
342
  }
343
- const mode = draft?.mode ?? status?.mode;
344
- const site = draft?.site ?? status?.site;
345
343
  const pendingId = status?.login.pendingId;
344
+ const mode = draft?.mode ?? (pendingId ? "oauth" : status?.mode);
345
+ const site = draft?.site ?? status?.login.pendingSite ?? status?.site;
346
346
  const userPrompt = prompt?.id === pendingId ? prompt : void 0;
347
347
  const connected = status?.login.connection?.ready ? status.login.connection : void 0;
348
348
  const canReauthorize = Boolean(connected && site === status.login.site);
@@ -1,9 +1,10 @@
1
1
  import { createRequire as __ctxdbCreateRequire } from "node:module"; const require = __ctxdbCreateRequire(import.meta.url);
2
2
 
3
3
  // ../../plugins/dsh-plugins/src/configure-host.ts
4
- import { readFileSync as readFileSync2 } from "node:fs";
4
+ import { readFileSync as readFileSync2, realpathSync } from "node:fs";
5
5
  import { createRequire } from "node:module";
6
- import { join } from "node:path";
6
+ import { basename, dirname as dirname3, join } from "node:path";
7
+ import { pathToFileURL } from "node:url";
7
8
 
8
9
  // ../shared/src/auth-config.ts
9
10
  import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
@@ -131,12 +132,20 @@ function managedCredentialRef(configPath, site) {
131
132
  }
132
133
 
133
134
  // ../../plugins/dsh-plugins/src/configure-host.ts
134
- var inject = ["profileContext", "credentials", "appReady", "appExit"];
135
- async function configure(ctx, site) {
136
- const profile = ctx.profileContext;
137
- if (profile.name !== "headless" || site !== "cn" && site !== "intl") {
138
- throw new Error("Expected the headless profile and site cn or intl.");
135
+ var inject = ["profileContext", "appReady", "appExit"];
136
+ async function configure(ctx, dir, site) {
137
+ if (realpathSync(dir) !== process.cwd() || basename(dirname3(dir)) !== "profiles" || site !== "cn" && site !== "intl") {
138
+ throw new Error("Expected the DSH-selected profile and site cn or intl.");
139
139
  }
140
+ const profile = {
141
+ ...ctx.profileContext,
142
+ name: basename(dir),
143
+ dir,
144
+ home: dirname3(dirname3(dir)),
145
+ patchPath: join(dir, "cordis.patch.yml"),
146
+ overlays: []
147
+ };
148
+ process.env.DSH_HOME = profile.home;
140
149
  const key = readFileSync2(0, "utf8");
141
150
  if (!key || /\s/.test(key)) throw new Error("Invalid ContextDB API Key.");
142
151
  const configPath = join(profile.dir, "aliyun-contextdb", "ctxdb.json");
@@ -146,7 +155,15 @@ async function configure(ctx, site) {
146
155
  const { parseDocument, isSeq, isMap, isScalar } = requireHost("yaml");
147
156
  const { load } = requireHost("js-yaml");
148
157
  const { entryListSchema } = requireHost("@deepseek-ai/cordis-plugin-include");
149
- const { loadProfileDirectory, readProfilePatches, composeEntries } = requireHost("@deepseek-ai/dsh-app-boot");
158
+ const {
159
+ boot,
160
+ loadLayeredEnv,
161
+ loadProfileDirectory,
162
+ readProfilePatches,
163
+ composeEntries,
164
+ PluginPackages,
165
+ createRuntimeResolution
166
+ } = requireHost("@deepseek-ai/dsh-app-boot");
150
167
  const { writeFileAtomic } = requireHost("@deepseek-ai/dsh-atomic-write");
151
168
  let before;
152
169
  try {
@@ -158,45 +175,69 @@ async function configure(ctx, site) {
158
175
  const document = parseDocument(before, {
159
176
  customTags: [{ tag: "tag:yaml.org,2002:js", resolve: (value) => value }]
160
177
  });
161
- if (document.errors.length) throw new Error("Invalid headless profile YAML.");
178
+ if (document.errors.length) throw new Error("Invalid DSH profile YAML.");
162
179
  if (document.contents === null) document.contents = document.createNode([]);
163
- if (!isSeq(document.contents)) throw new Error("Expected a list of headless profile patches.");
164
- const credentialRow = document.contents.items.findLast((row) => isMap(row) && row.get("id") === "credentials" && !row.has("insert"));
165
- if (credentialRow) {
166
- const disabled = credentialRow.get("disabled", true);
167
- if (isScalar(disabled)) {
168
- disabled.tag = void 0;
169
- disabled.value = false;
170
- } else credentialRow.set("disabled", false);
171
- } else {
172
- document.contents.flow = false;
173
- document.add({ id: "credentials", disabled: false });
174
- }
175
- const nextPatch = String(document);
176
- const installed = loadProfileDirectory("dsh", profile.dir, profile.installAnchor);
177
- const layers = readProfilePatches("dsh", { ...profile, overlays: [] }, {
178
- ...installed,
179
- patches: load(nextPatch, { schema: entryListSchema })
180
- });
181
- const entries = composeEntries([layers]);
182
- const credentialsEntry = entries.find((row) => row.id === "credentials");
180
+ if (!isSeq(document.contents)) throw new Error("Expected a list of DSH profile patches.");
181
+ const installed = loadProfileDirectory("dsh", dir, profile.installAnchor);
182
+ const findProvider = (patches) => composeEntries([readProfilePatches("dsh", profile, { ...installed, patches })]).find((row) => row.id === "credentials");
183
+ let credentialsEntry = findProvider(installed.patches);
184
+ let nextPatch = before;
183
185
  if (!credentialsEntry || credentialsEntry.disabled) {
184
- process.stderr.write("The DSH home patch overrides the headless credentials setting. Enable credentials there before running configure.\n");
186
+ const profileRows = composeEntries([...installed.layers.map((layer) => layer.patches), installed.patches]);
187
+ const hasProvider = profileRows.some((row) => row.id === "credentials");
188
+ const credentialRow = document.contents.items.findLast((row) => isMap(row) && row.get("id") === "credentials" && !row.has("insert"));
189
+ if (!hasProvider) {
190
+ document.contents.flow = false;
191
+ document.add({ insert: [{ id: "credentials", name: "@deepseek-ai/dsh-credentials-local" }] });
192
+ } else if (credentialRow) {
193
+ const disabled = credentialRow.get("disabled", true);
194
+ if (isScalar(disabled)) {
195
+ disabled.tag = void 0;
196
+ disabled.value = false;
197
+ } else credentialRow.set("disabled", false);
198
+ } else {
199
+ document.contents.flow = false;
200
+ document.add({ id: "credentials", disabled: false });
201
+ }
202
+ nextPatch = String(document);
203
+ credentialsEntry = findProvider(load(nextPatch, { schema: entryListSchema }));
204
+ }
205
+ if (!credentialsEntry || credentialsEntry.disabled === true) {
206
+ process.stderr.write("The target profile needs an enabled credentials provider. Check its bundles and the DSH home patch.\n");
185
207
  throw new Error("Credentials disabled outside this profile.");
186
208
  }
187
- await ctx.credentials.set(credentialRef, key);
209
+ const providerBase = pathToFileURL(join(profile.dir, "package.json")).href;
210
+ const resolution = await createRuntimeResolution({ installAnchor: profile.installAnchor, profile: installed, home: profile.home });
211
+ const credentialHost = await boot(
212
+ "dsh",
213
+ join(ctx.profileContext.dir, "credentials-root.yml"),
214
+ [{ insert: [credentialsEntry] }],
215
+ async (host) => {
216
+ host.provide("profileContext", { ...profile, startedBundles: installed.layers.map((layer) => layer.packageName) });
217
+ host.provide("launchEnvironment", loadLayeredEnv("dsh", profile.dir));
218
+ await host.plugin(PluginPackages, { resolution });
219
+ },
220
+ providerBase
221
+ );
222
+ try {
223
+ const credentials = credentialHost.get("credentials");
224
+ if (!credentials) throw new Error("The target profile's credential provider did not activate.");
225
+ await credentials.set(credentialRef, key);
226
+ } finally {
227
+ await credentialHost.fiber.dispose();
228
+ }
188
229
  if (before !== nextPatch) await writeFileAtomic(profile.patchPath, nextPatch, { mode: 384 });
189
230
  updateAuthConfig(configPath, (raw) => {
190
231
  raw.dsh_auth = { mode: "api-key", site, credentialRef };
191
232
  });
192
- console.log(`ContextDB API Key saved for headless (${site}). Run dsh headless "your task".`);
233
+ console.log(`ContextDB API Key saved for ${profile.name} (${site}).`);
193
234
  }
194
235
  function apply(ctx, config) {
195
236
  ctx.appReady.onReady(() => {
196
- void configure(ctx, config.site).then(
237
+ void configure(ctx, config.profileDir, config.site).then(
197
238
  () => ctx.appExit(0),
198
239
  () => {
199
- process.stderr.write("Could not configure ContextDB. Check the DSH credential store and headless profile permissions, then retry.\n");
240
+ process.stderr.write("Could not configure ContextDB. Check the DSH credential store and target profile permissions, then retry.\n");
200
241
  ctx.appExit(1);
201
242
  }
202
243
  );
package/dist/configure.js CHANGED
@@ -3,11 +3,12 @@ import { createRequire as __ctxdbCreateRequire } from "node:module"; const requi
3
3
 
4
4
  // ../../plugins/dsh-plugins/src/configure.ts
5
5
  import { spawnSync } from "node:child_process";
6
- import { mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
7
- import { tmpdir } from "node:os";
8
- import { basename, dirname as dirname6, join as join5 } from "node:path";
6
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3, mkdtempSync, readFileSync as readFileSync3, realpathSync, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
7
+ import { homedir as homedir2, tmpdir } from "node:os";
8
+ import { basename, dirname as dirname6, join as join5, resolve as resolve2 } from "node:path";
9
9
  import { createInterface } from "node:readline/promises";
10
10
  import { Writable } from "node:stream";
11
+ import { fileURLToPath } from "node:url";
11
12
  import { parseArgs } from "node:util";
12
13
 
13
14
  // src/lib/open-browser.ts
@@ -22,19 +23,19 @@ function openBrowser(url) {
22
23
  }
23
24
  const os = platform();
24
25
  const command = os === "darwin" ? { file: "open", args: [url] } : os === "win32" ? { file: "rundll32.exe", args: ["url.dll,FileProtocolHandler", url] } : { file: "xdg-open", args: [url] };
25
- return new Promise((resolve2) => {
26
+ return new Promise((resolve3) => {
26
27
  try {
27
28
  const child = spawn(command.file, command.args, { detached: true, stdio: "ignore", windowsHide: true, shell: false });
28
- const timer = setTimeout(() => resolve2(true), 2e3);
29
+ const timer = setTimeout(() => resolve3(true), 2e3);
29
30
  const finish = (opened) => {
30
31
  clearTimeout(timer);
31
- resolve2(opened);
32
+ resolve3(opened);
32
33
  };
33
34
  child.once("error", () => finish(false));
34
35
  child.once("exit", (code) => finish(code === 0));
35
36
  child.unref();
36
37
  } catch {
37
- resolve2(false);
38
+ resolve3(false);
38
39
  }
39
40
  });
40
41
  }
@@ -885,7 +886,7 @@ var OAuthCredentialError = class extends Error {
885
886
  };
886
887
  var loginRequired = () => new OAuthCredentialError("login_required");
887
888
  var unsafe = () => new OAuthCredentialError("unsafe_storage");
888
- var delay3 = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
889
+ var delay3 = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
889
890
  var OAuthSessionStore = class {
890
891
  provider;
891
892
  now;
@@ -1598,6 +1599,76 @@ function publicAuthorizationTarget(pending, revoke, trace, updateConfig) {
1598
1599
  };
1599
1600
  }
1600
1601
 
1602
+ // ../../plugins/dsh-plugins/src/settings-contract.ts
1603
+ var packageName = "@aliyunrds/ctxdb-dsh";
1604
+ var settingsNamespace = "aliyunContextdbSettings";
1605
+ var settingsEndpoint = `${settingsNamespace}/auth`;
1606
+ var memoryScopeFields = ["project_id", "user_id", "agent_id", "app_id"];
1607
+ var memoryRecallFields = ["project_id", "user_id", "agent_id", "app_id"];
1608
+ function parseMemoryScope(input) {
1609
+ if (!input || typeof input !== "object" || Array.isArray(input)) return;
1610
+ const values = input;
1611
+ const scope = {};
1612
+ for (const field of memoryScopeFields) {
1613
+ if (!Object.hasOwn(values, field)) continue;
1614
+ const value = values[field];
1615
+ if (field === "app_id" && value === null) {
1616
+ scope.app_id = null;
1617
+ continue;
1618
+ }
1619
+ if (typeof value !== "string" || value.length > 256 || /[\x00-\x1f\x7f]/.test(value) || value.trim() === "*") return;
1620
+ scope[field] = value.trim();
1621
+ }
1622
+ return scope;
1623
+ }
1624
+ function parseMemoryRecallFilters(input) {
1625
+ if (!input || typeof input !== "object" || Array.isArray(input)) return;
1626
+ const values = input;
1627
+ const filters = {};
1628
+ for (const field of memoryRecallFields) {
1629
+ if (!Object.hasOwn(values, field)) continue;
1630
+ const value = values[field];
1631
+ if (typeof value !== "boolean") return;
1632
+ filters[field] = value;
1633
+ }
1634
+ return filters;
1635
+ }
1636
+ function parseRequest(input) {
1637
+ if (input && typeof input === "object" && !Array.isArray(input)) {
1638
+ const { action, site, apiKey, pendingId, setting, enabled, scope: rawScope, recallFilters: rawFilters } = input;
1639
+ if (action === "status" || action === "disconnect" || action === "use-login") return { action };
1640
+ if (action === "cancel" && typeof pendingId === "string" && pendingId.length === 36) return { action, pendingId };
1641
+ if (action === "set-context" && (setting === "autoRecall" || setting === "autoCapture") && typeof enabled === "boolean") {
1642
+ return { action, setting, enabled };
1643
+ }
1644
+ if (action === "set-memory-scope") {
1645
+ const scope = parseMemoryScope(rawScope);
1646
+ const recallFilters = parseMemoryRecallFilters(rawFilters);
1647
+ if (scope && (rawFilters === void 0 || recallFilters)) return { action, scope, recallFilters };
1648
+ }
1649
+ if (site === "cn" || site === "intl") {
1650
+ if (action === "start") return { action, site };
1651
+ if (action === "save-key" && typeof apiKey === "string" && apiKey.length <= 4096) return { action, site, apiKey };
1652
+ }
1653
+ }
1654
+ throw new Error("Invalid ContextDB request.");
1655
+ }
1656
+ var settingsInvocation = {
1657
+ id: `${packageName}#${settingsEndpoint}`,
1658
+ service: settingsNamespace,
1659
+ namespace: settingsNamespace,
1660
+ method: "auth",
1661
+ invocation: { kind: "direct" },
1662
+ parameters: [{
1663
+ name: "request",
1664
+ wire: "request",
1665
+ source: "json",
1666
+ codec: { mode: "strict", typeSymbol: `${packageName}#SettingsRequest`, create: () => ({ parse: parseRequest }) }
1667
+ }],
1668
+ cancellation: { parameter: "signal" },
1669
+ result: { mode: "src-json" }
1670
+ };
1671
+
1601
1672
  // ../../plugins/dsh-plugins/src/auth.ts
1602
1673
  import { randomUUID } from "node:crypto";
1603
1674
  var agent = "dsh";
@@ -1675,8 +1746,8 @@ function createDeviceLogin(path) {
1675
1746
  attempt = { id, site, controller, done };
1676
1747
  return { prompt: first.promise, done, detach: () => signal?.removeEventListener("abort", withdraw) };
1677
1748
  }
1678
- async function start(site, signal) {
1679
- const login = begin(site, signal);
1749
+ async function start(site, signal, options) {
1750
+ const login = begin(site, signal, options?.selectOnSuccess);
1680
1751
  try {
1681
1752
  return await login.prompt;
1682
1753
  } finally {
@@ -1741,7 +1812,15 @@ function createDeviceLogin(path) {
1741
1812
  }
1742
1813
 
1743
1814
  // ../../plugins/dsh-plugins/src/configure.ts
1744
- var usage = "Usage: dsh plugin --profile headless exec ctxdb-dsh configure [--site cn|intl] [--key-stdin | --device-code]";
1815
+ var usage = `Usage: dsh plugin --profile <name> exec ctxdb-dsh configure [--site cn|intl] [--key-stdin | --device-code]
1816
+ ctxdb-dsh configure --profile <name> [--site cn|intl] [--key-stdin | --device-code]`;
1817
+ function profilesDirectory() {
1818
+ const home = process.env.DSH_HOME?.trim() ? process.env.DSH_HOME : join5(homedir2(), ".dsh");
1819
+ return resolve2(home.replace(/^~(?=$|[/\\])/, () => homedir2()), "profiles");
1820
+ }
1821
+ function hasPlugin(dir) {
1822
+ return existsSync3(join5(dir, "node_modules", "@aliyunrds", "ctxdb-dsh", "package.json"));
1823
+ }
1745
1824
  async function readKey(piped) {
1746
1825
  if (piped && !process.stdin.isTTY) return readFileSync3(0, "utf8").replace(/\r?\n$/, "");
1747
1826
  if (!process.stdin.isTTY || piped) throw new Error("Use a terminal or pipe the key with --key-stdin.");
@@ -1784,7 +1863,7 @@ Waiting for authorization. Press Ctrl+C to cancel.`);
1784
1863
  console.error("ContextDB authorization could not be read back. Run configure again.");
1785
1864
  return 1;
1786
1865
  }
1787
- console.log(`ContextDB connected to Workspace ${connection.workspaceId}, Member ${connection.memberId} (${site}).`);
1866
+ console.log(`ContextDB connected to Workspace ${connection.workspaceId}, Member ${connection.memberId} (${site}), profile ${basename(profileDir)}.`);
1788
1867
  if (phase === "cleanup-unconfirmed") console.error("Previous session revocation could not be confirmed.");
1789
1868
  return 0;
1790
1869
  } finally {
@@ -1793,7 +1872,7 @@ Waiting for authorization. Press Ctrl+C to cancel.`);
1793
1872
  }
1794
1873
  }
1795
1874
  async function main(args) {
1796
- if (args.length === 1 && args[0] === "--help" || args.length === 2 && args[0] === "configure" && args[1] === "--help") {
1875
+ if (args.length === 1 && args[0] === "--help") {
1797
1876
  console.log(usage);
1798
1877
  return 0;
1799
1878
  }
@@ -1804,6 +1883,8 @@ async function main(args) {
1804
1883
  allowPositionals: true,
1805
1884
  tokens: true,
1806
1885
  options: {
1886
+ help: { type: "boolean" },
1887
+ profile: { type: "string" },
1807
1888
  site: { type: "string", default: "cn" },
1808
1889
  "key-stdin": { type: "boolean" },
1809
1890
  "device-code": { type: "boolean" }
@@ -1821,15 +1902,44 @@ async function main(args) {
1821
1902
  console.error(usage);
1822
1903
  return 2;
1823
1904
  }
1905
+ if (parsed.values.help) {
1906
+ console.log(usage);
1907
+ return 0;
1908
+ }
1824
1909
  if (deviceCode && piped) {
1825
1910
  console.error("--device-code and --key-stdin are mutually exclusive.\n" + usage);
1826
1911
  return 2;
1827
1912
  }
1828
- const profileDir = process.cwd();
1829
- if (basename(profileDir) !== "headless" || basename(dirname6(profileDir)) !== "profiles") {
1830
- console.error(usage);
1913
+ const requested = parsed.values.profile;
1914
+ if (requested !== void 0 && (typeof requested !== "string" || !requested || /[/\\\x00]/.test(requested) || [".", "..", "node_modules"].includes(requested) || process.platform === "win32" && /[<>:"|?*\x00-\x1f]/.test(requested))) {
1915
+ console.error("Invalid DSH profile name.");
1831
1916
  return 2;
1832
1917
  }
1918
+ const cwd = process.cwd();
1919
+ const name = basename(cwd);
1920
+ const profiles = profilesDirectory();
1921
+ const insideProfile = basename(dirname6(cwd)) === "profiles" && hasPlugin(cwd);
1922
+ const fromExec = insideProfile && process.env.npm_command === "exec";
1923
+ if (typeof requested === "string" && !fromExec) {
1924
+ if (!hasPlugin(join5(profiles, requested))) {
1925
+ console.error("Install the ContextDB plugin in the target DSH profile first.");
1926
+ return 2;
1927
+ }
1928
+ const flags = ["--site", site, ...deviceCode ? ["--device-code"] : piped ? ["--key-stdin"] : []];
1929
+ const child = process.platform === "win32" ? spawnSync(
1930
+ process.env.ComSpec ?? "cmd.exe",
1931
+ ["/d", "/s", "/v:off", "/c", `dsh plugin --profile "%CTXDB_DSH_TARGET%" exec ctxdb-dsh configure ${flags.join(" ")}`],
1932
+ { env: { ...process.env, CTXDB_DSH_TARGET: requested }, stdio: "inherit", windowsVerbatimArguments: true }
1933
+ ) : spawnSync("dsh", ["plugin", "--profile", requested, "exec", "ctxdb-dsh", "configure", ...flags], { stdio: "inherit" });
1934
+ if (child.error) console.error("Could not start dsh. Check that dsh is on PATH.");
1935
+ return child.status ?? 1;
1936
+ }
1937
+ if (!insideProfile || requested !== void 0 && requested !== name) {
1938
+ console.error(insideProfile ? "The configure profile must match the profile selected by dsh plugin." : usage);
1939
+ return 2;
1940
+ }
1941
+ const configuredDir = join5(profiles, name);
1942
+ const profileDir = existsSync3(configuredDir) && realpathSync(configuredDir) === cwd ? configuredDir : cwd;
1833
1943
  if (deviceCode) return configureDeviceCode(profileDir, site);
1834
1944
  let key;
1835
1945
  try {
@@ -1844,31 +1954,26 @@ async function main(args) {
1844
1954
  }
1845
1955
  const temporary = mkdtempSync(join5(tmpdir(), "ctxdb-dsh-configure-"));
1846
1956
  try {
1847
- const patchPath = join5(temporary, "configure.yml");
1848
- writeFileSync3(patchPath, `
1849
- - id: headless-runner
1850
- disabled: true
1851
- - id: llm-deepseek
1852
- disabled: true
1853
- - id: credentials
1854
- disabled: false
1855
- - insert:
1856
- - id: aliyun-contextdb-configure
1857
- name: '@aliyunrds/ctxdb-dsh/configure-host'
1858
- config:
1859
- site: ${site}
1860
- `, { mode: 384 });
1861
- const env = { ...process.env, DSH_HOME: dirname6(dirname6(profileDir)), DSH_TELEMETRY_DISABLED: "1" };
1862
- const stdio = ["pipe", "inherit", "inherit"];
1957
+ const runner = join5(temporary, "profiles", "ctxdb-configure");
1958
+ mkdirSync3(runner, { recursive: true });
1959
+ writeFileSync3(join5(runner, "package.json"), JSON.stringify({ private: true, dsh: { profile: { bundles: [] } } }));
1960
+ writeFileSync3(join5(runner, "credentials-root.yml"), "[]\n");
1961
+ writeFileSync3(join5(runner, "cordis.patch.yml"), JSON.stringify([{ insert: [{
1962
+ id: "aliyun-contextdb-configure",
1963
+ name: fileURLToPath(new URL("./configure-host.js", import.meta.url)),
1964
+ config: { site, profileDir }
1965
+ }] }]), { mode: 384 });
1966
+ const options2 = {
1967
+ env: { ...process.env, DSH_HOME: temporary, DSH_TELEMETRY_DISABLED: "1" },
1968
+ input: key,
1969
+ stdio: ["pipe", "inherit", "inherit"],
1970
+ timeout: 3e4
1971
+ };
1863
1972
  const result = process.platform === "win32" ? spawnSync(
1864
1973
  process.env.ComSpec ?? "cmd.exe",
1865
- ["/d", "/s", "/v:off", "/c", 'dsh --profile headless --patch "%CTXDB_DSH_SETUP_PATCH%" ctxdb-configure'],
1866
- { env: { ...env, CTXDB_DSH_SETUP_PATCH: patchPath }, input: key, stdio: [...stdio], windowsVerbatimArguments: true, timeout: 3e4 }
1867
- ) : spawnSync(
1868
- "dsh",
1869
- ["--profile", "headless", "--patch", patchPath, "ctxdb-configure"],
1870
- { env, input: key, stdio: [...stdio], timeout: 3e4 }
1871
- );
1974
+ ["/d", "/s", "/v:off", "/c", "dsh --profile ctxdb-configure"],
1975
+ { ...options2, windowsVerbatimArguments: true }
1976
+ ) : spawnSync("dsh", ["--profile", "ctxdb-configure"], options2);
1872
1977
  if (result.error) console.error("Could not start the DSH configuration process. Check that dsh is on PATH and try again.");
1873
1978
  return result.status ?? 1;
1874
1979
  } finally {