@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.
- package/LICENSE +21 -0
- package/README.md +11 -0
- package/contracts/operations/agent.send/input.schema.json +335 -0
- package/contracts/operations/agent.send/output.schema.json +248 -0
- package/contracts/operations/auth.status/input.schema.json +7 -0
- package/contracts/operations/auth.status/output.schema.json +119 -0
- package/contracts/operations/dam.copy/input.schema.json +42 -0
- package/contracts/operations/dam.copy/output.schema.json +43 -0
- package/contracts/operations/dam.delete/input.schema.json +24 -0
- package/contracts/operations/dam.delete/output.schema.json +5 -0
- package/contracts/operations/dam.download/input.schema.json +28 -0
- package/contracts/operations/dam.download/output.schema.json +51 -0
- package/contracts/operations/dam.folder.list/input.schema.json +36 -0
- package/contracts/operations/dam.folder.list/output.schema.json +104 -0
- package/contracts/operations/dam.get/input.schema.json +16 -0
- package/contracts/operations/dam.get/output.schema.json +107 -0
- package/contracts/operations/dam.list/input.schema.json +73 -0
- package/contracts/operations/dam.list/output.schema.json +145 -0
- package/contracts/operations/dam.move/input.schema.json +42 -0
- package/contracts/operations/dam.move/output.schema.json +40 -0
- package/contracts/operations/dam.rename/input.schema.json +42 -0
- package/contracts/operations/dam.rename/output.schema.json +43 -0
- package/contracts/operations/dam.repository.list/input.schema.json +7 -0
- package/contracts/operations/dam.repository.list/output.schema.json +65 -0
- package/contracts/operations/dam.search/input.schema.json +79 -0
- package/contracts/operations/dam.search/output.schema.json +145 -0
- package/contracts/operations/dam.tag.list/input.schema.json +21 -0
- package/contracts/operations/dam.tag.list/output.schema.json +52 -0
- package/contracts/operations/dam.upload/input.schema.json +43 -0
- package/contracts/operations/dam.upload/output.schema.json +107 -0
- package/contracts/operations/editor.apply/input.schema.json +177 -0
- package/contracts/operations/editor.apply/output.schema.json +15 -0
- package/contracts/operations/editor.connect/input.schema.json +13 -0
- package/contracts/operations/editor.connect/output.schema.json +17 -0
- package/contracts/operations/editor.disconnect/input.schema.json +7 -0
- package/contracts/operations/editor.disconnect/output.schema.json +14 -0
- package/contracts/operations/editor.save/input.schema.json +7 -0
- package/contracts/operations/editor.save/output.schema.json +23 -0
- package/contracts/operations/editor.screenshot/input.schema.json +7 -0
- package/contracts/operations/editor.screenshot/output.schema.json +16 -0
- package/contracts/operations/editor.snapshot/input.schema.json +7 -0
- package/contracts/operations/editor.snapshot/output.schema.json +148 -0
- package/contracts/operations/model.get/input.schema.json +16 -0
- package/contracts/operations/model.get/output.schema.json +167 -0
- package/contracts/operations/model.list/input.schema.json +13 -0
- package/contracts/operations/model.list/output.schema.json +97 -0
- 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/contracts/operations/tool.call/input.schema.json +31 -0
- package/contracts/operations/tool.call/output.schema.json +115 -0
- package/contracts/operations/tool.list/input.schema.json +6 -0
- package/contracts/operations/tool.list/output.schema.json +40 -0
- package/dist/bin/agent-worker.js +41 -0
- package/dist/bin/insmind-cli.js +60 -0
- package/dist/bin/postinstall.js +69 -0
- package/dist/src/bootstrap/create-cli.js +124 -0
- package/dist/src/bootstrap/create-runtime.js +451 -0
- package/dist/src/bootstrap/run-agent-worker.js +37 -0
- package/dist/src/bootstrap/validators.js +169 -0
- package/dist/src/cli/action-binding.js +109 -0
- package/dist/src/cli/agent-commands.js +75 -0
- package/dist/src/cli/auth-commands.js +58 -0
- package/dist/src/cli/credits-command.js +23 -0
- package/dist/src/cli/dam-commands.js +470 -0
- package/dist/src/cli/editor-commands.js +74 -0
- package/dist/src/cli/errors.js +208 -0
- package/dist/src/cli/model-commands.js +62 -0
- package/dist/src/cli/org-commands.js +58 -0
- package/dist/src/cli/presenter.js +123 -0
- package/dist/src/cli/prompt.js +30 -0
- package/dist/src/cli/task-commands.js +48 -0
- package/dist/src/cli/tool-commands.js +101 -0
- package/dist/src/cli/update-command.js +15 -0
- package/dist/src/contracts/schema.js +4 -0
- package/dist/src/features/agent/creative-agent-adapter.js +42 -0
- package/dist/src/features/agent/creative-protocol.js +421 -0
- package/dist/src/features/agent/creative-stream.js +138 -0
- 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 +153 -0
- package/dist/src/features/auth/access-policy.js +101 -0
- package/dist/src/features/auth/credential-store.js +62 -0
- package/dist/src/features/auth/sso-service.js +196 -0
- package/dist/src/features/auth/state.js +129 -0
- package/dist/src/features/auth/use-cases.js +162 -0
- package/dist/src/features/credits/use-cases.js +52 -0
- package/dist/src/features/dam/asset-projection.js +278 -0
- package/dist/src/features/dam/dam-api-adapter.js +562 -0
- package/dist/src/features/dam/file-downloader.js +242 -0
- package/dist/src/features/dam/object-storage.js +193 -0
- package/dist/src/features/dam/operation-executor.js +72 -0
- package/dist/src/features/dam/registered-uploader.js +247 -0
- package/dist/src/features/dam/repository-catalog.js +127 -0
- package/dist/src/features/dam/storage-upload.js +141 -0
- package/dist/src/features/dam/transient-uploader.js +17 -0
- package/dist/src/features/dam/use-cases.js +470 -0
- package/dist/src/features/editor/bridge-client.js +109 -0
- package/dist/src/features/editor/bridge-process.js +229 -0
- package/dist/src/features/editor/bridge-server.js +337 -0
- package/dist/src/features/editor/protocol.js +1 -0
- package/dist/src/features/editor/public-url.js +36 -0
- package/dist/src/features/editor/session-state.js +78 -0
- package/dist/src/features/editor/session.js +213 -0
- package/dist/src/features/editor/use-cases.js +88 -0
- package/dist/src/features/org/org-service.js +76 -0
- package/dist/src/features/org/use-cases.js +163 -0
- package/dist/src/features/skill/bundled-skills.js +63 -0
- package/dist/src/features/skill/installer.js +271 -0
- 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/catalog.js +83 -0
- package/dist/src/features/tool/dynamic-schema.js +128 -0
- package/dist/src/features/tool/mns-catalog-adapter.js +265 -0
- package/dist/src/features/tool/tool-api-adapter.js +369 -0
- package/dist/src/features/tool/use-cases.js +180 -0
- package/dist/src/features/update/latest-version.js +37 -0
- package/dist/src/features/update/update-notification.js +271 -0
- package/dist/src/features/update/update-service.js +226 -0
- package/dist/src/platform/installation-owner.js +81 -0
- package/dist/src/platform/json-input.js +67 -0
- package/dist/src/platform/local-json-file.js +59 -0
- package/dist/src/platform/open-browser.js +8 -0
- package/dist/src/platform/redact.js +80 -0
- package/dist/src/platform/remote-error-evidence.js +80 -0
- package/dist/src/platform/remote-protocol.js +10 -0
- package/dist/src/platform/resource-auth-key.js +1 -0
- package/dist/src/platform/safe-upload-file.js +146 -0
- package/dist/src/platform/signature.js +20 -0
- package/dist/src/platform/signed-http-transport.js +144 -0
- package/dist/src/platform/task-observer.js +1 -0
- package/dist/src/platform/url-safety.js +100 -0
- package/dist/src/product/billing.js +47 -0
- package/dist/src/product/config.js +85 -0
- package/dist/src/product/locale.js +38 -0
- package/dist/src/product/text.js +3 -0
- package/dist/src/telemetry/invocation.js +156 -0
- package/dist/src/telemetry/sls-sink.js +30 -0
- package/package.json +53 -0
- package/skills/insmind-cli/SKILL.md +15 -0
- package/skills/insmind-cli/references/agent.md +34 -0
- package/skills/insmind-cli/references/auth.md +8 -0
- package/skills/insmind-cli/references/creation.md +40 -0
- package/skills/insmind-cli/references/dam.md +51 -0
- package/skills/insmind-cli/references/editor.md +184 -0
- package/skills/insmind-cli/references/errors.md +29 -0
- package/skills/insmind-cli/references/generation-constraints.md +36 -0
- package/skills/insmind-cli/references/tool.md +31 -0
- package/skills/insmind-cli/references/update.md +11 -0
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { buildCreativeRequest, creativeContextId, creativeTurnMessages, normalizeCreativeMessages, restoreCreativeResourceUrls } from "./creative-protocol.js";
|
|
2
|
+
import { parseCreativeStream } from "./creative-stream.js";
|
|
3
|
+
export function createCreativeAgentAdapter(dependencies) {
|
|
4
|
+
return {
|
|
5
|
+
async complete(message, access, signal, observe) {
|
|
6
|
+
signal.throwIfAborted();
|
|
7
|
+
const ids = message.contextId === undefined
|
|
8
|
+
? {
|
|
9
|
+
localThreadId: dependencies.idFactory(),
|
|
10
|
+
localMessageId: dependencies.idFactory()
|
|
11
|
+
}
|
|
12
|
+
: { localMessageId: dependencies.idFactory() };
|
|
13
|
+
await observe?.({ localMessageId: ids.localMessageId, ...(message.contextId ? { contextId: message.contextId } : {}) });
|
|
14
|
+
const streamed = await dependencies.telemetry.stage("execute", async () => {
|
|
15
|
+
await observe?.({ submissionStarted: true });
|
|
16
|
+
const stream = await dependencies.transport.postStream({
|
|
17
|
+
path: "/ai-agent/v1/thread/completion",
|
|
18
|
+
body: buildCreativeRequest(message, ids),
|
|
19
|
+
accept: "text/event-stream",
|
|
20
|
+
credential: access.credential,
|
|
21
|
+
organizationId: access.organizationId,
|
|
22
|
+
signal
|
|
23
|
+
});
|
|
24
|
+
await observe?.({ accepted: true });
|
|
25
|
+
return parseCreativeStream(stream, signal, observe ? async (contextId) => observe({ contextId }) : undefined);
|
|
26
|
+
});
|
|
27
|
+
const contextId = creativeContextId(streamed);
|
|
28
|
+
return dependencies.telemetry.stage("result", async () => {
|
|
29
|
+
const messages = await dependencies.transport.getJson({
|
|
30
|
+
path: `/ai-agent/v1/thread/${encodeURIComponent(contextId)}/messages`,
|
|
31
|
+
credential: access.credential,
|
|
32
|
+
organizationId: access.organizationId,
|
|
33
|
+
signal
|
|
34
|
+
});
|
|
35
|
+
const output = normalizeCreativeMessages(restoreCreativeResourceUrls(creativeTurnMessages(messages, ids.localMessageId), streamed));
|
|
36
|
+
return dependencies.resourceAuthorizer
|
|
37
|
+
? dependencies.resourceAuthorizer.authorize(output, access, signal)
|
|
38
|
+
: output;
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
2
|
+
export function buildCreativeRequest(message, ids) {
|
|
3
|
+
const prompt = [];
|
|
4
|
+
const textParts = [];
|
|
5
|
+
const attachments = [];
|
|
6
|
+
const parameters = Object.create(null);
|
|
7
|
+
const answerValues = [];
|
|
8
|
+
const answeredQuestions = [];
|
|
9
|
+
let questionMessageId;
|
|
10
|
+
let hasAnswers = false;
|
|
11
|
+
let hasGeneration = false;
|
|
12
|
+
let model;
|
|
13
|
+
for (const part of message.parts) {
|
|
14
|
+
if (part.kind === "text") {
|
|
15
|
+
textParts.push(part.text);
|
|
16
|
+
prompt.push({ type: "text", content: part.text });
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
if (part.kind === "asset") {
|
|
20
|
+
prompt.push({
|
|
21
|
+
type: "media",
|
|
22
|
+
url: part.asset.url,
|
|
23
|
+
name: part.asset.filename,
|
|
24
|
+
mime: part.asset.mediaType
|
|
25
|
+
});
|
|
26
|
+
attachments.push({
|
|
27
|
+
uri: part.asset.url,
|
|
28
|
+
mime_type: part.asset.mediaType,
|
|
29
|
+
from_user_upload: part.asset.fromUserUpload
|
|
30
|
+
});
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (part.kind === "generation") {
|
|
34
|
+
hasGeneration = true;
|
|
35
|
+
model = part.data.model ?? model;
|
|
36
|
+
Object.assign(parameters, part.data.arguments);
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
hasAnswers = true;
|
|
40
|
+
questionMessageId ??= part.data.questionMessageId;
|
|
41
|
+
for (const answer of part.data.answers) {
|
|
42
|
+
const values = [...answer.values];
|
|
43
|
+
answerValues.push(values);
|
|
44
|
+
answeredQuestions.push({ question: answer.question, answers: values });
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const generationFields = {
|
|
48
|
+
...(model === undefined ? {} : { scene_code: model }),
|
|
49
|
+
...(hasGeneration ? { parameters } : {})
|
|
50
|
+
};
|
|
51
|
+
let content;
|
|
52
|
+
if (hasAnswers) {
|
|
53
|
+
content = {
|
|
54
|
+
type: "user",
|
|
55
|
+
text: textParts.join("\n"),
|
|
56
|
+
prompt: prompt.length > 0 ? prompt : [{ type: "text", content: "" }],
|
|
57
|
+
...generationFields,
|
|
58
|
+
answer: { answers: answerValues }
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
else if (prompt.length === 1 && prompt[0]?.type === "text" && !hasGeneration) {
|
|
62
|
+
content = { type: "plain", text: prompt[0].content };
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
content = {
|
|
66
|
+
type: "plain",
|
|
67
|
+
prompt,
|
|
68
|
+
...generationFields
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
const extra = {};
|
|
72
|
+
if (hasAnswers && questionMessageId !== undefined) {
|
|
73
|
+
extra.lastToolMessageId = questionMessageId;
|
|
74
|
+
extra.last_tool_message_id = questionMessageId;
|
|
75
|
+
extra.askUserQuestionAnsweredQuestions = answeredQuestions;
|
|
76
|
+
extra.questions = answeredQuestions;
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
content,
|
|
80
|
+
name: hasAnswers ? "ask_user_question" : "user",
|
|
81
|
+
role: "user",
|
|
82
|
+
local_thread_id: message.contextId === undefined ? ids.localThreadId ?? "" : "",
|
|
83
|
+
local_message_id: ids.localMessageId,
|
|
84
|
+
thread_id: message.contextId ?? "",
|
|
85
|
+
attachments,
|
|
86
|
+
extra
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function record(value) {
|
|
90
|
+
return value !== null && typeof value === "object" && !Array.isArray(value)
|
|
91
|
+
? value
|
|
92
|
+
: undefined;
|
|
93
|
+
}
|
|
94
|
+
function parseJson(value) {
|
|
95
|
+
if (typeof value !== "string")
|
|
96
|
+
return value;
|
|
97
|
+
try {
|
|
98
|
+
return JSON.parse(value);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function nonEmptyString(value) {
|
|
105
|
+
return typeof value === "string" && value.trim() !== "" ? value : undefined;
|
|
106
|
+
}
|
|
107
|
+
function fail() {
|
|
108
|
+
throw new RemoteProtocolError();
|
|
109
|
+
}
|
|
110
|
+
export function creativeContextId(messages) {
|
|
111
|
+
if (messages.some((message) => message.event === "system_error"))
|
|
112
|
+
return fail();
|
|
113
|
+
const contextId = messages
|
|
114
|
+
.map((message) => nonEmptyString(message.thread_id))
|
|
115
|
+
.find((value) => value !== undefined);
|
|
116
|
+
return contextId ?? fail();
|
|
117
|
+
}
|
|
118
|
+
export function creativeTurnMessages(value, localMessageId) {
|
|
119
|
+
if (!Array.isArray(value) || !value.every((message) => record(message) !== undefined)) {
|
|
120
|
+
return fail();
|
|
121
|
+
}
|
|
122
|
+
const messages = value;
|
|
123
|
+
const start = messages.findIndex((message) => {
|
|
124
|
+
if (message.local_message_id !== localMessageId)
|
|
125
|
+
return false;
|
|
126
|
+
return message.role === "user" || contentOf(message)?.type === "function_response";
|
|
127
|
+
});
|
|
128
|
+
if (start < 0)
|
|
129
|
+
return fail();
|
|
130
|
+
const nextInput = messages.findIndex((message, index) => index > start
|
|
131
|
+
&& typeof message.local_message_id === "string" && message.local_message_id !== ""
|
|
132
|
+
&& message.local_message_id !== localMessageId
|
|
133
|
+
&& (message.role === "user" || contentOf(message)?.type === "function_response"));
|
|
134
|
+
return messages.slice(start, nextInput < 0 ? undefined : nextInput);
|
|
135
|
+
}
|
|
136
|
+
function contentOf(message) {
|
|
137
|
+
return record(message.content);
|
|
138
|
+
}
|
|
139
|
+
function functionPayload(message) {
|
|
140
|
+
const content = contentOf(message);
|
|
141
|
+
if (content?.type !== "function_call")
|
|
142
|
+
return undefined;
|
|
143
|
+
return record(parseJson(content.text));
|
|
144
|
+
}
|
|
145
|
+
function isQuestionCall(message) {
|
|
146
|
+
return functionPayload(message)?.name === "ask_user_question";
|
|
147
|
+
}
|
|
148
|
+
function hasHiddenTransportRole(message) {
|
|
149
|
+
return message.role === "user" || message.role === "system" || message.role === "tool";
|
|
150
|
+
}
|
|
151
|
+
function inferMediaType(url) {
|
|
152
|
+
let pathname;
|
|
153
|
+
try {
|
|
154
|
+
pathname = new URL(url).pathname;
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
pathname = url.split(/[?#]/, 1)[0] ?? "";
|
|
158
|
+
}
|
|
159
|
+
const extension = pathname.split(".").at(-1)?.toLowerCase();
|
|
160
|
+
return {
|
|
161
|
+
gif: "image/gif",
|
|
162
|
+
jpeg: "image/jpeg",
|
|
163
|
+
jpg: "image/jpeg",
|
|
164
|
+
mov: "video/quicktime",
|
|
165
|
+
mp3: "audio/mpeg",
|
|
166
|
+
mp4: "video/mp4",
|
|
167
|
+
png: "image/png",
|
|
168
|
+
wav: "audio/wav",
|
|
169
|
+
webm: "video/webm",
|
|
170
|
+
webp: "image/webp"
|
|
171
|
+
}[extension ?? ""] ?? "application/octet-stream";
|
|
172
|
+
}
|
|
173
|
+
function functionResponseParts(raw) {
|
|
174
|
+
const parsed = parseJson(raw);
|
|
175
|
+
const values = Array.isArray(parsed) ? parsed : parsed === undefined ? [] : [parsed];
|
|
176
|
+
const parts = [];
|
|
177
|
+
for (const value of values) {
|
|
178
|
+
const item = record(value);
|
|
179
|
+
if (item === undefined)
|
|
180
|
+
continue;
|
|
181
|
+
const text = nonEmptyString(item.text);
|
|
182
|
+
if (text !== undefined)
|
|
183
|
+
parts.push({ text });
|
|
184
|
+
const url = nonEmptyString(item.uri ?? item.url);
|
|
185
|
+
if (url === undefined)
|
|
186
|
+
continue;
|
|
187
|
+
const mediaType = nonEmptyString(item.mime_type ?? item.mimeType) ?? inferMediaType(url);
|
|
188
|
+
const filename = nonEmptyString(item.filename ?? item.name);
|
|
189
|
+
parts.push({
|
|
190
|
+
url,
|
|
191
|
+
mediaType,
|
|
192
|
+
...(filename === undefined ? {} : { filename })
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
return parts;
|
|
196
|
+
}
|
|
197
|
+
function hasAuthKey(url) {
|
|
198
|
+
try {
|
|
199
|
+
const value = new URL(url).searchParams.get("auth_key");
|
|
200
|
+
return value !== null && value.trim() !== "";
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function resourceUrlIdentity(url) {
|
|
207
|
+
try {
|
|
208
|
+
const parsed = new URL(url);
|
|
209
|
+
parsed.searchParams.delete("auth_key");
|
|
210
|
+
return parsed.toString();
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
return undefined;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
export function restoreCreativeResourceUrls(messages, streamed) {
|
|
217
|
+
const signedUrls = new Map();
|
|
218
|
+
for (const message of streamed) {
|
|
219
|
+
const messageId = nonEmptyString(message.message_id);
|
|
220
|
+
if (messageId === undefined)
|
|
221
|
+
continue;
|
|
222
|
+
const content = contentOf(message);
|
|
223
|
+
if (content?.type !== "function_response")
|
|
224
|
+
continue;
|
|
225
|
+
for (const part of functionResponseParts(content.text)) {
|
|
226
|
+
if (!("url" in part) || !hasAuthKey(part.url))
|
|
227
|
+
continue;
|
|
228
|
+
const identity = resourceUrlIdentity(part.url);
|
|
229
|
+
if (identity === undefined)
|
|
230
|
+
continue;
|
|
231
|
+
let messageUrls = signedUrls.get(messageId);
|
|
232
|
+
if (messageUrls === undefined) {
|
|
233
|
+
messageUrls = new Map();
|
|
234
|
+
signedUrls.set(messageId, messageUrls);
|
|
235
|
+
}
|
|
236
|
+
messageUrls.set(identity, part.url);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
const restored = messages.map((message) => {
|
|
240
|
+
const content = contentOf(message);
|
|
241
|
+
const messageId = nonEmptyString(message.message_id);
|
|
242
|
+
if (content?.type !== "function_response" || messageId === undefined)
|
|
243
|
+
return message;
|
|
244
|
+
const messageUrls = signedUrls.get(messageId);
|
|
245
|
+
if (messageUrls === undefined)
|
|
246
|
+
return message;
|
|
247
|
+
const parsed = parseJson(content.text);
|
|
248
|
+
const values = Array.isArray(parsed) ? parsed : parsed === undefined ? [] : [parsed];
|
|
249
|
+
let changed = false;
|
|
250
|
+
const nextValues = values.map((value) => {
|
|
251
|
+
const item = record(value);
|
|
252
|
+
if (item === undefined)
|
|
253
|
+
return value;
|
|
254
|
+
const uri = nonEmptyString(item.uri);
|
|
255
|
+
const fallbackUrl = nonEmptyString(item.url);
|
|
256
|
+
let field;
|
|
257
|
+
let url;
|
|
258
|
+
if (uri !== undefined) {
|
|
259
|
+
field = "uri";
|
|
260
|
+
url = uri;
|
|
261
|
+
}
|
|
262
|
+
else if (fallbackUrl !== undefined) {
|
|
263
|
+
field = "url";
|
|
264
|
+
url = fallbackUrl;
|
|
265
|
+
}
|
|
266
|
+
else {
|
|
267
|
+
return value;
|
|
268
|
+
}
|
|
269
|
+
if (hasAuthKey(url))
|
|
270
|
+
return value;
|
|
271
|
+
const identity = resourceUrlIdentity(url);
|
|
272
|
+
const signedUrl = identity === undefined ? undefined : messageUrls.get(identity);
|
|
273
|
+
if (signedUrl === undefined)
|
|
274
|
+
return value;
|
|
275
|
+
changed = true;
|
|
276
|
+
return { ...item, [field]: signedUrl };
|
|
277
|
+
});
|
|
278
|
+
if (!changed)
|
|
279
|
+
return message;
|
|
280
|
+
const nextValue = Array.isArray(parsed) ? nextValues : nextValues[0];
|
|
281
|
+
return {
|
|
282
|
+
...message,
|
|
283
|
+
content: {
|
|
284
|
+
...content,
|
|
285
|
+
text: typeof content.text === "string" ? JSON.stringify(nextValue) : nextValue
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
});
|
|
289
|
+
return restored;
|
|
290
|
+
}
|
|
291
|
+
function parseQuestionPart(message) {
|
|
292
|
+
const payload = functionPayload(message);
|
|
293
|
+
if (payload?.name !== "ask_user_question")
|
|
294
|
+
return fail();
|
|
295
|
+
const argumentsValue = parseJson(payload.arguments);
|
|
296
|
+
const argumentsRecord = record(argumentsValue);
|
|
297
|
+
if (argumentsRecord === undefined || !Array.isArray(argumentsRecord.questions)
|
|
298
|
+
|| argumentsRecord.questions.length === 0)
|
|
299
|
+
return fail();
|
|
300
|
+
const questions = argumentsRecord.questions.map((value) => {
|
|
301
|
+
const question = record(value);
|
|
302
|
+
const text = nonEmptyString(question?.question);
|
|
303
|
+
if (question === undefined || text === undefined)
|
|
304
|
+
return fail();
|
|
305
|
+
const rawOptions = question.options ?? [];
|
|
306
|
+
if (!Array.isArray(rawOptions))
|
|
307
|
+
return fail();
|
|
308
|
+
const options = rawOptions.map((rawOption) => {
|
|
309
|
+
const option = record(rawOption);
|
|
310
|
+
const label = nonEmptyString(option?.label);
|
|
311
|
+
if (option === undefined || label === undefined)
|
|
312
|
+
return fail();
|
|
313
|
+
return { label };
|
|
314
|
+
});
|
|
315
|
+
const allowMultiple = question.allow_multiple ?? question.allowMultiple;
|
|
316
|
+
if (typeof allowMultiple !== "boolean")
|
|
317
|
+
return fail();
|
|
318
|
+
return { question: text, options, allowMultiple };
|
|
319
|
+
});
|
|
320
|
+
const title = nonEmptyString(argumentsRecord.title);
|
|
321
|
+
return {
|
|
322
|
+
data: {
|
|
323
|
+
...(title === undefined ? {} : { title }),
|
|
324
|
+
questions: [questions[0], ...questions.slice(1)]
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
function dedupeParts(parts) {
|
|
329
|
+
const texts = new Set();
|
|
330
|
+
const urls = new Set();
|
|
331
|
+
return parts.filter((part) => {
|
|
332
|
+
if ("text" in part) {
|
|
333
|
+
if (texts.has(part.text))
|
|
334
|
+
return false;
|
|
335
|
+
texts.add(part.text);
|
|
336
|
+
return true;
|
|
337
|
+
}
|
|
338
|
+
if ("url" in part) {
|
|
339
|
+
if (urls.has(part.url))
|
|
340
|
+
return false;
|
|
341
|
+
urls.add(part.url);
|
|
342
|
+
}
|
|
343
|
+
return true;
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
export function normalizeCreativeMessages(messages) {
|
|
347
|
+
const contextId = creativeContextId(messages);
|
|
348
|
+
const latest = new Map();
|
|
349
|
+
const anonymous = [];
|
|
350
|
+
for (const message of messages) {
|
|
351
|
+
const id = nonEmptyString(message.message_id);
|
|
352
|
+
if (id === undefined)
|
|
353
|
+
anonymous.push(message);
|
|
354
|
+
else
|
|
355
|
+
latest.set(id, message);
|
|
356
|
+
}
|
|
357
|
+
const normalized = [...latest.values(), ...anonymous];
|
|
358
|
+
const parts = [];
|
|
359
|
+
for (const message of normalized) {
|
|
360
|
+
if (hasHiddenTransportRole(message))
|
|
361
|
+
continue;
|
|
362
|
+
const content = contentOf(message);
|
|
363
|
+
if (content !== undefined) {
|
|
364
|
+
if (content.type === "plain" || content.type === "user" || content.type === "text") {
|
|
365
|
+
const text = nonEmptyString(content.text);
|
|
366
|
+
if (text !== undefined)
|
|
367
|
+
parts.push({ text });
|
|
368
|
+
}
|
|
369
|
+
else if (content.type === "function_response") {
|
|
370
|
+
parts.push(...functionResponseParts(content.text));
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
else {
|
|
374
|
+
const text = nonEmptyString(message.content);
|
|
375
|
+
if (text !== undefined)
|
|
376
|
+
parts.push({ text });
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
const question = normalized.find((message) => !hasHiddenTransportRole(message) && isQuestionCall(message));
|
|
380
|
+
let questionMessageId;
|
|
381
|
+
if (question !== undefined) {
|
|
382
|
+
questionMessageId = nonEmptyString(question.message_id);
|
|
383
|
+
if (questionMessageId === undefined)
|
|
384
|
+
return fail();
|
|
385
|
+
parts.push(parseQuestionPart(question));
|
|
386
|
+
}
|
|
387
|
+
const publicParts = dedupeParts(parts);
|
|
388
|
+
if (publicParts.length === 0)
|
|
389
|
+
return fail();
|
|
390
|
+
const usageItems = [];
|
|
391
|
+
for (const message of normalized) {
|
|
392
|
+
if (contentOf(message)?.type !== "function_response")
|
|
393
|
+
continue;
|
|
394
|
+
const extra = record(message.extra);
|
|
395
|
+
const amount = extra?.deduct_points;
|
|
396
|
+
if (amount === undefined)
|
|
397
|
+
continue;
|
|
398
|
+
if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0)
|
|
399
|
+
return fail();
|
|
400
|
+
if (amount === 0)
|
|
401
|
+
continue;
|
|
402
|
+
const model = nonEmptyString(extra?.scene_code);
|
|
403
|
+
if (model === undefined)
|
|
404
|
+
return fail();
|
|
405
|
+
usageItems.push({ model, cost: { unit: "gaodou", amount } });
|
|
406
|
+
}
|
|
407
|
+
return {
|
|
408
|
+
message: {
|
|
409
|
+
...(questionMessageId === undefined ? {} : { messageId: questionMessageId }),
|
|
410
|
+
contextId,
|
|
411
|
+
parts: [publicParts[0], ...publicParts.slice(1)]
|
|
412
|
+
},
|
|
413
|
+
usage: {
|
|
414
|
+
cost: {
|
|
415
|
+
unit: "gaodou",
|
|
416
|
+
amount: usageItems.reduce((total, item) => total + item.cost.amount, 0)
|
|
417
|
+
},
|
|
418
|
+
items: usageItems
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
function isMessage(value) {
|
|
2
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3
|
+
}
|
|
4
|
+
function extractPayloads(raw) {
|
|
5
|
+
const lines = raw.replace(/\r\n?/g, "\n").split("\n");
|
|
6
|
+
const payloads = [];
|
|
7
|
+
let dataLines = [];
|
|
8
|
+
let foundData = false;
|
|
9
|
+
const flush = () => {
|
|
10
|
+
if (dataLines.length > 0)
|
|
11
|
+
payloads.push(dataLines.join("\n"));
|
|
12
|
+
dataLines = [];
|
|
13
|
+
};
|
|
14
|
+
for (const line of lines) {
|
|
15
|
+
if (line.startsWith("data:")) {
|
|
16
|
+
foundData = true;
|
|
17
|
+
dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
18
|
+
}
|
|
19
|
+
else if (line === "") {
|
|
20
|
+
flush();
|
|
21
|
+
}
|
|
22
|
+
else if (line.startsWith(":") || line.startsWith("event:") || line.startsWith("id:")) {
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
else if (!foundData || dataLines.length > 0) {
|
|
26
|
+
dataLines.push(line);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
flush();
|
|
30
|
+
return payloads;
|
|
31
|
+
}
|
|
32
|
+
function jsonEnd(value, start) {
|
|
33
|
+
const stack = [];
|
|
34
|
+
let inString = false;
|
|
35
|
+
let escaped = false;
|
|
36
|
+
for (let index = start; index < value.length; index += 1) {
|
|
37
|
+
const character = value[index];
|
|
38
|
+
if (inString) {
|
|
39
|
+
if (escaped)
|
|
40
|
+
escaped = false;
|
|
41
|
+
else if (character === "\\")
|
|
42
|
+
escaped = true;
|
|
43
|
+
else if (character === '"')
|
|
44
|
+
inString = false;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (character === '"') {
|
|
48
|
+
inString = true;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (character === "{" || character === "[")
|
|
52
|
+
stack.push(character);
|
|
53
|
+
else if (character === "}" || character === "]") {
|
|
54
|
+
const opening = stack.pop();
|
|
55
|
+
if ((character === "}" && opening !== "{") || (character === "]" && opening !== "[")) {
|
|
56
|
+
return -1;
|
|
57
|
+
}
|
|
58
|
+
if (stack.length === 0)
|
|
59
|
+
return index;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return -1;
|
|
63
|
+
}
|
|
64
|
+
function parseSequence(payload) {
|
|
65
|
+
if (payload.trim() === "[DONE]")
|
|
66
|
+
return [];
|
|
67
|
+
const values = [];
|
|
68
|
+
let index = 0;
|
|
69
|
+
while (index < payload.length) {
|
|
70
|
+
const objectStart = payload.indexOf("{", index);
|
|
71
|
+
const arrayStart = payload.indexOf("[", index);
|
|
72
|
+
const starts = [objectStart, arrayStart].filter((value) => value >= 0);
|
|
73
|
+
if (starts.length === 0)
|
|
74
|
+
break;
|
|
75
|
+
const start = Math.min(...starts);
|
|
76
|
+
const end = jsonEnd(payload, start);
|
|
77
|
+
if (end < 0)
|
|
78
|
+
break;
|
|
79
|
+
try {
|
|
80
|
+
values.push(JSON.parse(payload.slice(start, end + 1)));
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
// Ignore only the malformed value; a later complete value can still be read.
|
|
84
|
+
}
|
|
85
|
+
index = end + 1;
|
|
86
|
+
}
|
|
87
|
+
return values;
|
|
88
|
+
}
|
|
89
|
+
export async function parseCreativeStream(stream, signal, onContextId) {
|
|
90
|
+
signal.throwIfAborted();
|
|
91
|
+
const reader = stream.getReader();
|
|
92
|
+
const decoder = new TextDecoder();
|
|
93
|
+
let raw = "";
|
|
94
|
+
let contextReported = false;
|
|
95
|
+
const onAbort = () => {
|
|
96
|
+
void reader.cancel(signal.reason).catch(() => undefined);
|
|
97
|
+
};
|
|
98
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
99
|
+
try {
|
|
100
|
+
while (true) {
|
|
101
|
+
signal.throwIfAborted();
|
|
102
|
+
const result = await reader.read();
|
|
103
|
+
signal.throwIfAborted();
|
|
104
|
+
if (result.done)
|
|
105
|
+
break;
|
|
106
|
+
raw += decoder.decode(result.value, { stream: true });
|
|
107
|
+
if (onContextId && !contextReported) {
|
|
108
|
+
const contextId = messagesFrom(raw).find(message => typeof message.thread_id === "string" && message.thread_id)?.thread_id;
|
|
109
|
+
if (contextId) {
|
|
110
|
+
await onContextId(contextId);
|
|
111
|
+
contextReported = true;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
raw += decoder.decode();
|
|
116
|
+
}
|
|
117
|
+
finally {
|
|
118
|
+
signal.removeEventListener("abort", onAbort);
|
|
119
|
+
reader.releaseLock();
|
|
120
|
+
}
|
|
121
|
+
return messagesFrom(raw);
|
|
122
|
+
}
|
|
123
|
+
function messagesFrom(raw) {
|
|
124
|
+
const messages = [];
|
|
125
|
+
for (const payload of extractPayloads(raw)) {
|
|
126
|
+
for (const value of parseSequence(payload)) {
|
|
127
|
+
if (Array.isArray(value)) {
|
|
128
|
+
for (const item of value)
|
|
129
|
+
if (isMessage(item))
|
|
130
|
+
messages.push(item);
|
|
131
|
+
}
|
|
132
|
+
else if (isMessage(value)) {
|
|
133
|
+
messages.push(value);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return messages;
|
|
138
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
2
|
+
function isRecord(value) {
|
|
3
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4
|
+
}
|
|
5
|
+
export function createFilemsResourceAuthKeyProvider(dependencies) {
|
|
6
|
+
return {
|
|
7
|
+
async getAuthKey(access, signal) {
|
|
8
|
+
signal.throwIfAborted();
|
|
9
|
+
const response = await dependencies.transport.getJson({
|
|
10
|
+
path: "/filems/access/token",
|
|
11
|
+
credential: access.credential,
|
|
12
|
+
organizationId: access.organizationId,
|
|
13
|
+
signal
|
|
14
|
+
});
|
|
15
|
+
signal.throwIfAborted();
|
|
16
|
+
if (!isRecord(response) || typeof response.auth_key !== "string"
|
|
17
|
+
|| ["", "null", "undefined"].includes(response.auth_key.trim())) {
|
|
18
|
+
throw new RemoteProtocolError();
|
|
19
|
+
}
|
|
20
|
+
return response.auth_key;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
2
|
+
function unsignedPrivateUrl(value) {
|
|
3
|
+
let url;
|
|
4
|
+
try {
|
|
5
|
+
url = new URL(value);
|
|
6
|
+
}
|
|
7
|
+
catch {
|
|
8
|
+
throw new RemoteProtocolError();
|
|
9
|
+
}
|
|
10
|
+
const isPrivate = /^gd-ai-[a-z0-9-]+\.dancf\.com$/iu.test(url.hostname)
|
|
11
|
+
|| url.hostname === "dify-grsai.dancf.com"
|
|
12
|
+
|| url.hostname === "dify-aiznt.dancf.com";
|
|
13
|
+
if (!isPrivate || url.searchParams.get("auth_key")?.trim())
|
|
14
|
+
return undefined;
|
|
15
|
+
// Only send FileMS credentials to the verified HTTPS resource hosts.
|
|
16
|
+
if (url.protocol !== "https:" || url.username !== "" || url.password !== ""
|
|
17
|
+
|| url.port !== "")
|
|
18
|
+
throw new RemoteProtocolError();
|
|
19
|
+
return url;
|
|
20
|
+
}
|
|
21
|
+
export function createAgentResourceAuthorizer(dependencies) {
|
|
22
|
+
return {
|
|
23
|
+
async authorize(output, access, signal) {
|
|
24
|
+
signal.throwIfAborted();
|
|
25
|
+
const urls = output.message.parts.map((part) => ("url" in part ? unsignedPrivateUrl(part.url) : undefined));
|
|
26
|
+
if (urls.every((url) => url === undefined))
|
|
27
|
+
return output;
|
|
28
|
+
// One token serves this result only; do not retain it across identities or commands.
|
|
29
|
+
const authKey = await dependencies.authKeys.getAuthKey(access, signal);
|
|
30
|
+
signal.throwIfAborted();
|
|
31
|
+
const parts = output.message.parts.map((part, index) => {
|
|
32
|
+
const url = urls[index];
|
|
33
|
+
if (url === undefined || !("url" in part))
|
|
34
|
+
return part;
|
|
35
|
+
url.searchParams.set("auth_key", authKey);
|
|
36
|
+
return { ...part, url: url.href };
|
|
37
|
+
});
|
|
38
|
+
return {
|
|
39
|
+
...output,
|
|
40
|
+
message: {
|
|
41
|
+
...output.message,
|
|
42
|
+
parts: [parts[0], ...parts.slice(1)]
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|