@gaoding/cli 1.2.0 → 1.3.1
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.
- package/contracts/operations/task.get/input.schema.json +14 -0
- package/contracts/operations/task.get/output.schema.json +103 -0
- package/contracts/operations/task.list/input.schema.json +18 -0
- package/contracts/operations/task.list/output.schema.json +53 -0
- package/dist/bin/agent-worker.js +41 -0
- package/dist/bin/postinstall.js +2 -2
- package/dist/src/bootstrap/create-cli.js +2 -0
- package/dist/src/bootstrap/create-runtime.js +103 -4
- package/dist/src/bootstrap/run-agent-worker.js +37 -0
- package/dist/src/bootstrap/validators.js +8 -0
- package/dist/src/cli/agent-commands.js +36 -11
- package/dist/src/cli/errors.js +11 -0
- package/dist/src/cli/task-commands.js +48 -0
- package/dist/src/cli/tool-commands.js +31 -8
- package/dist/src/features/agent/creative-agent-adapter.js +9 -3
- package/dist/src/features/agent/creative-protocol.js +5 -16
- package/dist/src/features/agent/creative-stream.js +12 -1
- package/dist/src/features/agent/filems-resource-auth-key-provider.js +23 -0
- package/dist/src/features/agent/resource-authorizer.js +47 -0
- package/dist/src/features/agent/result-reader.js +30 -0
- package/dist/src/features/agent/use-cases.js +98 -95
- package/dist/src/features/task/agent-background.js +63 -0
- package/dist/src/features/task/store.js +97 -0
- package/dist/src/features/task/types.js +1 -0
- package/dist/src/features/task/use-cases.js +139 -0
- package/dist/src/features/tool/tool-api-adapter.js +53 -36
- package/dist/src/features/tool/use-cases.js +108 -105
- package/dist/src/platform/resource-auth-key.js +1 -0
- package/dist/src/platform/task-observer.js +1 -0
- package/dist/src/product/billing.js +21 -19
- package/dist/src/product/config.js +2 -0
- package/package.json +4 -4
- package/skills/gd-cli/SKILL.md +1 -1
- package/skills/gd-cli/references/agent.md +34 -0
- package/skills/gd-cli/references/creation.md +5 -73
- package/skills/gd-cli/references/errors.md +18 -2
- package/skills/gd-cli/references/generation-constraints.md +36 -0
- package/skills/gd-cli/references/tool.md +31 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readdir, lstat } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { createLocalJsonFile, LocalFileError } from "../../platform/local-json-file.js";
|
|
6
|
+
export class TaskStoreError extends LocalFileError {
|
|
7
|
+
}
|
|
8
|
+
export const validTaskId = (id) => /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/iu.test(id);
|
|
9
|
+
export function taskScope(state) {
|
|
10
|
+
return createHash("sha256").update(JSON.stringify([
|
|
11
|
+
state.account ? ["account", state.account.id] : ["credential", state.credential.accessKey],
|
|
12
|
+
state.organization?.id
|
|
13
|
+
])).digest("hex");
|
|
14
|
+
}
|
|
15
|
+
export function createTaskStore(options) {
|
|
16
|
+
const root = join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd", "tasks");
|
|
17
|
+
function file(scope, id) {
|
|
18
|
+
if (!/^[a-f0-9]{64}$/u.test(scope) || !validTaskId(id))
|
|
19
|
+
throw new LocalFileError(undefined);
|
|
20
|
+
return createLocalJsonFile({ directory: join(root, scope), filename: `${id}.json` });
|
|
21
|
+
}
|
|
22
|
+
const store = {
|
|
23
|
+
async read(scope, id) {
|
|
24
|
+
const stateFile = file(scope, id);
|
|
25
|
+
try {
|
|
26
|
+
const stat = await lstat(join(root, scope, `${id}.json`));
|
|
27
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
28
|
+
throw new LocalFileError(undefined);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
32
|
+
return null;
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
const text = await stateFile.readText();
|
|
36
|
+
if (text === null)
|
|
37
|
+
return null;
|
|
38
|
+
try {
|
|
39
|
+
const record = JSON.parse(text);
|
|
40
|
+
if (record.version !== 1 || record.task.taskId !== id || !record.progress
|
|
41
|
+
|| typeof record.progress !== "object" || Array.isArray(record.progress))
|
|
42
|
+
throw new Error();
|
|
43
|
+
options.validate(record.task);
|
|
44
|
+
for (const key of ["contextId", "localMessageId", "remoteTaskId"]) {
|
|
45
|
+
if (record.progress[key] !== undefined && typeof record.progress[key] !== "string")
|
|
46
|
+
throw new Error();
|
|
47
|
+
}
|
|
48
|
+
for (const key of ["submissionStarted", "detached", "accepted"]) {
|
|
49
|
+
if (record.progress[key] !== undefined && typeof record.progress[key] !== "boolean")
|
|
50
|
+
throw new Error();
|
|
51
|
+
}
|
|
52
|
+
return record;
|
|
53
|
+
}
|
|
54
|
+
catch (cause) {
|
|
55
|
+
throw new LocalFileError(cause);
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
async write(scope, record) {
|
|
59
|
+
options.validate(record.task);
|
|
60
|
+
await file(scope, record.task.taskId).writeTextAtomically(`${JSON.stringify(record)}\n`);
|
|
61
|
+
},
|
|
62
|
+
async list(scope) {
|
|
63
|
+
let names;
|
|
64
|
+
try {
|
|
65
|
+
names = await readdir(join(root, scope));
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
69
|
+
return [];
|
|
70
|
+
throw new LocalFileError(error);
|
|
71
|
+
}
|
|
72
|
+
const records = [];
|
|
73
|
+
for (const name of names) {
|
|
74
|
+
if (!name.endsWith(".json") || !validTaskId(name.slice(0, -5)))
|
|
75
|
+
continue;
|
|
76
|
+
const record = await store.read(scope, name.slice(0, -5));
|
|
77
|
+
if (record)
|
|
78
|
+
records.push(record);
|
|
79
|
+
}
|
|
80
|
+
return records.sort((a, b) => b.task.createdAt.localeCompare(a.task.createdAt)
|
|
81
|
+
|| a.task.taskId.localeCompare(b.task.taskId));
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
async function access(operation) {
|
|
85
|
+
try {
|
|
86
|
+
return await operation();
|
|
87
|
+
}
|
|
88
|
+
catch (cause) {
|
|
89
|
+
throw new TaskStoreError(cause);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
read: (scope, id) => access(() => store.read(scope, id)),
|
|
94
|
+
write: (scope, record) => access(() => store.write(scope, record)),
|
|
95
|
+
list: scope => access(() => store.list(scope))
|
|
96
|
+
};
|
|
97
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -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
|
+
}
|
|
@@ -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
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
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
|
-
|
|
300
|
-
|
|
301
|
-
|
|
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
|
-
|
|
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) {
|
|
@@ -54,6 +54,106 @@ 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
159
|
return projectToolList(await load(access, signal), dependencies.tools ?? defaultToolDefinitions);
|
|
@@ -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(
|
|
71
|
-
const
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
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
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -3,18 +3,7 @@ export function withAgentBillingUnit(source, unit) {
|
|
|
3
3
|
return source;
|
|
4
4
|
return {
|
|
5
5
|
async send(input) {
|
|
6
|
-
|
|
7
|
-
return {
|
|
8
|
-
...output,
|
|
9
|
-
usage: {
|
|
10
|
-
...output.usage,
|
|
11
|
-
cost: { ...output.usage.cost, unit },
|
|
12
|
-
items: output.usage.items.map((item) => ({
|
|
13
|
-
...item,
|
|
14
|
-
cost: { ...item.cost, unit }
|
|
15
|
-
}))
|
|
16
|
-
}
|
|
17
|
-
};
|
|
6
|
+
return agentOutputWithBillingUnit(await source.send(input), unit);
|
|
18
7
|
}
|
|
19
8
|
};
|
|
20
9
|
}
|
|
@@ -32,14 +21,27 @@ export function withToolBillingUnit(source, unit) {
|
|
|
32
21
|
return model(await source.getModel(input));
|
|
33
22
|
},
|
|
34
23
|
getArgumentsSchema: (input) => source.getArgumentsSchema(input),
|
|
24
|
+
submit: (input) => source.submit(input),
|
|
35
25
|
async call(input) {
|
|
36
|
-
|
|
37
|
-
return {
|
|
38
|
-
...output,
|
|
39
|
-
usage: output.usage.cost
|
|
40
|
-
? { ...output.usage, cost: { ...output.usage.cost, unit } }
|
|
41
|
-
: output.usage
|
|
42
|
-
};
|
|
26
|
+
return toolOutputWithBillingUnit(await source.call(input), unit);
|
|
43
27
|
}
|
|
44
28
|
};
|
|
45
29
|
}
|
|
30
|
+
export function agentOutputWithBillingUnit(output, unit) {
|
|
31
|
+
return {
|
|
32
|
+
...output,
|
|
33
|
+
usage: {
|
|
34
|
+
...output.usage,
|
|
35
|
+
cost: { ...output.usage.cost, unit },
|
|
36
|
+
items: output.usage.items.map(item => ({ ...item, cost: { ...item.cost, unit } }))
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
export function toolOutputWithBillingUnit(output, unit) {
|
|
41
|
+
return {
|
|
42
|
+
...output,
|
|
43
|
+
usage: output.usage.cost
|
|
44
|
+
? { ...output.usage, cost: { ...output.usage.cost, unit } }
|
|
45
|
+
: output.usage
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -29,6 +29,7 @@ export const gaodingProduct = freezeProduct({
|
|
|
29
29
|
mnsApi: gaodingApi,
|
|
30
30
|
toolApi: gaodingApi,
|
|
31
31
|
damApi: gaodingApi,
|
|
32
|
+
filemsApi: gaodingApi,
|
|
32
33
|
ssoApi: new URL("https://www.gaoding.com/api/sso"),
|
|
33
34
|
authPageOrigin: new URL("https://www.gaoding.art")
|
|
34
35
|
},
|
|
@@ -58,6 +59,7 @@ export const insmindProduct = freezeProduct({
|
|
|
58
59
|
mnsApi: insmindApi,
|
|
59
60
|
toolApi: insmindApi,
|
|
60
61
|
damApi: insmindApi,
|
|
62
|
+
filemsApi: insmindApi,
|
|
61
63
|
ssoApi: new URL("https://www.insmind.com/api/sso"),
|
|
62
64
|
authPageOrigin: new URL("https://www.insmind.com")
|
|
63
65
|
},
|