@insmind/cli 2.0.0 → 2.1.0

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.
@@ -0,0 +1,80 @@
1
+ import { withFileLock } from "../../platform/file-lock.js";
2
+ import { randomUUID } from "node:crypto";
3
+ import * as fileSystem from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ const STALE_LOCK_MS = 30_000;
6
+ export function createLocalUpdateNotificationLock(options) {
7
+ const path = join(options.directory, "update-check.lock");
8
+ return {
9
+ async acquire() {
10
+ await fileSystem.mkdir(options.directory, { mode: 0o700, recursive: true });
11
+ await fileSystem.chmod(options.directory, 0o700);
12
+ const first = await tryCreateLock(path);
13
+ if (first)
14
+ return releaseLock(path, first);
15
+ if (!await isStaleLock(path, options.now()))
16
+ return null;
17
+ // Two recoverers must not both unlink the lock: the first may already have
18
+ // replaced it with a live owner's file when the second resumes.
19
+ return withFileLock(path + ".recovery", async () => {
20
+ if (!await isStaleLock(path, options.now()))
21
+ return null;
22
+ await fileSystem.unlink(path).catch((error) => {
23
+ if (!isMissing(error))
24
+ throw error;
25
+ });
26
+ const recovered = await tryCreateLock(path);
27
+ return recovered ? releaseLock(path, recovered) : null;
28
+ });
29
+ }
30
+ };
31
+ }
32
+ async function tryCreateLock(path) {
33
+ const token = randomUUID();
34
+ let handle;
35
+ try {
36
+ handle = await fileSystem.open(path, "wx", 0o600);
37
+ await handle.writeFile(token, "utf8");
38
+ await handle.sync();
39
+ await handle.close();
40
+ return token;
41
+ }
42
+ catch (error) {
43
+ await handle?.close().catch(() => undefined);
44
+ if (isExists(error))
45
+ return null;
46
+ throw error;
47
+ }
48
+ }
49
+ function releaseLock(path, token) {
50
+ return async () => {
51
+ let current;
52
+ try {
53
+ current = await fileSystem.readFile(path, "utf8");
54
+ }
55
+ catch (error) {
56
+ if (isMissing(error))
57
+ return;
58
+ throw error;
59
+ }
60
+ if (current === token)
61
+ await fileSystem.unlink(path);
62
+ };
63
+ }
64
+ async function isStaleLock(path, now) {
65
+ try {
66
+ const stats = await fileSystem.stat(path);
67
+ return stats.mtimeMs + STALE_LOCK_MS <= now.getTime();
68
+ }
69
+ catch (error) {
70
+ if (isMissing(error))
71
+ return true;
72
+ throw error;
73
+ }
74
+ }
75
+ function isMissing(error) {
76
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
77
+ }
78
+ function isExists(error) {
79
+ return error instanceof Error && "code" in error && error.code === "EEXIST";
80
+ }
@@ -1,122 +1,151 @@
1
- import { randomUUID } from "node:crypto";
2
- import * as fileSystem from "node:fs/promises";
3
1
  import { homedir } from "node:os";
4
2
  import { join } from "node:path";
5
3
  import { gt, valid } from "semver";
6
4
  import { createLocalJsonFile } from "../../platform/local-json-file.js";
7
5
  import { fetchLatestVersion } from "./latest-version.js";
