@insmind/cli 1.5.1 → 1.5.2

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.
Files changed (61) hide show
  1. package/dist/bin/agent-worker.js +2 -1
  2. package/dist/bin/insmind-cli.js +12 -7
  3. package/dist/bin/postinstall.js +7 -5
  4. package/dist/src/bootstrap/create-cli.js +26 -17
  5. package/dist/src/bootstrap/create-runtime.js +31 -13
  6. package/dist/src/bootstrap/run-agent-worker.js +2 -1
  7. package/dist/src/bootstrap/validators.js +10 -5
  8. package/dist/src/cli/action-binding.js +14 -0
  9. package/dist/src/cli/agent-commands.js +8 -3
  10. package/dist/src/cli/auth-commands.js +1 -1
  11. package/dist/src/cli/credits-command.js +2 -2
  12. package/dist/src/cli/dam-commands.js +51 -52
  13. package/dist/src/cli/editor-commands.js +13 -15
  14. package/dist/src/cli/errors.js +91 -41
  15. package/dist/src/cli/model-commands.js +6 -4
  16. package/dist/src/cli/presenter.js +13 -10
  17. package/dist/src/cli/task-commands.js +13 -5
  18. package/dist/src/cli/tool-commands.js +9 -3
  19. package/dist/src/features/agent/use-cases.js +11 -5
  20. package/dist/src/features/auth/credential-store.js +2 -2
  21. package/dist/src/features/auth/sso-service.js +3 -2
  22. package/dist/src/features/auth/state.js +2 -0
  23. package/dist/src/features/auth/use-cases.js +30 -34
  24. package/dist/src/features/credits/use-cases.js +2 -0
  25. package/dist/src/features/dam/file-downloader.js +38 -16
  26. package/dist/src/features/dam/object-storage.js +23 -11
  27. package/dist/src/features/dam/operation-executor.js +46 -37
  28. package/dist/src/features/dam/registered-uploader.js +39 -29
  29. package/dist/src/features/dam/storage-upload.js +5 -4
  30. package/dist/src/features/dam/use-cases.js +81 -60
  31. package/dist/src/features/editor/bridge-client.js +6 -6
  32. package/dist/src/features/editor/bridge-process.js +2 -1
  33. package/dist/src/features/editor/session-state.js +6 -4
  34. package/dist/src/features/editor/session.js +26 -8
  35. package/dist/src/features/editor/use-cases.js +10 -3
  36. package/dist/src/features/org/use-cases.js +2 -1
  37. package/dist/src/features/task/agent-background.js +1 -0
  38. package/dist/src/features/task/store.js +2 -0
  39. package/dist/src/features/task/use-cases.js +80 -27
  40. package/dist/src/features/tool/catalog.js +11 -5
  41. package/dist/src/features/tool/dynamic-schema.js +9 -7
  42. package/dist/src/features/tool/mns-catalog-adapter.js +1 -0
  43. package/dist/src/features/tool/tool-api-adapter.js +8 -7
  44. package/dist/src/features/tool/use-cases.js +7 -3
  45. package/dist/src/features/update/update-notification.js +75 -70
  46. package/dist/src/features/update/update-service.js +24 -20
  47. package/dist/src/platform/file-lock.js +36 -9
  48. package/dist/src/platform/interruption.js +13 -0
  49. package/dist/src/platform/json-input.js +12 -9
  50. package/dist/src/platform/local-json-file.js +8 -4
  51. package/dist/src/platform/redact.js +7 -1
  52. package/dist/src/platform/remote-protocol.js +2 -2
  53. package/dist/src/platform/safe-upload-file.js +2 -1
  54. package/dist/src/platform/schema-issues.js +8 -0
  55. package/dist/src/platform/signed-http-transport.js +8 -7
  56. package/dist/src/platform/text-output.js +33 -0
  57. package/dist/src/telemetry/invocation.js +19 -4
  58. package/dist/src/telemetry/process-errors.js +14 -4
  59. package/dist/src/telemetry/sanitize.js +4 -2
  60. package/dist/src/telemetry/sls-sink.js +36 -20
  61. package/package.json +4 -4
