@blaxel/core 0.2.1-dev1 → 0.2.1-dev11

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.
@@ -1,5 +1,5 @@
1
1
  import type { Options as ClientOptions, TDataShape, Client } from '@hey-api/client-fetch';
2
- import type { ListAgentsData, CreateAgentData, DeleteAgentData, GetAgentData, UpdateAgentData, ListAgentRevisionsData, GetConfigurationData, ListFunctionsData, CreateFunctionData, DeleteFunctionData, GetFunctionData, UpdateFunctionData, ListFunctionRevisionsData, GetIntegrationData, ListIntegrationConnectionsData, CreateIntegrationConnectionData, DeleteIntegrationConnectionData, GetIntegrationConnectionData, UpdateIntegrationConnectionData, GetIntegrationConnectionModelEndpointConfigurationsData, ListIntegrationConnectionModelsData, GetIntegrationConnectionModelData, ListKnowledgebasesData, CreateKnowledgebaseData, DeleteKnowledgebaseData, GetKnowledgebaseData, UpdateKnowledgebaseData, ListKnowledgebaseRevisionsData, ListLocationsData, ListMcpHubDefinitionsData, ListModelsData, CreateModelData, DeleteModelData, GetModelData, UpdateModelData, ListModelRevisionsData, ListPoliciesData, CreatePolicyData, DeletePolicyData, GetPolicyData, UpdatePolicyData, ListPrivateClustersData, CreatePrivateClusterData, DeletePrivateClusterData, GetPrivateClusterData, UpdatePrivateClusterData, GetPrivateClusterHealthData, UpdatePrivateClusterHealthData, ListAllPendingInvitationsData, ListSandboxHubDefinitionsData, ListSandboxesData, CreateSandboxData, DeleteSandboxData, GetSandboxData, UpdateSandboxData, ListSandboxPreviewsData, CreateSandboxPreviewData, DeleteSandboxPreviewData, GetSandboxPreviewData, UpdateSandboxPreviewData, ListSandboxPreviewTokensData, CreateSandboxPreviewTokenData, DeleteSandboxPreviewTokenData, StartSandboxData, StopSandboxData, GetWorkspaceServiceAccountsData, CreateWorkspaceServiceAccountData, DeleteWorkspaceServiceAccountData, UpdateWorkspaceServiceAccountData, ListApiKeysForServiceAccountData, CreateApiKeyForServiceAccountData, DeleteApiKeyForServiceAccountData, ListTemplatesData, GetTemplateData, GetTemplateContentsData, GetTemplateFileContentsData, ListWorkspaceUsersData, InviteWorkspaceUserData, RemoveWorkspaceUserData, UpdateWorkspaceUserRoleData, ListWorkspacesData, CreateWorspaceData, DeleteWorkspaceData, GetWorkspaceData, UpdateWorkspaceData, DeclineWorkspaceInvitationData, AcceptWorkspaceInvitationData, LeaveWorkspaceData, CheckWorkspaceAvailabilityData } from './types.gen.js';
2
+ import type { ListAgentsData, CreateAgentData, DeleteAgentData, GetAgentData, UpdateAgentData, ListAgentRevisionsData, GetConfigurationData, ListFunctionsData, CreateFunctionData, DeleteFunctionData, GetFunctionData, UpdateFunctionData, ListFunctionRevisionsData, GetIntegrationData, ListIntegrationConnectionsData, CreateIntegrationConnectionData, DeleteIntegrationConnectionData, GetIntegrationConnectionData, UpdateIntegrationConnectionData, GetIntegrationConnectionModelEndpointConfigurationsData, ListIntegrationConnectionModelsData, GetIntegrationConnectionModelData, ListJobsData, CreateJobData, DeleteJobData, GetJobData, UpdateJobData, ListJobRevisionsData, ListKnowledgebasesData, CreateKnowledgebaseData, DeleteKnowledgebaseData, GetKnowledgebaseData, UpdateKnowledgebaseData, ListKnowledgebaseRevisionsData, ListLocationsData, ListMcpHubDefinitionsData, ListModelsData, CreateModelData, DeleteModelData, GetModelData, UpdateModelData, ListModelRevisionsData, ListPoliciesData, CreatePolicyData, DeletePolicyData, GetPolicyData, UpdatePolicyData, ListPrivateClustersData, CreatePrivateClusterData, DeletePrivateClusterData, GetPrivateClusterData, UpdatePrivateClusterData, GetPrivateClusterHealthData, UpdatePrivateClusterHealthData, ListAllPendingInvitationsData, ListSandboxHubDefinitionsData, ListSandboxesData, CreateSandboxData, DeleteSandboxData, GetSandboxData, UpdateSandboxData, ListSandboxPreviewsData, CreateSandboxPreviewData, DeleteSandboxPreviewData, GetSandboxPreviewData, UpdateSandboxPreviewData, ListSandboxPreviewTokensData, CreateSandboxPreviewTokenData, DeleteSandboxPreviewTokenData, StartSandboxData, StopSandboxData, GetWorkspaceServiceAccountsData, CreateWorkspaceServiceAccountData, DeleteWorkspaceServiceAccountData, UpdateWorkspaceServiceAccountData, ListApiKeysForServiceAccountData, CreateApiKeyForServiceAccountData, DeleteApiKeyForServiceAccountData, ListTemplatesData, GetTemplateData, GetTemplateContentsData, GetTemplateFileContentsData, ListWorkspaceUsersData, InviteWorkspaceUserData, RemoveWorkspaceUserData, UpdateWorkspaceUserRoleData, ListWorkspacesData, CreateWorspaceData, DeleteWorkspaceData, GetWorkspaceData, UpdateWorkspaceData, DeclineWorkspaceInvitationData, AcceptWorkspaceInvitationData, LeaveWorkspaceData, CheckWorkspaceAvailabilityData } from './types.gen.js';
3
3
  export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = ClientOptions<TData, ThrowOnError> & {
4
4
  /**
5
5
  * You can provide a client instance returned by `createClient()` instead of
@@ -111,6 +111,36 @@ export declare const listIntegrationConnectionModels: <ThrowOnError extends bool
111
111
  * Returns a model for an integration connection by ID.
112
112
  */
113
113
  export declare const getIntegrationConnectionModel: <ThrowOnError extends boolean = false>(options: Options<GetIntegrationConnectionModelData, ThrowOnError>) => import("@hey-api/client-fetch").RequestResult<unknown, unknown, ThrowOnError>;
114
+ /**
115
+ * List jobs
116
+ * Returns a list of all jobs in the workspace.
117
+ */
118
+ export declare const listJobs: <ThrowOnError extends boolean = false>(options?: Options<ListJobsData, ThrowOnError>) => import("@hey-api/client-fetch").RequestResult<import("./types.gen.js").Job[], unknown, ThrowOnError>;
119
+ /**
120
+ * Create job
121
+ * Creates a job.
122
+ */
123
+ export declare const createJob: <ThrowOnError extends boolean = false>(options: Options<CreateJobData, ThrowOnError>) => import("@hey-api/client-fetch").RequestResult<import("./types.gen.js").Job, unknown, ThrowOnError>;
124
+ /**
125
+ * Delete job
126
+ * Deletes a job by name.
127
+ */
128
+ export declare const deleteJob: <ThrowOnError extends boolean = false>(options: Options<DeleteJobData, ThrowOnError>) => import("@hey-api/client-fetch").RequestResult<import("./types.gen.js").Job, unknown, ThrowOnError>;
129
+ /**
130
+ * Get job
131
+ * Returns a job by name.
132
+ */
133
+ export declare const getJob: <ThrowOnError extends boolean = false>(options: Options<GetJobData, ThrowOnError>) => import("@hey-api/client-fetch").RequestResult<import("./types.gen.js").Model, unknown, ThrowOnError>;
134
+ /**
135
+ * Create or update job
136
+ * Update a job by name.
137
+ */
138
+ export declare const updateJob: <ThrowOnError extends boolean = false>(options: Options<UpdateJobData, ThrowOnError>) => import("@hey-api/client-fetch").RequestResult<import("./types.gen.js").Job, unknown, ThrowOnError>;
139
+ /**
140
+ * List job revisions
141
+ * Returns revisions for a job by name.
142
+ */
143
+ export declare const listJobRevisions: <ThrowOnError extends boolean = false>(options: Options<ListJobRevisionsData, ThrowOnError>) => import("@hey-api/client-fetch").RequestResult<import("./types.gen.js").RevisionMetadata[], unknown, ThrowOnError>;
114
144
  /**
115
145
  * List knowledgebases
116
146
  * Returns a list of all knowledgebases in the workspace.
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  // This file is auto-generated by @hey-api/openapi-ts
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.listSandboxHubDefinitions = exports.listAllPendingInvitations = exports.updatePrivateClusterHealth = exports.getPrivateClusterHealth = exports.updatePrivateCluster = exports.getPrivateCluster = exports.deletePrivateCluster = exports.createPrivateCluster = exports.listPrivateClusters = exports.updatePolicy = exports.getPolicy = exports.deletePolicy = exports.createPolicy = exports.listPolicies = exports.listModelRevisions = exports.updateModel = exports.getModel = exports.deleteModel = exports.createModel = exports.listModels = exports.listMcpHubDefinitions = exports.listLocations = exports.listKnowledgebaseRevisions = exports.updateKnowledgebase = exports.getKnowledgebase = exports.deleteKnowledgebase = exports.createKnowledgebase = exports.listKnowledgebases = exports.getIntegrationConnectionModel = exports.listIntegrationConnectionModels = exports.getIntegrationConnectionModelEndpointConfigurations = exports.updateIntegrationConnection = exports.getIntegrationConnection = exports.deleteIntegrationConnection = exports.createIntegrationConnection = exports.listIntegrationConnections = exports.getIntegration = exports.listFunctionRevisions = exports.updateFunction = exports.getFunction = exports.deleteFunction = exports.createFunction = exports.listFunctions = exports.getConfiguration = exports.listAgentRevisions = exports.updateAgent = exports.getAgent = exports.deleteAgent = exports.createAgent = exports.listAgents = void 0;
5
- exports.checkWorkspaceAvailability = exports.leaveWorkspace = exports.acceptWorkspaceInvitation = exports.declineWorkspaceInvitation = exports.updateWorkspace = exports.getWorkspace = exports.deleteWorkspace = exports.createWorspace = exports.listWorkspaces = exports.updateWorkspaceUserRole = exports.removeWorkspaceUser = exports.inviteWorkspaceUser = exports.listWorkspaceUsers = exports.getTemplateFileContents = exports.getTemplateContents = exports.getTemplate = exports.listTemplates = exports.deleteApiKeyForServiceAccount = exports.createApiKeyForServiceAccount = exports.listApiKeysForServiceAccount = exports.updateWorkspaceServiceAccount = exports.deleteWorkspaceServiceAccount = exports.createWorkspaceServiceAccount = exports.getWorkspaceServiceAccounts = exports.stopSandbox = exports.startSandbox = exports.deleteSandboxPreviewToken = exports.createSandboxPreviewToken = exports.listSandboxPreviewTokens = exports.updateSandboxPreview = exports.getSandboxPreview = exports.deleteSandboxPreview = exports.createSandboxPreview = exports.listSandboxPreviews = exports.updateSandbox = exports.getSandbox = exports.deleteSandbox = exports.createSandbox = exports.listSandboxes = void 0;
4
+ exports.deletePrivateCluster = exports.createPrivateCluster = exports.listPrivateClusters = exports.updatePolicy = exports.getPolicy = exports.deletePolicy = exports.createPolicy = exports.listPolicies = exports.listModelRevisions = exports.updateModel = exports.getModel = exports.deleteModel = exports.createModel = exports.listModels = exports.listMcpHubDefinitions = exports.listLocations = exports.listKnowledgebaseRevisions = exports.updateKnowledgebase = exports.getKnowledgebase = exports.deleteKnowledgebase = exports.createKnowledgebase = exports.listKnowledgebases = exports.listJobRevisions = exports.updateJob = exports.getJob = exports.deleteJob = exports.createJob = exports.listJobs = exports.getIntegrationConnectionModel = exports.listIntegrationConnectionModels = exports.getIntegrationConnectionModelEndpointConfigurations = exports.updateIntegrationConnection = exports.getIntegrationConnection = exports.deleteIntegrationConnection = exports.createIntegrationConnection = exports.listIntegrationConnections = exports.getIntegration = exports.listFunctionRevisions = exports.updateFunction = exports.getFunction = exports.deleteFunction = exports.createFunction = exports.listFunctions = exports.getConfiguration = exports.listAgentRevisions = exports.updateAgent = exports.getAgent = exports.deleteAgent = exports.createAgent = exports.listAgents = void 0;
5
+ exports.checkWorkspaceAvailability = exports.leaveWorkspace = exports.acceptWorkspaceInvitation = exports.declineWorkspaceInvitation = exports.updateWorkspace = exports.getWorkspace = exports.deleteWorkspace = exports.createWorspace = exports.listWorkspaces = exports.updateWorkspaceUserRole = exports.removeWorkspaceUser = exports.inviteWorkspaceUser = exports.listWorkspaceUsers = exports.getTemplateFileContents = exports.getTemplateContents = exports.getTemplate = exports.listTemplates = exports.deleteApiKeyForServiceAccount = exports.createApiKeyForServiceAccount = exports.listApiKeysForServiceAccount = exports.updateWorkspaceServiceAccount = exports.deleteWorkspaceServiceAccount = exports.createWorkspaceServiceAccount = exports.getWorkspaceServiceAccounts = exports.stopSandbox = exports.startSandbox = exports.deleteSandboxPreviewToken = exports.createSandboxPreviewToken = exports.listSandboxPreviewTokens = exports.updateSandboxPreview = exports.getSandboxPreview = exports.deleteSandboxPreview = exports.createSandboxPreview = exports.listSandboxPreviews = exports.updateSandbox = exports.getSandbox = exports.deleteSandbox = exports.createSandbox = exports.listSandboxes = exports.listSandboxHubDefinitions = exports.listAllPendingInvitations = exports.updatePrivateClusterHealth = exports.getPrivateClusterHealth = exports.updatePrivateCluster = exports.getPrivateCluster = void 0;
6
6
  const client_gen_1 = require("./client.gen");
7
7
  /**
8
8
  * List all agents
@@ -390,6 +390,116 @@ const getIntegrationConnectionModel = (options) => {
390
390
  });
391
391
  };
392
392
  exports.getIntegrationConnectionModel = getIntegrationConnectionModel;
393
+ /**
394
+ * List jobs
395
+ * Returns a list of all jobs in the workspace.
396
+ */
397
+ const listJobs = (options) => {
398
+ return (options?.client ?? client_gen_1.client).get({
399
+ security: [
400
+ {
401
+ scheme: 'bearer',
402
+ type: 'http'
403
+ }
404
+ ],
405
+ url: '/jobs',
406
+ ...options
407
+ });
408
+ };
409
+ exports.listJobs = listJobs;
410
+ /**
411
+ * Create job
412
+ * Creates a job.
413
+ */
414
+ const createJob = (options) => {
415
+ return (options.client ?? client_gen_1.client).post({
416
+ security: [
417
+ {
418
+ scheme: 'bearer',
419
+ type: 'http'
420
+ }
421
+ ],
422
+ url: '/jobs',
423
+ ...options,
424
+ headers: {
425
+ 'Content-Type': 'application/json',
426
+ ...options?.headers
427
+ }
428
+ });
429
+ };
430
+ exports.createJob = createJob;
431
+ /**
432
+ * Delete job
433
+ * Deletes a job by name.
434
+ */
435
+ const deleteJob = (options) => {
436
+ return (options.client ?? client_gen_1.client).delete({
437
+ security: [
438
+ {
439
+ scheme: 'bearer',
440
+ type: 'http'
441
+ }
442
+ ],
443
+ url: '/jobs/{jobId}',
444
+ ...options
445
+ });
446
+ };
447
+ exports.deleteJob = deleteJob;
448
+ /**
449
+ * Get job
450
+ * Returns a job by name.
451
+ */
452
+ const getJob = (options) => {
453
+ return (options.client ?? client_gen_1.client).get({
454
+ security: [
455
+ {
456
+ scheme: 'bearer',
457
+ type: 'http'
458
+ }
459
+ ],
460
+ url: '/jobs/{jobId}',
461
+ ...options
462
+ });
463
+ };
464
+ exports.getJob = getJob;
465
+ /**
466
+ * Create or update job
467
+ * Update a job by name.
468
+ */
469
+ const updateJob = (options) => {
470
+ return (options.client ?? client_gen_1.client).put({
471
+ security: [
472
+ {
473
+ scheme: 'bearer',
474
+ type: 'http'
475
+ }
476
+ ],
477
+ url: '/jobs/{jobId}',
478
+ ...options,
479
+ headers: {
480
+ 'Content-Type': 'application/json',
481
+ ...options?.headers
482
+ }
483
+ });
484
+ };
485
+ exports.updateJob = updateJob;
486
+ /**
487
+ * List job revisions
488
+ * Returns revisions for a job by name.
489
+ */
490
+ const listJobRevisions = (options) => {
491
+ return (options.client ?? client_gen_1.client).get({
492
+ security: [
493
+ {
494
+ scheme: 'bearer',
495
+ type: 'http'
496
+ }
497
+ ],
498
+ url: '/jobs/{jobId}/revisions',
499
+ ...options
500
+ });
501
+ };
502
+ exports.listJobRevisions = listJobRevisions;
393
503
  /**
394
504
  * List knowledgebases
395
505
  * Returns a list of all knowledgebases in the workspace.
@@ -639,6 +639,22 @@ export type IntegrationRepository = {
639
639
  */
640
640
  url?: string;
641
641
  };
