@gaoding/cli 2.1.0 → 2.1.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 (141) hide show
  1. package/README.md +30 -0
  2. package/contracts/operations/agent.send/input.schema.json +8 -84
  3. package/contracts/operations/agent.send/output.schema.json +6 -6
  4. package/contracts/operations/dam.folder.list/input.schema.json +1 -1
  5. package/contracts/operations/dam.folder.list/output.schema.json +1 -1
  6. package/contracts/operations/dam.list/input.schema.json +2 -5
  7. package/contracts/operations/dam.list/output.schema.json +1 -1
  8. package/contracts/operations/dam.search/input.schema.json +2 -5
  9. package/contracts/operations/dam.search/output.schema.json +1 -1
  10. package/contracts/operations/model.get/output.schema.json +6 -5
  11. package/contracts/operations/model.list/output.schema.json +5 -4
  12. package/contracts/operations/task.get/output.schema.json +22 -11
  13. package/contracts/operations/tool.call/models/image-edit-smart.schema.json +7 -5
  14. package/contracts/operations/tool.call/models/image-edit-standard.schema.json +6 -4
  15. package/contracts/operations/tool.call/models/image-enhance-smart.schema.json +5 -3
  16. package/contracts/operations/tool.call/models/image-enhance-standard.schema.json +3 -2
  17. package/contracts/operations/tool.call/models/image-expand-smart.schema.json +16 -10
  18. package/contracts/operations/tool.call/models/image-expand-standard.schema.json +13 -8
  19. package/contracts/operations/tool.call/models/image-layers-layout.schema.json +3 -2
  20. package/contracts/operations/tool.call/models/image-layers-smart.schema.json +3 -4
  21. package/contracts/operations/tool.call/models/image-matting-smart.schema.json +6 -4
  22. package/contracts/operations/tool.call/models/image-matting-standard.schema.json +3 -2
  23. package/contracts/operations/tool.call/models/image-ocr.schema.json +3 -2
  24. package/contracts/operations/tool.call/models/image-remove-smart.schema.json +6 -4
  25. package/contracts/operations/tool.call/models/image-remove-standard.schema.json +4 -3
  26. package/contracts/operations/tool.call/models/image-text-edit.schema.json +5 -3
  27. package/contracts/operations/tool.call/models/image-vectorize.schema.json +3 -2
  28. package/contracts/operations/tool.call/models/video-edit-smart.schema.json +6 -6
  29. package/contracts/operations/tool.call/models/video-enhance-smart.schema.json +7 -4
  30. package/contracts/operations/tool.call/models/video-enhance-standard.schema.json +5 -3
  31. package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
  32. package/contracts/operations/tool.call/output.schema.json +9 -8
  33. package/dist/bin/postinstall.js +22 -6
  34. package/dist/bin/sync-skill.js +33 -0
  35. package/dist/bin/task-worker.js +2 -2
  36. package/dist/src/bootstrap/create-cli.js +13 -6
  37. package/dist/src/bootstrap/create-runtime.js +103 -29
  38. package/dist/src/bootstrap/run-task-worker.js +6 -2
  39. package/dist/src/bootstrap/validators.js +87 -151
  40. package/dist/src/cli/action-binding.js +14 -37
  41. package/dist/src/cli/agent-commands.js +13 -13
  42. package/dist/src/cli/auth-commands.js +2 -1
  43. package/dist/src/cli/creation-help.js +9 -0
  44. package/dist/src/cli/dam-commands.js +10 -14
  45. package/dist/src/cli/editor-commands.js +16 -12
  46. package/dist/src/cli/errors.js +84 -26
  47. package/dist/src/cli/host-input.js +62 -5
  48. package/dist/src/cli/model-commands.js +9 -3
  49. package/dist/src/cli/observed-errors.js +7 -3
  50. package/dist/src/cli/org-commands.js +3 -1
  51. package/dist/src/cli/presenter.js +4 -5
  52. package/dist/src/cli/task-commands.js +6 -2
  53. package/dist/src/cli/tool-commands.js +12 -11
  54. package/dist/src/contracts/creation-input.js +20 -17
  55. package/dist/src/features/agent/creative-agent-adapter.js +6 -2
  56. package/dist/src/features/agent/creative-protocol.js +8 -29
  57. package/dist/src/features/agent/resource-authorizer.js +25 -17
  58. package/dist/src/features/agent/result-reader.js +31 -14
  59. package/dist/src/features/agent/use-cases.js +6 -31
  60. package/dist/src/features/auth/credential-store.js +1 -0
  61. package/dist/src/features/credits/use-cases.js +55 -28
  62. package/dist/src/features/dam/asset-projection.js +3 -6
  63. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  64. package/dist/src/features/dam/object-storage.js +2 -1
  65. package/dist/src/features/dam/repository-catalog.js +30 -21
  66. package/dist/src/features/dam/use-cases.js +14 -9
  67. package/dist/src/features/editor/bridge-client.js +0 -2
  68. package/dist/src/features/editor/bridge-process.js +3 -2
  69. package/dist/src/features/editor/public-url.js +1 -36
  70. package/dist/src/features/editor/session-state.js +1 -0
  71. package/dist/src/features/editor/session.js +3 -2
  72. package/dist/src/features/editor/use-cases.js +27 -2
  73. package/dist/src/features/org/org-service.js +10 -1
  74. package/dist/src/features/org/use-cases.js +18 -4
  75. package/dist/src/features/task/process-owner.js +54 -0
  76. package/dist/src/features/task/store.js +102 -32
  77. package/dist/src/features/task/task-background.js +8 -4
  78. package/dist/src/features/task/use-cases.js +184 -84
  79. package/dist/src/features/tool/argument-paths.js +14 -0
  80. package/dist/src/features/tool/canvas-copy.js +28 -15
  81. package/dist/src/features/tool/canvas-matting.js +123 -0
  82. package/dist/src/features/tool/canvas-media.js +102 -55
  83. package/dist/src/features/tool/canvas-models.js +66 -33
  84. package/dist/src/features/tool/canvas-pricing.js +12 -0
  85. package/dist/src/features/tool/canvas-recovery.js +13 -30
  86. package/dist/src/features/tool/canvas-results.js +92 -93
  87. package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
  88. package/dist/src/features/tool/canvas-video.js +44 -37
  89. package/dist/src/features/tool/catalog.js +2 -23
  90. package/dist/src/features/tool/dynamic-schema.js +42 -46
  91. package/dist/src/features/tool/ffprobe-executable.js +21 -0
  92. package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
  93. package/dist/src/features/tool/resource-authorizer.js +11 -3
  94. package/dist/src/features/tool/tool-api-adapter.js +73 -82
  95. package/dist/src/features/tool/tool-definitions.js +23 -0
  96. package/dist/src/features/tool/tool-errors.js +25 -0
  97. package/dist/src/features/tool/tool-output.js +15 -0
  98. package/dist/src/features/tool/use-cases.js +74 -98
  99. package/dist/src/features/update/package-manager.js +124 -0
  100. package/dist/src/features/update/update-service.js +195 -55
  101. package/dist/src/platform/detached-spawn.js +9 -0
  102. package/dist/src/platform/file-lock.js +12 -4
  103. package/dist/src/platform/input-uri.js +23 -1
  104. package/dist/src/platform/local-json-file.js +97 -15
  105. package/dist/src/platform/media-type.js +46 -0
  106. package/dist/src/platform/open-browser.js +5 -2
  107. package/dist/src/platform/public-url.js +35 -0
  108. package/dist/src/platform/remote-error-evidence.js +33 -6
  109. package/dist/src/platform/resource-auth-key.js +35 -1
  110. package/dist/src/platform/safe-upload-file.js +38 -44
  111. package/dist/src/platform/schema-compiler.js +16 -0
  112. package/dist/src/platform/signature.js +2 -2
  113. package/dist/src/platform/signed-http-transport.js +4 -1
  114. package/dist/src/platform/url-safety.js +6 -1
  115. package/dist/src/platform/webm-header.js +41 -0
  116. package/dist/src/platform/windows-acl/LICENSE-mingw-w64 +43 -0
  117. package/dist/src/platform/windows-acl/arm64.node +0 -0
  118. package/dist/src/platform/windows-acl/ia32.node +0 -0
  119. package/dist/src/platform/windows-acl/x64.node +0 -0
  120. package/dist/src/platform/windows-host-job/arm64.exe +0 -0
  121. package/dist/src/platform/windows-host-job/ia32.exe +0 -0
  122. package/dist/src/platform/windows-host-job/sha256.json +7 -0
  123. package/dist/src/platform/windows-host-job/x64.exe +0 -0
  124. package/dist/src/platform/windows-private-state.js +72 -0
  125. package/dist/src/product/config.js +1 -1
  126. package/dist/src/telemetry/command-route.js +38 -0
  127. package/dist/src/telemetry/command-routes.json +1 -0
  128. package/dist/src/telemetry/failure-summary.js +3 -3
  129. package/dist/src/telemetry/invocation.js +1 -2
  130. package/dist/src/telemetry/process-errors.js +17 -33
  131. package/dist/src/telemetry/sanitize.js +19 -4
  132. package/dist/src/telemetry/sls-sink.js +45 -20
  133. package/package.json +4 -4
  134. package/skills/gd-cli/SKILL.md +18 -5
  135. package/skills/gd-cli/references/agent.md +9 -4
  136. package/skills/gd-cli/references/creation.md +3 -1
  137. package/skills/gd-cli/references/editor.md +7 -5
  138. package/skills/gd-cli/references/errors.md +19 -8
  139. package/skills/gd-cli/references/matting.md +3 -5
  140. package/skills/gd-cli/references/media-tools.md +10 -4
  141. package/skills/gd-cli/references/tool.md +9 -15