@@ -28,86 +28,91 @@ export function createUpdateNotificationService(options) {
28
28
  return;
29
29
  if (env.CI === "true")
30
30
  return;
31
- let release = null;
31
+ const lease = { release: null };
32
32
  try {
33
- signal.throwIfAborted();
34
- release = await lock.acquire();
35
- if (release === null)
36
- return;
37
- const checkedAt = now();
38
- const today = localDate(checkedAt);
39
- const state = await readState(stateFile);
40
- if (isNewer(state.latest_version, options.currentVersion)
41
- && state.last_notified_on !== today) {
42
- const reminded = withReminder(state, today, state.latest_version);
43
- await writeState(stateFile, reminded);
44
- notify(options, state.latest_version);
45
- return;
46
- }
47
- if (!isDue(state.next_check_at, checkedAt))
48
- return;
49
- let latestResult;
50
- const timeout = signalWithTimeout(signal, REGISTRY_TIMEOUT_MS);
51
- try {
52
- latestResult = await fetchLatestVersion({
53
- fetch: fetchPackage,
54
- signal: timeout.signal,
55
- ...(options.registryUrl ? { registryUrl: options.registryUrl } : {}),
56
- ...(state.etag ? { etag: state.etag } : {})
57
- });
58
- }
59
- catch (error) {
60
- await options.reportError?.(error).catch(() => undefined);
61
- if (signal.aborted)
33
+ const run = async () => {
34
+ signal.throwIfAborted();
35
+ lease.release = await lock.acquire();
36
+ if (lease.release === null)
62
37
  return;
63
- await writeState(stateFile, {
64
- ...state,
65
- schema_version: 1,
66
- next_check_at: addMilliseconds(checkedAt, FAILED_CHECK_INTERVAL_MS)
67
- });
68
- return;
69
- }
70
- finally {
71
- timeout.dispose();
72
- }
73
- const latest = latestResult.status === "not_modified"
74
- ? state.latest_version
75
- : latestResult.version;
76
- if (latest === undefined || valid(latest) === null) {
77
- await writeState(stateFile, {
38
+ const checkedAt = now();
39
+ const today = localDate(checkedAt);
40
+ const state = await readState(stateFile);
41
+ if (isNewer(state.latest_version, options.currentVersion)
42
+ && state.last_notified_on !== today) {
43
+ const reminded = withReminder(state, today, state.latest_version);
44
+ await writeState(stateFile, reminded);
45
+ notify(options, state.latest_version);
46
+ return;
47
+ }
48
+ if (!isDue(state.next_check_at, checkedAt))
49
+ return;
50
+ let latestResult;
51
+ const timeout = signalWithTimeout(signal, REGISTRY_TIMEOUT_MS);
52
+ try {
53
+ const fetchLatest = () => fetchLatestVersion({
54
+ fetch: fetchPackage,
55
+ signal: timeout.signal,
56
+ ...(options.registryUrl ? { registryUrl: options.registryUrl } : {}),
57
+ ...(state.etag ? { etag: state.etag } : {})
58
+ });
59
+ latestResult = options.telemetry ? await options.telemetry.stage("update_check.registry", fetchLatest) : await fetchLatest();
60
+ }
61
+ catch (error) {
62
+ if (signal.aborted)
63
+ return;
64
+ await writeState(stateFile, {
65
+ ...state,
66
+ schema_version: 1,
67
+ next_check_at: addMilliseconds(checkedAt, FAILED_CHECK_INTERVAL_MS)
68
+ });
69
+ return;
70
+ }
71
+ finally {
72
+ timeout.dispose();
73
+ }
74
+ const latest = latestResult.status === "not_modified"
75
+ ? state.latest_version
76
+ : latestResult.version;
77
+ if (latest === undefined || valid(latest) === null) {
78
+ await writeState(stateFile, {
79
+ ...state,
80
+ schema_version: 1,
81
+ next_check_at: addMilliseconds(checkedAt, FAILED_CHECK_INTERVAL_MS)
82
+ });
83
+ return;
84
+ }
85
+ let nextState = {
78
86
  ...state,
79
87
  schema_version: 1,
80
- next_check_at: addMilliseconds(checkedAt, FAILED_CHECK_INTERVAL_MS)
81
- });
82
- return;
83
- }
84
- let nextState = {
85
- ...state,
86
- schema_version: 1,
87
- last_success_check_at: checkedAt.toISOString(),
88
- next_check_at: addMilliseconds(checkedAt, SUCCESS_CHECK_INTERVAL_MS),
89
- latest_version: latest,
90
- ...(latestResult.status === "modified" && latestResult.etag
91
- ? { etag: latestResult.etag }
92
- : {})
88
+ last_success_check_at: checkedAt.toISOString(),
89
+ next_check_at: addMilliseconds(checkedAt, SUCCESS_CHECK_INTERVAL_MS),
90
+ latest_version: latest,
91
+ ...(latestResult.status === "modified" && latestResult.etag
92
+ ? { etag: latestResult.etag }
93
+ : {})
94
+ };
95
+ if (latestResult.status === "modified" && latestResult.etag === undefined) {
96
+ delete nextState.etag;
97
+ }
98
+ const shouldNotify = gt(latest, options.currentVersion)
99
+ && nextState.last_notified_on !== today;
100
+ if (shouldNotify)
101
+ nextState = withReminder(nextState, today, latest);
102
+ await writeState(stateFile, nextState);
103
+ if (shouldNotify)
104
+ notify(options, latest);
93
105
  };
94
- if (latestResult.status === "modified" && latestResult.etag === undefined) {
95
- delete nextState.etag;
96
- }
97
- const shouldNotify = gt(latest, options.currentVersion)
98
- && nextState.last_notified_on !== today;
99
- if (shouldNotify)
100
- nextState = withReminder(nextState, today, latest);
101
- await writeState(stateFile, nextState);
102
- if (shouldNotify)
103
- notify(options, latest);
106
+ if (options.telemetry)
107
+ await options.telemetry.stage("update_check", run);
108
+ else
109
+ await run();
104
110
  }
105
111
  catch (error) {
106
- await options.reportError?.(error).catch(() => undefined);
107
112
  // Availability checks are best-effort and never change command behavior.
108
113
  }
109
114
  finally {
110
- await release?.().catch(() => undefined);
115
+ await lease.release?.().catch(() => undefined);
111
116
  }
112
117
  }
113
118
  };
