@axiom-lattice/gateway 4.4.0 → 4.4.2

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 (25) hide show
  1. package/dist/{a2a-standard-P7JDL6ZA.mjs → a2a-standard-RWR5JTMH.mjs} +2 -2
  2. package/dist/a2a-standard-RWR5JTMH.mjs.map +1 -0
  3. package/dist/embed/{embed-page-AgentDetailSideApp-PSRQVFNR.js → embed-page-AgentDetailSideApp-2BDEWFQ6.js} +1 -1
  4. package/dist/embed/embed-page-AgentGovernanceWorkbench-WG7E3G5T.js +5 -0
  5. package/dist/embed/{embed-page-MessageGraph-PDNQ67T4.js → embed-page-MessageGraph-5SWPEQ4V.js} +1 -1
  6. package/dist/embed/{embed-page-ReactChart-25KAFLQ3.js → embed-page-ReactChart-ZYWRXIMC.js} +1 -1
  7. package/dist/embed/{embed-page-TasksSideApp-DLH5LRMS.js → embed-page-TasksSideApp-X6255GEF.js} +1 -1
  8. package/dist/embed/{embed-page-TeamWorkspace-2WJJWF25.js → embed-page-TeamWorkspace-XNZM7AV7.js} +1 -1
  9. package/dist/embed/{embed-page-TopologyRuntimeView-WDQRHDMO.js → embed-page-TopologyRuntimeView-DGSHSTIU.js} +1 -1
  10. package/dist/embed/{embed-page-WorkflowAutomationView-BAMJ2WVB.js → embed-page-WorkflowAutomationView-BHIRIWV3.js} +1 -1
  11. package/dist/embed/embed-page-chunk-DEDTYRZE.js +245 -0
  12. package/dist/embed/{embed-page-chunk-XVUA7UHE.js → embed-page-chunk-HEO7X7LH.js} +1 -1
  13. package/dist/embed/{embed-page-chunk-TL2AYM76.js → embed-page-chunk-JMZ7OODN.js} +1 -1
  14. package/dist/embed/{embed-page-chunk-OBM5EUWZ.js → embed-page-chunk-SPC4BYNU.js} +192 -192
  15. package/dist/embed/{embed-page-chunk-LOXLXZNP.js → embed-page-chunk-XUXEGF3S.js} +1 -1
  16. package/dist/embed/{embed-page-chunk-MQDYZS3S.js → embed-page-chunk-YCX5YZRP.js} +1 -1
  17. package/dist/embed/embed-page.js +1 -1
  18. package/dist/index.js +9 -23
  19. package/dist/index.js.map +1 -1
  20. package/dist/index.mjs +9 -23
  21. package/dist/index.mjs.map +1 -1
  22. package/package.json +7 -7
  23. package/dist/a2a-standard-P7JDL6ZA.mjs.map +0 -1
  24. package/dist/embed/embed-page-AgentGovernanceWorkbench-UPQHJZD7.js +0 -5
  25. package/dist/embed/embed-page-chunk-SSC7ANWV.js +0 -245
