-
Notifications
You must be signed in to change notification settings - Fork 20
feat(studio): create Fabric agents by uploading their directory [ASTD-448] #1429
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 11 commits
37b5f17
a9291d7
ac42e2f
7533810
e743498
3e47de4
0e149fd
9ee0e01
8f37799
7d813b6
d9deaae
c153a87
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import { agentsCreateAgent, agentsGetAgent } from '@nemo/sdk/generated/agents/api'; | ||
| import { | ||
| filesCreateFileset, | ||
| filesDeleteFileset, | ||
| filesRetrieveFileset, | ||
| filesUploadFile, | ||
| } from '@nemo/sdk/generated/platform/api'; | ||
| import { | ||
| AgentSpecFilesetConflictError, | ||
| AgentSpecFilesetOrphanError, | ||
| createAgentFromUpload, | ||
| } from '@studio/api/agents/useCreateAgentFromUpload'; | ||
| import type { UploadAgentEntry } from '@studio/routes/agents/AgentsListRoute/UploadAgentModal/type'; | ||
|
|
||
| vi.mock('@nemo/sdk/generated/agents/api', async (importOriginal) => ({ | ||
| ...(await importOriginal<typeof import('@nemo/sdk/generated/agents/api')>()), | ||
| agentsCreateAgent: vi.fn(), | ||
| agentsGetAgent: vi.fn(), | ||
| })); | ||
|
|
||
| vi.mock('@nemo/sdk/generated/platform/api', async (importOriginal) => ({ | ||
| ...(await importOriginal<typeof import('@nemo/sdk/generated/platform/api')>()), | ||
| filesRetrieveFileset: vi.fn(), | ||
| filesCreateFileset: vi.fn(), | ||
| filesUploadFile: vi.fn(), | ||
| filesDeleteFileset: vi.fn(), | ||
| })); | ||
|
|
||
| const FABRIC_YAML = 'config_format: nemo-agents-spec-v1\nname: calc\ndescription: Adds numbers\n'; | ||
|
|
||
| const entryFor = (path: string, contents: string): UploadAgentEntry => ({ | ||
| path, | ||
| file: new File([contents], path.split('/').pop() ?? path), | ||
| }); | ||
|
|
||
| const entries = (): UploadAgentEntry[] => [ | ||
| entryFor('agent.yaml', FABRIC_YAML), | ||
| entryFor('mcps/calculator.py', 'print(1)\n'), | ||
| ]; | ||
|
|
||
| const params = () => ({ workspace: 'ws', name: 'calc', entries: entries() }); | ||
|
|
||
| const filesetMissing = () => vi.mocked(filesRetrieveFileset).mockRejectedValue(new Error('404')); | ||
| const filesetExists = () => | ||
| vi.mocked(filesRetrieveFileset).mockResolvedValue({ name: 'calc-spec' } as never); | ||
| const agentMissing = () => vi.mocked(agentsGetAgent).mockRejectedValue(new Error('404')); | ||
| const agentExists = () => vi.mocked(agentsGetAgent).mockResolvedValue({ name: 'calc' } as never); | ||
|
|
||
| beforeEach(() => { | ||
| filesetMissing(); | ||
| agentMissing(); | ||
| vi.mocked(filesCreateFileset).mockResolvedValue({ name: 'calc-spec' } as never); | ||
| vi.mocked(filesUploadFile).mockResolvedValue({ path: 'agent.yaml' } as never); | ||
| vi.mocked(filesDeleteFileset).mockResolvedValue(undefined as never); | ||
| vi.mocked(agentsCreateAgent).mockResolvedValue({ name: 'calc' } as never); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| describe('createAgentFromUpload', () => { | ||
| it('uploads every file before creating the agent', async () => { | ||
| const order: string[] = []; | ||
| vi.mocked(filesUploadFile).mockImplementation(async (_ws, _fs, path) => { | ||
| order.push(`upload:${path}`); | ||
| return { path } as never; | ||
| }); | ||
| vi.mocked(agentsCreateAgent).mockImplementation(async () => { | ||
| order.push('createAgent'); | ||
| return { name: 'calc' } as never; | ||
| }); | ||
|
|
||
| await createAgentFromUpload(params()); | ||
|
|
||
| // Uploads run concurrently, so only their completion before the create is guaranteed. | ||
| expect(order.at(-1)).toBe('createAgent'); | ||
| expect(order.slice(0, -1).sort()).toEqual(['upload:agent.yaml', 'upload:mcps/calculator.py']); | ||
| expect(agentsCreateAgent).toHaveBeenCalledWith('ws', { | ||
| name: 'calc', | ||
| description: 'Adds numbers', | ||
| config: expect.objectContaining({ config_format: 'nemo-agents-spec-v1' }), | ||
| config_format: 'nemo-agents-spec-v1', | ||
| }); | ||
| }); | ||
|
|
||
| it('refuses a fileset that an existing agent owns', async () => { | ||
| filesetExists(); | ||
| agentExists(); | ||
|
|
||
| await expect(createAgentFromUpload(params())).rejects.toThrow(AgentSpecFilesetConflictError); | ||
| expect(filesCreateFileset).not.toHaveBeenCalled(); | ||
| expect(filesDeleteFileset).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('asks before replacing a fileset that no agent owns', async () => { | ||
| filesetExists(); | ||
|
|
||
| await expect(createAgentFromUpload(params())).rejects.toThrow(AgentSpecFilesetOrphanError); | ||
| expect(filesDeleteFileset).not.toHaveBeenCalled(); | ||
| expect(agentsCreateAgent).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('replaces an orphaned fileset once confirmed', async () => { | ||
| filesetExists(); | ||
|
|
||
| await createAgentFromUpload({ ...params(), replaceOrphanedFileset: true }); | ||
|
|
||
| expect(filesDeleteFileset).toHaveBeenCalledWith('ws', 'calc-spec'); | ||
| expect(filesCreateFileset).toHaveBeenCalledWith( | ||
| 'ws', | ||
| expect.objectContaining({ name: 'calc-spec' }) | ||
| ); | ||
| expect(agentsCreateAgent).toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('does not replace an owned fileset even when confirmed', async () => { | ||
| filesetExists(); | ||
| agentExists(); | ||
|
|
||
| await expect( | ||
| createAgentFromUpload({ ...params(), replaceOrphanedFileset: true }) | ||
| ).rejects.toThrow(AgentSpecFilesetConflictError); | ||
| expect(filesDeleteFileset).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('deletes the fileset when an upload fails', async () => { | ||
| vi.mocked(filesUploadFile) | ||
| .mockResolvedValueOnce({ path: 'agent.yaml' } as never) | ||
| .mockRejectedValueOnce(new Error('network down')); | ||
|
|
||
| await expect(createAgentFromUpload(params())).rejects.toThrow('network down'); | ||
| expect(filesDeleteFileset).toHaveBeenCalledWith('ws', 'calc-spec'); | ||
| }); | ||
|
|
||
| it('deletes the fileset when creating the agent fails', async () => { | ||
| vi.mocked(agentsCreateAgent).mockRejectedValue(new Error('409 conflict')); | ||
|
|
||
| await expect(createAgentFromUpload(params())).rejects.toThrow('409 conflict'); | ||
| expect(filesDeleteFileset).toHaveBeenCalledWith('ws', 'calc-spec'); | ||
| }); | ||
|
|
||
| it('rejects a non-Fabric config before touching anything', async () => { | ||
| const natEntries = [entryFor('agent.yaml', 'config_format: nat-workflow-v1\n')]; | ||
|
|
||
| await expect( | ||
| createAgentFromUpload({ workspace: 'ws', name: 'calc', entries: natEntries }) | ||
| ).rejects.toThrow(/config_format/); | ||
| expect(filesRetrieveFileset).not.toHaveBeenCalled(); | ||
| expect(filesCreateFileset).not.toHaveBeenCalled(); | ||
| expect(agentsCreateAgent).not.toHaveBeenCalled(); | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import { agentsCreateAgent, agentsGetAgent } from '@nemo/sdk/generated/agents/api'; | ||
| import type { Agent } from '@nemo/sdk/generated/agents/schema/Agent'; | ||
| import { | ||
| filesCreateFileset, | ||
| filesDeleteFileset, | ||
| filesRetrieveFileset, | ||
| filesUploadFile, | ||
| } from '@nemo/sdk/generated/platform/api'; | ||
| import { | ||
| AGENT_CONFIG_FILENAME, | ||
| FABRIC_CONFIG_FORMAT, | ||
| } from '@studio/routes/agents/AgentsListRoute/UploadAgentModal/const'; | ||
| import type { UploadAgentEntry } from '@studio/routes/agents/AgentsListRoute/UploadAgentModal/type'; | ||
| import { | ||
| agentSpecFilesetName, | ||
| parseAgentConfig, | ||
| } from '@studio/routes/agents/AgentsListRoute/UploadAgentModal/utils'; | ||
| import { UseMutationOptions, useMutation } from '@tanstack/react-query'; | ||
|
|
||
| export interface CreateAgentFromUploadParams { | ||
| workspace: string; | ||
| name: string; | ||
| entries: UploadAgentEntry[]; | ||
| replaceOrphanedFileset?: boolean; | ||
| } | ||
|
|
||
| /** An agent of this name already exists; its spec fileset is not ours to take. */ | ||
| export class AgentSpecFilesetConflictError extends Error { | ||
| constructor(public readonly filesetName: string) { | ||
| super( | ||
| `An agent named "${filesetName.replace(/-spec$/, '')}" already owns the fileset "${filesetName}". Choose a different name.` | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| /** A spec fileset with no agent behind it — an abandoned upload, or an agent since deleted. */ | ||
| export class AgentSpecFilesetOrphanError extends Error { | ||
| constructor(public readonly filesetName: string) { | ||
| super( | ||
| `A fileset named "${filesetName}" already exists, but no agent owns it — an upload that did not finish, or an agent that was deleted, since deleting an agent leaves its fileset behind. Replacing it discards its current contents.` | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| // Files first: the fileset reserves the name, and a create-time validation that needs a | ||
| // base_dir can only see files that are already uploaded. Deleting the fileset on rollback | ||
| // is safe because an existing one is either refused or replaced deliberately above. | ||
| export const createAgentFromUpload = async ({ | ||
| workspace, | ||
| name, | ||
| entries, | ||
| replaceOrphanedFileset = false, | ||
| }: CreateAgentFromUploadParams): Promise<Agent> => { | ||
| const filesetName = agentSpecFilesetName(name); | ||
|
|
||
| const configEntry = entries.find((entry) => entry.path === AGENT_CONFIG_FILENAME); | ||
| if (!configEntry) throw new Error(`No ${AGENT_CONFIG_FILENAME} in the selected directory.`); | ||
| const config = parseAgentConfig(await configEntry.file.text()); | ||
|
|
||
| await claimFileset(workspace, name, filesetName, replaceOrphanedFileset); | ||
|
|
||
| try { | ||
| await filesCreateFileset(workspace, { | ||
| name: filesetName, | ||
| description: `Agent spec for ${name}`, | ||
| }); | ||
| await uploadEntries(workspace, filesetName, entries); | ||
|
|
||
| return await agentsCreateAgent(workspace, { | ||
| name, | ||
| description: typeof config.description === 'string' ? config.description : '', | ||
| config, | ||
| config_format: FABRIC_CONFIG_FORMAT, | ||
| }); | ||
| } catch (error) { | ||
| await rollback(workspace, filesetName); | ||
| throw error; | ||
| } | ||
| }; | ||
|
|
||
| const claimFileset = async ( | ||
| workspace: string, | ||
| agentName: string, | ||
| filesetName: string, | ||
| replaceOrphanedFileset: boolean | ||
| ): Promise<void> => { | ||
| try { | ||
| await filesRetrieveFileset(workspace, filesetName); | ||
| } catch { | ||
| return; | ||
| } | ||
|
|
||
| if (await agentExists(workspace, agentName)) { | ||
| throw new AgentSpecFilesetConflictError(filesetName); | ||
| } | ||
| if (!replaceOrphanedFileset) { | ||
| throw new AgentSpecFilesetOrphanError(filesetName); | ||
| } | ||
|
|
||
| await filesDeleteFileset(workspace, filesetName); | ||
| }; | ||
|
Comment on lines
+84
to
+104
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift 🧩 Analysis chain🏁 Script executed: #!/bin/bash
# Locate the generated SDK error type and how status codes are exposed.
fd -t f -i 'api.ts' web/packages/sdk | head -50
rg -nP --type=ts -C5 '(class \w*(Http|Api)Error|throw new \w*Error\()' web/packages/sdk/generated | head -80
rg -nP --type=ts -C4 '\bstatus\b' web/packages/sdk/src 2>/dev/null | head -40Repository: NVIDIA-NeMo/nemo-platform Length of output: 288 🏁 Script executed: #!/bin/bash
set -eu
printf '%s\n' '--- target files ---'
fd -t f 'useCreateAgentFromUpload\.ts$' .
printf '%s\n' '--- referenced symbols ---'
rg -n -C3 --glob '!node_modules' --glob '!dist' \
'filesRetrieveFileset|filesCreateFileset|filesDeleteFileset|agentsGetAgent|AgentSpecFileset|agentExists|isNotFound' .
printf '%s\n' '--- SDK and generated-code candidates ---'
fd -t d -i 'sdk|generated|api' web | head -100
fd -t f -i '(api|client|errors?|exceptions?)\.(ts|tsx|js|jsx)$' web | head -150
printf '%s\n' '--- target outline and size ---'
target="$(fd -t f 'useCreateAgentFromUpload\.ts$' . | head -1)"
if [ -n "$target" ]; then
wc -l "$target"
ast-grep outline "$target"
fiRepository: NVIDIA-NeMo/nemo-platform Length of output: 50381 🏁 Script executed: #!/bin/bash
set -eu
target='web/packages/studio/src/api/agents/useCreateAgentFromUpload.ts'
test='web/packages/studio/src/api/agents/useCreateAgentFromUpload.test.ts'
printf '%s\n' '--- target implementation ---'
cat -n "$target"
printf '%s\n' '--- focused tests ---'
cat -n "$test"
printf '%s\n' '--- SDK file inventory ---'
git ls-files 'web/packages/sdk/*' | sed -n '1,160p'
printf '%s\n' '--- generated API and error declarations ---'
rg -n -C4 --glob '*.ts' \
'class .*Error|interface .*Error|type .*Error|statusCode|response\??:|HttpError|ApiError|FetchError|throw new|filesRetrieveFileset|agentsGetAgent' \
web/packages/sdk | sed -n '1,260p'Repository: NVIDIA-NeMo/nemo-platform Length of output: 23143 🏁 Script executed: #!/bin/bash
set -eu
printf '%s\n' '--- generated fetcher template ---'
cat -n web/packages/sdk/orval/templates/customFetcherTemplate.ts | sed -n '1,115p'
printf '%s\n' '--- existing not-found helper ---'
cat -n web/packages/studio/src/routes/agents/AgentMonitorRoute/utils.ts | sed -n '1,35p'
printf '%s\n' '--- generated output/config references ---'
rg -n -C3 --glob '*.ts' --glob '*.json' \
'output:|target:|generated/platform/api|customFetch|AxiosError|includeHttpResponseReturnType' \
web/packages/sdk web/packages | sed -n '1,180p'
printf '%s\n' '--- read-only behavioral verifier ---'
python3 - <<'PY'
from dataclasses import dataclass
`@dataclass`
class Outcome:
retrieve_error: object | None = None
agent_error: object | None = None
replace: bool = False
def current_claim(outcome):
# Mirrors claimFileset's catch behavior.
if outcome.retrieve_error is not None:
return "create"
# Mirrors agentExists's catch behavior.
if outcome.agent_error is not None:
exists = False
else:
exists = True
if exists:
return "conflict"
if not outcome.replace:
return "orphan"
return "delete_then_create"
def status_aware_claim(outcome):
def is_404(error):
return (
isinstance(error, dict)
and (
error.get("status") == 404
or isinstance(error.get("response"), dict)
and error["response"].get("status") == 404
)
)
if outcome.retrieve_error is not None and not is_404(outcome.retrieve_error):
return "rethrow_retrieve"
if outcome.retrieve_error is not None:
return "create"
if outcome.agent_error is not None and not is_404(outcome.agent_error):
return "rethrow_agent"
exists = outcome.agent_error is None
if exists:
return "conflict"
if not outcome.replace:
return "orphan"
return "delete_then_create"
cases = [
Outcome(retrieve_error={"response": {"status": 503}}, replace=True),
Outcome(agent_error={"response": {"status": 503}}, replace=True),
Outcome(retrieve_error={"response": {"status": 404}}, replace=False),
Outcome(agent_error={"response": {"status": 404}}, replace=True),
]
for case in cases:
print(case, "current=", current_claim(case), "status_aware=", status_aware_claim(case))
# A successful preflight does not reserve the name. Another writer can create the
# fileset before this call's create request, causing rollback to target that writer's fileset.
steps = ["retrieve absent", "concurrent create succeeds", "our create fails", "rollback deletes by name"]
print("race=", " -> ".join(steps))
PYRepository: NVIDIA-NeMo/nemo-platform Length of output: 19986 🏁 Script executed: #!/bin/bash
set -eu
printf '%s\n' '--- generated fetcher template ---'
cat -n web/packages/sdk/orval/templates/customFetcherTemplate.ts | sed -n '1,115p'
printf '%s\n' '--- existing not-found helper ---'
cat -n web/packages/studio/src/routes/agents/AgentMonitorRoute/utils.ts | sed -n '1,35p'
printf '%s\n' '--- generated output/config references ---'
rg -n -C3 --glob '*.ts' --glob '*.json' \
'output:|target:|generated/platform/api|customFetch|AxiosError|includeHttpResponseReturnType' \
web/packages/sdk web/packages | sed -n '1,180p'
printf '%s\n' '--- read-only behavioral verifier ---'
python3 - <<'PY'
from dataclasses import dataclass
`@dataclass`
class Outcome:
retrieve_error: object | None = None
agent_error: object | None = None
replace: bool = False
def current_claim(outcome):
if outcome.retrieve_error is not None:
return "create"
if outcome.agent_error is not None:
exists = False
else:
exists = True
if exists:
return "conflict"
if not outcome.replace:
return "orphan"
return "delete_then_create"
def status_aware_claim(outcome):
def is_404(error):
return (
isinstance(error, dict)
and (
error.get("status") == 404
or (
isinstance(error.get("response"), dict)
and error["response"].get("status") == 404
)
)
)
if outcome.retrieve_error is not None and not is_404(outcome.retrieve_error):
return "rethrow_retrieve"
if outcome.retrieve_error is not None:
return "create"
if outcome.agent_error is not None and not is_404(outcome.agent_error):
return "rethrow_agent"
exists = outcome.agent_error is None
if exists:
return "conflict"
if not outcome.replace:
return "orphan"
return "delete_then_create"
cases = [
Outcome(retrieve_error={"response": {"status": 503}}, replace=True),
Outcome(agent_error={"response": {"status": 503}}, replace=True),
Outcome(retrieve_error={"response": {"status": 404}}, replace=False),
Outcome(agent_error={"response": {"status": 404}}, replace=True),
]
for case in cases:
print(case, "current=", current_claim(case), "status_aware=", status_aware_claim(case))
steps = ["retrieve absent", "concurrent create succeeds", "our create fails", "rollback deletes by name"]
print("race=", " -> ".join(steps))
PYRepository: NVIDIA-NeMo/nemo-platform Length of output: 19986 🏁 Script executed: #!/bin/bash
set -eu
python3 - <<'PY'
def outcome(retrieve_error=None, agent_error=None, replace=False):
# Current claimFileset behavior.
if retrieve_error is not None:
current = "create"
elif agent_error is not None:
current = "delete_then_create" if replace else "orphan"
else:
current = "conflict"
def is_404(error):
return (
isinstance(error, dict)
and (
error.get("status") == 404
or (
isinstance(error.get("response"), dict)
and error["response"].get("status") == 404
)
)
)
# Behavior after rethrowing non-404 errors.
if retrieve_error is not None and not is_404(retrieve_error):
status_aware = "rethrow_retrieve"
elif retrieve_error is not None:
status_aware = "create"
elif agent_error is not None and not is_404(agent_error):
status_aware = "rethrow_agent"
elif agent_error is None:
status_aware = "conflict"
else:
status_aware = "delete_then_create" if replace else "orphan"
return current, status_aware
cases = [
("retrieve 503 with replacement", {"response": {"status": 503}}, None, True),
("agent 503 with replacement", None, {"response": {"status": 503}}, True),
("retrieve 404", {"response": {"status": 404}}, None, False),
("agent 404 with replacement", None, {"response": {"status": 404}}, True),
]
for name, retrieve_error, agent_error, replace in cases:
current, status_aware = outcome(retrieve_error, agent_error, replace)
print(name + ": current=" + current + ", status_aware=" + status_aware)
print(
"rollback race: retrieve 404 -> concurrent fileset creation -> "
"our filesCreateFileset fails -> rollback calls filesDeleteFileset by name"
)
PYRepository: NVIDIA-NeMo/nemo-platform Length of output: 597 🏁 Script executed: #!/bin/bash
set -eu
python3 - <<'PY'
def outcome(retrieve_error=None, agent_error=None, replace=False):
if retrieve_error is not None:
current = "create"
elif agent_error is not None:
current = "delete_then_create" if replace else "orphan"
else:
current = "conflict"
def is_404(error):
return (
isinstance(error, dict)
and (
error.get("status") == 404
or (
isinstance(error.get("response"), dict)
and error["response"].get("status") == 404
)
)
)
if retrieve_error is not None and not is_404(retrieve_error):
status_aware = "rethrow_retrieve"
elif retrieve_error is not None:
status_aware = "create"
elif agent_error is not None and not is_404(agent_error):
status_aware = "rethrow_agent"
elif agent_error is None:
status_aware = "conflict"
else:
status_aware = "delete_then_create" if replace else "orphan"
return current, status_aware
cases = [
("retrieve 503 with replacement", {"response": {"status": 503}}, None, True),
("agent 503 with replacement", None, {"response": {"status": 503}}, True),
("retrieve 404", {"response": {"status": 404}}, None, False),
("agent 404 with replacement", None, {"response": {"status": 404}}, True),
]
for name, retrieve_error, agent_error, replace in cases:
current, status_aware = outcome(retrieve_error, agent_error, replace)
print(name + ": current=" + current + ", status_aware=" + status_aware)
print(
"rollback race: retrieve 404 -> concurrent fileset creation -> "
"our filesCreateFileset fails -> rollback calls filesDeleteFileset by name"
)
PYRepository: NVIDIA-NeMo/nemo-platform Length of output: 597 Preserve fileset ownership during claim and rollback.
🤖 Prompt for AI Agents |
||
|
|
||
| const agentExists = async (workspace: string, agentName: string): Promise<boolean> => { | ||
| try { | ||
| await agentsGetAgent(workspace, agentName); | ||
| return true; | ||
| } catch { | ||
| return false; | ||
| } | ||
| }; | ||
|
|
||
| // One request per file, so a 500-file agent is 500 round trips. Run a bounded number at | ||
| // once: unbounded Promise.all would queue them all against the browser's per-host limit | ||
| // and lose the first error behind hundreds of in-flight requests. | ||
| const UPLOAD_CONCURRENCY = 6; | ||
|
|
||
| const uploadEntries = async ( | ||
| workspace: string, | ||
| filesetName: string, | ||
| entries: UploadAgentEntry[] | ||
| ): Promise<void> => { | ||
| const queue = [...entries]; | ||
| const worker = async (): Promise<void> => { | ||
| for (let entry = queue.shift(); entry; entry = queue.shift()) { | ||
| const blob = new Blob([await entry.file.arrayBuffer()], { type: 'application/octet-stream' }); | ||
| await filesUploadFile(workspace, filesetName, entry.path, blob); | ||
| } | ||
| }; | ||
|
|
||
| await Promise.all( | ||
| Array.from({ length: Math.min(UPLOAD_CONCURRENCY, entries.length) }, () => worker()) | ||
| ); | ||
| }; | ||
|
|
||
| const rollback = async (workspace: string, filesetName: string): Promise<void> => { | ||
| await filesDeleteFileset(workspace, filesetName).catch(() => undefined); | ||
| }; | ||
|
|
||
| export type UseCreateAgentFromUploadOptions = Omit< | ||
| UseMutationOptions<Agent, Error, CreateAgentFromUploadParams>, | ||
| 'mutationFn' | ||
| >; | ||
|
|
||
| export const useCreateAgentFromUpload = (options?: UseCreateAgentFromUploadOptions) => | ||
| useMutation({ ...options, mutationFn: createAgentFromUpload }); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import { z } from 'zod'; | ||
|
|
||
| export const AGENT_CONFIG_FILENAME = 'agent.yaml'; | ||
|
|
||
| export const FABRIC_CONFIG_FORMAT = 'nemo-agents-spec-v1'; | ||
|
|
||
| // Container staging skips this file, so its bytes never reach a deployment. | ||
| export const AGENT_SPEC_FILENAME = 'AGENT-SPEC.md'; | ||
|
|
||
| // Mirrors MAX_AGENT_SPEC_STAGED_BYTES / _FILES; the platform only enforces them at deploy. | ||
| export const MAX_AGENT_SPEC_BYTES = 900_000; | ||
| export const MAX_AGENT_SPEC_FILES = 500; | ||
|
|
||
| // A directory picker hands over every descendant, so a mistaken pick can arrive with | ||
| // hundreds of thousands of entries. Reject on the raw count before mapping, filtering or | ||
| // sorting any of them — the ignore list cannot be applied without touching every entry. | ||
| export const MAX_PICKED_FILES = 1_000; | ||
|
|
||
| export const IGNORED_DIRECTORIES = new Set([ | ||
| '__pycache__', | ||
| '.git', | ||
| '.venv', | ||
| 'venv', | ||
| 'node_modules', | ||
| '.mypy_cache', | ||
| '.pytest_cache', | ||
| '.ruff_cache', | ||
| '.idea', | ||
| '.vscode', | ||
| ]); | ||
|
|
||
| export const IGNORED_FILENAMES = new Set(['.DS_Store', 'Thumbs.db']); | ||
|
|
||
| export const IGNORED_EXTENSIONS = ['.pyc', '.pyo', '.pyd', '.so', '.dylib', '.dll']; | ||
|
|
||
| export const uploadAgentFormSchema = z.object({ | ||
| name: z | ||
| .string() | ||
| .trim() | ||
| .min(1, 'Name is required') | ||
| .regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/, 'Use lowercase letters, numbers, and hyphens'), | ||
| }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Rollback can delete a fileset this call did not create.
filesCreateFilesetsits inside the try block. If it fails because the fileset already exists, line 79 deletes that pre-existing fileset. The comment on lines 48-50 assumes the existence check above is reliable; it is not, and a concurrent create still races it.Roll back only what this call created.
Proposed fix
📝 Committable suggestion
🤖 Prompt for AI Agents