Add artifact upload feature to CLI for agent sessions
This commit is contained in:
parent
932681bcab
commit
85a4a69ebe
10 changed files with 804 additions and 2 deletions
335
extensions/cli/docs/artifact-uploads.md
Normal file
335
extensions/cli/docs/artifact-uploads.md
Normal file
|
|
@ -0,0 +1,335 @@
|
|||
# Artifact Upload Architecture
|
||||
|
||||
## Overview
|
||||
|
||||
The artifact upload feature enables Continue agents running in devboxes to upload arbitrary files (screenshots, videos, logs) to agent session storage for review and debugging purposes. The architecture uses a two-step presigned URL pattern for secure, performant uploads.
|
||||
|
||||
## Architecture Pattern: Presigned URLs
|
||||
|
||||
### Why Presigned URLs?
|
||||
|
||||
The artifact upload system uses **presigned URLs** for direct client-to-S3 uploads rather than proxying files through the backend. This design provides several benefits:
|
||||
|
||||
1. **Security**: The backend controls who can upload, validates file types/sizes, and enforces storage limits before issuing a presigned URL. The agent cannot bypass these validations.
|
||||
|
||||
2. **Performance**: Files upload directly from the devbox to S3, avoiding bandwidth costs and latency of routing through the backend API server.
|
||||
|
||||
3. **Scalability**: The backend doesn't become a bottleneck for file uploads. S3 handles the heavy lifting of data transfer.
|
||||
|
||||
4. **Simplicity**: Presigned URLs are time-limited (15 minutes), self-contained credentials that require no complex token management.
|
||||
|
||||
## Two-Step Upload Flow
|
||||
|
||||
### Step 1: Request Presigned URL
|
||||
|
||||
The agent requests a presigned upload URL from the backend:
|
||||
|
||||
**Request:**
|
||||
|
||||
```http
|
||||
POST /agents/artifacts/upload-url
|
||||
Authorization: Bearer <CONTINUE_API_KEY>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"agentSessionId": "<session-id>",
|
||||
"filename": "screenshot.png",
|
||||
"contentType": "image/png",
|
||||
"fileSize": 1048576
|
||||
}
|
||||
```
|
||||
|
||||
**Backend Validation:**
|
||||
|
||||
- Authenticates the API key and verifies session ownership
|
||||
- Validates filename (no path traversal, allowed extension)
|
||||
- Validates file size against per-file limit (50MB default)
|
||||
- Validates content type against allowlist
|
||||
- Checks total session storage against limit (500MB default)
|
||||
|
||||
**Response (if validation passes):**
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://s3.amazonaws.com/bucket/sessions/org/abc123/artifacts/screenshot.png?X-Amz-...",
|
||||
"key": "sessions/org/abc123/artifacts/screenshot.png",
|
||||
"expiresIn": 900
|
||||
}
|
||||
```
|
||||
|
||||
**Response (if validation fails):**
|
||||
|
||||
```http
|
||||
400 Bad Request
|
||||
|
||||
{
|
||||
"error": "File size exceeds maximum allowed (50MB)"
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: Upload to S3
|
||||
|
||||
The agent uploads the file directly to S3 using the presigned URL:
|
||||
|
||||
**Request:**
|
||||
|
||||
```http
|
||||
PUT <presigned-url>
|
||||
Content-Type: image/png
|
||||
<file-contents>
|
||||
```
|
||||
|
||||
S3 validates the presigned URL signature and accepts the upload. The backend is not involved in this step.
|
||||
|
||||
## Storage Organization
|
||||
|
||||
Artifacts are stored in S3 with the following path structure:
|
||||
|
||||
```
|
||||
sessions/
|
||||
user/
|
||||
<userId>/
|
||||
<sessionId>/
|
||||
artifacts/
|
||||
screenshot.png
|
||||
video.mp4
|
||||
debug.log
|
||||
session.json # Session state (existing)
|
||||
diff.txt # Git diff (existing)
|
||||
org/
|
||||
<organizationId>/
|
||||
<sessionId>/
|
||||
artifacts/
|
||||
...
|
||||
```
|
||||
|
||||
This structure:
|
||||
|
||||
- Maintains backward compatibility with existing `session.json` and `diff.txt` files
|
||||
- Isolates user/org data for security
|
||||
- Groups all session-related files together
|
||||
- Allows simple recursive deletion when a session is removed
|
||||
|
||||
## File Type and Size Limits
|
||||
|
||||
### Allowed File Types
|
||||
|
||||
The system validates both file extensions and MIME types:
|
||||
|
||||
**Images:** `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`
|
||||
**Videos:** `.mp4`, `.mov`, `.avi`, `.webm`
|
||||
**Text/Logs:** `.log`, `.txt`, `.json`, `.xml`, `.csv`, `.html`
|
||||
|
||||
Content types are validated against an allowlist to prevent uploading executable files or other potentially dangerous content.
|
||||
|
||||
### Size Limits
|
||||
|
||||
Two limits are enforced:
|
||||
|
||||
1. **Per-File Limit:** 50MB (configurable via `ARTIFACT_MAX_FILE_SIZE_MB`)
|
||||
2. **Total Session Storage:** 500MB (configurable via `ARTIFACT_MAX_TOTAL_SIZE_MB`)
|
||||
|
||||
The backend calculates total storage by summing all files under the session's S3 prefix before issuing presigned URLs. This prevents a single session from consuming excessive storage.
|
||||
|
||||
## CLI Usage
|
||||
|
||||
### Using the UploadArtifact Tool (Recommended)
|
||||
|
||||
The `UploadArtifact` tool is available when running with the beta flag:
|
||||
|
||||
```bash
|
||||
cn serve --id <agentSessionId> --beta-upload-artifact-tool
|
||||
```
|
||||
|
||||
Agents can then use the built-in `UploadArtifact` tool to upload files:
|
||||
|
||||
```typescript
|
||||
// The agent calls this tool with the file path
|
||||
{
|
||||
"name": "UploadArtifact",
|
||||
"parameters": {
|
||||
"filePath": "/tmp/screenshot.png"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The tool will:
|
||||
|
||||
- Validate the file exists and is an allowed type
|
||||
- Check file size limits (50MB max per file)
|
||||
- Upload to session storage
|
||||
- Return success message or detailed error
|
||||
|
||||
**Tool Description:** "Upload a file (screenshot, video, log) to the session artifacts for user review. Supported formats: images (png, jpg, jpeg, gif, webp), videos (mp4, mov, avi, webm), and text files (log, txt, json, xml, csv, html). Maximum file size: 50MB. **If an artifact with the same filename already exists, it will be overwritten with the new file.**"
|
||||
|
||||
**Requirements:**
|
||||
|
||||
- Must run with `--id <agentSessionId>` (agent mode)
|
||||
- Must enable `--beta-upload-artifact-tool` flag
|
||||
- User must be authenticated (`cn login`)
|
||||
|
||||
### Programmatic Upload (Service API)
|
||||
|
||||
For custom implementations, use the service directly:
|
||||
|
||||
```typescript
|
||||
import { services } from "./services/index.js";
|
||||
|
||||
const result = await services.artifactUpload.uploadArtifact({
|
||||
agentSessionId: process.env.AGENT_SESSION_ID,
|
||||
filePath: "/tmp/screenshot.png",
|
||||
accessToken: process.env.CONTINUE_API_KEY,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
console.log(`Uploaded: ${result.filename}`);
|
||||
} else {
|
||||
console.error(`Failed: ${result.error}`);
|
||||
}
|
||||
```
|
||||
|
||||
### Multiple Files
|
||||
|
||||
```typescript
|
||||
const results = await services.artifactUpload.uploadArtifacts(
|
||||
process.env.AGENT_SESSION_ID,
|
||||
["/tmp/screenshot1.png", "/tmp/screenshot2.png", "/tmp/debug.log"],
|
||||
process.env.CONTINUE_API_KEY,
|
||||
);
|
||||
|
||||
results.forEach((result) => {
|
||||
console.log(`${result.filename}: ${result.success ? "✓" : "✗"}`);
|
||||
});
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
The CLI requires these environment variables for artifact uploads:
|
||||
|
||||
- `CONTINUE_API_KEY`: Bearer token for backend authentication
|
||||
- `CONTINUE_API_BASE`: API base URL (defaults to `https://api.continue.dev/`)
|
||||
- `AGENT_SESSION_ID`: The current agent session identifier
|
||||
|
||||
These are automatically provided when running in Continue's devbox environment.
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Validation Errors (400)
|
||||
|
||||
- Invalid filename (path traversal, disallowed extension)
|
||||
- File too large (exceeds per-file limit)
|
||||
- Storage limit exceeded (session total > 500MB)
|
||||
- Invalid content type
|
||||
|
||||
### Authentication Errors (401/403)
|
||||
|
||||
- Missing or invalid API key
|
||||
- User doesn't own the agent session
|
||||
|
||||
### Upload Errors (S3)
|
||||
|
||||
- Network failure during upload
|
||||
- Presigned URL expired (15-minute timeout)
|
||||
- S3 service error
|
||||
|
||||
All errors are logged and returned with descriptive messages. Failed uploads don't crash the agent - they return an error result that the agent can handle gracefully.
|
||||
|
||||
## Frontend Access
|
||||
|
||||
The frontend can list and download artifacts using:
|
||||
|
||||
**List artifacts:**
|
||||
|
||||
```http
|
||||
GET /agents/{agentSessionId}/artifacts
|
||||
Authorization: Bearer <API_KEY>
|
||||
|
||||
Response:
|
||||
{
|
||||
"artifacts": [
|
||||
{
|
||||
"filename": "screenshot.png",
|
||||
"size": 1048576,
|
||||
"sizeFormatted": "1.0 MB",
|
||||
"lastModified": "2025-12-08T10:30:00Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Download artifact:**
|
||||
|
||||
```http
|
||||
GET /agents/{agentSessionId}/artifacts/{filename}/download
|
||||
Authorization: Bearer <API_KEY>
|
||||
|
||||
Response:
|
||||
{
|
||||
"url": "https://s3.amazonaws.com/...",
|
||||
"expiresIn": 3600
|
||||
}
|
||||
```
|
||||
|
||||
The frontend then uses the presigned download URL to fetch the artifact directly from S3.
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **Authentication**: All endpoints require valid API keys tied to user/org accounts
|
||||
2. **Authorization**: Session ownership is verified before issuing presigned URLs
|
||||
3. **Path Traversal Prevention**: Filenames are validated to prevent `../` attacks
|
||||
4. **Content Validation**: File types are restricted via extension and MIME type checks
|
||||
5. **Rate Limiting**: Storage limits prevent abuse (per-file and total session limits)
|
||||
6. **Time-Limited URLs**: Presigned URLs expire after 15 minutes for uploads, 1 hour for downloads
|
||||
7. **Storage Isolation**: Files are scoped to user/org prefixes, preventing cross-tenant access
|
||||
|
||||
## Design Trade-offs
|
||||
|
||||
### Chosen: No Database Tracking
|
||||
|
||||
**Decision:** Store artifacts as files in S3 without tracking individual files in the database.
|
||||
|
||||
**Rationale:**
|
||||
|
||||
- Simpler implementation (no new database tables)
|
||||
- Files are the source of truth (no sync issues between DB and S3)
|
||||
- Fast listing via S3 API (ListObjects)
|
||||
- Automatic cleanup when deleting session folder
|
||||
|
||||
**Trade-off:** Cannot query artifacts across sessions or track metadata without scanning S3.
|
||||
|
||||
### Chosen: Overwrite on Name Collision
|
||||
|
||||
**Decision:** If the same filename is uploaded twice, the last upload wins.
|
||||
|
||||
**Rationale:**
|
||||
|
||||
- Simpler than versioning or auto-renaming
|
||||
- Common use case: agent re-uploading updated screenshot
|
||||
- Reduces storage consumption
|
||||
|
||||
**Trade-off:** No version history for artifacts.
|
||||
|
||||
### Chosen: Direct S3 Upload (Presigned URLs)
|
||||
|
||||
**Decision:** Use presigned URLs instead of proxying files through backend.
|
||||
|
||||
**Rationale:**
|
||||
|
||||
- Better performance (no backend bottleneck)
|
||||
- Lower cost (no backend bandwidth charges)
|
||||
- Proven pattern (already used in StorageSyncService)
|
||||
|
||||
**Trade-off:** Backend cannot inspect file contents before upload (relies on validation at URL generation).
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
- **Compression**: Automatically compress screenshots/videos before upload
|
||||
- **Retention Policies**: Auto-delete artifacts after N days
|
||||
- **Artifact Types**: Support more file types (PDFs, archives)
|
||||
- **Preview Generation**: Generate thumbnails for images/videos
|
||||
- **Streaming**: Support large file uploads with multipart upload
|
||||
- **Metadata**: Attach custom metadata to artifacts (tags, descriptions)
|
||||
|
||||
---
|
||||
|
||||
This document describes the initial artifact upload implementation. Update it when the architecture evolves.
|
||||
|
|
@ -35,4 +35,6 @@ export interface ExtendedCommandOptions extends BaseCommandOptions {
|
|||
readonly?: boolean;
|
||||
/** Start in auto mode (all tools allowed) */
|
||||
auto?: boolean;
|
||||
/** Enable beta UploadArtifact tool */
|
||||
betaUploadArtifactTool?: boolean;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -379,6 +379,10 @@ program
|
|||
"--id <storageId>",
|
||||
"Upload session snapshots to Continue-managed storage using the provided identifier",
|
||||
)
|
||||
.option(
|
||||
"--beta-upload-artifact-tool",
|
||||
"Enable beta UploadArtifact tool for uploading screenshots, videos, and logs",
|
||||
)
|
||||
.action(async (prompt, options) => {
|
||||
// Telemetry: record command invocation
|
||||
await posthogService.capture("cliCommand", { command: "serve" });
|
||||
|
|
|
|||
278
extensions/cli/src/services/ArtifactUploadService.ts
Normal file
278
extensions/cli/src/services/ArtifactUploadService.ts
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
|
||||
import { env } from "../env.js";
|
||||
import { formatError } from "../util/formatError.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import type { ArtifactUploadServiceState } from "./types.js";
|
||||
|
||||
/**
|
||||
* Response from backend when requesting a presigned upload URL
|
||||
*/
|
||||
type ArtifactPresignedUrlResponse = {
|
||||
url: string;
|
||||
key: string;
|
||||
expiresIn: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Options for uploading an artifact file
|
||||
*/
|
||||
export interface ArtifactUploadOptions {
|
||||
/** The agent session ID to upload to */
|
||||
agentSessionId: string;
|
||||
/** Path to the file to upload */
|
||||
filePath: string;
|
||||
/** Optional content type (auto-detected from extension if not provided) */
|
||||
contentType?: string;
|
||||
/** Access token for authentication */
|
||||
accessToken: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of an artifact upload attempt
|
||||
*/
|
||||
export interface ArtifactUploadResult {
|
||||
success: boolean;
|
||||
filename: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service for uploading artifact files (screenshots, videos, logs) to agent sessions.
|
||||
*
|
||||
* Architecture:
|
||||
* 1. Request presigned URL from backend API
|
||||
* 2. Upload file directly to S3 using presigned URL
|
||||
* 3. Backend validates file size, type, and storage limits before issuing URL
|
||||
*
|
||||
* This two-step process provides security (backend controls access) and performance
|
||||
* (direct S3 upload without proxying through backend).
|
||||
*/
|
||||
export class ArtifactUploadService {
|
||||
private state: ArtifactUploadServiceState = {
|
||||
uploadsInProgress: 0,
|
||||
lastError: null,
|
||||
};
|
||||
|
||||
async initialize(): Promise<ArtifactUploadServiceState> {
|
||||
return this.getState();
|
||||
}
|
||||
|
||||
getState(): ArtifactUploadServiceState {
|
||||
return { ...this.state };
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload an artifact file to an agent session.
|
||||
*
|
||||
* @param options Upload options including session ID, file path, and auth token
|
||||
* @returns Upload result with success status and error if failed
|
||||
*/
|
||||
async uploadArtifact(
|
||||
options: ArtifactUploadOptions,
|
||||
): Promise<ArtifactUploadResult> {
|
||||
const filename = path.basename(options.filePath);
|
||||
|
||||
// Validate file exists
|
||||
if (!fs.existsSync(options.filePath)) {
|
||||
const error = `File not found: ${options.filePath}`;
|
||||
logger.error(error);
|
||||
return { success: false, filename, error };
|
||||
}
|
||||
|
||||
// Get file stats
|
||||
const stats = fs.statSync(options.filePath);
|
||||
const fileSizeBytes = stats.size;
|
||||
|
||||
// Detect content type if not provided
|
||||
const contentType = options.contentType ?? this.inferContentType(filename);
|
||||
|
||||
this.setState({
|
||||
uploadsInProgress: this.state.uploadsInProgress + 1,
|
||||
lastError: null,
|
||||
});
|
||||
|
||||
try {
|
||||
// Step 1: Request presigned URL from backend
|
||||
logger.info(`Requesting upload URL for artifact: ${filename}`);
|
||||
const presignedData = await this.requestPresignedUploadUrl(
|
||||
options.agentSessionId,
|
||||
filename,
|
||||
contentType,
|
||||
fileSizeBytes,
|
||||
options.accessToken,
|
||||
);
|
||||
|
||||
if (!presignedData) {
|
||||
const error = "Failed to obtain presigned upload URL";
|
||||
this.setState({
|
||||
uploadsInProgress: this.state.uploadsInProgress - 1,
|
||||
lastError: error,
|
||||
});
|
||||
return { success: false, filename, error };
|
||||
}
|
||||
|
||||
// Step 2: Upload file directly to S3
|
||||
logger.info(`Uploading artifact to S3: ${filename}`);
|
||||
await this.uploadFileToS3(
|
||||
presignedData.url,
|
||||
options.filePath,
|
||||
contentType,
|
||||
);
|
||||
|
||||
logger.info(`Successfully uploaded artifact: ${filename}`);
|
||||
this.setState({
|
||||
uploadsInProgress: this.state.uploadsInProgress - 1,
|
||||
lastError: null,
|
||||
});
|
||||
|
||||
return { success: true, filename };
|
||||
} catch (error) {
|
||||
const errorMsg = formatError(error);
|
||||
logger.error(`Failed to upload artifact ${filename}: ${errorMsg}`);
|
||||
this.setState({
|
||||
uploadsInProgress: this.state.uploadsInProgress - 1,
|
||||
lastError: errorMsg,
|
||||
});
|
||||
return { success: false, filename, error: errorMsg };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload multiple artifacts in parallel.
|
||||
*
|
||||
* @param agentSessionId The agent session ID
|
||||
* @param filePaths Array of file paths to upload
|
||||
* @param accessToken Access token for authentication
|
||||
* @returns Array of upload results
|
||||
*/
|
||||
async uploadArtifacts(
|
||||
agentSessionId: string,
|
||||
filePaths: string[],
|
||||
accessToken: string,
|
||||
): Promise<ArtifactUploadResult[]> {
|
||||
const uploadPromises = filePaths.map((filePath) =>
|
||||
this.uploadArtifact({
|
||||
agentSessionId,
|
||||
filePath,
|
||||
accessToken,
|
||||
}),
|
||||
);
|
||||
|
||||
return Promise.all(uploadPromises);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a presigned URL from the backend API for uploading an artifact.
|
||||
*/
|
||||
private async requestPresignedUploadUrl(
|
||||
agentSessionId: string,
|
||||
filename: string,
|
||||
contentType: string,
|
||||
fileSizeBytes: number,
|
||||
accessToken: string,
|
||||
): Promise<ArtifactPresignedUrlResponse | null> {
|
||||
const url = new URL("agents/artifacts/upload-url", env.apiBase);
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
agentSessionId,
|
||||
filename,
|
||||
contentType,
|
||||
fileSize: fileSizeBytes,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
const errorMsg =
|
||||
errorData.error || `${response.status} ${response.statusText}`;
|
||||
logger.warn(`Failed to get presigned upload URL: ${errorMsg}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = (await response.json()) as ArtifactPresignedUrlResponse;
|
||||
|
||||
if (!data.url) {
|
||||
logger.warn("Presigned URL response missing required 'url' field");
|
||||
return null;
|
||||
}
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
`Error requesting presigned upload URL: ${formatError(error)}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a file to S3 using a presigned URL.
|
||||
*/
|
||||
private async uploadFileToS3(
|
||||
presignedUrl: string,
|
||||
filePath: string,
|
||||
contentType: string,
|
||||
): Promise<void> {
|
||||
// Read file contents
|
||||
const fileBuffer = fs.readFileSync(filePath);
|
||||
|
||||
// Upload to S3
|
||||
const response = await fetch(presignedUrl, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": contentType,
|
||||
},
|
||||
body: fileBuffer,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const statusText = `${response.status} ${response.statusText}`.trim();
|
||||
const responseBody = await response.text();
|
||||
throw new Error(`S3 upload failed (${statusText}): ${responseBody}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer content type from file extension.
|
||||
*/
|
||||
private inferContentType(filename: string): string {
|
||||
const ext = path.extname(filename).toLowerCase();
|
||||
|
||||
const contentTypeMap: Record<string, string> = {
|
||||
// Images
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".gif": "image/gif",
|
||||
".webp": "image/webp",
|
||||
// Videos
|
||||
".mp4": "video/mp4",
|
||||
".mov": "video/quicktime",
|
||||
".avi": "video/x-msvideo",
|
||||
".webm": "video/webm",
|
||||
// Text/Logs
|
||||
".log": "text/plain",
|
||||
".txt": "text/plain",
|
||||
".json": "application/json",
|
||||
".xml": "text/xml",
|
||||
".csv": "text/csv",
|
||||
".html": "text/html",
|
||||
};
|
||||
|
||||
return contentTypeMap[ext] || "application/octet-stream";
|
||||
}
|
||||
|
||||
private setState(next: ArtifactUploadServiceState): void {
|
||||
this.state = { ...next };
|
||||
}
|
||||
}
|
||||
|
|
@ -1,9 +1,11 @@
|
|||
import { loadAuthConfig } from "../auth/workos.js";
|
||||
import { initializeWithOnboarding } from "../onboarding.js";
|
||||
import { setBetaUploadArtifactToolEnabled } from "../tools/toolsConfig.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { AgentFileService } from "./AgentFileService.js";
|
||||
import { ApiClientService } from "./ApiClientService.js";
|
||||
import { ArtifactUploadService } from "./ArtifactUploadService.js";
|
||||
import { AuthService } from "./AuthService.js";
|
||||
import { ChatHistoryService } from "./ChatHistoryService.js";
|
||||
import { ConfigService } from "./ConfigService.js";
|
||||
|
|
@ -43,6 +45,7 @@ const storageSyncService = new StorageSyncService();
|
|||
const agentFileService = new AgentFileService();
|
||||
const toolPermissionService = new ToolPermissionService();
|
||||
const systemMessageService = new SystemMessageService();
|
||||
const artifactUploadService = new ArtifactUploadService();
|
||||
|
||||
/**
|
||||
* Initialize all services and register them with the service container
|
||||
|
|
@ -52,6 +55,11 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
|
|||
logger.debug("Initializing service registry");
|
||||
|
||||
const commandOptions = initOptions.options || {};
|
||||
|
||||
// Configure beta tools based on command options
|
||||
if (commandOptions.betaUploadArtifactTool) {
|
||||
setBetaUploadArtifactToolEnabled(true);
|
||||
}
|
||||
// Handle onboarding for TUI mode (headless: false) unless explicitly skipped
|
||||
if (!initOptions.headless && !initOptions.skipOnboarding) {
|
||||
const authConfig = loadAuthConfig();
|
||||
|
|
@ -290,6 +298,12 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) {
|
|||
[],
|
||||
);
|
||||
|
||||
serviceContainer.register(
|
||||
SERVICE_NAMES.ARTIFACT_UPLOAD,
|
||||
() => artifactUploadService.initialize(),
|
||||
[],
|
||||
);
|
||||
|
||||
serviceContainer.register(
|
||||
SERVICE_NAMES.CHAT_HISTORY,
|
||||
() => chatHistoryService.initialize(undefined, initOptions.headless),
|
||||
|
|
@ -357,6 +371,7 @@ export const services = {
|
|||
storageSync: storageSyncService,
|
||||
agentFile: agentFileService,
|
||||
toolPermissions: toolPermissionService,
|
||||
artifactUpload: artifactUploadService,
|
||||
} as const;
|
||||
|
||||
// Export the service container for advanced usage
|
||||
|
|
|
|||
|
|
@ -125,6 +125,11 @@ export interface AgentFileServiceState {
|
|||
parsedRules: ReturnType<typeof parseAgentFileRules> | null;
|
||||
}
|
||||
|
||||
export interface ArtifactUploadServiceState {
|
||||
uploadsInProgress: number;
|
||||
lastError: string | null;
|
||||
}
|
||||
|
||||
export type { ChatHistoryState } from "./ChatHistoryService.js";
|
||||
export type { FileIndexServiceState } from "./FileIndexService.js";
|
||||
|
||||
|
|
@ -145,6 +150,7 @@ export const SERVICE_NAMES = {
|
|||
UPDATE: "update",
|
||||
STORAGE_SYNC: "storageSync",
|
||||
AGENT_FILE: "agentFile",
|
||||
ARTIFACT_UPLOAD: "artifactUpload",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { readFileTool } from "./readFile.js";
|
|||
import { reportFailureTool } from "./reportFailure.js";
|
||||
import { runTerminalCommandTool } from "./runTerminalCommand.js";
|
||||
import { searchCodeTool } from "./searchCode.js";
|
||||
import { uploadArtifactTool } from "./uploadArtifact.js";
|
||||
import { writeChecklistTool } from "./writeChecklist.js";
|
||||
import { writeFileTool } from "./writeFile.js";
|
||||
|
||||
|
|
@ -23,4 +24,5 @@ export const ALL_BUILT_IN_TOOLS = [
|
|||
writeChecklistTool,
|
||||
exitTool,
|
||||
reportFailureTool,
|
||||
uploadArtifactTool,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import { readFileTool } from "./readFile.js";
|
|||
import { reportFailureTool } from "./reportFailure.js";
|
||||
import { runTerminalCommandTool } from "./runTerminalCommand.js";
|
||||
import { checkIfRipgrepIsInstalled, searchCodeTool } from "./searchCode.js";
|
||||
import { isBetaUploadArtifactToolEnabled } from "./toolsConfig.js";
|
||||
import {
|
||||
type Tool,
|
||||
type ToolCall,
|
||||
|
|
@ -35,6 +36,7 @@ import {
|
|||
ParameterSchema,
|
||||
PreprocessedToolCall,
|
||||
} from "./types.js";
|
||||
import { uploadArtifactTool } from "./uploadArtifact.js";
|
||||
import { writeChecklistTool } from "./writeChecklist.js";
|
||||
import { writeFileTool } from "./writeFile.js";
|
||||
|
||||
|
|
@ -75,11 +77,16 @@ export async function getAllAvailableTools(
|
|||
tools.push(...BUILTIN_SEARCH_TOOLS);
|
||||
}
|
||||
|
||||
// Add ReportFailure tool if no agent ID is present
|
||||
// (it requires --id to function and will confuse the agent if unavailable)
|
||||
// Add agent-specific tools if agent ID is present
|
||||
// (these require --id to function and will confuse the agent if unavailable)
|
||||
const agentId = getAgentIdFromArgs();
|
||||
if (agentId) {
|
||||
tools.push(reportFailureTool);
|
||||
|
||||
// UploadArtifact tool is gated behind beta flag
|
||||
if (isBetaUploadArtifactToolEnabled()) {
|
||||
tools.push(uploadArtifactTool);
|
||||
}
|
||||
}
|
||||
|
||||
// If model is capable, exclude editTool in favor of multiEditTool
|
||||
|
|
|
|||
14
extensions/cli/src/tools/toolsConfig.ts
Normal file
14
extensions/cli/src/tools/toolsConfig.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
/**
|
||||
* Global configuration for tools system.
|
||||
* This stores command-line flags that affect tool availability.
|
||||
*/
|
||||
|
||||
let betaUploadArtifactToolEnabled = false;
|
||||
|
||||
export function setBetaUploadArtifactToolEnabled(enabled: boolean): void {
|
||||
betaUploadArtifactToolEnabled = enabled;
|
||||
}
|
||||
|
||||
export function isBetaUploadArtifactToolEnabled(): boolean {
|
||||
return betaUploadArtifactToolEnabled;
|
||||
}
|
||||
139
extensions/cli/src/tools/uploadArtifact.ts
Normal file
139
extensions/cli/src/tools/uploadArtifact.ts
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
|
||||
import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
|
||||
|
||||
import { getAccessToken, loadAuthConfig } from "../auth/workos.js";
|
||||
import { services } from "../services/index.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { Tool } from "./types.js";
|
||||
|
||||
/**
|
||||
* Extract the agent ID from the --id command line flag
|
||||
*/
|
||||
function getAgentIdFromArgs(): string | undefined {
|
||||
const args = process.argv;
|
||||
const idIndex = args.indexOf("--id");
|
||||
if (idIndex !== -1 && idIndex + 1 < args.length) {
|
||||
return args[idIndex + 1];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export const uploadArtifactTool: Tool = {
|
||||
name: "UploadArtifact",
|
||||
displayName: "Upload Artifact",
|
||||
description:
|
||||
"Upload a file (screenshot, video, log) to the session artifacts for user review. Supported formats: images (png, jpg, jpeg, gif, webp), videos (mp4, mov, avi, webm), and text files (log, txt, json, xml, csv, html). Maximum file size: 50MB. If an artifact with the same filename already exists, it will be overwritten with the new file.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filePath"],
|
||||
properties: {
|
||||
filePath: {
|
||||
type: "string",
|
||||
description:
|
||||
"Absolute path to the file to upload (e.g., /tmp/screenshot.png)",
|
||||
},
|
||||
},
|
||||
},
|
||||
readonly: true,
|
||||
isBuiltIn: true,
|
||||
run: async (args: { filePath: string }): Promise<string> => {
|
||||
try {
|
||||
const trimmedPath = args.filePath?.trim();
|
||||
if (!trimmedPath) {
|
||||
throw new ContinueError(
|
||||
ContinueErrorReason.Unspecified,
|
||||
"filePath is required to upload an artifact.",
|
||||
);
|
||||
}
|
||||
|
||||
// Get agent session ID
|
||||
const agentId = getAgentIdFromArgs();
|
||||
if (!agentId) {
|
||||
throw new ContinueError(
|
||||
ContinueErrorReason.Unspecified,
|
||||
"Agent ID is required. This tool only works with 'cn serve --id <agentId>'.",
|
||||
);
|
||||
}
|
||||
|
||||
// Get access token
|
||||
const authConfig = loadAuthConfig();
|
||||
const accessToken = getAccessToken(authConfig);
|
||||
if (!accessToken) {
|
||||
throw new ContinueError(
|
||||
ContinueErrorReason.Unspecified,
|
||||
"Authentication required. Please log in with 'cn login'.",
|
||||
);
|
||||
}
|
||||
|
||||
// Validate file exists
|
||||
if (!fs.existsSync(trimmedPath)) {
|
||||
throw new ContinueError(
|
||||
ContinueErrorReason.Unspecified,
|
||||
`File not found: ${trimmedPath}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Get file stats for logging
|
||||
const stats = fs.statSync(trimmedPath);
|
||||
const fileSizeMB = (stats.size / (1024 * 1024)).toFixed(2);
|
||||
const filename = path.basename(trimmedPath);
|
||||
|
||||
logger.info(`Uploading artifact: ${filename} (${fileSizeMB} MB)`);
|
||||
|
||||
// Upload the artifact
|
||||
const result = await services.artifactUpload.uploadArtifact({
|
||||
agentSessionId: agentId,
|
||||
filePath: trimmedPath,
|
||||
accessToken,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
logger.info(`Successfully uploaded artifact: ${result.filename}`);
|
||||
return `Artifact uploaded successfully: ${result.filename} (${fileSizeMB} MB). The user can view it in the Artifacts tab of the session.`;
|
||||
} else {
|
||||
// Handle specific error cases with helpful messages
|
||||
const errorMsg = result.error || "Unknown error";
|
||||
|
||||
if (errorMsg.includes("File size exceeds")) {
|
||||
throw new ContinueError(
|
||||
ContinueErrorReason.Unspecified,
|
||||
`File is too large (${fileSizeMB} MB). Maximum allowed size is 50MB. Consider compressing the file or splitting it into smaller parts.`,
|
||||
);
|
||||
} else if (errorMsg.includes("Storage limit exceeded")) {
|
||||
throw new ContinueError(
|
||||
ContinueErrorReason.Unspecified,
|
||||
"Session storage limit exceeded (500MB total). The user may need to delete old artifacts or you may need to reduce the number of uploads.",
|
||||
);
|
||||
} else if (
|
||||
errorMsg.includes("not allowed") ||
|
||||
errorMsg.includes("extension")
|
||||
) {
|
||||
throw new ContinueError(
|
||||
ContinueErrorReason.Unspecified,
|
||||
`File type not supported. Only images (png, jpg, jpeg, gif, webp), videos (mp4, mov, avi, webm), and text files (log, txt, json, xml, csv, html) are allowed.`,
|
||||
);
|
||||
} else {
|
||||
throw new ContinueError(
|
||||
ContinueErrorReason.Unspecified,
|
||||
`Failed to upload artifact: ${errorMsg}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ContinueError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
logger.error(`Error uploading artifact: ${errorMessage}`);
|
||||
throw new ContinueError(
|
||||
ContinueErrorReason.Unspecified,
|
||||
`Error uploading artifact: ${errorMessage}`,
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
Loading…
Add table
Reference in a new issue