@@ -1,19 +1,23 @@
1
+ import { isInterruption } from "../../platform/interruption.js";
1
2
  import { spawn } from "node:child_process";
2
3
  import { realpathSync } from "node:fs";
3
4
  import { resolve } from "node:path";
4
5
  import { gt } from "semver";
5
- import { syncBundledSkills, verifyBundledSkills } from "../skill/installer.js";
6
+ import { syncBundledSkills, SkillSyncError, verifyBundledSkills } from "../skill/installer.js";
6
7
  import { fetchLatestVersion } from "./latest-version.js";
7
8
  import { readInstallationOwner } from "../../platform/installation-owner.js";
8
9
  export class UpdateError extends Error {
9
10
  code;
10
11
  nextSteps;
11
- constructor(code, message, nextSteps) {
12
- super(message);
12
+ constructor(code, message, nextSteps, cause) {
13
+ super(message, { cause });
13
14
  this.code = code;
14
15
  this.nextSteps = nextSteps;
15
16
  this.name = "UpdateError";
16
17
  }
18
+ get details() {
19
+ return this.cause instanceof SkillSyncError ? { skills: this.cause.results } : undefined;
20
+ }
17
21
  }
18
22
  export function detectInstallSource(input) {
19
23
  const binaryPath = normalizePath(input.binaryPath);
@@ -90,12 +94,13 @@ export function createUpdateService(options) {
90
94
  return result.version;
91
95
  }
92
96
  catch (error) {
93
- rethrowAbort(signal);
94
- throw new UpdateError("UPDATE_FAILED", options.commandName === undefined
97
+ if (isInterruption(error, signal))
98
+ throw signal.reason;
99
+ throw new UpdateError("UPDATE_FAILED", !insmind
95
100
  ? "无法获取 @gaoding/cli 最新版本。"
96
- : `Unable to get the latest ${packageName} version.`, [options.commandName === undefined
101
+ : `Unable to get the latest ${packageName} version.`, [!insmind
97
102
  ? "请稍后重新执行 gd-cli update。"
98
- : `Run ${commandName} update again later.`]);
103
+ : `Run ${commandName} update again later.`], error);
99
104
  }
100
105
  });
