@insmind/cli 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 (153) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -0
  3. package/contracts/operations/agent.send/input.schema.json +335 -0
  4. package/contracts/operations/agent.send/output.schema.json +248 -0
  5. package/contracts/operations/auth.status/input.schema.json +7 -0
  6. package/contracts/operations/auth.status/output.schema.json +119 -0
  7. package/contracts/operations/dam.copy/input.schema.json +42 -0
  8. package/contracts/operations/dam.copy/output.schema.json +43 -0
  9. package/contracts/operations/dam.delete/input.schema.json +24 -0
  10. package/contracts/operations/dam.delete/output.schema.json +5 -0
  11. package/contracts/operations/dam.download/input.schema.json +28 -0
  12. package/contracts/operations/dam.download/output.schema.json +51 -0
  13. package/contracts/operations/dam.folder.list/input.schema.json +36 -0
  14. package/contracts/operations/dam.folder.list/output.schema.json +104 -0
  15. package/contracts/operations/dam.get/input.schema.json +16 -0
  16. package/contracts/operations/dam.get/output.schema.json +107 -0
  17. package/contracts/operations/dam.list/input.schema.json +73 -0
  18. package/contracts/operations/dam.list/output.schema.json +145 -0
  19. package/contracts/operations/dam.move/input.schema.json +42 -0
  20. package/contracts/operations/dam.move/output.schema.json +40 -0
  21. package/contracts/operations/dam.rename/input.schema.json +42 -0
  22. package/contracts/operations/dam.rename/output.schema.json +43 -0
  23. package/contracts/operations/dam.repository.list/input.schema.json +7 -0
  24. package/contracts/operations/dam.repository.list/output.schema.json +65 -0
  25. package/contracts/operations/dam.search/input.schema.json +79 -0
  26. package/contracts/operations/dam.search/output.schema.json +145 -0
  27. package/contracts/operations/dam.tag.list/input.schema.json +21 -0
  28. package/contracts/operations/dam.tag.list/output.schema.json +52 -0
  29. package/contracts/operations/dam.upload/input.schema.json +43 -0
  30. package/contracts/operations/dam.upload/output.schema.json +107 -0
  31. package/contracts/operations/editor.apply/input.schema.json +177 -0
  32. package/contracts/operations/editor.apply/output.schema.json +15 -0
  33. package/contracts/operations/editor.connect/input.schema.json +13 -0
  34. package/contracts/operations/editor.connect/output.schema.json +17 -0
  35. package/contracts/operations/editor.disconnect/input.schema.json +7 -0
  36. package/contracts/operations/editor.disconnect/output.schema.json +14 -0
  37. package/contracts/operations/editor.save/input.schema.json +7 -0
  38. package/contracts/operations/editor.save/output.schema.json +23 -0
  39. package/contracts/operations/editor.screenshot/input.schema.json +7 -0
  40. package/contracts/operations/editor.screenshot/output.schema.json +16 -0
  41. package/contracts/operations/editor.snapshot/input.schema.json +7 -0
  42. package/contracts/operations/editor.snapshot/output.schema.json +148 -0
  43. package/contracts/operations/model.get/input.schema.json +16 -0
  44. package/contracts/operations/model.get/output.schema.json +167 -0
  45. package/contracts/operations/model.list/input.schema.json +13 -0
  46. package/contracts/operations/model.list/output.schema.json +97 -0
  47. package/contracts/operations/task.get/input.schema.json +14 -0
  48. package/contracts/operations/task.get/output.schema.json +103 -0
  49. package/contracts/operations/task.list/input.schema.json +18 -0
  50. package/contracts/operations/task.list/output.schema.json +53 -0
  51. package/contracts/operations/tool.call/input.schema.json +31 -0
  52. package/contracts/operations/tool.call/output.schema.json +115 -0
  53. package/contracts/operations/tool.list/input.schema.json +6 -0
  54. package/contracts/operations/tool.list/output.schema.json +40 -0
  55. package/dist/bin/agent-worker.js +41 -0
  56. package/dist/bin/insmind-cli.js +60 -0
  57. package/dist/bin/postinstall.js +69 -0
  58. package/dist/src/bootstrap/create-cli.js +124 -0
  59. package/dist/src/bootstrap/create-runtime.js +451 -0
  60. package/dist/src/bootstrap/run-agent-worker.js +37 -0
  61. package/dist/src/bootstrap/validators.js +169 -0
  62. package/dist/src/cli/action-binding.js +109 -0
  63. package/dist/src/cli/agent-commands.js +75 -0
  64. package/dist/src/cli/auth-commands.js +58 -0
  65. package/dist/src/cli/credits-command.js +23 -0
  66. package/dist/src/cli/dam-commands.js +470 -0
  67. package/dist/src/cli/editor-commands.js +74 -0
  68. package/dist/src/cli/errors.js +208 -0
  69. package/dist/src/cli/model-commands.js +62 -0
  70. package/dist/src/cli/org-commands.js +58 -0
  71. package/dist/src/cli/presenter.js +123 -0
  72. package/dist/src/cli/prompt.js +30 -0
  73. package/dist/src/cli/task-commands.js +48 -0
  74. package/dist/src/cli/tool-commands.js +101 -0
  75. package/dist/src/cli/update-command.js +15 -0
  76. package/dist/src/contracts/schema.js +4 -0
  77. package/dist/src/features/agent/creative-agent-adapter.js +42 -0
  78. package/dist/src/features/agent/creative-protocol.js +421 -0
  79. package/dist/src/features/agent/creative-stream.js +138 -0
  80. package/dist/src/features/agent/filems-resource-auth-key-provider.js +23 -0
  81. package/dist/src/features/agent/resource-authorizer.js +47 -0
  82. package/dist/src/features/agent/result-reader.js +30 -0
  83. package/dist/src/features/agent/use-cases.js +153 -0
  84. package/dist/src/features/auth/access-policy.js +101 -0
  85. package/dist/src/features/auth/credential-store.js +62 -0
  86. package/dist/src/features/auth/sso-service.js +196 -0
  87. package/dist/src/features/auth/state.js +129 -0
  88. package/dist/src/features/auth/use-cases.js +162 -0
  89. package/dist/src/features/credits/use-cases.js +52 -0
  90. package/dist/src/features/dam/asset-projection.js +278 -0
  91. package/dist/src/features/dam/dam-api-adapter.js +562 -0
  92. package/dist/src/features/dam/file-downloader.js +242 -0
  93. package/dist/src/features/dam/object-storage.js +193 -0
  94. package/dist/src/features/dam/operation-executor.js +72 -0
  95. package/dist/src/features/dam/registered-uploader.js +247 -0
  96. package/dist/src/features/dam/repository-catalog.js +127 -0
  97. package/dist/src/features/dam/storage-upload.js +141 -0
  98. package/dist/src/features/dam/transient-uploader.js +17 -0
  99. package/dist/src/features/dam/use-cases.js +470 -0
  100. package/dist/src/features/editor/bridge-client.js +109 -0
  101. package/dist/src/features/editor/bridge-process.js +229 -0
  102. package/dist/src/features/editor/bridge-server.js +337 -0
  103. package/dist/src/features/editor/protocol.js +1 -0
  104. package/dist/src/features/editor/public-url.js +36 -0
  105. package/dist/src/features/editor/session-state.js +78 -0
  106. package/dist/src/features/editor/session.js +213 -0
  107. package/dist/src/features/editor/use-cases.js +88 -0
  108. package/dist/src/features/org/org-service.js +76 -0
  109. package/dist/src/features/org/use-cases.js +163 -0
  110. package/dist/src/features/skill/bundled-skills.js +63 -0
  111. package/dist/src/features/skill/installer.js +271 -0
  112. package/dist/src/features/task/agent-background.js +63 -0
  113. package/dist/src/features/task/store.js +97 -0
  114. package/dist/src/features/task/types.js +1 -0
  115. package/dist/src/features/task/use-cases.js +139 -0
  116. package/dist/src/features/tool/catalog.js +83 -0
  117. package/dist/src/features/tool/dynamic-schema.js +128 -0
  118. package/dist/src/features/tool/mns-catalog-adapter.js +265 -0
  119. package/dist/src/features/tool/tool-api-adapter.js +369 -0
  120. package/dist/src/features/tool/use-cases.js +180 -0
  121. package/dist/src/features/update/latest-version.js +37 -0
  122. package/dist/src/features/update/update-notification.js +271 -0
  123. package/dist/src/features/update/update-service.js +226 -0
  124. package/dist/src/platform/installation-owner.js +81 -0
  125. package/dist/src/platform/json-input.js +67 -0
  126. package/dist/src/platform/local-json-file.js +59 -0
  127. package/dist/src/platform/open-browser.js +8 -0
  128. package/dist/src/platform/redact.js +80 -0
  129. package/dist/src/platform/remote-error-evidence.js +80 -0
  130. package/dist/src/platform/remote-protocol.js +10 -0
  131. package/dist/src/platform/resource-auth-key.js +1 -0
  132. package/dist/src/platform/safe-upload-file.js +146 -0
  133. package/dist/src/platform/signature.js +20 -0
  134. package/dist/src/platform/signed-http-transport.js +144 -0
  135. package/dist/src/platform/task-observer.js +1 -0
  136. package/dist/src/platform/url-safety.js +100 -0
  137. package/dist/src/product/billing.js +47 -0
  138. package/dist/src/product/config.js +85 -0
  139. package/dist/src/product/locale.js +38 -0
  140. package/dist/src/product/text.js +3 -0
  141. package/dist/src/telemetry/invocation.js +156 -0
  142. package/dist/src/telemetry/sls-sink.js +30 -0
  143. package/package.json +53 -0
  144. package/skills/insmind-cli/SKILL.md +15 -0
  145. package/skills/insmind-cli/references/agent.md +34 -0
  146. package/skills/insmind-cli/references/auth.md +8 -0
  147. package/skills/insmind-cli/references/creation.md +40 -0
  148. package/skills/insmind-cli/references/dam.md +51 -0
  149. package/skills/insmind-cli/references/editor.md +184 -0
  150. package/skills/insmind-cli/references/errors.md +29 -0
  151. package/skills/insmind-cli/references/generation-constraints.md +36 -0
  152. package/skills/insmind-cli/references/tool.md +31 -0
  153. package/skills/insmind-cli/references/update.md +11 -0
