@gaoding/cli 1.1.0 → 1.3.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.
Files changed (65) hide show
  1. package/contracts/operations/task.get/input.schema.json +14 -0
  2. package/contracts/operations/task.get/output.schema.json +103 -0
  3. package/contracts/operations/task.list/input.schema.json +18 -0
  4. package/contracts/operations/task.list/output.schema.json +53 -0
  5. package/dist/bin/agent-worker.js +41 -0
  6. package/dist/bin/gd-cli.js +2 -1
  7. package/dist/bin/insmind-cli.js +60 -0
  8. package/dist/bin/postinstall.js +1 -1
  9. package/dist/src/bootstrap/create-cli.js +16 -4
  10. package/dist/src/bootstrap/create-runtime.js +190 -33
  11. package/dist/src/bootstrap/run-agent-worker.js +37 -0
  12. package/dist/src/bootstrap/validators.js +17 -5
  13. package/dist/src/cli/agent-commands.js +40 -14
  14. package/dist/src/cli/auth-commands.js +13 -10
  15. package/dist/src/cli/credits-command.js +23 -0
  16. package/dist/src/cli/dam-commands.js +70 -69
  17. package/dist/src/cli/editor-commands.js +12 -11
  18. package/dist/src/cli/errors.js +60 -9
  19. package/dist/src/cli/model-commands.js +6 -5
  20. package/dist/src/cli/presenter.js +24 -6
  21. package/dist/src/cli/task-commands.js +48 -0
  22. package/dist/src/cli/tool-commands.js +38 -14
  23. package/dist/src/cli/update-command.js +4 -3
  24. package/dist/src/features/agent/creative-agent-adapter.js +9 -3
  25. package/dist/src/features/agent/creative-protocol.js +5 -16
  26. package/dist/src/features/agent/creative-stream.js +12 -1
  27. package/dist/src/features/agent/filems-resource-auth-key-provider.js +23 -0
  28. package/dist/src/features/agent/resource-authorizer.js +47 -0
  29. package/dist/src/features/agent/result-reader.js +30 -0
  30. package/dist/src/features/agent/use-cases.js +98 -95
  31. package/dist/src/features/auth/credential-store.js +1 -1
  32. package/dist/src/features/auth/sso-service.js +3 -1
  33. package/dist/src/features/auth/use-cases.js +38 -12
  34. package/dist/src/features/credits/use-cases.js +52 -0
  35. package/dist/src/features/dam/storage-upload.js +1 -1
  36. package/dist/src/features/editor/bridge-process.js +11 -4
  37. package/dist/src/features/editor/session-state.js +1 -1
  38. package/dist/src/features/editor/session.js +14 -8
  39. package/dist/src/features/org/use-cases.js +7 -0
  40. package/dist/src/features/skill/bundled-skills.js +13 -5
  41. package/dist/src/features/task/agent-background.js +63 -0
  42. package/dist/src/features/task/store.js +97 -0
  43. package/dist/src/features/task/types.js +1 -0
  44. package/dist/src/features/task/use-cases.js +139 -0
  45. package/dist/src/features/tool/catalog.js +13 -13
  46. package/dist/src/features/tool/tool-api-adapter.js +53 -36
  47. package/dist/src/features/tool/use-cases.js +111 -108
  48. package/dist/src/features/update/latest-version.js +2 -2
  49. package/dist/src/features/update/update-notification.js +10 -3
  50. package/dist/src/features/update/update-service.js +57 -23
  51. package/dist/src/platform/resource-auth-key.js +1 -0
  52. package/dist/src/platform/signed-http-transport.js +1 -0
  53. package/dist/src/platform/task-observer.js +1 -0
  54. package/dist/src/product/billing.js +47 -0
  55. package/dist/src/product/config.js +85 -0
  56. package/dist/src/product/locale.js +38 -0
  57. package/dist/src/product/text.js +3 -0
  58. package/dist/src/telemetry/sls-sink.js +1 -2
  59. package/package.json +5 -5
  60. package/skills/gd-cli/SKILL.md +1 -1
  61. package/skills/gd-cli/references/agent.md +34 -0
  62. package/skills/gd-cli/references/creation.md +5 -73
  63. package/skills/gd-cli/references/errors.md +18 -2
  64. package/skills/gd-cli/references/generation-constraints.md +36 -0
  65. package/skills/gd-cli/references/tool.md +31 -0