101
106
  signal.throwIfAborted();
@@ -109,12 +114,13 @@ export function createUpdateService(options) {
109
114
  await syncSkills(options.bundledSkills, skillOptions);
110
115
  }
111
116
  catch (error) {
112
- rethrowAbort(signal);
117
+ if (isInterruption(error, signal))
118
+ throw signal.reason;
113
119
  throw new UpdateError("UPDATE_FAILED", insmind
114
120
  ? `${commandName} ${options.currentVersion} is current, but Agent Skill synchronization failed.`
115
121
  : `gd-cli ${options.currentVersion} 无需更新,但 Agent Skill 同步失败。`, [insmind
116
- ? `Resolve the conflict and run ${commandName} update again.`
117
- : "请解决冲突后重新执行 gd-cli update。"]);
122
+ ? `Inspect the reported Skill targets and file permissions, then run ${commandName} update again.`
123
+ : "检查所列 Skill 目标、文件权限和已有内容后,重新执行 gd-cli update。"], error);
118
124
  }
119
125
  });
120
126
  return { version: options.currentVersion, updated: false };
@@ -129,7 +135,7 @@ export function createUpdateService(options) {
129
135
  packageName,
130
136
  binaryName: commandName
131
137
  });
132
- const nextSteps = manualCommands(latest, packageName);
138
+ const nextSteps = [insmind ? "Choose the command for your original package manager:" : "按原安装工具选择下面一条命令执行:", ...manualCommands(latest, packageName)];
133
139
  if (source.kind === "unsupported") {
134
140
  throw new UpdateError("UPDATE_FAILED", insmind
135
141
  ? "The current installation method does not support automatic updates."
@@ -144,10 +150,11 @@ export function createUpdateService(options) {
144
150
  await runProcess(command, args, signal);
145
151
  }
146
152
  catch (error) {
147
- rethrowAbort(signal);
153
+ if (isInterruption(error, signal))
154
+ throw signal.reason;
148
155
  throw new UpdateError("UPDATE_FAILED", insmind
149
156
  ? `Failed to update ${commandName} to ${latest}.`
150
- : `gd-cli 更新到 ${latest} 失败。`, nextSteps);
157
+ : `gd-cli 更新到 ${latest} 失败。`, nextSteps, error);
151
158
  }
152
159
  });
153
160
  signal.throwIfAborted();
@@ -160,12 +167,13 @@ export function createUpdateService(options) {
160
167
  await verifySkills(targetSkills, skillOptions);
161
168
  }
