@codeguide/core 0.0.28 → 0.0.29

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.
Files changed (79) hide show
  1. package/__tests__/services/usage/usage-service.test.ts +442 -83
  2. package/codeguide.ts +3 -0
  3. package/dist/codeguide.d.ts +2 -1
  4. package/dist/codeguide.js +1 -0
  5. package/dist/index.d.ts +4 -3
  6. package/dist/services/base/base-service.d.ts +21 -0
  7. package/dist/services/base/base-service.js +114 -0
  8. package/dist/services/codespace/codespace-service.d.ts +55 -1
  9. package/dist/services/codespace/codespace-service.js +257 -0
  10. package/dist/services/codespace/codespace-types.d.ts +192 -12
  11. package/dist/services/codespace/index.d.ts +1 -1
  12. package/dist/services/index.d.ts +2 -0
  13. package/dist/services/index.js +4 -1
  14. package/dist/services/projects/project-types.d.ts +66 -32
  15. package/dist/services/starter-kits/index.d.ts +2 -0
  16. package/dist/services/starter-kits/index.js +20 -0
  17. package/dist/services/starter-kits/starter-kits-service.d.ts +13 -0
  18. package/dist/services/starter-kits/starter-kits-service.js +27 -0
  19. package/dist/services/starter-kits/starter-kits-types.d.ts +34 -0
  20. package/dist/services/starter-kits/starter-kits-types.js +2 -0
  21. package/dist/services/tasks/task-service.d.ts +2 -1
  22. package/dist/services/tasks/task-service.js +8 -0
  23. package/dist/services/tasks/task-types.d.ts +26 -7
  24. package/dist/services/usage/usage-service.d.ts +5 -2
  25. package/dist/services/usage/usage-service.js +58 -9
  26. package/dist/services/usage/usage-types.d.ts +150 -26
  27. package/docs/.vitepress/README.md +51 -0
  28. package/docs/.vitepress/config.ts +139 -0
  29. package/docs/.vitepress/theme/custom.css +80 -0
  30. package/docs/.vitepress/theme/index.ts +13 -0
  31. package/docs/.vitepress/tsconfig.json +19 -0
  32. package/docs/QUICKSTART.md +77 -0
  33. package/docs/README.md +134 -0
  34. package/docs/README_SETUP.md +46 -0
  35. package/docs/authentication.md +351 -0
  36. package/docs/codeguide-client.md +350 -0
  37. package/docs/codespace-models.md +1004 -0
  38. package/docs/codespace-service.md +444 -0
  39. package/docs/index.md +135 -0
  40. package/docs/package.json +14 -0
  41. package/docs/projects-service.md +688 -0
  42. package/docs/security-keys-service.md +773 -0
  43. package/docs/starter-kits-service.md +249 -0
  44. package/docs/task-service.md +955 -0
  45. package/docs/testsprite_tests/TC001_Homepage_Load_and_Hero_Section_Display.py +70 -0
  46. package/docs/testsprite_tests/TC002_Sidebar_Navigation_ExpandCollapse_Functionality.py +73 -0
  47. package/docs/testsprite_tests/TC003_Full_Text_Local_Search_with_Keyboard_Shortcut.py +90 -0
  48. package/docs/testsprite_tests/TC004_Dark_Mode_Toggle_and_Persistence.py +73 -0
  49. package/docs/testsprite_tests/TC005_Mobile_Responsiveness_and_Touch_Navigation.py +113 -0
  50. package/docs/testsprite_tests/TC006_GitHub_Integration_Edit_this_page_Links.py +73 -0
  51. package/docs/testsprite_tests/TC007_Syntax_Highlighting_and_Code_Copy_Functionality.py +73 -0
  52. package/docs/testsprite_tests/TC008_Auto_Generated_Table_of_Contents_Accuracy.py +73 -0
  53. package/docs/testsprite_tests/TC009_SEO_and_Content_Discoverability_Verification.py +73 -0
  54. package/docs/testsprite_tests/TC010_Accessibility_Compliance_WCAG_AA.py +73 -0
  55. package/docs/testsprite_tests/TC011_Local_Development_Workflow_Build_and_Hot_Reload.py +74 -0
  56. package/docs/testsprite_tests/TC012_Performance_Metrics_Compliance.py +73 -0
  57. package/docs/testsprite_tests/standard_prd.json +122 -0
  58. package/docs/testsprite_tests/testsprite-mcp-test-report.html +2508 -0
  59. package/docs/testsprite_tests/testsprite-mcp-test-report.md +273 -0
  60. package/docs/testsprite_tests/testsprite_frontend_test_plan.json +390 -0
  61. package/docs/usage-service.md +291 -1
  62. package/index.ts +11 -3
  63. package/package.json +16 -2
  64. package/plans/CODESPACE_LOGS_STREAMING_GUIDE.md +320 -0
  65. package/plans/CODESPACE_TASK_LOGS_API_COMPLETE_GUIDE.md +821 -0
  66. package/services/base/base-service.ts +130 -0
  67. package/services/codespace/codespace-service.ts +337 -0
  68. package/services/codespace/codespace-types.ts +262 -13
  69. package/services/codespace/index.ts +16 -1
  70. package/services/index.ts +2 -0
  71. package/services/projects/README.md +107 -34
  72. package/services/projects/project-types.ts +69 -32
  73. package/services/starter-kits/index.ts +2 -0
  74. package/services/starter-kits/starter-kits-service.ts +33 -0
  75. package/services/starter-kits/starter-kits-types.ts +38 -0
  76. package/services/tasks/task-service.ts +10 -0
  77. package/services/tasks/task-types.ts +29 -7
  78. package/services/usage/usage-service.ts +59 -10
  79. package/services/usage/usage-types.ts +178 -27
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Overview
4
4
 
