Spaces:
Paused
Paused
File size: 15,430 Bytes
ba0ce97 6f07329 ba0ce97 fffab5b ba0ce97 6f07329 ba0ce97 6f07329 ba0ce97 fffab5b ba0ce97 6f07329 ba0ce97 6f07329 ba0ce97 fffab5b ba0ce97 6f07329 ba0ce97 6f07329 ba0ce97 6f07329 ba0ce97 6f07329 ba0ce97 6f07329 ba0ce97 6f07329 ba0ce97 6f07329 ba0ce97 6f07329 ba0ce97 6f07329 ba0ce97 6f07329 ba0ce97 6f07329 ba0ce97 fffab5b ba0ce97 fffab5b ba0ce97 fffab5b ba0ce97 6f07329 ba0ce97 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 | <script lang="ts">
import { onDestroy, untrack } from "svelte";
import { base } from "$app/paths";
import type { Model } from "$lib/types/Model";
import type { WorkspacePolicy } from "$lib/types/Workspace";
import {
isAgentCompatibleModel,
type AgentRepositoryKind,
type AgentRepositoryType,
type AgentThinkingLevel,
type AgentWorkspaceSetupValue,
} from "./types";
interface Props {
models: Model[];
initialValue: AgentWorkspaceSetupValue;
onsave?: (value: AgentWorkspaceSetupValue) => void | Promise<void>;
ondraftchange?: (value: AgentWorkspaceSetupValue) => void;
oncancel?: () => void;
}
let { models, initialValue, onsave, ondraftchange, oncancel }: Props = $props();
const initial = untrack(() => initialValue);
const initialModels = untrack(() => models.filter(isAgentCompatibleModel));
let repoKind = $state<AgentRepositoryKind>(initial.repo.kind);
let hfRef = $state(initial.repo.kind === "hf" ? (initial.repo.ref ?? "") : "");
let gitRef = $state(initial.repo.kind === "git" ? (initial.repo.ref ?? "") : "");
let repoType = $state<AgentRepositoryType>(initial.repo.repoType ?? "space");
let branch = $state(initial.branch || "main");
let flavor = $state<"cpu-basic">("cpu-basic");
let model = $state(
initialModels.some((entry) => entry.id === initial.model)
? initial.model
: (initialModels[0]?.id ?? "")
);
let thinkingLevel = $state<AgentThinkingLevel>(initial.thinkingLevel || "medium");
let policy = $state<WorkspacePolicy>(initial.policy);
let validationError = $state("");
let saving = $state(false);
let repositoryOptions = $state<Array<{ ref: string; private: boolean }>>([]);
let repositoriesLoading = $state(false);
let repositoriesLoadingFor = $state<AgentRepositoryType | undefined>();
let repositoriesLoadedFor = $state<AgentRepositoryType | undefined>();
let repositoriesError = $state("");
let repositoryLoadController: AbortController | undefined;
let availableModels = $derived(models.filter(isAgentCompatibleModel));
const sourceOptions: Array<{
value: AgentRepositoryKind;
title: string;
description: string;
}> = [
{
value: "blank",
title: "Blank workspace",
description: "Start from your prompt with an empty working directory.",
},
{
value: "hf",
title: "Hugging Face repo",
description: "Work on one of your Spaces, models, or datasets.",
},
{
value: "git",
title: "Git URL",
description: "Clone a repository using a public HTTPS URL.",
},
];
const thinkingOptions: Array<{ value: AgentThinkingLevel; label: string }> = [
{ value: "off", label: "Off" },
{ value: "minimal", label: "Minimal" },
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra high" },
{ value: "max", label: "Maximum" },
];
const policyOptions: Array<{
value: WorkspacePolicy;
label: string;
description: string;
}> = [
{
value: "auto",
label: "Auto",
description:
"Allow local edits and commands; ask before sensitive reads or external actions.",
},
{
value: "ask",
label: "Ask more",
description: "Ask before every file change or shell command.",
},
{
value: "read-only",
label: "Read-only",
description: "Block all file changes and shell commands; per-call overrides are disabled.",
},
];
function validate(): string | undefined {
if (!model || !availableModels.some((entry) => entry.id === model)) {
return "Choose an available Agent model.";
}
const normalizedBranch = branch.trim();
if (!normalizedBranch) return "Enter a branch name.";
if (
normalizedBranch.startsWith("-") ||
normalizedBranch.startsWith("/") ||
normalizedBranch.endsWith("/") ||
normalizedBranch.endsWith(".") ||
normalizedBranch.endsWith(".lock") ||
normalizedBranch.includes("..") ||
normalizedBranch.includes("@{") ||
normalizedBranch.includes("//") ||
// Git rejects ASCII control characters in branch names.
// eslint-disable-next-line no-control-regex
/[~^:?*[\\\x00-\x20\x7f]/.test(normalizedBranch)
) {
return "Enter a valid Git branch name.";
}
if (
repoKind === "hf" &&
!/^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/.test(hfRef.trim())
) {
return "Enter a Hugging Face repository as namespace/name.";
}
if (repoKind === "git") {
try {
const url = new URL(gitRef.trim());
if (
url.protocol !== "https:" ||
!url.hostname ||
url.username ||
url.password ||
url.search ||
url.hash
) {
throw new Error("invalid URL");
}
} catch {
return "Enter a public credential-free HTTPS Git URL.";
}
}
return undefined;
}
function workspaceValue(normalize: boolean): AgentWorkspaceSetupValue {
const refValue = repoKind === "hf" ? hfRef : repoKind === "git" ? gitRef : undefined;
const ref = normalize ? refValue?.trim() : refValue;
return {
repo: {
kind: repoKind,
...(ref ? { ref } : {}),
...(repoKind === "hf" ? { repoType } : {}),
},
branch: normalize ? branch.trim() : branch,
flavor,
model,
thinkingLevel,
policy,
};
}
let draftEffectInitialized = false;
$effect(() => {
const value = workspaceValue(false);
if (!draftEffectInitialized) {
draftEffectInitialized = true;
return;
}
ondraftchange?.(value);
});
function cancel() {
ondraftchange?.(workspaceValue(false));
oncancel?.();
}
async function submit() {
const error = validate();
if (error) {
validationError = error;
return;
}
validationError = "";
saving = true;
try {
await onsave?.(workspaceValue(true));
} catch (error) {
validationError =
error instanceof Error ? error.message : "Could not save the Agent workspace.";
} finally {
saving = false;
}
}
async function loadRepositories(force = false) {
const requestedType = repoType;
if (
!force &&
(repositoriesLoadedFor === requestedType ||
(repositoriesLoading && repositoriesLoadingFor === requestedType))
) {
return;
}
repositoryLoadController?.abort();
const controller = new AbortController();
repositoryLoadController = controller;
repositoriesLoading = true;
repositoriesLoadingFor = requestedType;
repositoriesError = "";
repositoryOptions = [];
try {
const response = await fetch(
`${base}/api/agent/repositories?type=${encodeURIComponent(requestedType)}&limit=50`,
{ signal: controller.signal }
);
if (!response.ok) {
let message = "Could not load your Hugging Face repositories.";
try {
const failure = (await response.json()) as { message?: unknown };
if (typeof failure.message === "string" && failure.message.trim()) {
message = failure.message;
}
} catch {
// Keep the stable fallback for non-JSON gateway responses.
}
throw new Error(message);
}
const data = (await response.json()) as {
repositories?: Array<{ ref?: unknown; private?: unknown }>;
};
if (controller.signal.aborted || repoType !== requestedType) return;
repositoryOptions = (data.repositories ?? []).flatMap((repository) =>
typeof repository.ref === "string"
? [{ ref: repository.ref, private: repository.private === true }]
: []
);
repositoriesLoadedFor = requestedType;
} catch (error) {
if (controller.signal.aborted || repoType !== requestedType) return;
repositoriesError =
error instanceof Error ? error.message : "Could not load your Hugging Face repositories.";
} finally {
if (repositoryLoadController === controller) {
repositoryLoadController = undefined;
repositoriesLoading = false;
repositoriesLoadingFor = undefined;
}
}
}
onDestroy(() => repositoryLoadController?.abort());
const fieldClass =
"min-h-11 w-full rounded-xl border border-gray-200 bg-white px-3.5 py-2 text-sm text-gray-900 outline-hidden focus:border-blue-500 focus:ring-2 focus:ring-blue-500/25 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-100";
</script>
<form
class="flex w-full flex-col gap-5 p-5 sm:p-6"
aria-labelledby="agent-workspace-setup-title"
onsubmit={(event) => {
event.preventDefault();
submit();
}}
>
<header class="pr-8">
<h2
id="agent-workspace-setup-title"
class="text-xl font-semibold text-gray-900 dark:text-gray-100"
>
Set up an Agent workspace
</h2>
<p class="mt-1 text-sm leading-relaxed text-gray-500 dark:text-gray-400">
Choose where the agent will work. The sandbox starts only after you send your prompt.
</p>
</header>
<fieldset class="flex flex-col gap-2">
<legend class="mb-1 text-sm font-medium text-gray-800 dark:text-gray-200"
>Workspace source</legend
>
<div class="grid gap-2 sm:grid-cols-3">
{#each sourceOptions as option}
<label
class="min-h-24 cursor-pointer rounded-xl border p-3 outline-hidden transition-colors focus-within:border-blue-500 focus-within:ring-2 focus-within:ring-blue-500/25 {repoKind ===
option.value
? 'border-blue-500 bg-blue-50/70 dark:border-blue-500 dark:bg-blue-950/25'
: 'border-gray-200 bg-white hover:border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:hover:border-gray-600'}"
>
<span class="flex items-start gap-2.5">
<input
type="radio"
name="agent-workspace-source"
value={option.value}
bind:group={repoKind}
onchange={() => (validationError = "")}
class="mt-0.5 size-4 shrink-0 accent-blue-600"
/>
<span>
<span class="block text-sm font-semibold text-gray-900 dark:text-gray-100">
{option.title}
</span>
<span class="mt-1 block text-xs leading-relaxed text-gray-500 dark:text-gray-400">
{option.description}
</span>
</span>
</span>
</label>
{/each}
</div>
</fieldset>
{#if repoKind === "hf"}
<div class="grid gap-3 sm:grid-cols-[9rem_1fr]">
<label class="flex flex-col gap-1.5">
<span class="text-sm font-medium text-gray-800 dark:text-gray-200">Repository type</span>
<select
bind:value={repoType}
class={fieldClass}
onchange={() => void loadRepositories(true)}
>
<option value="space">Space</option>
<option value="model">Model</option>
<option value="dataset">Dataset</option>
</select>
</label>
<label class="flex min-w-0 flex-col gap-1.5">
<span class="text-sm font-medium text-gray-800 dark:text-gray-200"
>Hugging Face repository</span
>
<input
type="text"
bind:value={hfRef}
required
list="agent-hf-repositories"
autocomplete="off"
placeholder="username/my-space"
class={fieldClass}
onfocus={() => void loadRepositories()}
/>
<datalist id="agent-hf-repositories">
{#each repositoryOptions as repository (repository.ref)}
<option value={repository.ref}>{repository.private ? "Private" : "Public"}</option>
{/each}
</datalist>
{#if repositoriesError}
<span class="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs" role="status">
<span class="text-amber-700 dark:text-amber-300">{repositoriesError}</span>
<button
type="button"
class="font-medium text-blue-600 hover:underline dark:text-blue-400"
onclick={() => void loadRepositories(true)}>Retry</button
>
<span class="text-gray-500 dark:text-gray-400">or enter namespace/name manually</span>
</span>
{:else}
<span class="text-xs text-gray-500 dark:text-gray-400">
{repositoriesLoading
? "Loading your repositories…"
: repositoryOptions.length
? `${repositoryOptions.length} recent repositories available`
: "Choose from your HF assets or enter namespace/name"}
</span>
{/if}
</label>
</div>
{:else if repoKind === "git"}
<label class="flex flex-col gap-1.5">
<span class="text-sm font-medium text-gray-800 dark:text-gray-200">HTTPS Git URL</span>
<input
type="url"
bind:value={gitRef}
required
inputmode="url"
autocomplete="url"
placeholder="https://github.com/org/repository.git"
class={fieldClass}
/>
</label>
{/if}
<div class="grid gap-3 sm:grid-cols-2">
<label class="flex flex-col gap-1.5">
<span class="text-sm font-medium text-gray-800 dark:text-gray-200">Working branch</span>
<input type="text" bind:value={branch} required autocomplete="off" class={fieldClass} />
</label>
<label class="flex flex-col gap-1.5">
<span class="text-sm font-medium text-gray-800 dark:text-gray-200">Hardware</span>
<select bind:value={flavor} class={fieldClass}>
<option value="cpu-basic">CPU Basic</option>
</select>
<span class="text-xs text-gray-500 dark:text-gray-400">Fast-starting CPU sandbox</span>
</label>
</div>
<label class="flex flex-col gap-1.5">
<span class="text-sm font-medium text-gray-800 dark:text-gray-200">Approval policy</span>
<select
bind:value={policy}
class={fieldClass}
aria-label="Approval policy"
aria-describedby="agent-policy-description"
>
{#each policyOptions as option (option.value)}
<option value={option.value}>{option.label}</option>
{/each}
</select>
<span id="agent-policy-description" class="text-xs text-gray-500 dark:text-gray-400">
{policyOptions.find((option) => option.value === policy)?.description}
</span>
</label>
<div class="grid gap-3 sm:grid-cols-2">
<label class="flex min-w-0 flex-col gap-1.5">
<span class="text-sm font-medium text-gray-800 dark:text-gray-200">Agent model</span>
<select bind:value={model} class={fieldClass} aria-label="Agent model">
{#each availableModels as option (option.id)}
<option value={option.id}>{option.displayName || option.name || option.id}</option>
{/each}
{#if !availableModels.length}
<option value="" disabled>No compatible Agent models</option>
{/if}
</select>
</label>
<label class="flex flex-col gap-1.5">
<span class="text-sm font-medium text-gray-800 dark:text-gray-200">Thinking level</span>
<select bind:value={thinkingLevel} class={fieldClass} aria-label="Thinking level">
{#each thinkingOptions as option (option.value)}
<option value={option.value}>{option.label}</option>
{/each}
</select>
</label>
</div>
{#if validationError}
<p
role="alert"
class="rounded-xl border border-red-300/70 bg-red-50 px-3.5 py-2.5 text-sm text-red-700 dark:border-red-500/40 dark:bg-red-500/10 dark:text-red-300"
>
{validationError}
</p>
{/if}
<footer class="flex flex-col-reverse gap-2 pt-1 sm:flex-row sm:justify-end">
<button
type="button"
disabled={saving}
class="min-h-11 rounded-xl border border-gray-300 bg-white px-4 text-sm font-medium text-gray-800 outline-hidden hover:bg-gray-50 focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100 dark:hover:bg-gray-700 dark:focus-visible:ring-offset-gray-800"
onclick={cancel}
>
Cancel
</button>
<button
type="submit"
disabled={saving}
class="min-h-11 rounded-xl bg-gray-900 px-4 text-sm font-semibold text-white outline-hidden hover:bg-black focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-white dark:focus-visible:ring-offset-gray-800"
>
{saving ? "Saving workspace…" : "Use this workspace"}
</button>
</footer>
</form>
|