seacloud-sdk 0.9.7 → 0.9.9

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/dist/cli.js CHANGED
@@ -13,7 +13,51 @@ var SeacloudError = class extends Error {
13
13
  };
14
14
 
15
15
  // src/core/config.ts
16
- function getApiToken(providedApiKey) {
16
+ function isInIframe() {
17
+ try {
18
+ return typeof globalThis.window !== "undefined" && globalThis.window.self !== globalThis.window.top;
19
+ } catch (e) {
20
+ return true;
21
+ }
22
+ }
23
+ async function getTokenFromParent(timeout = 5e3) {
24
+ if (!isInIframe()) {
25
+ return null;
26
+ }
27
+ return new Promise((resolve) => {
28
+ const messageHandler = (event) => {
29
+ if (event.data && event.data.type === "seaverse:token") {
30
+ cleanup();
31
+ const token = event.data.payload?.accessToken;
32
+ resolve(token || null);
33
+ } else if (event.data && event.data.type === "seaverse:error") {
34
+ cleanup();
35
+ console.warn("[SeaCloud SDK] Error getting token from parent:", event.data.error);
36
+ resolve(null);
37
+ }
38
+ };
39
+ const timeoutId = setTimeout(() => {
40
+ cleanup();
41
+ resolve(null);
42
+ }, timeout);
43
+ const cleanup = () => {
44
+ clearTimeout(timeoutId);
45
+ globalThis.window.removeEventListener("message", messageHandler);
46
+ };
47
+ globalThis.window.addEventListener("message", messageHandler);
48
+ try {
49
+ globalThis.window.parent.postMessage(
50
+ { type: "seaverse:get_token" },
51
+ "*"
52
+ // 允许任何源,支持跨域场景
53
+ );
54
+ } catch (e) {
55
+ cleanup();
56
+ resolve(null);
57
+ }
58
+ });
59
+ }
60
+ async function getApiToken(providedApiKey) {
17
61
  if (providedApiKey) {
18
62
  return providedApiKey;
19
63
  }
@@ -29,19 +73,24 @@ function getApiToken(providedApiKey) {
29
73
  if (typeof process !== "undefined" && process.env?.API_SERVICE_TOKEN) {
30
74
  return process.env.API_SERVICE_TOKEN;
31
75
  }
32
- throw new Error(
33
- 'SeaCloud SDK: No API token found. Please ensure token is available in localStorage.getItem("auth_token") (browser) or process.env.API_SERVICE_TOKEN (Node.js), or initialize with initSeacloud({ apiKey: "your-token" }).'
34
- );
76
+ if (typeof globalThis.window !== "undefined") {
77
+ const parentToken = await getTokenFromParent();
78
+ if (parentToken) {
79
+ return parentToken;
80
+ }
81
+ }
82
+ return "";
35
83
  }
36
84
  function createConfig(options = {}) {
37
- const apiKey = getApiToken(options.apiKey);
85
+ const apiKey = options.apiKey;
38
86
  const baseUrl = options.baseUrl || (typeof process !== "undefined" ? process.env?.SEACLOUD_BASE_URL : void 0) || "https://proxy-rs.seaverse.ai";
39
87
  const fetchImpl = options.fetch || (globalThis.fetch ? globalThis.fetch.bind(globalThis) : void 0);
40
88
  if (!fetchImpl) {
41
89
  throw new Error("fetch is not available. Please provide a fetch implementation in config or upgrade to Node.js 18+");
42
90
  }
43
91
  return {
44
- apiKey,
92
+ apiKey: apiKey || "",
93
+ // 提供默认空字符串,实际请求时会动态获取
45
94
  baseUrl,
46
95
  fetch: fetchImpl,
47
96
  timeout: options.timeout || 3e4
@@ -86,7 +135,7 @@ var SeacloudClient = class {
86
135
  */
87
136
  async createTask(endpoint, body) {
88
137
  const url = `${this.config.baseUrl}${endpoint}`;
89
- const currentToken = getApiToken(this.providedApiKey);
138
+ const currentToken = await getApiToken(this.providedApiKey);
90
139
  const controller = new AbortController();
91
140
  const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
92
141
  try {
@@ -133,7 +182,7 @@ var SeacloudClient = class {
133
182
  */
134
183
  async getTaskStatus(endpoint, taskId) {
135
184
  const url = `${this.config.baseUrl}${endpoint}/task/${taskId}`;
136
- const currentToken = getApiToken(this.providedApiKey);
185
+ const currentToken = await getApiToken(this.providedApiKey);
137
186
  const controller = new AbortController();
138
187
  const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
139
188
  try {
@@ -230,6 +279,7 @@ async function llmChatCompletions(params) {
230
279
  const client = getClient();
231
280
  const config = client.getConfig();
232
281
  const url = `${config.baseUrl}/llm/chat/completions`;
282
+ const token = await getApiToken(config.apiKey);
233
283
  const controller = new AbortController();
234
284
  const timeoutId = setTimeout(() => controller.abort(), config.timeout);
235
285
  try {
@@ -237,7 +287,7 @@ async function llmChatCompletions(params) {
237
287
  method: "POST",
238
288
  headers: {
239
289
  "Content-Type": "application/json",
240
- "Authorization": `Bearer ${config.apiKey}`
290
+ "Authorization": `Bearer ${token}`
241
291
  },
242
292
  body: JSON.stringify(params),
243
293
  signal: controller.signal
@@ -551,6 +601,7 @@ Commands:
551
601
  llm <prompt> Chat with LLM models
552
602
  agent <prompt> Chat with Fast Agent (supports image/video generation)
553
603
  app <subcommand> App-related operations (search, generation)
604
+ status <task-id> Query task status by task ID
554
605
  <model> Test specific model generation
555
606
 
556
607
  App Subcommands:
@@ -581,6 +632,10 @@ Model Generation Options:
581
632
  --base-url <url> Base URL (default: http://proxy.sg.seaverse.dev)
582
633
  --params <json> JSON parameters for the model
583
634
 
635
+ Status Query Options:
636
+ --api-key <key> API key (or set API_SERVICE_TOKEN env var)
637
+ --base-url <url> Base URL (default: http://proxy.sg.seaverse.dev)
638
+
584
639
  Examples:
585
640
  # Chat with LLM (non-streaming)
586
641
  seacloud llm "What is the capital of France?"
@@ -604,6 +659,9 @@ Examples:
604
659
  # Create generation task (app generation)
605
660
  seacloud app generation --template-id "d26trpte878eqsnm3bjg" --params '[{"field":"prompt1","value":"hello"}]'
606
661
 
662
+ # Query task status
663
+ seacloud status d123456789abcdef
664
+
607
665
  # Test model generation
608
666
  seacloud flux_1_1_pro --params '{"prompt":"a beautiful sunset"}'
609
667
 
@@ -902,6 +960,68 @@ async function runAppSearch(templateIdsStr, args) {
902
960
  });
903
961
  console.log(JSON.stringify(result, null, 2));
904
962
  }
963
+ async function runTaskStatus(taskId, args) {
964
+ const options = {};
965
+ for (let i = 0; i < args.length; i++) {
966
+ const arg = args[i];
967
+ if (arg === "--api-key") options.apiKey = args[++i];
968
+ else if (arg === "--base-url") options.baseUrl = args[++i];
969
+ }
970
+ const apiKey = options.apiKey || process.env.API_SERVICE_TOKEN || "";
971
+ const baseUrl = options.baseUrl || process.env.SEACLOUD_BASE_URL || "http://proxy.sg.seaverse.dev";
972
+ const client = new SeacloudClient({ apiKey, baseUrl });
973
+ console.log(`Querying task status...`);
974
+ console.log(`Task ID: ${taskId}`);
975
+ console.log(`Base URL: ${baseUrl}
976
+ `);
977
+ try {
978
+ const result = await client.getTaskStatus("/model/v1/generation", taskId);
979
+ console.log(`Status: ${result.status}`);
980
+ console.log(`Task ID: ${result.id}
981
+ `);
982
+ if (result.status === "completed") {
983
+ console.log("\u2705 Task completed successfully!\n");
984
+ console.log("Output:");
985
+ console.log(JSON.stringify(result.output, null, 2));
986
+ if (result.output) {
987
+ const urls = [];
988
+ for (const item of result.output) {
989
+ if (item.content) {
990
+ for (const resource of item.content) {
991
+ if (resource.url) {
992
+ urls.push(resource.url);
993
+ }
994
+ }
995
+ }
996
+ }
997
+ if (urls.length > 0) {
998
+ console.log("\nGenerated URLs:");
999
+ urls.forEach((url, i) => {
1000
+ console.log(` ${i + 1}. ${url}`);
1001
+ });
1002
+ }
1003
+ }
1004
+ } else if (result.status === "failed") {
1005
+ console.log("\u274C Task failed!\n");
1006
+ console.log("Error:", JSON.stringify(result.error, null, 2));
1007
+ } else if (result.status === "processing") {
1008
+ console.log("\u23F3 Task is still processing...");
1009
+ console.log("Please check again later.");
1010
+ } else if (result.status === "pending") {
1011
+ console.log("\u23F3 Task is pending...");
1012
+ console.log("Please check again later.");
1013
+ } else {
1014
+ console.log("Full result:");
1015
+ console.log(JSON.stringify(result, null, 2));
1016
+ }
1017
+ } catch (error) {
1018
+ console.error("\nError querying task status:", error.message);
1019
+ if (error.statusCode) {
1020
+ console.error("HTTP Status Code:", error.statusCode);
1021
+ }
1022
+ process.exit(1);
1023
+ }
1024
+ }
905
1025
  async function main() {
906
1026
  const args = process.argv.slice(2);
907
1027
  if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
@@ -924,6 +1044,13 @@ async function main() {
924
1044
  process.exit(1);
925
1045
  }
926
1046
  await runAgent(args[1], args.slice(2));
1047
+ } else if (command === "status") {
1048
+ if (args.length < 2) {
1049
+ console.error("Error: task ID required for status command");
1050
+ console.log("Usage: seacloud status <task-id> [options]");
1051
+ process.exit(1);
1052
+ }
1053
+ await runTaskStatus(args[1], args.slice(2));
927
1054
  } else if (command === "app") {
928
1055
  const subcommand = args[1];
929
1056
  if (!subcommand) {