642
+ /**
643
+ * Job
644
+ */
645
+ export type Job = {
646
+ events?: CoreEvents;
647
+ metadata?: Metadata;
648
+ spec?: JobSpec;
649
+ /**
650
+ * Job status
651
+ */
652
+ status?: string;
653
+ };
654
+ /**
655
+ * Job specification
656
+ */
657
+ export type JobSpec = CoreSpec & unknown;
642
658
  /**
643
659
  * Knowledgebase
644
660
  */
@@ -1624,6 +1640,10 @@ export type Runtime = {
1624
1640
  * The Docker image for the deployment
1625
1641
  */
1626
1642
  image?: string;
1643
+ /**
1644
+ * The maximum number of retries for the deployment
1645
+ */
1646
+ maxRetries?: number;
1627
1647
  /**
1628
1648
  * The minimum number of replicas for the deployment. Can be 0 or 1 (in which case the deployment is always running in at least one location).
1629
1649
  */
@@ -1744,6 +1764,10 @@ export type ServerlessConfig = {
1744
1764
  configuration?: {
1745
1765
  [key: string]: unknown;
1746
1766
  };
1767
+ /**
1768
+ * The maximum number of retries for the deployment
1769
+ */
1770
+ maxRetries?: number;
1747
1771
  /**
1748
1772
  * The minimum number of replicas for the deployment. Can be 0 or 1 (in which case the deployment is always running in at least one location).
1749
1773
  */
@@ -2525,6 +2549,104 @@ export type GetIntegrationConnectionModelResponses = {
2525
2549
  */
2526
2550
  200: unknown;
2527
2551
  };
2552
+ export type ListJobsData = {
2553
+ body?: never;
2554
+ path?: never;
2555
+ query?: never;
2556
+ url: '/jobs';
2557
+ };
2558
+ export type ListJobsResponses = {
2559
+ /**
2560
+ * successful operation
2561
+ */
2562
+ 200: Array<Job>;
2563
+ };
2564
+ export type ListJobsResponse = ListJobsResponses[keyof ListJobsResponses];
2565
+ export type CreateJobData = {
2566
+ body: Job;
2567
+ path?: never;
2568
+ query?: never;
2569
+ url: '/jobs';
2570
+ };
2571
+ export type CreateJobResponses = {
2572
+ /**
2573
+ * successful operation
2574
+ */
2575
+ 200: Job;
2576
+ };
2577
+ export type CreateJobResponse = CreateJobResponses[keyof CreateJobResponses];
2578
+ export type DeleteJobData = {
2579
+ body?: never;
2580
+ path: {
2581
+ /**
2582
+ * Name of the job
2583
+ */
2584
+ jobId: string;
2585
+ };
2586
+ query?: never;
2587
+ url: '/jobs/{jobId}';
2588
+ };
2589
+ export type DeleteJobResponses = {
2590
+ /**
2591
+ * successful operation
2592
+ */
2593
+ 200: Job;
2594
+ };
2595
+ export type DeleteJobResponse = DeleteJobResponses[keyof DeleteJobResponses];
2596
+ export type GetJobData = {
2597
+ body?: never;
2598
+ path: {
2599
+ /**
2600
+ * Name of the job
2601
+ */
2602
+ jobId: string;
2603
+ };
2604
+ query?: never;
2605
+ url: '/jobs/{jobId}';
2606
+ };
2607
+ export type GetJobResponses = {
2608
+ /**
2609
+ * successful operation
2610
+ */
2611
+ 200: Model;
2612
+ };
2613
+ export type GetJobResponse = GetJobResponses[keyof GetJobResponses];
2614
+ export type UpdateJobData = {
2615
+ body: Job;
2616
+ path: {
2617
+ /**
2618
+ * Name of the job
2619
+ */
2620
+ jobId: string;
2621
+ };
2622
+ query?: never;
2623
+ url: '/jobs/{jobId}';
2624
+ };
2625
+ export type UpdateJobResponses = {
2626
+ /**
2627
+ * successful operation
2628
+ */
2629
+ 200: Job;
2630
+ };
2631
+ export type UpdateJobResponse = UpdateJobResponses[keyof UpdateJobResponses];
2632
+ export type ListJobRevisionsData = {
2633
+ body?: never;
2634
+ path: {
2635
+ /**
2636
+ * Name of the job
2637
+ */
2638
+ jobId: string;
2639
+ };
2640
+ query?: never;
2641
+ url: '/jobs/{jobId}/revisions';
2642
+ };
2643
+ export type ListJobRevisionsResponses = {
2644
+ /**
2645
+ * successful operation
2646
+ */
2647
+ 200: Array<RevisionMetadata>;
2648
+ };
2649
+ export type ListJobRevisionsResponse = ListJobRevisionsResponses[keyof ListJobRevisionsResponses];
2528
2650
  export type ListKnowledgebasesData = {
2529
2651
  body?: never;
2530
2652
  path?: never;
@@ -1,2 +1,2 @@
1
- export declare function getAlphanumericLimitedHash(input: string, maxSize: number): string;
1
+ export declare function getAlphanumericLimitedHash(input: string, maxSize?: number): string;
2
2
  export declare function getGlobalUniqueHash(workspace: string, type: string, name: string): string;
@@ -6,12 +6,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getAlphanumericLimitedHash = getAlphanumericLimitedHash;
7
7
  exports.getGlobalUniqueHash = getGlobalUniqueHash;
8
8
  const crypto_1 = __importDefault(require("crypto"));
9
- function getAlphanumericLimitedHash(input, maxSize) {
10
- const hash = crypto_1.default.createHash("sha256").update(input).digest("base64");
11
- const alphanumeric = hash.replace(/[^a-z0-9]+/g, "");
12
- return alphanumeric.length > maxSize
13
- ? alphanumeric.substring(0, maxSize)
14
- : alphanumeric;
9
+ function getAlphanumericLimitedHash(input, maxSize = 48) {
10
+ const hash = crypto_1.default.createHash('md5').update(input).digest('hex');
11
+ return hash.length > maxSize ? hash.substring(0, maxSize) : hash;
15
12
  }
16
13
  function getGlobalUniqueHash(workspace, type, name) {
17
14
  const globalUniqueName = `${workspace}-${type}-${name}`;
@@ -21,6 +21,7 @@ declare class Settings {
21
21
  get runInternalHostname(): string;
22
22
  get runInternalProtocol(): string;
23
23
  get blCloud(): boolean;
24
+ get generation(): string;
24
25
  get loggerType(): string;
25
26
  authenticate(): Promise<void>;
26
27
  }
@@ -72,7 +72,10 @@ class Settings {
72
72
  return env_js_1.env.BL_TYPE || "agents";
73
73
  }
74
74
  get runInternalHostname() {
75
- return env_js_1.env.BL_RUN_INTERNAL_HOSTNAME || "";
75
+ if (!this.generation) {
76
+ return "";
77
+ }
78
+ return env_js_1.env.BL_RUN_INTERNAL_HOST || "";
76
79
  }
77
80
  get runInternalProtocol() {
78
81
  return env_js_1.env.BL_RUN_INTERNAL_PROTOCOL || "https";
@@ -80,6 +83,9 @@ class Settings {
80
83
  get blCloud() {
81
84
  return env_js_1.env.BL_CLOUD === "true";
82
85
  }
86
+ get generation() {
87
+ return env_js_1.env.BL_GENERATION || "";
88
+ }
83
89
  get loggerType() {
84
90
  return env_js_1.env.BL_LOGGER || "http";
85
91
  }
package/dist/jobs/jobs.js CHANGED
@@ -9,17 +9,17 @@ const helpers_1 = require("yargs/helpers");
9
9
  const env_js_1 = require("../common/env.js");
10
10
  class BlJob {
11
11
  async getArguments() {
12
- if (!env_js_1.env.BL_BATCH_DATA_URL) {
12
+ if (!env_js_1.env.BL_EXECUTION_DATA_URL) {
13
13
  const argv = await (0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
14
14
  .parseAsync();
15
15
  return argv;
16
16
  }
17
- const response = await fetch(env_js_1.env.BL_BATCH_DATA_URL);
17
+ const response = await fetch(env_js_1.env.BL_EXECUTION_DATA_URL);
18
18
  const data = await response.json();
19
19
  return data.tasks[this.index] ?? {};
20
20
  }
21
21
  get indexKey() {
22
- return env_js_1.env.BL_BATCH_INDEX_KEY ?? "TASK_INDEX";
22
+ return env_js_1.env.BL_EXECUTION_INDEX_KEY ?? "TASK_INDEX";
23
23
  }
24
24
  get index() {
25
25
  return env_js_1.env[this.indexKey] ? Number(env_js_1.env[this.indexKey]) ?? 0 : 0;
@@ -63,16 +63,13 @@ class BlaxelMcpClientTransport {
63
63
  this.onerror?.(error);
64
64
  };
65
65
  this._socket.onopen = () => {
66
- logger_js_1.logger.debug("WebSocket opened");
67
66
  resolve();
68
67
  };
69
68
  this._socket.onclose = () => {
70
- logger_js_1.logger.debug("WebSocket closed");
71
69
  this.onclose?.();
72
70
  this._socket = undefined;
73
71
  };
74
72
  this._socket.onmessage = (event) => {
75
- logger_js_1.logger.debug("WebSocket message received");
76
73
  let message;
77
74
  try {
78
75
  let dataString;
@@ -15,4 +15,5 @@ export declare class SandboxAction {
15
15
  get forcedUrl(): string | null;
16
16
  get url(): string;
17
17
  handleResponseError(response: Response, data: unknown, error: unknown): void;
18
+ websocket(path: string): WebSocket | null;
18
19
  }
@@ -61,8 +61,9 @@ class SandboxAction {
61
61
  get url() {
62
62
  if (this.forcedUrl)
63
63
  return this.forcedUrl;
64
- if (settings_js_1.settings.runInternalHostname)
65
- return this.internalUrl;
64
+ // Uncomment and use this when agent and mcp are available in mk3
65
+ // Update all requests made in this package to use fallbackUrl when internalUrl is not working
66
+ // if (settings.runInternalHostname) return this.internalUrl;
66
67
  return this.externalUrl;
67
68
  }
68
69
  handleResponseError(response, data, error) {
@@ -70,5 +71,37 @@ class SandboxAction {
70
71
  throw new ResponseError(response, data, error);
71
72
  }
72
73
  }
74
+ websocket(path) {
75
+ let ws = null;
76
+ // Build ws:// or wss:// URL from baseUrl
77
+ let baseUrl = this.url.replace(/^http/, 'ws');
78
+ if (baseUrl.endsWith('/'))
79
+ baseUrl = baseUrl.slice(0, -1);
80
+ const wsUrl = `${baseUrl}/ws/${path}?token=${settings_js_1.settings.token}`;
81
+ // Use isomorphic WebSocket: browser or Node.js
82
+ let WS = undefined;
83
+ if (typeof globalThis.WebSocket !== 'undefined') {
84
+ WS = globalThis.WebSocket;
85
+ }
86
+ else {
87
+ try {
88
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
89
+ WS = require('ws');
90
+ }
91
+ catch {
92
+ WS = undefined;
93
+ }
94
+ }
95
+ if (!WS)
96
+ throw new Error('WebSocket is not available in this environment');
97
+ try {
98
+ ws = typeof WS === 'function' ? new WS(wsUrl) : new WS(wsUrl);
99
+ }
100
+ catch (err) {
101
+ console.error('WebSocket connection error:', err);
102
+ throw err;
103
+ }
104
+ return ws;
105
+ }
73
106
  }
74
107
  exports.SandboxAction = SandboxAction;
@@ -1,5 +1,5 @@
1
1
  import type { Options as ClientOptions, TDataShape, Client } from '@hey-api/client-fetch';
2
- import type { DeleteFilesystemByPathData, GetFilesystemByPathData, PutFilesystemByPathData, DeleteNetworkProcessByPidMonitorData, PostNetworkProcessByPidMonitorData, GetNetworkProcessByPidPortsData, GetProcessData, PostProcessData, DeleteProcessByIdentifierData, GetProcessByIdentifierData, DeleteProcessByIdentifierKillData, GetProcessByIdentifierLogsData, GetProcessByIdentifierLogsStreamData } from './types.gen';
2
+ import type { DeleteFilesystemByPathData, GetFilesystemByPathData, PutFilesystemByPathData, DeleteNetworkProcessByPidMonitorData, PostNetworkProcessByPidMonitorData, GetNetworkProcessByPidPortsData, GetProcessData, PostProcessData, DeleteProcessByIdentifierData, GetProcessByIdentifierData, DeleteProcessByIdentifierKillData, GetProcessByIdentifierLogsData, GetProcessByIdentifierLogsStreamData, GetWatchFilesystemByPathData } from './types.gen';
3
3
  export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = ClientOptions<TData, ThrowOnError> & {
4
4
  /**
5
5
  * You can provide a client instance returned by `createClient()` instead of
@@ -22,7 +22,7 @@ export declare const deleteFilesystemByPath: <ThrowOnError extends boolean = fal
22
22
  * Get file or directory information
23
23
  * Get content of a file or listing of a directory
24
24
  */
25
- export declare const getFilesystemByPath: <ThrowOnError extends boolean = false>(options: Options<GetFilesystemByPathData, ThrowOnError>) => import("@hey-api/client-fetch").RequestResult<import("./types.gen").Directory | import("./types.gen").FileWithContent, import("./types.gen").ErrorResponse, ThrowOnError>;
25
+ export declare const getFilesystemByPath: <ThrowOnError extends boolean = false>(options: Options<GetFilesystemByPathData, ThrowOnError>) => import("@hey-api/client-fetch").RequestResult<import("./types.gen").FileWithContent | import("./types.gen").Directory, import("./types.gen").ErrorResponse, ThrowOnError>;
26
26
  /**
27
27
  * Create or update file or directory
28
28
  * Create or update a file or directory
@@ -82,9 +82,12 @@ export declare const getProcessByIdentifierLogs: <ThrowOnError extends boolean =
82
82
  [key: string]: string;
83
83
  }, import("./types.gen").ErrorResponse, ThrowOnError>;
84
84
  /**
85
- * Get process logs in realtime
86
- * Get the stdout and stderr output of a process in realtime
85
+ * Stream process logs in real time
86
+ * Streams the stdout and stderr output of a process in real time, one line per log, prefixed with 'stdout:' or 'stderr:'. Closes when the process exits or the client disconnects.
87
87
  */
88
- export declare const getProcessByIdentifierLogsStream: <ThrowOnError extends boolean = false>(options: Options<GetProcessByIdentifierLogsStreamData, ThrowOnError>) => import("@hey-api/client-fetch").RequestResult<{
89
- [key: string]: string;
90
- }, import("./types.gen").ErrorResponse, ThrowOnError>;
88
+ export declare const getProcessByIdentifierLogsStream: <ThrowOnError extends boolean = false>(options: Options<GetProcessByIdentifierLogsStreamData, ThrowOnError>) => import("@hey-api/client-fetch").RequestResult<string, import("./types.gen").ErrorResponse, ThrowOnError>;
89
+ /**
90
+ * Stream file modification events in a directory
91
+ * Streams the path of modified files (one per line) in the given directory. Closes when the client disconnects.
92
+ */
93
+ export declare const getWatchFilesystemByPath: <ThrowOnError extends boolean = false>(options: Options<GetWatchFilesystemByPathData, ThrowOnError>) => import("@hey-api/client-fetch").RequestResult<string, import("./types.gen").ErrorResponse, ThrowOnError>;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  // This file is auto-generated by @hey-api/openapi-ts
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.getProcessByIdentifierLogsStream = exports.getProcessByIdentifierLogs = exports.deleteProcessByIdentifierKill = exports.getProcessByIdentifier = exports.deleteProcessByIdentifier = exports.postProcess = exports.getProcess = exports.getNetworkProcessByPidPorts = exports.postNetworkProcessByPidMonitor = exports.deleteNetworkProcessByPidMonitor = exports.putFilesystemByPath = exports.getFilesystemByPath = exports.deleteFilesystemByPath = void 0;
4
+ exports.getWatchFilesystemByPath = exports.getProcessByIdentifierLogsStream = exports.getProcessByIdentifierLogs = exports.deleteProcessByIdentifierKill = exports.getProcessByIdentifier = exports.deleteProcessByIdentifier = exports.postProcess = exports.getProcess = exports.getNetworkProcessByPidPorts = exports.postNetworkProcessByPidMonitor = exports.deleteNetworkProcessByPidMonitor = exports.putFilesystemByPath = exports.getFilesystemByPath = exports.deleteFilesystemByPath = void 0;
5
5
  const client_gen_1 = require("./client.gen");
6
6
  /**
7
7
  * Delete file or directory
@@ -152,8 +152,8 @@ const getProcessByIdentifierLogs = (options) => {
152
152
  };
153
153
  exports.getProcessByIdentifierLogs = getProcessByIdentifierLogs;
154
154
  /**
155
- * Get process logs in realtime
156
- * Get the stdout and stderr output of a process in realtime
155
+ * Stream process logs in real time
156
+ * Streams the stdout and stderr output of a process in real time, one line per log, prefixed with 'stdout:' or 'stderr:'. Closes when the process exits or the client disconnects.
157
157
  */
158
158
  const getProcessByIdentifierLogsStream = (options) => {
159
159
  return (options.client ?? client_gen_1.client).get({
@@ -162,3 +162,14 @@ const getProcessByIdentifierLogsStream = (options) => {
162
162
  });
163
163
  };
164
164
  exports.getProcessByIdentifierLogsStream = getProcessByIdentifierLogsStream;
165
+ /**
166
+ * Stream file modification events in a directory
167
+ * Streams the path of modified files (one per line) in the given directory. Closes when the client disconnects.
168
+ */
169
+ const getWatchFilesystemByPath = (options) => {
170
+ return (options.client ?? client_gen_1.client).get({
171
+ url: '/watch/filesystem/{path}',
172
+ ...options
173
+ });
174
+ };
175
+ exports.getWatchFilesystemByPath = getWatchFilesystemByPath;
@@ -1,11 +1,3 @@
1
- export type Directory = {
2
- files?: Array<File>;
3
- path?: string;
4
- /**
5
- * @name Subdirectories
6
- */
7
- subdirectories?: Array<Subdirectory>;
8
- };
9
1
  export type ErrorResponse = {
10
2
  error?: string;
11
3
  };
@@ -14,6 +6,9 @@ export type File = {
14
6
  lastModified?: string;
15
7
  owner?: string;
16
8
  path?: string;
9
+ /**
10
+ * swagger:strfmt string
11
+ */
17
12
  permissions?: string;
18
13
  size?: number;
19
14
  };
@@ -28,6 +23,9 @@ export type FileWithContent = {
28
23
  lastModified?: string;
29
24
  owner?: string;
30
25
  path?: string;
26
+ /**
27
+ * swagger:strfmt string
28
+ */
31
29
  permissions?: string;
32
30
  size?: number;
33
31
  };
@@ -43,7 +41,6 @@ export type ProcessKillRequest = {
43
41
  export type ProcessRequest = {
44
42
  command: string;
45
43
  name?: string;
46
- streamLogs?: boolean;
47
44
  timeout?: number;
48
45
  waitForCompletion?: boolean;
49
46
  waitForPorts?: Array<number>;
@@ -59,13 +56,18 @@ export type ProcessResponse = {
59
56
  status?: string;
60
57
  workingDir?: string;
61
58
  };
62
- export type Subdirectory = {
63
- path?: string;
64
- };
65
59
  export type SuccessResponse = {
66
60
  message?: string;
67
61
  path?: string;
68
62
  };
63
+ export type Directory = {
64
+ files?: Array<File>;
65
+ path?: string;
66
+ /**
67
+ * @name Subdirectories
68
+ */
69
+ subdirectories?: Array<Directory>;
70
+ };
69
71
  export type DeleteFilesystemByPathData = {
70
72
  body?: never;
71
73
  path: {
@@ -391,12 +393,7 @@ export type GetProcessByIdentifierLogsData = {
391
393
  */
392
394
  identifier: string;
393
395
  };
394
- query?: {
395
- /**
396
- * Stream logs
397
- */
398
- stream?: boolean;
399
- };
396
+ query?: never;
400
397
  url: '/process/{identifier}/logs';
401
398
  };
402
399
  export type GetProcessByIdentifierLogsErrors = {
@@ -427,12 +424,7 @@ export type GetProcessByIdentifierLogsStreamData = {
427
424
  */
428
425
  identifier: string;
429
426
  };
430
- query?: {
431
- /**
432
- * Stream logs
433
- */
434
- stream?: boolean;
435
- };
427
+ query?: never;
436
428
  url: '/process/{identifier}/logs/stream';
437
429
  };
438
430
  export type GetProcessByIdentifierLogsStreamErrors = {
@@ -448,13 +440,40 @@ export type GetProcessByIdentifierLogsStreamErrors = {
448
440
  export type GetProcessByIdentifierLogsStreamError = GetProcessByIdentifierLogsStreamErrors[keyof GetProcessByIdentifierLogsStreamErrors];
449
441
  export type GetProcessByIdentifierLogsStreamResponses = {
450
442
  /**
451
- * Process logs
443
+ * Stream of process logs, one line per log (prefixed with stdout:/stderr:)
452
444
  */
453
- 200: {
454
- [key: string]: string;
455
- };
445
+ 200: string;
456
446
  };
457
447
  export type GetProcessByIdentifierLogsStreamResponse = GetProcessByIdentifierLogsStreamResponses[keyof GetProcessByIdentifierLogsStreamResponses];
448
+ export type GetWatchFilesystemByPathData = {
449
+ body?: never;
450
+ path: {
451
+ /**
452
+ * Directory path to watch
453
+ */
454
+ path: string;
455
+ };
456
+ query?: never;
457
+ url: '/watch/filesystem/{path}';
458
+ };
459
+ export type GetWatchFilesystemByPathErrors = {
460
+ /**
461
+ * Invalid path
462
+ */
463
+ 400: ErrorResponse;
464
+ /**
465
+ * Internal server error
466
+ */
467
+ 500: ErrorResponse;
468
+ };
469
+ export type GetWatchFilesystemByPathError = GetWatchFilesystemByPathErrors[keyof GetWatchFilesystemByPathErrors];
470
+ export type GetWatchFilesystemByPathResponses = {
471
+ /**
472
+ * Stream of modified file paths, one per line
473
+ */
474
+ 200: string;
475
+ };
476
+ export type GetWatchFilesystemByPathResponse = GetWatchFilesystemByPathResponses[keyof GetWatchFilesystemByPathResponses];
458
477
  export type ClientOptions = {
459
478
  baseUrl: `${string}://localhost:8080` | (string & {});
460
479
  };
@@ -14,5 +14,31 @@ export declare class SandboxFileSystem extends SandboxAction {
14
14
  rm(path: string, recursive?: boolean): Promise<SuccessResponse>;
15
15
  ls(path: string): Promise<Directory>;
16
16
  cp(source: string, destination: string): Promise<CopyResponse>;
17
+ /**
18
+ * Watch for changes in a directory. Calls the callback with the changed file path (and optionally its content).
19
+ * Returns a handle with a close() method to stop watching.
20
+ * @param path Directory to watch
21
+ * @param callback Function called on each change: (filePath, content?)
22
+ * @param withContent If true, also fetches and passes the file content (default: false)
23
+ */
24
+ watch(path: string, callback: (filePath: string, content?: string) => void | Promise<void>, options?: {
25
+ ws?: boolean;
26
+ onError?: (error: Error) => void;
27
+ withContent: boolean;
28
+ }): {
29
+ close: () => void;
30
+ };
31
+ wsWatch(path: string, callback: (filePath: string, content?: string) => void | Promise<void>, options?: {
32
+ onError?: (error: Error) => void;
33
+ withContent: boolean;
34
+ }): {
35
+ close: () => void;
36
+ };
37
+ sseWatch(path: string, callback: (filePath: string, content?: string) => void | Promise<void>, options?: {
38
+ onError?: (error: Error) => void;
39
+ withContent: boolean;
40
+ }): {
41
+ close: () => void;
42
+ };
17
43
  private formatPath;
18
44
  }
@@ -111,6 +111,197 @@ class SandboxFileSystem extends action_js_1.SandboxAction {
111
111
  }
112
112
  throw new Error("Unsupported file type");
113
113
  }
114
+ /**
115
+ * Watch for changes in a directory. Calls the callback with the changed file path (and optionally its content).
116
+ * Returns a handle with a close() method to stop watching.
117
+ * @param path Directory to watch
118
+ * @param callback Function called on each change: (filePath, content?)
119
+ * @param withContent If true, also fetches and passes the file content (default: false)
120
+ */
121
+ watch(path, callback, options) {
122
+ if (options?.ws) {
123
+ return this.wsWatch(path, callback, options);
124
+ }
125
+ return this.sseWatch(path, callback, options);
126
+ }
127
+ wsWatch(path, callback, options) {
128
+ path = this.formatPath(path);
129
+ let closed = false;
130
+ let ws = this.websocket(`watch/filesystem${path.startsWith('/') ? path : '/' + path}`);
131
+ let pingInterval = null;
132
+ let pongTimeout = null;
133
+ const PING_INTERVAL_MS = 30000;
134
+ const PONG_TIMEOUT_MS = 10000;
135
+ function sendPing() {
136
+ if (ws && ws.readyState === ws.OPEN) {
137
+ try {
138
+ ws.send(JSON.stringify({ type: 'ping' }));
139
+ }
140
+ catch { }
141
+ // Set pong timeout
142
+ if (pongTimeout)
143
+ clearTimeout(pongTimeout);
144
+ pongTimeout = setTimeout(() => {
145
+ // No pong received in time, close connection
146
+ if (ws && typeof ws.close === 'function')
147
+ ws.close();
148
+ }, PONG_TIMEOUT_MS);
149
+ }
150
+ }
151
+ if (ws) {
152
+ ws.onmessage = async (event) => {
153
+ if (closed)
154
+ return;
155
+ let data;
156
+ try {
157
+ data = typeof event.data === 'string' ? event.data : event.data;
158
+ if (!data)
159
+ return;
160
+ // Accept both JSON and plain string (file path)
161
+ let payload;
162
+ try {
163
+ payload = JSON.parse(data);
164
+ }
165
+ catch {
166
+ payload = { name: data, event: undefined };
167
+ }
168
+ // Handle ping/pong
169
+ if (payload.type === 'ping') {
170
+ // Respond to ping with pong
171
+ if (ws && ws.readyState === ws.OPEN) {
172
+ try {
173
+ ws.send(JSON.stringify({ type: 'pong' }));
174
+ }
175
+ catch { }
176
+ }
177
+ return;
178
+ }
179
+ if (payload.type === 'pong') {
180
+ // Pong received, clear pong timeout
181
+ if (pongTimeout)
182
+ clearTimeout(pongTimeout);
183
+ pongTimeout = null;
184
+ return;
185
+ }
186
+ const filePath = payload.name || payload.path || data;
187
+ if (!filePath)
188
+ return;
189
+ if (options?.withContent) {
190
+ try {
191
+ const content = await this.read(filePath);
192
+ await callback(filePath, content);
193
+ }
194
+ catch (e) {
195
+ await callback(filePath, undefined);
196
+ }
197
+ }
198
+ else {
199
+ await callback(filePath);
200
+ }
201
+ }
202
+ catch (err) {
203
+ if (options?.onError)
204
+ options.onError(err);
205
+ }
206
+ };
207
+ ws.onerror = (err) => {
208
+ if (options?.onError)
209
+ options.onError(err instanceof Error ? err : new Error(String(err)));
210
+ closed = true;
211
+ if (ws && typeof ws.close === 'function')
212
+ ws.close();
213
+ };
214
+ ws.onclose = () => {
215
+ closed = true;
216
+ ws = null;
217
+ if (pingInterval)
218
+ clearInterval(pingInterval);
219
+ if (pongTimeout)
220
+ clearTimeout(pongTimeout);
221
+ };
222
+ // Start ping interval
223
+ pingInterval = setInterval(sendPing, PING_INTERVAL_MS);
224
+ }
225
+ return {
226
+ close: () => {
227
+ closed = true;
228
+ if (ws && typeof ws.close === 'function')
229
+ ws.close();
230
+ ws = null;
231
+ if (pingInterval)
232
+ clearInterval(pingInterval);
233
+ if (pongTimeout)
234
+ clearTimeout(pongTimeout);
235
+ },
236
+ };
237
+ }
238
+ sseWatch(path, callback, options) {
239
+ path = this.formatPath(path);
240
+ let closed = false;
241
+ let controller = new AbortController();
242
+ const start = async () => {
243
+ const { response, data, error } = await (0, index_js_1.getWatchFilesystemByPath)({
244
+ path: { path },
245
+ baseUrl: this.url,
246
+ parseAs: 'stream',
247
+ signal: controller.signal,
248
+ });
249
+ if (error)
250
+ throw error;
251
+ const stream = data ?? response.body;
252
+ if (!stream)
253
+ throw new Error('No stream returned');
254
+ const reader = stream.getReader();
255
+ let buffer = '';
256
+ const decoder = new TextDecoder();
257
+ try {
258
+ while (!closed) {
259
+ const { value, done } = await reader.read();
260
+ if (done)
261
+ break;
262
+ buffer += decoder.decode(value, { stream: true });
263
+ let lines = buffer.split('\n');
264
+ buffer = lines.pop();
265
+ for (const line of lines) {
266
+ const filePath = line.trim();
267
+ if (!filePath)
268
+ continue;
269
+ if (options?.withContent) {
270
+ try {
271
+ const content = await this.read(filePath);
272
+ await callback(filePath, content);
273
+ }
274
+ catch (e) {
275
+ await callback(filePath, undefined);
276
+ }
277
+ }
278
+ else {
279
+ await callback(filePath);
280
+ }
281
+ }
282
+ }
283
+ }
284
+ finally {
285
+ reader.releaseLock();
286
+ }
287
+ };
288
+ start().catch((err) => {
289
+ // Suppress AbortError when closing
290
+ if (!(err && err.name === 'AbortError')) {
291
+ if (options?.onError) {
292
+ options.onError(err);
293
+ }
294
+ }
295
+ closed = true;
296
+ controller?.abort();
297
+ });
298
+ return {
299
+ close: () => {
300
+ closed = true;
301
+ controller?.abort();
302
+ },
303
+ };
304
+ }
114
305
  formatPath(path) {
115
306
  if (path === "/") {
116
307
  return path;
@@ -3,7 +3,33 @@ import { SandboxAction } from "./action.js";
3
3
  import { DeleteProcessByIdentifierKillResponse, DeleteProcessByIdentifierResponse, GetProcessByIdentifierResponse, GetProcessResponse, PostProcessResponse, ProcessRequest } from "./client/index.js";
4
4
  export declare class SandboxProcess extends SandboxAction {
5
5
  constructor(sandbox: Sandbox);
6
+ streamLogs(identifier: string, options: {
7
+ ws?: boolean;
8
+ onLog?: (log: string) => void;
9
+ onStdout?: (stdout: string) => void;
10
+ onStderr?: (stderr: string) => void;
11
+ }): {
12
+ close: () => void;
13
+ };
14
+ wsStreamLogs(identifier: string, options: {
15
+ onLog?: (log: string) => void;
16
+ onStdout?: (stdout: string) => void;
17
+ onStderr?: (stderr: string) => void;
18
+ }): {
19
+ close: () => void;
20
+ };
21
+ sseStreamLogs(identifier: string, options: {
22
+ onLog?: (log: string) => void;
23
+ onStdout?: (stdout: string) => void;
24
+ onStderr?: (stderr: string) => void;
25
+ }): {
26
+ close: () => void;
27
+ };
6
28
  exec(process: ProcessRequest): Promise<PostProcessResponse>;
29
+ wait(identifier: string, { maxWait, interval }?: {
30
+ maxWait?: number;
31
+ interval?: number;
32
+ }): Promise<GetProcessByIdentifierResponse>;
7
33
  get(identifier: string): Promise<GetProcessByIdentifierResponse>;
8
34
  list(): Promise<GetProcessResponse>;
9
35
  stop(identifier: string): Promise<DeleteProcessByIdentifierResponse>;
@@ -1,12 +1,176 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SandboxProcess = void 0;
4
+ const settings_js_1 = require("../common/settings.js");
4
5
  const action_js_1 = require("./action.js");
5
6
  const index_js_1 = require("./client/index.js");
6
7
  class SandboxProcess extends action_js_1.SandboxAction {
7
8
  constructor(sandbox) {
8
9
  super(sandbox);
9
10
  }
11
+ streamLogs(identifier, options) {
12
+ if (options.ws) {
13
+ return this.wsStreamLogs(identifier, options);
14
+ }
15
+ return this.sseStreamLogs(identifier, options);
16
+ }
17
+ wsStreamLogs(identifier, options) {
18
+ let closed = false;
19
+ let ws = this.websocket(`process/${identifier}/logs/stream`);
20
+ let pingInterval = null;
21
+ let pongTimeout = null;
22
+ const PING_INTERVAL_MS = 30000;
23
+ const PONG_TIMEOUT_MS = 10000;
24
+ function sendPing() {
25
+ if (ws && ws.readyState === ws.OPEN) {
26
+ try {
27
+ ws.send(JSON.stringify({ type: 'ping' }));
28
+ }
29
+ catch { }
30
+ // Set pong timeout
31
+ if (pongTimeout)
32
+ clearTimeout(pongTimeout);
33
+ pongTimeout = setTimeout(() => {
34
+ // No pong received in time, close connection
35
+ if (ws && typeof ws.close === 'function')
36
+ ws.close();
37
+ }, PONG_TIMEOUT_MS);
38
+ }
39
+ }
40
+ if (ws) {
41
+ ws.onmessage = (event) => {
42
+ if (closed)
43
+ return;
44
+ let data;
45
+ try {
46
+ data = typeof event.data === 'string' ? event.data : event.data;
47
+ if (!data)
48
+ return;
49
+ let payload;
50
+ try {
51
+ payload = JSON.parse(data);
52
+ }
53
+ catch {
54
+ payload = { log: data };
55
+ }
56
+ // Handle ping/pong
57
+ if (payload.type === 'ping') {
58
+ // Respond to ping with pong
59
+ if (ws && ws.readyState === ws.OPEN) {
60
+ try {
61
+ ws.send(JSON.stringify({ type: 'pong' }));
62
+ }
63
+ catch { }
64
+ }
65
+ return;
66
+ }
67
+ if (payload.type === 'pong') {
68
+ // Pong received, clear pong timeout
69
+ if (pongTimeout)
70
+ clearTimeout(pongTimeout);
71
+ pongTimeout = null;
72
+ return;
73
+ }
74
+ if (payload.type === 'log') {
75
+ const logLine = payload.log || "";
76
+ if (typeof logLine === 'string') {
77
+ if (logLine.startsWith('stdout:')) {
78
+ options.onStdout?.(logLine.slice(7));
79
+ options.onLog?.(logLine.slice(7));
80
+ }
81
+ else if (logLine.startsWith('stderr:')) {
82
+ options.onStderr?.(logLine.slice(7));
83
+ options.onLog?.(logLine.slice(7));
84
+ }
85
+ else {
86
+ options.onLog?.(logLine);
87
+ }
88
+ }
89
+ }
90
+ }
91
+ catch (err) {
92
+ console.error('WebSocket log stream error:', err);
93
+ }
94
+ };
95
+ ws.onerror = (err) => {
96
+ closed = true;
97
+ if (ws && typeof ws.close === 'function')
98
+ ws.close();
99
+ };
100
+ ws.onclose = () => {
101
+ closed = true;
102
+ ws = null;
103
+ if (pingInterval)
104
+ clearInterval(pingInterval);
105
+ if (pongTimeout)
106
+ clearTimeout(pongTimeout);
107
+ };
108
+ // Start ping interval
109
+ pingInterval = setInterval(sendPing, PING_INTERVAL_MS);
110
+ }
111
+ return {
112
+ close: () => {
113
+ closed = true;
114
+ if (ws && typeof ws.close === 'function')
115
+ ws.close();
116
+ ws = null;
117
+ if (pingInterval)
118
+ clearInterval(pingInterval);
119
+ if (pongTimeout)
120
+ clearTimeout(pongTimeout);
121
+ },
122
+ };
123
+ }
124
+ sseStreamLogs(identifier, options) {
125
+ const controller = new AbortController();
126
+ (async () => {
127
+ try {
128
+ const stream = await fetch(`${this.url}/process/${identifier}/logs/stream`, {
129
+ method: 'GET',
130
+ signal: controller.signal,
131
+ headers: settings_js_1.settings.headers,
132
+ });
133
+ if (stream.status !== 200) {
134
+ throw new Error(`Failed to stream logs: ${await stream.text()}`);
135
+ }
136
+ if (!stream.body)
137
+ throw new Error('No stream body');
138
+ const reader = stream.body.getReader();
139
+ const decoder = new TextDecoder();
140
+ let buffer = '';
141
+ while (true) {
142
+ const { done, value } = await reader.read();
143
+ if (done)
144
+ break;
145
+ buffer += decoder.decode(value, { stream: true });
146
+ let lines = buffer.split(/\r?\n/);
147
+ buffer = lines.pop();
148
+ for (const line of lines) {
149
+ if (line.startsWith('stdout:')) {
150
+ options.onStdout?.(line.slice(7));
151
+ options.onLog?.(line.slice(7));
152
+ }
153
+ else if (line.startsWith('stderr:')) {
154
+ options.onStderr?.(line.slice(7));
155
+ options.onLog?.(line.slice(7));
156
+ }
157
+ else {
158
+ options.onLog?.(line);
159
+ }
160
+ }
161
+ }
162
+ }
163
+ catch (err) {
164
+ if (err && err.name !== 'AbortError') {
165
+ console.error("Stream error:", err);
166
+ throw err;
167
+ }
168
+ }
169
+ })();
170
+ return {
171
+ close: () => controller.abort(),
172
+ };
173
+ }
10
174
  async exec(process) {
11
175
  const { response, data, error } = await (0, index_js_1.postProcess)({
12
176
  body: process,
@@ -15,6 +179,25 @@ class SandboxProcess extends action_js_1.SandboxAction {
15
179
  this.handleResponseError(response, data, error);
16
180
  return data;
17
181
  }
182
+ async wait(identifier, { maxWait = 60000, interval = 1000 } = {}) {
183
+ const startTime = Date.now();
184
+ let status = "running";
185
+ let data = await this.get(identifier);
186
+ while (status === "running") {
187
+ await new Promise((resolve) => setTimeout(resolve, interval));
188
+ try {
189
+ data = await this.get(identifier);
190
+ status = data.status ?? "running";
191
+ }
192
+ catch {
193
+ break;
194
+ }
195
+ if (Date.now() - startTime > maxWait) {
196
+ throw new Error("Process did not finish in time");
197
+ }
198
+ }
199
+ return data;
200
+ }
18
201
  async get(identifier) {
19
202
  const { response, data, error } = await (0, index_js_1.getProcessByIdentifier)({
20
203
  path: { identifier },
@@ -55,4 +55,5 @@ export declare const telemetryRegistry: TelemetryRegistry;
55
55
  * Create a span with the registered provider
56
56
  */
57
57
  export declare function startSpan(name: string, options?: BlaxelSpanOptions): BlaxelSpan;
58
+ export declare function withSpan<T>(name: string, fn: () => T, options?: BlaxelSpanOptions): T;
58
59
  export {};
@@ -3,6 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.telemetryRegistry = void 0;
5
5
  exports.startSpan = startSpan;
6
+ exports.withSpan = withSpan;
6
7
  /**
7
8
  * No-operation implementation of Span
8
9
  */
@@ -57,3 +58,16 @@ exports.telemetryRegistry = TelemetryRegistry.getInstance();
57
58
  function startSpan(name, options) {
58
59
  return exports.telemetryRegistry.getProvider().startSpan(name, options);
59
60
  }
61
+ function withSpan(name, fn, options) {
62
+ const span = startSpan(name, options);
63
+ try {
64
+ const result = fn();
65
+ span.end();
66
+ return result;
67
+ }
68
+ catch (error) {
69
+ span.recordException(error);
70
+ span.end();
71
+ throw error;
72
+ }
73
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blaxel/core",
3
- "version": "0.2.1-dev1",
3
+ "version": "0.2.1-dev11",
4
4
  "description": "Blaxel Core SDK for TypeScript",
5
5
  "license": "MIT",
6
6
  "author": "Blaxel, INC (https://blaxel.ai)",