8
- const SUCCESS_CHECK_INTERVAL_MS = 60 * 60 * 1_000;
9
- const FAILED_CHECK_INTERVAL_MS = 15 * 60 * 1_000;
10
- const REGISTRY_TIMEOUT_MS = 2_000;
11
- const STALE_LOCK_MS = 30_000;
6
+ import { createLocalUpdateNotificationLock } from "./update-lock.js";
7
+ const HOUR = 60 * 60 * 1_000;
8
+ const RETRY = 15 * 60 * 1_000;
12
9
  export function createUpdateNotificationService(options) {
13
- const fetchPackage = options.fetch ?? globalThis.fetch;
10
+ const { currentVersion } = options;
11
+ const command = options.commandName ?? "gd-cli";
14
12
  const now = options.now ?? (() => new Date());
15
13
  const env = options.env ?? process.env;
16
- const stateDirectory = join(options.homeDirectory ?? homedir(), options.stateDirectoryName ?? ".gd");
17
- const stateFile = options.stateFile ?? createLocalJsonFile({
18
- directory: stateDirectory,
19
- filename: "update-check.json"
20
- });
21
- const lock = options.lock ?? createLocalUpdateNotificationLock({
22
- directory: stateDirectory,
23
- now: () => new Date()
24
- });
14
+ const directory = join(options.homeDirectory ?? homedir(), options.stateDirectoryName ?? ".gd");
15
+ const file = options.stateFile ?? createLocalJsonFile({ directory, filename: "update-check.json" });
16
+ const lock = options.lock ?? createLocalUpdateNotificationLock({ directory, now: () => new Date() });
17
+ const host = env.CLI_HOST_APPLICATION?.toLowerCase();
18
+ const surface = host && /^[a-z0-9_-]{1,48}$/.test(host) ? host : "terminal";
19
+ const unknown = { status: "unknown", currentVersion };
20
+ async function refresh(state, time, signal) {
21
+ if (Date.parse(state.next_check_at ?? "") > time.getTime())
22
+ return state;
23
+ const timeout = signalWithTimeout(signal, 2_000);
24
+ try {
25
+ const fetchLatest = () => fetchLatestVersion({
26
+ fetch: options.fetch ?? globalThis.fetch, signal: timeout.signal,
27
+ ...(options.registryUrl ? { registryUrl: options.registryUrl } : {}),
28
+ ...(state.etag ? { etag: state.etag } : {})
29
+ });
30
+ const result = options.telemetry ? await options.telemetry.stage("update_check.registry", fetchLatest) : await fetchLatest();
31
+ const latest = result.status === "modified" ? result.version : state.latest_version;
32
+ if (!latest || !valid(latest))
33
+ throw new Error("Missing cached Registry version");
34
+ const next = { ...state, latest_version: latest, last_success_check_at: time.toISOString(),
35
+ next_check_at: new Date(time.getTime() + HOUR).toISOString() };
36
+ if (result.status === "modified") {
37
+ if (result.etag)
38
+ next.etag = result.etag;
39
+ else
40
+ delete next.etag;
41
+ }
42
+ return next;
43
+ }
44
+ catch {
45
+ signal.throwIfAborted();
46
+ // A failed refresh cannot establish what the latest version is.
47
+ const { latest_version, etag, ...prior } = state;
48
+ return { ...prior, next_check_at: new Date(time.getTime() + RETRY).toISOString() };
49
+ }
50
+ finally {
51
+ timeout.dispose();
52
+ }
53
+ }
54
+ async function report(signal, channel, deliver, remember = true) {
55
+ if (options.installationOwner === "workbuddy")
56
+ return deliver({ status: "managed", currentVersion });
57
+ if (options.installationOwner === "invalid" || env.CI === "true")
58
+ return deliver(unknown);
59
+ const release = await lock.acquire().catch(() => null);
60
+ if (!release)
61
+ return deliver(unknown);
62
+ try {
63
+ let state;
64
+ try {
65
+ signal.throwIfAborted();
66
+ const prior = await readState(file);
67
+ state = await refresh(prior, now(), signal);
68
+ if (state !== prior)
69
+ await save(file, state);
70
+ }
71
+ catch {
72
+ signal.throwIfAborted();
73
+ return await deliver(unknown);
74
+ }
75
+ const latest = valid(state.latest_version);
76
+ if (!latest)
77
+ return await deliver(unknown);
78
+ if (!gt(latest, currentVersion))
79
+ return await deliver({ status: "current", currentVersion, latestVersion: latest });
80
+ const available = { status: "available", currentVersion, latestVersion: latest, updateCommand: command + " update" };
81
+ const windowStart = now().getTime() - HOUR;
82
+ const recent = Object.fromEntries(Object.entries(state.notified_at ?? {}).filter(([, at]) => at > windowStart));
83
+ if (!channel || Object.hasOwn(recent, channel))
84
+ return await deliver(available);
85
+ const notice = command === "gd-cli"
86
+ ? `gd-cli 有新版本 ${latest},当前版本为 ${currentVersion}。运行 gd-cli update 即可更新。`
87
+ : `${command} ${latest} is available; current version is ${currentVersion}. Run ${command} update to update.`;
88
+ await deliver({ ...available, notice });
89
+ if (remember)
90
+ await save(file, { ...state, notified_at: { ...recent, [channel]: now().getTime() } }).catch(() => undefined);
91
+ }
92
+ finally {
93
+ await release().catch(() => undefined);
94
+ }
95
+ }
25
96
  return {
26
- async check(signal) {
27
- if ((options.installationOwner ?? "user") !== "user")
97
+ async check(signal, output = "machine") {
98
+ if (env.CI === "true" || env.CLI_INVOCATION_PURPOSE === "auth_status" || env.CLI_INVOCATION_PURPOSE === "version_check")
28
99
  return;
29
- if (env.CI === "true")
30
- return;
31
- const lease = { release: null };
100
+ // An unobserved stderr pipe must not spend the next visible text/Skill reminder.
101
+ const channel = output === "machine" && options.diagnosticOnly ? "stderr:" + surface : "display:" + surface;
102
+ const run = () => report(signal, channel, async (result) => {
103
+ if (result.status === "available" && result.notice)
104
+ await options.notify(result.notice, output);
105
+ }, env.CLI_UPDATE_NOTICE_FORMAT !== "offer");
32
106
  try {
33
- const run = async () => {
34
- signal.throwIfAborted();
35
- lease.release = await lock.acquire();
36
- if (lease.release === null)
37
- return;
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 = {
86
- ...state,
87
- schema_version: 1,
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);
105
- };
106
107
  if (options.telemetry)
107
108
  await options.telemetry.stage("update_check", run);
108
109
  else
109
110
  await run();
110
111
  }
111
- catch (error) {
112
- // Availability checks are best-effort and never change command behavior.
113
- }
114
- finally {
115
- await lease.release?.().catch(() => undefined);
116
- }
112
+ catch { /* Optional notices never change a business command's result. */ }
113
+ },
114
+ report(signal, forDisplay, deliver) {
115
+ return report(signal, forDisplay ? "display:" + surface : undefined, deliver);
117
116
  }
118
117
  };
119
118
  }
119
+ async function readState(file) {
120
+ const empty = { schema_version: 1 };
121
+ const content = await file.readText();
122
+ if (!content)
123
+ return empty;
124
+ try {
125
+ const value = JSON.parse(content);
126
+ if (!isRecord(value) || value.schema_version !== 1)
127
+ return empty;
128
+ const state = { ...empty };
129
+ for (const key of ["next_check_at", "latest_version", "etag", "last_success_check_at"]) {
130
+ if (typeof value[key] === "string")
131
+ state[key] = value[key];
132
+ }
133
+ // v1 date-only reminders have no time of day. Start the rolling window on first delivery.
134
+ if (isRecord(value.notified_at)) {
135
+ state.notified_at = Object.fromEntries(Object.entries(value.notified_at).filter((entry) => typeof entry[1] === "number" && Number.isFinite(entry[1])));
136
+ }
137
+ return state;
138
+ }
139
+ catch {
140
+ return empty;
141
+ }
142
+ }
143
+ function isRecord(value) {
144
+ return typeof value === "object" && value !== null && !Array.isArray(value);
145
+ }
146
+ function save(file, state) {
147
+ return file.writeTextAtomically(JSON.stringify(state, null, 2) + "\n");
148
+ }
120
149
  function signalWithTimeout(parent, milliseconds) {
121
150
  const controller = new AbortController();
122
151
  const forwardAbort = () => { controller.abort(parent.reason); };
@@ -136,143 +165,3 @@ function signalWithTimeout(parent, milliseconds) {
136
165
  }
137
166
  };
138
167
  }
