File size: 5,211 Bytes
5f0975b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { createRepo, uploadFiles } from "@huggingface/hub";
import { HF_HUB } from "./config";
import type { HardwareFlavor } from "./hardware";
import type { Workspace } from "./agent/workspace";

const execFileAsync = promisify(execFile);

export interface DeployResult {
  url: string;
  repoId: string;
  hardware: string;
  hardwareRequested: boolean;
  method: "git" | "upload";
}

export function spaceRemoteUrl(owner: string, spaceName: string, token: string): string {
  return `https://${encodeURIComponent(owner)}:${token}@huggingface.co/spaces/${owner}/${spaceName}`;
}

async function git(workspace: Workspace, args: string[]): Promise<string> {
  const { stdout } = await execFileAsync("git", args, {
    cwd: workspace.dir,
    maxBuffer: 8_000_000,
    timeout: 120_000,
  });
  return stdout;
}

async function requestHardware(
  repoId: string,
  token: string,
  hardware: HardwareFlavor,
): Promise<boolean> {
  if (hardware === "cpu-basic") return false;
  try {
    const res = await fetch(`${HF_HUB}/api/spaces/${repoId}/hardware`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ flavor: hardware }),
    });
    return res.ok;
  } catch {
    return false;
  }
}

/** Deploy the workspace to the user's Space. Ensures the repo exists, then
 *  pushes via git (preferred — the agent can also `git push` manually), falling
 *  back to the Hub upload API if git push fails. */
export async function deployWorkspace(opts: {
  accessToken: string;
  owner: string;
  spaceName: string;
  workspace: Workspace;
  isPrivate: boolean;
  hardware: HardwareFlavor;
}): Promise<DeployResult> {
  const repoId = `${opts.owner}/${opts.spaceName}`;
  const repo = { type: "space" as const, name: repoId };

  try {
    await createRepo({
      repo,
      accessToken: opts.accessToken,
      visibility: opts.isPrivate ? "private" : "public",
      sdk: "gradio",
    });
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    if (!/already (exists|created)/i.test(message)) throw err;
  }

  let method: "git" | "upload" = "git";
  try {
    const remote = spaceRemoteUrl(opts.owner, opts.spaceName, opts.accessToken);
    await git(opts.workspace, ["remote", "remove", "space"]).catch(() => {});
    await git(opts.workspace, ["remote", "add", "space", remote]);
    await git(opts.workspace, ["add", "-A"]);
    // Commit; ignore "nothing to commit" so re-deploys still push.
    await git(opts.workspace, [
      "-c",
      "user.name=mfn",
      "-c",
      "user.email=mfn@example.com",
      "commit",
      "-m",
      "Deploy via SpaceFactory",
    ]).catch(() => {});
    await git(opts.workspace, ["push", "--force", "space", "HEAD:main"]);
  } catch {
    // Fallback: Hub upload API.
    method = "upload";
    await uploadFiles({
      repo,
      accessToken: opts.accessToken,
      files: opts.workspace.toFiles().map((f) => ({
        path: f.path,
        content: new Blob([f.content]),
      })),
      commitTitle: "Deploy via SpaceFactory",
    });
  }

  const hardwareRequested = await requestHardware(
    repoId,
    opts.accessToken,
    opts.hardware,
  );

  return {
    url: `${HF_HUB}/spaces/${repoId}`,
    repoId,
    hardware: opts.hardware,
    hardwareRequested,
    method,
  };
}

export interface SpaceRuntime {
  stage: string;
  hardware?: string;
}

export async function getSpaceRuntime(
  repoId: string,
  token: string,
): Promise<SpaceRuntime> {
  const res = await fetch(`${HF_HUB}/api/spaces/${repoId}`, {
    headers: { Authorization: `Bearer ${token}` },
  });
  if (!res.ok) throw new Error(`Could not read Space ${repoId} (HTTP ${res.status})`);
  const data = (await res.json()) as {
    runtime?: { stage?: string; hardware?: { current?: string } };
  };
  return {
    stage: data.runtime?.stage ?? "UNKNOWN",
    hardware: data.runtime?.hardware?.current,
  };
}

export async function fetchSpaceLogs(
  repoId: string,
  token: string,
  kind: "build" | "run",
  maxLines = 120,
): Promise<string> {
  const res = await fetch(`${HF_HUB}/api/spaces/${repoId}/logs/${kind}`, {
    headers: { Authorization: `Bearer ${token}`, Accept: "text/event-stream" },
    signal: AbortSignal.timeout(30_000),
  });
  if (!res.ok) throw new Error(`Could not fetch ${kind} logs (HTTP ${res.status})`);
  const text = await res.text();
  const lines: string[] = [];
  for (const line of text.split("\n")) {
    if (!line.startsWith("data:")) continue;
    try {
      const data = JSON.parse(line.slice(5).trim()) as { data?: string };
      if (data.data != null) lines.push(String(data.data).replace(/\n$/, ""));
    } catch {
      // ignore keepalives / partial frames
    }
  }
  return lines.slice(-maxLines).join("\n") || "(no logs yet)";
}

const TERMINAL_STAGES = new Set([
  "RUNNING",
  "BUILD_ERROR",
  "RUNTIME_ERROR",
  "CONFIG_ERROR",
  "ERROR",
  "APP_STARTING_ERROR",
  "DELETING",
  "PAUSED",
]);

export function isTerminalStage(stage: string): boolean {
  return TERMINAL_STAGES.has(stage);
}