5
- The Usage Service provides methods to track usage, check credits, and retrieve authorization information for users.
5
+ The Usage Service provides methods to track usage, check credits, retrieve authorization information, and access comprehensive dashboard analytics for users.
6
6
 
7
7
  ## Methods
8
8
 
@@ -324,3 +324,293 @@ interface PlanLimits {
324
324
  }
325
325
  }
326
326
  ```
327
+
328
+ # Dashboard Analytics
329
+
330
+ The Usage Service also provides comprehensive dashboard analytics endpoints for visualizing usage patterns, costs, and trends. All dashboard endpoints follow the `/usage/dashboard/*` pattern.
331
+
332
+ ## `getDashboardAnalytics(params?)`
333
+
334
+ Retrieves comprehensive analytics data with daily breakdowns, trends, and top services for dashboard visualization.
335
+
336
+ **Endpoint:** `GET /usage/dashboard/analytics`
337
+
338
+ **Parameters:** `DashboardAnalyticsRequest` (optional)
339
+ ```typescript
340
+ interface DashboardAnalyticsRequest {
341
+ period?: "7d" | "1w" | "1m" | "3m" // Time period
342
+ start_date?: string // Custom start date (YYYY-MM-DD)
343
+ end_date?: string // Custom end date (YYYY-MM-DD)
344
+ service_type?: "docs" | "chat" | "codespace_task" | "api"
345
+ }
346
+ ```
347
+
348
+ **Returns:** `Promise<DashboardAnalyticsResponse>`
349
+
350
+ **Response Structure:**
351
+ ```typescript
352
+ interface DashboardAnalyticsResponse {
353
+ status: string
354
+ data: {
355
+ period: {
356
+ start: string
357
+ end: string
358
+ label: string
359
+ }
360
+ daily_usage: Array<{
361
+ date: string
362
+ credits_consumed: number
363
+ cost_usd: number
364
+ requests_count: number
365
+ average_credits_per_request: number
366
+ }>
367
+ totals: {
368
+ credits_consumed: number
369
+ cost_usd: number
370
+ requests_count: number
371
+ }
372
+ averages: {
373
+ daily_credits: number
374
+ daily_requests: number
375
+ }
376
+ trends: {
377
+ credits_consumed: number // Percentage change
378
+ requests_count: number // Percentage change
379
+ }
380
+ top_services: Array<{
381
+ service_type: string
382
+ credits_consumed: number
383
+ requests_count: number
384
+ }>
385
+ }
386
+ }
387
+ ```
388
+
389
+ **Example Usage:**
390
+ ```typescript
391
+ // Get last 7 days analytics
392
+ const analytics = await codeguide.usage.getDashboardAnalytics({ period: '7d' })
393
+
394
+ // Get custom date range for docs service
395
+ const docsAnalytics = await codeguide.usage.getDashboardAnalytics({
396
+ start_date: '2024-01-01',
397
+ end_date: '2024-01-31',
398
+ service_type: 'docs'
399
+ })
400
+ ```
401
+
402
+ ## `getUsageDetails(params?)`
403
+
404
+ Retrieves paginated individual usage records with filtering and sorting capabilities for detailed analysis.
405
+
406
+ **Endpoint:** `GET /usage/dashboard/details`
407
+
408
+ **Parameters:** `UsageDetailsRequest` (optional)
409
+ ```typescript
410
+ interface UsageDetailsRequest {
411
+ period?: "7d" | "1w" | "1m" | "3m"
412
+ start_date?: string
413
+ end_date?: string
414
+ service_type?: "docs" | "chat" | "codespace_task" | "api"
415
+ page?: number // Default: 1
416
+ page_size?: number // Default: 50, Max: 100
417
+ sort_by?: "created_at" | "credits_consumed" | "cost_amount" // Default: "created_at"
418
+ sort_order?: "asc" | "desc" // Default: "desc"
419
+ }
420
+ ```
421
+
422
+ **Returns:** `Promise<UsageDetailsResponse>`
423
+
424
+ **Response Structure:**
425
+ ```typescript
426
+ interface UsageDetailsResponse {
427
+ status: string
428
+ data: Array<{
429
+ id: string
430
+ created_at: string
431
+ service_type: string
432
+ model_name: string
433
+ usage_type: string
434
+ units_consumed: number
435
+ credits_consumed: number
436
+ cost_amount: number | null
437
+ }>
438
+ pagination: {
439
+ page: number
440
+ page_size: number
441
+ total_count: number
442
+ total_pages: number
443
+ has_next: boolean
444
+ has_prev: boolean
445
+ }
446
+ filters: {
447
+ period: string | null
448
+ start_date: string | null
449
+ end_date: string | null
450
+ service_type: string | null
451
+ }
452
+ }
453
+ ```
454
+
455
+ **Example Usage:**
456
+ ```typescript
457
+ // Get first page of usage details for last 7 days
458
+ const details = await codeguide.usage.getUsageDetails({ period: '7d' })
459
+
460
+ // Get page 2 with custom sorting
461
+ const sortedDetails = await codeguide.usage.getUsageDetails({
462
+ period: '1m',
463
+ page: 2,
464
+ page_size: 25,
465
+ sort_by: 'credits_consumed',
466
+ sort_order: 'desc'
467
+ })
468
+ ```
469
+
470
+ ## `getUsageSummary(params?)`
471
+
472
+ Retrieves quick overview statistics for dashboard widgets, including current vs previous period comparisons and billing cycle information.
473
+
474
+ **Endpoint:** `GET /usage/dashboard/summary`
475
+
476
+ **Parameters:** `UsageSummaryRequest` (optional)
477
+ ```typescript
478
+ interface UsageSummaryRequest {
479
+ period?: "7d" | "1w" | "1m" | "3m"
480
+ start_date?: string
481
+ end_date?: string
482
+ }
483
+ ```
484
+
485
+ **Returns:** `Promise<UsageSummaryResponse>`
486
+
487
+ **Response Structure:**
488
+ ```typescript
489
+ interface UsageSummaryResponse {
490
+ status: string
491
+ data: {
492
+ current_period: {
493
+ credits_consumed: number
494
+ cost_usd: number
495
+ requests_count: number
496
+ }
497
+ previous_period: {
498
+ credits_consumed: number
499
+ cost_usd: number
500
+ requests_count: number
501
+ }
502
+ billing_cycle: {
503
+ total_allotted: number
504
+ total_consumed: number
505
+ remaining_credits: number
506
+ }
507
+ utilization_percentage: number
508
+ remaining_credits: number
509
+ daily_average: number
510
+ projected_monthly: number
511
+ }
512
+ }
513
+ ```
514
+
515
+ **Example Usage:**
516
+ ```typescript
517
+ // Get summary for last 7 days
518
+ const summary = await codeguide.usage.getUsageSummary({ period: '7d' })
519
+
520
+ // Get monthly summary
521
+ const monthlySummary = await codeguide.usage.getUsageSummary({ period: '1m' })
522
+ ```
523
+
524
+ ## `getServiceBreakdown(params?)`
525
+
526
+ Retrieves usage breakdown by service type for pie charts and comparative analysis.
527
+
528
+ **Endpoint:** `GET /usage/dashboard/services`
529
+
530
+ **Parameters:** `ServiceBreakdownRequest` (optional)
531
+ ```typescript
532
+ interface ServiceBreakdownRequest {
533
+ period?: "7d" | "1w" | "1m" | "3m"
534
+ start_date?: string
535
+ end_date?: string
536
+ }
537
+ ```
538
+
539
+ **Returns:** `Promise<ServiceBreakdownResponse>`
540
+
541
+ **Response Structure:**
542
+ ```typescript
543
+ interface ServiceBreakdownResponse {
544
+ status: string
545
+ data: {
546
+ period: {
547
+ start: string
548
+ end: string
549
+ label: string
550
+ }
551
+ services: Array<{
552
+ service_type: string
553
+ credits_consumed: number
554
+ percentage: number
555
+ cost_usd: number
556
+ requests_count: number
557
+ trend: number // Percentage change
558
+ }>
559
+ total_credits: number
560
+ total_cost: number
561
+ }
562
+ }
563
+ ```
564
+
565
+ **Example Usage:**
566
+ ```typescript
567
+ // Get service breakdown for last 7 days
568
+ const breakdown = await codeguide.usage.getServiceBreakdown({ period: '7d' })
569
+
570
+ // Get service breakdown for custom date range
571
+ const customBreakdown = await codeguide.usage.getServiceBreakdown({
572
+ start_date: '2024-01-01',
573
+ end_date: '2024-01-31'
574
+ })
575
+ ```
576
+
577
+ ## Complete Dashboard Example
578
+
579
+ ```typescript
580
+ import { CodeGuide } from '@codeguide/core'
581
+
582
+ const codeguide = new CodeGuide({
583
+ baseUrl: 'https://api.codeguide.app',
584
+ databaseApiKey: 'sk_your_key',
585
+ })
586
+
587
+ // Get comprehensive dashboard data
588
+ async function loadDashboardData() {
589
+ try {
590
+ // Main analytics with trends
591
+ const analytics = await codeguide.usage.getDashboardAnalytics({ period: '7d' })
592
+
593
+ // Quick overview for widgets
594
+ const summary = await codeguide.usage.getUsageSummary({ period: '7d' })
595
+
596
+ // Service breakdown for pie charts
597
+ const services = await codeguide.usage.getServiceBreakdown({ period: '7d' })
598
+
599
+ // Detailed records for table
600
+ const details = await codeguide.usage.getUsageDetails({
601
+ period: '7d',
602
+ page_size: 100,
603
+ sort_by: 'credits_consumed',
604
+ sort_order: 'desc'
605
+ })
606
+
607
+ console.log('Dashboard Analytics:', analytics.data)
608
+ console.log('Summary Stats:', summary.data)
609
+ console.log('Service Breakdown:', services.data)
610
+ console.log('Usage Details:', details.data)
611
+
612
+ } catch (error) {
613
+ console.error('Failed to load dashboard data:', error)
614
+ }
615
+ }
616
+ ```
package/index.ts CHANGED
@@ -18,7 +18,7 @@ export type {
18
18
  ProjectRepository,
19
19
  GetProjectsRequest,
20
20
  PaginatedProjectsRequest,
21
- PaginatedProjectsResponse
21
+ PaginatedProjectsResponse,
22
22
  } from './services/projects/project-types'
23
23
  export type {
24
24
  CreateCodespaceTaskRequestV2 as CreateCodespaceTaskRequest,
@@ -30,7 +30,7 @@ export type {
30
30
  GetCodespaceTaskResponse,
31
31
  CodespaceTaskData,
32
32
  TechnicalDocument,
33
- GetProjectTasksByCodespaceResponse
33
+ GetProjectTasksByCodespaceResponse,
34
34
  } from './services/codespace/codespace-types'
35
35
 
36
36
  // Export commonly used external tokens types for convenience
@@ -44,5 +44,13 @@ export type {
44
44
  FindBestMatchRequest,
45
45
  FindBestMatchResponse,
46
46
  Platform,
47
- TokenType
47
+ TokenType,
48
48
  } from './services/external-tokens/external-tokens-types'
49
+
50
+ // Export commonly used starter kits types for convenience
51
+ export type {
52
+ StarterKit,
53
+ StarterKitMetadata,
54
+ GetStarterKitsRequest,
55
+ GetStarterKitsResponse,
56
+ } from './services/starter-kits/starter-kits-types'
package/package.json CHANGED
@@ -1,14 +1,28 @@
1
1
  {
2
2
  "name": "@codeguide/core",
3
- "version": "0.0.28",
3
+ "version": "0.0.29",
4
4
  "description": "Core package for code guidance with programmatic API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./dist/services/starter-kits/starter-kits-types": {
13
+ "types": "./dist/services/starter-kits/starter-kits-types.d.ts"
14
+ }
15
+ },
7
16
  "scripts": {
8
17
  "build": "tsc",
9
18
  "test": "jest --config=jest.config.json",
10
19
  "test:watch": "jest --config=jest.config.json --watch",
11
- "test:coverage": "jest --config=jest.config.json --coverage"
20
+ "test:coverage": "jest --config=jest.config.json --coverage",
21
+ "docs:dev": "cd docs && npm run dev",
22
+ "docs:build": "cd docs && npm run build",
23
+ "docs:preview": "cd docs && npm run preview",
24
+ "docs:install": "cd docs && npm install",
25
+ "docs:setup": "npm run docs:install"
12
26
  },
13
27
  "keywords": [
14
28
  "api",
@@ -0,0 +1,320 @@
1
+ # Codespace Logs Streaming Guide
2
+
3
+ ## Overview
4
+ The codespace logs API now supports real-time streaming using Server-Sent Events (SSE). This allows you to monitor logs from long-running codespace tasks in real-time.
5
+
6
+ ## Endpoints
7
+
8
+ ### 1. Standard REST API (Polling)
9
+ ```
10
+ GET /codespace/task/{codespace_task_id}/logs
11
+ ```
12
+
13
+ **Query Parameters:**
14
+ - `limit` (1-500, default: 50) - Number of logs to return
15
+ - `offset` (default: 0) - Pagination offset
16
+ - `log_type` - Filter by type (thinking, coding, info, error, success)
17
+ - `step_name` - Filter by step name (partial matching)
18
+ - `search` - Search in message content
19
+ - `sort_by` (created_at, step_name, log_type) - Sort field
20
+ - `sort_order` (asc, desc) - Sort order
21
+ - `since` - Get logs after timestamp (for incremental updates)
22
+
23
+ ### 2. Real-time Streaming (SSE) ⭐
24
+ ```
25
+ GET /codespace/task/{codespace_task_id}/logs/stream
26
+ ```
27
+
28
+ **Query Parameters:**
29
+ - `since` (optional) - Start from timestamp (gets recent logs if not provided)
30
+ - `timeout` (30-1800 seconds, default: 300) - Stream timeout
31
+
32
+ ## Client Implementation Examples
33
+
34
+ ### JavaScript/TypeScript (Recommended)
35
+
36
+ ```javascript
37
+ // Basic streaming setup
38
+ const taskLogsStream = (taskId) => {
39
+ const eventSource = new EventSource(
40
+ `/codespace/task/${taskId}/logs/stream`,
41
+ {
42
+ headers: {
43
+ 'Authorization': `Bearer ${yourAuthToken}`
44
+ }
45
+ }
46
+ );
47
+
48
+ // Listen for new logs
49
+ eventSource.addEventListener('log', (event) => {
50
+ const log = JSON.parse(event.data);
51
+ console.log('New log:', log);
52
+
53
+ // Update UI
54
+ appendLogToTerminal(log);
55
+ });
56
+
57
+ // Listen for heartbeat (keep-alive)
58
+ eventSource.addEventListener('heartbeat', (event) => {
59
+ const data = JSON.parse(event.data);
60
+ console.log('Heartbeat:', data.timestamp);
61
+ });
62
+
63
+ // Listen for completion
64
+ eventSource.addEventListener('complete', (event) => {
65
+ console.log('Task completed!');
66
+ eventSource.close();
67
+ showCompletionMessage();
68
+ });
69
+
70
+ // Handle errors
71
+ eventSource.addEventListener('error', (event) => {
72
+ console.error('Stream error:', event);
73
+ eventSource.close();
74
+ showErrorMessage();
75
+ });
76
+
77
+ // Handle timeout
78
+ eventSource.addEventListener('timeout', (event) => {
79
+ console.log('Stream timeout, reconnecting...');
80
+ eventSource.close();
81
+ // Optionally reconnect with the 'since' parameter
82
+ reconnectWithTimestamp(taskId, lastTimestamp);
83
+ });
84
+
85
+ return eventSource;
86
+ };
87
+
88
+ // Usage
89
+ const stream = taskLogsStream('your-codespace-task-id');
90
+
91
+ // To stop streaming
92
+ stream.close();
93
+ ```
94
+
95
+ ### React Hook Example
96
+
97
+ ```jsx
98
+ import { useEffect, useState } from 'react';
99
+
100
+ export const useCodespaceLogs = (taskId, authToken) => {
101
+ const [logs, setLogs] = useState([]);
102
+ const [isStreaming, setIsStreaming] = useState(false);
103
+ const [error, setError] = useState(null);
104
+
105
+ useEffect(() => {
106
+ if (!taskId) return;
107
+
108
+ setIsStreaming(true);
109
+ setError(null);
110
+
111
+ const eventSource = new EventSource(
112
+ `/codespace/task/${taskId}/logs/stream`,
113
+ {
114
+ headers: {
115
+ 'Authorization': `Bearer ${authToken}`
116
+ }
117
+ }
118
+ );
119
+
120
+ eventSource.addEventListener('log', (event) => {
121
+ const log = JSON.parse(event.data);
122
+ setLogs(prev => [...prev, log]);
123
+ });
124
+
125
+ eventSource.addEventListener('complete', () => {
126
+ setIsStreaming(false);
127
+ eventSource.close();
128
+ });
129
+
130
+ eventSource.addEventListener('error', () => {
131
+ setError('Failed to stream logs');
132
+ setIsStreaming(false);
133
+ eventSource.close();
134
+ });
135
+
136
+ return () => {
137
+ eventSource.close();
138
+ };
139
+ }, [taskId, authToken]);
140
+
141
+ return { logs, isStreaming, error };
142
+ };
143
+
144
+ // Usage in component
145
+ function LogsViewer({ taskId, authToken }) {
146
+ const { logs, isStreaming, error } = useCodespaceLogs(taskId, authToken);
147
+
148
+ if (error) return <div>Error: {error}</div>;
149
+
150
+ return (
151
+ <div className="logs-container">
152
+ <div className="status">
153
+ {isStreaming ? '🔄 Streaming...' : '✅ Complete'}
154
+ </div>
155
+ {logs.map(log => (
156
+ <div key={log.id} className={`log log-${log.log_type}`}>
157
+ <span className="timestamp">{log.created_at}</span>
158
+ <span className="step">{log.step_name}</span>
159
+ <span className="message">{log.message}</span>
160
+ </div>
161
+ ))}
162
+ </div>
163
+ );
164
+ }
165
+ ```
166
+
167
+ ### Python Example
168
+
169
+ ```python
170
+ import requests
171
+ import json
172
+ from datetime import datetime
173
+
174
+ def stream_codespace_logs(task_id, auth_token):
175
+ """Stream logs from a codespace task."""
176
+ url = f"http://localhost:8000/codespace/task/{task_id}/logs/stream"
177
+ headers = {
178
+ 'Authorization': f'Bearer {auth_token}',
179
+ 'Accept': 'text/event-stream'
180
+ }
181
+
182
+ try:
183
+ response = requests.get(url, headers=headers, stream=True)
184
+ response.raise_for_status()
185
+
186
+ for line in response.iter_lines():
187
+ if line:
188
+ line = line.decode('utf-8')
189
+
190
+ if line.startswith('data: '):
191
+ data = json.loads(line[6:])
192
+ print(f"[{datetime.now()}] {data}")
193
+ elif line.startswith('event: '):
194
+ event_type = line[7:]
195
+ print(f"Event: {event_type}")
196
+
197
+ if event_type == 'complete':
198
+ print("Task completed!")
199
+ break
200
+ elif event_type == 'error':
201
+ print("Error occurred!")
202
+ break
203
+
204
+ except requests.exceptions.RequestException as e:
205
+ print(f"Error streaming logs: {e}")
206
+
207
+ # Usage
208
+ stream_codespace_logs('your-task-id', 'your-auth-token')
209
+ ```
210
+
211
+ ### curl Example (for testing)
212
+
213
+ ```bash
214
+ # Basic stream
215
+ curl -N -H "Authorization: Bearer YOUR_TOKEN" \
216
+ "http://localhost:8000/codespace/task/TASK_ID/logs/stream"
217
+
218
+ # With custom timeout
219
+ curl -N -H "Authorization: Bearer YOUR_TOKEN" \
220
+ "http://localhost:8000/codespace/task/TASK_ID/logs/stream?timeout=600"
221
+
222
+ # Start from specific timestamp
223
+ curl -N -H "Authorization: Bearer YOUR_TOKEN" \
224
+ "http://localhost:8000/codespace/task/TASK_ID/logs/stream?since=2024-01-01T00:00:00Z"
225
+ ```
226
+
227
+ ## SSE Event Types
228
+
229
+ ### `log`
230
+ ```json
231
+ {
232
+ "id": "uuid",
233
+ "step_name": "task_creation",
234
+ "log_type": "info",
235
+ "message": "🚀 Your coding task is ready!",
236
+ "created_at": "2024-01-01T00:00:00Z",
237
+ "progress_percentage": 25,
238
+ "metadata": {}
239
+ }
240
+ ```
241
+
242
+ ### `heartbeat`
243
+ ```json
244
+ {
245
+ "timestamp": "2024-01-01T00:00:00Z"
246
+ }
247
+ ```
248
+
249
+ ### `complete`
250
+ ```json
251
+ {
252
+ "message": "Task completed"
253
+ }
254
+ ```
255
+
256
+ ### `timeout`
257
+ ```json
258
+ {
259
+ "message": "Stream timeout reached"
260
+ }
261
+ ```
262
+
263
+ ### `error`
264
+ ```json
265
+ {
266
+ "error": "Error message"
267
+ }
268
+ ```
269
+
270
+ ## Reconnection Strategy
271
+
272
+ For production use, implement automatic reconnection:
273
+
274
+ ```javascript
275
+ const connectWithRetry = (taskId, maxRetries = 5) => {
276
+ let retryCount = 0;
277
+
278
+ const connect = () => {
279
+ const eventSource = new EventSource(`/codespace/task/${taskId}/logs/stream`);
280
+
281
+ eventSource.addEventListener('log', (event) => {
282
+ retryCount = 0; // Reset retry count on successful message
283
+ const log = JSON.parse(event.data);
284
+ handleLog(log);
285
+ });
286
+
287
+ eventSource.addEventListener('error', () => {
288
+ eventSource.close();
289
+
290
+ if (retryCount < maxRetries) {
291
+ retryCount++;
292
+ console.log(`Reconnecting... (${retryCount}/${maxRetries})`);
293
+ setTimeout(connect, 2000 * retryCount); // Exponential backoff
294
+ } else {
295
+ console.error('Max retries reached');
296
+ showErrorMessage();
297
+ }
298
+ });
299
+
300
+ return eventSource;
301
+ };
302
+
303
+ return connect();
304
+ };
305
+ ```
306
+
307
+ ## Production Considerations
308
+
309
+ 1. **Authentication**: Ensure proper auth tokens are sent with SSE requests
310
+ 2. **Error Handling**: Implement robust error handling and reconnection logic
311
+ 3. **Rate Limiting**: Be mindful of server resources and implement client-side throttling
312
+ 4. **Browser Compatibility**: SSE is supported in all modern browsers
313
+ 5. **Connection Limits**: Most browsers limit concurrent SSE connections per domain (typically 6)
314
+
315
+ ## Troubleshooting
316
+
317
+ - **Connection closes immediately**: Check authentication token
318
+ - **No logs received**: Verify task ID and user permissions
319
+ - **Connection times out**: Check network stability and increase timeout parameter
320
+ - **Server errors**: Check server logs for authentication or database issues