162
169
  catch (error) {
163
- rethrowAbort(signal);
170
+ if (isInterruption(error, signal))
171
+ throw signal.reason;
164
172
  throw new UpdateError("UPDATE_PARTIAL", insmind
165
173
  ? `${commandName} was updated to ${latest}, but Agent Skill verification failed.`
166
174
  : `gd-cli 已更新到 ${latest},但 Agent Skill 验收失败。`, [insmind
167
175
  ? `Run ${commandName} update again.`
168
- : "请重新执行 gd-cli update。"]);
176
+ : "请重新执行 gd-cli update。"], error);
169
177
  }
170
178
  });
171
179
  return { version: latest, updated: true };
@@ -175,7 +183,7 @@ export function createUpdateService(options) {
175
183
  function spawnProcess(command, args, signal) {
176
184
  return new Promise((resolvePromise, reject) => {
177
185
  const child = spawn(command, args, {
178
- stdio: "inherit",
186
+ stdio: [0, 2, 2],
179
187
  shell: false,
180
188
  signal
181
189
  });
@@ -220,7 +228,3 @@ function safeRealpath(path) {
220
228
  function unsupported(reason) {
221
229
  return { kind: "unsupported", reason };
222
230
  }
223
- function rethrowAbort(signal) {
224
- if (signal.aborted)
225
- signal.throwIfAborted();
226
- }
@@ -1,17 +1,21 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir, open, readFile, readdir, unlink, chmod } from "node:fs/promises";
2
+ import * as nodeFileSystem from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { setTimeout as delay } from "node:timers/promises";
5
5
  import { createLocalJsonFile } from "./local-json-file.js";
6
6
  /** Local bakery lock: unique owner files avoid deleting a new owner's lock
7
7
  * when several processes simultaneously recover a dead writer. */
8
- export async function withFileLock(path, run) {
8
+ export async function withFileLock(path, run, options = {}) {
9
+ const fileSystem = options.fileSystem ?? nodeFileSystem;
10
+ const { mkdir, open, readFile, readdir, unlink, chmod, rename } = fileSystem;
11
+ const deadline = Math.min(options.deadline ?? Infinity, Date.now() + 2_000);
12
+ if (Date.now() >= deadline)
13
+ throw new Error("Local state lock timed out.");
9
14
  const directory = `${path}.d`;
10
15
  await mkdir(directory, { recursive: true, mode: 0o700 });
11
16
  await chmod(directory, 0o700);
12
17
  const name = `${process.pid}-${randomUUID()}.json`;
13
18
  const ownPath = join(directory, name);
14
- const deadline = Date.now() + 2_000;
15
19
  async function contenders() {
16
20
  const found = [];
17
21
  for (const entry of await readdir(directory)) {
@@ -47,22 +51,45 @@ export async function withFileLock(path, run) {
47
51
  return found;
48
52
  }
49
53
  const handle = await open(ownPath, "wx", 0o600);
54
+ let failed = false;
55
+ let primaryError;
50
56
  try {
51
57
  await handle.writeFile('{"ticket":null}');
52
58
  const ticket = 1 + Math.max(0, ...(await contenders()).map(owner => owner.ticket ?? 0));
53
- await createLocalJsonFile({ directory, filename: name }).writeTextAtomically(JSON.stringify({ ticket }));
59
+ await createLocalJsonFile({ directory, filename: name, fileSystem }).writeTextAtomically(JSON.stringify({ ticket }));
54
60
  for (;;) {
61
+ if (Date.now() >= deadline)
62
+ throw new Error("Local state lock timed out.");
55
63
  const waiting = (await contenders()).some(owner => owner.name !== name
56
64
  && (owner.ticket === null || owner.ticket < ticket || (owner.ticket === ticket && owner.name < name)));
57
- if (!waiting)
65
+ if (!waiting) {
66
+ if (Date.now() >= deadline)
67
+ throw new Error("Local state lock timed out.");
58
68
  return await run();
59
- if (Date.now() >= deadline)
60
- throw new Error("Local state lock timed out.");
69
+ }
61
70
  await delay(10);
62
71
  }
63
72
  }
73
+ catch (error) {
74
+ failed = true;
75
+ primaryError = error;
76
+ throw error;
77
+ }
64
78
  finally {
65
- await handle.close();
66
- await unlink(ownPath).catch(() => undefined);
79
+ const releaseErrors = [];
80
+ await handle.close().catch(error => { releaseErrors.push(error); });
81
+ try {
82
+ await unlink(ownPath);
83
+ }
84
+ catch (error) {
85
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
86
+ // Only our finished owner is retired. Old clients also ignore this suffix.
87
+ await rename(ownPath, `${ownPath}.released`).catch(cause => {
88
+ releaseErrors.push(new AggregateError([error, cause], "Cannot retire the local lock owner."));
89
+ });
90
+ }
91
+ }
92
+ if (releaseErrors.length)
93
+ throw new AggregateError(failed ? [primaryError, ...releaseErrors] : releaseErrors, "Local state lock release failed.", { cause: failed ? primaryError : releaseErrors[0] });
67
94
  }
68
95
  }
@@ -0,0 +1,13 @@
1
+ /** An unrelated failure must remain a failure even when cancellation races it. */
2
+ export function isInterruption(error, signal) {
3
+ if (!signal?.aborted)
4
+ return false;
5
+ for (let depth = 0; depth < 10; depth++) {
6
+ if (error === signal.reason)
7
+ return true;
8
+ if (!(error instanceof Error) || error.cause === undefined)
9
+ return false;
10
+ error = error.cause;
11
+ }
12
+ return false;
13
+ }
@@ -1,8 +1,11 @@
1
+ import { isInterruption } from "./interruption.js";
1
2
  import { readFile } from "node:fs/promises";
2
3
  import { resolve } from "node:path";
3
4
  export class JsonInputError extends Error {
4
- constructor() {
5
- super("无法读取有效的 JSON。");
5
+ reason;
6
+ constructor(reason = "parse", cause) {
7
+ super(reason === "read" ? "无法读取 JSON 输入。" : "JSON 输入语法无效。", { cause });
8
+ this.reason = reason;
6
9
  this.name = "JsonInputError";
7
10
  }
8
11
  }
@@ -16,16 +19,16 @@ export function createJsonInputReader(options) {
16
19
  ? await readStream(options.stdin, signal)
17
20
  : await readFile(resolve(options.cwd, source), { encoding: "utf8", signal });
18
21
  }
19
- catch {
20
- if (signal.aborted)
22
+ catch (cause) {
23
+ if (isInterruption(cause, signal))
21
24
  throw signal.reason;
22
- throw new JsonInputError();
25
+ throw new JsonInputError("read", cause);
23
26
  }
24
27
  try {
25
28
  return JSON.parse(text);
26
29
  }
27
- catch {
28
- throw new JsonInputError();
30
+ catch (cause) {
31
+ throw new JsonInputError("parse", cause);
29
32
  }
30
33
  }
31
34
  };
@@ -46,9 +49,9 @@ function readStream(stream, signal) {
46
49
  cleanup();
47
50
  resolve(Buffer.concat(chunks).toString("utf8"));
48
51
  };
49
- const onError = () => {
52
+ const onError = (cause) => {
50
53
  cleanup();
51
- reject(new JsonInputError());
54
+ reject(new JsonInputError("read", cause));
52
55
  };
53
56
  const onAbort = () => {
54
57
  cleanup();
@@ -2,8 +2,12 @@ import { randomUUID } from "node:crypto";
2
2
  import * as nodeFileSystem from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  export class LocalFileError extends Error {
5
- constructor(cause) {
5
+ file;
6
+ reason;
7
+ constructor(cause, file, reason = "io") {
6
8
  super("无法访问本地状态文件。", { cause });
9
+ this.file = file;
10
+ this.reason = reason;
7
11
  this.name = "LocalFileError";
8
12
  }
9
13
  }
@@ -20,7 +24,7 @@ export function createLocalJsonFile(options) {
20
24
  catch (cause) {
21
25
  if (isMissing(cause))
22
26
  return null;
23
- throw new LocalFileError(cause);
27
+ throw new LocalFileError(cause, options.filename);
24
28
  }
25
29
  },
26
30
  async writeTextAtomically(value) {
@@ -40,7 +44,7 @@ export function createLocalJsonFile(options) {
40
44
  catch (cause) {
41
45
  await handle?.close().catch(() => undefined);
42
46
  await fileSystem.unlink(temporaryPath).catch(() => undefined);
43
- throw new LocalFileError(cause);
47
+ throw new LocalFileError(cause, options.filename);
44
48
  }
45
49
  },
46
50
  async remove() {
@@ -49,7 +53,7 @@ export function createLocalJsonFile(options) {
49
53
  }
50
54
  catch (cause) {
51
55
  if (!isMissing(cause))
52
- throw new LocalFileError(cause);
56
+ throw new LocalFileError(cause, options.filename);
53
57
  }
54
58
  }
55
59
  };
@@ -33,7 +33,7 @@ export function redactSensitiveText(value) {
33
33
  const url = redactUrl(value);
34
34
  if (url)
35
35
  return url;
36
- return value
36
+ return value.replace(/https?:\/\/[^\s<>"`\]\)]+/gu, raw => redactUrl(raw) ?? raw)
37
37
  .replace(/(authorization\s*:\s*bearer\s+)[^\s,;]+/gi, `$1${REDACTED}`)
38
38
  .replace(/(cookie\s*:\s*)[^\r\n]+/gi, `$1${REDACTED}`)
39
39
  .replace(/\b(ak|sk|access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|auth[_-]?key|token|access[_-]?token|refresh[_-]?token|security[_-]?token|sts[_-]?token|signature|authorize[_-]?code|authorization[_-]?code|device[_-]?code|org[_-]?id|content[_-]?id|dify[_-]?task[_-]?id|task[_-]?id)\s*[:=]\s*(?:\[REDACTED\]|[^\s,;}&"'\]]+)/gi, `$1=${REDACTED}`);
@@ -69,6 +69,12 @@ function redactUrl(value) {
69
69
  }
70
70
  if (url.protocol !== "http:" && url.protocol !== "https:")
71
71
  return undefined;
72
+ url.username = "";
73
+ url.password = "";
74
+ // Fragments can carry OAuth credentials or application-private state. They
75
+ // are irrelevant to diagnostics; result URLs do not pass through this path.
76
+ if (url.hash)
77
+ url.hash = "[REDACTED]";
72
78
  for (const key of [...url.searchParams.keys()]) {
73
79
  if (isSensitiveKey(key))
74
80
  url.searchParams.set(key, REDACTED);
@@ -1,8 +1,8 @@
1
1
  export class RemoteProtocolError extends Error {
2
2
  remoteCode;
3
3
  remoteBody;
4
- constructor(evidence = {}) {
5
- super("稿定服务响应与当前 CLI 不兼容。");
4
+ constructor(evidence = {}, cause) {
5
+ super("稿定服务响应与当前 CLI 不兼容。", { cause });
6
6
  this.name = "RemoteProtocolError";
7
7
  this.remoteCode = evidence.remoteCode;
8
8
  this.remoteBody = evidence.remoteBody;
@@ -1,3 +1,4 @@
1
+ import { isInterruption } from "./interruption.js";
1
2
  import { open, realpath, stat } from "node:fs/promises";
2
3
  import { basename, extname, sep } from "node:path";
3
4
  import { fileURLToPath } from "node:url";
@@ -137,7 +138,7 @@ export async function inspectUploadFile(input) {
137
138
  };
138
139
  }
139
140
  catch (error) {
140
- if (input.signal.aborted)
141
+ if (isInterruption(error, input.signal))
141
142
  throw input.signal.reason;
142
143
  if (error instanceof LocalFileInputError)
143
144
  throw error;
@@ -0,0 +1,8 @@
1
+ export function validationIssues(errors) {
2
+ return (errors ?? []).slice(0, 8).map(error => ({
3
+ field: `${error.instancePath}${typeof error.params.missingProperty === "string" ? `/${error.params.missingProperty}`
4
+ : typeof error.params.additionalProperty === "string" ? `/${error.params.additionalProperty}` : ""}`.slice(0, 256) || "/",
5
+ rule: error.keyword,
6
+ message: (error.message ?? error.keyword).slice(0, 256)
7
+ }));
8
+ }
@@ -1,3 +1,4 @@
1
+ import { isInterruption } from "./interruption.js";
1
2
  import { remoteErrorEvidence } from "./remote-error-evidence.js";
2
3
  import { RemoteProtocolError } from "./remote-protocol.js";
3
4
  import { canonicalizeQuery, signRequest } from "./signature.js";
@@ -100,7 +101,7 @@ export function createSignedHttpTransport(options) {
100
101
  return response;
101
102
  }
102
103
  catch (error) {
103
- if (request.signal.aborted)
104
+ if (isInterruption(error, request.signal))
104
105
  throw request.signal.reason;
105
106
  throw new RemoteRequestError(undefined, isTransientNetworkFailure(error), {}, error);
106
107
  }
@@ -110,8 +111,8 @@ export function createSignedHttpTransport(options) {
110
111
  try {
111
112
  body = await response.text();
112
113
  }
113
- catch {
114
- throw new RemoteRequestError(response.status);
114
+ catch (error) {
115
+ throw new RemoteRequestError(response.status, false, {}, error);
115
116
  }
116
117
  const evidence = remoteErrorEvidence(body);
117
118
  if (!response.ok)
@@ -119,8 +120,8 @@ export function createSignedHttpTransport(options) {
119
120
  try {
120
121
  return JSON.parse(body);
121
122
  }
122
- catch {
123
- throw new RemoteProtocolError(evidence);
123
+ catch (error) {
124
+ throw new RemoteProtocolError(evidence, error);
124
125
  }
125
126
  }
126
127
  async function getJsonResponse(request) {
@@ -145,8 +146,8 @@ export function createSignedHttpTransport(options) {
145
146
  try {
146
147
  body = await response.text();
147
148
  }
148
- catch {
149
- throw new RemoteRequestError(response.status);
149
+ catch (error) {
150
+ throw new RemoteRequestError(response.status, false, {}, error);
150
151
  }
151
152
  throw new RemoteRequestError(response.status, false, remoteErrorEvidence(body));
152
153
  }
@@ -0,0 +1,33 @@
1
+ import { Writable } from "node:stream";
2
+ /** Writes remain synchronous for command presenters; flush acknowledges delivery. */
3
+ export function createTextOutput(stream) {
4
+ if (!(stream instanceof Writable))
5
+ return {
6
+ write: text => { stream.write(text); }, flush: async () => { }
7
+ };
8
+ const pending = new Set();
9
+ let failure;
10
+ stream.on("error", error => { failure ??= error; });
11
+ return {
12
+ write(text) {
13
+ if (failure)
14
+ throw failure;
15
+ const writing = new Promise(resolve => {
16
+ try {
17
+ stream.write(text, error => { failure ??= error ?? undefined; resolve(); });
18
+ }
19
+ catch (error) {
20
+ failure ??= error instanceof Error ? error : new Error(String(error));
21
+ resolve();
22
+ }
23
+ });
24
+ pending.add(writing);
25
+ void writing.then(() => pending.delete(writing));
26
+ },
27
+ async flush() {
28
+ await Promise.all(pending);
29
+ if (failure)
30
+ throw failure;
31
+ }
32
+ };
33
+ }