@@ -1,5 +1,6 @@
1
1
  import { resolve } from "node:path";
2
- import { pathToFileURL } from "node:url";
2
+ import { fileUriFromLocalPath } from "../../platform/input-uri.js";
3
+ import { RemoteProtocolError } from "../../platform/remote-protocol.js";
3
4
  import { DamAssetNotDownloadableError } from "./dam-api-adapter.js";
4
5
  import { DamInputError, normalizeDamAssetId } from "./input.js";
5
6
  import { damAssetSourcePresent } from "./asset-projection.js";
@@ -19,8 +20,8 @@ function nonblank(value) {
19
20
  return value !== undefined && value.trim() !== "";
20
21
  }
21
22
  function assertPageSize(value) {
22
- if (value !== undefined && (!Number.isInteger(value) || value < 1 || value > 100))
23
- invalid("integer_1_to_100", "pageSize");
23
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 1))
24
+ invalid("positive_integer", "pageSize");
24
25
  }
25
26
  function assertPage(value) {
26
27
  if (value !== undefined && (!Number.isInteger(value) || value < 1))
@@ -97,8 +98,6 @@ export function createDamUseCases(dependencies) {
97
98
  invalid("nonblank", "targetFolderId");
98
99
  assertOptionalNonblank(input.repositoryId, "repositoryId");
99
100
  assertOptionalNonblank(input.targetRepositoryId, "targetRepositoryId");
100
- if (input.kind === "folder" && input.entry_id === input.targetFolderId)
101
- invalid("cannot_target_self", "targetFolderId");
102
101
  }
103
102
  async function entryOperation(input) {
104
103
  assertEntryOperationInput(input.request);
@@ -110,6 +109,9 @@ export function createDamUseCases(dependencies) {
110
109
  if (sourceRepository === undefined)
111
110
  throw new DamRepositoryNotFoundError();
112
111
  const targetRepositoryId = input.request.targetRepositoryId ?? sourceRepository.id;
112
+ if (input.request.kind === "folder" && input.request.entry_id === input.request.targetFolderId
113
+ && targetRepositoryId === sourceRepository.id)
114
+ invalid("cannot_target_self", "targetFolderId");
113
115
  const locationRequest = {
114
116
  entryId: input.request.entry_id,
115
117
  kind: input.request.kind,
@@ -165,13 +167,16 @@ export function createDamUseCases(dependencies) {
165
167
  if (input.repositoryId !== undefined)
166
168
  return [{ id: input.repositoryId }];
167
169
  signal.throwIfAborted();
168
- const available = await dependencies.repositories.list({ access, signal });
170
+ const available = await dependencies.repositories.list({ access, signal, allowPartial: input.allRepositories === true });
169
171
  signal.throwIfAborted();
170
172
  if (available.length === 0)
171
173
  throw new DamRepositoryNotFoundError();
174
+ const preferred = available.find(repository => repository.is_default);
175
+ if (!input.allRepositories && !preferred)
176
+ throw new RemoteProtocolError({}, undefined, "DAM_DEFAULT_REPOSITORY_UNKNOWN");
172
177
  const selected = input.allRepositories === true
173
178
  ? available
174
- : [available.find((repository) => repository.is_default) ?? available[0]];
179
+ : [preferred];
175
180
  return selected.map((repository) => ({
176
181
  id: repository.repository_id,
177
182
  ...(repository.name === undefined ? {} : { name: repository.name })
@@ -180,7 +185,7 @@ export function createDamUseCases(dependencies) {
180
185
  return {
181
186
  async repositoryList({ access, signal }) {
182
187
  signal.throwIfAborted();
183
- const repositories = await dependencies.repositories.list({ access, signal });
188
+ const repositories = await dependencies.repositories.list({ access, signal, allowPartial: true });
184
189
  signal.throwIfAborted();
185
190
  if (repositories.length === 0)
186
191
  throw new DamRepositoryNotFoundError();
@@ -448,7 +453,7 @@ export function createDamUseCases(dependencies) {
448
453
  if (!nonblank(input.file))
449
454
  invalid("nonblank", "file");
450
455
  const file = await dependencies.telemetry.stage("inspect", () => (dependencies.storage.inspect({
451
- url: pathToFileURL(resolve(process.cwd(), input.file)).href,
456
+ url: fileUriFromLocalPath(resolve(process.cwd(), input.file)),
452
457
  ...(input.allowSensitivePath === undefined
453
458
  ? {}
454
459
  : { allowSensitivePath: input.allowSensitivePath })
@@ -19,7 +19,6 @@ export function createEditorBridgeClient(options) {
19
19
  async health(signal) {
20
20
  const value = await request("/health", "GET", undefined, signal);
21
21
  if (!isRecord(value) ||
22
- !hasExactKeys(value, ["status", "pageConnected", "protocolVersion"]) ||
23
22
  value.status !== "ok" ||
24
23
  typeof value.pageConnected !== "boolean" ||
25
24
  typeof value.protocolVersion !== "number") {
@@ -42,7 +41,6 @@ export function createEditorBridgeClient(options) {
42
41
  async disconnect(signal) {
43
42
  const value = await request("/disconnect", "POST", {}, signal);
44
43
  if (!isRecord(value) ||
45
- !hasExactKeys(value, ["status"]) ||
46
44
  value.status !== "disconnected") {
47
45
  throw invalidResponse();
48
46
  }
@@ -1,3 +1,4 @@
1
+ import { startDetached } from "../../platform/detached-spawn.js";
1
2
  import { reportProcessError } from "../../telemetry/process-errors.js";
2
3
  import { spawn as nodeSpawn } from "node:child_process";
3
4
  import { resolve } from "node:path";
@@ -53,7 +54,7 @@ export function startEditorBridgeProcess(input) {
53
54
  return Promise.reject(abortReason(input.signal));
54
55
  let child;
55
56
  try {
56
- child = (input.spawn ?? nodeSpawn)(process.execPath, [
57
+ child = startDetached(() => (input.spawn ?? nodeSpawn)(process.execPath, [
57
58
  fileURLToPath(new URL("./bridge-process.js", import.meta.url)),
58
59
  input.targetOrigin,
59
60
  ...(input.stateDirectory === undefined
@@ -62,7 +63,7 @@ export function startEditorBridgeProcess(input) {
62
63
  ], {
63
64
  detached: true,
64
65
  stdio: ["ignore", "ignore", "ignore", "ipc"]
65
- });
66
+ }));
66
67
  }
67
68
  catch (cause) {
68
69
  return Promise.reject(cause);
@@ -1,36 +1 @@
1
- import { isSensitiveKey } from "../../platform/redact.js";
2
- const PRIVATE_SEGMENTS = new Set([
3
- "token",
4
- "signature",
5
- "secret",
6
- "password",
7
- "credential",
8
- "credentials"
9
- ]);
10
- const PRIVATE_FOCUSED_KEYS = new Set([
11
- "focused-editor-token",
12
- "focused-editor-port"
13
- ]);
14
- export function toPublicEditorUrl(input) {
15
- const output = new URL(input.href);
16
- removePrivateParameters(output.searchParams);
17
- const fragment = output.hash.slice(1);
18
- if (fragment.includes("=") || fragment.includes("&")) {
19
- const parameters = new URLSearchParams(fragment);
20
- removePrivateParameters(parameters);
21
- output.hash = parameters.toString();
22
- }
23
- return output;
24
- }
25
- function removePrivateParameters(parameters) {
26
- for (const key of new Set(parameters.keys())) {
27
- if (isPrivateKey(key))
28
- parameters.delete(key);
29
- }
30
- }
31
- function isPrivateKey(key) {
32
- const lower = key.toLowerCase();
33
- if (isSensitiveKey(key) || PRIVATE_FOCUSED_KEYS.has(lower))
34
- return true;
35
- return lower.split(/[-_.]+/u).some((part) => PRIVATE_SEGMENTS.has(part));
36
- }
1
+ export { filterUrlParameters as toPublicEditorUrl } from "../../platform/public-url.js";
@@ -4,6 +4,7 @@ import { createLocalJsonFile, LocalFileError } from "../../platform/local-json-f
4
4
  export function createEditorSessionStateStore(options = {}) {
5
5
  const file = options.file ?? createLocalJsonFile({
6
6
  directory: join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd"),
7
+ protectWindowsAcl: true,
7
8
  filename: "editor-session.json"
8
9
  });
9
10
  const read = async () => {
@@ -206,11 +206,12 @@ function resolveTarget(value, createUrl, workUrl, restrictTargets) {
206
206
  return url;
207
207
  }
208
208
  function buildHandoffUrl(target, state) {
209
- const url = new URL(target.href);
210
- url.hash = new URLSearchParams({
209
+ const url = toPublicEditorUrl(target, new Set(["focused-editor-token", "focused-editor-port"]));
210
+ const handshake = new URLSearchParams({
211
211
  "focused-editor-port": String(state.port),
212
212
  "focused-editor-token": state.token
213
213
  }).toString();
214
+ url.hash = url.hash ? url.hash.slice(1) + "&" + handshake : handshake;
214
215
  return url;
215
216
  }
216
217
  function abortableSleep(milliseconds, signal) {
@@ -23,8 +23,33 @@ export function createEditorUseCases(dependencies) {
23
23
  },
24
24
  async snapshot({ signal }) {
25
25
  const raw = await dependencies.session.rpc("snapshot", undefined, signal);
26
- const result = raw && typeof raw === "object" && "elements" in raw && "selectedIds" in raw
27
- ? { elements: raw.elements, selectedIds: raw.selectedIds } : raw;
26
+ if (!raw || typeof raw !== "object" || !("elements" in raw) || !Array.isArray(raw.elements) || !("selectedIds" in raw))
27
+ throw new OutputContractError();
28
+ const elements = [];
29
+ let skipped = 0;
30
+ for (const item of raw.elements) {
31
+ if (item && typeof item === "object") {
32
+ const keys = item._type === "shape" ? ["_type", "id", "shapeType", "x", "y", "w", "h", "text", "fill", "stroke"]
33
+ : item._type === "connector" ? ["_type", "id", "fromId", "toId", "lineType", "color"] : [];
34
+ const projected = Object.fromEntries(keys.filter(k => Object.hasOwn(item, k)).map(k => [k, item[k]]));
35
+ const one = { elements: [projected], selectedIds: [] };
36
+ try {
37
+ validate.snapshot(one);
38
+ elements.push(one.elements[0]);
39
+ continue;
40
+ }
41
+ catch (error) {
42
+ if (!(error instanceof OutputContractError))
43
+ throw error;
44
+ }
45
+ }
46
+ skipped++;
47
+ }
48
+ if (skipped && !elements.length)
49
+ throw new OutputContractError();
50
+ if (skipped)
51
+ dependencies.onPartial?.(skipped);
52
+ const result = { elements, selectedIds: raw.selectedIds };
28
53
  validate.snapshot(result);
29
54
  return result;
30
55
  },
@@ -16,13 +16,22 @@ export function createOrgService(dependencies) {
16
16
  throw new OrganizationResponseError();
17
17
  const records = [];
18
18
  const seen = new Set();
19
+ let unreadable = 0;
19
20
  for (const item of raw) {
20
21
  const record = normalizeOrganization(item);
21
- if (!record || seen.has(record.id))
22
+ if (!record) {
23
+ unreadable++;
24
+ continue;
25
+ }
26
+ if (seen.has(record.id))
22
27
  continue;
23
28
  seen.add(record.id);
24
29
  records.push(record);
25
30
  }
31
+ if (unreadable && !records.length)
32
+ throw new OrganizationResponseError();
33
+ if (unreadable)
34
+ dependencies.onPartial?.(unreadable);
26
35
  return records;
27
36
  }
28
37
  };
@@ -82,14 +82,28 @@ export function createOrgUseCases(dependencies) {
82
82
  async switchOrganization(input) {
83
83
  input.signal.throwIfAborted();
84
84
  dependencies.telemetry.annotate({ account_id: input.state.account?.id });
85
- const records = await dependencies.telemetry.stage("list", () => dependencies.org.list(input.state.credential, input.signal));
85
+ const records = await dependencies.telemetry.stage("list", async () => {
86
+ try {
87
+ return await dependencies.org.list(input.state.credential, input.signal);
88
+ }
89
+ catch (error) {
90
+ input.signal.throwIfAborted();
91
+ if (input.organizationId === undefined || !isExpectedAuthorizationFailure(error))
92
+ throw error;
93
+ return [];
94
+ }
95
+ });
86
96
  const { record, selectedId } = await dependencies.telemetry.stage("select", async () => {
87
97
  const selectedId = input.organizationId === undefined
88
98
  ? await selectOrganization(records, input.select)
89
99
  : requiredSelection(input.organizationId);
90
- const record = records.find((candidate) => candidate.id === selectedId);
91
- if (!record)
92
- throw new OrganizationInvalidError();
100
+ let record = records.find((candidate) => candidate.id === selectedId);
101
+ if (!record) {
102
+ if (input.organizationId === undefined)
103
+ throw new OrganizationInvalidError();
104
+ // The bind endpoint validates current membership; the discovery list is not an authorization decision.
105
+ record = { id: selectedId, realName: null, publicName: `组织 ${selectedId}` };
106
+ }
93
107
  return { record, selectedId };
94
108
  });
95
109
  dependencies.telemetry.annotate({ parameters: { organizationId: selectedId } });
@@ -0,0 +1,54 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ // If the OS cannot supply a start identity, an active worker renews its lease.
5
+ // An old PID alone must never keep a crashed worker's claim indefinitely.
6
+ const LEASE_MS = 60_000;
7
+ let ownGeneration;
8
+ function processGeneration(pid) {
9
+ try {
10
+ if (process.platform === "linux") {
11
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
12
+ // comm may contain spaces and parentheses. Fields after its final ')' start with field 3.
13
+ const startTicks = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
14
+ if (!startTicks || !/^\d+$/u.test(startTicks))
15
+ return;
16
+ return `${readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim()}:${startTicks}`;
17
+ }
18
+ const win = process.platform === "win32";
19
+ const command = win ? join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "/bin/ps";
20
+ const stamp = execFileSync(command, win
21
+ ? ["-NoProfile", "-NonInteractive", "-Command", `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc()`]
22
+ : ["-p", String(pid), "-o", "lstart="], {
23
+ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 700, windowsHide: true,
24
+ env: { ...process.env, LC_ALL: "C", TZ: "UTC" }
25
+ }).trim();
26
+ return stamp || undefined;
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
32
+ export function taskProcessGeneration(pid = process.pid) {
33
+ if (pid !== process.pid)
34
+ return processGeneration(pid);
35
+ if (ownGeneration === undefined)
36
+ ownGeneration = processGeneration(process.pid) ?? null;
37
+ return ownGeneration ?? undefined;
38
+ }
39
+ export function taskProcessAlive(pid, generation, heartbeatAtMs) {
40
+ if (!Number.isSafeInteger(pid) || !pid || pid <= 0)
41
+ return false;
42
+ try {
43
+ process.kill(pid, 0);
44
+ }
45
+ catch (error) {
46
+ if (error instanceof Error && "code" in error && error.code === "ESRCH")
47
+ return false;
48
+ }
49
+ if (generation && pid === process.pid)
50
+ return generation === taskProcessGeneration();
51
+ if (Number.isFinite(heartbeatAtMs) && Math.abs(Date.now() - heartbeatAtMs) < LEASE_MS)
52
+ return true;
53
+ return !!generation && generation === processGeneration(pid);
54
+ }
@@ -1,14 +1,28 @@
1
- import { withFileLock } from "../../platform/file-lock.js";
1
+ import { fileLockDirectory, withFileLock } from "../../platform/file-lock.js";
2
2
  import { createHash } from "node:crypto";
3
- import { readdir, lstat } from "node:fs/promises";
3
+ import { readdir, lstat, mkdir } from "node:fs/promises";
4
4
  import { homedir } from "node:os";
5
5
  import { join } from "node:path";
6
- import { createLocalJsonFile, LocalFileError } from "../../platform/local-json-file.js";
6
+ import { confirmMissingPath, createLocalJsonFile, LocalFileError } from "../../platform/local-json-file.js";
7
+ import { pinWindowsStateDirectories, readWindowsPrivateText } from "../../platform/windows-private-state.js";
7
8
  export class TaskStoreError extends LocalFileError {
8
9
  context;
9
10
  constructor(cause) { super(cause); this.name = "TaskStoreError"; }
10
11
  }
11
12
  export const validTaskId = (id) => /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/iu.test(id);
13
+ function mergeProgress(previous, incoming) {
14
+ const progress = { ...previous, ...incoming };
15
+ for (const key of ["accepted", "submissionStarted", "detached", "agentUsageModelMissing", "agentUsageAmountMissing"]) {
16
+ if (previous[key])
17
+ progress[key] = true;
18
+ }
19
+ // A stale reader or heartbeat cannot roll back child receipts or a saved final PNG.
20
+ const previousCheckpoint = previous.toolPipeline?.checkpoint;
21
+ if (previous.toolPipeline && previousCheckpoint !== undefined && previousCheckpoint >= (incoming.toolPipeline?.checkpoint ?? 0)) {
22
+ progress.toolPipeline = previous.toolPipeline;
23
+ }
24
+ return progress;
25
+ }
12
26
  export function taskScope(state) {
13
27
  return createHash("sha256").update(JSON.stringify([
14
28
  state.account ? ["account", state.account.id] : ["credential", state.credential.accessKey],
@@ -16,23 +30,31 @@ export function taskScope(state) {
16
30
  ])).digest("hex");
17
31
  }
18
32
  export function createTaskStore(options) {
19
- const root = join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd", "tasks", "v6");
33
+ const home = options.homeDirectory ?? homedir();
34
+ const stateDirectory = options.stateDirectory ?? ".gd";
35
+ const root = join(home, stateDirectory, "tasks", "v6");
36
+ const lockOptions = process.platform === "win32" ? { readOwner: readWindowsPrivateText } : {};
20
37
  function file(scope, id) {
21
- if (!/^[a-f0-9]{64}$/u.test(scope) || !validTaskId(id))
22
- throw new LocalFileError(undefined);
23
- return createLocalJsonFile({ directory: join(root, scope), filename: `${id}.json`, role: "task" });
38
+ return createLocalJsonFile({ directory: join(root, scope), filename: `${id}.json`, role: "task", protectWindowsAcl: true });
24
39
  }
25
40
  const store = {
26
41
  async read(scope, id, summaryOnly = false) {
27
42
  const stateFile = file(scope, id);
28
43
  try {
29
44
  const stat = await lstat(join(root, scope, `${id}.json`));
30
- if (!stat.isFile() || stat.isSymbolicLink())
45
+ if (!stat.isFile() || stat.isSymbolicLink() || (process.platform === "win32" && stat.nlink !== 1))
31
46
  throw new LocalFileError(undefined, undefined, "invalid_data", { operation: "read", step: "stat" });
32
47
  }
33
48
  catch (error) {
34
- if (error instanceof Error && "code" in error && error.code === "ENOENT")
35
- return null;
49
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
50
+ try {
51
+ await confirmMissingPath(join(root, scope), error);
52
+ return null;
53
+ }
54
+ catch (cause) {
55
+ throw new LocalFileError(cause, undefined, "io", { operation: "read", step: "stat" });
56
+ }
57
+ }
36
58
  if (error instanceof LocalFileError)
37
59
  throw error;
38
60
  throw new LocalFileError(error, undefined, "io", { operation: "read", step: "stat" });
@@ -47,6 +69,10 @@ export function createTaskStore(options) {
47
69
  if (record.version !== 1 || record.task.taskId !== id || !record.progress
48
70
  || typeof record.progress !== "object" || Array.isArray(record.progress))
49
71
  throw new Error();
72
+ if (Object.hasOwn(record.progress, "toolRun") && !["completed", "failed"].includes(record.task.state)) {
73
+ record.task.state = "unknown";
74
+ delete record.task.note;
75
+ }
50
76
  if (summaryOnly && options.validateSummary) {
51
77
  const { result, partialResult, ...summary } = record.task;
52
78
  options.validateSummary(summary);
@@ -67,7 +93,7 @@ export function createTaskStore(options) {
67
93
  if (record.progress[key] !== undefined && typeof record.progress[key] !== "string")
68
94
  throw new Error();
69
95
  }
70
- for (const key of ["submissionStarted", "detached", "accepted", "agentUsageModelMissing"]) {
96
+ for (const key of ["submissionStarted", "detached", "accepted", "agentUsageModelMissing", "agentUsageAmountMissing"]) {
71
97
  if (record.progress[key] !== undefined && typeof record.progress[key] !== "boolean")
72
98
  throw new Error();
73
99
  }
@@ -78,17 +104,13 @@ export function createTaskStore(options) {
78
104
  }
79
105
  },
80
106
  async write(scope, record) {
81
- file(scope, record.task.taskId);
82
107
  await withFileLock(join(root, scope, `${record.task.taskId}.lock`), async () => {
83
108
  const previous = await store.read(scope, record.task.taskId);
84
109
  if (previous) {
85
- record.progress = { ...previous.progress, ...record.progress };
86
- for (const key of ["accepted", "submissionStarted", "detached", "agentUsageModelMissing"]) {
87
- if (previous.progress[key])
88
- record.progress[key] = true;
89
- }
90
- if (previous.task.state === "completed" || (previous.task.state === "failed" && record.task.state !== "completed"))
110
+ record.progress = mergeProgress(previous.progress, record.progress);
111
+ if (previous.task.state === "completed" || (previous.task.state === "failed" && record.task.state !== "completed")) {
91
112
  record.task = previous.task;
113
+ }
92
114
  if (previous.analytics)
93
115
  record.analytics = { ...record.analytics, ...previous.analytics };
94
116
  if (previous.telemetry) {
@@ -102,10 +124,9 @@ export function createTaskStore(options) {
102
124
  }
103
125
  options.validate(record.task);
104
126
  await file(scope, record.task.taskId).writeTextAtomically(`${JSON.stringify(record)}\n`);
105
- }, { action: "task_write" });
127
+ }, { ...lockOptions, action: "task_write" });
106
128
  },
107
129
  async update(scope, id, change) {
108
- file(scope, id);
109
130
  return withFileLock(join(root, scope, `${id}.lock`), async () => {
110
131
  const record = await store.read(scope, id);
111
132
  if (!record)
@@ -114,7 +135,7 @@ export function createTaskStore(options) {
114
135
  options.validate(record.task);
115
136
  await file(scope, id).writeTextAtomically(`${JSON.stringify(record)}\n`);
116
137
  return record;
117
- }, { action: "task_update" });
138
+ }, { ...lockOptions, action: "task_update" });
118
139
  },
119
140
  async list(scope) {
120
141
  let names;
@@ -122,34 +143,83 @@ export function createTaskStore(options) {
122
143
  names = await readdir(join(root, scope));
123
144
  }
124
145
  catch (error) {
125
- if (error instanceof Error && "code" in error && error.code === "ENOENT")
126
- return [];
146
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
147
+ try {
148
+ await confirmMissingPath(join(root, scope), error);
149
+ return [];
150
+ }
151
+ catch (cause) {
152
+ throw new LocalFileError(cause, undefined, "io", { operation: "list", step: "directory_read" });
153
+ }
154
+ }
127
155
  throw new LocalFileError(error, undefined, "io", { operation: "list", step: "directory_read" });
128
156
  }
129
157
  const records = [];
158
+ const corrupt = [];
130
159
  for (const name of names) {
131
160
  if (!name.endsWith(".json") || !validTaskId(name.slice(0, -5)))
132
161
  continue;
133
- const record = await store.read(scope, name.slice(0, -5), true);
134
- if (record)
135
- records.push(record);
162
+ try {
163
+ const record = await store.read(scope, name.slice(0, -5), true);
164
+ if (record)
165
+ records.push(record);
166
+ }
167
+ catch (error) {
168
+ if (!(error instanceof LocalFileError) || error.reason !== "invalid_data")
169
+ throw error;
170
+ corrupt.push(error);
171
+ }
172
+ }
173
+ if (corrupt.length) {
174
+ if (!records.length)
175
+ throw corrupt[0];
176
+ options.onUnreadableRecords?.(corrupt.length);
136
177
  }
137
178
  return records.sort((a, b) => b.task.createdAt.localeCompare(a.task.createdAt)
138
179
  || a.task.taskId.localeCompare(b.task.taskId));
139
180
  }
140
181
  };
141
- async function access(operation) {
182
+ async function access(scope, request, run) {
183
+ let release;
142
184
  try {
143
- return await operation();
185
+ if (!/^[a-f0-9]{64}$/u.test(scope) || ("id" in request && !validTaskId(request.id)))
186
+ throw new LocalFileError(undefined);
187
+ if (process.platform === "win32") {
188
+ const components = [stateDirectory, "tasks", "v6", scope];
189
+ try {
190
+ if (request.operation === "write") {
191
+ await mkdir(home, { recursive: true });
192
+ components.push(fileLockDirectory(`${request.id}.lock`));
193
+ }
194
+ release = pinWindowsStateDirectories(home, components, request.operation === "write");
195
+ }
196
+ catch (cause) {
197
+ if (request.operation !== "write" && cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
198
+ try {
199
+ await confirmMissingPath(home, cause);
200
+ return request.missing;
201
+ }
202
+ catch (error) {
203
+ cause = error;
204
+ }
205
+ }
206
+ throw new LocalFileError(cause, undefined, "io", { role: "task", operation: request.operation,
207
+ step: request.operation === "list" ? "directory_read" : "directory_permissions" });
208
+ }
209
+ }
210
+ return await run();
144
211
  }
145
212
  catch (cause) {
146
213
  throw new TaskStoreError(cause);
147
214
  }
215
+ finally {
216
+ release?.();
217
+ }
148
218
  }
149
219
  return {
150
- update: (scope, id, change) => access(() => store.update(scope, id, change)),
151
- read: (scope, id) => access(() => store.read(scope, id)),
152
- write: (scope, record) => access(() => store.write(scope, record)),
153
- list: scope => access(() => store.list(scope))
220
+ update: (scope, id, change) => access(scope, { operation: "write", id }, () => store.update(scope, id, change)),
221
+ read: (scope, id) => access(scope, { operation: "read", id, missing: null }, () => store.read(scope, id)),
222
+ write: (scope, record) => access(scope, { operation: "write", id: record?.task?.taskId }, () => store.write(scope, record)),
223
+ list: scope => access(scope, { operation: "list", missing: [] }, () => store.list(scope))
154
224
  };
155
225
  }
@@ -1,3 +1,4 @@
1
+ import { startDetached } from "../../platform/detached-spawn.js";
1
2
  import { fork } from "node:child_process";
2
3
  import { safeFailureSummary } from "../../telemetry/failure-summary.js";
3
4
  import { validTaskId } from "./store.js";
@@ -89,17 +90,17 @@ export function taskWorkerUnavailableError(options) {
89
90
  }
90
91
  export function createTaskBackgroundLauncher(options) {
91
92
  return {
92
- submit(job, signal, started) {
93
+ submit(job, signal, started, observeReceipt) {
93
94
  signal.throwIfAborted();
94
95
  return new Promise((resolve, reject) => {
95
96
  let child;
96
97
  try {
97
- child = (options.fork ?? fork)(options.workerPath, [], {
98
+ child = startDetached(() => (options.fork ?? fork)(options.workerPath, [], {
98
99
  detached: true,
99
100
  stdio: ["ignore", "ignore", "ignore", "ipc"],
100
101
  execArgv: [],
101
102
  env: { ...process.env, ...options.env }
102
- });
103
+ }));
103
104
  }
104
105
  catch (cause) {
105
106
  reject(taskWorkerUnavailableError({ product: job.product, phase: "spawn", cause }));
@@ -145,9 +146,12 @@ export function createTaskBackgroundLauncher(options) {
145
146
  child.on("message", (message) => {
146
147
  if (settled)
147
148
  return;
149
+ if (message.type !== "error" && message.execution_protocol && ["dify", "toolkit", "sync"].includes(message.execution_protocol)) {
150
+ observeReceipt?.({ execution_protocol: message.execution_protocol });
151
+ }
148
152
  if (message.type === "started") {
149
153
  taskId = message.task.taskId;
150
- started(message.task);
154
+ started(message.task, diagnosticToken(message.creationTraceId, /^[0-9a-f]{32}$/u));
151
155
  }
152
156
  else if (message.type === "accepted")
153
157
  finish(message.task);