cloudgpu-mcp 0.7.0 → 0.9.0

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.
package/README.md CHANGED
@@ -10,6 +10,14 @@ It is a local (stdio) MCP server. It works with any MCP client that can start on
10
10
 
11
11
  ## Install
12
12
 
13
+ For the browser-approval flow, add this local MCP server **without** an API key first:
14
+
15
+ ```bash
16
+ claude mcp add cloudgpu -- npx -y cloudgpu-mcp
17
+ ```
18
+
19
+ For another stdio client, use `command: "npx"` and `args: ["-y", "cloudgpu-mcp"]`; omit the environment key. Ask the Agent to call `connect_account`, open its returned CloudGPU link yourself, approve the account, spending limit, GPU concurrency and expiry, then let it call `finish_connect`. Never paste your password or API key into the conversation. The client must support and configure MCP; the approval link alone does not install tools in an arbitrary assistant. Existing API-key setup remains available below.
20
+
13
21
  1. Create an API key at [cloudgpu.app/api](https://cloudgpu.app/api) and add a prepaid balance (card or USDT).
14
22
  2. Add the server to your client. Node.js 18 or newer is required. The key goes in the environment variable `CLOUDGPU_API_KEY`.
15
23
 
@@ -162,7 +170,7 @@ The server also provides a `train_on_cloudgpu` prompt.
162
170
 
163
171
  The key also works with the OpenAI-compatible API at `https://cloudgpu.app/v1`. Call `list_models` (or `GET /v1/models`) to see the available model IDs. Model prices are on [cloudgpu.app/api](https://cloudgpu.app/api).
164
172
 
165
- ## Optional persistent files and Workspaces (development)
173
+ ## Optional persistent files and Workspaces
166
174
 
167
175
  These tools require persistent storage to be explicitly enabled on the server;
168
176
  they return `storage_not_enabled` until it is ready. Discover server capabilities
@@ -262,6 +270,21 @@ Use `list_workspace_instances`, then `get_workspace_application` with the saved
262
270
 
263
271
  Repeated application of the same version to the same instance returns the existing result, including user edits after success. On `needs_attention`, `failed` or `conflict`, inspect the result rather than automatically retrying. A new saved version creates a separate directory. The feature must be enabled by the server; unavailable storage does not disable ordinary GPU rental or Job tools.
264
272
 
273
+ ### D13 model preparation (0.8.0)
274
+
275
+ Version 0.8.0 adds three preparation tools; check both the installed tools and live backend capabilities before using them:
276
+
277
+ - `resolve_model_reference`: resolve a public Hugging Face branch/tag and explicit filenames to a commit-addressed manifest, sizes and available LFS SHA-256. No weights are hosted by CloudGPU. To enable verified use of the instance’s existing mirror, up to 8 selected JSON configuration files of at most 64 KiB each may be read from the pinned origin and SHA-256 hashed, within a shared 15-second deadline. Weight files are not fetched by this resolver. Private/gated models are refused.
278
+ - `prepare_job_rerun`: read parameters from a successful owned Job. No new GPU, old quote or old idempotency key. Obtain a fresh quote and explicit budget approval before `run_job`.
279
+ - `prepare_model_deployment`: prepare a setup script for the **existing ComfyUI template**, with direct model downloads and optional UI-format workflow JSON. Use the model name as a category (e.g. `checkpoints`, `loras`, `vae`). Review and approve the script before deploying. Custom nodes are not installed and workflows are not executed automatically. This is preparation support, not a real-GPU-validated template catalog.
280
+
281
+ `run_job` accepts optional `model_references`. A supporting backend is checked before submission; an old backend cannot silently ignore the references. Models are downloaded after Workspace restoration, into `$CLOUDGPU_MODEL_DIR/<name>/<path>`. Download time consumes the same rental budget. File size/checksum, disk and download timeout failures stop the Job and follow the existing release-evidence flow, without provisioning retries. The weights disappear with the GPU unless the user separately persists them; no R2 model cache is added.
282
+
283
+ Agent-first interaction: ask your Agent to run the project again; no separate web Job console or model JSON form is required. Team-authorized keys spend the selected team wallet; personal funds are separate.
284
+
285
+ Suggested workflow: resolve references → review model license/files and compatible environment → get quote → obtain explicit budget/time/GPU approval → run once with a stable idempotency key → poll status/cost → prepare a rerun only after success. Output collection remains the user's command's responsibility.
286
+
287
+ See [`examples/pinned-model-job.mjs`](examples/pinned-model-job.mjs) for a default **dry-run** REST example. Do not enable submission during routine tests. Bounded internal acceptance covered actual MCP, candidate HTTP authentication/MySQL, independent model hashes, two GPU runs and release. A separate ComfyUI image accepted model links and a workflow file. This does not validate arbitrary custom nodes or graph execution.
265
288
 
266
289
  ## Small Job output snapshots and diagnosis (0.7.0)
267
290
 
@@ -272,3 +295,13 @@ This branch adds `diagnose_job` (read-only) and `save_job_output` (explicit stor
272
295
  `diagnose_job` reports the error category, platform instance status and whether platform charges are final. It does not prove supplier release, infer that command failures are always user errors, or automatically rerun work. `needs_attention` requires resource reconciliation before a new task. A rerun requires a fresh quote, explicit approval and a new idempotency key.
273
296
 
274
297
  Registry configuration allows discovery and connect-link approval without pre-entering a key. A tool-enabled MCP client is still required; a link does not install a client or grant unlimited spending. No new fixed infrastructure or model storage is introduced.
298
+
299
+ ### Optional Job output collection (requires backend capability)
300
+
301
+ Call `run_job` with `outputs: {"files":["metrics.json"],"max_bytes":1048576}` and a command that writes to `"$CLOUDGPU_OUTPUT_DIR/metrics.json"`. Files are relative to this dedicated directory; the platform does not scan the disk. The server refuses unsupported backends rather than silently starting a Job without saving results. GPU download/execution/upload time shares the same time and spend limits.
302
+
303
+ After completion, inspect `get_job.output_collection`: only `succeeded` confirms collection. Each saved entry gives `file_id`, `sha256`, `size_bytes` and status; use existing file download tools. Partial failure may retain ready files, but is not overall success. Cancellation, budget exhaustion, instance loss or interrupted collection can prevent saving; GPU release still proceeds with no automatic re-run. Files follow the existing account quota, storage pricing and 30-day retention. `accept_storage_charges` defaults false and requires explicit user agreement to paid storage. The 10 MiB default/100 MiB maximum is a transfer bound, not a new user quota. File-name protections cannot guarantee that user-selected file contents contain no secrets.
304
+
305
+ ### Job log snapshot safety
306
+
307
+ Version 0.8.0 still has a credential-filter gap in `save_job_output`; upgrading to 0.8.0 did not fix it. The 0.9.0 candidate rejects quoted JSON credential keys, common prefixed/aliased secret fields, authorization schemes, queried/user-info URLs and bounded common escaped representations before any storage operation. Safe logs remain byte-identical. This is a conservative recognizable-pattern check, not a guarantee that arbitrary, encrypted or unknown credentials will be detected. Save only logs you know are sanitized, with explicit user approval; no actual exposure is established by this fix.
@@ -0,0 +1,22 @@
1
+ // Dry-run by default. No dependencies beyond Node and this repository's REST client.
2
+ // Example: CLOUDGPU_API_KEY=... node examples/pinned-model-job.mjs org/model main config.json
3
+ // To submit, explicitly set CGPU_SUBMIT=YES plus CGPU_GPU, CGPU_BUDGET_USD, CGPU_MAX_MINUTES,
4
+ // CGPU_COMMAND and CGPU_JOB_KEY. Reuse the SAME key only to retry this SAME submission.
5
+ import {resolveModelReference} from '../src/model-references.js';
6
+ import {CloudGpuApi} from '../src/api.js';
7
+ const [repo_id,revision='main',...files]=process.argv.slice(2);
8
+ if(!repo_id||!files.length)throw new Error('Provide repository, revision and explicit model files');
9
+ const model=await resolveModelReference({repo_id,revision,name:'model',files});
10
+ if(process.env.CGPU_SUBMIT!=='YES'){
11
+ console.log(JSON.stringify({model_references:[model],next:'Dry run only. Choose the full model file set, compatible GPU image, command, budget and time limit before explicit submission. Files will be in $CLOUDGPU_MODEL_DIR/model. No GPU created.'},null,2));
12
+ }else{
13
+ const {CGPU_GPU:gpu_model,CGPU_BUDGET_USD:budget,CGPU_MAX_MINUTES:minutes,CGPU_COMMAND:command,CGPU_JOB_KEY:key}=process.env;
14
+ if(!gpu_model||!command||!key||!(Number(budget)>0)||!Number.isInteger(Number(minutes))||Number(minutes)<1)throw new Error('Explicit GPU, command, new submission key, positive budget and integer minutes are required');
15
+ const api=new CloudGpuApi({apiKey:process.env.CLOUDGPU_API_KEY});
16
+ const quote=await api.quote({requirements:{gpu_model,gpu_count:1},estimated_duration_seconds:Number(minutes)*60,max_budget_usd:Number(budget)});
17
+ const body={gpu_model,gpu_count:1,command,max_minutes:Number(minutes),max_spend_usd:Number(budget),quote_id:quote.id,model_references:[model]};
18
+ if(!body.quote_id)throw new Error('Quote did not return quote_id; no Job submitted');
19
+ if(process.env.CGPU_WORKSPACE_VERSION)body.workspace_version_id=process.env.CGPU_WORKSPACE_VERSION;
20
+ const job=await api.createJob(body,key);
21
+ console.log(JSON.stringify({job_id:job.id,status:job.status,next:'Poll get_job until terminal; inspect release evidence and cost. To run again, prepare_job_rerun, obtain a new quote/approval, then use a NEW submission key. Output is not automatically persisted.'},null,2));
22
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cloudgpu-mcp",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "mcpName": "io.github.mrhy7176/cloudgpu-mcp",
5
5
  "description": "MCP server and command-line tool for cloudgpu.app: let Claude Code, Cursor, Cline, opencode, goose and other MCP clients (or you, from a terminal) rent a GPU per minute, run a job, fetch the results and shut it down, with spending limits the platform enforces.",
6
6
  "type": "module",
@@ -13,7 +13,8 @@
13
13
  "src",
14
14
  "rules",
15
15
  "README.md",
16
- "LICENSE"
16
+ "LICENSE",
17
+ "examples"
17
18
  ],
18
19
  "engines": {
19
20
  "node": ">=18.3"
package/src/api.js CHANGED
@@ -106,8 +106,25 @@ export class CloudGpuApi {
106
106
  // ── jobs: start a GPU, run one command, destroy the GPU (server-side) ──
107
107
  createJob(body, idempotencyKey) {
108
108
  if (!idempotencyKey) throw new Error("createJob needs an idempotency key");
109
+ if (body.outputs) return this.createOutputJob(body,idempotencyKey);
110
+ if (body.model_references?.length) return this.createModelJob(body,idempotencyKey);
109
111
  return this.request("POST", "/v1/jobs", body, { idempotencyKey });
110
112
  }
113
+ async createOutputJob(body,idempotencyKey) {
114
+ const caps=await this.request("GET","/v1/public/compute-capabilities",undefined,{noAuth:true});
115
+ if(caps.automatic_output_collection!==true || caps.storage!==true)
116
+ throw new ApiError(503,"outputs_unavailable","Automatic output collection is not enabled; no Job was submitted. Do not silently remove outputs.");
117
+ if(body.model_references?.length && caps.model_references!==true)
118
+ throw new ApiError(503,"model_references_unavailable","Pinned model loading is not enabled; no Job was submitted.");
119
+ return this.request("POST","/v1/jobs",body,{idempotencyKey});
120
+ }
121
+ async createModelJob(body,idempotencyKey) {
122
+ const caps=await this.request("GET","/v1/public/compute-capabilities",undefined,{noAuth:true});
123
+ if(caps.model_references!==true) throw new ApiError(503,"model_references_unavailable","Backend has not enabled pinned model loading; no Job was submitted.");
124
+ return this.request("POST", "/v1/jobs", body, { idempotencyKey });
125
+ }
126
+ prepareModelDeployment(body) { return this.request("POST", "/v1/jobs/prepare-model-deployment", body); }
127
+ jobRerunSpec(id) { return this.request("GET", `/v1/jobs/${encodeURIComponent(id)}/rerun-spec`); }
111
128
  job(id) {
112
129
  return this.request("GET", `/v1/jobs/${encodeURIComponent(id)}`);
113
130
  }
package/src/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import {resolveModelReference} from "./model-references.js";
2
3
  // CloudGPU MCP server (stdio). Lets an AI coding assistant rent a GPU on cloudgpu.app, run a job,
3
4
  // fetch the results and shut the GPU down.
4
5
  //
@@ -31,7 +32,7 @@ import {
31
32
  shq,
32
33
  } from "./guards.js";
33
34
 
34
- const VERSION = "0.7.0";
35
+ const VERSION = "0.9.0";
35
36
  const HERE = path.dirname(fileURLToPath(import.meta.url));
36
37
  const RULES = fs.readFileSync(path.join(HERE, "..", "rules", "cloudgpu.md"), "utf8");
37
38
 
@@ -59,7 +60,7 @@ const session = new Map();
59
60
  const INSTRUCTIONS = `CloudGPU (cloudgpu.app) rents GPUs billed per minute from a prepaid balance.
60
61
  Workflow: get_account and list_gpus -> estimate_cost -> show the quote to the user and get an explicit yes -> create_instance -> get_status until running -> upload -> run_command (background for long jobs) -> tail_logs -> download results -> stop_instance -> report the actual cost.
61
62
  Rules: never rent without the user's yes on a quote; always set a budget and time limit (the platform shuts the instance down when either is hit); download results before stop_instance because destroying an instance erases its disk; never change passwords, SSH config, the firewall or the platform's monitoring agent on the instance; if anything fails, download what exists and stop the instance rather than leaving it running.
62
- Jobs: for a batch task (one command that writes its results somewhere), run_job does the whole thing on CloudGPU's servers: start a GPU, run the command, destroy the GPU, with the same per-job budget and time limit. Check it with get_job. The GPU's disk is erased when the job ends, so the command must upload its results itself (for example to the user's own S3 bucket) or print them; get_job returns the last ~4 KB of output.
63
+ Jobs: for a batch task (one command that writes its results somewhere), run_job does the whole thing on CloudGPU's servers: start a GPU, run the command, destroy the GPU, with the same per-job budget and time limit. Check it with get_job. The GPU disk is erased on release. When automatic_output_collection is enabled, declare explicit outputs and write them under $CLOUDGPU_OUTPUT_DIR; inspect output_collection and download ready file IDs afterward. Otherwise upload results yourself or print them; get_job returns the last ~4 KB of logs. Saving output shares the same GPU budget and existing storage quota/fees; never infer storage-fee acceptance.
63
64
  No API key yet? connect_account gives the user a link to approve this assistant with a spending limit; then finish_connect stores the key on this computer.
64
65
  The same API key also works for the OpenAI-compatible model API at ${cfg.baseUrl}/v1 (see list_models).`;
65
66
 
@@ -482,6 +483,21 @@ if (!cfg.readOnly) {
482
483
  }),
483
484
  );
484
485
 
486
+ server.registerTool("resolve_model_reference", {
487
+ title:"Pin a public model reference", description:"Read-only. Resolve a public Hugging Face model revision and explicit file list to immutable commit, sizes and available LFS SHA-256 checksums. Does not download weights, rent a GPU or authenticate to Hugging Face. Review model license and application compatibility separately.",
488
+ inputSchema:{repo_id:z.string(),revision:z.string().default("main"),name:z.string(),files:z.array(z.string()).min(1).max(32)},
489
+ annotations:{readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:true},
490
+ },wrap(async (input)=>ok(await resolveModelReference(input))));
491
+ server.registerTool("prepare_model_deployment", {
492
+ title:"Prepare models and a ComfyUI workflow",description:"Preparation only; no GPU is started. Create a reviewed setup script for the existing ComfyUI template. Downloads go from the public model host directly to the rented GPU, never through CloudGPU storage. Use model names as categories (checkpoints, loras, vae, diffusion_models, text_encoders, clip, controlnet, upscale_models). Does not install custom nodes, execute workflows, accept licenses for the user, or promise compatibility. Pass the setup_script only after explicit approval to the existing deployment flow.",
493
+ inputSchema:{model_references:z.array(z.record(z.unknown())).min(1).max(4),workflow:z.record(z.unknown()).optional()},
494
+ annotations:{readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false},
495
+ },wrap(async (input)=>ok(await api.prepareModelDeployment(input))));
496
+ server.registerTool("prepare_job_rerun", {
497
+ title:"Prepare a successful job for rerun",description:"Read-only. Retrieve the original command, pinned model references and Workspace without starting anything. Request a fresh quote, check Workspace expiry and obtain explicit budget approval before calling run_job with a NEW idempotency key. Never reuse the old quote or key.",
498
+ inputSchema:{job_id:z.string()},annotations:{readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:true},
499
+ },wrap(async ({job_id})=>ok(await api.jobRerunSpec(job_id))));
500
+
485
501
  server.registerTool(
486
502
  "run_job",
487
503
  {
@@ -489,7 +505,7 @@ if (!cfg.readOnly) {
489
505
  description:
490
506
  "Costs money. CloudGPU starts a GPU, runs one bash command on it, then destroys the GPU, all on its servers, so it finishes even if this assistant disconnects. " +
491
507
  "max_spend_usd and max_hours are enforced by the servers. Retrying with the same idempotency_key never starts a second GPU; this tool generates one if you leave it out and returns it. " +
492
- "The disk is erased when the job ends: the command must upload its own results (for example to the user's storage) or print them. " +
508
+ "The disk is erased when the job ends. When automatic_output_collection is available, declare outputs and write only those files under $CLOUDGPU_OUTPUT_DIR for persistent storage before release. Otherwise upload results yourself or print them. Storage retention and fees follow the account policy; collection consumes the same GPU budget and may fail. " +
493
509
  "Requires the user's explicit yes on the GPU, budget and time limit.",
494
510
  inputSchema: {
495
511
  command: z.string().min(1).max(32768).describe("bash command or script to run on the GPU"),
@@ -498,6 +514,12 @@ if (!cfg.readOnly) {
498
514
  gpu_count: z.number().int().min(1).max(8).default(1),
499
515
  disk_gb: z.number().int().optional().describe("Larger system disk: 100, 200 or 500; omit for the standard disk"),
500
516
  workspace_version_id: z.string().optional().describe("Immutable Workspace version to restore before the command; requires enabled persistent storage"),
517
+ model_references: z.array(z.object({name:z.string(),repo_id:z.string(),revision:z.string().regex(/^[0-9a-f]{40}$/),files:z.array(z.object({path:z.string(),size_bytes:z.number().int().positive(),sha256:z.string().regex(/^[0-9a-f]{64}$/).optional()})).min(1).max(32)})).max(4).optional().describe("Pinned public model references from resolve_model_reference. Downloads into $CLOUDGPU_MODEL_DIR/<name> before the command; download time consumes the same GPU budget. No R2 cache or remote repository code execution."),
518
+ outputs: z.object({
519
+ files: z.array(z.string().min(1).max(512)).min(1).max(16),
520
+ max_bytes: z.number().int().min(1).max(104857600).optional(),
521
+ accept_storage_charges: z.boolean().optional(),
522
+ }).strict().optional().describe("Explicit relative output files under $CLOUDGPU_OUTPUT_DIR; no globs, symlinks, hidden or credential files. Default total limit 10 MiB, maximum 100 MiB. Only set accept_storage_charges=true after the user agrees to existing paid storage terms. Inspect output_collection after completion; the GPU is released even if saving fails."),
501
523
  quote_id: z.string().optional().describe("Server quote from quote_compute, starting quote_; binds configuration and checks price at submission"),
502
524
  max_spend_usd: z.number().positive().describe(`Budget for this job in USD (at most ${cfg.maxSpend})`),
503
525
  max_hours: z.number().positive().describe(`Hard time limit in hours (at most ${cfg.maxHours})`),
@@ -506,7 +528,7 @@ if (!cfg.readOnly) {
506
528
  },
507
529
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
508
530
  },
509
- wrap(async ({ command, gpu_model, template, gpu_count = 1, disk_gb, workspace_version_id, quote_id, max_spend_usd, max_hours, user_confirmed, idempotency_key }) => {
531
+ wrap(async ({ command, gpu_model, template, gpu_count = 1, disk_gb, workspace_version_id, model_references, outputs, quote_id, max_spend_usd, max_hours, user_confirmed, idempotency_key }) => {
510
532
  if (user_confirmed !== true) {
511
533
  return fail("Not started: tell the user the GPU, budget and time limit, wait for an explicit yes, then call again with user_confirmed=true.");
512
534
  }
@@ -525,6 +547,8 @@ if (!cfg.readOnly) {
525
547
  if (template) body.template = template;
526
548
  if (disk_gb) body.disk_gb = disk_gb;
527
549
  if (workspace_version_id) body.workspace_version_id = workspace_version_id;
550
+ if (outputs) body.outputs = outputs;
551
+ if (model_references?.length) body.model_references = model_references;
528
552
  if (quote_id) body.quote_id = quote_id;
529
553
  const job = await api.createJob(body, key);
530
554
  return ok({
@@ -9,11 +9,33 @@ const terminal=new Set(['succeeded','failed','cancelled']);
9
9
  const idSchema=z.string().regex(/^job_[a-f0-9]{32}$/);
10
10
  const locks=new Map();
11
11
  function assertId(id){if(!/^job_[a-f0-9]{32}$/.test(id))throw Error('Invalid Job ID.');}
12
+ // Inspect bounded decoded views but preserve the original safe log byte-for-byte.
13
+ // This is a conservative refusal filter, not proof that arbitrary log content is secret-free.
14
+ const credentialField=/(?:^|[^A-Za-z0-9_])["']?[A-Za-z0-9_.-]*(?:password|passwd|pwd|passphrase|secret|client[_-]?secret|secret[_-]?(?:access[_-]?)?key|api[_-]?key|access[_-]?key(?:[_-]?id)?|aws[_-]?(?:access[_-]?key[_-]?id|secret[_-]?access[_-]?key|session[_-]?token)|(?:access|refresh|id|auth|session|csrf|xsrf)[_-]?token|token|authorization|proxy[_-]?authorization|cookie|set[_-]?cookie|x[_-]?(?:api[_-]?key|auth[_-]?token))["']?\s*[:=]\s*(?=\S)/i;
15
+ const credentialForms=[credentialField,/-----BEGIN [^-]*PRIVATE KEY-----/i,/\bsk-[A-Za-z0-9_-]{16,}/,/\b(?:Bearer|Basic)\s+[A-Za-z0-9_+/.=-]{8,}/i,/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/,/https?:\/\/[^\s"'<>]*\?[^\s"'<>]*/i,/https?:\/\/[^/\s"'<>@]+@/i];
16
+ function decodedTailView(text){
17
+ const named={quot:'"',apos:"'",colon:':',equals:'=',amp:'&',sol:'/',quest:'?'};
18
+ return text.normalize('NFKC')
19
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g,'')
20
+ .replace(/[\u200b-\u200f\u202a-\u202e\u2060-\u206f\ufeff]/g,'')
21
+ .replace(/\\u([0-9a-f]{4})|\\x([0-9a-f]{2})|\\(["'\\/:=])/gi,(_m,u,x,c)=>u?String.fromCharCode(parseInt(u,16)):x?String.fromCharCode(parseInt(x,16)):c)
22
+ .replace(/(?:%[0-9a-f]{2})+/gi,part=>Buffer.from(part.replaceAll('%',''),'hex').toString('utf8'))
23
+ .replace(/&#(x[0-9a-f]+|[0-9]+);|&(quot|apos|colon|equals|amp|sol|quest);/gi,(_m,n,name)=>{
24
+ if(name)return named[name.toLowerCase()];const value=n[0].toLowerCase()==='x'?parseInt(n.slice(1),16):parseInt(n,10);
25
+ if(value>0x10ffff)throw Error('Output normalization is unsafe; nothing was uploaded.');return String.fromCodePoint(value);
26
+ });
27
+ }
12
28
  export function checkedTail(text,apiKey){
13
29
  if(typeof text!=='string'||Buffer.byteLength(text)>16384)throw Error('Job output tail exceeds the bounded snapshot limit.');
14
- const secrets=[/-----BEGIN [^-]*PRIVATE KEY-----/,/\bsk-[A-Za-z0-9_-]{16,}/,/\b(?:password|secret|token|api[_-]?key|authorization)\s*[:=]\s*["']?[^\s"',}]+/i,/https?:\/\/[^\s]+\?[^\s]+/i];
15
- if((apiKey&&apiKey.length>=4&&text.includes(apiKey))||secrets.some(re=>re.test(text)))throw Error('Output may contain credentials or a signed URL. Sanitize it before saving; nothing was uploaded.');
16
- return text;
30
+ let view=text;
31
+ for(let depth=0;depth<5;depth++){
32
+ if((apiKey&&apiKey.length>=4&&view.includes(apiKey))||credentialForms.some(re=>re.test(view)))throw Error('Output may contain credentials or a signed URL. Sanitize it before saving; nothing was uploaded.');
33
+ const next=decodedTailView(view);
34
+ if(Buffer.byteLength(next)>65536)throw Error('Output normalization exceeds the bounded snapshot limit.');
35
+ if(next===view)return text;
36
+ view=next;
37
+ }
38
+ throw Error('Output normalization is too deeply encoded; nothing was uploaded.');
17
39
  }
18
40
  export async function diagnoseJob(api,id){
19
41
  assertId(id);const job=await api.job(id);const code=job.error?.code||null;
@@ -50,5 +72,5 @@ export function registerJobResultTools(server,{api,wrap,ok,readOnly}){
50
72
  const storage=new PersistentStorage(api);
51
73
  server.registerTool('diagnose_job',{title:'Inspect Job failure and cost state',description:'Read-only Job diagnosis and observed platform instance state. Never creates, stops or retries a GPU. Does not claim supplier release verification or classify every command failure as user error.',inputSchema:{job_id:idSchema},annotations:{readOnlyHint:true,openWorldHint:true}},wrap(async({job_id})=>ok(await diagnoseJob(api,job_id))));
52
74
  if(readOnly)return;
53
- server.registerTool('save_job_output',{title:'Save ended Job output tail',description:'With approval, persist the ended Job log tail as a small Artifact using existing storage quota and retention. This is not the full log or binary output collection. Refuses recognizable credentials and queried URLs. Never touches GPU resources. Reuses a matching verified snapshot when found; cross-client concurrent calls may create duplicates.',inputSchema:{job_id:idSchema,user_confirmed:z.boolean(),accept_storage_charges:z.boolean().default(false)},annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:true}},wrap(async({job_id,user_confirmed,accept_storage_charges})=>ok(await saveJobOutput(api,storage,job_id,user_confirmed,accept_storage_charges))));
75
+ server.registerTool('save_job_output',{title:'Save ended Job output tail',description:'With approval, persist the ended Job log tail as a small Artifact using existing storage quota and retention. This is not the full log or binary output collection. Refuses recognizable credentials, quoted/aliased fields and bounded escaped representations or queried URLs. This is not a guarantee that arbitrary logs contain no secrets; save only logs you know are sanitized. Never touches GPU resources. Reuses a matching verified snapshot when found; cross-client concurrent calls may create duplicates.',inputSchema:{job_id:idSchema,user_confirmed:z.boolean(),accept_storage_charges:z.boolean().default(false)},annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:true}},wrap(async({job_id,user_confirmed,accept_storage_charges})=>ok(await saveJobOutput(api,storage,job_id,user_confirmed,accept_storage_charges))));
54
76
  }
@@ -0,0 +1,44 @@
1
+ // 只向 Hugging Face 的固定公开 API 解析引用,不携带 CloudGPU key 或用户 token。
2
+ import {createHash} from 'node:crypto';
3
+ export async function resolveModelReference({repo_id, revision = "main", name, files}, fetchImpl = globalThis.fetch) {
4
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,95}\/[A-Za-z0-9][A-Za-z0-9_.-]{0,95}$/.test(repo_id)
5
+ || !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,119}$/.test(revision)
6
+ || !/^[A-Za-z][A-Za-z0-9_-]{0,47}$/.test(name)
7
+ || !Array.isArray(files) || !files.length || files.length > 32 || new Set(files).size !== files.length
8
+ || files.some(p => typeof p !== "string" || p.length > 240 || !/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/.test(p) || p.split("/").some(s => !s || s === "." || s === ".."))) throw new Error("Invalid public model reference");
9
+ const url = `https://huggingface.co/api/models/${repo_id}/revision/${encodeURIComponent(revision)}?blobs=true`;
10
+ const response = await fetchImpl(url, {headers:{"User-Agent":"CloudGPU-model-reference/1"}, redirect:"error", signal:AbortSignal.timeout(15000)});
11
+ if (!response.ok) throw new Error("Public model metadata unavailable; check repository, revision and public access");
12
+ const reader=response.body.getReader();const chunks=[];let bytes=0;
13
+ try {while(true){const r=await reader.read();if(r.done)break;bytes+=r.value.byteLength;if(bytes>2*1024*1024)throw new Error("Model metadata exceeds limit; use a smaller repository or supply a pinned manifest");chunks.push(r.value);}}
14
+ finally {await reader.cancel();}
15
+ let data;try{data=JSON.parse(Buffer.concat(chunks).toString("utf8"));}catch{throw new Error("Invalid public model metadata");}
16
+ if (data.private || data.gated) throw new Error("Private or gated models are not supported; select a public model without an access gate");
17
+ if (!/^[0-9a-f]{40}$/.test(data.sha)) throw new Error("Model revision could not be pinned");
18
+ const selected=files.map(path=>{
19
+ const file=data.siblings?.find(f=>f.rfilename===path);const size=file?.lfs?.size ?? file?.size;
20
+ if(!Number.isSafeInteger(size)||size<1)throw new Error("Requested file metadata missing or empty");
21
+ const sha=file?.lfs?.sha256;
22
+ if(sha!==undefined&&!/^[0-9a-f]{64}$/.test(sha))throw new Error("Invalid file checksum metadata");
23
+ return {path,size_bytes:size,...(sha?{sha256:sha}:{})};
24
+ });
25
+ if(selected.reduce((n,f)=>n+f.size_bytes,0)>100_000_000_000)throw new Error("Model exceeds the first-version 100 GB job limit");
26
+ // Git-backed config files have no LFS SHA. Hash bounded public JSON metadata
27
+ // on the origin so the GPU can verify it even when using its existing mirror.
28
+ const configs=selected.filter(f=>!f.sha256&&f.path.endsWith('.json')&&f.size_bytes<=65536);
29
+ if(configs.length>8)throw new Error('Too many unhashed JSON metadata files; supply an independently verified manifest');
30
+ const deadline=Date.now()+15000;
31
+ for(const file of configs){
32
+ const remaining=deadline-Date.now();
33
+ if(remaining<=0)throw new Error('Model config metadata deadline exceeded');
34
+ const config=await fetchImpl(`https://huggingface.co/${repo_id}/raw/${data.sha}/${file.path.split('/').map(encodeURIComponent).join('/')}`,
35
+ {headers:{'User-Agent':'CloudGPU-model-reference/1'},redirect:'error',signal:AbortSignal.timeout(remaining)});
36
+ if(!config.ok)throw new Error('Public model config metadata unavailable');
37
+ const stream=config.body.getReader();const content=[];let size=0;
38
+ try{while(true){const r=await stream.read();if(r.done)break;size+=r.value.byteLength;if(size>file.size_bytes)throw new Error('Model config metadata size mismatch');content.push(r.value);}}
39
+ finally{await stream.cancel();}
40
+ if(size!==file.size_bytes)throw new Error('Model config metadata size mismatch');
41
+ file.sha256=createHash('sha256').update(Buffer.concat(content)).digest('hex');
42
+ }
43
+ return {name,repo_id,revision:data.sha,files:selected};
44
+ }