139
- function createLocalUpdateNotificationLock(options) {
140
- const path = join(options.directory, "update-check.lock");
141
- return {
142
- async acquire() {
143
- await fileSystem.mkdir(options.directory, { mode: 0o700, recursive: true });
144
- await fileSystem.chmod(options.directory, 0o700);
145
- const first = await tryCreateLock(path);
146
- if (first)
147
- return releaseLock(path, first);
148
- if (!await isStaleLock(path, options.now()))
149
- return null;
150
- await fileSystem.unlink(path).catch((error) => {
151
- if (!isMissing(error))
152
- throw error;
153
- });
154
- const recovered = await tryCreateLock(path);
155
- return recovered ? releaseLock(path, recovered) : null;
156
- }
157
- };
158
- }
159
- async function tryCreateLock(path) {
160
- const token = randomUUID();
161
- let handle;
162
- try {
163
- handle = await fileSystem.open(path, "wx", 0o600);
164
- await handle.writeFile(token, "utf8");
165
- await handle.sync();
166
- await handle.close();
167
- return token;
168
- }
169
- catch (error) {
170
- await handle?.close().catch(() => undefined);
171
- if (isExists(error))
172
- return null;
173
- throw error;
174
- }
175
- }
176
- function releaseLock(path, token) {
177
- return async () => {
178
- let current;
179
- try {
180
- current = await fileSystem.readFile(path, "utf8");
181
- }
182
- catch (error) {
183
- if (isMissing(error))
184
- return;
185
- throw error;
186
- }
187
- if (current === token)
188
- await fileSystem.unlink(path);
189
- };
190
- }
191
- async function isStaleLock(path, now) {
192
- try {
193
- const stats = await fileSystem.stat(path);
194
- return stats.mtimeMs + STALE_LOCK_MS <= now.getTime();
195
- }
196
- catch (error) {
197
- if (isMissing(error))
198
- return true;
199
- throw error;
200
- }
201
- }
202
- async function readState(file) {
203
- const text = await file.readText();
204
- if (text === null)
205
- return { schema_version: 1 };
206
- try {
207
- const value = JSON.parse(text);
208
- return parseState(value) ?? { schema_version: 1 };
209
- }
210
- catch {
211
- return { schema_version: 1 };
212
- }
213
- }
214
- function parseState(value) {
215
- if (!isRecord(value) || value.schema_version !== 1)
216
- return null;
217
- for (const key of [
218
- "last_success_check_at",
219
- "next_check_at",
220
- "latest_version",
221
- "last_notified_on",
222
- "last_notified_version",
223
- "etag"
224
- ]) {
225
- if (value[key] !== undefined && typeof value[key] !== "string")
226
- return null;
227
- }
228
- return value;
229
- }
230
- async function writeState(file, state) {
231
- await file.writeTextAtomically(`${JSON.stringify(state, null, 2)}\n`);
232
- }
233
- function withReminder(state, today, version) {
234
- return {
235
- ...state,
236
- schema_version: 1,
237
- last_notified_on: today,
238
- last_notified_version: version
239
- };
240
- }
241
- function notify(options, latest) {
242
- if (options.commandName && options.commandName !== "gd-cli") {
243
- options.notify(`${options.commandName} ${latest} is available; current version is ` +
244
- `${options.currentVersion}. Run ${options.commandName} update to update.`);
245
- }
246
- else {
247
- options.notify(`gd-cli 有新版本 ${latest},当前版本为 ${options.currentVersion}。` +
248
- "运行 gd-cli update 即可更新。");
249
- }
250
- }
251
- function isNewer(version, currentVersion) {
252
- return version !== undefined && valid(version) !== null && gt(version, currentVersion);
253
- }
254
- function isDue(nextCheckAt, now) {
255
- if (nextCheckAt === undefined)
256
- return true;
257
- const timestamp = Date.parse(nextCheckAt);
258
- return !Number.isFinite(timestamp) || timestamp <= now.getTime();
259
- }
260
- function addMilliseconds(value, milliseconds) {
261
- return new Date(value.getTime() + milliseconds).toISOString();
262
- }
263
- function localDate(value) {
264
- return [
265
- String(value.getFullYear()).padStart(4, "0"),
266
- String(value.getMonth() + 1).padStart(2, "0"),
267
- String(value.getDate()).padStart(2, "0")
268
- ].join("-");
269
- }
270
- function isRecord(value) {
271
- return typeof value === "object" && value !== null && !Array.isArray(value);
272
- }
273
- function isMissing(error) {
274
- return error instanceof Error && "code" in error && error.code === "ENOENT";
275
- }
276
- function isExists(error) {
277
- return error instanceof Error && "code" in error && error.code === "EEXIST";
278
- }
@@ -7,7 +7,9 @@ export function canonicalizeQuery(entries) {
7
7
  .replaceAll("%3A", ":");
8
8
  }