@@ -594,7 +594,7 @@ ${formatFileRefsSection(inputFiles)}` : text;
594
594
  const { messageId } = await agent.addMessage({
595
595
  input: { message: messageText },
596
596
  ...reviewCommand || continuationCommand ? { command: reviewCommand ?? continuationCommand } : {},
597
- custom_run_config: { taskId: ctx.taskId }
597
+ custom_run_config: { taskId: ctx.taskId, execution: { taskId: ctx.taskId } }
598
598
  });
599
599
  const stream = agent.chunkStream(messageId, [
600
600
  MessageChunkTypes.MESSAGE_COMPLETED
@@ -1372,4 +1372,4 @@ data: ${JSON.stringify(data)}
1372
1372
  export {
1373
1373
  registerA2AStandardRoutes
1374
1374
  };
1375
- //# sourceMappingURL=a2a-standard-P7JDL6ZA.mjs.map
1375
+ //# sourceMappingURL=a2a-standard-RWR5JTMH.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/routes/a2a-standard.ts","../src/services/a2a/A2ATaskStoreAdapter.ts","../src/services/a2a/AxiomAgentExecutor.ts","../src/services/a2a/a2aFileRefs.ts","../src/services/a2a/A2AFileIngestor.ts","../src/services/a2a/A2ARuntimeRegistry.ts"],"sourcesContent":["import type { FastifyInstance, FastifyRequest } from \"fastify\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport {\n A2AError,\n DefaultExecutionEventBus,\n DefaultRequestHandler,\n InMemoryTaskStore,\n JsonRpcTransportHandler,\n RequestContext,\n} from \"@a2a-js/sdk/server\";\nimport type { AgentExecutionEvent } from \"@a2a-js/sdk/server\";\nimport type { JSONRPCResponse, Message } from \"@a2a-js/sdk\";\nimport { createTaskLifecycleService, getStoreLattice } from \"@axiom-lattice/core\";\nimport type {\n Assistant,\n AssistantStore,\n ProjectStore,\n TaskStore,\n TaskWorkItemStore,\n TenantStore,\n} from \"@axiom-lattice/protocols\";\nimport { A2AAuthError } from \"../services/a2a/A2AAuthService\";\nimport type { A2AAuthService } from \"../services/a2a/A2AAuthService\";\nimport { buildAgentCardForAssistant } from \"../services/a2a/A2AAgentCardBuilder\";\nimport { A2ATaskStoreAdapter } from \"../services/a2a/A2ATaskStoreAdapter\";\nimport type { A2ATaskLifecycleAdapter, A2ATaskStore } from \"../services/a2a/A2ATaskStoreAdapter\";\nimport { AxiomAgentExecutor, assistantHasGovernedTask } from \"../services/a2a/AxiomAgentExecutor\";\nimport { A2AFileIngestor } from \"../services/a2a/A2AFileIngestor\";\nimport {\n A2ARuntimeCapacityError,\n A2ARuntimeRegistry,\n} from \"../services/a2a/A2ARuntimeRegistry\";\nimport { saveProjectFile } from \"../services/workspace-file-service\";\n\n/** Stores injectable into the standard A2A routes (overridable in tests). */\nexport interface A2AStandardRoutesDeps {\n authService: A2AAuthService;\n /** Returns the internal task store (default: `getStoreLattice(\"default\",\"task\").store`). */\n getTaskStoreLattice?: () => TaskStore;\n /** Returns the work-item store used for governed A2A observations and lifecycle events. */\n getTaskWorkItemStore?: () => TaskWorkItemStore;\n /** Returns the assistant store (default: `getStoreLattice(\"default\",\"assistant\").store`). */\n getAssistantStore?: () => AssistantStore;\n /** Returns the project store (used by test-call to scope the request's project to the tenant). */\n getProjectStore?: () => ProjectStore;\n /** Returns the tenant store (used by agent-card discovery for cross-tenant fallback). */\n getTenantStore?: () => TenantStore | undefined;\n /**\n * Maximum decoded byte size accepted per inline file; defaults to the\n * {@link A2AFileIngestor} default (10 MiB). Exposed for testability.\n */\n maxFileBytes?: number;\n /** Gateway-lifetime scoped runtime registry; injectable for lifecycle tests. */\n runtimeRegistry?: A2ARuntimeRegistry;\n}\n\nfunction getHeader(value: string | string[] | undefined): string | undefined {\n if (Array.isArray(value)) return value[0];\n return value;\n}\n\n/** Session user parsed by the gateway global preHandler from the `Authorization` header. */\nfunction getSessionUser(\n request: FastifyRequest,\n): { id: string; tenantId?: string } | undefined {\n return (request as unknown as { user?: { id: string; tenantId?: string } })\n .user;\n}\n\n/**\n * Resolve the request tenant for session-aware discovery: prefer the session\n * user's tenant, then fall back to the `x-tenant-id` header, then `\"default\"`.\n */\nfunction buildBaseUrl(request: FastifyRequest): string {\n const protocol =\n getHeader(request.headers[\"x-forwarded-proto\"]) ?? request.protocol;\n const forwardedHost = getHeader(request.headers[\"x-forwarded-host\"]);\n const host = forwardedHost\n ? forwardedHost.split(\",\")[0]!.trim()\n : request.host;\n return `${protocol}://${host}`;\n}\n\n/**\n * Build a per-request file ingestor, binding the request's tenant onto the\n * shared `saveProjectFile` service (whose signature requires `tenantId`).\n */\nfunction makeFileIngestor(\n tenantId: string,\n maxFileBytes?: number,\n): A2AFileIngestor {\n return new A2AFileIngestor({\n saveProjectFile: (params) =>\n saveProjectFile({ tenantId, ...params }),\n ...(maxFileBytes !== undefined ? { maxBytes: maxFileBytes } : {}),\n });\n}\n\n/**\n * Resolve the addressing workspace for the key's bound project. Best-effort:\n * a missing project or store error leaves the workspace unset so the agent\n * keeps its legacy \"default\" fallback.\n */\nasync function resolveWorkspaceId(\n getProjectStore: () => ProjectStore,\n tenantId: string,\n projectId: string | undefined,\n): Promise<string | undefined> {\n if (!projectId) return undefined;\n try {\n const project = await getProjectStore().getProjectById(tenantId, projectId);\n return project?.workspaceId;\n } catch {\n return undefined;\n }\n}\n\nfunction extractRequestId(body: unknown): string | number | null {\n if (typeof body === \"object\" && body !== null && \"id\" in body) {\n const id = (body as { id?: unknown }).id;\n if (typeof id === \"string\" || typeof id === \"number\" || id === null) {\n return id;\n }\n }\n return null;\n}\n\n/** Map an auth failure status onto a JSON-RPC server error code. */\nfunction authErrorToRpcCode(statusCode: number): number {\n switch (statusCode) {\n case 401:\n return -32001;\n case 403:\n return -32002;\n case 404:\n return -32003;\n default:\n return -32603;\n }\n}\n\nfunction jsonRpcError(\n id: string | number | null,\n code: number,\n message: string,\n): JSONRPCResponse {\n return { jsonrpc: \"2.0\", id, error: { code, message } };\n}\n\nfunction isAsyncGenerator(\n value: JSONRPCResponse | AsyncGenerator<JSONRPCResponse, void, undefined>,\n): value is AsyncGenerator<JSONRPCResponse, void, undefined> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as unknown as { [Symbol.asyncIterator]?: unknown })[\n Symbol.asyncIterator\n ] === \"function\"\n );\n}\n\nconst SSE_HEADERS: Record<string, string> = {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Access-Control-Allow-Origin\": \"*\",\n \"A2A-Version\": \"0.3\",\n};\n\n/**\n * Register the standard A2A 0.3 endpoints for per-assistant discovery and\n * execution: agent card, JSON-RPC (`message/send`, `message/stream`,\n * `tasks/get`, `tasks/cancel`), and an internal `test-call` management route.\n */\nexport function registerA2AStandardRoutes(\n app: FastifyInstance,\n deps: A2AStandardRoutesDeps,\n): void {\n const authService = deps.authService;\n const resolveTasks =\n deps.getTaskStoreLattice ??\n (() => getStoreLattice(\"default\", \"task\").store as TaskStore);\n const resolveTaskWorkItems = deps.getTaskWorkItemStore ??\n (() => getStoreLattice(\"default\", \"taskWorkItem\").store as TaskWorkItemStore);\n const getAssistantStore =\n deps.getAssistantStore ??\n (() => getStoreLattice(\"default\", \"assistant\").store as AssistantStore);\n const getProjectStore =\n deps.getProjectStore ??\n (() => getStoreLattice(\"default\", \"project\").store as ProjectStore);\n const runtimeRegistry = deps.runtimeRegistry ?? new A2ARuntimeRegistry();\n app.addHook(\"onClose\", async () => {\n runtimeRegistry.close();\n });\n\n // GET /api/a2a/agents/:assistantId/.well-known/agent-card.json\n app.get<{ Params: { assistantId: string } }>(\n \"/api/a2a/agents/:assistantId/.well-known/agent-card.json\",\n async (request, reply) => {\n // Card discovery is key-authenticated: the same key that authorizes\n // jsonrpc also gates which agents are discoverable.\n const auth = await authService.authenticate(\n getHeader(request.headers.authorization) ??\n getHeader(request.headers[\"x-api-key\"]),\n );\n if (!auth.authenticated) {\n reply.status(401).send({ error: \"Unauthorized\" });\n return;\n }\n\n let assistant: Assistant;\n try {\n assistant = await authService.assertAgentAccess(\n auth,\n request.params.assistantId,\n );\n } catch (err) {\n if (err instanceof A2AAuthError) {\n reply.status(err.statusCode).send({ error: err.message });\n return;\n }\n request.log.error({ err }, \"a2a:agent-card:auth\");\n reply.status(500).send({ error: \"Internal error\" });\n return;\n }\n\n reply.header(\"A2A-Version\", \"0.3\");\n reply\n .status(200)\n .send(\n buildAgentCardForAssistant({\n assistant,\n baseUrl: buildBaseUrl(request),\n }),\n );\n },\n );\n\n // POST /api/a2a/agents/:assistantId/jsonrpc\n app.post<{ Params: { assistantId: string } }>(\n \"/api/a2a/agents/:assistantId/jsonrpc\",\n async (request, reply) => {\n const requestId = extractRequestId(request.body);\n const auth = await authService.authenticate(\n getHeader(request.headers.authorization) ??\n getHeader(request.headers[\"x-api-key\"]),\n );\n\n if (!auth.authenticated) {\n reply.status(401).send(jsonRpcError(requestId, -32001, \"Unauthorized\"));\n return;\n }\n\n let assistant: Assistant;\n try {\n assistant = await authService.assertAgentAccess(\n auth,\n request.params.assistantId,\n );\n } catch (err) {\n if (err instanceof A2AAuthError) {\n reply\n .status(err.statusCode)\n .send(\n jsonRpcError(\n requestId,\n authErrorToRpcCode(err.statusCode),\n err.message,\n ),\n );\n return;\n }\n request.log.error({ err }, \"a2a:jsonrpc:auth\");\n reply\n .status(500)\n .send(jsonRpcError(requestId, -32603, \"Internal error\"));\n return;\n }\n\n const tenantId = auth.tenantId ?? \"default\";\n const scope = {\n tenantId,\n projectId: auth.projectId ?? \"\",\n workspaceId: await resolveWorkspaceId(getProjectStore, tenantId, auth.projectId),\n assistantId: assistant.id,\n };\n const internalTasks = resolveTasks();\n const workItems = resolveTaskWorkItems();\n // Governed agents persist A2A tasks as platform TaskItems; plain agents\n // use an SDK in-memory A2A task store (no TaskMiddleware required).\n const taskStore: A2ATaskStore = assistantHasGovernedTask(assistant)\n ? new A2ATaskStoreAdapter({\n taskStore: internalTasks,\n workItemStore: workItems,\n lifecycle: createTaskLifecycleService({\n taskStore: internalTasks,\n workItemStore: workItems,\n }) as unknown as A2ATaskLifecycleAdapter,\n scope,\n })\n : (new InMemoryTaskStore() as unknown as A2ATaskStore);\n const ingestor = makeFileIngestor(scope.tenantId, deps.maxFileBytes);\n const executor = new AxiomAgentExecutor({ scope, assistant, taskStore, ingestor });\n const card = buildAgentCardForAssistant({\n assistant,\n baseUrl: buildBaseUrl(request),\n });\n let runtimeLease;\n try {\n runtimeLease = runtimeRegistry.acquire(scope);\n } catch (err) {\n if (err instanceof A2ARuntimeCapacityError) {\n request.log.error({ err, scope }, \"a2a:jsonrpc:runtime_capacity\");\n reply\n .status(503)\n .send(jsonRpcError(requestId, -32603, \"A2A runtime capacity exhausted\"));\n return;\n }\n throw err;\n }\n let result: JSONRPCResponse | AsyncGenerator<JSONRPCResponse, void, undefined>;\n try {\n const handler = new DefaultRequestHandler(\n card,\n taskStore,\n executor,\n runtimeLease.manager,\n );\n const transport = new JsonRpcTransportHandler(handler);\n reply.header(\"A2A-Version\", \"0.3\");\n result = await transport.handle(request.body);\n } catch (err) {\n runtimeLease.release();\n request.log.error({ err }, \"a2a:jsonrpc:handler\");\n reply\n .status(500)\n .send(jsonRpcError(requestId, -32603, \"Internal error\"));\n return;\n }\n\n if (isAsyncGenerator(result)) {\n reply.hijack();\n reply.raw.writeHead(200, SSE_HEADERS);\n try {\n for await (const evt of result) {\n reply.raw.write(`data: ${JSON.stringify(evt)}\\n\\n`);\n }\n } catch (err) {\n request.log.error({ err }, \"a2a:jsonrpc:stream\");\n const errorResponse = {\n jsonrpc: \"2.0\" as const,\n id: requestId,\n error: A2AError.internalError(\n err instanceof Error ? err.message : \"Streaming error.\",\n ).toJSONRPCError(),\n };\n reply.raw.write(`event: error\\ndata: ${JSON.stringify(errorResponse)}\\n\\n`);\n } finally {\n runtimeLease.release();\n reply.raw.end();\n }\n return;\n }\n\n runtimeLease.release();\n reply.send(result);\n },\n );\n\n // POST /api/a2a/agents/:assistantId/test-call\n app.post<{\n Params: { assistantId: string };\n Body: { projectId?: string; message?: string };\n }>(\n \"/api/a2a/agents/:assistantId/test-call\",\n async (request, reply) => {\n const user = getSessionUser(request);\n if (!user?.tenantId) {\n reply.status(401).send({ success: false, error: \"Unauthorized\" });\n return;\n }\n const tenantId = user.tenantId;\n const body = request.body ?? {};\n const { projectId, message } = body;\n\n if (!projectId) {\n reply.status(400).send({ error: \"projectId is required\" });\n return;\n }\n if (!message || !message.trim()) {\n reply.status(400).send({ error: \"message is required\" });\n return;\n }\n\n const assistant = await getAssistantStore().getAssistantById(\n tenantId,\n request.params.assistantId,\n );\n if (!assistant) {\n reply.status(404).send({ error: \"Assistant not found\" });\n return;\n }\n\n const project = await getProjectStore().getProjectById(\n tenantId,\n projectId,\n );\n if (!project || project.tenantId !== tenantId) {\n reply.status(403).send({ error: \"Project not found\" });\n return;\n }\n\n const scope = {\n tenantId,\n projectId,\n workspaceId: project.workspaceId,\n assistantId: assistant.id,\n };\n const ingestor = makeFileIngestor(scope.tenantId, deps.maxFileBytes);\n const internalTasks = resolveTasks();\n const workItems = resolveTaskWorkItems();\n // Governed agents persist A2A tasks as platform TaskItems; plain agents\n // use an SDK in-memory A2A task store (no TaskMiddleware required).\n const taskStore: A2ATaskStore = assistantHasGovernedTask(assistant)\n ? new A2ATaskStoreAdapter({\n taskStore: internalTasks,\n workItemStore: workItems,\n lifecycle: createTaskLifecycleService({\n taskStore: internalTasks,\n workItemStore: workItems,\n }) as unknown as A2ATaskLifecycleAdapter,\n scope,\n })\n : (new InMemoryTaskStore() as unknown as A2ATaskStore);\n const executor = new AxiomAgentExecutor({ scope, assistant, taskStore, ingestor });\n\n const taskId = uuidv4();\n const contextId = uuidv4();\n const userMessage: Message = {\n kind: \"message\",\n messageId: uuidv4(),\n role: \"user\",\n parts: [{ kind: \"text\", text: message }],\n };\n const requestContext = new RequestContext(userMessage, taskId, contextId);\n const bus = new DefaultExecutionEventBus();\n\n reply.hijack();\n reply.raw.writeHead(200, SSE_HEADERS);\n\n const sendEvent = (event: string, data: unknown): void => {\n reply.raw.write(`event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`);\n };\n\n bus.on(\"event\", (event: AgentExecutionEvent) => {\n sendEvent(event.kind, event);\n });\n\n try {\n await executor.execute(requestContext, bus);\n } catch (err) {\n request.log.error({ err }, \"a2a:test-call:execution\");\n sendEvent(\"status-update\", {\n kind: \"status-update\",\n taskId,\n contextId,\n status: { state: \"failed\", timestamp: new Date().toISOString() },\n final: true,\n });\n } finally {\n reply.raw.end();\n }\n },\n );\n}\n","import { createHash } from \"node:crypto\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport {\n createTaskRunBridge,\n type BeginRunResult,\n type LifecycleResult,\n type StartLifecycleResult,\n type TaskRunBridge,\n} from \"@axiom-lattice/core\";\nimport type {\n A2AMessage,\n A2APart,\n A2ATask,\n A2ATaskState,\n TaskFileRef,\n TaskItem,\n TaskStore,\n TaskWorkItemStore,\n} from \"@axiom-lattice/protocols\";\n\n/**\n * Projection from A2A protocol `TaskState` values onto the internal\n * `TaskItem` status lifecycle. `TaskItem` is the single source of truth,\n * so each SDK state must collapse onto one of its statuses.\n */\nexport const A2A_STATE_TO_TASK_STATUS: Record<string, TaskItem[\"status\"]> = {\n submitted: \"pending\",\n working: \"in_progress\",\n \"input-required\": \"interrupted\",\n completed: \"completed\",\n failed: \"failed\",\n canceled: \"cancelled\",\n rejected: \"failed\",\n};\n\n/**\n * Reverse projection used by {@link A2ATaskStoreAdapter.load} to surface the\n * current `TaskItem.status` back onto the restored SDK task's `status.state`.\n */\nexport const TASK_STATUS_TO_A2A_STATE: Record<TaskItem[\"status\"], A2ATaskState> = {\n pending: \"submitted\",\n in_progress: \"working\",\n review: \"input-required\",\n interrupted: \"input-required\",\n completed: \"completed\",\n failed: \"failed\",\n cancelled: \"canceled\",\n};\n\n/**\n * Structural contract satisfied by {@link A2ATaskStoreAdapter}, mirroring the\n * `@a2a-js/sdk` `TaskStore` interface (`save` / `load`). The `context` argument\n * is the SDK `ServerCallContext`, unused by this adapter.\n */\nexport interface A2ATaskStore {\n save(task: A2ATask, context?: unknown): Promise<void>;\n load(taskId: string, context?: unknown): Promise<A2ATask | undefined>;\n}\n\n/** Scope captured per A2A request, used to bind tasks to the right owner. */\nexport interface A2ATaskStoreAdapterScope {\n tenantId: string;\n projectId: string;\n /** Backfilled from the key's bound project; absent leaves TaskItem workspace unset. */\n workspaceId?: string;\n assistantId: string;\n}\n\n/** Dependencies injected into {@link A2ATaskStoreAdapter}. */\nexport interface A2ATaskStoreAdapterOptions {\n taskStore: TaskStore;\n workItemStore: TaskWorkItemStore;\n lifecycle: A2ATaskLifecycleAdapter;\n scope: A2ATaskStoreAdapterScope;\n}\n\n/** Narrow Core lifecycle surface used to govern A2A status observations. */\nexport interface A2ATaskLifecycleAdapter {\n startTask(input: { tenantId: string; taskId: string; actor: string; threadId?: string }): Promise<StartLifecycleResult>;\n resumeInterruption(input: { tenantId: string; taskId: string; actor: string; threadId?: string }): Promise<LifecycleResult>;\n retryTask(input: { tenantId: string; taskId: string; actor: string; threadId?: string }): Promise<LifecycleResult>;\n failTask(input: {\n tenantId: string; taskId: string; failureReason: string; actor: string; threadId?: string;\n }): Promise<LifecycleResult>;\n interruptTask(input: {\n tenantId: string; taskId: string; type: \"missing_input\" | \"external_dependency\" | \"user_decision\";\n summary: string; actor: string; threadId?: string;\n }): Promise<LifecycleResult>;\n cancelTask(input: {\n tenantId: string; taskId: string; actor: string; threadId?: string; summary?: string;\n }): Promise<LifecycleResult>;\n}\n\ntype A2AArtifact = NonNullable<A2ATask[\"artifacts\"]>[number];\nconst TITLE_MAX_LENGTH = 80;\n\n/** Structured failure raised when an A2A task ID belongs to another exact scope. */\nexport class A2ATaskScopeConflictError extends Error {\n readonly code = \"A2A_TASK_SCOPE_CONFLICT\";\n readonly taskId: string;\n\n constructor(taskId: string) {\n super(`A2A task ${taskId} belongs to another scope`);\n this.name = \"A2ATaskScopeConflictError\";\n this.taskId = taskId;\n }\n}\n\nfunction mapTaskStatusToA2AState(status: TaskItem[\"status\"]): A2ATaskState {\n return TASK_STATUS_TO_A2A_STATE[status];\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction asStringArray(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const strings = value.filter((item): item is string => typeof item === \"string\");\n return strings.length > 0 ? strings : undefined;\n}\n\nfunction extractText(parts: A2APart[]): string {\n return parts\n .filter((part): part is Extract<A2APart, { kind: \"text\" }> => part.kind === \"text\")\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\nfunction truncate(text: string, maxLength: number): string {\n if (text.length <= maxLength) return text;\n return `${text.slice(0, maxLength)}…`;\n}\n\nfunction extractTitleAndDescription(task: A2ATask): {\n title: string;\n description: string;\n} {\n const firstUserMessage = task.history?.find((message) => message.role === \"user\");\n const text = firstUserMessage ? extractText(firstUserMessage.parts) : \"\";\n return {\n title: truncate(text, TITLE_MAX_LENGTH),\n description: text ? [\n \"## Objective\",\n \"\",\n text,\n \"\",\n \"## Acceptance Criteria\",\n \"\",\n \"Complete the requested work and return the result through A2A.\",\n ].join(\"\\n\") : \"\",\n };\n}\n\nfunction isFileRef(value: unknown): value is TaskFileRef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as TaskFileRef).uri === \"string\"\n );\n}\n\nfunction artifactFileRefs(artifacts: A2AArtifact[] | undefined): TaskFileRef[] {\n const refs: TaskFileRef[] = [];\n for (const artifact of artifacts ?? []) {\n for (const part of artifact.parts) {\n if (part.kind !== \"file\") continue;\n const file = part.file;\n if (!(\"uri\" in file)) continue;\n refs.push({\n uri: file.uri,\n ...(file.name ? { name: file.name } : {}),\n ...(file.mimeType ? { mimeType: file.mimeType } : {}),\n addedBy: \"agent\",\n });\n }\n }\n return refs;\n}\n\nfunction extractFiles(task: A2ATask): TaskFileRef[] {\n const inputFiles = task.metadata?.inputFiles;\n const inputRefs = Array.isArray(inputFiles) ? inputFiles.filter(isFileRef) : [];\n return [...inputRefs, ...artifactFileRefs(task.artifacts)];\n}\n\nfunction extractArtifactText(artifacts: A2AArtifact[] | undefined): string {\n return (artifacts ?? [])\n .map((artifact) => extractText(artifact.parts))\n .filter((text) => text.length > 0)\n .join(\"\\n\");\n}\n\n/**\n * Derive the result text from the final agent turn in the task history.\n *\n * The executor streams agent output as incremental `working` status-update\n * messages (one per chunk), so a text-only result is present as a sequence of\n * agent messages after the last user message rather than as an artifact.\n */\nfunction extractFinalTurnAgentText(history: A2AMessage[] | undefined): string {\n const messages = history ?? [];\n let lastUserIndex = -1;\n for (let i = 0; i < messages.length; i += 1) {\n if (messages[i].role === \"user\") lastUserIndex = i;\n }\n return messages\n .slice(lastUserIndex + 1)\n .filter((message) => message.role === \"agent\")\n .map((message) => extractText(message.parts))\n .filter((text) => text.length > 0)\n .join(\"\");\n}\n\nfunction isFailureState(state: A2ATaskState): boolean {\n return state === \"failed\" || state === \"rejected\";\n}\n\nfunction extractFailureReason(task: A2ATask): string | undefined {\n if (!isFailureState(task.status.state) || !task.status.message) return undefined;\n return extractText(task.status.message.parts);\n}\n\nfunction observationEventKey(task: A2ATask, result?: string, failureReason?: string): string {\n const digest = createHash(\"sha256\").update(JSON.stringify({\n state: task.status.state,\n timestamp: task.status.timestamp,\n message: task.status.message,\n result,\n failureReason,\n })).digest(\"hex\");\n return `a2a-status-observation:${task.id}:${digest}`;\n}\n\nfunction snapshotEventKey(task: A2ATask): string {\n const digest = createHash(\"sha256\").update(JSON.stringify(task)).digest(\"hex\");\n return `a2a-task-snapshot:${task.id}:${digest}`;\n}\n\nfunction isGovernedObservation(state: A2ATaskState): boolean {\n return state === \"completed\" || state === \"failed\" || state === \"rejected\" ||\n state === \"input-required\" || state === \"canceled\";\n}\n\nfunction isA2ATaskSnapshot(value: unknown): value is A2ATask {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as A2ATask).id === \"string\" &&\n typeof (value as A2ATask).status === \"object\" &&\n (value as A2ATask).status !== null\n );\n}\n\nfunction snapshotSequence(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0\n ? value\n : undefined;\n}\n\n/**\n * Adapter projecting the A2A SDK's `Task` objects onto the internal `TaskStore`\n * lattice (`TaskItem` is the single lifecycle truth). Implements the SDK\n * `TaskStore` contract so `DefaultRequestHandler` can persist and restore tasks.\n *\n * A single ID is used in both directions: `TaskItem.id === SDK task.id`.\n */\nexport class A2ATaskStoreAdapter implements A2ATaskStore {\n private readonly taskStore: TaskStore;\n private readonly workItemStore: TaskWorkItemStore;\n private readonly lifecycle: A2ATaskStoreAdapterOptions[\"lifecycle\"];\n private readonly scope: A2ATaskStoreAdapterScope;\n private readonly runBridge: TaskRunBridge;\n private readonly snapshotSequences = new Map<string, number>();\n\n constructor(options: A2ATaskStoreAdapterOptions) {\n this.taskStore = options.taskStore;\n this.workItemStore = options.workItemStore;\n this.lifecycle = options.lifecycle;\n this.scope = options.scope;\n this.runBridge = createTaskRunBridge({\n lifecycle: this.lifecycle,\n taskStore: this.taskStore,\n workItemStore: this.workItemStore,\n });\n }\n\n /**\n * Persist an SDK task by projecting it onto a `TaskItem`, creating it when\n * the id is unseen or updating it otherwise. A full snapshot of the SDK task\n * is stored under `context.a2aTask` so `load` can restore it.\n */\n async save(task: A2ATask): Promise<void> {\n const { tenantId } = this.scope;\n const { title, description } = extractTitleAndDescription(task);\n const files = extractFiles(task);\n const result =\n task.status.state === \"completed\"\n ? extractArtifactText(task.artifacts) ||\n extractFinalTurnAgentText(task.history)\n : undefined;\n const failureReason = extractFailureReason(task);\n const context: Record<string, unknown> = {\n a2aContextId: task.contextId,\n threadId: asString(task.metadata?.threadId),\n a2aTask: task,\n };\n\n let existing = await this.taskStore.getById(tenantId, task.id);\n if (existing) {\n this.requireScope(existing, task.id);\n await this.recordSnapshot(task, existing);\n } else {\n try {\n existing = await this.taskStore.create({\n id: task.id,\n tenantId,\n ownerType: \"agent\",\n ownerId: this.scope.assistantId,\n projectId: this.scope.projectId,\n ...(this.scope.workspaceId ? { workspaceId: this.scope.workspaceId } : {}),\n title,\n description,\n sourceId: \"a2a\",\n status: \"pending\",\n priority: \"medium\",\n dependencies: asStringArray(task.metadata?.dependencies),\n files,\n context,\n });\n } catch (error) {\n existing = await this.taskStore.getById(tenantId, task.id);\n if (!existing) throw error;\n this.requireScope(existing, task.id);\n }\n await this.recordSnapshot(task, existing);\n }\n\n const actor = `a2a:${this.scope.assistantId}`;\n const threadId = asString(task.metadata?.threadId);\n if (task.status.state === \"working\") {\n if (existing.status === \"pending\") {\n await this.requireLifecycleSuccess(\"start\", task.id, await this.runBridge.beginRun({\n tenantId, task: existing, actor, ...(threadId ? { threadId } : {}),\n }));\n }\n return;\n }\n if (!isGovernedObservation(task.status.state)) return;\n await this.recordObservation(task, existing, result, failureReason);\n if ([\"completed\", \"failed\", \"cancelled\"].includes(existing.status)) return;\n if (task.status.state === \"input-required\" && this.isExactInterruptionReplay(task, existing)) return;\n if (existing.status === \"pending\") {\n const started = await this.requireLifecycleSuccess(\"start\", task.id, await this.runBridge.beginRun({\n tenantId, task: existing, actor, ...(threadId ? { threadId } : {}),\n }));\n existing = started.task;\n }\n await this.applyObservation(task, existing, failureReason);\n }\n\n private async recordSnapshot(task: A2ATask, item: TaskItem): Promise<void> {\n const incomingSequence = snapshotSequence(task.metadata?.snapshotSequence) ?? 0;\n const currentSequence = this.snapshotSequences.get(task.id) ?? 0;\n const sequence = Math.max(incomingSequence, currentSequence) + 1;\n this.snapshotSequences.set(task.id, sequence);\n const sequencedTask: A2ATask = {\n ...task,\n metadata: { ...(task.metadata ?? {}), snapshotSequence: sequence },\n };\n const eventKey = snapshotEventKey(sequencedTask);\n const workspaceId = item.workspaceId ?? this.scope.workspaceId;\n await this.workItemStore.createIfAbsentByEventKey({\n tenantId: this.scope.tenantId,\n taskId: task.id,\n projectId: this.scope.projectId,\n action: \"activity\",\n actor: `a2a:${this.scope.assistantId}`,\n summary: \"A2A task snapshot\",\n detail: { type: \"a2a_task_snapshot\", snapshotSequence: sequence, eventKey, task: sequencedTask },\n eventKey,\n ...(asString(task.metadata?.threadId) ? { threadId: asString(task.metadata?.threadId) } : {}),\n ...(workspaceId ? { workspaceId } : {}),\n });\n }\n\n private async recordObservation(\n task: A2ATask,\n item: TaskItem,\n result?: string,\n failureReason?: string,\n ): Promise<void> {\n const workspaceId = item.workspaceId ?? this.scope.workspaceId;\n await this.workItemStore.createIfAbsentByEventKey({\n tenantId: this.scope.tenantId,\n taskId: task.id,\n projectId: this.scope.projectId,\n action: \"activity\",\n actor: `a2a:${this.scope.assistantId}`,\n summary: `A2A observed ${task.status.state}`,\n detail: {\n type: \"a2a_status_observation\",\n state: task.status.state,\n ...(result === undefined ? {} : { result }),\n ...(failureReason === undefined ? {} : { failureReason }),\n ...(task.status.message ? { message: extractText(task.status.message.parts) } : {}),\n },\n eventKey: observationEventKey(task, result, failureReason),\n ...(asString(task.metadata?.threadId) ? { threadId: asString(task.metadata?.threadId) } : {}),\n ...(workspaceId ? { workspaceId } : {}),\n });\n }\n\n private async applyObservation(\n task: A2ATask,\n item: TaskItem,\n failureReason?: string,\n ): Promise<void> {\n const actor = `a2a:${this.scope.assistantId}`;\n const threadId = asString(task.metadata?.threadId);\n if (task.status.state === \"canceled\") {\n await this.requireLifecycleSuccess(\"cancel\", task.id, await this.runBridge.settleRun({\n tenantId: this.scope.tenantId, task: item, actor, ...(threadId ? { threadId } : {}),\n outcome: { kind: \"cancelled\", summary: \"A2A observed canceled\" },\n }));\n return;\n }\n if (isFailureState(task.status.state)) {\n await this.requireLifecycleSuccess(\"fail\", task.id, await this.runBridge.settleRun({\n tenantId: this.scope.tenantId, task: item, actor, ...(threadId ? { threadId } : {}),\n outcome: {\n kind: \"failed\", lifecycleHandled: false,\n error: failureReason?.trim() || `A2A observed ${task.status.state}`,\n },\n }));\n return;\n }\n if (task.status.state === \"input-required\") {\n await this.requireLifecycleSuccess(\"interrupt\", task.id, await this.runBridge.settleRun({\n tenantId: this.scope.tenantId, task: item, actor, ...(threadId ? { threadId } : {}),\n outcome: {\n kind: \"interrupted\",\n summary: task.status.message ? extractText(task.status.message.parts).trim() || \"A2A requires input\" : \"A2A requires input\",\n },\n }));\n return;\n }\n\n const canonical = await this.taskStore.getById(this.scope.tenantId, task.id);\n if (!canonical || !this.isInScope(canonical)) {\n throw new Error(`A2A completed observation cannot reconcile missing task ${task.id}`);\n }\n if (canonical.status === \"completed\") return;\n throw new Error(\n `A2A completed observation conflicts with canonical ${canonical.status} task ${task.id}`,\n );\n }\n\n private async requireLifecycleSuccess(\n operation: string,\n taskId: string,\n result: LifecycleResult | BeginRunResult,\n ): Promise<Extract<LifecycleResult, { success: true }> | Extract<BeginRunResult, { success: true }>> {\n if (result.success) {\n if (result.warnings?.length) {\n console.warn({ event: \"a2a:lifecycle:warnings\", operation, taskId, warnings: result.warnings });\n }\n return result;\n }\n throw new Error(`A2A lifecycle ${operation} failed: ${result.code}: ${result.error}`);\n }\n\n private isExactInterruptionReplay(task: A2ATask, item: TaskItem): boolean {\n const observed = task.metadata?.interruption;\n const canonical = item.context?.interruption;\n if (item.status !== \"interrupted\" || !canonical || typeof canonical !== \"object\") return false;\n if (observed && typeof observed === \"object\") return isDeepStrictEqual(observed, canonical);\n const observedSummary = task.status.message ? extractText(task.status.message.parts).trim() : \"\";\n return observedSummary.length > 0 &&\n (canonical as Record<string, unknown>).summary === observedSummary;\n }\n\n /**\n * Restore an SDK task from the stored snapshot, overlaying the current\n * `TaskItem.status` onto `task.status.state`. Returns `undefined` when the\n * task is unknown to the tenant or has no A2A snapshot.\n */\n async load(taskId: string): Promise<A2ATask | undefined> {\n const item = await this.taskStore.getById(this.scope.tenantId, taskId);\n if (!item || !this.isInScope(item)) return undefined;\n\n const pageSize = 100;\n let selected: SnapshotCandidate | undefined;\n for (let offset = 0; ; offset += pageSize) {\n const activities = await this.workItemStore.list({\n tenantId: this.scope.tenantId,\n taskId,\n action: \"activity\",\n order: \"desc\",\n limit: pageSize,\n offset,\n });\n for (const activity of activities) {\n if (activity.detail?.type !== \"a2a_task_snapshot\" || !isA2ATaskSnapshot(activity.detail.task)) continue;\n const sequence = snapshotSequence(activity.detail.snapshotSequence) ??\n snapshotSequence(activity.detail.task.metadata?.snapshotSequence);\n const candidate = {\n task: activity.detail.task,\n sequence,\n eventKey: asString(activity.detail.eventKey) ?? activity.eventKey ??\n snapshotEventKey(activity.detail.task),\n statusTimestamp: Date.parse(activity.detail.task.status.timestamp ?? \"\"),\n createdAt: activity.createdAt,\n id: activity.id,\n };\n if (!selected || this.isLaterSnapshot(candidate, selected)) selected = candidate;\n }\n if (activities.length < pageSize) break;\n }\n const snapshot = selected?.task ?? item.context?.a2aTask;\n if (!isA2ATaskSnapshot(snapshot)) return undefined;\n const restoredSequence = selected?.sequence ?? snapshotSequence(snapshot.metadata?.snapshotSequence);\n if (restoredSequence !== undefined) {\n this.snapshotSequences.set(taskId, Math.max(this.snapshotSequences.get(taskId) ?? 0, restoredSequence));\n }\n\n const state = mapTaskStatusToA2AState(item.status);\n const interruption = item.context?.interruption;\n const metadata = {\n ...(snapshot.metadata ?? {}),\n ...(interruption && typeof interruption === \"object\" ? { interruption } : {}),\n };\n const nonResultArtifacts = (snapshot.artifacts ?? []).filter((artifact) => artifact.name !== \"result\");\n const artifacts = item.status === \"completed\" && item.result?.trim()\n ? [...nonResultArtifacts, {\n artifactId: `${item.id}:result`,\n name: \"result\",\n parts: [{ kind: \"text\" as const, text: item.result }],\n }]\n : nonResultArtifacts;\n const message = state === \"failed\" && item.failureReason?.trim()\n ? {\n kind: \"message\" as const,\n messageId: `${item.id}:failure`,\n role: \"agent\" as const,\n parts: [{ kind: \"text\" as const, text: item.failureReason }],\n }\n : interruption && typeof interruption === \"object\" &&\n typeof (interruption as Record<string, unknown>).summary === \"string\"\n ? {\n kind: \"message\" as const,\n messageId: `${item.id}:interruption`,\n role: \"agent\" as const,\n parts: [{ kind: \"text\" as const, text: (interruption as Record<string, unknown>).summary as string }],\n }\n : snapshot.status.message;\n return {\n ...snapshot,\n metadata,\n ...(artifacts.length > 0 ? { artifacts } : { artifacts: undefined }),\n status: {\n ...snapshot.status,\n state,\n ...(message ? { message } : {}),\n },\n };\n }\n\n private isInScope(item: TaskItem): boolean {\n return (\n item.tenantId === this.scope.tenantId &&\n item.projectId === this.scope.projectId &&\n item.ownerType === \"agent\" &&\n item.ownerId === this.scope.assistantId &&\n item.sourceId === \"a2a\"\n );\n }\n\n private requireScope(item: TaskItem, taskId: string): void {\n if (!this.isInScope(item)) throw new A2ATaskScopeConflictError(taskId);\n }\n\n private isLaterSnapshot(\n candidate: SnapshotCandidate,\n selected: SnapshotCandidate,\n ): boolean {\n if (candidate.sequence !== undefined || selected.sequence !== undefined) {\n if (candidate.sequence === undefined) return false;\n if (selected.sequence === undefined) return true;\n if (candidate.sequence !== selected.sequence) return candidate.sequence > selected.sequence;\n\n // Concurrent adapters can allocate the same sequence. This resolves that\n // unordered conflict deterministically; it does not imply wall-clock append order.\n const candidateTimestamp = Number.isNaN(candidate.statusTimestamp) ? Number.NEGATIVE_INFINITY : candidate.statusTimestamp;\n const selectedTimestamp = Number.isNaN(selected.statusTimestamp) ? Number.NEGATIVE_INFINITY : selected.statusTimestamp;\n if (candidateTimestamp !== selectedTimestamp) return candidateTimestamp > selectedTimestamp;\n return candidate.eventKey > selected.eventKey;\n }\n return candidate.createdAt.getTime() > selected.createdAt.getTime() ||\n (candidate.createdAt.getTime() === selected.createdAt.getTime() && candidate.id > selected.id);\n }\n}\n\ninterface SnapshotCandidate {\n task: A2ATask;\n sequence?: number;\n eventKey: string;\n statusTimestamp: number;\n createdAt: Date;\n id: string;\n}\n","import { v4 as uuidv4 } from \"uuid\";\nimport { agentInstanceManager } from \"@axiom-lattice/core\";\nimport { MessageChunkTypes } from \"@axiom-lattice/protocols\";\nimport type { A2AMessage, A2APart, A2ATask, Assistant, TaskFileRef } from \"@axiom-lattice/protocols\";\nimport type {\n AgentExecutor,\n ExecutionEventBus,\n RequestContext,\n} from \"@a2a-js/sdk/server\";\nimport type {\n TaskArtifactUpdateEvent,\n TaskStatusUpdateEvent,\n} from \"@a2a-js/sdk\";\nimport { filePartsToRefsWithIngest } from \"./a2aFileRefs\";\nimport type { A2AFileIngestor } from \"./A2AFileIngestor\";\nimport type { A2ATaskStore } from \"./A2ATaskStoreAdapter\";\nimport { formatFileRefsSection } from \"../files/task-file-refs\";\n\n/** Scope captured per A2A request, used to bind execution to the right owner. */\nexport interface AxiomAgentExecutorScope {\n tenantId: string;\n projectId: string;\n /** Optional addressing workspace; omitted falls back to the agent's \"default\". */\n workspaceId?: string;\n assistantId: string;\n}\n\n/** Dependencies injected into {@link AxiomAgentExecutor}. */\nexport interface AxiomAgentExecutorOptions {\n scope: AxiomAgentExecutorScope;\n /** Persisted assistant definition used to preflight governed task capability. */\n assistant: Assistant;\n /**\n * Task store used to resolve thread/scope info when canceling a task.\n * Optional: execution-only harnesses (e.g. the internal `test-call` route)\n * omit it because they do not persist TaskItems.\n */\n taskStore?: A2ATaskStore;\n /**\n * Optional bytes-ingestor for inline A2A file parts. When omitted, inline\n * bytes parts are rejected (URI-only projection).\n */\n ingestor?: A2AFileIngestor;\n}\n\nfunction isoNow(): string {\n return new Date().toISOString();\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction extractText(parts: A2APart[]): string {\n return parts\n .filter((part): part is Extract<A2APart, { kind: \"text\" }> => part.kind === \"text\")\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\nfunction agentMessage(text: string): A2AMessage {\n return {\n kind: \"message\",\n messageId: uuidv4(),\n role: \"agent\",\n parts: [{ kind: \"text\", text }],\n };\n}\n\n/**\n * Whether an assistant is built for the platform's governed TaskItem flow\n * (TaskMiddleware exposing manage_task). Governed agents get TaskItem-mapped\n * A2A persistence; others get a plain A2A task store.\n */\nexport function assistantHasGovernedTask(assistant: Assistant): boolean {\n const graph = assistant.graphDefinition;\n const middleware = graph && typeof graph === \"object\"\n ? (graph as { middleware?: unknown }).middleware\n : undefined;\n const taskMiddleware = Array.isArray(middleware)\n ? middleware.find((entry): entry is Record<string, unknown> =>\n !!entry && typeof entry === \"object\" &&\n (entry as Record<string, unknown>).type === \"task\" &&\n (entry as Record<string, unknown>).enabled === true)\n : undefined;\n const allowedTools = taskMiddleware?.allowedTools;\n return !!taskMiddleware && (\n allowedTools === undefined ||\n (Array.isArray(allowedTools) && (allowedTools.length === 0 || allowedTools.includes(\"manage_task\")))\n );\n}\n\n/**\n * Translates a standard A2A request into an internal agent execution and\n * projects the agent's chunk stream back onto A2A lifecycle events.\n *\n * Implements the SDK `AgentExecutor` contract so `DefaultRequestHandler` can\n * drive execution. `TaskItem` persistence is owned by the injected task store\n * adapter; this class only publishes the correct event sequence.\n *\n * This intentionally does not use the Console/WebApp execution helper: A2A\n * owns a distinct event bus, cancellation protocol, and canonical task lifecycle.\n */\nexport class AxiomAgentExecutor implements AgentExecutor {\n private static readonly executions = new Map<string, Set<{ canceled: boolean }>>();\n private readonly scope: AxiomAgentExecutorScope;\n private readonly assistant: Assistant;\n private readonly taskStore?: A2ATaskStore;\n private readonly ingestor?: A2AFileIngestor;\n\n constructor(options: AxiomAgentExecutorOptions) {\n this.scope = options.scope;\n this.assistant = options.assistant;\n this.taskStore = options.taskStore;\n this.ingestor = options.ingestor;\n }\n\n /**\n * Execute the incoming message on the bound internal agent and publish the\n * resulting task/status/artifact events onto the bus.\n */\n async execute(ctx: RequestContext, bus: ExecutionEventBus): Promise<void> {\n const execution = { canceled: false };\n const taskKey = this.taskKey(ctx.taskId);\n const active = AxiomAgentExecutor.executions.get(taskKey) ?? new Set();\n active.add(execution);\n AxiomAgentExecutor.executions.set(taskKey, active);\n const text = extractText(ctx.userMessage.parts);\n const existing = ctx.task;\n const threadId = asString(existing?.metadata?.threadId) ?? uuidv4();\n const dependencies = ctx.referenceTasks?.map((task) => task.id) ?? [];\n\n const createTask = (inputFiles: TaskFileRef[]): A2ATask => ({\n kind: \"task\",\n id: ctx.taskId,\n contextId: ctx.contextId,\n ...(existing?.history ? { history: existing.history } : {}),\n ...(existing?.artifacts ? { artifacts: existing.artifacts } : {}),\n status: { state: \"working\", timestamp: isoNow() },\n metadata: { threadId, dependencies, inputFiles },\n } as A2ATask);\n\n const publishFailed = (err: unknown): void => {\n bus.publish({\n kind: \"status-update\",\n taskId: ctx.taskId,\n contextId: ctx.contextId,\n status: {\n state: \"failed\",\n message: agentMessage(err instanceof Error ? err.message : String(err)),\n timestamp: isoNow(),\n },\n final: true,\n } as TaskStatusUpdateEvent);\n };\n\n try {\n if (!this.taskStore) {\n const initialTask = createTask([]);\n bus.publish(initialTask);\n publishFailed(new Error(\"A2A execution requires a canonical task store\"));\n return;\n }\n // Governed task flow requires TaskMiddleware exposing manage_task; without\n // it we run a plain A2A task (platform-managed lifecycle) so any agent is\n // exposable over A2A — per the A2A spec, which mandates no middleware.\n const governed = this.hasGovernedTaskCapability();\n\n const interruption = existing?.metadata?.interruption;\n const reviewInterruption = interruption && typeof interruption === \"object\" &&\n (interruption as Record<string, unknown>).type === \"review_required\";\n const reviewCommand = reviewInterruption\n ? this.reviewCommand(text)\n : undefined;\n if (reviewInterruption && !reviewCommand) {\n bus.publish(agentMessage(\"Review response must be exactly 'approve', 'reject', or 'reject: <note>'.\"));\n return;\n }\n\n let inputFiles: TaskFileRef[];\n try {\n inputFiles = await filePartsToRefsWithIngest(\n ctx.userMessage.parts,\n \"user\",\n this.ingestor,\n ctx.taskId,\n this.scope.projectId,\n );\n } catch (err) {\n // Emit the initial task (without files) before the terminal status so the\n // ResultManager has a task to attach the failure to — otherwise the\n // failed status-update is dropped for a not-yet-persisted task.\n const initialTask = createTask([]);\n if (this.taskStore) await this.taskStore.save(initialTask);\n bus.publish(initialTask);\n publishFailed(err);\n return;\n }\n\n const initialTask = createTask(inputFiles);\n await this.taskStore.save(initialTask);\n bus.publish(initialTask);\n try {\n const agent = agentInstanceManager.getAgent(this.agentParams(threadId));\n\n // Files must reach the agent, not just TaskItem metadata. There is no\n // attachment channel on `QueueMessage`, so the references are appended\n // to the message text as a structured \"[附件]\" section (see\n // `formatFileRefsSection`).\n const requestText =\n inputFiles.length > 0\n ? `${text}\\n\\n${formatFileRefsSection(inputFiles)}`\n : text;\n const messageText = governed\n ? [\n `A2A governed task instruction: get and update the existing TaskItem ${ctx.taskId}; do not create a replacement task.`,\n \"Before doing the requested work, initialize its canonical description through manage_task with ## Objective, ## Acceptance Criteria, and ## Belief State sections.\",\n \"Keep lifecycle status truthful. Change status only through manage_task set_status; complete with a nonblank result and structured beliefImpact, and use interrupted, failed, or cancelled when appropriate. Use manage_task update for content fields only.\",\n \"\",\n requestText,\n ].join(\"\\n\")\n : requestText;\n\n const continuationCommand = interruption && typeof interruption === \"object\"\n ? { resume: text }\n : undefined;\n const { messageId } = await agent.addMessage({\n input: { message: messageText },\n ...(reviewCommand || continuationCommand\n ? { command: reviewCommand ?? continuationCommand }\n : {}),\n custom_run_config: { taskId: ctx.taskId, execution: { taskId: ctx.taskId } },\n });\n\n const stream = agent.chunkStream(messageId, [\n MessageChunkTypes.MESSAGE_COMPLETED,\n ]);\n\n let outputText = \"\";\n let interrupted = false;\n for await (const chunk of stream) {\n if (execution.canceled) return;\n const chunkType = chunk.type;\n const chunkText = chunk.data?.content ?? \"\";\n\n if (chunkType === MessageChunkTypes.INTERRUPT) {\n interrupted = true;\n break;\n }\n\n if (chunkType === MessageChunkTypes.AI && chunkText) {\n outputText += chunkText;\n }\n\n if (\n chunkType === MessageChunkTypes.AI ||\n chunkType === MessageChunkTypes.TOOL\n ) {\n if (chunkText) {\n bus.publish({\n kind: \"status-update\",\n taskId: ctx.taskId,\n contextId: ctx.contextId,\n status: {\n state: \"working\",\n message: agentMessage(chunkText),\n timestamp: isoNow(),\n },\n final: false,\n } as TaskStatusUpdateEvent);\n }\n }\n }\n\n if (execution.canceled) return;\n\n if (!governed) {\n if (interrupted) {\n const paused = {\n ...createTask(inputFiles),\n status: { state: \"input-required\", timestamp: isoNow() },\n } as A2ATask;\n await this.taskStore.save(paused);\n bus.publish({\n kind: \"status-update\",\n taskId: ctx.taskId,\n contextId: ctx.contextId,\n status: { state: \"input-required\", timestamp: isoNow() },\n final: true,\n } as TaskStatusUpdateEvent);\n return;\n }\n const resultArtifact = {\n artifactId: uuidv4(),\n name: \"result\",\n parts: [{ kind: \"text\", text: outputText }],\n };\n const completed = {\n ...createTask(inputFiles),\n artifacts: [...(existing?.artifacts ?? []), resultArtifact],\n status: { state: \"completed\", timestamp: isoNow() },\n } as A2ATask;\n await this.taskStore.save(completed);\n bus.publish({\n kind: \"artifact-update\",\n taskId: ctx.taskId,\n contextId: ctx.contextId,\n artifact: resultArtifact,\n } as TaskArtifactUpdateEvent);\n bus.publish({\n kind: \"status-update\",\n taskId: ctx.taskId,\n contextId: ctx.contextId,\n status: { state: \"completed\", timestamp: isoNow() },\n final: true,\n } as TaskStatusUpdateEvent);\n return;\n }\n\n const canonical = await this.taskStore.load(ctx.taskId);\n const canonicalState = canonical?.status.state;\n if (canonicalState === \"completed\") {\n const resultArtifact = canonical?.artifacts?.find((artifact) => artifact.name === \"result\");\n if (!resultArtifact) {\n throw new Error(`Canonical completed task ${ctx.taskId} has no result artifact`);\n }\n if (execution.canceled) return;\n bus.publish({\n kind: \"artifact-update\",\n taskId: ctx.taskId,\n contextId: ctx.contextId,\n artifact: resultArtifact,\n } as TaskArtifactUpdateEvent);\n }\n if (canonicalState === \"completed\" || canonicalState === \"failed\" || canonicalState === \"canceled\") {\n if (execution.canceled) return;\n bus.publish({\n kind: \"status-update\",\n taskId: ctx.taskId,\n contextId: ctx.contextId,\n status: {\n state: canonicalState,\n ...(canonical?.status.message ? { message: canonical.status.message } : {}),\n timestamp: isoNow(),\n },\n final: true,\n } as TaskStatusUpdateEvent);\n return;\n }\n if (canonicalState === \"input-required\") {\n bus.publish({\n kind: \"status-update\",\n taskId: ctx.taskId,\n contextId: ctx.contextId,\n status: {\n state: \"input-required\",\n ...(canonical?.status.message ? { message: canonical.status.message } : {}),\n timestamp: isoNow(),\n },\n final: true,\n } as TaskStatusUpdateEvent);\n return;\n }\n bus.publish({\n kind: \"status-update\",\n taskId: ctx.taskId,\n contextId: ctx.contextId,\n status: {\n state: \"failed\",\n message: agentMessage(\"Agent did not complete governed task lifecycle\"),\n timestamp: isoNow(),\n },\n final: true,\n } as TaskStatusUpdateEvent);\n } catch (err) {\n publishFailed(err);\n }\n } finally {\n active.delete(execution);\n if (active.size === 0) AxiomAgentExecutor.executions.delete(taskKey);\n }\n }\n\n private reviewCommand(text: string):\n { resume: { action: \"approve\" } | { action: \"reject\"; data: { note: string } } } | undefined {\n const trimmed = text.trim();\n const normalized = trimmed.toLowerCase();\n if (normalized === \"approve\") return { resume: { action: \"approve\" } };\n if (normalized === \"reject\") {\n return { resume: { action: \"reject\", data: { note: \"Changes requested.\" } } };\n }\n const prefixedNote = /^reject:\\s*(.+)$/is.exec(trimmed)?.[1]?.trim();\n if (prefixedNote) {\n return { resume: { action: \"reject\", data: { note: prefixedNote } } };\n }\n return undefined;\n }\n\n private taskKey(taskId: string): string {\n return `${this.scope.tenantId}:${this.scope.projectId}:${this.scope.assistantId}:${taskId}`;\n }\n\n private agentParams(threadId: string): {\n assistant_id: string;\n thread_id: string;\n tenant_id: string;\n project_id: string;\n workspace_id?: string;\n } {\n return {\n assistant_id: this.scope.assistantId,\n thread_id: threadId,\n tenant_id: this.scope.tenantId,\n project_id: this.scope.projectId,\n ...(this.scope.workspaceId ? { workspace_id: this.scope.workspaceId } : {}),\n };\n }\n\n private hasGovernedTaskCapability(): boolean {\n return assistantHasGovernedTask(this.assistant);\n }\n\n /**\n * Cancel a running task: resolve its thread id from the task store, abort the\n * underlying agent, and publish the terminal `canceled` event.\n */\n async cancelTask(taskId: string, bus: ExecutionEventBus): Promise<void> {\n for (const execution of AxiomAgentExecutor.executions.get(this.taskKey(taskId)) ?? []) {\n execution.canceled = true;\n }\n const task = this.taskStore ? await this.taskStore.load(taskId) : undefined;\n const threadId = task ? asString(task.metadata?.threadId) : undefined;\n\n if (threadId) {\n try {\n const agent = agentInstanceManager.getAgent(this.agentParams(threadId));\n await agent.abort();\n } catch (err) {\n // The agent session may have already been cleaned up.\n console.warn({\n event: \"a2a:cancel:no_agent\",\n taskId,\n threadId,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n bus.publish({\n kind: \"status-update\",\n taskId,\n contextId: task?.contextId ?? \"\",\n status: { state: \"canceled\", timestamp: isoNow() },\n final: true,\n } as TaskStatusUpdateEvent);\n }\n}\n","import type { A2APart, TaskFileRef } from \"@axiom-lattice/protocols\";\nimport type { A2AFileIngestor } from \"./A2AFileIngestor\";\nexport { formatFileRefsSection } from \"../files/task-file-refs\";\n\n/**\n * Project A2A message `file` parts onto internal {@link TaskFileRef} records.\n *\n * This is a URI-only pure function: only parts whose file is referenced by URI\n * are supported. Inline `bytes` files are rejected with an explicit error — to\n * ingest `bytes` into workspace storage, use {@link filePartsToRefsWithIngest}\n * with an {@link A2AFileIngestor} instead.\n *\n * @param parts - The A2A message parts to scan for file references.\n * @param addedBy - Who attached the file: `\"user\"` (reference material) or `\"agent\"` (artifact).\n * @returns The file references extracted from URI-backed file parts, in encounter order.\n * @throws {Error} When any file part carries inline `bytes` instead of a `uri`.\n */\nexport function filePartsToRefs(\n parts: A2APart[],\n addedBy: \"user\" | \"agent\",\n): TaskFileRef[] {\n const refs: TaskFileRef[] = [];\n\n for (const part of parts) {\n if (part.kind !== \"file\") continue;\n\n const file = part.file;\n if (\"bytes\" in file) {\n throw new Error(\n \"A2A file parts with inline bytes are not supported by this pure function — bytes ingest requires filePartsToRefsWithIngest with an A2AFileIngestor; provide a file uri otherwise\",\n );\n }\n\n refs.push({\n uri: file.uri,\n ...(file.name ? { name: file.name } : {}),\n ...(file.mimeType ? { mimeType: file.mimeType } : {}),\n addedBy,\n });\n }\n\n return refs;\n}\n\n/**\n * Project A2A message `file` parts onto {@link TaskFileRef} records, ingesting\n * inline `bytes` through the provided {@link A2AFileIngestor}.\n *\n * When no ingestor is supplied this delegates to the pure {@link filePartsToRefs}\n * projection (URI-only, rejecting inline bytes), preserving the executor's\n * original behavior for harnesses that do not wire storage.\n *\n * @param parts - The A2A message parts to scan for file references.\n * @param addedBy - Who attached the files: `\"user\"` or `\"agent\"`.\n * @param ingestor - Optional bytes-ingestor; when absent, bytes parts are rejected.\n * @param dedupeKeyBase - Stable key prefix for idempotent ingest (e.g. `taskId`).\n * @param projectId - Destination project for bytes ingestion.\n * @returns The file references in encounter order.\n */\nexport async function filePartsToRefsWithIngest(\n parts: A2APart[],\n addedBy: \"user\" | \"agent\",\n ingestor: A2AFileIngestor | undefined,\n dedupeKeyBase: string,\n projectId: string,\n): Promise<TaskFileRef[]> {\n if (!ingestor) {\n return filePartsToRefs(parts, addedBy);\n }\n\n const refs: TaskFileRef[] = [];\n for (let index = 0; index < parts.length; index += 1) {\n const part = parts[index];\n if (part.kind !== \"file\") continue;\n const dedupeKey = `${dedupeKeyBase}:${index}`;\n refs.push(await ingestor.ingest(part, dedupeKey, projectId, addedBy));\n }\n return refs;\n}\n","import type { A2APart, TaskFileRef } from \"@axiom-lattice/protocols\";\n\ntype FilePart = Extract<A2APart, { kind: \"file\" }>;\n\n/** Dependencies injected into {@link A2AFileIngestor} for testability. */\nexport interface A2AFileIngestorOptions {\n /**\n * Writes decoded file bytes into project storage and returns the URI agents\n * reference. Bound to the shared workspace `saveProjectFile` service by the\n * gateway wiring; overridable in tests.\n *\n * NOTE: this contract does not include `tenantId` — callers bind the tenant\n * via a closure (e.g. `(p) => saveProjectFile({ tenantId, ...p })`).\n */\n saveProjectFile: (params: {\n projectId: string;\n name: string;\n bytes: Uint8Array;\n mimeType?: string;\n /** Relative subdirectory under the project root (e.g. `a2a/<taskId>`). */\n path?: string;\n }) => Promise<{ uri: string }>;\n /** Maximum decoded byte size accepted per file; defaults to 10 MiB. */\n maxBytes?: number;\n}\n\nconst DEFAULT_MAX_BYTES = 100 * 1024 * 1024;\n\n/**\n * Minimal executable-file blacklist. Inline `bytes` uploads are an ingestion\n * vector for scripts/binaries; there is no existing allowlist in the upload\n * flow, so reject these by extension or MIME before writing.\n */\nconst EXECUTABLE_EXTENSIONS = new Set([\n \".exe\", \".sh\", \".bat\", \".cmd\", \".com\", \".msi\",\n \".js\", \".mjs\", \".cjs\", \".ps1\", \".vbs\", \".dll\", \".so\", \".dylib\",\n]);\n\nconst EXECUTABLE_MIME_TYPES = new Set([\n \"application/x-msdownload\",\n \"application/x-msdos-program\",\n \"application/x-executable\",\n \"application/x-sh\",\n \"application/x-bat\",\n \"application/x-shellscript\",\n \"text/x-shellscript\",\n \"application/javascript\",\n \"application/x-javascript\",\n \"text/javascript\",\n]);\n\nfunction decodeBase64(value: string): Uint8Array {\n return new Uint8Array(Buffer.from(value, \"base64\"));\n}\n\n/**\n * Upper bound on a base64 string length that can still fit within `maxBytes`\n * after decoding (4 base64 chars encode 3 bytes, plus up to 2 padding chars).\n * Used as a cheap pre-flight guard to avoid decoding oversized payloads into\n * memory; the exact decoded length is verified after decoding.\n */\nfunction maxEncodedLengthFor(maxBytes: number): number {\n return Math.ceil((maxBytes * 4) / 3) + 4;\n}\n\n/**\n * Reduce an untrusted string to a single safe path segment: no separators, no\n * `..` runs, no leading/trailing dots or dashes. Falls back when nothing\n * usable remains.\n */\nfunction sanitizePathSegment(segment: string, fallback: string): string {\n const cleaned = segment\n .replace(/[^A-Za-z0-9._-]+/g, \"-\")\n .replace(/\\.{2,}/g, \".\")\n .replace(/^[.-]+|[.-]+$/g, \"\");\n return cleaned.length > 0 ? cleaned : fallback;\n}\n\n/**\n * Derive the deterministic storage location for a bytes part from its\n * `dedupeKey` (`<taskId>:<partIndex>`). Retried requests for the same task\n * recompute the same location, so re-ingestion overwrites the same object\n * instead of accumulating duplicates — idempotency no longer depends on the\n * in-memory cache surviving across requests.\n */\nfunction storageLocationFor(\n dedupeKey: string,\n name: string,\n): { path: string; name: string } {\n const separatorIndex = dedupeKey.lastIndexOf(\":\");\n const keyBase = separatorIndex >= 0 ? dedupeKey.slice(0, separatorIndex) : dedupeKey;\n const keyIndex = separatorIndex >= 0 ? dedupeKey.slice(separatorIndex + 1) : \"0\";\n return {\n path: `a2a/${sanitizePathSegment(keyBase, \"task\")}`,\n name: `${sanitizePathSegment(keyIndex, \"0\")}-${sanitizePathSegment(name, \"file\")}`,\n };\n}\n\nfunction extensionOf(name: string): string { return name.includes(\".\")\n ? name.slice(name.lastIndexOf(\".\")).toLowerCase()\n : \"\";\n}\n\nfunction assertAllowedFileType(name: string, mimeType: string | undefined): void {\n if (EXECUTABLE_EXTENSIONS.has(extensionOf(name))) {\n throw new Error(`Refusing to ingest executable file \"${name}\"`);\n }\n if (mimeType && EXECUTABLE_MIME_TYPES.has(mimeType.toLowerCase())) {\n throw new Error(`Refusing to ingest executable file \"${name}\"`);\n }\n}\n\n/**\n * Turns A2A file parts into {@link TaskFileRef} records, ingesting inline\n * `bytes` into workspace storage.\n *\n * URI-backed parts pass through untouched. Bytes-backed parts are validated,\n * base64-decoded, written via the injected `saveProjectFile`, and cached by\n * `dedupeKey` so repeated ingests of the same part do not rewrite storage.\n */\nexport class A2AFileIngestor {\n private readonly saveProjectFile: A2AFileIngestorOptions[\"saveProjectFile\"];\n private readonly maxBytes: number;\n private readonly cache = new Map<string, string>();\n\n constructor(options: A2AFileIngestorOptions) {\n this.saveProjectFile = options.saveProjectFile;\n this.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n }\n\n /**\n * Project a single file part onto a {@link TaskFileRef}, ingesting bytes when\n * present. Idempotent per `dedupeKey`: a repeated key returns the cached URI\n * without re-writing storage, and even across ingestor instances the key\n * maps to a deterministic storage path (`a2a/<taskId>/<partIndex>-<name>`),\n * so request retries overwrite the same object.\n *\n * NOTE: the key is based on `taskId` + part index rather than the internal\n * message id because the executor must ingest files *before* `addMessage`\n * returns a messageId. A client retrying with a different taskId for the\n * same message writes a second copy; that is accepted and documented.\n */\n async ingest(\n part: FilePart,\n dedupeKey: string,\n projectId: string,\n addedBy: \"user\" | \"agent\",\n ): Promise<TaskFileRef> {\n const file = part.file;\n\n if (\"uri\" in file) {\n return {\n uri: file.uri,\n ...(file.name ? { name: file.name } : {}),\n ...(file.mimeType ? { mimeType: file.mimeType } : {}),\n addedBy,\n };\n }\n\n const name = file.name ?? \"file\";\n assertAllowedFileType(name, file.mimeType);\n\n if (file.bytes.length > maxEncodedLengthFor(this.maxBytes)) {\n throw new Error(\n `A2A file part exceeds the ${this.maxBytes} byte ingest limit`,\n );\n }\n\n const bytes = decodeBase64(file.bytes);\n if (bytes.length > this.maxBytes) {\n throw new Error(\n `A2A file part exceeds the ${this.maxBytes} byte ingest limit`,\n );\n }\n\n const cached = this.cache.get(dedupeKey);\n if (cached !== undefined) {\n return {\n uri: cached,\n ...(file.name ? { name: file.name } : {}),\n ...(file.mimeType ? { mimeType: file.mimeType } : {}),\n addedBy,\n };\n }\n\n const location = storageLocationFor(dedupeKey, name);\n const { uri } = await this.saveProjectFile({\n projectId,\n name: location.name,\n path: location.path,\n bytes,\n ...(file.mimeType ? { mimeType: file.mimeType } : {}),\n });\n this.cache.set(dedupeKey, uri);\n\n return {\n uri,\n ...(file.name ? { name: file.name } : {}),\n ...(file.mimeType ? { mimeType: file.mimeType } : {}),\n addedBy,\n };\n }\n}\n","import {\n DefaultExecutionEventBus,\n type ExecutionEventBus,\n type ExecutionEventBusManager,\n} from \"@a2a-js/sdk/server\";\nimport type { A2ATaskStoreAdapterScope } from \"./A2ATaskStoreAdapter\";\n\nconst DEFAULT_MAX_SCOPES = 1_000;\nconst DEFAULT_IDLE_TTL_MS = 15 * 60 * 1_000;\n\n/** Error raised when every bounded runtime scope is currently active. */\nexport class A2ARuntimeCapacityError extends Error {\n constructor(maxScopes: number) {\n super(`A2A runtime scope capacity of ${maxScopes} is exhausted`);\n this.name = \"A2ARuntimeCapacityError\";\n }\n}\n\n/** Configuration for the bounded process-local A2A runtime registry. */\nexport interface A2ARuntimeRegistryOptions {\n maxScopes?: number;\n idleTtlMs?: number;\n now?: () => number;\n}\n\n/**\n * Pins one scoped A2A runtime while a request is using its manager.\n *\n * @remarks Call {@link release} exactly once when request or stream processing\n * finishes. Repeated calls are harmless.\n */\nexport interface A2ARuntimeLease {\n manager: ExecutionEventBusManager;\n release(): void;\n}\n\ninterface RuntimeEntry {\n manager: ScopedExecutionEventBusManager;\n lastAccessedAt: number;\n leaseCount: number;\n}\n\nclass ScopedExecutionEventBusManager implements ExecutionEventBusManager {\n private readonly buses = new Map<string, ExecutionEventBus>();\n private readonly touch: () => void;\n\n constructor(touch: () => void) {\n this.touch = touch;\n }\n\n createOrGetByTaskId(taskId: string): ExecutionEventBus {\n this.touch();\n const existing = this.buses.get(taskId);\n if (existing) return existing;\n\n const bus = new DefaultExecutionEventBus();\n this.buses.set(taskId, bus);\n return bus;\n }\n\n getByTaskId(taskId: string): ExecutionEventBus | undefined {\n this.touch();\n return this.buses.get(taskId);\n }\n\n cleanupByTaskId(taskId: string): void {\n this.touch();\n const bus = this.buses.get(taskId);\n bus?.removeAllListeners();\n this.buses.delete(taskId);\n }\n\n get activeBusCount(): number {\n return this.buses.size;\n }\n\n close(): void {\n for (const bus of this.buses.values()) {\n bus.removeAllListeners();\n }\n this.buses.clear();\n }\n}\n\n/**\n * Owns process-local SDK event bus managers isolated by authorization scope.\n *\n * @remarks Call {@link acquire} for every request and retain its lease until\n * ordinary response completion or complete streaming generator consumption.\n */\nexport class A2ARuntimeRegistry {\n private readonly entries = new Map<string, RuntimeEntry>();\n private readonly maxScopes: number;\n private readonly idleTtlMs: number;\n private readonly now: () => number;\n private closed = false;\n\n constructor(options: A2ARuntimeRegistryOptions = {}) {\n this.maxScopes = options.maxScopes ?? DEFAULT_MAX_SCOPES;\n this.idleTtlMs = options.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;\n this.now = options.now ?? Date.now;\n }\n\n /**\n * Acquire and pin the runtime manager for an authorization scope.\n *\n * @param scope Exact tenant, project, and assistant authorization scope.\n * @returns A lease whose manager is shared only within that scope.\n */\n acquire(scope: A2ATaskStoreAdapterScope): A2ARuntimeLease {\n if (this.closed) throw new Error(\"A2A runtime registry is closed\");\n\n const now = this.now();\n this.pruneExpired(now);\n const key = JSON.stringify([\n scope.tenantId,\n scope.projectId,\n scope.assistantId,\n ]);\n const existing = this.entries.get(key);\n const entry = existing ?? this.createEntry(key, now);\n entry.lastAccessedAt = now;\n entry.leaseCount += 1;\n let released = false;\n return {\n manager: entry.manager,\n release: (): void => {\n if (released) return;\n released = true;\n entry.leaseCount -= 1;\n entry.lastAccessedAt = this.now();\n },\n };\n }\n\n close(): void {\n if (this.closed) return;\n this.closed = true;\n for (const entry of this.entries.values()) {\n entry.manager.close();\n }\n this.entries.clear();\n }\n\n private pruneExpired(now: number): void {\n for (const [key, entry] of this.entries) {\n if (\n !this.isActive(entry) &&\n now - entry.lastAccessedAt > this.idleTtlMs\n ) {\n entry.manager.close();\n this.entries.delete(key);\n }\n }\n }\n\n private makeCapacity(): void {\n if (this.entries.size < this.maxScopes) return;\n\n let oldest: [string, RuntimeEntry] | undefined;\n for (const candidate of this.entries) {\n if (this.isActive(candidate[1])) continue;\n if (!oldest || candidate[1].lastAccessedAt < oldest[1].lastAccessedAt) {\n oldest = candidate;\n }\n }\n\n if (!oldest) throw new A2ARuntimeCapacityError(this.maxScopes);\n oldest[1].manager.close();\n this.entries.delete(oldest[0]);\n }\n\n private createEntry(key: string, now: number): RuntimeEntry {\n this.makeCapacity();\n const entry: RuntimeEntry = {\n lastAccessedAt: now,\n leaseCount: 0,\n manager: new ScopedExecutionEventBusManager(() => {\n entry.lastAccessedAt = this.now();\n }),\n };\n this.entries.set(key, entry);\n return entry;\n }\n\n private is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gBAAQ,IAAI,MAAM,EAAE,IAAI,GAAG,yBAAyB;AACpD,kBAAU,iBAAiB;AAAA,UACzB,MAAM;AAAA,UACN;AAAA,UACA;AAAA,UACA,QAAQ,EAAE,OAAO,UAAU,YAAW,oBAAI,KAAK,GAAE,YAAY,EAAE;AAAA,UAC/D,OAAO;AAAA,QACT,CAAC;AAAA,MACH,UAAE;AACA,cAAM,IAAI,IAAI;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;","names":["uuidv4","DefaultExecutionEventBus","asString","extractText","initialTask","uuidv4","DefaultExecutionEventBus"]}
@@ -1 +1 @@
1
- import{l as C}from"./embed-page-chunk-SSC7ANWV.js";import"./embed-page-chunk-XVUA7UHE.js";import"./embed-page-chunk-MQDYZS3S.js";import"./embed-page-chunk-LOXLXZNP.js";import"./embed-page-chunk-KEL6XU6R.js";import"./embed-page-chunk-AC6X2XRH.js";import"./embed-page-chunk-S4XZPBRM.js";import"./embed-page-chunk-TL2AYM76.js";import{Da as T,jb as B}from"./embed-page-chunk-OBM5EUWZ.js";import{r as P}from"./embed-page-chunk-HMTKPZ5B.js";import{a as I}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{U as c,W as p,oa as D,va as b,xa as l}from"./embed-page-chunk-O4QK5LWZ.js";import{a as U}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as u}from"./embed-page-chunk-6Y3UYJ6Z.js";var e=u(U());var t=u(I()),G={component_key:"workspace_assistants",data:{},message:"Assistants"},N=r=>{let i=r;if(typeof r=="string")try{i=JSON.parse(r)}catch{return{}}return i!==null&&typeof i=="object"&&!Array.isArray(i)?i:{}},H=({data:r})=>{let{assistantId:i,initialTab:F}=r??{},{get:m,put:f,del:A}=P(),y=T(),[g,w]=(0,e.useState)(null),[R,h]=(0,e.useState)([]),[E,v]=(0,e.useState)(!1),[L,S]=(0,e.useState)(null),d=(0,e.useCallback)(()=>{y(G)},[y]),a=(0,e.useCallback)(async()=>{v(!0),S(null);try{let s=(await m("/api/assistants")).data?.records??[];h(s),w(s.find(o=>o.id===i)??null)}catch{S("Failed to load agent")}finally{v(!1)}},[m,i]);(0,e.useEffect)(()=>{i&&a()},[a,i]);let _=(0,e.useCallback)(async(n,s)=>{let o=N(n.graphDefinition),k;try{k=await f(`/api/assistants/${n.id}`,{name:s.name!==void 0?s.name:n.name,description:s.description!==void 0?s.description:n.description,graphDefinition:{...o,...s}})}catch(z){throw l.error("Failed to save agent"),z}if(!k.success)throw l.error("Failed to save agent"),new Error("Failed to save agent");l.success("Saved"),await a()},[f,a]),j=(0,e.useCallback)(n=>{w(s=>s&&s.id===n.id?n:s),h(s=>s.map(o=>o.id===n.id?n:o))},[]),x=(0,e.useCallback)(async n=>{if(!(await A(`/api/assistants/${n}`)).success)throw new Error("Failed to delete agent");l.success("Agent deleted"),d()},[A,d]);return i?g?(0,t.jsx)("div",{style:{height:"100%",overflow:"auto"},children:(0,t.jsx)(B,{children:(0,t.jsx)(C,{assistant:g,allAssistants:R,onBack:d,onDeleted:x,onSave:_,onAssistantUpdated:j,onAgentListInvalidated:()=>void a(),initialTab:F})},g.id)}):E?(0,t.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:(0,t.jsx)(b,{})}):L?(0,t.jsx)("div",{style:{padding:24},children:(0,t.jsx)(c,{type:"error",showIcon:!0,message:"Failed to load agent","data-testid":"detail-error",action:(0,t.jsxs)(D,{children:[(0,t.jsx)(p,{size:"small",onClick:()=>void a(),children:"Retry"}),(0,t.jsx)(p,{size:"small",type:"primary",onClick:d,children:"Back to list"})]})})}):(0,t.jsx)("div",{style:{padding:24},children:(0,t.jsx)(c,{type:"warning",showIcon:!0,message:"Agent not found","data-testid":"detail-not-found",action:(0,t.jsx)(p,{size:"small",type:"primary",onClick:d,children:"Back to list"})})}):(0,t.jsx)("div",{style:{padding:24},children:(0,t.jsx)(c,{type:"warning",showIcon:!0,message:"Missing agent id","data-testid":"detail-missing-id"})})};export{H as AgentDetailSideApp};
1
+ import{l as C}from"./embed-page-chunk-DEDTYRZE.js";import"./embed-page-chunk-HEO7X7LH.js";import"./embed-page-chunk-YCX5YZRP.js";import"./embed-page-chunk-XUXEGF3S.js";import"./embed-page-chunk-KEL6XU6R.js";import"./embed-page-chunk-AC6X2XRH.js";import"./embed-page-chunk-S4XZPBRM.js";import"./embed-page-chunk-JMZ7OODN.js";import{Da as T,jb as B}from"./embed-page-chunk-SPC4BYNU.js";import{r as P}from"./embed-page-chunk-HMTKPZ5B.js";import{a as I}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{U as c,W as p,oa as D,va as b,xa as l}from"./embed-page-chunk-O4QK5LWZ.js";import{a as U}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as u}from"./embed-page-chunk-6Y3UYJ6Z.js";var e=u(U());var t=u(I()),G={component_key:"workspace_assistants",data:{},message:"Assistants"},N=r=>{let i=r;if(typeof r=="string")try{i=JSON.parse(r)}catch{return{}}return i!==null&&typeof i=="object"&&!Array.isArray(i)?i:{}},H=({data:r})=>{let{assistantId:i,initialTab:F}=r??{},{get:m,put:f,del:A}=P(),y=T(),[g,w]=(0,e.useState)(null),[R,h]=(0,e.useState)([]),[E,v]=(0,e.useState)(!1),[L,S]=(0,e.useState)(null),d=(0,e.useCallback)(()=>{y(G)},[y]),a=(0,e.useCallback)(async()=>{v(!0),S(null);try{let s=(await m("/api/assistants")).data?.records??[];h(s),w(s.find(o=>o.id===i)??null)}catch{S("Failed to load agent")}finally{v(!1)}},[m,i]);(0,e.useEffect)(()=>{i&&a()},[a,i]);let _=(0,e.useCallback)(async(n,s)=>{let o=N(n.graphDefinition),k;try{k=await f(`/api/assistants/${n.id}`,{name:s.name!==void 0?s.name:n.name,description:s.description!==void 0?s.description:n.description,graphDefinition:{...o,...s}})}catch(z){throw l.error("Failed to save agent"),z}if(!k.success)throw l.error("Failed to save agent"),new Error("Failed to save agent");l.success("Saved"),await a()},[f,a]),j=(0,e.useCallback)(n=>{w(s=>s&&s.id===n.id?n:s),h(s=>s.map(o=>o.id===n.id?n:o))},[]),x=(0,e.useCallback)(async n=>{if(!(await A(`/api/assistants/${n}`)).success)throw new Error("Failed to delete agent");l.success("Agent deleted"),d()},[A,d]);return i?g?(0,t.jsx)("div",{style:{height:"100%",overflow:"auto"},children:(0,t.jsx)(B,{children:(0,t.jsx)(C,{assistant:g,allAssistants:R,onBack:d,onDeleted:x,onSave:_,onAssistantUpdated:j,onAgentListInvalidated:()=>void a(),initialTab:F})},g.id)}):E?(0,t.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:(0,t.jsx)(b,{})}):L?(0,t.jsx)("div",{style:{padding:24},children:(0,t.jsx)(c,{type:"error",showIcon:!0,message:"Failed to load agent","data-testid":"detail-error",action:(0,t.jsxs)(D,{children:[(0,t.jsx)(p,{size:"small",onClick:()=>void a(),children:"Retry"}),(0,t.jsx)(p,{size:"small",type:"primary",onClick:d,children:"Back to list"})]})})}):(0,t.jsx)("div",{style:{padding:24},children:(0,t.jsx)(c,{type:"warning",showIcon:!0,message:"Agent not found","data-testid":"detail-not-found",action:(0,t.jsx)(p,{size:"small",type:"primary",onClick:d,children:"Back to list"})})}):(0,t.jsx)("div",{style:{padding:24},children:(0,t.jsx)(c,{type:"warning",showIcon:!0,message:"Missing agent id","data-testid":"detail-missing-id"})})};export{H as AgentDetailSideApp};
@@ -0,0 +1,5 @@
1
+ import{a as Re,b as Ne,c as Dt,d as Rt,e as Pt,f as Ft,g as Mt,h as Et,i as Nt,j as Lt,k as Bt,l as Ot}from"./embed-page-chunk-DEDTYRZE.js";import"./embed-page-chunk-HEO7X7LH.js";import{a as Ue}from"./embed-page-chunk-YCX5YZRP.js";import"./embed-page-chunk-XUXEGF3S.js";import"./embed-page-chunk-KEL6XU6R.js";import{b as Ge,e as ze,f as xt,g as wt,h as vt,i as kt,l as St,m as It}from"./embed-page-chunk-AC6X2XRH.js";import{a as ut,b as ft,c as yt,d as ht,e as bt}from"./embed-page-chunk-SV2BM3WO.js";import"./embed-page-chunk-S4XZPBRM.js";import"./embed-page-chunk-JMZ7OODN.js";import{$ as dt,Da as At,G as st,J as it,P as lt,Pa as Ct,Qa as Ve,da as ct,jb as Tt,k as De,oa as pt,va as mt,w as rt,wa as gt}from"./embed-page-chunk-SPC4BYNU.js";import{m as et,r as ye}from"./embed-page-chunk-HMTKPZ5B.js";import{a as M}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{Db as nt,Fa as Qe,Ia as Te,Ja as Xe,La as X,Ua as tt,W as J,_ as Se,aa as Ie,ac as Ee,ea as Me,ka as Ke,la as Ze,ma as Je,mc as at,oa as Ye,ra as R,ta as V,wa as _e,xa as v,ya as fe,yc as ot}from"./embed-page-chunk-O4QK5LWZ.js";import{a as ue}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as x}from"./embed-page-chunk-6Y3UYJ6Z.js";var u=x(ue());var te=x(ue());var Y=x(ue());var $t=x(ue());var ie=x(M()),Kt=60,_t=72,je=(0,$t.memo)(({data:n})=>{let r=Re(n.type),p=Math.min(12+Math.sqrt(n.subAgentCount)*10,48);return(0,ie.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center"},children:[(0,ie.jsx)(ze,{type:"target",position:Ge.Top,style:{left:"50%",top:"50%",transform:"translate(-50%, -50%)",background:"transparent",border:"none",width:0,height:0},isConnectable:!1}),(0,ie.jsx)("div",{title:n.label,style:{width:p,height:p,borderRadius:"50%",background:Ne(r.color),display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontSize:Math.max(10,p*.4),fontWeight:600,cursor:"pointer",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"},children:n.label.charAt(0).toUpperCase()}),(0,ie.jsx)("div",{style:{fontSize:11,maxWidth:120,textAlign:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",marginTop:4},children:n.label}),(0,ie.jsx)(ze,{type:"source",position:Ge.Top,style:{left:"50%",top:"50%",transform:"translate(-50%, -50%)",background:"transparent",border:"none",width:0,height:0},isConnectable:!1})]})});je.displayName="AgentGraphNode";var ee=x(M()),sn=({assistants:n,onNodeClick:r})=>{let[p,l,g]=vt([]),[o,f,k]=kt([]),[d,S]=(0,Y.useState)(null),H=(0,Y.useMemo)(()=>({agent:je}),[]),m=(0,Y.useMemo)(()=>Pt(n),[n]);(0,Y.useEffect)(()=>{let w=m.nodes.map(i=>({id:i.id})),P=m.edges.map(i=>({source:i.source,target:i.target})),N=new Map(m.nodes.map(i=>[i.id,i])),z=ht(w).force("link",yt(P).id(i=>i.id).distance(80)).force("charge",bt().strength(-220)).force("center",ut(0,0)).force("collide",ft(45)).stop();for(let i=0;i<300;i++)z.tick();let F=w.map(i=>({id:i.id,type:"agent",data:N.get(i.id),position:{x:i.x-Kt/2,y:i.y-_t/2}})),s=m.edges.map(i=>({id:`e${i.source}-${i.target}`,source:i.source,target:i.target,style:{stroke:"#1677ff",strokeWidth:2},type:"straight"}));l(F),f(s)},[m,l,f]);let T=(0,Y.useMemo)(()=>d===null?p:p.map(w=>{let P=w.id===d||o.some(N=>N.source===d&&N.target===w.id||N.target===d&&N.source===w.id);return{...w,style:{opacity:P?1:.2,transition:"opacity 0.2s ease"}}}),[p,o,d]),K=(0,Y.useMemo)(()=>d===null?o.map(w=>({...w,style:{stroke:"#1677ff",strokeWidth:1.5,opacity:.25,transition:"opacity 0.2s ease"}})):o.map(w=>{let P=w.source===d||w.target===d;return{...w,style:{stroke:"#1677ff",strokeWidth:P?2.5:1,opacity:P?1:.04,transition:"opacity 0.2s ease"}}}),[o,d]);return(0,ee.jsx)("div",{style:{width:"100%",height:"100%",background:"#fafafa",position:"relative"},children:(0,ee.jsxs)(wt,{nodes:T,edges:K,onNodesChange:g,onEdgesChange:k,onNodeMouseEnter:(w,P)=>S(P.id),onNodeMouseLeave:()=>S(null),onNodeClick:(w,P)=>r?.(String(P.id)),nodeTypes:H,fitView:!0,fitViewOptions:{padding:.25},children:[(0,ee.jsx)(St,{color:"#eee",gap:20}),(0,ee.jsx)(It,{})]})})},Vt=n=>(0,ee.jsx)(xt,{children:(0,ee.jsx)(sn,{...n})});var E=x(M()),ln=n=>{if(!n)return"\u2014";let r=Date.now()-new Date(n).getTime(),p=Math.floor(r/6e4);if(p<1)return"just now";if(p<60)return`${p}m ago`;let l=Math.floor(p/60);return l<24?`${l}h ago`:`${Math.floor(l/24)}d ago`},dn=n=>n===null?"#d9d9d9":n>=80?"#22c55e":n>=50?"#f59e0b":"#ef4444",cn=mt(({css:n})=>({row:n`
2
+ display: flex;
3
+ justify-content: space-between;
4
+ align-items: flex-end;
5
+ `})),Gt={fontSize:16,fontWeight:700,lineHeight:1.2,cursor:"help"},He={fontSize:10,color:"rgba(0, 0, 0, 0.45)",whiteSpace:"nowrap",marginTop:1},We={display:"flex",flexDirection:"column",alignItems:"center"},zt=({stats:n})=>{let{styles:r}=cn();if(!n)return(0,E.jsxs)("div",{style:{display:"flex",fontSize:11,color:"#d9d9d9"},children:[(0,E.jsx)("span",{style:{flex:1},children:"score \u2014"}),(0,E.jsx)("span",{style:{flex:1},children:"threads \u2014"})]});let p=n.evalScore!==null?Number(n.evalScore).toFixed(1):"\u2014",l=n.threadCount>0?n.threadCount:"\u2014",g=dn(n.evalScore),o=n.evalPassRate!==null?`${n.evalPassRate}%`:"\u2014";return(0,E.jsxs)("div",{className:r.row,children:[(0,E.jsxs)("div",{style:{display:"flex",gap:16,alignItems:"flex-end"},children:[(0,E.jsx)(Ie,{title:`Eval score: ${p} \xB7 pass rate ${o} \xB7 ${n.evalRuns} runs`,children:(0,E.jsxs)("div",{style:We,children:[(0,E.jsx)("span",{style:{...Gt,color:g},children:p}),(0,E.jsx)("span",{className:"lattice-stat-label",style:He,children:"eval score"})]})}),(0,E.jsx)(Ie,{title:`Conversations: ${n.threadCount} total \xB7 ${n.last7d} in 7d \xB7 ${n.last30d} in 30d${n.lastActive?` \xB7 last active ${ln(n.lastActive)}`:""}`,children:(0,E.jsxs)("div",{style:We,children:[(0,E.jsx)("span",{style:{...Gt,color:l==="\u2014"?"#d9d9d9":"#595959"},children:l}),(0,E.jsx)("span",{className:"lattice-stat-label",style:He,children:"threads"})]})})]}),n.daily7d.length>0&&(0,E.jsxs)("div",{style:We,children:[(0,E.jsx)(Ft,{values:n.daily7d,width:40,height:24,color:"#8c8c8c"}),(0,E.jsx)("span",{className:"lattice-stat-label",style:He,children:"7d threads"})]})]})};var C=x(M()),pn=[{key:"all",label:"All"},{key:"capability",label:"Capability"},{key:"orchestrator",label:"Orchestrator"},{key:"team",label:"Team"},{key:"workflow",label:"Workflow"}],Ut=({items:n,assistants:r=[],stats:p,loading:l,onItemClick:g,onOpenPlayground:o,onOpenEval:f,onCreate:k,onDelete:d})=>{let[S,H]=(0,te.useState)("all"),[m,T]=(0,te.useState)(null),[K,w]=(0,te.useState)(null),P=(0,te.useMemo)(()=>{let s=new Set;return n.forEach(i=>i.tags.forEach(ae=>s.add(ae))),Array.from(s).map(i=>({value:i,label:i}))},[n]),N=(0,te.useMemo)(()=>n.filter(s=>!(S!=="all"&&s.type!==S||m&&!s.tags.includes(m)||K&&s.status!==K)),[n,S,m,K]),z=[{key:"edit",icon:ct,label:"Edit",onClick:s=>g(s.id)},{key:"playground",icon:rt,label:"Playground",onClick:s=>o(s.id)},{key:"eval",icon:it,label:"Eval",onClick:s=>f(s.id)}];d&&z.push({key:"delete",icon:pt,label:"Delete",danger:!0,onClick:s=>d(s.id)});let F=(0,te.useMemo)(()=>[{mode:"graph",icon:dt,label:"Graph",render:()=>(0,C.jsx)(Vt,{assistants:r,onNodeClick:g})}],[r,g]);return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)("span",{"data-testid":"agent-list-state","data-loading":String(l),"data-count":N.length,hidden:!0,"aria-hidden":"true"}),(0,C.jsx)(Ct,{title:"Agents",itemName:"agent",items:N,loading:l,keyExtractor:s=>s.id,tabs:pn,activeTab:S,onTabChange:s=>H(s),headerLeft:(0,C.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[(0,C.jsx)(Ve,{value:m,onChange:T,options:P,placeholder:"Domain",allLabel:"All domains"}),(0,C.jsx)(Ve,{value:K,onChange:w,options:[{value:"enabled",label:"Enabled"},{value:"draft",label:"Draft"},{value:"disabled",label:"Disabled"}],placeholder:"Status",allLabel:"All statuses"})]}),renderIcon:s=>{let i=Ne(Re(s.type).color);return(0,C.jsx)("div",{title:`${s.type} agent`,style:{width:32,height:32,borderRadius:8,background:`${i}1A`,color:i,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,C.jsx)(De,{size:18})})},renderPrimary:s=>(0,C.jsx)("span",{"data-testid":"agent-name","data-agent-id":s.id,children:s.name}),renderSecondary:s=>s.description||void 0,renderDetails:s=>(0,C.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,C.jsxs)("div",{style:{display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},children:[s.tags.map(i=>(0,C.jsx)(Te,{color:"magenta",style:{margin:0,borderRadius:10,border:"none"},children:i},i)),(0,C.jsx)(Te,{color:Re(s.type).color,style:{margin:0,borderRadius:10,border:"none"},children:s.type})]}),(0,C.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexShrink:0},children:[(0,C.jsx)(Ie,{title:`Status: ${s.status}`,children:(0,C.jsx)("span",{style:{width:8,height:8,borderRadius:"50%",background:Dt(s.status),display:"inline-block",cursor:"help"}})}),(0,C.jsx)("span",{style:{fontSize:12,color:"#8c8c8c"},children:s.version})]})]}),renderFooter:s=>(0,C.jsx)("div",{style:{borderTop:"1px dashed #f0f0f0",paddingTop:10},children:(0,C.jsx)(zt,{stats:p?.[s.id]})}),itemActions:z,actionsStyle:"icon",actionsPosition:"hover",onItemClick:s=>g(s.id),createLabel:"New Agent",onCreateClick:k,viewModeExtensions:F,emptyIcon:(0,C.jsx)(De,{size:48,style:{opacity:.5}}),emptyTitle:"No agents yet",emptyDescription:'Click "New Agent" to create one'})]})};var b=x(ue());var le=x(ue());var he=x(M()),{Text:mn}=X,jt=({onSelect:n,value:r,placeholder:p="Select a parent agent to extend..."})=>{let[l,g]=(0,le.useState)([]),[o,f]=(0,le.useState)(!1),{get:k}=ye(),d=(0,le.useCallback)(async()=>{f(!0);try{let m=await k("/api/assistants");m.success&&g(m.data?.records||[])}catch(m){console.error("Failed to fetch assistants:",m)}finally{f(!1)}},[k]);return(0,le.useEffect)(()=>{d()},[d]),(0,he.jsx)(Se,{showSearch:!0,allowClear:!0,value:r,placeholder:p,loading:o,onChange:m=>{if(!m){n(null);return}let T=l.find(K=>K.id===m);n(T||null)},onDropdownVisibleChange:m=>{m&&d()},optionFilterProp:"label",style:{width:"100%"},options:l.map(m=>({value:m.id,label:m.name||m.id,description:m.description})),optionRender:m=>(0,he.jsxs)("div",{children:[(0,he.jsx)("div",{children:m.label}),m.data.description&&(0,he.jsx)(mn,{type:"secondary",style:{fontSize:12},children:m.data.description})]})})};var O=x(M()),{Text:Ht}=X,Wt=({subAgentKeys:n,decisions:r,onChange:p})=>{let{token:l}=Xe.useToken(),g=(f,k)=>{let d=r.map(S=>S.originalKey===f?{...S,clone:k,cloneKey:k?`${f}_clone`:void 0}:S);p(d)},o=(f,k)=>{let d=r.map(S=>S.originalKey===f?{...S,cloneKey:k}:S);p(d)};return n.length===0?null:(0,O.jsxs)("div",{children:[(0,O.jsx)(Ht,{type:"secondary",style:{display:"block",marginBottom:8},children:"Choose how to handle each sub-agent from the parent:"}),(0,O.jsx)(_e,{size:"small",bordered:!0,dataSource:r,style:{borderRadius:l.borderRadius},renderItem:f=>(0,O.jsxs)(_e.Item,{style:{display:"flex",flexDirection:"column",alignItems:"stretch",gap:8,padding:"8px 16px"},children:[(0,O.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,O.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[f.clone?(0,O.jsx)(Ee,{style:{color:l.colorPrimary}}):(0,O.jsx)(at,{style:{color:l.colorTextSecondary}}),(0,O.jsx)(Ht,{style:{fontFamily:"monospace"},children:f.originalKey})]}),(0,O.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,O.jsx)(Te,{color:f.clone?"blue":"default",children:f.clone?"Clone as new":"Reuse"}),(0,O.jsx)(Qe,{size:"small",checked:f.clone,onChange:k=>g(f.originalKey,k)})]})]}),f.clone&&(0,O.jsx)(V,{size:"small",placeholder:"Enter key for the cloned agent",value:f.cloneKey,onChange:k=>o(f.originalKey,k.target.value),style:{fontFamily:"monospace",fontSize:12},addonBefore:"Key"})]})})]})};function qt(n){return n.mode!=="local"||n.templateKey||typeof n.executable=="string"&&n.executable.trim().length>0?null:"Choose a template or enter a custom executable"}var t=x(M()),{TextArea:Zt}=V,{Text:ne}=X,Jt="/.well-known/agent-card.json",gn=[{value:"http://",label:"http://"},{value:"https://",label:"https://"}],Yt={react:"Executor: Directly executes tasks using tools. Best for single-step operations like search, code execution, and data retrieval.",deep_agent:"Orchestrator: Manages a sequential todo list to plan and assign todo items to sub-agents. Best for structured multi-step workflows.",team:"Team: Creates tasks with dependencies and dynamically spawns teammates. Like a swarm, teammates communicate via mailbox. Best for tasks requiring exploration and divergent thinking.",processing:"Workflow: Enforces a fixed workflow topology by delegating to sub-agents in a predefined order. Best for deterministic multi-step processes with validated delegation paths.",a2a_remote:"A2A Remote: Delegates to an external A2A-compatible agent server. Use for local CLI tools (Claude Code, Codex, OpenCode) or remote agents."};function Qt(n,r,p="https://"){let l=String(n??"").trim();if(!l)return"";let g=r==="http://"||r==="https://"?r:p,f=(/^https?:\/\//i.test(l)?l:`${g}${l.replace(/^\/+/,"")}`).replace(/\/+$/,"");return f.endsWith(Jt)?f:`${f}${Jt}`}function un(n){try{return new URL(n).port||void 0}catch{return}}function fn(n){return n.some(r=>r==="--port"||r==="-p"||/^--port=/.test(r)||/^-p=/.test(r))}function Xt(n,r){let p=[...n.args],l=un(r);return l&&!fn(p)&&p.push("--port",l),{...n,args:p,...n.env?{env:{...n.env}}:{}}}var en=({open:n,onCancel:r,onSuccess:p,initialMode:l,initialValues:g})=>{let[o]=R.useForm(),[f,k]=(0,b.useState)(!1),[d,S]=(0,b.useState)("learn"),[H,m]=(0,b.useState)(""),[T,K]=(0,b.useState)(null),[w,P]=(0,b.useState)([]),N=R.useWatch("type",o)||"react",z=N==="a2a_remote",[F,s]=(0,b.useState)("remote"),[i,ae]=(0,b.useState)(void 0),[de,be]=(0,b.useState)([]),[ce,pe]=(0,b.useState)(!1),q=(0,b.useRef)(0),[Le,Ae]=(0,b.useState)(!1),[Be,oe]=(0,b.useState)(!1),{get:Z,post:W,put:Oe}=ye(),Pe=et("agent-architect"),{workspaceId:_,trainingProjects:me,loading:Q}=gt(),[$e,ge]=(0,b.useState)(null),Ce=JSON.stringify(g??null),L=me.find(e=>e.id===$e)??me[0]??null,[xe,we]=(0,b.useState)([]),Fe=(0,b.useCallback)(()=>{K(null),P([])},[]),re=(0,b.useCallback)(()=>{o.resetFields(),Fe(),S("learn"),m(""),we([]),ge(null),s("remote"),ae(void 0),be([]),oe(!1),Ae(!1)},[o,Fe]);(0,b.useEffect)(()=>{if(n){re(),S(l??"learn");let e=g?.a2aMode;(e==="remote"||e==="local")&&s(e),o.setFieldsValue({type:"react",agentCardProtocol:"https://",a2aMode:"remote",timeout:3e5,...g})}},[n,o,l,Ce,re]),(0,b.useEffect)(()=>{let e=++q.current,a=!0;return n&&z?(o.setFieldValue("prompt",""),F==="local"?(pe(!0),Z("/api/local-a2a/templates").then(A=>{a&&e===q.current&&A?.data?.records&&be(A.data.records)}).catch(()=>{a&&e===q.current&&be([])}).finally(()=>{a&&e===q.current&&pe(!1)})):pe(!1)):pe(!1),()=>{a=!1,q.current+=1}},[o,z,F,Z,n]);let se=de.find(e=>e.key===i),ve=(0,b.useCallback)(()=>{let e=qt({mode:F,templateKey:i,executable:o.getFieldValue("commandExecutable")});return e?(oe(!0),o.setFields([{name:"commandExecutable",errors:[e]}]),v.warning(e),!1):!0},[F,i,o]);(0,b.useEffect)(()=>{se&&o.setFieldsValue({agentCardProtocol:"http://"})},[o,se]);let c=(0,b.useCallback)(async()=>{if(!ve())return;let e=Qt(o.getFieldValue("agentCardUrl"),o.getFieldValue("agentCardProtocol"),F==="local"?"http://":"https://");if(!e){v.warning("Please enter an A2A server URL first");return}Ae(!0);try{let a={agentCardUrl:e,apiKey:o.getFieldValue("apiKey")};if(F==="local"){let y=se;if(y)a.localRuntime={label:o.getFieldValue("name")||void 0,agentCardUrl:e,command:Xt(y.command,e)};else{let B=o.getFieldValue("commandArgs")||"",j=B?B.split(/\s+/).filter(Boolean):[],D=String(o.getFieldValue(["command","cwd"])||"").trim();a.localRuntime={label:o.getFieldValue("name")||void 0,agentCardUrl:e,command:{executable:String(o.getFieldValue("commandExecutable")||"").trim(),args:j,...D?{cwd:D}:{}}}}}let A=await W("/api/a2a/test-connection",a);if(A.data?.reachable){let y=A.data.agentCard;v.success(`Connected to "${A.data.agentName||e}"`)}else v.error(A.data?.error||"Connection failed")}catch{v.error("Connection test failed")}finally{Ae(!1)}},[o,W,F,se,ve]),h=(0,b.useCallback)(e=>{if(K(e),!e){o.resetFields(["key","name","description","type","prompt"]),P([]);return}let a=typeof e.graphDefinition=="object"&&e.graphDefinition!==null?e.graphDefinition:{},A=a.key||e.id,y=e.name||a.name||"";o.setFieldsValue({key:`${A}_ext`,name:y?`${y} (Extended)`:"",description:e.description||a.description||"",type:a.type||"react",prompt:a.prompt||""});let B=a.subAgents||[];P(B.map(j=>({originalKey:j,clone:!1})))},[o]),I=async(e,a)=>{let A=await Z(`/api/assistants/${e}`);if(!A.success)throw new Error(`Failed to fetch sub-agent "${e}" for cloning`);let y=A.data,B=typeof y.graphDefinition=="object"?y.graphDefinition:{},j={id:a,name:`${y.name} (Clone)`,description:y.description||"",graphDefinition:{...B,key:a,name:`${y.name} (Clone)`}},D=await W("/api/assistants",j);if(!D.success)throw new Error(D.message||`Failed to clone sub-agent "${e}"`);return D.data},U=e=>{let a={id:e.key,name:e.name,description:e.description||"",graphDefinition:{key:e.key,name:e.name,description:e.description||"",type:e.type,prompt:e.prompt||"",tools:[],skills:[],subAgents:e.type==="deep_agent"||e.type==="processing"?[]:void 0,middleware:[]}};if(e.type==="a2a_remote"&&(a.graphDefinition.agentCardUrl=Qt(e.agentCardUrl,e.agentCardProtocol,(e.a2aMode||F)==="local"?"http://":"https://"),e.apiKey&&(a.graphDefinition.apiKey=e.apiKey),e.timeout&&(a.graphDefinition.timeout=e.timeout),(e.a2aMode||F)==="local")){let A=se;if(A)a.graphDefinition.localRuntime={label:e.name||void 0,agentCardUrl:a.graphDefinition.agentCardUrl,command:Xt(A.command,a.graphDefinition.agentCardUrl)};else{let y=e.commandArgs||"",B=y?y.split(/\s+/).filter(Boolean):[],j=String(e.command?.cwd||"").trim();a.graphDefinition.localRuntime={label:e.name||void 0,agentCardUrl:a.graphDefinition.agentCardUrl,command:{executable:String(e.commandExecutable||"").trim(),args:B,...j?{cwd:j}:{}}}}}return a},ke=async(e,a)=>{if(!T)throw new Error("No parent agent selected");let A=w.filter(D=>D.clone);for(let D of A){if(!D.cloneKey||!D.cloneKey.trim())throw new Error(`Please provide a key for the cloned sub-agent "${D.originalKey}"`);if(!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(D.cloneKey))throw new Error(`Invalid key "${D.cloneKey}" for cloned sub-agent "${D.originalKey}". Key must start with a letter and contain only letters, numbers, underscores, or hyphens.`)}let y=[];for(let D of w)if(D.clone){let rn=await I(D.originalKey,D.cloneKey);a.push(rn),y.push(D.cloneKey)}else y.push(D.originalKey);let B=typeof T.graphDefinition=="object"?T.graphDefinition:{},j={key:e.key,name:e.name,description:e.description||"",extendsAgent:T.id,type:e.type||B.type};return e.prompt&&e.prompt!==B.prompt&&(j.prompt=e.prompt),(y.length>0||B.subAgents&&B.subAgents.length>0)&&(j.subAgents=y),{id:e.key,name:e.name,description:e.description||"",graphDefinition:j}},an=async()=>{if(d==="learn"){let e=H.trim();if(!e){v.error("Please describe the training goal");return}if(!L){v.error("No shared training project available");return}k(!0);try{let a=`agent-${Et(e+Date.now())}`,A=await W("/api/assistants",{id:a,name:a,graphDefinition:{key:a,name:a,description:"",type:"react",prompt:"To be trained",metadata:{trainingProjectId:L.id,learningPlaceholder:"true",architectureStatus:"undecided"}}});if(!A.data)throw new Error("Failed to create agent");let{roundTaskId:y}=await Lt({goal:e,targetAgentId:a,workspaceId:_??void 0,projectId:L.id,existingThreadId:Nt(Pe.tenantId,a),files:xe,post:W,put:Oe});v.success("Agent created \u2014 architect started building"),m(""),we([]),S("learn"),p?.(A.data,{initialMessage:Bt({goal:e,roundTaskId:y,targetAgentId:a,targetMode:"placeholder",files:xe,projectId:L.id,workspaceId:L.workspaceId??_??void 0}),projectId:L.id,initialMessageCustomRunConfig:{execution:{taskId:y}}}),r()}catch(a){v.error(a instanceof Error?a.message:"Failed to create agent")}finally{k(!1)}return}try{if(d==="scratch"&&z&&!ve())return;let e=await o.validateFields();k(!0);let a=[],A=d==="scratch"?U(e):await ke(e,a),y=await W("/api/assistants",A);if(y.success){v.success(d==="extend"?`Assistant created by extending "${T?.name}"`:"Assistant created successfully"),re();for(let B of a)p?.(B);p?.(y.data),r()}else v.error(y.message||"Failed to create assistant")}catch(e){if(e?.errorFields){let a={key:"Key (ID)",name:"Name",description:"Description",prompt:"System Prompt"},A=e.errorFields.map(y=>a[String((y.name??[])[0])]??String((y.name??[])[0])).filter(Boolean);v.warning(A.length>0?`Please complete the required fields: ${[...new Set(A)].join(", ")}`:"Please complete the required fields");return}v.error(e.message||"An error occurred while creating the assistant")}finally{k(!1)}},qe=T?.graphDefinition?.subAgents||[],on=d==="extend"&&T&&qe.length>0;return(0,t.jsxs)(fe,{title:"Create New Assistant",open:n,onCancel:()=>{re(),r()},footer:[(0,t.jsx)(J,{onClick:()=>{re(),r()},children:"Cancel"},"cancel"),(0,t.jsx)(J,{type:"primary",icon:d==="extend"?(0,t.jsx)(Ee,{}):d==="learn"?(0,t.jsx)(nt,{}):(0,t.jsx)(ot,{}),loading:f,disabled:d==="learn"&&(Q||!L),onClick:an,children:d==="extend"?"Create (Extend)":d==="learn"?"Start Learning":"Create"},"submit")],width:760,children:[d==="extend"&&(0,t.jsxs)("div",{style:{marginBottom:20},children:[(0,t.jsx)(ne,{type:"secondary",style:{display:"block",marginBottom:8},children:"Parent Agent"}),(0,t.jsx)(jt,{value:T?.id,onSelect:h}),T&&(0,t.jsx)(ne,{type:"secondary",style:{display:"block",marginTop:4,fontSize:12},children:"Fields left unchanged will be inherited from the parent agent."})]}),d==="extend"&&T&&(0,t.jsx)(Ke,{style:{margin:"12px 0"}}),d==="learn"&&(0,t.jsxs)("div",{children:[(0,t.jsx)(ne,{style:{display:"block",marginBottom:8},children:"Describe what the agent should do."}),(0,t.jsx)(V.TextArea,{rows:3,value:H,onChange:e=>m(e.target.value),placeholder:"e.g. Handle price disputes using the price protection policy"}),L&&(0,t.jsxs)("div",{style:{marginTop:12},children:[(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginBottom:8},children:[(0,t.jsx)(ne,{type:"secondary",children:"Reference Files"}),(0,t.jsx)(Ue,{project:L,projects:me,value:L?.id??null,onChange:ge,loading:Q})]}),(0,t.jsx)(Mt,{projectId:L.id,value:xe,onChange:we}),(0,t.jsx)(ne,{type:"secondary",style:{display:"block",marginTop:6,fontSize:12},children:"Optional \u2014 uploaded to the shared training workspace and attached to the learning round; the architect reads them as round material."})]}),!L&&!Q&&(0,t.jsx)("div",{style:{marginTop:12},children:(0,t.jsx)(Ue,{project:L,projects:me,value:null,onChange:ge,loading:Q})})]}),d!=="learn"&&(0,t.jsxs)(R,{form:o,layout:"vertical",autoComplete:"off",initialValues:{type:"react",agentCardProtocol:"https://",a2aMode:"remote"},children:[(0,t.jsx)(R.Item,{name:"key",label:"Key (ID)",rules:[{required:!0,message:"Please enter a unique key"},{pattern:/^[a-zA-Z][a-zA-Z0-9_-]*$/,message:"Key must start with a letter and contain only letters, numbers, underscores, or hyphens"}],style:{marginBottom:16},children:(0,t.jsx)(V,{placeholder:"e.g., my_assistant"})}),(0,t.jsx)(R.Item,{name:"name",label:"Name",rules:[{required:!0,message:"Please enter a name"}],style:{marginBottom:16},children:(0,t.jsx)(V,{placeholder:"e.g., My Assistant"})}),(0,t.jsx)(R.Item,{name:"description",label:"Description",rules:[{required:!0,message:"Please enter a description"}],style:{marginBottom:16},children:(0,t.jsx)(Zt,{placeholder:"Enter a description for this assistant...",autoSize:{minRows:2,maxRows:4}})}),(0,t.jsx)(R.Item,{name:"type",label:"Agent Type",rules:[{required:!0}],style:{marginBottom:16},children:(0,t.jsx)(Ze,{options:[{value:"react",label:"Executor"},{value:"deep_agent",label:"Orchestrator"},{value:"team",label:"Team"},{value:"processing",label:"Workflow"},{value:"a2a_remote",label:"A2A Remote"}],block:!0})}),(0,t.jsx)(ne,{type:"secondary",style:{fontSize:12,display:"block",marginTop:-12,marginBottom:16,lineHeight:1.5},children:Yt[N]||Yt.react}),z&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(R.Item,{label:"Connection Mode",style:{marginBottom:16},children:(0,t.jsxs)(Me.Group,{value:F,onChange:e=>{let a=e.target.value;s(a),o.setFieldValue("a2aMode",a),a==="local"&&o.setFieldValue("agentCardProtocol","http://"),ae(void 0)},optionType:"button",buttonStyle:"solid",children:[(0,t.jsx)(Me.Button,{value:"remote",children:"Remote URL"}),(0,t.jsx)(Me.Button,{value:"local",children:"Local Managed"})]})}),(0,t.jsx)(R.Item,{name:"a2aMode",noStyle:!0,hidden:!0,children:(0,t.jsx)(V,{})}),F==="local"&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(R.Item,{label:"Template",style:{marginBottom:16},children:(0,t.jsx)(Se,{placeholder:"Choose a template...",allowClear:!0,loading:ce,value:i,onChange:e=>{ae(e),e&&oe(!1)},options:de.map(e=>({value:e.key,label:e.name||e.key})),notFoundContent:ce?void 0:(0,t.jsx)(ne,{type:"secondary",style:{padding:8,display:"block"},children:'No templates. Use "Custom Command" below.'})})}),!i&&(0,t.jsx)(t.Fragment,{children:Be?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(R.Item,{name:"commandExecutable",label:"Executable",rules:[{required:!0,whitespace:!0,message:"Executable is required"}],style:{marginBottom:16},children:(0,t.jsx)(V,{placeholder:"e.g. node, opencode, /usr/local/bin/my-server"})}),(0,t.jsx)(R.Item,{name:"commandArgs",label:"Arguments",style:{marginBottom:16},children:(0,t.jsx)(V,{placeholder:"e.g. --serve --port 4301"})}),(0,t.jsx)(R.Item,{name:["command","cwd"],label:"Working directory",style:{marginBottom:16},children:(0,t.jsx)(V,{placeholder:"e.g. /Users/me/project"})}),(0,t.jsx)(J,{type:"link",onClick:()=>{oe(!1),o.setFieldsValue({commandExecutable:"",commandArgs:"",command:{cwd:void 0}})},style:{padding:0,marginBottom:16,display:"block"},children:"- Hide Custom Command"})]}):(0,t.jsx)(J,{type:"link",onClick:()=>oe(!0),style:{padding:0,marginBottom:16,display:"block"},children:"+ Custom Command"})})]}),(0,t.jsx)(R.Item,{label:"Agent Card URL",required:!0,style:{marginBottom:16},children:(0,t.jsxs)(Ye.Compact,{style:{width:"100%"},children:[(0,t.jsx)(R.Item,{name:"agentCardProtocol",noStyle:!0,children:(0,t.jsx)(Se,{style:{width:100},options:gn})}),(0,t.jsx)(R.Item,{name:"agentCardUrl",noStyle:!0,rules:[{required:!0,message:"Please enter the A2A server URL"}],children:(0,t.jsx)(V,{placeholder:F==="local"?"localhost:4301":"host:port or full URL"})}),(0,t.jsx)(J,{icon:(0,t.jsx)(tt,{}),onClick:c,loading:Le,children:"Test"})]})}),F==="remote"&&(0,t.jsx)(R.Item,{name:"apiKey",label:"API Key (optional)",style:{marginBottom:16},children:(0,t.jsx)(V.Password,{placeholder:"API key for authentication"})}),(0,t.jsx)(R.Item,{name:"timeout",label:"Timeout (ms)",style:{marginBottom:16},initialValue:3e5,children:(0,t.jsx)(Je,{min:1e3,max:36e5,style:{width:"100%"},placeholder:"300000"})})]}),!z&&(0,t.jsx)(R.Item,{name:"prompt",label:d==="extend"&&T?"System Prompt (leave unchanged to inherit from parent)":"System Prompt",rules:d==="scratch"?[{required:!0,message:"Please enter a system prompt"}]:[],children:(0,t.jsx)(Zt,{placeholder:d==="extend"&&T?"Leave empty to inherit parent's prompt, or enter a new prompt to override...":"Enter the system prompt for this agent...",autoSize:{minRows:4,maxRows:8},style:{fontFamily:"monospace",fontSize:13,lineHeight:1.6}})})]}),on&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(Ke,{style:{margin:"12px 0"}}),(0,t.jsx)(ne,{strong:!0,style:{display:"block",marginBottom:8},children:"Sub-Agents"}),(0,t.jsx)(Wt,{subAgentKeys:qe,decisions:w,onChange:P})]})]})};var $=x(M()),{Paragraph:yn,Text:tn}=X,hn=[{key:"manual",icon:De,title:"Manual Configuration",description:"Define the agent's identity, type, tools, and system prompt yourself."},{key:"external",icon:st,title:"External Agent",description:"Connect an existing A2A-compatible agent by URL or manage a local runtime."},{key:"learn",icon:lt,title:"Learn with Agent Architect",description:"Describe the goal and let Agent Architect build and evaluate the agent with training context."}],nn=({open:n,onCancel:r,onSelectMethod:p,focusTriggerAfterClose:l=!0})=>(0,$.jsx)(fe,{title:"Choose how to create your agent",open:n,onCancel:r,footer:null,width:560,centered:!0,destroyOnHidden:!0,focusTriggerAfterClose:l,children:(0,$.jsxs)("div",{style:{padding:"8px 4px 4px"},children:[(0,$.jsx)(yn,{style:{color:"#595959",fontSize:15,margin:"8px 0 24px"},children:"Choose the path that best fits the agent you want to build."}),(0,$.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:hn.map(g=>{let o=g.icon;return(0,$.jsxs)(J,{type:"default",onClick:()=>p(g.key),"aria-label":g.title,style:{display:"flex",flexDirection:"row",alignItems:"center",gap:16,width:"100%",minHeight:88,height:"auto",padding:16,borderRadius:16,textAlign:"left",whiteSpace:"normal"},children:[(0,$.jsx)("div",{style:{width:40,height:40,borderRadius:12,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"#6366f1",background:"#eeeeff"},children:(0,$.jsx)(o,{size:19})}),(0,$.jsxs)("div",{style:{minWidth:0},children:[(0,$.jsx)(tn,{strong:!0,style:{display:"block",fontSize:15,marginBottom:3},children:g.title}),(0,$.jsx)(tn,{style:{color:"#737373",lineHeight:1.5},children:g.description})]})]},g.key)})}),(0,$.jsx)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,flexWrap:"wrap",marginTop:24},children:(0,$.jsx)(J,{onClick:r,children:"Not now"})})]})});var G=x(M()),bn=n=>{let r=n;if(typeof n=="string")try{r=JSON.parse(n)}catch{return{}}return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:{}},Da=()=>{let{get:n,del:r,put:p}=ye(),[l,g]=(0,u.useState)([]),[o,f]=(0,u.useState)({}),[k,d]=(0,u.useState)(null),[S,H]=(0,u.useState)(!1),[m,T]=(0,u.useState)(null),[K,w]=(0,u.useState)("graph"),[P,N]=(0,u.useState)(null),[z,F]=(0,u.useState)(null),[s,i]=(0,u.useState)(null),[ae,de]=(0,u.useState)(!1),[be,ce]=(0,u.useState)(!0),[pe,q]=(0,u.useState)(!1),[Le,Ae]=(0,u.useState)("learn"),[Be,oe]=(0,u.useState)({}),[Z,W]=(0,u.useState)(null),[Oe,Pe]=(0,u.useState)(!1),_=(0,u.useCallback)(async()=>{H(!0);try{let[c,h]=await Promise.all([n("/api/assistants"),n("/api/assistants/stats").catch(()=>null)]);if(c.success&&c.data?.records&&g(c.data.records),h?.success&&h.data?.records){let I={};for(let U of h.data.records)I[U.id]=U;f(I),d(h.cache?.expiresAt??null)}}catch{v.error("Failed to load agents")}finally{H(!1)}},[n]);(0,u.useEffect)(()=>{_()},[_]);let me=u.default.useMemo(()=>Rt(l),[l]),Q=l.find(c=>c.id===m)??null,$e=(0,u.useCallback)((c,h="graph")=>{T(c),w(h),N(null),i(null)},[]),ge=At(),Ce=(0,u.useCallback)((c,h)=>{let I=l.find(U=>U.id===c)?.name??"Agent";ge({component_key:"agent_detail_side_app",data:{assistantId:c,initialTab:h},message:I})},[l,ge]),L=(0,u.useCallback)(()=>{ce(!0),de(!0)},[]),xe=(0,u.useCallback)(c=>{let I={manual:{mode:"scratch",values:{}},external:{mode:"scratch",values:{type:"a2a_remote"}},learn:{mode:"learn",values:{}}}[c];Ae(I.mode),oe(I.values),ce(!1),de(!1),q(!0)},[]),we=(0,u.useCallback)(async(c,h)=>{let I=bn(c.graphDefinition),U;try{U=await p(`/api/assistants/${c.id}`,{name:h.name!==void 0?h.name:c.name,description:h.description!==void 0?h.description:c.description,graphDefinition:{...I,...h}})}catch(ke){throw v.error("Failed to save agent"),ke}if(!U.success)throw v.error("Failed to save agent"),new Error("Failed to save agent");v.success("Saved"),_()},[p,_]),Fe=(0,u.useCallback)(c=>{g(h=>h.map(I=>I.id===c.id?c:I))},[]),re=(0,u.useCallback)(c=>{W(c)},[]),se=(0,u.useCallback)(async()=>{if(Z){Pe(!0);try{(await r(`/api/assistants/${Z}`)).success?(v.success("Agent deleted"),g(h=>h.filter(I=>I.id!==Z)),_(),W(null)):v.error("Failed to delete agent")}catch{v.error("Failed to delete agent")}finally{Pe(!1)}}},[Z,r,_]),ve=(0,u.useCallback)(async c=>{if(!(await r(`/api/assistants/${c}`)).success)throw new Error("Failed to delete agent");v.success("Agent deleted"),g(I=>I.filter(U=>U.id!==c)),_()},[r,_]);return(0,G.jsxs)("div",{style:{height:"100%",background:"#fafafa",overflow:"hidden"},children:[Q?(0,G.jsx)(Tt,{defaultProjectId:s??void 0,children:(0,G.jsx)(Ot,{assistant:Q,allAssistants:l,onBack:()=>T(null),onDeleted:ve,onSave:we,onAssistantUpdated:Fe,onAgentListInvalidated:_,initialTab:K,initialMessage:P,initialMessageCustomRunConfig:z,initialProjectId:s})},Q.id):(0,G.jsx)(G.Fragment,{children:(0,G.jsx)(Ut,{items:me,assistants:l,stats:o,statsExpiresAt:k,loading:S,onItemClick:c=>Ce(c,"graph"),onOpenPlayground:c=>Ce(c,"playground"),onOpenEval:c=>Ce(c,"eval"),onCreate:L,onDelete:re})}),(0,G.jsx)(nn,{open:ae,onCancel:()=>{ce(!0),de(!1)},onSelectMethod:xe,focusTriggerAfterClose:be}),(0,G.jsx)(en,{open:pe,initialMode:Le,initialValues:Be,onCancel:()=>q(!1),onSuccess:(c,h)=>{q(!1),g(I=>I.some(ke=>ke.id===c.id)?I:[c,...I]),$e(c.id,"graph"),N(h?.initialMessage??null),F(h?.initialMessageCustomRunConfig??null),i(h?.projectId??null),_()}}),(0,G.jsx)(fe,{title:"Delete Agent",open:Z!==null,onCancel:()=>W(null),onOk:se,okText:"Delete",okButtonProps:{danger:!0,loading:Oe},cancelText:"Cancel",children:(0,G.jsx)("p",{children:"This action cannot be undone."})})]})};export{Da as AgentGovernanceWorkbench};
@@ -1,4 +1,4 @@
1
- import{c as W,d as V}from"./embed-page-chunk-KEL6XU6R.js";import{b as N,d as U,e as k}from"./embed-page-chunk-AC6X2XRH.js";import"./embed-page-chunk-S4XZPBRM.js";import{Fa as b,Ha as z,Ia as F,Ja as H,Ka as L,Wa as R,Xa as $,Ya as J}from"./embed-page-chunk-OBM5EUWZ.js";import"./embed-page-chunk-HMTKPZ5B.js";import{a as g}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{Dc as D,Ia as O,Rc as G,Sc as w,Vc as _,W as v,aa as M,gb as P,lb as B,nc as E}from"./embed-page-chunk-O4QK5LWZ.js";import{a as C}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as p}from"./embed-page-chunk-6Y3UYJ6Z.js";var s=p(C());var S=p(C());var o=p(g());var se="tracePulse 1.4s ease-in-out infinite",ie={running:(0,o.jsx)(E,{style:{color:"#1890ff"}}),success:(0,o.jsx)(P,{style:{color:"#52c41a"}}),error:(0,o.jsx)(B,{style:{color:"#ff4d4f"}})};function ae({kind:e}){switch(e){case"human":return(0,o.jsx)(_,{});case"agent":return(0,o.jsx)(G,{});case"tool":return(0,o.jsx)(w,{});case"ai":return(0,o.jsx)(D,{});default:return(0,o.jsx)(w,{})}}var I=S.default.createContext({}),le=()=>S.default.useContext(I),de=({data:e,selected:i})=>{let{onJumpToMessage:a}=le(),t=e.isAnswer===!0,r=e.status==="running",d=(e.parallelCount??1)>1,m=!!(a&&e.messageId&&!e.messageId.startsWith("summary:")),f=e.toolCall?F(e.toolCall.name):e.label,y=()=>{if((e.kind==="tool"||e.kind==="agent")&&e.toolCall){let h=H(e.toolCall.response);return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(z,{data:{name:e.toolCall.name,parameters:e.toolCall.args,type:"tool_call"},component_key:`${e.toolCall.id}-params`,interactive:!1}),h&&(0,o.jsx)("div",{style:{marginTop:8},children:(0,o.jsx)(b,{content:h})}),(0,o.jsx)(L,{ui:e.toolCall.ui})]})}return e.content?(0,o.jsx)(b,{content:e.content}):(0,o.jsx)("span",{style:{color:"#8c8c8c"},children:e.label})};return(0,o.jsxs)("div",{"data-testid":"trace-card",style:{height:"100%",display:"flex",flexDirection:"column",border:`1px solid ${t||i?"#6366f1":r?"#91caff":"#e5e7eb"}`,borderRadius:12,background:t?"#eef2ff":"#fff",boxShadow:r?"0 0 0 2px rgba(24,144,255,0.18)":i?"0 0 0 2px rgba(99,102,241,0.2)":"none",animation:r?se:void 0,overflow:"hidden",fontSize:13},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",borderBottom:"1px solid #f0f0f0",background:"rgba(0,0,0,0.02)"},children:[(0,o.jsx)(ae,{kind:e.kind}),(0,o.jsx)("span",{style:{fontWeight:t?700:600,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f}),d&&(0,o.jsxs)(O,{color:"purple",style:{marginInlineEnd:0,fontSize:10},children:["\u5E76\u53D1 \xD7",e.parallelCount]}),ie[e.status],m&&(0,o.jsx)(v,{type:"text",size:"small",onClick:()=>a?.(e.messageId),children:"\u5BF9\u8BDD"})]}),(0,o.jsx)("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:12},children:y()})]})},ce=({data:e,selected:i})=>(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(k,{type:"target",position:N.Top}),(0,o.jsx)(de,{data:e,selected:i}),(0,o.jsx)(k,{type:"source",position:N.Bottom})]}),K={trace:ce};var Y=p(C());var u=p(g()),pe={running:"#1890ff",success:"#52c41a",error:"#ff4d4f"},Z=({graph:e,activeNodeId:i,onSelectNode:a})=>{let t=Y.default.useMemo(()=>new Map(e.nodes.map(r=>[r.id,r])),[e.nodes]);return(0,u.jsx)("div",{"data-testid":"trace-overview-rail",style:{display:"flex",flexDirection:"column",gap:10,width:160,padding:8,overflowY:"auto",borderRight:"1px solid #f0f0f0"},children:e.phases.map(r=>(0,u.jsxs)("div",{"data-testid":"trace-rail-phase",children:[(0,u.jsx)("div",{style:{fontSize:12,color:"#8c8c8c",marginBottom:4},children:r.title}),(0,u.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:r.nodeIds.map(d=>{let m=t.get(d);if(!m)return null;let f=d===i;return(0,u.jsx)(M,{title:m.data.label,children:(0,u.jsx)("button",{type:"button","data-testid":"trace-rail-tick",onClick:()=>a?.(d),style:{width:f?12:8,height:f?12:8,borderRadius:"50%",border:"none",padding:0,cursor:"pointer",background:pe[m.data.status],outline:f?"2px solid #6366f1":"none"}})},d)})})]},r.id))})};var l=p(g()),j=3,q=()=>{},fe=`
1
+ import{c as W,d as V}from"./embed-page-chunk-KEL6XU6R.js";import{b as N,d as U,e as k}from"./embed-page-chunk-AC6X2XRH.js";import"./embed-page-chunk-S4XZPBRM.js";import{Fa as b,Ha as z,Ia as F,Ja as H,Ka as L,Wa as R,Xa as $,Ya as J}from"./embed-page-chunk-SPC4BYNU.js";import"./embed-page-chunk-HMTKPZ5B.js";import{a as g}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{Dc as D,Ia as O,Rc as G,Sc as w,Vc as _,W as v,aa as M,gb as P,lb as B,nc as E}from"./embed-page-chunk-O4QK5LWZ.js";import{a as C}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as p}from"./embed-page-chunk-6Y3UYJ6Z.js";var s=p(C());var S=p(C());var o=p(g());var se="tracePulse 1.4s ease-in-out infinite",ie={running:(0,o.jsx)(E,{style:{color:"#1890ff"}}),success:(0,o.jsx)(P,{style:{color:"#52c41a"}}),error:(0,o.jsx)(B,{style:{color:"#ff4d4f"}})};function ae({kind:e}){switch(e){case"human":return(0,o.jsx)(_,{});case"agent":return(0,o.jsx)(G,{});case"tool":return(0,o.jsx)(w,{});case"ai":return(0,o.jsx)(D,{});default:return(0,o.jsx)(w,{})}}var I=S.default.createContext({}),le=()=>S.default.useContext(I),de=({data:e,selected:i})=>{let{onJumpToMessage:a}=le(),t=e.isAnswer===!0,r=e.status==="running",d=(e.parallelCount??1)>1,m=!!(a&&e.messageId&&!e.messageId.startsWith("summary:")),f=e.toolCall?F(e.toolCall.name):e.label,y=()=>{if((e.kind==="tool"||e.kind==="agent")&&e.toolCall){let h=H(e.toolCall.response);return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(z,{data:{name:e.toolCall.name,parameters:e.toolCall.args,type:"tool_call"},component_key:`${e.toolCall.id}-params`,interactive:!1}),h&&(0,o.jsx)("div",{style:{marginTop:8},children:(0,o.jsx)(b,{content:h})}),(0,o.jsx)(L,{ui:e.toolCall.ui})]})}return e.content?(0,o.jsx)(b,{content:e.content}):(0,o.jsx)("span",{style:{color:"#8c8c8c"},children:e.label})};return(0,o.jsxs)("div",{"data-testid":"trace-card",style:{height:"100%",display:"flex",flexDirection:"column",border:`1px solid ${t||i?"#6366f1":r?"#91caff":"#e5e7eb"}`,borderRadius:12,background:t?"#eef2ff":"#fff",boxShadow:r?"0 0 0 2px rgba(24,144,255,0.18)":i?"0 0 0 2px rgba(99,102,241,0.2)":"none",animation:r?se:void 0,overflow:"hidden",fontSize:13},children:[(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",borderBottom:"1px solid #f0f0f0",background:"rgba(0,0,0,0.02)"},children:[(0,o.jsx)(ae,{kind:e.kind}),(0,o.jsx)("span",{style:{fontWeight:t?700:600,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f}),d&&(0,o.jsxs)(O,{color:"purple",style:{marginInlineEnd:0,fontSize:10},children:["\u5E76\u53D1 \xD7",e.parallelCount]}),ie[e.status],m&&(0,o.jsx)(v,{type:"text",size:"small",onClick:()=>a?.(e.messageId),children:"\u5BF9\u8BDD"})]}),(0,o.jsx)("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:12},children:y()})]})},ce=({data:e,selected:i})=>(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(k,{type:"target",position:N.Top}),(0,o.jsx)(de,{data:e,selected:i}),(0,o.jsx)(k,{type:"source",position:N.Bottom})]}),K={trace:ce};var Y=p(C());var u=p(g()),pe={running:"#1890ff",success:"#52c41a",error:"#ff4d4f"},Z=({graph:e,activeNodeId:i,onSelectNode:a})=>{let t=Y.default.useMemo(()=>new Map(e.nodes.map(r=>[r.id,r])),[e.nodes]);return(0,u.jsx)("div",{"data-testid":"trace-overview-rail",style:{display:"flex",flexDirection:"column",gap:10,width:160,padding:8,overflowY:"auto",borderRight:"1px solid #f0f0f0"},children:e.phases.map(r=>(0,u.jsxs)("div",{"data-testid":"trace-rail-phase",children:[(0,u.jsx)("div",{style:{fontSize:12,color:"#8c8c8c",marginBottom:4},children:r.title}),(0,u.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:r.nodeIds.map(d=>{let m=t.get(d);if(!m)return null;let f=d===i;return(0,u.jsx)(M,{title:m.data.label,children:(0,u.jsx)("button",{type:"button","data-testid":"trace-rail-tick",onClick:()=>a?.(d),style:{width:f?12:8,height:f?12:8,borderRadius:"50%",border:"none",padding:0,cursor:"pointer",background:pe[m.data.status],outline:f?"2px solid #6366f1":"none"}})},d)})})]},r.id))})};var l=p(g()),j=3,q=()=>{},fe=`
2
2
  @keyframes tracePulse {
3
3
  0%, 100% { box-shadow: 0 0 0 2px rgba(24,144,255,0.18); }
4
4
  50% { box-shadow: 0 0 0 6px rgba(24,144,255,0.05); }
@@ -1 +1 @@
1
- import{s as C}from"./embed-page-chunk-OOZDPBUK.js";import{Ea as v}from"./embed-page-chunk-OBM5EUWZ.js";import{a as w}from"./embed-page-chunk-HMTKPZ5B.js";import{a as x}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{ga as b}from"./embed-page-chunk-O4QK5LWZ.js";import{a as D}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as d}from"./embed-page-chunk-6Y3UYJ6Z.js";var c=d(D());var E=d(w());var f=d(x());function p(s){if(!s||s.length===0)return{title:{text:"Chart",left:"left"},tooltip:{trigger:"axis"},legend:{right:0,orient:"vertical"},xAxis:{type:"category",data:[]},yAxis:{type:"value"},series:[{type:"line",name:"Series 1",data:[]}],grid:{left:"3%",right:"4%",bottom:"3%",containLabel:!0}};let i=s[0],t=Object.keys(i);if(t.length===0)return p([]);let r=t.filter(e=>{let n=i[e];return typeof n=="number"||!isNaN(Number(n))});if(r.length>0){let e=r[0],n=t.find(a=>!r.includes(a))||t[0],o=s.map((a,l)=>a[n]!==void 0?String(a[n]):`Item ${l+1}`),u=s.map(a=>{let l=a[e];return typeof l=="number"?l:Number(l)||0});return{title:{text:"Chart",left:"left"},tooltip:{trigger:"axis"},legend:{right:0,orient:"vertical",data:[e]},xAxis:{type:"category",data:o},yAxis:{type:"value"},series:[{type:"line",name:e,data:u}],grid:{left:"3%",right:"4%",bottom:"3%",containLabel:!0}}}return{title:{text:"Chart",left:"left"},tooltip:{trigger:"axis"},legend:{right:0,orient:"vertical"},xAxis:{type:"category",data:s.map((e,n)=>`Item ${n+1}`)},yAxis:{type:"value"},series:[{type:"bar",name:"Count",data:s.map(()=>1)}],grid:{left:"3%",right:"4%",bottom:"3%",containLabel:!0}}}function S(s){if(!s||typeof s!="object"||!s.series||!Array.isArray(s.series)||s.series.length===0)return null;let i=s.series.map((e,n)=>{if(!e||typeof e!="object"||!e.type||!e.data||!Array.isArray(e.data)||e.data.length===0)return null;let o={...e,name:e.name||`Series ${n+1}`};if(e.type==="pie"){let u=e.data.map((a,l)=>typeof a=="object"&&a!==null&&"value"in a?{value:a.value,name:a.name||`Item ${l+1}`}:typeof a=="number"?{value:a,name:`Item ${l+1}`}:null).filter(a=>a!==null);return u.length===0?null:{...o,data:u}}return o}).filter(e=>e!==null);if(i.length===0)return null;let t={...s,series:i},r=i[0].type;if(r!=="pie"){if(!t.xAxis)t.xAxis={type:"category",data:[]};else if(typeof t.xAxis=="object"&&!Array.isArray(t.xAxis)){let e=t.xAxis;if(e.type||(e.type="category"),e.type==="category"&&!e.data){let n=i[0].data;Array.isArray(n)&&n.length>0?Array.isArray(n[0])?e.data=n.map(o=>o[0]):e.data=n.map((o,u)=>`Item ${u+1}`):e.data=[]}t.xAxis=e}t.yAxis?typeof t.yAxis=="object"&&!Array.isArray(t.yAxis)&&(t.yAxis.type||(t.yAxis.type="value")):t.yAxis={type:"value"}}if(!t.title)t.title={text:"Chart",left:"left"};else if(typeof t.title=="object"){let e=t.title;e.left||(e.left="left"),e.text||(e.text="Chart"),t.title=e}if(t.tooltip||(t.tooltip={trigger:r==="pie"?"item":"axis"}),!t.legend)i.length>1&&(t.legend={right:0,orient:"vertical"});else if(typeof t.legend=="object"){let e=t.legend;t.legend=e}return r!=="pie"&&!t.grid&&(t.grid={left:"3%",right:"4%",bottom:"3%",containLabel:!0}),t}function j(s){let i=null;try{let n=typeof s=="string"?s:s.join("");i=(0,E.parse)(n)}catch(n){return{data:null,error:`Failed to parse JSON: ${n instanceof Error?n.message:String(n)}`}}if(!i||typeof i!="object")return{data:null,error:"Parsed data is not an object"};let t=i.series&&Array.isArray(i.series)&&i.series.length>0,r={table:Array.isArray(i.table)?i.table:void 0},e=null;if(i.echarts?e=i.echarts:t&&(e=i),e){let n=S(e);if(n)r.echarts=n;else if(r.table&&r.table.length>0)r.echarts=p(r.table);else return{data:null,error:"ECharts configuration is invalid or incomplete. Required: series array with at least one series containing type and data."}}else r.table&&r.table.length>0?r.echarts=p(r.table):r.echarts=p([]);return{data:r,error:null}}var T=s=>{let{children:i}=s,t=(0,c.useRef)(null),r=(0,c.useRef)(null),e=(0,c.useRef)(null),[n,o]=(0,c.useState)(null);(0,c.useEffect)(()=>{if(!t.current)return;r.current||(r.current=C(t.current));let a=null;if((typeof i=="string"||Array.isArray(i))&&(a=i),!a){r.current&&r.current.clear(),o(null);return}let{data:l,error:g}=j(a);if(g||!l){console.warn("ReactChart failed to parse chart data:",g||"Unknown parse error"),r.current&&r.current.clear(),o(null);return}if(l.table&&Array.isArray(l.table)&&o(l.table),l.echarts)try{r.current.setOption(l.echarts,!0)}catch(h){let m=h instanceof Error?h.message:"Failed to render chart";console.error("Failed to set ECharts option:",h),r.current&&r.current.clear(),o(null)}let y=()=>{r.current&&r.current.resize()};return e.current&&(e.current.disconnect(),e.current=null),t.current&&typeof ResizeObserver<"u"&&(e.current=new ResizeObserver(h=>{requestAnimationFrame(()=>{y()})}),e.current.observe(t.current)),window.addEventListener("resize",y),()=>{e.current&&(e.current.disconnect(),e.current=null),window.removeEventListener("resize",y)}},[i]),(0,c.useEffect)(()=>()=>{e.current&&(e.current.disconnect(),e.current=null),r.current&&(r.current.dispose(),r.current=null)},[]);let u=a=>{if(!a||a.length===0)return[];if(Array.isArray(a[0])){let l=a[0];return a.slice(1).map((y,h)=>{let m={};return y.forEach((R,A)=>{m[l[A]||`col_${A}`]=R}),m})}return a};return(0,f.jsxs)(b,{children:[(0,f.jsx)("div",{ref:t,style:{width:"100%",height:"400px",minHeight:"300px"}}),n&&n.length>0&&(0,f.jsx)("div",{style:{marginTop:16},children:(0,f.jsx)(v,{component_key:"chart_table_data",data:{dataSource:u(n),message:"Data Details"},interactive:!0,default_open_in_side_app:!0})})]})};export{T as ReactChart};
1
+ import{s as C}from"./embed-page-chunk-OOZDPBUK.js";import{Ea as v}from"./embed-page-chunk-SPC4BYNU.js";import{a as w}from"./embed-page-chunk-HMTKPZ5B.js";import{a as x}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{ga as b}from"./embed-page-chunk-O4QK5LWZ.js";import{a as D}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as d}from"./embed-page-chunk-6Y3UYJ6Z.js";var c=d(D());var E=d(w());var f=d(x());function p(s){if(!s||s.length===0)return{title:{text:"Chart",left:"left"},tooltip:{trigger:"axis"},legend:{right:0,orient:"vertical"},xAxis:{type:"category",data:[]},yAxis:{type:"value"},series:[{type:"line",name:"Series 1",data:[]}],grid:{left:"3%",right:"4%",bottom:"3%",containLabel:!0}};let i=s[0],t=Object.keys(i);if(t.length===0)return p([]);let r=t.filter(e=>{let n=i[e];return typeof n=="number"||!isNaN(Number(n))});if(r.length>0){let e=r[0],n=t.find(a=>!r.includes(a))||t[0],o=s.map((a,l)=>a[n]!==void 0?String(a[n]):`Item ${l+1}`),u=s.map(a=>{let l=a[e];return typeof l=="number"?l:Number(l)||0});return{title:{text:"Chart",left:"left"},tooltip:{trigger:"axis"},legend:{right:0,orient:"vertical",data:[e]},xAxis:{type:"category",data:o},yAxis:{type:"value"},series:[{type:"line",name:e,data:u}],grid:{left:"3%",right:"4%",bottom:"3%",containLabel:!0}}}return{title:{text:"Chart",left:"left"},tooltip:{trigger:"axis"},legend:{right:0,orient:"vertical"},xAxis:{type:"category",data:s.map((e,n)=>`Item ${n+1}`)},yAxis:{type:"value"},series:[{type:"bar",name:"Count",data:s.map(()=>1)}],grid:{left:"3%",right:"4%",bottom:"3%",containLabel:!0}}}function S(s){if(!s||typeof s!="object"||!s.series||!Array.isArray(s.series)||s.series.length===0)return null;let i=s.series.map((e,n)=>{if(!e||typeof e!="object"||!e.type||!e.data||!Array.isArray(e.data)||e.data.length===0)return null;let o={...e,name:e.name||`Series ${n+1}`};if(e.type==="pie"){let u=e.data.map((a,l)=>typeof a=="object"&&a!==null&&"value"in a?{value:a.value,name:a.name||`Item ${l+1}`}:typeof a=="number"?{value:a,name:`Item ${l+1}`}:null).filter(a=>a!==null);return u.length===0?null:{...o,data:u}}return o}).filter(e=>e!==null);if(i.length===0)return null;let t={...s,series:i},r=i[0].type;if(r!=="pie"){if(!t.xAxis)t.xAxis={type:"category",data:[]};else if(typeof t.xAxis=="object"&&!Array.isArray(t.xAxis)){let e=t.xAxis;if(e.type||(e.type="category"),e.type==="category"&&!e.data){let n=i[0].data;Array.isArray(n)&&n.length>0?Array.isArray(n[0])?e.data=n.map(o=>o[0]):e.data=n.map((o,u)=>`Item ${u+1}`):e.data=[]}t.xAxis=e}t.yAxis?typeof t.yAxis=="object"&&!Array.isArray(t.yAxis)&&(t.yAxis.type||(t.yAxis.type="value")):t.yAxis={type:"value"}}if(!t.title)t.title={text:"Chart",left:"left"};else if(typeof t.title=="object"){let e=t.title;e.left||(e.left="left"),e.text||(e.text="Chart"),t.title=e}if(t.tooltip||(t.tooltip={trigger:r==="pie"?"item":"axis"}),!t.legend)i.length>1&&(t.legend={right:0,orient:"vertical"});else if(typeof t.legend=="object"){let e=t.legend;t.legend=e}return r!=="pie"&&!t.grid&&(t.grid={left:"3%",right:"4%",bottom:"3%",containLabel:!0}),t}function j(s){let i=null;try{let n=typeof s=="string"?s:s.join("");i=(0,E.parse)(n)}catch(n){return{data:null,error:`Failed to parse JSON: ${n instanceof Error?n.message:String(n)}`}}if(!i||typeof i!="object")return{data:null,error:"Parsed data is not an object"};let t=i.series&&Array.isArray(i.series)&&i.series.length>0,r={table:Array.isArray(i.table)?i.table:void 0},e=null;if(i.echarts?e=i.echarts:t&&(e=i),e){let n=S(e);if(n)r.echarts=n;else if(r.table&&r.table.length>0)r.echarts=p(r.table);else return{data:null,error:"ECharts configuration is invalid or incomplete. Required: series array with at least one series containing type and data."}}else r.table&&r.table.length>0?r.echarts=p(r.table):r.echarts=p([]);return{data:r,error:null}}var T=s=>{let{children:i}=s,t=(0,c.useRef)(null),r=(0,c.useRef)(null),e=(0,c.useRef)(null),[n,o]=(0,c.useState)(null);(0,c.useEffect)(()=>{if(!t.current)return;r.current||(r.current=C(t.current));let a=null;if((typeof i=="string"||Array.isArray(i))&&(a=i),!a){r.current&&r.current.clear(),o(null);return}let{data:l,error:g}=j(a);if(g||!l){console.warn("ReactChart failed to parse chart data:",g||"Unknown parse error"),r.current&&r.current.clear(),o(null);return}if(l.table&&Array.isArray(l.table)&&o(l.table),l.echarts)try{r.current.setOption(l.echarts,!0)}catch(h){let m=h instanceof Error?h.message:"Failed to render chart";console.error("Failed to set ECharts option:",h),r.current&&r.current.clear(),o(null)}let y=()=>{r.current&&r.current.resize()};return e.current&&(e.current.disconnect(),e.current=null),t.current&&typeof ResizeObserver<"u"&&(e.current=new ResizeObserver(h=>{requestAnimationFrame(()=>{y()})}),e.current.observe(t.current)),window.addEventListener("resize",y),()=>{e.current&&(e.current.disconnect(),e.current=null),window.removeEventListener("resize",y)}},[i]),(0,c.useEffect)(()=>()=>{e.current&&(e.current.disconnect(),e.current=null),r.current&&(r.current.dispose(),r.current=null)},[]);let u=a=>{if(!a||a.length===0)return[];if(Array.isArray(a[0])){let l=a[0];return a.slice(1).map((y,h)=>{let m={};return y.forEach((R,A)=>{m[l[A]||`col_${A}`]=R}),m})}return a};return(0,f.jsxs)(b,{children:[(0,f.jsx)("div",{ref:t,style:{width:"100%",height:"400px",minHeight:"300px"}}),n&&n.length>0&&(0,f.jsx)("div",{style:{marginTop:16},children:(0,f.jsx)(v,{component_key:"chart_table_data",data:{dataSource:u(n),message:"Data Details"},interactive:!0,default_open_in_side_app:!0})})]})};export{T as ReactChart};
@@ -1,4 +1,4 @@
1
- import{a as de,b as we,c as Ge,d as He,e as We}from"./embed-page-chunk-XVUA7UHE.js";import{c as _e,d as je}from"./embed-page-chunk-KEL6XU6R.js";import{b as ke,e as ve,h as Me,i as Oe}from"./embed-page-chunk-AC6X2XRH.js";import"./embed-page-chunk-S4XZPBRM.js";import{C as Ee,Qa as De,bb as Fe,cb as Ve,db as Ke,ga as se,k as ae,qa as le,va as _,wa as ze}from"./embed-page-chunk-OBM5EUWZ.js";import{j as Le,m as Ae}from"./embed-page-chunk-HMTKPZ5B.js";import{a as $}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{Fa as ne,Ia as Be,La as ie,W as oe,Y as Ie,Z as Se,_ as Re,la as $e,ra as F,ta as xe,va as K,ya as Pe}from"./embed-page-chunk-O4QK5LWZ.js";import{a as re}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as v}from"./embed-page-chunk-6Y3UYJ6Z.js";var n=v(re());var qe=v(re());var l=v($()),ut=[{key:"pending",label:"Pending",color:"#7A7A7A"},{key:"in_progress",label:"In Progress",color:"#3b82f6"},{key:"review",label:"Review",color:"#f59e0b"},{key:"failed",label:"Failed",color:"#ef4444"},{key:"interrupted",label:"Interrupted",color:"#8b5cf6"},{key:"completed",label:"Completed",color:"#22c55e"}],Ue={high:{label:"High",color:"#ef4444"},medium:{label:"Medium",color:"#f59e0b"},low:{label:"Low",color:"#22c55e"}};function ft(e){let r=typeof e=="string"?new Date(e):e,u=new Date().getTime()-r.getTime(),i=Math.floor(u/1e3),m=Math.floor(i/60),o=Math.floor(m/60),b=Math.floor(o/24);return i<60?"just now":m<60?`${m}m ago`:o<24?`${o}h ago`:b<30?`${b}d ago`:r.toLocaleDateString("en-US")}var gt=_(({css:e,token:r})=>({container:e`
1
+ import{a as de,b as we,c as Ge,d as He,e as We}from"./embed-page-chunk-HEO7X7LH.js";import{c as _e,d as je}from"./embed-page-chunk-KEL6XU6R.js";import{b as ke,e as ve,h as Me,i as Oe}from"./embed-page-chunk-AC6X2XRH.js";import"./embed-page-chunk-S4XZPBRM.js";import{C as Ee,Qa as De,bb as Fe,cb as Ve,db as Ke,ga as se,k as ae,qa as le,va as _,wa as ze}from"./embed-page-chunk-SPC4BYNU.js";import{j as Le,m as Ae}from"./embed-page-chunk-HMTKPZ5B.js";import{a as $}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{Fa as ne,Ia as Be,La as ie,W as oe,Y as Ie,Z as Se,_ as Re,la as $e,ra as F,ta as xe,va as K,ya as Pe}from"./embed-page-chunk-O4QK5LWZ.js";import{a as re}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as v}from"./embed-page-chunk-6Y3UYJ6Z.js";var n=v(re());var qe=v(re());var l=v($()),ut=[{key:"pending",label:"Pending",color:"#7A7A7A"},{key:"in_progress",label:"In Progress",color:"#3b82f6"},{key:"review",label:"Review",color:"#f59e0b"},{key:"failed",label:"Failed",color:"#ef4444"},{key:"interrupted",label:"Interrupted",color:"#8b5cf6"},{key:"completed",label:"Completed",color:"#22c55e"}],Ue={high:{label:"High",color:"#ef4444"},medium:{label:"Medium",color:"#f59e0b"},low:{label:"Low",color:"#22c55e"}};function ft(e){let r=typeof e=="string"?new Date(e):e,u=new Date().getTime()-r.getTime(),i=Math.floor(u/1e3),m=Math.floor(i/60),o=Math.floor(m/60),b=Math.floor(o/24);return i<60?"just now":m<60?`${m}m ago`:o<24?`${o}h ago`:b<30?`${b}d ago`:r.toLocaleDateString("en-US")}var gt=_(({css:e,token:r})=>({container:e`
2
2
  display: flex;
3
3
  flex-direction: column;
4
4
  height: 100%;
@@ -1,4 +1,4 @@
1
- import{d as Pe,f as Ge,g as Be,h as _e,i as Fe,l as We,m as je}from"./embed-page-chunk-AC6X2XRH.js";import"./embed-page-chunk-S4XZPBRM.js";import{$ as Ae,$a as He,A as ye,C as Z,Ga as Ee,I as Ce,N as Se,R as $e,T as Ne,U as Ie,W as we,X as Me,Y as B,Z as oe,_ as De,_a as Oe,g as he,ia as Le,n as J,o as ve,p as Te,q as Q,qa as se,r as O,ra as Re,t as G,va as I,z as be,za as ze}from"./embed-page-chunk-OBM5EUWZ.js";import"./embed-page-chunk-HMTKPZ5B.js";import{a as N}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{Da as re,Ea as V,Ia as E,Ka as xe,La as R,W as ce,Z as X,aa as z,da as K,fa as me,ga as W,ja as j,ka as pe,oa as q,ua as ge,va as fe,ya as ue}from"./embed-page-chunk-O4QK5LWZ.js";import{a as H}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as h}from"./embed-page-chunk-6Y3UYJ6Z.js";var ie=h(H());var ee=h(H());var f=h(N()),pt=I(({token:e,css:t})=>({container:t`
1
+ import{d as Pe,f as Ge,g as Be,h as _e,i as Fe,l as We,m as je}from"./embed-page-chunk-AC6X2XRH.js";import"./embed-page-chunk-S4XZPBRM.js";import{$ as Ae,$a as He,A as ye,C as Z,Ga as Ee,I as Ce,N as Se,R as $e,T as Ne,U as Ie,W as we,X as Me,Y as B,Z as oe,_ as De,_a as Oe,g as he,ia as Le,n as J,o as ve,p as Te,q as Q,qa as se,r as O,ra as Re,t as G,va as I,z as be,za as ze}from"./embed-page-chunk-SPC4BYNU.js";import"./embed-page-chunk-HMTKPZ5B.js";import{a as N}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{Da as re,Ea as V,Ia as E,Ka as xe,La as R,W as ce,Z as X,aa as z,da as K,fa as me,ga as W,ja as j,ka as pe,oa as q,ua as ge,va as fe,ya as ue}from"./embed-page-chunk-O4QK5LWZ.js";import{a as H}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as h}from"./embed-page-chunk-6Y3UYJ6Z.js";var ie=h(H());var ee=h(H());var f=h(N()),pt=I(({token:e,css:t})=>({container:t`
2
2
  display: flex;
3
3
  flex-direction: column;
4
4
  height: 100%;
@@ -1,4 +1,4 @@
1
- import{a as ce,c as pe}from"./embed-page-chunk-LOXLXZNP.js";import{a as xe}from"./embed-page-chunk-KEL6XU6R.js";import{a as ne,b as O,e as j,f as G,g as oe,h as ie,i as re,k as se,l as ae,m as le,n as de}from"./embed-page-chunk-AC6X2XRH.js";import"./embed-page-chunk-S4XZPBRM.js";import{Fa as H,Y as L,h as Q,pa as te,s as F,u as ee,y as M}from"./embed-page-chunk-OBM5EUWZ.js";import{r as $}from"./embed-page-chunk-HMTKPZ5B.js";import{a as I}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{Aa as J,Bc as K,Fa as Z,Ia as D,La as X,Z as E,aa as P,na as _,oa as A,tb as q,va as B,wa as Y}from"./embed-page-chunk-O4QK5LWZ.js";import{a as U}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as k}from"./embed-page-chunk-6Y3UYJ6Z.js";var r=k(U());var V=k(xe());var ue=k(U());var ge=k(I()),fe=({steps:t,graphDefinition:o,assistantId:n})=>{let l=(0,ue.useMemo)(()=>pe(o),[o]);return(0,ge.jsx)(ce,{dsl:l,steps:t,assistantId:n})};var e=k(I()),ve=`
1
+ import{a as ce,c as pe}from"./embed-page-chunk-XUXEGF3S.js";import{a as xe}from"./embed-page-chunk-KEL6XU6R.js";import{a as ne,b as O,e as j,f as G,g as oe,h as ie,i as re,k as se,l as ae,m as le,n as de}from"./embed-page-chunk-AC6X2XRH.js";import"./embed-page-chunk-S4XZPBRM.js";import{Fa as H,Y as L,h as Q,pa as te,s as F,u as ee,y as M}from"./embed-page-chunk-SPC4BYNU.js";import{r as $}from"./embed-page-chunk-HMTKPZ5B.js";import{a as I}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{Aa as J,Bc as K,Fa as Z,Ia as D,La as X,Z as E,aa as P,na as _,oa as A,tb as q,va as B,wa as Y}from"./embed-page-chunk-O4QK5LWZ.js";import{a as U}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as k}from"./embed-page-chunk-6Y3UYJ6Z.js";var r=k(U());var V=k(xe());var ue=k(U());var ge=k(I()),fe=({steps:t,graphDefinition:o,assistantId:n})=>{let l=(0,ue.useMemo)(()=>pe(o),[o]);return(0,ge.jsx)(ce,{dsl:l,steps:t,assistantId:n})};var e=k(I()),ve=`
2
2
  @keyframes spin {
3
3
  from { transform: rotate(0deg); }
4
4
  to { transform: rotate(360deg); }
@@ -1,3 +1,3 @@
1
- import{a as Fe,b as qe}from"./embed-page-chunk-MQDYZS3S.js";import{b as He,c as fe}from"./embed-page-chunk-LOXLXZNP.js";import"./embed-page-chunk-KEL6XU6R.js";import{f as _e}from"./embed-page-chunk-AC6X2XRH.js";import"./embed-page-chunk-S4XZPBRM.js";import{C as ae,F as le,Fa as Ne,K as Te,M as de,O as ce,S as De,W as Le,_ as Pe,ha as je,i as Me,ib as Be,l as se,la as _,m as Ae,ma as ge,na as Oe,ra as pe,sa as X,ta as Ee,wa as J}from"./embed-page-chunk-OBM5EUWZ.js";import{r as V}from"./embed-page-chunk-HMTKPZ5B.js";import{a as P}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{Aa as Se,Gc as We,La as U,W as q,Z as H,aa as Y,fc as ze,ga as Ce,pc as Ie,ra as $,ta as K,tb as Re,va as re,ya as G,yc as ie}from"./embed-page-chunk-O4QK5LWZ.js";import{a as oe}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as W}from"./embed-page-chunk-6Y3UYJ6Z.js";var i=W(oe());var Q=W(oe());var L=W(P());function st(o){let s=o.split(/[\n\r.。;;!!??]+/).filter(Boolean)[0]?.trim()||"";return s=s.replace(/[,,]+$/,"").trim(),s.length>50&&(s=s.slice(0,50)),s||(s=o.slice(0,50).trim()),s}function at(o){let e=5381;for(let s=0;s<o.length;s++)e=(e<<5)+e+o.charCodeAt(s)>>>0;return e.toString(36).slice(0,6)}var ue=({open:o,onCancel:e,onCreated:s,type:m="processing"})=>{let{post:d}=V(),{trainingProjects:p,loading:b}=J(),[f,M]=(0,Q.useState)(null),[y]=$.useForm(),u=p.find(w=>w.id===f)??p[0]??null;return(0,Q.useEffect)(()=>{o&&(y.resetFields(),M(null))},[o,y]),(0,L.jsx)(G,{title:m==="workflow"?"New Workflow":"New Processing Workflow",open:o,onCancel:e,onOk:async()=>{if(m==="workflow"&&!u)return;let x=((await y.validateFields()).purpose||"").trim(),z=st(x),I=`wf-${at(x+Date.now())}`,g=m==="workflow"?{key:I,name:z,description:x,type:"workflow",prompt:"Complete the assigned task accurately and concisely.",metadata:{trainingProjectId:u?.id},workflowYaml:`name: ${I}
1
+ import{a as Fe,b as qe}from"./embed-page-chunk-YCX5YZRP.js";import{b as He,c as fe}from"./embed-page-chunk-XUXEGF3S.js";import"./embed-page-chunk-KEL6XU6R.js";import{f as _e}from"./embed-page-chunk-AC6X2XRH.js";import"./embed-page-chunk-S4XZPBRM.js";import{C as ae,F as le,Fa as Ne,K as Te,M as de,O as ce,S as De,W as Le,_ as Pe,ha as je,i as Me,ib as Be,l as se,la as _,m as Ae,ma as ge,na as Oe,ra as pe,sa as X,ta as Ee,wa as J}from"./embed-page-chunk-SPC4BYNU.js";import{r as V}from"./embed-page-chunk-HMTKPZ5B.js";import{a as P}from"./embed-page-chunk-MB65DZAX.js";import"./embed-page-chunk-VW3NF5NT.js";import"./embed-page-chunk-5JDQ456X.js";import"./embed-page-chunk-Z7USDLHI.js";import{Aa as Se,Gc as We,La as U,W as q,Z as H,aa as Y,fc as ze,ga as Ce,pc as Ie,ra as $,ta as K,tb as Re,va as re,ya as G,yc as ie}from"./embed-page-chunk-O4QK5LWZ.js";import{a as oe}from"./embed-page-chunk-4BKXE5ON.js";import"./embed-page-chunk-IX4WLWCY.js";import"./embed-page-chunk-EUOOO2LS.js";import{e as W}from"./embed-page-chunk-6Y3UYJ6Z.js";var i=W(oe());var Q=W(oe());var L=W(P());function st(o){let s=o.split(/[\n\r.。;;!!??]+/).filter(Boolean)[0]?.trim()||"";return s=s.replace(/[,,]+$/,"").trim(),s.length>50&&(s=s.slice(0,50)),s||(s=o.slice(0,50).trim()),s}function at(o){let e=5381;for(let s=0;s<o.length;s++)e=(e<<5)+e+o.charCodeAt(s)>>>0;return e.toString(36).slice(0,6)}var ue=({open:o,onCancel:e,onCreated:s,type:m="processing"})=>{let{post:d}=V(),{trainingProjects:p,loading:b}=J(),[f,M]=(0,Q.useState)(null),[y]=$.useForm(),u=p.find(w=>w.id===f)??p[0]??null;return(0,Q.useEffect)(()=>{o&&(y.resetFields(),M(null))},[o,y]),(0,L.jsx)(G,{title:m==="workflow"?"New Workflow":"New Processing Workflow",open:o,onCancel:e,onOk:async()=>{if(m==="workflow"&&!u)return;let x=((await y.validateFields()).purpose||"").trim(),z=st(x),I=`wf-${at(x+Date.now())}`,g=m==="workflow"?{key:I,name:z,description:x,type:"workflow",prompt:"Complete the assigned task accurately and concisely.",metadata:{trainingProjectId:u?.id},workflowYaml:`name: ${I}
2
2
  steps: []
3
3
  `}:{key:I,name:z,description:x,type:"processing",prompt:`You are the orchestrator for workflow "${z}". Purpose: ${x}. Follow the topology to delegate tasks to sub-agents.`,tools:[],skills:[],subAgents:[],middleware:[{id:"topology",type:"topology",name:"Topology",description:"Workflow topology",enabled:!0,config:{edges:[]}}]};await d("/api/assistants",{id:I,name:z,description:x,graphDefinition:g}),y.resetFields(),s(I,x,m==="workflow"?u?.id:void 0)},okText:"Create",okButtonProps:{disabled:m==="workflow"&&(b||!u)},destroyOnClose:!0,children:(0,L.jsxs)($,{form:y,layout:"vertical",initialValues:{purpose:""},children:[(0,L.jsx)($.Item,{name:"purpose",label:"Purpose",rules:[{required:!0,message:"Please describe the workflow purpose"}],children:(0,L.jsx)(K.TextArea,{placeholder:"Describe what this workflow should do. Name and key will be generated automatically.",rows:4})}),m==="workflow"&&(0,L.jsx)(Fe,{project:u,projects:p,value:u?.id??null,onChange:M,loading:b})]})})};var Ke=W(oe());var t=W(P()),{Text:be}=U;function lt(o){if(!o||typeof o!="object")return null;let e=o;return{modelKey:e.modelKey||e.model||void 0,tools:Array.isArray(e.tools)?e.tools:[],middleware:Array.isArray(e.middleware)?e.middleware.filter(s=>s&&typeof s=="object"&&s.type):[],subAgents:Array.isArray(e.subAgents)?e.subAgents:[],skillCategories:Array.isArray(e.skillCategories)?e.skillCategories:[],runConfig:e.runConfig&&typeof e.runConfig=="object"?e.runConfig:void 0}}var dt={filesystem:(0,t.jsx)(Te,{size:12}),code_eval:(0,t.jsx)(Oe,{size:12}),browser:(0,t.jsx)(ce,{size:12}),sql:(0,t.jsx)(le,{size:12}),skill:(0,t.jsx)(ge,{size:12}),http:(0,t.jsx)(Le,{size:12}),scheduler:(0,t.jsx)(ae,{size:12}),metrics:(0,t.jsx)(Me,{size:12}),topology:(0,t.jsx)(de,{size:12}),ask_user_to_clarify:(0,t.jsx)(Pe,{size:12}),widget:(0,t.jsx)(se,{size:12}),date:(0,t.jsx)(Ae,{size:12}),task:(0,t.jsx)(de,{size:12}),custom:(0,t.jsx)(je,{size:12}),claw:(0,t.jsx)(_,{size:12}),collection:(0,t.jsx)(De,{size:12})},ct={filesystem:{bg:"rgba(34,197,94,0.08)",text:"#16a34a",border:"rgba(34,197,94,0.2)"},code_eval:{bg:"rgba(99,102,241,0.08)",text:"#4f46e5",border:"rgba(99,102,241,0.2)"},browser:{bg:"rgba(59,130,246,0.08)",text:"#2563eb",border:"rgba(59,130,246,0.2)"},sql:{bg:"rgba(249,115,22,0.08)",text:"#ea580c",border:"rgba(249,115,22,0.2)"},skill:{bg:"rgba(168,85,247,0.08)",text:"#9333ea",border:"rgba(168,85,247,0.2)"},http:{bg:"rgba(20,184,166,0.08)",text:"#0d9488",border:"rgba(20,184,166,0.2)"},scheduler:{bg:"rgba(245,158,11,0.08)",text:"#d97706",border:"rgba(245,158,11,0.2)"},metrics:{bg:"rgba(236,72,153,0.08)",text:"#db2777",border:"rgba(236,72,153,0.2)"},topology:{bg:"rgba(99,102,241,0.08)",text:"#4f46e5",border:"rgba(99,102,241,0.2)"},ask_user_to_clarify:{bg:"rgba(245,158,11,0.08)",text:"#d97706",border:"rgba(245,158,11,0.2)"},widget:{bg:"rgba(20,184,166,0.08)",text:"#0d9488",border:"rgba(20,184,166,0.2)"},date:{bg:"rgba(139,92,246,0.08)",text:"#7c3aed",border:"rgba(139,92,246,0.2)"},task:{bg:"rgba(99,102,241,0.08)",text:"#4f46e5",border:"rgba(99,102,241,0.2)"},custom:{bg:"rgba(107,114,128,0.08)",text:"#4b5563",border:"rgba(107,114,128,0.2)"},claw:{bg:"rgba(107,114,128,0.08)",text:"#4b5563",border:"rgba(107,114,128,0.2)"},collection:{bg:"rgba(6,182,212,0.08)",text:"#0891b2",border:"rgba(6,182,212,0.2)"}},gt={bg:"rgba(107,114,128,0.08)",text:"#4b5563",border:"rgba(107,114,128,0.2)"};function pt(o){let e=o.split(/[_-]+/).filter(Boolean);return e.length===1?e[0].slice(0,2).toUpperCase():e.map(s=>s[0]).join("").toUpperCase().slice(0,2)}var Ye=[{bg:"rgba(99,102,241,0.1)",text:"#6366f1"},{bg:"rgba(34,197,94,0.1)",text:"#22c55e"},{bg:"rgba(245,158,11,0.1)",text:"#f59e0b"},{bg:"rgba(59,130,246,0.1)",text:"#3b82f6"},{bg:"rgba(239,68,68,0.1)",text:"#ef4444"},{bg:"rgba(168,85,247,0.1)",text:"#a855f7"},{bg:"rgba(20,184,166,0.1)",text:"#14b8a6"},{bg:"rgba(236,72,153,0.1)",text:"#ec4899"}];function $e(o){return Ye[o%Ye.length]}var B=({icon:o,label:e,count:s,children:m})=>(0,t.jsxs)("div",{style:{marginBottom:10},children:[(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:6},children:[(0,t.jsx)("span",{style:{color:"#6366f1",display:"flex",alignItems:"center"},children:o}),(0,t.jsx)(be,{strong:!0,style:{fontSize:11,color:"#52525b",textTransform:"uppercase",letterSpacing:"0.3px"},children:e}),(0,t.jsx)("span",{style:{fontSize:9,fontWeight:600,color:"#a1a1aa",background:"rgba(0,0,0,0.04)",borderRadius:8,padding:"1px 6px",lineHeight:"16px"},children:s})]}),m]}),Ge=({graphDef:o})=>{let e=(0,Ke.useMemo)(()=>lt(o),[o]);if(!e)return null;let s=e.middleware.filter(d=>d.enabled!==!1),m=!1;return e.tools.length===0&&s.length===0&&e.subAgents.length===0?null:(0,t.jsx)("div",{style:{pointerEvents:"auto"},children:(0,t.jsxs)("div",{style:{background:"rgba(255,255,255,0.5)",borderRadius:8,width:250,transition:"all 0.25s ease",overflow:"hidden"},children:[(0,t.jsx)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",background:"rgba(99,102,241,0.02)",borderBottom:"1px solid rgba(0,0,0,0.03)"},children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,t.jsx)("div",{style:{width:24,height:24,borderRadius:6,background:"rgba(99,102,241,0.05)",display:"flex",alignItems:"center",justifyContent:"center",color:"#6366f1"},children:(0,t.jsx)(_,{size:13})}),(0,t.jsx)(be,{strong:!0,style:{fontSize:12,color:"#1a1a1a"},children:"Environment"})]})}),(0,t.jsxs)("div",{style:{padding:"10px 12px 12px",maxHeight:"calc(60vh - 48px)",overflowY:"auto"},children:[e.tools.length>0&&(0,t.jsx)(B,{icon:(0,t.jsx)(Ee,{size:12}),label:"Tools",count:e.tools.length,children:(0,t.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:e.tools.map((d,p)=>{let b=$e(p);return(0,t.jsx)(Y,{title:d,placement:"top",children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",borderRadius:6,fontSize:10,fontWeight:500,color:b.text,background:b.bg,cursor:"default",whiteSpace:"nowrap",lineHeight:"16px"},children:[(0,t.jsx)("span",{style:{fontWeight:700,fontSize:9,opacity:.7},children:pt(d)}),(0,t.jsx)("span",{children:d})]})},d)})})}),s.length>0&&(0,t.jsx)(B,{icon:(0,t.jsx)(se,{size:12}),label:"Capabilities",count:s.length,children:(0,t.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:s.map(d=>{let p=ct[d.type]||gt,b=dt[d.type]||(0,t.jsx)(_,{size:12});return(0,t.jsx)(Y,{title:d.name||d.type,placement:"top",children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",borderRadius:6,fontSize:10,fontWeight:500,color:p.text,background:p.bg,border:`1px solid ${p.border}`,cursor:"default",whiteSpace:"nowrap",lineHeight:"16px"},children:[b,(0,t.jsx)("span",{children:d.name||d.type})]})},d.type)})})}),e.subAgents.length>0&&(0,t.jsx)(B,{icon:(0,t.jsx)(pe,{size:12}),label:"Sub-agents",count:e.subAgents.length,children:(0,t.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:e.subAgents.map((d,p)=>{let b=$e(p+3);return(0,t.jsx)(Y,{title:d,placement:"top",children:(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",borderRadius:6,fontSize:10,fontWeight:500,color:b.text,background:b.bg,cursor:"default",whiteSpace:"nowrap",lineHeight:"16px"},children:[(0,t.jsx)(pe,{size:10}),(0,t.jsx)("span",{children:d})]})},d)})})}),(e.modelKey||e.runConfig)&&(0,t.jsx)(B,{icon:(0,t.jsx)(ae,{size:12}),label:"Runtime",count:e.modelKey?1:0,children:(0,t.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[e.modelKey&&(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",borderRadius:6,fontSize:10,fontWeight:500,color:"#4f46e5",background:"rgba(99,102,241,0.08)",border:"1px solid rgba(99,102,241,0.2)",cursor:"default",whiteSpace:"nowrap",lineHeight:"16px"},children:[(0,t.jsx)(_,{size:10}),(0,t.jsxs)("span",{children:["Model: ",e.modelKey]})]}),!!e.runConfig?.databaseKey&&(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",borderRadius:6,fontSize:10,fontWeight:500,color:"#ea580c",background:"rgba(249,115,22,0.08)",border:"1px solid rgba(249,115,22,0.2)",cursor:"default",whiteSpace:"nowrap",lineHeight:"16px"},children:[(0,t.jsx)(le,{size:10}),(0,t.jsxs)("span",{children:["DB: ",String(e.runConfig?.databaseKey)]})]}),e.skillCategories&&e.skillCategories.length>0&&(0,t.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",borderRadius:6,fontSize:10,fontWeight:500,color:"#9333ea",background:"rgba(168,85,247,0.08)",border:"1px solid rgba(168,85,247,0.2)",cursor:"default",whiteSpace:"nowrap",lineHeight:"16px"},children:[(0,t.jsx)(ge,{size:10}),(0,t.jsxs)("span",{children:["Skills: ",e.skillCategories.join(", ")]})]})]})}),m&&(0,t.jsx)(B,{icon:(0,t.jsx)(ce,{size:12}),label:"Channels",count:0,children:(0,t.jsx)(be,{type:"secondary",style:{fontSize:10,fontStyle:"italic"},children:"No channels configured"})})]})]})})};var n=W(P()),{Text:F}=U;function Ue(o){if(typeof o=="string")try{let e=JSON.parse(o);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}return o&&typeof o=="object"&&!Array.isArray(o)?o:null}function ft(o){let e=null;if(typeof o=="string")try{e=JSON.parse(o)}catch{return null}else o&&typeof o=="object"&&(e=o);if(!e)return null;if(e.type!=="workflow")return console.warn("[extractDSL] type is not 'workflow':",e.type),null;if(typeof e.workflowYaml!="string")return console.warn("[extractDSL] workflowYaml not found or not a string, keys:",Object.keys(e)),null;try{return fe(e.workflowYaml)}catch(s){return console.error("[extractDSL] expandWorkflow failed:",s.message,s),null}}function ut({workflows:o,selectedId:e,onSelect:s,onCreate:m,onDelete:d,dsl:p,agentNameMap:b,onSpecClick:f,environmentConfig:M}){let y=o.find(g=>g.id===e),[u,S]=(0,i.useState)(!0),[w,x]=(0,i.useState)(""),z=(0,i.useMemo)(()=>{let g=w.trim().toLowerCase();return g?o.filter(h=>h.name.toLowerCase().includes(g)||h.description.toLowerCase().includes(g)):o},[o,w]);(0,i.useEffect)(()=>{e?S(!1):(S(!0),x(""))},[e]);let I=g=>{s(g),S(!1)};return(0,n.jsx)("div",{style:{display:"flex",height:"100%",width:"100%"},children:(0,n.jsxs)("div",{style:{flex:1,position:"relative"},children:[y?(0,n.jsxs)(n.Fragment,{children:[p?(0,n.jsx)(He,{dsl:p,agentNameMap:b}):(0,n.jsx)("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%"},children:(0,n.jsx)(re,{tip:"Loading workflow DSL..."})}),!u&&(0,n.jsx)("div",{style:{position:"absolute",top:12,left:12,zIndex:10},children:(0,n.jsx)(q,{type:"default",icon:(0,n.jsx)(Ie,{}),onClick:()=>S(!0),style:{width:32,height:32,borderRadius:10,boxShadow:"0 2px 12px rgba(0,0,0,0.08)",border:"1px solid #f0f0f0",background:"rgba(255,255,255,0.95)",color:"#6366f1",display:"flex",alignItems:"center",justifyContent:"center"}})}),(0,n.jsxs)("div",{style:{position:"absolute",top:12,left:u?12:56,zIndex:10,display:"flex",alignItems:"center",gap:6,height:32,padding:"0 14px",background:"rgba(255,255,255,0.95)",borderRadius:10,boxShadow:"0 2px 12px rgba(0,0,0,0.08)",border:"1px solid #f0f0f0"},children:[(0,n.jsx)(X,{size:16,color:"#6366f1"}),(0,n.jsx)(F,{strong:!0,style:{fontSize:13},children:y.name}),(0,n.jsx)(ze,{style:{color:"#6366f1",cursor:"pointer",fontSize:15},onClick:f})]}),(0,n.jsx)("div",{style:{position:"absolute",top:12,right:12,zIndex:10,display:"flex",alignItems:"center",height:32,padding:"0 14px",background:"rgba(255,255,255,0.95)",borderRadius:10,boxShadow:"0 2px 12px rgba(0,0,0,0.08)",border:"1px solid #f0f0f0"},children:(0,n.jsx)(Se,{title:"Delete workflow",description:"This will permanently delete this workflow agent.",onConfirm:()=>d(y.id),okText:"Delete",cancelText:"Cancel",okButtonProps:{danger:!0},children:(0,n.jsx)(Re,{style:{color:"#ff4d4f",cursor:"pointer",fontSize:15}})})}),!u&&(0,n.jsx)("div",{style:{position:"absolute",top:52,left:u?12:56,zIndex:20},children:(0,n.jsx)(Ge,{graphDef:M},y.id)})]}):(0,n.jsx)("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%"},children:(0,n.jsx)(H,{description:"Select a workflow to view its graph"})}),u&&(0,n.jsxs)(n.Fragment,{children:[e&&(0,n.jsx)("div",{onClick:()=>S(!1),style:{position:"absolute",inset:0,zIndex:25,background:"transparent"}}),(0,n.jsxs)(Ce,{size:"small",title:(0,n.jsx)(F,{strong:!0,style:{fontSize:15,color:"#1a1a1a"},children:"Workflows"}),extra:(0,n.jsx)(q,{type:"text",size:"small",icon:(0,n.jsx)(ie,{}),onClick:m,style:{color:"#6366f1"}}),styles:{body:{padding:"12px 16px 16px"},header:{padding:"14px 16px 10px",borderBottom:"1px solid rgba(0,0,0,0.04)"}},style:{position:"absolute",left:16,top:e?56:48,bottom:16,width:300,zIndex:30,borderRadius:16,boxShadow:"0 4px 24px rgba(0,0,0,0.12)",border:"1px solid #f0f0f0",overflow:"auto",background:"rgba(255, 255, 255, 0.92)"},children:[(0,n.jsx)("div",{style:{marginBottom:12},children:(0,n.jsx)(K,{prefix:(0,n.jsx)(We,{style:{color:"#bbb"}}),placeholder:"Filter workflows...",value:w,onChange:g=>x(g.target.value),allowClear:!0,size:"small",style:{borderRadius:10,border:"1px solid rgba(0,0,0,0.06)"}})}),z.length===0?(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"32px 16px",color:"#bbb"},children:[(0,n.jsx)(X,{size:28,style:{marginBottom:10,opacity:.4}}),(0,n.jsx)(F,{type:"secondary",style:{fontSize:13},children:w.trim()?"No workflows match your search":"No workflows yet"})]}):z.map(g=>{let h=e===g.id;return(0,n.jsxs)("div",{onClick:()=>I(g.id),style:{display:"flex",alignItems:"center",gap:12,padding:"13px 15px",borderRadius:12,cursor:"pointer",transition:"all 0.2s ease",background:h?"rgba(99, 102, 241, 0.07)":"rgba(255, 255, 255, 0.5)",border:h?"1px solid rgba(99, 102, 241, 0.25)":"1px solid transparent",marginBottom:6},onMouseEnter:C=>{h||(C.currentTarget.style.background="rgba(255, 255, 255, 0.92)",C.currentTarget.style.boxShadow="0 2px 8px rgba(0,0,0,0.05)",C.currentTarget.style.transform="translateY(-1px)",C.currentTarget.style.borderColor="rgba(0,0,0,0.06)")},onMouseLeave:C=>{h||(C.currentTarget.style.background="rgba(255, 255, 255, 0.5)",C.currentTarget.style.boxShadow="none",C.currentTarget.style.transform="translateY(0)",C.currentTarget.style.borderColor="transparent")},children:[(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:38,height:38,borderRadius:10,background:h?"rgba(99, 102, 241, 0.12)":"rgba(0, 0, 0, 0.04)",flexShrink:0,transition:"background 0.2s ease"},children:(0,n.jsx)(X,{size:18,color:h?"#6366f1":"#888"})}),(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)(F,{strong:!0,ellipsis:{tooltip:g.name},style:{fontSize:14,color:h?"#6366f1":"#1a1a1a",transition:"color 0.2s ease"},children:g.name}),g.description&&(0,n.jsx)("div",{style:{fontSize:12,color:"#999",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",marginTop:3,lineHeight:"18px"},children:g.description})]})]},g.id)})]})]})]})})}var bt=()=>{let{get:o,del:e}=V(),{workspaceId:s,trainingProjects:m,loading:d}=J(),[p,b]=(0,i.useState)([]),[f,M]=(0,i.useState)(null),[y,u]=(0,i.useState)(null),[S,w]=(0,i.useState)(null),[x,z]=(0,i.useState)([]),[I,g]=(0,i.useState)(new Map),h=(0,i.useCallback)(async()=>{try{let r=await o("/api/assistants");if(r.success&&r.data?.records){let c=[],a=new Map;for(let l of r.data.records){if(l.id&&l.name){let k=typeof l.graphDefinition=="object"&&l.graphDefinition!==null?l.graphDefinition:void 0;a.set(l.id,{name:l.name,type:k?.type??"unknown"})}if(l.graphDefinition)if(typeof l.graphDefinition=="string")try{c.push(JSON.parse(l.graphDefinition))}catch{}else typeof l.graphDefinition=="object"&&c.push(l.graphDefinition)}z(c),g(a)}}catch{}},[o]),[C,me]=(0,i.useState)(!0),[Z,Xe]=(0,i.useState)(420),j=(0,i.useRef)(null),[Je,Ve]=(0,i.useState)(!0),[ye,we]=(0,i.useState)(null),[Qe,xe]=(0,i.useState)(!1),[he,O]=(0,i.useState)(!1),[Ze,ke]=(0,i.useState)(null),et=(0,i.useMemo)(()=>["create_workflow","update_workflow","validate_workflow","create_agent","update_agent","delete_agent"],[]),T=(0,i.useCallback)(async()=>{let r=await o("/api/assistants");if(r.success&&r.data?.records){let c=r.data.records.filter(a=>(Ue(a.graphDefinition)??void 0)?.type==="workflow").map(a=>{let l=Ue(a.graphDefinition)??void 0,k=typeof l?.workflowYaml=="string"?l.workflowYaml:"",E=l?.metadata,N=0;try{N=fe(k).nodes.filter(R=>R.type!=="terminal").length}catch{}return{id:a.id,name:a.name,description:a.description||"",type:"workflow",stepCount:N,trainingProjectId:typeof E?.trainingProjectId=="string"?E.trainingProjectId:void 0}});b(c)}we(null)},[o]),ee=(0,i.useCallback)(async r=>{try{let c=await o(`/api/assistants/${r}`);if(c.success&&c.data){let a=c.data.graphDefinition,l=ft(a);if(u(l),!a)w(null);else if(typeof a=="string")try{w(JSON.parse(a))}catch{w(null)}else w(typeof a=="object"?a:null)}}catch{u(null),w(null)}},[o]);(0,i.useEffect)(()=>{let r=!1;return(async()=>{try{await T(),await h()}catch(a){r||we(a instanceof Error?a.message:"Failed to load workflows")}finally{r||Ve(!1)}})(),()=>{r=!0}},[T]),(0,i.useEffect)(()=>{f?ee(f):u(null)},[f,ee]);let tt=(0,i.useCallback)(r=>{r.preventDefault(),j.current={startX:r.clientX,startWidth:Z}},[Z]);(0,i.useEffect)(()=>{let r=a=>{if(!j.current)return;let l=j.current.startX-a.clientX,k=Math.min(900,Math.max(400,j.current.startWidth+l));Xe(k)},c=()=>{j.current=null};return window.addEventListener("mousemove",r),window.addEventListener("mouseup",c),()=>{window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",c)}},[]);let nt=(0,i.useCallback)(r=>{M(r)},[]),ve=(0,i.useCallback)((r,c,a)=>{O(!1),T().then(()=>{M(r),a&&b(l=>l.map(k=>k.id===r?{...k,trainingProjectId:a}:k)),c&&ke({requestId:r,content:c})})},[T]),ot=(0,i.useCallback)(async r=>{await e(`/api/assistants/${r}`),f===r&&M(null),await T()},[e,T,f]),D=(0,i.useMemo)(()=>p.find(r=>r.id===f)||null,[p,f]),te=D?.trainingProjectId??m[0]?.id??null,rt=(0,i.useMemo)(()=>f&&D?{id:f,name:D.name,type:"workflow"}:null,[f,D]),it=(0,i.useMemo)(()=>{let r=y?.nodes.filter(v=>v.type!=="terminal"&&v.ref).map(v=>v.ref).filter((v,R,A)=>A.indexOf(v)===R)??[];if(r.length===0)return S;let c=x.filter(v=>{let R=v.key;return R&&r.includes(R)});if(c.length===0)return S;let a={...S??{}},l=new Set(a.tools??[]),k=[...a.middleware??[]],E=new Set(a.subAgents??[]),N=new Set(k.map(v=>v.type).filter(Boolean));for(let v of c){let R=v;for(let A of R.tools??[])l.add(A);for(let A of R.middleware??[]){let ne=A.type;ne&&!N.has(ne)&&(k.push(A),N.add(ne))}for(let A of R.subAgents??[])E.add(A)}return a.tools=Array.from(l),a.middleware=k,a.subAgents=Array.from(E),a},[y,S,x]);return Je?(0,n.jsx)("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%"},children:(0,n.jsx)(re,{size:"large",tip:"Loading workflows..."})}):ye?(0,n.jsx)(H,{description:ye}):p.length===0?(0,n.jsxs)("div",{style:{width:"100%",height:"100%"},children:[(0,n.jsx)(ue,{open:he,onCancel:()=>O(!1),onCreated:ve,type:"workflow"}),(0,n.jsx)(H,{description:"No workflow definitions found.",children:(0,n.jsx)(q,{type:"primary",icon:(0,n.jsx)(ie,{}),onClick:()=>O(!0),children:"Create Workflow"})})]}):(0,n.jsxs)("div",{style:{width:"100%",height:"100%"},children:[(0,n.jsx)(ue,{open:he,onCancel:()=>O(!1),onCreated:ve,type:"workflow"}),(0,n.jsx)(G,{title:D?.name,open:Qe,onCancel:()=>xe(!1),footer:null,width:"85vw",centered:!0,styles:{body:{maxHeight:"calc(85vh - 120px)",overflow:"auto",padding:"12px 24px 24px"}},children:D?.description?(0,n.jsx)(Ne,{content:D.description}):(0,n.jsx)(F,{type:"secondary",children:"No description set."})}),(0,n.jsx)(_e,{children:(0,n.jsxs)("div",{style:{height:"100%",width:"100%",position:"relative",overflow:"hidden"},children:[(0,n.jsx)(ut,{workflows:p,selectedId:f,onSelect:nt,onCreate:()=>O(!0),onDelete:ot,dsl:y,agentNameMap:I,onSpecClick:()=>xe(!0),environmentConfig:it}),!C&&f&&(0,n.jsx)("div",{style:{position:"absolute",right:0,top:"50%",transform:"translateY(-50%)",zIndex:20},children:(0,n.jsx)("div",{onClick:()=>me(!0),style:{writingMode:"vertical-rl",textOrientation:"mixed",padding:"16px 8px",background:"#6366f1",color:"#fff",borderRadius:"8px 0 0 8px",cursor:"pointer",fontSize:12,fontWeight:500,userSelect:"none"},children:"Copilot"})}),C&&f&&te&&!d&&(0,n.jsxs)("div",{style:{position:"absolute",right:16,top:48,bottom:12,zIndex:15,width:Z,borderRadius:16,overflow:"hidden",boxShadow:"0 4px 24px rgba(0,0,0,0.12)"},children:[(0,n.jsx)("div",{onMouseDown:tt,style:{position:"absolute",left:0,top:0,bottom:0,width:6,cursor:"ew-resize",zIndex:2,background:"transparent"}}),(0,n.jsx)(Be,{defaultWorkspaceId:s??void 0,defaultProjectId:te??void 0,children:(0,n.jsx)(qe,{workflowContext:rt,onClose:()=>me(!1),onToolCompleted:r=>{et.includes(r)&&(T(),f&&ee(f))},initialMessageRequest:Ze,onInitialMessageSubmitted:r=>ke(c=>c?.requestId===r?null:c)})},`${s??"default"}:${te??"default"}`)]})]})})]})},qt=bt;export{bt as WorkflowAutomationView,qt as default};