|
@@ -41,29 +41,46 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
|
|
|
const connections = new Map<number, { url: string; apiKey: string }>()
|
|
const connections = new Map<number, { url: string; apiKey: string }>()
|
|
|
const executing = new Set<number>()
|
|
const executing = new Set<number>()
|
|
|
const pending = new Map<number, symbol>()
|
|
const pending = new Map<number, symbol>()
|
|
|
|
|
+ const streams = new Map<number, AbortController>()
|
|
|
|
|
|
|
|
async function request(
|
|
async function request(
|
|
|
connection: { url: string; apiKey: string },
|
|
connection: { url: string; apiKey: string },
|
|
|
path: string,
|
|
path: string,
|
|
|
- body?: Record<string, unknown> | FormData,
|
|
|
|
|
- stream?: { progress: (event: Omit<PaasProgress, "executionID">) => void },
|
|
|
|
|
|
|
+ body?: Record<string, unknown> | FormData | Uint8Array,
|
|
|
|
|
+ stream?: { progress: (event: Omit<PaasProgress, "executionID">) => void; controller: AbortController },
|
|
|
timeout = 30000,
|
|
timeout = 30000,
|
|
|
method = body ? "POST" : "GET",
|
|
method = body ? "POST" : "GET",
|
|
|
|
|
+ raw = false,
|
|
|
) {
|
|
) {
|
|
|
|
|
+ const timer = stream ? setTimeout(() => stream.controller.abort(), timeout) : undefined
|
|
|
const response = await fetcher(`${connection.url}/api/v1${path}`, {
|
|
const response = await fetcher(`${connection.url}/api/v1${path}`, {
|
|
|
method,
|
|
method,
|
|
|
redirect: "error",
|
|
redirect: "error",
|
|
|
headers: {
|
|
headers: {
|
|
|
Authorization: `Bearer ${connection.apiKey}`,
|
|
Authorization: `Bearer ${connection.apiKey}`,
|
|
|
Accept: stream ? "text/event-stream" : "application/json",
|
|
Accept: stream ? "text/event-stream" : "application/json",
|
|
|
- ...(body && !(body instanceof FormData) ? { "Content-Type": "application/json" } : {}),
|
|
|
|
|
|
|
+ ...(body instanceof Uint8Array
|
|
|
|
|
+ ? { "Content-Type": "application/octet-stream" }
|
|
|
|
|
+ : body && !(body instanceof FormData)
|
|
|
|
|
+ ? { "Content-Type": "application/json" }
|
|
|
|
|
+ : {}),
|
|
|
},
|
|
},
|
|
|
- body: body instanceof FormData ? body : body && JSON.stringify(body),
|
|
|
|
|
- signal: AbortSignal.timeout(stream ? 30 * 60 * 1000 : timeout),
|
|
|
|
|
- }).catch(() => {
|
|
|
|
|
- throw new Error("无法连接 AgentPaaS,请检查地址与网络。已有任务不会因此停止。")
|
|
|
|
|
|
|
+ body:
|
|
|
|
|
+ body instanceof Uint8Array
|
|
|
|
|
+ ? new Uint8Array(body)
|
|
|
|
|
+ : body instanceof FormData
|
|
|
|
|
+ ? body
|
|
|
|
|
+ : body && JSON.stringify(body),
|
|
|
|
|
+ signal: stream?.controller.signal ?? AbortSignal.timeout(timeout),
|
|
|
})
|
|
})
|
|
|
|
|
+ .catch(() => {
|
|
|
|
|
+ throw new Error("无法连接 AgentPaaS,请检查地址与网络。请到任务列表核对已有任务状态。")
|
|
|
|
|
+ })
|
|
|
|
|
+ .finally(() => clearTimeout(timer))
|
|
|
if (!response.ok) {
|
|
if (!response.ok) {
|
|
|
|
|
+ if (response.status === 413) throw new Error("文件超过当前平台的上传额度,请调整材料或联系平台管理员。")
|
|
|
|
|
+ if (response.status === 403)
|
|
|
|
|
+ throw new Error("AgentPaaS 返回 HTTP 403:当前账号没有执行此操作的权限,其他功能仍可使用。")
|
|
|
if (method === "PUT" && response.status === 409) {
|
|
if (method === "PUT" && response.status === 409) {
|
|
|
const result = paasRecord(await response.json().catch(() => undefined))
|
|
const result = paasRecord(await response.json().catch(() => undefined))
|
|
|
if (paasRecord(result?.detail)?.code === "AGENT_NAME_CONFLICT") throw new Error("已存在同名智能体。")
|
|
if (paasRecord(result?.detail)?.code === "AGENT_NAME_CONFLICT") throw new Error("已存在同名智能体。")
|
|
@@ -73,12 +90,15 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
|
|
|
throw new Error("PaaS 未接受修改,请检查配置字段及其值。")
|
|
throw new Error("PaaS 未接受修改,请检查配置字段及其值。")
|
|
|
throw new Error(`AgentPaaS 返回 HTTP ${response.status},请检查权限与平台版本。`)
|
|
throw new Error(`AgentPaaS 返回 HTTP ${response.status},请检查权限与平台版本。`)
|
|
|
}
|
|
}
|
|
|
|
|
+ if (raw) return response
|
|
|
if (stream) return readPaasStream(response, stream.progress)
|
|
if (stream) return readPaasStream(response, stream.progress)
|
|
|
return response.json() as Promise<unknown>
|
|
return response.json() as Promise<unknown>
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
return {
|
|
|
|
|
+ identity: (owner: number) => connections.get(owner),
|
|
|
async connect(owner: number, input?: { url: string; apiKey: string }) {
|
|
async connect(owner: number, input?: { url: string; apiKey: string }) {
|
|
|
|
|
+ streams.get(owner)?.abort()
|
|
|
connections.delete(owner)
|
|
connections.delete(owner)
|
|
|
const attempt = Symbol()
|
|
const attempt = Symbol()
|
|
|
pending.set(owner, attempt)
|
|
pending.set(owner, attempt)
|
|
@@ -96,12 +116,18 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
|
|
|
return { url: connection.url }
|
|
return { url: connection.url }
|
|
|
},
|
|
},
|
|
|
disconnect: (owner: number) => {
|
|
disconnect: (owner: number) => {
|
|
|
|
|
+ streams.get(owner)?.abort()
|
|
|
|
|
+ streams.delete(owner)
|
|
|
connections.delete(owner)
|
|
connections.delete(owner)
|
|
|
pending.delete(owner)
|
|
pending.delete(owner)
|
|
|
},
|
|
},
|
|
|
async request(owner: number, input: PaasRequest, emit?: (event: PaasProgress) => void) {
|
|
async request(owner: number, input: PaasRequest, emit?: (event: PaasProgress) => void) {
|
|
|
const connection = connections.get(owner)
|
|
const connection = connections.get(owner)
|
|
|
if (!connection) throw new Error("请先连接 AgentPaaS。")
|
|
if (!connection) throw new Error("请先连接 AgentPaaS。")
|
|
|
|
|
+ if (input?.action === "detach") {
|
|
|
|
|
+ streams.get(owner)?.abort()
|
|
|
|
|
+ return { detached: true }
|
|
|
|
|
+ }
|
|
|
if (input?.action === "execute") {
|
|
if (input?.action === "execute") {
|
|
|
if (typeof input.input !== "string" || !input.input.trim() || input.input.length > 100000)
|
|
if (typeof input.input !== "string" || !input.input.trim() || input.input.length > 100000)
|
|
|
throw new Error("请输入 1 到 100000 个字符的任务内容。")
|
|
throw new Error("请输入 1 到 100000 个字符的任务内容。")
|
|
@@ -113,25 +139,65 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
|
|
|
const path = `/agents/${identifier(input.agentID)}/run/stream`
|
|
const path = `/agents/${identifier(input.agentID)}/run/stream`
|
|
|
executing.add(owner)
|
|
executing.add(owner)
|
|
|
const executionID = input.executionID
|
|
const executionID = input.executionID
|
|
|
|
|
+ const controller = new AbortController()
|
|
|
|
|
+ streams.set(owner, controller)
|
|
|
return request(
|
|
return request(
|
|
|
connection,
|
|
connection,
|
|
|
path,
|
|
path,
|
|
|
{
|
|
{
|
|
|
input: input.input.trim(),
|
|
input: input.input.trim(),
|
|
|
|
|
+ input_files: input.files || [],
|
|
|
thread_id: input.threadID || "",
|
|
thread_id: input.threadID || "",
|
|
|
parameters: {},
|
|
parameters: {},
|
|
|
context: {},
|
|
context: {},
|
|
|
mode: "iterate",
|
|
mode: "iterate",
|
|
|
target_subagent: "",
|
|
target_subagent: "",
|
|
|
effort: input.effort,
|
|
effort: input.effort,
|
|
|
|
|
+ cancel_on_disconnect: false,
|
|
|
},
|
|
},
|
|
|
{
|
|
{
|
|
|
|
|
+ controller,
|
|
|
progress: (event) => {
|
|
progress: (event) => {
|
|
|
if (connections.get(owner) === connection && typeof executionID === "string" && executionID.length <= 64)
|
|
if (connections.get(owner) === connection && typeof executionID === "string" && executionID.length <= 64)
|
|
|
emit?.({ ...event, executionID })
|
|
emit?.({ ...event, executionID })
|
|
|
},
|
|
},
|
|
|
},
|
|
},
|
|
|
- ).finally(() => executing.delete(owner))
|
|
|
|
|
|
|
+ ).finally(() => {
|
|
|
|
|
+ executing.delete(owner)
|
|
|
|
|
+ if (streams.get(owner) === controller) streams.delete(owner)
|
|
|
|
|
+ })
|
|
|
|
|
+ }
|
|
|
|
|
+ if (input?.action === "file-capabilities") return request(connection, "/files/capabilities")
|
|
|
|
|
+ if (input?.action === "upload-file") {
|
|
|
|
|
+ if (!(input.data instanceof Uint8Array) || !input.data.byteLength) throw new Error("文件为空,未上传。")
|
|
|
|
|
+ const query = new URLSearchParams({
|
|
|
|
|
+ name: input.name,
|
|
|
|
|
+ agent_id: input.agentID,
|
|
|
|
|
+ session_id: input.threadID || "",
|
|
|
|
|
+ })
|
|
|
|
|
+ return request(connection, `/files?${query}`, input.data, undefined, 120000)
|
|
|
|
|
+ }
|
|
|
|
|
+ if (["run-files", "download", "cancel", "pause", "resume", "confirm"].includes(input?.action)) {
|
|
|
|
|
+ if (!("agentID" in input) || !("runID" in input)) throw new Error("缺少任务编号。")
|
|
|
|
|
+ const path = `/agents/${identifier(input.agentID)}/runs/${identifier(input.runID)}`
|
|
|
|
|
+ if (input.action === "run-files") return request(connection, `${path}/workspace`)
|
|
|
|
|
+ if (input.action === "download") {
|
|
|
|
|
+ const resource = input.artifactID
|
|
|
|
|
+ ? `artifacts/${identifier(input.artifactID)}/download`
|
|
|
|
|
+ : `workspace/${(input.path || "").split("/").map(identifier).join("/")}`
|
|
|
|
|
+ return request(connection, `${path}/${resource}`, undefined, undefined, 120000, "GET", true)
|
|
|
|
|
+ }
|
|
|
|
|
+ if (input.action === "resume")
|
|
|
|
|
+ return request(connection, `${path}/resume`, { checkpoint_id: input.checkpointID })
|
|
|
|
|
+ if (input.action === "confirm")
|
|
|
|
|
+ return request(connection, `${path}/confirm`, {
|
|
|
|
|
+ approval_id: input.approvalID,
|
|
|
|
|
+ approved: input.approved,
|
|
|
|
|
+ note: input.note,
|
|
|
|
|
+ idempotency_key: input.requestID,
|
|
|
|
|
+ })
|
|
|
|
|
+ if (input.action === "cancel" || input.action === "pause")
|
|
|
|
|
+ return request(connection, `${path}/${input.action}`, {})
|
|
|
}
|
|
}
|
|
|
if (input?.action === "agents") return request(connection, "/agents")
|
|
if (input?.action === "agents") return request(connection, "/agents")
|
|
|
if (input?.action === "packs") return request(connection, "/agentpacks")
|
|
if (input?.action === "packs") return request(connection, "/agentpacks")
|
|
@@ -206,6 +272,7 @@ export async function readPaasStream(
|
|
|
throw new Error("平台未返回会话事件流,请检查平台版本。")
|
|
throw new Error("平台未返回会话事件流,请检查平台版本。")
|
|
|
const reader = response.body.getReader()
|
|
const reader = response.body.getReader()
|
|
|
const decoder = new TextDecoder()
|
|
const decoder = new TextDecoder()
|
|
|
|
|
+ let result: Record<string, unknown> = {}
|
|
|
const state = { buffer: "", run_id: "", thread_id: "", output: "", error_message: "", status: "unknown", done: false }
|
|
const state = { buffer: "", run_id: "", thread_id: "", output: "", error_message: "", status: "unknown", done: false }
|
|
|
|
|
|
|
|
function consume(block: string) {
|
|
function consume(block: string) {
|
|
@@ -215,7 +282,18 @@ export async function readPaasStream(
|
|
|
?.slice(6)
|
|
?.slice(6)
|
|
|
.trim()
|
|
.trim()
|
|
|
if (
|
|
if (
|
|
|
- !["started", "answer", "error", "done", "cancelled", "paused", "tool_call", "tool_result"].includes(event || "")
|
|
|
|
|
|
|
+ ![
|
|
|
|
|
+ "started",
|
|
|
|
|
+ "answer",
|
|
|
|
|
+ "error",
|
|
|
|
|
+ "done",
|
|
|
|
|
+ "cancelled",
|
|
|
|
|
+ "paused",
|
|
|
|
|
+ "tool_call",
|
|
|
|
|
+ "tool_result",
|
|
|
|
|
+ "approval_required",
|
|
|
|
|
+ "confirmation_required",
|
|
|
|
|
+ ].includes(event || "")
|
|
|
)
|
|
)
|
|
|
return
|
|
return
|
|
|
const data = lines
|
|
const data = lines
|
|
@@ -229,7 +307,16 @@ export async function readPaasStream(
|
|
|
if (typeof value.run_id === "string") state.run_id = value.run_id
|
|
if (typeof value.run_id === "string") state.run_id = value.run_id
|
|
|
if (typeof value.thread_id === "string") state.thread_id = value.thread_id
|
|
if (typeof value.thread_id === "string") state.thread_id = value.thread_id
|
|
|
if (event === "started" || event === "paused" || event === "cancelled" || event === "done")
|
|
if (event === "started" || event === "paused" || event === "cancelled" || event === "done")
|
|
|
- progress?.({ type: event, status: typeof value.status === "string" ? value.status : undefined })
|
|
|
|
|
|
|
+ progress?.({
|
|
|
|
|
+ type: event,
|
|
|
|
|
+ runID: state.run_id,
|
|
|
|
|
+ threadID: state.thread_id,
|
|
|
|
|
+ status: typeof value.status === "string" ? value.status : undefined,
|
|
|
|
|
+ })
|
|
|
|
|
+ if (event === "approval_required" || event === "confirmation_required") {
|
|
|
|
|
+ result.pending_approval = value
|
|
|
|
|
+ progress?.({ type: "approval_required", runID: state.run_id, threadID: state.thread_id, approval: value })
|
|
|
|
|
+ }
|
|
|
if (event === "tool_call" || event === "tool_result") {
|
|
if (event === "tool_call" || event === "tool_result") {
|
|
|
const content = value.content ?? value.input ?? value.output
|
|
const content = value.content ?? value.input ?? value.output
|
|
|
progress?.({
|
|
progress?.({
|
|
@@ -245,6 +332,7 @@ export async function readPaasStream(
|
|
|
if (event === "error" && typeof value.message === "string") state.error_message = value.message
|
|
if (event === "error" && typeof value.message === "string") state.error_message = value.message
|
|
|
if (event === "cancelled" || event === "paused") state.status = event
|
|
if (event === "cancelled" || event === "paused") state.status = event
|
|
|
if (event === "done") {
|
|
if (event === "done") {
|
|
|
|
|
+ result = { ...result, ...value }
|
|
|
state.done = true
|
|
state.done = true
|
|
|
if (typeof value.status === "string") state.status = value.status
|
|
if (typeof value.status === "string") state.status = value.status
|
|
|
}
|
|
}
|
|
@@ -269,6 +357,7 @@ export async function readPaasStream(
|
|
|
state.error_message = "平台连接已结束,但未收到完成事件。请查看任务状态,勿直接重复发送。"
|
|
state.error_message = "平台连接已结束,但未收到完成事件。请查看任务状态,勿直接重复发送。"
|
|
|
}
|
|
}
|
|
|
return {
|
|
return {
|
|
|
|
|
+ ...result,
|
|
|
run_id: state.run_id,
|
|
run_id: state.run_id,
|
|
|
thread_id: state.thread_id,
|
|
thread_id: state.thread_id,
|
|
|
output: state.output,
|
|
output: state.output,
|
|
@@ -277,6 +366,7 @@ export async function readPaasStream(
|
|
|
}
|
|
}
|
|
|
})()
|
|
})()
|
|
|
.catch(() => ({
|
|
.catch(() => ({
|
|
|
|
|
+ ...result,
|
|
|
run_id: state.run_id,
|
|
run_id: state.run_id,
|
|
|
thread_id: state.thread_id,
|
|
thread_id: state.thread_id,
|
|
|
output: state.output,
|
|
output: state.output,
|