9
9
  export function createSigningString(input) {
10
- return `${input.method.toUpperCase()}@${input.pathname}@${input.canonicalQuery}@${input.timestamp}`;
10
+ // The gateway signs literal base64 padding; keep its wire query URL-encoded.
11
+ const signingQuery = input.canonicalQuery.replaceAll("%3D", "=");
12
+ return `${input.method.toUpperCase()}@${input.pathname}@${signingQuery}@${input.timestamp}`;
11
13
  }
12
14
  export function signRequest(input) {
13
15
  return hmac(input.secretKey, createSigningString(input));
@@ -195,24 +195,29 @@ export function createSignedHttpTransport(options) {
195
195
  }, error, diagnosticReason, { ...received.diagnostics(), ...summary });
196
196
  }
197
197
  }
198
- async function json(received) {
198
+ async function json(received, sensitiveResponse = false, parseJson = JSON.parse) {
199
199
  const { response } = received;
200
200
  const body = await readText(received);
201
- const evidence = remoteErrorEvidence(body);
201
+ const originalEvidence = remoteErrorEvidence(body);
202
+ const evidence = sensitiveResponse ? {
203
+ ...(originalEvidence.remoteCode === undefined ? {} : { remoteCode: originalEvidence.remoteCode }),
204
+ ...(originalEvidence.diagnosticReason === undefined ? {} : { diagnosticReason: originalEvidence.diagnosticReason })
205
+ } : originalEvidence;
202
206
  if (!response.ok)
203
207
  throw new RemoteRequestError(response.status, false, evidence, undefined, undefined, received.diagnostics());
204
208
  try {
205
- return JSON.parse(body);
209
+ return parseJson(body);
206
210
  }
207
211
  catch (error) {
208
- throw Object.assign(new RemoteProtocolError(evidence, error, "RESPONSE_JSON_INVALID"), {
212
+ // SyntaxError messages can embed raw JSON fragments, including private ledger data.
213
+ throw Object.assign(new RemoteProtocolError(evidence, sensitiveResponse ? undefined : error, "RESPONSE_JSON_INVALID"), {
209
214
  status: response.status, diagnosticSummary: received.diagnostics()
210
215
  });
211
216
  }
212
217
  }
213
218
  async function getJsonResponse(request) {
214
219
  const received = await send("GET", request, "application/json", undefined, true);
215
- return { body: await json(received), headers: received.response.headers, status: received.response.status };
220
+ return { body: await json(received, request.sensitiveResponse, request.parseJson), headers: received.response.headers, status: received.response.status };
216
221
  }
217
222
  return {
218
223
  async getJson(request) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@insmind/cli",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "insMind command-line interface for agents and people.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -47,8 +47,8 @@
47
47
  "@gaoding/cli": "workspace:*"
48
48
  },
49
49
  "gaodingRelease": {
50
- "sourceCommit": "216c910373e0a89ff902e655f3cda89cae32887b",
51
- "pipelineId": "241612",
52
- "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/241612"
50
+ "sourceCommit": "5a8acfd84d3ce5ed311d5442c66ebc6b62c9f680",
51
+ "pipelineId": "241803",
52
+ "pipelineUrl": "https://git.intra.gaoding.com/gtt/gaoding-cli/-/pipelines/241803"
53
53
  }
54
54
  }
@@ -9,6 +9,7 @@ description: Use when creating images, videos or text with insMind CLI, operatin
9
9
 
10
10
  - For `agent send`, `tool call` and `editor apply`, set the top-level `host_application` in the input JSON to the calling app, for example `workbuddy`, `qwenwork` or `trae`. Use `terminal` for direct terminal use.
11
11
  - Check `insmind-cli --version` on first use. If the entry point is unclear, read `insmind-cli --help`, follow the relevant command group, then read the chosen command's `--help` before execution. Examples here are not an exhaustive capability list.
12
+ - Relay an available update to the user alongside their foreground result, at most once per hour. For stdout-only hosts, see “Update” below.
12
13
  - For structured input, query `--schema` only where the command exposes it. Discover models, parameter choices, prices and resource IDs through current lists/details rather than old examples. Report missing support or failed discovery without silently replacing explicit user constraints.
13
14
  - Reuse help and static Schema within the same session and CLI path/version; refresh after changing the CLI. Query dynamic metadata when selecting capabilities or quoting prices for this task, and refresh relevant results after identity changes or an explicit mismatch. Avoid unrelated catalog scans.
14
15
  - Discovery describes the installed CLI; it neither upgrades it nor authorizes generation, writes or installation. Recover unknown outcomes through the error-handling reference.
@@ -1,5 +1,7 @@
1
1
  # Update
2
2
 
3
+ Relay an update alongside the foreground business result. In a stdout-only host, discover `check` through `insmind-cli update --help`. On first foreground use or after an hour, set `CLI_HOST_APPLICATION` to the actual host, run `insmind-cli update check --json --for-display`, and relay the returned `notice` if present. Ordinary `update check --json` queries do not spend a display slot. For an older CLI, compare its actual version to `npm view @insmind/cli dist-tags.latest` only for a confirmed user installation. Continue the task if the check is unavailable.
4
+
3
5
  When the user requests an upgrade or approves resolving a compatibility issue, discover the current installation channel's update behavior before updating:
4
6
 
5
7
  ```bash