@@ -0,0 +1,139 @@
1
+ import { redactSensitiveText } from "../../platform/redact.js";
2
+ import { taskScope } from "./store.js";
3
+ export class TaskNotFoundError extends Error {
4
+ constructor(message) { super(message); }
5
+ }
6
+ // Cached results are private output data, but expiring resource credentials are
7
+ // removed. Query delivery uses the existing authorization adapter again.
8
+ export function withoutResourceKeys(value) {
9
+ function clean(item) {
10
+ if (typeof item === "string") {
11
+ return item.replace(/https?:\/\/[^\s<>"`\]\)]+/gu, raw => {
12
+ try {
13
+ const url = new URL(raw);
14
+ if (!url.searchParams.has("auth_key"))
15
+ return raw;
16
+ url.searchParams.delete("auth_key");
17
+ return url.href;
18
+ }
19
+ catch {
20
+ return raw;
21
+ }
22
+ });
23
+ }
24
+ if (Array.isArray(item))
25
+ return item.map(clean);
26
+ if (item && typeof item === "object")
27
+ return Object.fromEntries(Object.entries(item)
28
+ .filter(([key]) => key.toLowerCase().replaceAll("_", "") !== "authkey")
29
+ .map(([key, nested]) => [key, clean(nested)]));
30
+ return item;
31
+ }
32
+ return clean(value);
33
+ }
34
+ const HEARTBEAT_MS = 5_000;
35
+ const LEASE_MS = 15_000;
36
+ export function createTaskUseCases(dependencies) {
37
+ const { text, commandName } = dependencies;
38
+ function summary(record) {
39
+ const { result: _result, partialResult: _partial, ...task } = record.task;
40
+ if (!record.progress.detached && task.state === "running"
41
+ && dependencies.now().getTime() - Date.parse(task.updatedAt) >= LEASE_MS) {
42
+ return { ...task, state: "unknown", note: text("原 CLI 未继续更新记录;使用 task get 查询,不能据此重新生成。", "The original CLI stopped updating this task. Use task get to check; do not submit again.") };
43
+ }
44
+ return task;
45
+ }
46
+ async function execute(input, finish) {
47
+ const scope = taskScope(input.state);
48
+ const timestamp = dependencies.now().toISOString();
49
+ const record = {
50
+ version: 1, progress: {},
51
+ task: { taskId: dependencies.idFactory(), operation: input.operation,
52
+ label: redactSensitiveText(input.label).slice(0, 200),
53
+ createdAt: timestamp, updatedAt: timestamp, state: "running" }
54
+ };
55
+ await dependencies.store.write(scope, record);
56
+ input.onUpdate?.(structuredClone(record.task), { ...record.progress });
57
+ dependencies.notice(text(`任务 ID: ${record.task.taskId};结果未收到时执行 ${commandName} task get ${record.task.taskId}`, `Task ID: ${record.task.taskId}; retrieve missing output with ${commandName} task get ${record.task.taskId}`));
58
+ let writes = Promise.resolve();
59
+ const save = () => {
60
+ record.task.updatedAt = dependencies.now().toISOString();
61
+ const snapshot = structuredClone(record);
62
+ writes = writes.catch(() => undefined).then(() => dependencies.store.write(scope, snapshot));
63
+ return writes;
64
+ };
65
+ const timer = setInterval(() => { void save().catch(() => undefined); }, HEARTBEAT_MS);
66
+ timer.unref();
67
+ try {
68
+ const result = await input.run(async (progress) => {
69
+ Object.assign(record.progress, progress);
70
+ if (progress.contextId)
71
+ record.task.contextId = progress.contextId;
72
+ await save();
73
+ input.onUpdate?.(structuredClone(record.task), { ...record.progress });
74
+ });
75
+ clearInterval(timer);
76
+ finish(record, result);
77
+ await save();
78
+ return { task: record.task, result };
79
+ }
80
+ catch (error) {
81
+ clearInterval(timer);
82
+ if (record.task.state !== "completed") {
83
+ record.task.state = record.progress.submissionStarted ? "unknown" : "failed";
84
+ record.task.note = record.progress.submissionStarted
85
+ ? text("CLI 未取得完整回执或结果;远端可能仍在执行。查询原任务,不自动重新生成。", "The CLI did not receive a complete receipt or result; the service may still be running. Query this task instead of submitting again.")
86
+ : text("CLI 在提交创作前结束;具体错误见原命令。", "The CLI stopped before submitting the creation. See the original command for the error.");
87
+ }
88
+ const detail = dependencies.failureNote?.(error);
89
+ if (detail)
90
+ record.task.note = `${record.task.note} ${redactSensitiveText(detail)}`;
91
+ await save().catch(() => undefined);
92
+ throw error;
93
+ }
94
+ }
95
+ return {
96
+ async track(input) {
97
+ return (await execute(input, (record, result) => {
98
+ record.task.state = "completed";
99
+ record.task.result = withoutResourceKeys(result);
100
+ if ("message" in result)
101
+ record.task.contextId = result.message.contextId;
102
+ })).result;
103
+ },
104
+ async submit(input) {
105
+ return (await execute(input, record => { record.progress.detached = true; })).task;
106
+ },
107
+ async list({ state, limit, operation }) {
108
+ const records = await dependencies.store.list(taskScope(state));
109
+ return { tasks: records.filter(r => !operation || r.task.operation === operation).slice(0, limit).map(summary) };
110
+ },
111
+ async get({ state, id, signal }) {
112
+ signal.throwIfAborted();
113
+ const scope = taskScope(state);
114
+ const record = await dependencies.store.read(scope, id);
115
+ if (!record)
116
+ throw new TaskNotFoundError(text(`当前身份中没有该任务。请执行 ${commandName} task list 查找。`, `No task was found in the current identity context. Use ${commandName} task list to find it.`));
117
+ if (record.task.state === "completed" && record.task.result) {
118
+ return { ...record.task, result: await dependencies.recovery.authorize(record.task.result, state, signal) };
119
+ }
120
+ const task = summary(record);
121
+ if (task.state === "failed" || (task.state === "running" && !record.progress.detached))
122
+ return task;
123
+ const recovered = await dependencies.recovery[task.operation === "agent.send" ? "agent" : "tool"](record.progress, state, signal);
124
+ const { note: _note, ...metadata } = task;
125
+ const result = { ...metadata, ...recovered };
126
+ if (result.state === "unknown" && task.note) {
127
+ result.note = [task.note, recovered.note].filter(Boolean).join(" ");
128
+ }
129
+ // Only detached tasks have no original writer. Cache terminal results before
130
+ // delivery, without saving expiring resource authorization credentials.
131
+ if (record.progress.detached && (result.state === "completed" || result.state === "failed")) {
132
+ result.updatedAt = dependencies.now().toISOString();
133
+ record.task = withoutResourceKeys(result);
134
+ await dependencies.store.write(scope, record);
135
+ }
136
+ return result;
137
+ }
138
+ };
139
+ }
@@ -1,10 +1,4 @@
1
- export class ToolInputError extends Error {
2
- constructor() {
3
- super("Tool 输入不可用。");
4
- this.name = "ToolInputError";
5
- }
6
- }
7
- const tools = [
1
+ export const defaultToolDefinitions = [
8
2
  {
9
3
  name: "image.generate",
10
4
  title: "图片生成与编辑",
@@ -21,11 +15,17 @@ const tools = [
21
15
  description: "使用已发布的文本模型,根据文本和可选图片生成文本。"
22
16
  }
23
17
  ];
24
- function toolIndex(tool) {
18
+ export class ToolInputError extends Error {
19
+ constructor() {
20
+ super("Tool 输入不可用。");
21
+ this.name = "ToolInputError";
22
+ }
23
+ }
24
+ function toolIndex(tool, tools) {
25
25
  return tools.findIndex((candidate) => candidate.name === tool);
26
26
  }
27
- function compareModels(left, right) {
28
- return toolIndex(left.tool) - toolIndex(right.tool)
27
+ function compareModels(left, right, tools) {
28
+ return toolIndex(left.tool, tools) - toolIndex(right.tool, tools)
29
29
  || left.sceneSort - right.sceneSort
30
30
  || left.modelSort - right.modelSort
31
31
  || (left.model < right.model ? -1 : left.model > right.model ? 1 : 0);
@@ -40,19 +40,19 @@ function summary(model) {
40
40
  ...(model.estimatedTime === undefined ? {} : { estimatedTime: model.estimatedTime })
41
41
  };
42
42
  }
43
- export function projectToolList(catalog) {
43
+ export function projectToolList(catalog, tools = defaultToolDefinitions) {
44
44
  return {
45
45
  tools: tools.filter((tool) => catalog.models.some((model) => model.tool === tool.name))
46
46
  };
47
47
  }
48
- export function projectModelList(catalog, tool) {
48
+ export function projectModelList(catalog, tool, tools = defaultToolDefinitions) {
49
49
  if (tool !== undefined && !catalog.models.some((model) => model.tool === tool)) {
50
50
  throw new ToolInputError();
51
51
  }
52
52
  return {
53
53
  models: catalog.models
54
54
  .filter((model) => tool === undefined || model.tool === tool)
55
- .toSorted(compareModels)
55
+ .toSorted((left, right) => compareModels(left, right, tools))
56
56
  .map(summary)
57
57
  };
58
58
  }
@@ -135,6 +135,15 @@ export class ToolTaskFailedError extends Error {
135
135
  this.remoteBody = evidence.remoteBody;
136
136
  }
137
137
  }
138
+ export async function queryToolResult(transport, request) {
139
+ return pollResult(await safePost(transport, {
140
+ credential: request.credential,
141
+ ...(request.organizationId === undefined ? {} : { organizationId: request.organizationId }),
142
+ signal: request.signal,
143
+ path: "/gdesign/tool/v1/dify/process/batch",
144
+ body: { task_ids: [request.taskId] }
145
+ }), request.taskId);
146
+ }
138
147
  function failedPoll(error, difyTaskId) {
139
148
  return {
140
149
  state: "failed",
@@ -267,49 +276,57 @@ function defaultContentId() {
267
276
  export function createToolApiAdapter(dependencies) {
268
277
  const createContentId = dependencies.contentIdFactory ?? defaultContentId;
269
278
  const sleep = dependencies.sleep ?? defaultSleep;
270
- return {
271
- async execute({ invocation, access, signal }) {
272
- signal.throwIfAborted();
273
- const managedContentId = contentId(createContentId());
274
- const resolved = invocation.kind === "direct"
275
- ? { name: invocation.name, arguments: invocation.arguments }
276
- : await dependencies.telemetry.stage("intent", async () => {
277
- const intent = parseIntent(await safePost(dependencies.transport, {
278
- path: "/ai-agent/v1/tool-intent",
279
- body: {
280
- prompt: invocation.prompt,
281
- scene_code: invocation.model,
282
- parameters: invocation.parameters
283
- },
284
- credential: access.credential,
285
- organizationId: access.organizationId,
286
- signal
287
- }));
288
- return {
289
- ...intent,
290
- arguments: withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters)
291
- };
292
- });
293
- signal.throwIfAborted();
294
- const taskId = await dependencies.telemetry.stage("submit", async () => {
295
- dependencies.telemetry.annotate({ content_id: managedContentId });
296
- return submittedTask(await safePost(dependencies.transport, {
297
- path: "/gdesign/tool/v1/dify/call_async",
279
+ async function submit({ invocation, access, signal, observe }) {
280
+ signal.throwIfAborted();
281
+ const managedContentId = contentId(createContentId());
282
+ const resolved = invocation.kind === "direct"
283
+ ? { name: invocation.name, arguments: invocation.arguments }
284
+ : await dependencies.telemetry.stage("intent", async () => {
285
+ const intent = parseIntent(await safePost(dependencies.transport, {
286
+ path: "/ai-agent/v1/tool-intent",
298
287
  body: {
299
- jsonrpc: "2.0",
300
- id: 0,
301
- method: "tools/call",
302
- params: {
303
- name: resolved.name,
304
- arguments: { ...resolved.arguments, content_id: managedContentId }
305
- }
288
+ prompt: invocation.prompt,
289
+ scene_code: invocation.model,
290
+ parameters: invocation.parameters
306
291
  },
307
292
  credential: access.credential,
308
293
  organizationId: access.organizationId,
309
294
  signal
310
295
  }));
296
+ return {
297
+ ...intent,
298
+ arguments: withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters)
299
+ };
311
300
  });
312
- dependencies.telemetry.annotate({ task_id: taskId });
301
+ signal.throwIfAborted();
302
+ await observe?.({ submissionStarted: true });
303
+ const taskId = await dependencies.telemetry.stage("submit", async () => {
304
+ dependencies.telemetry.annotate({ content_id: managedContentId });
305
+ return submittedTask(await safePost(dependencies.transport, {
306
+ path: "/gdesign/tool/v1/dify/call_async",
307
+ body: {
308
+ jsonrpc: "2.0",
309
+ id: 0,
310
+ method: "tools/call",
311
+ params: {
312
+ name: resolved.name,
313
+ arguments: { ...resolved.arguments, content_id: managedContentId }
314
+ }
315
+ },
316
+ credential: access.credential,
317
+ organizationId: access.organizationId,
318
+ signal
319
+ }));
320
+ });
321
+ await observe?.({ remoteTaskId: taskId });
322
+ dependencies.telemetry.annotate({ task_id: taskId });
323
+ return taskId;
324
+ }
325
+ return {
326
+ async submit(input) { await submit(input); },
327
+ async execute(input) {
328
+ const { access, signal } = input;
329
+ const taskId = await submit(input);
313
330
  return dependencies.telemetry.stage("wait", async () => {
314
331
  let transientFailures = 0;
315
332
  while (true) {
@@ -1,5 +1,5 @@
1
1
  import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
2
- import { findToolModel, projectModelDetail, projectModelList, projectToolList, ToolInputError } from "./catalog.js";
2
+ import { findToolModel, defaultToolDefinitions, projectModelDetail, projectModelList, projectToolList, ToolInputError } from "./catalog.js";
3
3
  import { assertModelArguments, buildToolArgumentsSchema } from "./dynamic-schema.js";
4
4
  const mediaTypes = {
5
5
  avif: "image/avif",
@@ -54,12 +54,112 @@ export function createToolUseCases(dependencies) {
54
54
  dependencies.warn(warning);
55
55
  return catalog;
56
56
  }
57
+ async function prepare({ input, access, signal, observe }) {
58
+ const catalog = await load(access, signal);
59
+ const model = await dependencies.telemetry.stage("input", () => {
60
+ const modelName = input.arguments.model;
61
+ if (typeof modelName !== "string")
62
+ throw new ToolInputError();
63
+ const selected = findToolModel(catalog, input.name, modelName);
64
+ assertModelArguments(selected, input.arguments);
65
+ return selected;
66
+ });
67
+ const { model: ignoredModel, ...parameters } = input.arguments;
68
+ void ignoredModel;
69
+ dependencies.telemetry.annotate({
70
+ tool_name: model.tool,
71
+ model_id: model.model,
72
+ parameters
73
+ });
74
+ const prompt = [];
75
+ const requestParameters = {};
76
+ const directArguments = {};
77
+ const prepare = async () => {
78
+ for (const parameter of model.parameters) {
79
+ signal.throwIfAborted();
80
+ const value = input.arguments[parameter.name];
81
+ if (value === undefined)
82
+ continue;
83
+ if (parameter.type === "string") {
84
+ if (parameter.name === "prompt") {
85
+ prompt.push({ type: "text", content: value });
86
+ directArguments[parameter.name] = value;
87
+ }
88
+ else {
89
+ requestParameters[parameter.name] = value;
90
+ directArguments[parameter.name] = value;
91
+ }
92
+ continue;
93
+ }
94
+ if (parameter.type === "number") {
95
+ requestParameters[parameter.name] = value;
96
+ directArguments[parameter.name] = value;
97
+ continue;
98
+ }
99
+ const values = parameter.type === "uri[]" ? value : [value];
100
+ for (const mediaUrl of values) {
101
+ signal.throwIfAborted();
102
+ if (mediaUrl.startsWith("file:")) {
103
+ const uploaded = await dependencies.uploader.upload({ url: mediaUrl }, access, signal);
104
+ signal.throwIfAborted();
105
+ prompt.push({
106
+ type: "media",
107
+ url: uploaded.url,
108
+ mime: uploaded.mediaType,
109
+ name: parameter.name
110
+ });
111
+ }
112
+ else {
113
+ prompt.push(remoteMedia(mediaUrl, parameter.name));
114
+ }
115
+ }
116
+ }
117
+ };
118
+ const hasLocalMedia = model.parameters.some((parameter) => {
119
+ const value = input.arguments[parameter.name];
120
+ return parameter.type === "uri"
121
+ ? typeof value === "string" && value.startsWith("file:")
122
+ : parameter.type === "uri[]"
123
+ && Array.isArray(value) && value.some((url) => url.startsWith("file:"));
124
+ });
125
+ if (hasLocalMedia) {
126
+ await dependencies.telemetry.stage("upload", prepare);
127
+ }
128
+ else {
129
+ await prepare();
130
+ }
131
+ signal.throwIfAborted();
132
+ const requiresIntent = prompt.some((item) => item.type === "media")
133
+ || Object.values(requestParameters).some((value) => value === "");
134
+ const invocation = requiresIntent
135
+ ? {
136
+ kind: "intent",
137
+ model: model.model,
138
+ prompt,
139
+ parameters: requestParameters,
140
+ optionalMediaParameters: model.parameters
141
+ .filter((parameter) => ((parameter.type === "uri" || parameter.type === "uri[]")
142
+ && !parameter.required))
143
+ .map((parameter) => parameter.name)
144
+ }
145
+ : {
146
+ kind: "direct",
147
+ name: model.model,
148
+ arguments: directArguments
149
+ };
150
+ const usage = {
151
+ model: model.model,
152
+ ...(model.cost === undefined ? {} : { cost: model.cost })
153
+ };
154
+ await observe?.({ toolUsage: usage });
155
+ return { invocation, usage };
156
+ }
57
157
  return {
58
158
  async listTools({ access, signal }) {
59
- return projectToolList(await load(access, signal));
159
+ return projectToolList(await load(access, signal), dependencies.tools ?? defaultToolDefinitions);
60
160
  },
61
161
  async listModels({ input, access, signal }) {
62
- return projectModelList(await load(access, signal), input.tool);
162
+ return projectModelList(await load(access, signal), input.tool, dependencies.tools ?? defaultToolDefinitions);
63
163
  },
64
164
  async getModel({ input, access, signal }) {
65
165
  return projectModelDetail(await load(access, signal), input.model);
@@ -67,111 +167,14 @@ export function createToolUseCases(dependencies) {
67
167
  async getArgumentsSchema({ name, access, signal }) {
68
168
  return buildToolArgumentsSchema(await load(access, signal), name);
69
169
  },
70
- async call({ input, access, signal }) {
71
- const catalog = await load(access, signal);
72
- const model = await dependencies.telemetry.stage("input", () => {
73
- const modelName = input.arguments.model;
74
- if (typeof modelName !== "string")
75
- throw new ToolInputError();
76
- const selected = findToolModel(catalog, input.name, modelName);
77
- assertModelArguments(selected, input.arguments);
78
- return selected;
79
- });
80
- const { model: ignoredModel, ...parameters } = input.arguments;
81
- void ignoredModel;
82
- dependencies.telemetry.annotate({
83
- tool_name: model.tool,
84
- model_id: model.model,
85
- parameters
86
- });
87
- const prompt = [];
88
- const requestParameters = {};
89
- const directArguments = {};
90
- const prepare = async () => {
91
- for (const parameter of model.parameters) {
92
- signal.throwIfAborted();
93
- const value = input.arguments[parameter.name];
94
- if (value === undefined)
95
- continue;
96
- if (parameter.type === "string") {
97
- if (parameter.name === "prompt") {
98
- prompt.push({ type: "text", content: value });
99
- directArguments[parameter.name] = value;
100
- }
101
- else {
102
- requestParameters[parameter.name] = value;
103
- directArguments[parameter.name] = value;
104
- }
105
- continue;
106
- }
107
- if (parameter.type === "number") {
108
- requestParameters[parameter.name] = value;
109
- directArguments[parameter.name] = value;
110
- continue;
111
- }
112
- const values = parameter.type === "uri[]" ? value : [value];
113
- for (const mediaUrl of values) {
114
- signal.throwIfAborted();
115
- if (mediaUrl.startsWith("file:")) {
116
- const uploaded = await dependencies.uploader.upload({ url: mediaUrl }, access, signal);
117
- signal.throwIfAborted();
118
- prompt.push({
119
- type: "media",
120
- url: uploaded.url,
121
- mime: uploaded.mediaType,
122
- name: parameter.name
123
- });
124
- }
125
- else {
126
- prompt.push(remoteMedia(mediaUrl, parameter.name));
127
- }
128
- }
129
- }
130
- };
131
- const hasLocalMedia = model.parameters.some((parameter) => {
132
- const value = input.arguments[parameter.name];
133
- return parameter.type === "uri"
134
- ? typeof value === "string" && value.startsWith("file:")
135
- : parameter.type === "uri[]"
136
- && Array.isArray(value) && value.some((url) => url.startsWith("file:"));
137
- });
138
- if (hasLocalMedia) {
139
- await dependencies.telemetry.stage("upload", prepare);
140
- }
141
- else {
142
- await prepare();
143
- }
144
- signal.throwIfAborted();
145
- const requiresIntent = prompt.some((item) => item.type === "media")
146
- || Object.values(requestParameters).some((value) => value === "");
147
- const invocation = requiresIntent
148
- ? {
149
- kind: "intent",
150
- model: model.model,
151
- prompt,
152
- parameters: requestParameters,
153
- optionalMediaParameters: model.parameters
154
- .filter((parameter) => ((parameter.type === "uri" || parameter.type === "uri[]")
155
- && !parameter.required))
156
- .map((parameter) => parameter.name)
157
- }
158
- : {
159
- kind: "direct",
160
- name: model.model,
161
- arguments: directArguments
162
- };
163
- const content = await dependencies.execution.execute({
164
- invocation,
165
- access,
166
- signal
167
- });
168
- return {
169
- content,
170
- usage: {
171
- model: model.model,
172
- ...(model.cost === undefined ? {} : { cost: model.cost })
173
- }
174
- };
170
+ async call(input) {
171
+ const { invocation, usage } = await prepare(input);
172
+ const content = await dependencies.execution.execute({ invocation, access: input.access, signal: input.signal, ...(input.observe ? { observe: input.observe } : {}) });
173
+ return { content, usage };
174
+ },
175
+ async submit(input) {
176
+ const { invocation } = await prepare(input);
177
+ await dependencies.execution.submit({ invocation, access: input.access, signal: input.signal, ...(input.observe ? { observe: input.observe } : {}) });
175
178
  }
176
179
  };
177
180
  }
@@ -1,12 +1,12 @@
1
1
  import { valid } from "semver";
2
- const REGISTRY_DIST_TAGS_URL = "https://registry.npmjs.org/@gaoding%2fcli";
2
+ export const GAODING_REGISTRY_DIST_TAGS_URL = "https://registry.npmjs.org/@gaoding%2fcli";
3
3
  export async function fetchLatestVersion(options) {
4
4
  const headers = new Headers({
5
5
  Accept: "application/vnd.npm.install-v1+json"
6
6
  });
7
7
  if (options.etag)
8
8
  headers.set("If-None-Match", options.etag);
9
- const response = await options.fetch(REGISTRY_DIST_TAGS_URL, {
9
+ const response = await options.fetch(options.registryUrl ?? GAODING_REGISTRY_DIST_TAGS_URL, {
10
10
  headers,
11
11
  redirect: "error",
12
12
  signal: options.signal
@@ -13,7 +13,7 @@ export function createUpdateNotificationService(options) {
13
13
  const fetchPackage = options.fetch ?? globalThis.fetch;
14
14
  const now = options.now ?? (() => new Date());
15
15
  const env = options.env ?? process.env;
16
- const stateDirectory = join(options.homeDirectory ?? homedir(), ".gd");
16
+ const stateDirectory = join(options.homeDirectory ?? homedir(), options.stateDirectoryName ?? ".gd");
17
17
  const stateFile = options.stateFile ?? createLocalJsonFile({
18
18
  directory: stateDirectory,
19
19
  filename: "update-check.json"
@@ -52,6 +52,7 @@ export function createUpdateNotificationService(options) {
52
52
  latestResult = await fetchLatestVersion({
53
53
  fetch: fetchPackage,
54
54
  signal: timeout.signal,
55
+ ...(options.registryUrl ? { registryUrl: options.registryUrl } : {}),
55
56
  ...(state.etag ? { etag: state.etag } : {})
56
57
  });
57
58
  }
@@ -231,8 +232,14 @@ function withReminder(state, today, version) {
231
232
  };
232
233
  }
233
234
  function notify(options, latest) {
234
- options.notify(`gd-cli 有新版本 ${latest},当前版本为 ${options.currentVersion}。` +
235
- "运行 gd-cli update 即可更新。");
235
+ if (options.commandName && options.commandName !== "gd-cli") {
236
+ options.notify(`${options.commandName} ${latest} is available; current version is ` +
237
+ `${options.currentVersion}. Run ${options.commandName} update to update.`);
238
+ }
239
+ else {
240
+ options.notify(`gd-cli 有新版本 ${latest},当前版本为 ${options.currentVersion}。` +
241
+ "运行 gd-cli update 即可更新。");
242
+ }
236
243
  }
237
244
  function isNewer(version, currentVersion) {
238
245
  return version !== undefined && valid(version) !== null && gt(version, currentVersion);