@@ -0,0 +1,369 @@
1
+ import { randomInt } from "node:crypto";
2
+ import { setTimeout as delay } from "node:timers/promises";
3
+ import { RemoteRequestError } from "../../platform/signed-http-transport.js";
4
+ import { remoteErrorEvidence } from "../../platform/remote-error-evidence.js";
5
+ import { RemoteProtocolError } from "../../platform/remote-protocol.js";
6
+ const MAX_JAVA_LONG = 9223372036854775807n;
7
+ function isRecord(value) {
8
+ return value !== null && typeof value === "object" && !Array.isArray(value);
9
+ }
10
+ function fail() {
11
+ throw new RemoteRequestError();
12
+ }
13
+ function protocolFailure(value) {
14
+ throw new RemoteProtocolError(remoteErrorEvidence(value));
15
+ }
16
+ function nonBlank(value) {
17
+ if (typeof value !== "string" || value.trim() === "")
18
+ return fail();
19
+ return value;
20
+ }
21
+ function parseRecord(value) {
22
+ try {
23
+ const parsed = JSON.parse(value);
24
+ if (!isRecord(parsed))
25
+ return fail();
26
+ return parsed;
27
+ }
28
+ catch (error) {
29
+ if (error instanceof RemoteRequestError)
30
+ throw error;
31
+ return fail();
32
+ }
33
+ }
34
+ function contentId(value) {
35
+ if (!/^\d+$/u.test(value))
36
+ return fail();
37
+ const numeric = BigInt(value);
38
+ if (numeric > MAX_JAVA_LONG)
39
+ return fail();
40
+ return value;
41
+ }
42
+ function parseIntent(value) {
43
+ if (!isRecord(value))
44
+ return fail();
45
+ return {
46
+ name: nonBlank(value.name),
47
+ arguments: parseRecord(nonBlank(value.arguments))
48
+ };
49
+ }
50
+ function isEmptyOptionalMedia(value) {
51
+ return value === undefined
52
+ || value === null
53
+ || value === ""
54
+ || (Array.isArray(value) && value.length === 0)
55
+ || (typeof value === "string" && value.trim() === "[]");
56
+ }
57
+ function withoutEmptyOptionalMedia(value, optionalMediaParameters) {
58
+ const normalized = { ...value };
59
+ for (const name of optionalMediaParameters) {
60
+ if (isEmptyOptionalMedia(normalized[name]))
61
+ delete normalized[name];
62
+ }
63
+ return normalized;
64
+ }
65
+ function submittedTask(value) {
66
+ if (!isRecord(value) || !isRecord(value.result))
67
+ return protocolFailure(value);
68
+ if (value.result.isError === true) {
69
+ throw new ToolTaskFailedError(remoteErrorEvidence(value));
70
+ }
71
+ if (value.result.isError !== false)
72
+ return protocolFailure(value);
73
+ if (typeof value.task_id !== "string" || value.task_id.trim() === "") {
74
+ return protocolFailure(value);
75
+ }
76
+ return value.task_id;
77
+ }
78
+ function resourceName(uri) {
79
+ let url;
80
+ try {
81
+ url = new URL(uri);
82
+ }
83
+ catch {
84
+ return protocolFailure(uri);
85
+ }
86
+ const segment = url.pathname.split("/").filter(Boolean).at(-1);
87
+ if (segment === undefined)
88
+ return protocolFailure(uri);
89
+ try {
90
+ const decoded = decodeURIComponent(segment);
91
+ if (decoded.trim() === "")
92
+ return protocolFailure(uri);
93
+ return decoded;
94
+ }
95
+ catch {
96
+ return protocolFailure(uri);
97
+ }
98
+ }
99
+ function normalizeContent(value) {
100
+ if (!isRecord(value))
101
+ return protocolFailure(value);
102
+ if (value.type === "text") {
103
+ if (typeof value.text !== "string" || value.text.trim() === "") {
104
+ return protocolFailure(value);
105
+ }
106
+ return { type: "text", text: value.text };
107
+ }
108
+ if (value.type !== "resource" || !isRecord(value.resource)) {
109
+ return protocolFailure(value);
110
+ }
111
+ if ("blob" in value.resource || "text" in value.resource)
112
+ return protocolFailure(value);
113
+ if (typeof value.resource.uri !== "string" || value.resource.uri.trim() === "") {
114
+ return protocolFailure(value);
115
+ }
116
+ const uri = value.resource.uri;
117
+ const mimeType = value.resource.mimeType;
118
+ if (mimeType !== undefined && (typeof mimeType !== "string" || mimeType.trim() === "")) {
119
+ return protocolFailure(value);
120
+ }
121
+ return {
122
+ type: "resource_link",
123
+ uri,
124
+ name: resourceName(uri),
125
+ ...(mimeType === undefined ? {} : { mimeType })
126
+ };
127
+ }
128
+ export class ToolTaskFailedError extends Error {
129
+ remoteCode;
130
+ remoteBody;
131
+ constructor(evidence = {}) {
132
+ super("稿定工具任务执行失败。");
133
+ this.name = "ToolTaskFailedError";
134
+ this.remoteCode = evidence.remoteCode;
135
+ this.remoteBody = evidence.remoteBody;
136
+ }
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
+ }
147
+ function failedPoll(error, difyTaskId) {
148
+ return {
149
+ state: "failed",
150
+ error,
151
+ ...(difyTaskId === undefined ? {} : { difyTaskId })
152
+ };
153
+ }
154
+ function optionalInnerDifyTaskId(value) {
155
+ if (typeof value !== "string" || value.trim() === "")
156
+ return undefined;
157
+ try {
158
+ const parsed = JSON.parse(value);
159
+ if (!isRecord(parsed))
160
+ return undefined;
161
+ const difyTaskId = parsed.dify_task_id;
162
+ return typeof difyTaskId === "string" && difyTaskId.trim() !== ""
163
+ ? difyTaskId
164
+ : undefined;
165
+ }
166
+ catch {
167
+ return undefined;
168
+ }
169
+ }
170
+ function isJsonRpcError(value) {
171
+ if (value.jsonrpc !== "2.0"
172
+ || Object.prototype.hasOwnProperty.call(value, "result")
173
+ || !isRecord(value.error)) {
174
+ return false;
175
+ }
176
+ return typeof value.error.code === "number"
177
+ && Number.isInteger(value.error.code)
178
+ && typeof value.error.message === "string"
179
+ && value.error.message.trim() !== "";
180
+ }
181
+ function pollResult(value, taskId) {
182
+ if (!Array.isArray(value))
183
+ return protocolFailure(value);
184
+ const item = value.find((candidate) => isRecord(candidate) && candidate.task_id === taskId);
185
+ if (!isRecord(item))
186
+ return { state: "pending" };
187
+ if (typeof item.code !== "string" || item.code.trim() === "") {
188
+ return protocolFailure(item);
189
+ }
190
+ if (item.code !== "200") {
191
+ return failedPoll(new ToolTaskFailedError(remoteErrorEvidence(item)), optionalInnerDifyTaskId(item.result));
192
+ }
193
+ if (typeof item.result !== "string" || item.result.trim() === "") {
194
+ return protocolFailure(item);
195
+ }
196
+ let inner;
197
+ try {
198
+ const parsed = JSON.parse(item.result);
199
+ if (!isRecord(parsed))
200
+ return protocolFailure(item);
201
+ inner = parsed;
202
+ }
203
+ catch (error) {
204
+ if (error instanceof RemoteProtocolError)
205
+ throw error;
206
+ return protocolFailure(item);
207
+ }
208
+ const difyTaskId = inner.dify_task_id;
209
+ if (difyTaskId !== undefined
210
+ && (typeof difyTaskId !== "string" || difyTaskId.trim() === "")) {
211
+ return protocolFailure(inner);
212
+ }
213
+ if (Object.prototype.hasOwnProperty.call(inner, "error")) {
214
+ return isJsonRpcError(inner)
215
+ ? failedPoll(new ToolTaskFailedError(remoteErrorEvidence(inner)), difyTaskId)
216
+ : failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
217
+ }
218
+ if (!isRecord(inner.result)) {
219
+ return failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
220
+ }
221
+ if (inner.result.isError === true) {
222
+ return failedPoll(new ToolTaskFailedError(remoteErrorEvidence(inner)), difyTaskId);
223
+ }
224
+ if (inner.result.isError !== false) {
225
+ return failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
226
+ }
227
+ const content = inner.result.content;
228
+ if (content === undefined || (Array.isArray(content) && content.length === 0)) {
229
+ return {
230
+ state: "pending",
231
+ ...(difyTaskId === undefined ? {} : { difyTaskId })
232
+ };
233
+ }
234
+ if (!Array.isArray(content)) {
235
+ return failedPoll(new RemoteProtocolError(remoteErrorEvidence(inner)), difyTaskId);
236
+ }
237
+ try {
238
+ return {
239
+ state: "complete",
240
+ content: content.map(normalizeContent),
241
+ ...(difyTaskId === undefined ? {} : { difyTaskId })
242
+ };
243
+ }
244
+ catch (error) {
245
+ if (error instanceof RemoteProtocolError)
246
+ return failedPoll(error, difyTaskId);
247
+ throw error;
248
+ }
249
+ }
250
+ async function safePost(transport, request) {
251
+ try {
252
+ return await transport.postJson(request);
253
+ }
254
+ catch (error) {
255
+ if (request.signal.aborted)
256
+ throw request.signal.reason;
257
+ if (error instanceof RemoteRequestError || error instanceof RemoteProtocolError)
258
+ throw error;
259
+ throw new RemoteRequestError();
260
+ }
261
+ }
262
+ async function defaultSleep(milliseconds, signal) {
263
+ signal.throwIfAborted();
264
+ try {
265
+ await delay(milliseconds, undefined, { signal });
266
+ }
267
+ catch {
268
+ if (signal.aborted)
269
+ throw signal.reason;
270
+ throw new RemoteRequestError();
271
+ }
272
+ }
273
+ function defaultContentId() {
274
+ return (BigInt(Date.now()) * 100000n + BigInt(randomInt(100_000))).toString();
275
+ }
276
+ export function createToolApiAdapter(dependencies) {
277
+ const createContentId = dependencies.contentIdFactory ?? defaultContentId;
278
+ const sleep = dependencies.sleep ?? defaultSleep;
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",
287
+ body: {
288
+ prompt: invocation.prompt,
289
+ scene_code: invocation.model,
290
+ parameters: invocation.parameters
291
+ },
292
+ credential: access.credential,
293
+ organizationId: access.organizationId,
294
+ signal
295
+ }));
296
+ return {
297
+ ...intent,
298
+ arguments: withoutEmptyOptionalMedia(intent.arguments, invocation.optionalMediaParameters)
299
+ };
300
+ });
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);
330
+ return dependencies.telemetry.stage("wait", async () => {
331
+ let transientFailures = 0;
332
+ while (true) {
333
+ signal.throwIfAborted();
334
+ let response;
335
+ try {
336
+ response = await safePost(dependencies.transport, {
337
+ path: "/gdesign/tool/v1/dify/process/batch",
338
+ body: { task_ids: [taskId] },
339
+ credential: access.credential,
340
+ organizationId: access.organizationId,
341
+ signal
342
+ });
343
+ transientFailures = 0;
344
+ }
345
+ catch (error) {
346
+ if (signal.aborted)
347
+ throw signal.reason;
348
+ if (!(error instanceof RemoteRequestError) || !error.transient)
349
+ throw error;
350
+ transientFailures += 1;
351
+ if (transientFailures > 3)
352
+ throw error;
353
+ await sleep(transientFailures * 1_000, signal);
354
+ continue;
355
+ }
356
+ const poll = pollResult(response, taskId);
357
+ if (poll.difyTaskId !== undefined) {
358
+ dependencies.telemetry.annotate({ dify_task_id: poll.difyTaskId });
359
+ }
360
+ if (poll.state === "failed")
361
+ throw poll.error;
362
+ if (poll.state === "complete")
363
+ return poll.content;
364
+ await sleep(2_000, signal);
365
+ }
366
+ });
367
+ }
368
+ };
369
+ }
@@ -0,0 +1,180 @@
1
+ import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
2
+ import { findToolModel, defaultToolDefinitions, projectModelDetail, projectModelList, projectToolList, ToolInputError } from "./catalog.js";
3
+ import { assertModelArguments, buildToolArgumentsSchema } from "./dynamic-schema.js";
4
+ const mediaTypes = {
5
+ avif: "image/avif",
6
+ gif: "image/gif",
7
+ heic: "image/heic",
8
+ jpeg: "image/jpeg",
9
+ jpg: "image/jpeg",
10
+ mov: "video/quicktime",
11
+ mp3: "audio/mpeg",
12
+ mp4: "video/mp4",
13
+ png: "image/png",
14
+ wav: "audio/wav",
15
+ webm: "video/webm",
16
+ webp: "image/webp"
17
+ };
18
+ function inferRemoteMediaType(url) {
19
+ const segment = url.pathname.split("/").filter(Boolean).at(-1) ?? "";
20
+ let filename = segment;
21
+ try {
22
+ filename = decodeURIComponent(segment);
23
+ }
24
+ catch {
25
+ // The extension remains usable when the path contains malformed escapes.
26
+ }
27
+ const extension = filename.split(".").at(-1)?.toLowerCase();
28
+ return extension === undefined || extension === filename.toLowerCase()
29
+ ? "application/octet-stream"
30
+ : mediaTypes[extension] ?? "application/octet-stream";
31
+ }
32
+ function remoteMedia(value, name) {
33
+ try {
34
+ const url = parseSafeRemoteAssetUrl(value);
35
+ return {
36
+ type: "media",
37
+ url: value,
38
+ mime: inferRemoteMediaType(url),
39
+ name
40
+ };
41
+ }
42
+ catch (error) {
43
+ if (error instanceof UrlSafetyError)
44
+ throw new ToolInputError();
45
+ throw error;
46
+ }
47
+ }
48
+ export function createToolUseCases(dependencies) {
49
+ async function load(access, signal) {
50
+ signal.throwIfAborted();
51
+ const catalog = await dependencies.telemetry.stage("catalog", () => (dependencies.catalog.load({ access, signal })));
52
+ signal.throwIfAborted();
53
+ for (const warning of catalog.warnings)
54
+ dependencies.warn(warning);
55
+ return catalog;
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
+ }
157
+ return {
158
+ async listTools({ access, signal }) {
159
+ return projectToolList(await load(access, signal), dependencies.tools ?? defaultToolDefinitions);
160
+ },
161
+ async listModels({ input, access, signal }) {
162
+ return projectModelList(await load(access, signal), input.tool, dependencies.tools ?? defaultToolDefinitions);
163
+ },
164
+ async getModel({ input, access, signal }) {
165
+ return projectModelDetail(await load(access, signal), input.model);
166
+ },
167
+ async getArgumentsSchema({ name, access, signal }) {
168
+ return buildToolArgumentsSchema(await load(access, signal), name);
169
+ },
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 } : {}) });
178
+ }
179
+ };
180
+ }
@@ -0,0 +1,37 @@
1
+ import { valid } from "semver";
2
+ export const GAODING_REGISTRY_DIST_TAGS_URL = "https://registry.npmjs.org/@gaoding%2fcli";
3
+ export async function fetchLatestVersion(options) {
4
+ const headers = new Headers({
5
+ Accept: "application/vnd.npm.install-v1+json"
6
+ });
7
+ if (options.etag)
8
+ headers.set("If-None-Match", options.etag);
9
+ const response = await options.fetch(options.registryUrl ?? GAODING_REGISTRY_DIST_TAGS_URL, {
10
+ headers,
11
+ redirect: "error",
12
+ signal: options.signal
13
+ });
14
+ if (response.status === 304)
15
+ return { status: "not_modified" };
16
+ if (!response.ok)
17
+ throw new Error(`Registry status ${response.status}`);
18
+ const metadata = await response.json();
19
+ if (!isRecord(metadata))
20
+ throw new Error("Registry metadata invalid");
21
+ const tags = metadata["dist-tags"];
22
+ if (!isRecord(tags))
23
+ throw new Error("Registry dist-tags missing");
24
+ const latest = tags.latest;
25
+ if (typeof latest !== "string" || valid(latest.trim()) === null) {
26
+ throw new Error("Registry latest missing");
27
+ }
28
+ const etag = response.headers.get("ETag") ?? undefined;
29
+ return {
30
+ status: "modified",
31
+ version: latest.trim(),
32
+ ...(etag ? { etag } : {})
33
+ };
34
+ }
35
+ function isRecord(value) {
36
+ return typeof value === "object" && value !== null && !Array.isArray(value);
37
+ }