@gaoding/cli 3.0.1 → 3.0.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.
Files changed (54) hide show
  1. package/README.md +7 -3
  2. package/contracts/operations/agent.send/input.schema.json +1 -1
  3. package/contracts/operations/credits.get/output.schema.json +3 -3
  4. package/contracts/operations/dam.copy/input.schema.json +3 -3
  5. package/contracts/operations/dam.copy/output.schema.json +1 -1
  6. package/contracts/operations/dam.list/output.schema.json +2 -2
  7. package/contracts/operations/dam.move/input.schema.json +3 -3
  8. package/contracts/operations/dam.search/output.schema.json +2 -2
  9. package/contracts/operations/feedback.submit/input.schema.json +231 -0
  10. package/contracts/operations/feedback.submit/output.schema.json +29 -0
  11. package/contracts/operations/task.get/output.schema.json +2 -2
  12. package/contracts/presentations/task.get.schema.json +2 -2
  13. package/dist/bin/gd-cli.js +1 -6
  14. package/dist/bin/insmind-cli.js +1 -6
  15. package/dist/src/bootstrap/create-cli.js +34 -19
  16. package/dist/src/bootstrap/create-runtime.js +13 -2
  17. package/dist/src/bootstrap/run-task-worker.js +6 -2
  18. package/dist/src/bootstrap/validators.js +1 -8
  19. package/dist/src/cli/agent-commands.js +7 -6
  20. package/dist/src/cli/dam-commands.js +14 -6
  21. package/dist/src/cli/errors.js +23 -6
  22. package/dist/src/cli/feedback-command.js +31 -0
  23. package/dist/src/cli/model-commands.js +4 -4
  24. package/dist/src/cli/skill-output.js +13 -4
  25. package/dist/src/cli/task-commands.js +3 -2
  26. package/dist/src/cli/tool-commands.js +12 -5
  27. package/dist/src/cli/update-command.js +3 -3
  28. package/dist/src/contracts/creation-input.js +0 -3
  29. package/dist/src/features/dam/file-downloader.js +19 -9
  30. package/dist/src/features/dam/operation-executor.js +2 -0
  31. package/dist/src/features/dam/use-cases.js +53 -29
  32. package/dist/src/features/feedback/submit.js +86 -0
  33. package/dist/src/features/skill/catalog.js +17 -1
  34. package/dist/src/features/skill/manual.js +37 -31
  35. package/dist/src/features/task/store.js +7 -0
  36. package/dist/src/features/task/use-cases.js +66 -10
  37. package/dist/src/features/update/check-schema.js +22 -16
  38. package/dist/src/features/update/update-notification.js +8 -4
  39. package/dist/src/features/update/update-service.js +37 -16
  40. package/dist/src/telemetry/command-routes.json +1 -1
  41. package/dist/src/telemetry/invocation.js +8 -4
  42. package/dist/src/telemetry/process-errors.js +7 -2
  43. package/dist/src/telemetry/sanitize.js +18 -7
  44. package/dist/src/telemetry/sls-sink.js +38 -15
  45. package/package.json +7 -7
  46. package/skills/gd-cli/SKILL.md +2 -2
  47. package/dist/src/features/editor/bridge-client.js +0 -107
  48. package/dist/src/features/editor/bridge-process.js +0 -237
  49. package/dist/src/features/editor/bridge-server.js +0 -339
  50. package/dist/src/features/editor/protocol.js +0 -1
  51. package/dist/src/features/editor/public-url.js +0 -1
  52. package/dist/src/features/editor/session-state.js +0 -81
  53. package/dist/src/features/editor/session.js +0 -232
  54. package/dist/src/features/editor/use-cases.js +0 -118
@@ -90,6 +90,45 @@ export function createDamUseCases(dependencies) {
90
90
  });
91
91
  return { repositoryId: detail.repository_id, folderId: detail.folder_id };
92
92
  }
93
+ async function verifyEntryChange(signal, matches) {
94
+ signal.throwIfAborted();
95
+ const timeoutMs = 60_000;
96
+ const end = performance.now() + timeoutMs;
97
+ const controller = new AbortController();
98
+ const verificationSignal = AbortSignal.any([signal, controller.signal]);
99
+ const expire = () => controller.abort(new Error("DAM verification timed out"));
100
+ const timer = setTimeout(expire, timeoutMs);
101
+ let onAbort;
102
+ const aborted = new Promise((_resolve, reject) => {
103
+ onAbort = () => reject(verificationSignal.reason);
104
+ verificationSignal.addEventListener("abort", onAbort, { once: true });
105
+ });
106
+ function remainingTime() {
107
+ const remaining = end - performance.now();
108
+ if (remaining <= 0)
109
+ expire();
110
+ verificationSignal.throwIfAborted();
111
+ return remaining;
112
+ }
113
+ async function verify() {
114
+ while (true) {
115
+ remainingTime();
116
+ const confirmed = await matches(verificationSignal);
117
+ const remaining = remainingTime();
118
+ if (confirmed)
119
+ return;
120
+ await dependencies.sleep(Math.min(2_000, remaining), verificationSignal);
121
+ }
122
+ }
123
+ try {
124
+ // End the wait even if the in-flight read or interval ignores cancellation.
125
+ await Promise.race([verify(), aborted]);
126
+ }
127
+ finally {
128
+ clearTimeout(timer);
129
+ verificationSignal.removeEventListener("abort", onAbort);
130
+ }
131
+ }
93
132
  function assertEntryOperationInput(input) {
94
133
  assertAssetId(input.entry_id, "entry_id");
95
134
  if (input.kind !== "asset" && input.kind !== "folder")
@@ -157,6 +196,7 @@ export function createDamUseCases(dependencies) {
157
196
  sourceRepositoryId: sourceRepository.id,
158
197
  targetRepositoryId,
159
198
  targetFolderId: input.request.targetFolderId,
199
+ ...(execution.task_id ? { taskId: execution.task_id } : {}),
160
200
  ...(execution.copied_entry_id === undefined
161
201
  ? {}
162
202
  : { copiedEntryId: execution.copied_entry_id })
@@ -358,16 +398,7 @@ export function createDamUseCases(dependencies) {
358
398
  return result;
359
399
  }
360
400
  try {
361
- await dependencies.telemetry.stage("verify", async () => {
362
- for (let attempt = 0; attempt <= 30; attempt += 1) {
363
- signal.throwIfAborted();
364
- if (await entryTitle(request) === input.title)
365
- return;
366
- if (attempt < 30)
367
- await dependencies.sleep(2_000, signal);
368
- }
369
- throw new DamOperationUnconfirmedError("rename");
370
- });
401
+ await dependencies.telemetry.stage("verify", () => verifyEntryChange(signal, async (verifySignal) => await entryTitle({ ...request, signal: verifySignal }) === input.title));
371
402
  }
372
403
  catch (error) {
373
404
  throw new DamOperationUnconfirmedError("rename", { phase: "verify", entry_id: input.entry_id, repository_id: repository.id, accepted: true }, error);
@@ -386,28 +417,21 @@ export function createDamUseCases(dependencies) {
386
417
  input = { ...input, entry_id: normalizeDamAssetId(input.entry_id, "entry_id") };
387
418
  const operation = await entryOperation({ operation: "move", request: input, access, signal });
388
419
  try {
389
- await dependencies.telemetry.stage("verify", async () => {
390
- for (let attempt = 0; attempt <= 30; attempt += 1) {
391
- signal.throwIfAborted();
392
- const location = await entryLocation({
393
- entryId: input.entry_id,
394
- kind: input.kind,
395
- repositoryId: operation.targetRepositoryId,
396
- access,
397
- signal
398
- });
399
- if (location.repositoryId === operation.targetRepositoryId
400
- && location.folderId === operation.targetFolderId)
401
- return;
402
- if (attempt < 30)
403
- await dependencies.sleep(2_000, signal);
404
- }
405
- throw new DamOperationUnconfirmedError("move");
406
- });
420
+ await dependencies.telemetry.stage("verify", () => verifyEntryChange(signal, async (verifySignal) => {
421
+ const location = await entryLocation({
422
+ entryId: input.entry_id,
423
+ kind: input.kind,
424
+ repositoryId: operation.targetRepositoryId,
425
+ access,
426
+ signal: verifySignal
427
+ });
428
+ return location.repositoryId === operation.targetRepositoryId && location.folderId === operation.targetFolderId;
429
+ }));
407
430
  }
408
431
  catch (error) {
409
432
  throw new DamOperationUnconfirmedError("move", { phase: "verify", accepted: true,
410
- entry_id: input.entry_id, repository_id: operation.targetRepositoryId, folder_id: operation.targetFolderId }, error);
433
+ entry_id: input.entry_id, repository_id: operation.targetRepositoryId, folder_id: operation.targetFolderId,
434
+ ...(operation.taskId ? { task_id: operation.taskId } : {}) }, error);
411
435
  }
412
436
  const result = {
413
437
  entry_id: input.entry_id,
@@ -0,0 +1,86 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { cleanText } from "../../telemetry/sanitize.js";
3
+ export class FeedbackDeliveryError extends Error {
4
+ outcome;
5
+ feedbackId;
6
+ status;
7
+ constructor(outcome, feedbackId, status) {
8
+ super("Feedback delivery " + outcome);
9
+ this.outcome = outcome;
10
+ this.feedbackId = feedbackId;
11
+ this.status = status;
12
+ }
13
+ messageFor(english) {
14
+ if (this.outcome === "unknown")
15
+ return english
16
+ ? "Receipt could not be confirmed. Keep feedback ID " + this.feedbackId + " and avoid sending the same report again."
17
+ : "暂时无法确认反馈是否收到。请保留反馈编号 " + this.feedbackId + ",避免重复提交。";
18
+ if (this.outcome === "unavailable")
19
+ return english
20
+ ? "Feedback could not be sent. The feedback service is unavailable."
21
+ : "反馈还没发出。反馈服务暂时不可用。";
22
+ return english ? "The feedback service declined this report (HTTP " + this.status + ")."
23
+ : "反馈服务拒绝了这次提交(HTTP " + this.status + ")。";
24
+ }
25
+ }
26
+ function clean(value) {
27
+ return cleanText(value.replace(/(?:https?|file):\/\/[^\s<>"',。;]+/giu, "[link]")
28
+ .replace(/(["'])(?:(?:[A-Z]:[\\/]|\/|\\\\)[^"'\r\n]+)\1/giu, "[path]")
29
+ .replace(/(?:^|(?<=[\s((=::]))(?:\/[^\s,。;、))"'<>]+|[a-z]:[\\/][^\s,。;、))"'<>]+|\\\\[^\s,。;、))"'<>]+)/giu, "[path]")
30
+ .replace(/(?:\/(?:Users|home|private|tmp|var|mnt|Volumes)\/|[a-z]:\\)[^\s,。;、))"'<>]+/giu, "[path]")
31
+ .replace(/\b(authorization|proxy-authorization)\s*[:=]\s*(?:basic|bearer)\s+[^\s,;]+/giu, "$1=[REDACTED]")
32
+ .replace(/\b(password|passwd|secret)\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/giu, "$1=[REDACTED]")
33
+ .replace(/[\w.+%-]+@[\w.-]+\.[a-z]{2,}/giu, "[email]")
34
+ .replace(/(?<!\d)(?:\+86[- ]?)?1[3-9]\d{9}(?!\d)/gu, "[phone]"));
35
+ }
36
+ export async function sendFeedback(input, context, options) {
37
+ if (!options.url)
38
+ throw new FeedbackDeliveryError("unavailable");
39
+ options.signal?.throwIfAborted();
40
+ const feedbackId = randomUUID();
41
+ const { environment, ...source } = context;
42
+ const fields = {
43
+ ...source, ...(source.entry_point === "cli" ? { env: environment } : { environment }), event_name: "user_feedback", operation: "feedback.submit", command_kind: "technical",
44
+ feedback_id: feedbackId, feedback_type: input.type, received_at: new Date().toISOString(),
45
+ os: process.platform, arch: process.arch, node_version: process.versions.node,
46
+ reported_host_application: input.host_application,
47
+ reported_host_application_version: input.host_application_version ?? "unknown",
48
+ reported_user_os: input.user_os.name, reported_user_os_version: input.user_os.version ?? "unknown",
49
+ reported_user_os_arch: input.user_os.arch, reported_connector_version: input.connector_version,
50
+ actual: input.actual, expected: input.expected, scenario: input.scenario,
51
+ reported_operation: input.operation, reported_failed_step: input.failedStep, reported_error_code: input.errorCode,
52
+ reported_task_id: input.taskId, reported_trace_id: input.traceId, reported_occurred_at: input.occurredAt,
53
+ };
54
+ const record = {};
55
+ for (const [key, value] of Object.entries(fields))
56
+ if (value !== undefined)
57
+ record[key] = clean(value);
58
+ if (input.steps)
59
+ record.steps = JSON.stringify(input.steps.map(clean));
60
+ const body = JSON.stringify({ __logs__: [record] });
61
+ const request = options.fetch ?? globalThis.fetch;
62
+ let uncertain = false;
63
+ for (let attempt = 1;; attempt++) {
64
+ try {
65
+ const timeout = AbortSignal.timeout(12_000);
66
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
67
+ const response = await request(options.url, { method: "POST", headers: { "Content-Type": "application/json" },
68
+ redirect: "error", credentials: "omit", body, signal });
69
+ void response.body?.cancel().catch(() => { });
70
+ if (response.ok)
71
+ return { feedbackId, status: "received" };
72
+ if (response.status >= 500 || response.status === 408)
73
+ uncertain = true;
74
+ if (attempt === 1 && (uncertain || response.status === 429) && !options.signal?.aborted)
75
+ continue;
76
+ throw new FeedbackDeliveryError(uncertain ? "unknown" : "rejected", feedbackId, response.status);
77
+ }
78
+ catch (error) {
79
+ if (error instanceof FeedbackDeliveryError)
80
+ throw error;
81
+ uncertain = true;
82
+ if (attempt === 2 || options.signal?.aborted)
83
+ throw new FeedbackDeliveryError("unknown", feedbackId);
84
+ }
85
+ }
86
+ }
@@ -20,6 +20,9 @@ function parseCatalog(body) {
20
20
  }
21
21
  return value.skills;
22
22
  }
23
+ function matchesOperation(item, operation) {
24
+ return item.operations.some(op => op.endsWith(".*") ? operation.startsWith(op.slice(0, -1)) : op === operation);
25
+ }
23
26
  async function readCache(path) {
24
27
  try {
25
28
  const cached = JSON.parse(await readFile(path, "utf8"));
@@ -136,10 +139,23 @@ export function createSkillCatalog(client, options = {}) {
136
139
  return body;
137
140
  }, 3500);
138
141
  },
142
+ async guidesForTools(names) {
143
+ const result = new Map();
144
+ try {
145
+ const catalog = (await load(undefined, parseCatalog, 650)).sort((a, b) => a.operations.length - b.operations.length);
146
+ for (const name of names) {
147
+ const guide = catalog.find(item => matchesOperation(item, name));
148
+ if (guide)
149
+ result.set(name, client + " --skill " + guide.id);
150
+ }
151
+ }
152
+ catch { /* Tools remain usable without the guide catalog. */ }
153
+ return result;
154
+ },
139
155
  async recommendations(operation) {
140
156
  try {
141
157
  const items = await load(undefined, parseCatalog, 650);
142
- return items.filter(item => item.operations.some(op => op.endsWith(".*") ? operation.startsWith(op.slice(0, -1)) : op === operation))
158
+ return items.filter(item => matchesOperation(item, operation))
143
159
  .map(({ id, title, description }) => ({ id, title, description, command: client + " --skill " + id }));
144
160
  }
145
161
  catch {
@@ -2,8 +2,14 @@ import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { createSkillCatalog, MissingSkill } from "./catalog.js";
5
- /** Return undefined for normal commands. Documentation also works with lifecycle scripts disabled. */
6
- export async function runSkillManual(argv, name, jsonErrors) {
5
+ export class SkillManualError extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.code = code;
10
+ }
11
+ }
12
+ export function skillManualArguments(argv, name) {
7
13
  if (!argv.includes("--skill"))
8
14
  return;
9
15
  const end = argv.indexOf("--");
@@ -27,45 +33,45 @@ export async function runSkillManual(argv, name, jsonErrors) {
27
33
  return;
28
34
  if (end >= 0)
29
35
  words.push(...argv.slice(end + 1));
36
+ return words;
37
+ }
38
+ export async function writeSkillManual(words, name, write, catalog = createSkillCatalog(name)) {
30
39
  const english = name === "insmind-cli";
31
40
  const usage = english ? "Usage: insmind-cli --skill [chapter]" : "用法:gd-cli --skill [章节]";
32
41
  const [chapter] = words;
33
42
  const help = chapter === "--help" || chapter === "-h";
34
43
  if (words.length > 1 || (chapter && !help && !/^[a-z][a-z0-9-]{0,63}$/u.test(chapter))) {
35
- writeError("USAGE_ERROR", usage, jsonErrors);
36
- return 2;
44
+ throw new SkillManualError("USAGE_ERROR", usage);
37
45
  }
38
- const catalog = createSkillCatalog(name);
39
- try {
40
- if (chapter !== undefined && !help) {
41
- process.stdout.write(await catalog.read(chapter));
42
- return 0;
46
+ async function read(load) {
47
+ try {
48
+ return await load();
43
49
  }
44
- if (!help) {
50
+ catch (error) {
51
+ if (error instanceof MissingSkill) {
52
+ throw new SkillManualError("USAGE_ERROR", (english ? "Unknown chapter. " : "未找到该章节。") + usage);
53
+ }
54
+ throw new SkillManualError("SKILL_UNAVAILABLE", english
55
+ ? "The guide is unavailable. Use command --help for basic usage."
56
+ : "当前无法取得指引,可用命令的 --help 查看基础用法。");
57
+ }
58
+ }
59
+ if (chapter !== undefined && !help) {
60
+ await write(await read(() => catalog.read(chapter)));
61
+ return;
62
+ }
63
+ if (!help) {
64
+ const entry = await read(async () => {
45
65
  const { loadBundledSkills } = await import("./bundled-skills.js");
46
66
  const skill = loadBundledSkills(fileURLToPath(import.meta.url)).find(entry => entry.skill === name);
47
67
  if (!skill)
48
68
  throw Error("Missing entry Skill");
49
- const entry = await readFile(join(skill.sourceDirectory, "SKILL.md"), "utf8");
50
- process.stdout.write(entry.replace(/^---\n[\s\S]*?\n---\n/u, "") + "\n");
51
- }
52
- process.stdout.write(usage + "\n");
53
- const skills = await catalog.list();
54
- for (const item of skills)
55
- process.stdout.write(name + " --skill " + item.id + " " + item.title + " — " + item.description + "\n");
56
- return 0;
69
+ return readFile(join(skill.sourceDirectory, "SKILL.md"), "utf8");
70
+ });
71
+ await write(entry.replace(/^---\n[\s\S]*?\n---\n/u, "") + "\n");
57
72
  }
58
- catch (error) {
59
- if (error instanceof MissingSkill) {
60
- writeError("USAGE_ERROR", (english ? "Unknown chapter. " : "未找到该章节。") + usage, jsonErrors);
61
- return 2;
62
- }
63
- const message = english ? "The guide is unavailable. Use command --help for basic usage."
64
- : "当前无法取得指引,可用命令的 --help 查看基础用法。";
65
- writeError("SKILL_UNAVAILABLE", message, jsonErrors);
66
- return 1;
67
- }
68
- }
69
- function writeError(code, message, json) {
70
- process.stderr.write((json ? JSON.stringify({ error: { code, message } }) : message) + "\n");
73
+ await write(usage + "\n");
74
+ const skills = await read(catalog.list);
75
+ for (const item of skills)
76
+ await write(name + " --skill " + item.id + " " + item.title + " — " + item.description + "\n");
71
77
  }
@@ -108,6 +108,11 @@ export function createTaskStore(options) {
108
108
  const previous = await store.read(scope, record.task.taskId);
109
109
  if (previous) {
110
110
  record.progress = mergeProgress(previous.progress, record.progress);
111
+ if (previous.observationCorrection && !record.observationCorrection) {
112
+ if (record.task.state !== "completed")
113
+ record.task = previous.task;
114
+ record.observationCorrection = previous.observationCorrection;
115
+ }
111
116
  if (previous.task.state === "completed" || (previous.task.state === "failed" && record.task.state !== "completed")) {
112
117
  record.task = previous.task;
113
118
  }
@@ -116,6 +121,8 @@ export function createTaskStore(options) {
116
121
  if (previous.telemetry) {
117
122
  const steps = [...previous.telemetry.steps];
118
123
  for (const item of record.telemetry?.steps ?? []) {
124
+ if (item.event.step === "result_received" && record.task.state === "completed" && item.event.outcome === "failure")
125
+ continue;
119
126
  if (!steps.some(saved => saved.event.step === item.event.step))
120
127
  steps.push(item);
121
128
  }
@@ -33,6 +33,26 @@ function resultTypes(result) {
33
33
  }
34
34
  return [...types].sort();
35
35
  }
36
+ function legacyObservationFailure(record) {
37
+ const { task, progress } = record;
38
+ if (task.state !== "failed" || record.observationCorrection)
39
+ return;
40
+ const hasReceipt = task.operation === "agent.send"
41
+ ? progress.contextId && progress.localMessageId
42
+ : !Object.hasOwn(progress, "toolRun") && (progress.remoteTaskId || progress.toolPipeline?.settlement?.contentId
43
+ || progress.toolPipeline?.matting?.segmentTaskId || progress.toolPipeline?.matting?.classifyTaskId);
44
+ if (!hasReceipt)
45
+ return;
46
+ const terminal = record.telemetry?.steps.filter(({ event }) => event.step === "result_received" || event.step === "delivered").at(-1)?.event;
47
+ if (!terminal || terminal.outcome === "success" || (terminal.cli_task_id && terminal.cli_task_id !== task.taskId))
48
+ return;
49
+ for (const code of [terminal.diagnostic_reason, terminal.error_code]) {
50
+ if (code === "LOCAL_WAIT_INTERRUPTED" || code === "TASK_QUERY_FAILED")
51
+ return code;
52
+ }
53
+ if (terminal.failure_stage === "task.query" && terminal.remote_error_code === "12020704")
54
+ return "task.query/12020704";
55
+ }
36
56
  const HEARTBEAT_MS = 5_000;
37
57
  const LEASE_MS = 15_000;
38
58
  export function taskStartedNotice(taskId, command, mode, text) {
@@ -75,15 +95,20 @@ export function createTaskUseCases(dependencies) {
75
95
  if (!telemetry)
76
96
  return;
77
97
  for (const item of record.telemetry?.steps ?? []) {
78
- if (item.enqueued)
98
+ if (item.enqueued || (record.observationCorrection && item.event.step !== "request_sent"))
79
99
  continue;
80
100
  const generation = taskProcessGeneration();
81
101
  let mayEmit = true;
82
102
  try {
83
103
  await dependencies.store.update(scope, record.task.taskId, stored => {
104
+ if (stored.observationCorrection && item.event.step !== "request_sent") {
105
+ mayEmit = false;
106
+ return;
107
+ }
84
108
  const saved = stored.telemetry?.steps.find(row => row.event.step === item.event.step);
85
109
  if (!saved)
86
110
  return; // The first-observation write failed; the stable event still goes to the queue.
111
+ item.event = saved.event;
87
112
  item.enqueued = saved.enqueued;
88
113
  mayEmit = !saved.enqueued && !taskProcessAlive(saved.enqueuePid, saved.enqueueGeneration, saved.enqueueAtMs ?? saved.event.occurred_at_ms);
89
114
  if (mayEmit) {
@@ -127,9 +152,13 @@ export function createTaskUseCases(dependencies) {
127
152
  catch { /* If the writer exits here, a later process reuses the original event key. */ }
128
153
  }
129
154
  }
130
- async function fact(scope, record, step, at, outcome = "success", error) {
155
+ function factObservation(record, step, at, outcome = "success", error) {
131
156
  if (!telemetry || !record.telemetry)
132
157
  return;
158
+ // Terminal facts for this corrected trace already have stable IDs. Keep the
159
+ // original evidence locally and do not send conflicting outcomes on recovery.
160
+ if (record.observationCorrection && step !== "request_sent")
161
+ return;
133
162
  const current = telemetry.creationContext();
134
163
  const { parameters, ...origin } = record.telemetry.context;
135
164
  const creating = current.operation === origin.operation;
@@ -147,9 +176,9 @@ export function createTaskUseCases(dependencies) {
147
176
  ...(step === "request_sent" && (current.parameters ?? parameters) ? { parameters: current.parameters ?? parameters } : {}),
148
177
  ...(error === undefined ? {} : telemetry.taskFailure(error)),
149
178
  ...(step !== "request_sent" && record.task.result ? { result_types: resultTypes(record.task.result) } : {}) };
150
- function observe(stored) {
179
+ return (stored) => {
151
180
  const facts = stored.telemetry;
152
- if (!facts)
181
+ if (!facts || (stored.observationCorrection && step !== "request_sent"))
153
182
  return;
154
183
  for (const item of record.telemetry?.steps ?? []) {
155
184
  if (!facts.steps.some(saved => saved.event.step === item.event.step))
@@ -170,7 +199,12 @@ export function createTaskUseCases(dependencies) {
170
199
  facts.context = { ...origin, ...(protocol ? { execution_protocol: protocol } : {}), ...(event.content_id ? { content_id: event.content_id } : {}), ...(event.tool_name ? { tool_name: event.tool_name } : {}), ...(event.model_id ? { model_id: event.model_id } : {}) };
171
200
  }
172
201
  facts.steps.push({ event, enqueued: false });
173
- }
202
+ };
203
+ }
204
+ async function fact(scope, record, step, at, outcome = "success", error) {
205
+ const observe = factObservation(record, step, at, outcome, error);
206
+ if (!observe)
207
+ return;
174
208
  try {
175
209
  const updated = await dependencies.store.update(scope, record.task.taskId, observe);
176
210
  if (updated.telemetry)
@@ -327,7 +361,7 @@ export function createTaskUseCases(dependencies) {
327
361
  catch (error) {
328
362
  if (!(error instanceof LocalFileError) || !dispatched || (input.executionMode === "async" && !durableAcceptance)
329
363
  || (progress.toolPipeline?.matting && progress.toolPipeline.stage !== "complete")) {
330
- throw storageContext(error, dispatched ? "after_dispatch" : "before_dispatch");
364
+ throw storageContext(error, dispatched ? "after_dispatch" : record.progress.submissionStarted ? "submission_unconfirmed" : "before_dispatch");
331
365
  }
332
366
  await cacheWarning(record.task.taskId);
333
367
  return;
@@ -338,7 +372,9 @@ export function createTaskUseCases(dependencies) {
338
372
  clearInterval(timer);
339
373
  await stage("task.validate", async () => { finish(record, result); });
340
374
  telemetry?.annotate({ result_state: record.task.state });
341
- const receivedAt = dependencies.now().getTime();
375
+ if (record.task.state === "completed") {
376
+ factObservation(record, "result_received", dependencies.now().getTime())?.(record);
377
+ }
342
378
  let persistenceError;
343
379
  try {
344
380
  await stage("task.persist", save);
@@ -349,7 +385,7 @@ export function createTaskUseCases(dependencies) {
349
385
  persistenceError = error;
350
386
  }
351
387
  if (record.task.state === "completed") {
352
- await fact(scope, record, "result_received", receivedAt);
388
+ await enqueuePending(scope, record);
353
389
  await analyticsFact("completed");
354
390
  }
355
391
  if (persistenceError) {
@@ -431,7 +467,21 @@ export function createTaskUseCases(dependencies) {
431
467
  },
432
468
  async get({ state, id, signal }) {
433
469
  const scope = taskScope(state);
434
- const record = await readRecord(state, id, signal);
470
+ let record = await readRecord(state, id, signal);
471
+ if (legacyObservationFailure(record)) {
472
+ record = await stage("task.persist", () => dependencies.store.update(scope, id, stored => {
473
+ const reason = legacyObservationFailure(stored);
474
+ if (!reason)
475
+ return;
476
+ const task = stored.task;
477
+ const correctedAt = dependencies.now().toISOString();
478
+ stored.observationCorrection = { previousState: "failed", previousUpdatedAt: task.updatedAt, reason, correctedAt,
479
+ ...(task.note === undefined ? {} : { previousNote: task.note }) };
480
+ task.state = "unknown";
481
+ task.updatedAt = correctedAt;
482
+ delete task.note;
483
+ }));
484
+ }
435
485
  await enqueuePending(scope, record);
436
486
  telemetry?.annotate({ diagnostic_summary: {
437
487
  ...(record.progress.contextId ? { agentContextId: record.progress.contextId } : {}),
@@ -440,6 +490,11 @@ export function createTaskUseCases(dependencies) {
440
490
  telemetry?.annotate({ cli_task_id: id, result_state: record.task.state });
441
491
  if (record.task.state === "completed" && record.task.result) {
442
492
  const result = { ...record.task, result: await stage("task.authorize", () => dependencies.recovery.authorize(record.task.result, state, signal, record.progress)) };
493
+ // A pre-upgrade writer could save the work before recording its receipt.
494
+ if (record.telemetry?.steps.some(item => item.event.step === "request_sent")
495
+ && !record.telemetry.steps.some(item => item.event.step === "result_received")) {
496
+ await fact(scope, record, "result_received", dependencies.now().getTime());
497
+ }
443
498
  pendingOutput = { scope, record };
444
499
  await usageWarning(id, record.progress.agentUsageModelMissing === true, record.progress.agentUsageAmountMissing === true);
445
500
  return result;
@@ -496,6 +551,7 @@ export function createTaskUseCases(dependencies) {
496
551
  record.task = result;
497
552
  // Store merging protects terminal results and facts against stale heartbeats.
498
553
  const observedTask = record.task;
554
+ factObservation(record, "result_received", dependencies.now().getTime(), result.state === "completed" ? "success" : "failure", failure)?.(record);
499
555
  try {
500
556
  await stage("task.persist", () => dependencies.store.write(scope, record));
501
557
  }
@@ -507,7 +563,7 @@ export function createTaskUseCases(dependencies) {
507
563
  if (record.task !== observedTask || recoveredFromCache) {
508
564
  result = { ...record.task, ...(record.task.result ? { result: await stage("task.authorize", () => dependencies.recovery.authorize(record.task.result, state, signal, record.progress)) } : {}) };
509
565
  }
510
- await fact(scope, record, "result_received", dependencies.now().getTime(), result.state === "completed" ? "success" : "failure", result.state === "failed" ? failure : undefined);
566
+ await enqueuePending(scope, record);
511
567
  if (result.state === "failed")
512
568
  pendingOutput = { scope, record, rejected: true };
513
569
  }
@@ -1,17 +1,23 @@
1
1
  // Local CLI output contract exposed by `update check --schema`.
2
- export const updateCheckSchema = {
3
- $schema: "https://json-schema.org/draft/2020-12/schema",
4
- type: "object",
5
- additionalProperties: false,
6
- required: ["status", "currentVersion"],
7
- properties: {
8
- status: { enum: ["available", "current", "managed", "unknown"] },
9
- currentVersion: { type: "string" }, latestVersion: { type: "string" },
10
- updateCommand: { type: "string" }, notice: { type: "string" }
11
- },
12
- oneOf: [
13
- { properties: { status: { const: "available" } }, required: ["latestVersion", "updateCommand"] },
14
- { properties: { status: { const: "current" }, notice: false, updateCommand: false }, required: ["latestVersion"] },
15
- { properties: { status: { enum: ["managed", "unknown"] }, latestVersion: false, updateCommand: false, notice: false } }
16
- ]
17
- };
2
+ export function updateCheckSchema(english) {
3
+ return {
4
+ $schema: "https://json-schema.org/draft/2020-12/schema",
5
+ type: "object",
6
+ additionalProperties: false,
7
+ required: ["status", "currentVersion"],
8
+ properties: {
9
+ status: { enum: ["available", "current", "managed", "unknown"], description: english
10
+ ? "available: a newer version was found. current: the installed version is current. managed: the host manages updates and npm was not queried. unknown: this check could not determine availability."
11
+ : "available 表示查到新版本;current 表示当前已是最新;managed 表示更新由宿主管理,本次未查询 npm;unknown 表示本次无法确定是否有更新。" },
12
+ currentVersion: { type: "string" }, latestVersion: { type: "string" },
13
+ updateCommand: { type: "string", description: english
14
+ ? "The self-update command for a recognized global installation, or the command to read update guidance for other sources."
15
+ : "已确认的全局安装返回自更新命令;其他来源返回查看更新说明的命令。" }, notice: { type: "string" }
16
+ },
17
+ oneOf: [
18
+ { properties: { status: { const: "available" } }, required: ["latestVersion", "updateCommand"] },
19
+ { properties: { status: { const: "current" }, notice: false, updateCommand: false }, required: ["latestVersion"] },
20
+ { properties: { status: { enum: ["managed", "unknown"] }, latestVersion: false, updateCommand: false, notice: false } }
21
+ ]
22
+ };
23
+ }
@@ -1,3 +1,4 @@
1
+ import { legacyQwenBridge, updateGuidance } from "./update-service.js";
1
2
  import { homedir } from "node:os";
2
3
  import { join } from "node:path";
3
4
  import { gt, valid } from "semver";
@@ -52,7 +53,7 @@ export function createUpdateNotificationService(options) {
52
53
  }
53
54
  }
54
55
  async function report(signal, channel, deliver, remember = true) {
55
- if (options.installationOwner === "workbuddy")
56
+ if (options.installationOwner === "workbuddy" || (command === "gd-cli" && options.installationOwner !== "invalid" && legacyQwenBridge(env)))
56
57
  return deliver({ status: "managed", currentVersion });
57
58
  if (options.installationOwner === "invalid" || env.CI === "true")
58
59
  return deliver(unknown);
@@ -77,14 +78,17 @@ export function createUpdateNotificationService(options) {
77
78
  return await deliver(unknown);
78
79
  if (!gt(latest, currentVersion))
79
80
  return await deliver({ status: "current", currentVersion, latestVersion: latest });
80
- const available = { status: "available", currentVersion, latestVersion: latest, updateCommand: command + " update" };
81
+ const source = options.installSource?.();
82
+ const installChannel = source?.kind === "global" ? "global" : source?.channel ?? "unknown";
83
+ const available = { status: "available", currentVersion, latestVersion: latest,
84
+ updateCommand: installChannel === "global" ? command + " update" : command + " update --help" };
81
85
  const windowStart = now().getTime() - HOUR;
82
86
  const recent = Object.fromEntries(Object.entries(state.notified_at ?? {}).filter(([, at]) => at > windowStart));
83
87
  if (!channel || Object.hasOwn(recent, channel))
84
88
  return await deliver(available);
85
89
  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.`;
90
+ ? `gd-cli 有新版本 ${latest},当前版本为 ${currentVersion}。${updateGuidance(installChannel, command)}`
91
+ : `${command} ${latest} is available; current version is ${currentVersion}. ${updateGuidance(installChannel, command)}`;
88
92
  await deliver({ ...available, notice });
89
93
  if (remember)
90
94
  await save(file, { ...state, notified_at: { ...recent, [channel]: now().getTime() } }).catch(() => undefined);