@archetypeai/ds-cli 0.5.7 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/files/AGENTS.md CHANGED
@@ -56,12 +56,6 @@ Before installing, check if the pattern already exists locally in `$lib/componen
56
56
 
57
57
  ## Skills
58
58
 
59
- **Skill composition:** When building a demo that uses a Newton or Embedding API skill:
60
- 1. Use `@skills/create-dashboard` for the page layout (dashboard with Menubar)
61
- 2. Fetch `https://design-system.archetypeai.workers.dev/r/patterns.json` and reuse existing patterns before creating new components
62
- 3. Apply `@rules/design-principles` aesthetic conventions (BackgroundCard for single-purpose cards, mono font for headers/numbers)
63
- 4. Only include chart components if the user's request involves time-series or explicitly mentions charts
64
-
65
59
  Read these when relevant to your task:
66
60
 
67
61
  - `@skills/apply-ds` - apply DS tokens, components, and patterns to an existing demo
@@ -71,15 +65,6 @@ Read these when relevant to your task:
71
65
  - `@skills/fix-accessibility` - audit and fix a11y issues
72
66
  - `@skills/fix-metadata` - update page titles, favicons, and OG tags
73
67
  - `@skills/deploy-worker` - deploy SvelteKit projects to Cloudflare Workers
74
- - `@skills/embedding-from-file` - run an Embedding Lens by streaming sensor data from a CSV file
75
- - `@skills/embedding-from-sensor` - run an Embedding Lens by streaming real-time data from a physical sensor
76
- - `@skills/embedding-upload` - run an Embedding Lens by uploading a CSV file for server-side processing
77
- - `@skills/newton-activity-monitor-lens-on-video` - analyze uploaded video files using Newton's activity monitor lens
78
- - `@skills/newton-camera-frame-analysis` - live webcam frame analysis using Newton's vision model
79
- - `@skills/newton-direct-query` - simple direct query to Newton model using the /query API endpoint
80
- - `@skills/newton-machine-state-from-file` - run a Machine State Lens by streaming sensor data from a CSV file
81
- - `@skills/newton-machine-state-from-sensor` - run a Machine State Lens by streaming real-time data from a physical sensor
82
- - `@skills/newton-machine-state-upload` - run a Machine State Lens by uploading a CSV file for server-side processing
83
68
 
84
69
  ## Rules
85
70
 
package/files/CLAUDE.md CHANGED
@@ -56,12 +56,6 @@ Before installing, check if the pattern already exists locally in `$lib/componen
56
56
 
57
57
  ## Skills
58
58
 
59
- **Skill composition:** When building a demo that uses a Newton or Embedding API skill:
60
- 1. Use `@skills/create-dashboard` for the page layout (dashboard with Menubar)
61
- 2. Fetch `https://design-system.archetypeai.workers.dev/r/patterns.json` and reuse existing patterns before creating new components
62
- 3. Apply `@rules/design-principles` aesthetic conventions (BackgroundCard for single-purpose cards, mono font for headers/numbers)
63
- 4. Only include chart components if the user's request involves time-series or explicitly mentions charts
64
-
65
59
  Read these when relevant to your task:
66
60
 
67
61
  - `@skills/apply-ds` - apply DS tokens, components, and patterns to an existing demo
@@ -71,15 +65,6 @@ Read these when relevant to your task:
71
65
  - `@skills/fix-accessibility` - audit and fix a11y issues
72
66
  - `@skills/fix-metadata` - update page titles, favicons, and OG tags
73
67
  - `@skills/deploy-worker` - deploy SvelteKit projects to Cloudflare Workers
74
- - `@skills/embedding-from-file` - run an Embedding Lens by streaming sensor data from a CSV file
75
- - `@skills/embedding-from-sensor` - run an Embedding Lens by streaming real-time data from a physical sensor
76
- - `@skills/embedding-upload` - run an Embedding Lens by uploading a CSV file for server-side processing
77
- - `@skills/newton-activity-monitor-lens-on-video` - analyze uploaded video files using Newton's activity monitor lens
78
- - `@skills/newton-camera-frame-analysis` - live webcam frame analysis using Newton's vision model
79
- - `@skills/newton-direct-query` - simple direct query to Newton model using the /query API endpoint
80
- - `@skills/newton-machine-state-from-file` - run a Machine State Lens by streaming sensor data from a CSV file
81
- - `@skills/newton-machine-state-from-sensor` - run a Machine State Lens by streaming real-time data from a physical sensor
82
- - `@skills/newton-machine-state-upload` - run a Machine State Lens by uploading a CSV file for server-side processing
83
68
 
84
69
  ## Rules
85
70
 
@@ -70,7 +70,6 @@ SSE consumers, fetch wrappers, polling loops, and data transforms belong in a ut
70
70
  ```
71
71
  src/lib/api/activity-monitor.js — SSE + session management
72
72
  src/lib/api/machine-state.js — streaming + windowing
73
- src/lib/api/embeddings.js — upload + embedding extraction
74
73
  ```
75
74
 
76
75
  This keeps components focused on rendering and makes API logic testable and reusable.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@archetypeai/ds-cli",
3
- "version": "0.5.7",
3
+ "version": "0.5.9",
4
4
  "description": "Archetype AI Design System CLI Tool",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,428 +0,0 @@
1
- ---
2
- name: embedding-from-file
3
- description: Run an Embedding Lens by streaming sensor data from a CSV file. Use when extracting embeddings from time-series CSV data for visualization, clustering, dimensionality reduction, or similarity analysis.
4
- argument-hint: [csv-file-path]
5
- ---
6
-
7
- # Embedding Lens — Stream from CSV File
8
-
9
- Generate a script that streams time-series data from a CSV file to the Archetype AI Embedding Lens and collects embedding vectors. Supports both Python and JavaScript/Web.
10
-
11
- ## Frontend Architecture
12
-
13
- Decompose the UI into components. See `@rules/frontend-architecture` for conventions.
14
-
15
- ### Recommended decomposition
16
-
17
- | UI Area | Component | Pattern/Primitives | Key Props |
18
- |---------|-----------|-------------------|-----------|
19
- | File input | `DataInput.svelte` | BackgroundCard, Button, Input | `onselect`, `status` |
20
- | Scatter plot | Reuse ScatterChart pattern | BackgroundCard, Chart | `data[]`, `categories` |
21
- | Progress | `StreamProgress.svelte` | BackgroundCard, Progress | `current`, `total` |
22
-
23
- - Use `@skills/create-dashboard` for the page layout
24
- - Extract streaming and session logic into `$lib/api/embeddings.js`
25
-
26
- ---
27
-
28
- ## Python Implementation
29
-
30
- ### Requirements
31
-
32
- - `archetypeai` Python package
33
- - `pandas`, `numpy`
34
- - Environment variables: `ATAI_API_KEY`, optionally `ATAI_API_ENDPOINT`
35
-
36
- ### Architecture
37
-
38
- #### 1. API Client Setup
39
-
40
- ```python
41
- from archetypeai.api_client import ArchetypeAI
42
- import os
43
-
44
- api_key = os.getenv("ATAI_API_KEY")
45
- api_endpoint = os.getenv("ATAI_API_ENDPOINT", ArchetypeAI.get_default_endpoint())
46
- client = ArchetypeAI(api_key, api_endpoint=api_endpoint)
47
- ```
48
-
49
- #### 2. Lens YAML Configuration
50
-
51
- The embedding lens uses `lens_timeseries_embedding_processor` — no n-shot files or KNN config needed.
52
-
53
- ```yaml
54
- lens_name: Embedding Lens
55
- lens_config:
56
- model_pipeline:
57
- - processor_name: lens_timeseries_embedding_processor
58
- processor_config: {}
59
- model_parameters:
60
- model_name: OmegaEncoder
61
- model_version: OmegaEncoder::omega_embeddings_01
62
- normalize_input: true
63
- buffer_size: {window_size}
64
- csv_configs:
65
- timestamp_column: timestamp
66
- data_columns: ['a1', 'a2', 'a3', 'a4']
67
- window_size: {window_size}
68
- step_size: {step_size}
69
- output_streams:
70
- - stream_type: server_sent_events_writer
71
- ```
72
-
73
- **Key difference from Machine State Lens**: No `input_n_shot`, no `knn_configs`. The processor outputs raw embedding vectors instead of class predictions.
74
-
75
- #### 3. Session Callback — Stream Windows
76
-
77
- ```python
78
- def session_callback(session_id, session_endpoint, client, args):
79
- sse_reader = client.lens.sessions.create_sse_consumer(
80
- session_id, max_read_time_sec=args["max_run_time_sec"]
81
- )
82
-
83
- # Load CSV with pandas
84
- df = pd.read_csv(args["file_path"])
85
- columns = ["a1", "a2", "a3", "a4"]
86
- data = df[columns].values.T.tolist() # Transpose: [channels][samples]
87
-
88
- # Stream data in windows
89
- total_samples = len(df)
90
- start = 0
91
- counter = 0
92
- while start < total_samples:
93
- end = start + args["window_size"]
94
- chunk = [series[start:end] for series in data]
95
-
96
- payload = {
97
- "type": "session.update",
98
- "event_data": {
99
- "type": "data.json",
100
- "event_data": {
101
- "sensor_data": chunk,
102
- "sensor_metadata": {
103
- "sensor_timestamp": time.time(),
104
- "sensor_id": f"streamed_sensor_{counter}"
105
- }
106
- }
107
- }
108
- }
109
- client.lens.sessions.process_event(session_id, payload)
110
- start += args["step_size"]
111
- counter += 1
112
-
113
- # Collect embeddings
114
- embeddings = []
115
- for event in sse_reader.read(block=True):
116
- if stop_flag:
117
- break
118
- etype = event.get("type")
119
- if etype == "inference.result":
120
- ed = event.get("event_data", {})
121
- embedding = ed.get("response")
122
- meta = ed.get("query_metadata", {})
123
-
124
- # Flatten 4×768 to 3072D vector
125
- if isinstance(embedding, list) and len(embedding) > 0:
126
- if isinstance(embedding[0], list):
127
- flat = [val for row in embedding for val in row]
128
- else:
129
- flat = embedding
130
-
131
- embeddings.append({
132
- "window_index": len(embeddings),
133
- "query_timestamp": meta.get("query_timestamp", "N/A"),
134
- "embedding": flat,
135
- })
136
- print(f"[{len(embeddings)}] Embedding: {len(flat)}D")
137
-
138
- sse_reader.close()
139
- return embeddings
140
- ```
141
-
142
- #### 4. Create and Run Lens
143
-
144
- ```python
145
- client.lens.create_and_run_lens(
146
- yaml_config, session_callback,
147
- client=client, args=args
148
- )
149
- ```
150
-
151
- ### Embedding Response Structure
152
-
153
- The `inference.result` response contains:
154
- - `response`: nested list of shape `(4, 768)` — one 768D vector per input channel
155
- - Flatten to `3072D` by concatenating: `[a1_768D, a2_768D, a3_768D, a4_768D]`
156
- - `query_metadata.query_timestamp`: timestamp of the window
157
- - `query_metadata.sensor_id`: sensor identifier
158
- - `query_metadata.read_index`: window position in the data
159
-
160
- ### Saving Embeddings to CSV
161
-
162
- ```python
163
- import csv
164
-
165
- with open(output_file, 'w', newline='') as f:
166
- writer = csv.writer(f)
167
- writer.writerow(['window_index', 'query_timestamp', 'analysis_timestamp',
168
- 'read_index', 'window_size', 'step_size', 'embedding_vector'])
169
-
170
- for emb in embeddings:
171
- writer.writerow([
172
- emb["window_index"],
173
- emb["query_timestamp"],
174
- datetime.now().isoformat(),
175
- emb.get("read_index", "N/A"),
176
- args["window_size"],
177
- args["step_size"],
178
- str(emb["embedding"]),
179
- ])
180
- ```
181
-
182
- ### CLI Arguments
183
-
184
- ```
185
- --api-key API key (fallback to ATAI_API_KEY env var)
186
- --api-endpoint API endpoint (default from SDK)
187
- --file-path Path to CSV file to analyze (required)
188
- --window-size Window size in samples (default: 100)
189
- --step-size Step size in samples (default: 100)
190
- --max-run-time-sec Max runtime in seconds (default: 500)
191
- --output-file Path to save embeddings CSV (optional)
192
- ```
193
-
194
- ---
195
-
196
- ## Web / JavaScript Implementation
197
-
198
- Uses direct `fetch` calls to the Archetype AI REST API.
199
-
200
- ### API Reference
201
-
202
- | Operation | Method | Endpoint | Body |
203
- |-----------|--------|----------|------|
204
- | Register lens | POST | `/lens/register` | `{ lens_config: config }` |
205
- | Create session | POST | `/lens/sessions/create` | `{ lens_id }` |
206
- | Process event | POST | `/lens/sessions/events/process` | `{ session_id, event }` |
207
- | Delete lens | POST | `/lens/delete` | `{ lens_id }` |
208
- | Destroy session | POST | `/lens/sessions/destroy` | `{ session_id }` |
209
- | SSE consumer | GET | `/lens/sessions/consumer/{sessionId}` | — |
210
-
211
- ### Helper: API fetch wrapper
212
-
213
- ```typescript
214
- const API_ENDPOINT = 'https://api.u1.archetypeai.app/v0.5'
215
-
216
- async function apiPost<T>(path: string, apiKey: string, body: unknown, timeoutMs = 5000): Promise<T> {
217
- const controller = new AbortController()
218
- const timeoutId = setTimeout(() => controller.abort(), timeoutMs)
219
-
220
- try {
221
- const response = await fetch(`${API_ENDPOINT}${path}`, {
222
- method: 'POST',
223
- headers: {
224
- Authorization: `Bearer ${apiKey}`,
225
- 'Content-Type': 'application/json',
226
- },
227
- body: JSON.stringify(body),
228
- signal: controller.signal,
229
- })
230
-
231
- if (!response.ok) {
232
- const errorBody = await response.json().catch(() => ({}))
233
- throw new Error(`API POST ${path} failed: ${response.status} - ${JSON.stringify(errorBody)}`)
234
- }
235
-
236
- return response.json()
237
- } finally {
238
- clearTimeout(timeoutId)
239
- }
240
- }
241
- ```
242
-
243
- ### Step 1: Build and register the embedding lens
244
-
245
- ```typescript
246
- const windowSize = 100
247
- const stepSize = 100
248
-
249
- const lensConfig = {
250
- lens_name: 'embedding_lens',
251
- lens_config: {
252
- model_pipeline: [
253
- { processor_name: 'lens_timeseries_embedding_processor', processor_config: {} },
254
- ],
255
- model_parameters: {
256
- model_name: 'OmegaEncoder',
257
- model_version: 'OmegaEncoder::omega_embeddings_01',
258
- normalize_input: true,
259
- buffer_size: windowSize,
260
- csv_configs: {
261
- timestamp_column: 'timestamp',
262
- data_columns: ['a1', 'a2', 'a3', 'a4'],
263
- window_size: windowSize,
264
- step_size: stepSize,
265
- },
266
- },
267
- output_streams: [
268
- { stream_type: 'server_sent_events_writer' },
269
- ],
270
- },
271
- }
272
-
273
- // Register lens
274
- const registeredLens = await apiPost<{ lens_id: string }>(
275
- '/lens/register', apiKey, { lens_config: lensConfig }
276
- )
277
- const lensId = registeredLens.lens_id
278
-
279
- // Create session
280
- const session = await apiPost<{ session_id: string }>(
281
- '/lens/sessions/create', apiKey, { lens_id: lensId }
282
- )
283
- const sessionId = session.session_id
284
-
285
- await apiPost('/lens/delete', apiKey, { lens_id: lensId })
286
-
287
- // Wait for session ready
288
- async function waitForSessionReady(sessionId: string, maxWaitMs = 30000): Promise<boolean> {
289
- const start = Date.now()
290
- while (Date.now() - start < maxWaitMs) {
291
- const status = await apiPost<{ session_status: string }>(
292
- '/lens/sessions/events/process', apiKey,
293
- { session_id: sessionId, event: { type: 'session.status' } },
294
- 10000
295
- )
296
- if (status.session_status === 'LensSessionStatus.SESSION_STATUS_RUNNING' ||
297
- status.session_status === '3') return true
298
- if (status.session_status === 'LensSessionStatus.SESSION_STATUS_FAILED' ||
299
- status.session_status === '6') return false
300
- await new Promise(r => setTimeout(r, 500))
301
- }
302
- return false
303
- }
304
-
305
- await waitForSessionReady(sessionId)
306
- ```
307
-
308
- ### Step 2: Stream CSV data in windows
309
-
310
- ```typescript
311
- // Parse CSV (PapaParse or similar)
312
- const rows = parsedCsv.data
313
- const columns = ['a1', 'a2', 'a3', 'a4']
314
-
315
- let start = 0
316
- let counter = 0
317
-
318
- while (start < rows.length) {
319
- const end = Math.min(start + windowSize, rows.length)
320
- const window = rows.slice(start, end)
321
-
322
- const sensorData = columns.map(col =>
323
- window.map(row => Number(row[col]))
324
- )
325
-
326
- await apiPost('/lens/sessions/events/process', apiKey, {
327
- session_id: sessionId,
328
- event: {
329
- type: 'session.update',
330
- event_data: {
331
- type: 'data.json',
332
- event_data: {
333
- sensor_data: sensorData,
334
- sensor_metadata: {
335
- sensor_timestamp: Date.now() / 1000,
336
- sensor_id: `web_sensor_${counter}`,
337
- },
338
- },
339
- },
340
- },
341
- }, 10000)
342
-
343
- start += stepSize
344
- counter++
345
- }
346
- ```
347
-
348
- ### Step 3: Consume SSE embedding results
349
-
350
- ```typescript
351
- import { fetchEventSource } from '@microsoft/fetch-event-source'
352
-
353
- interface EmbeddingResult {
354
- windowIndex: number
355
- queryTimestamp: string
356
- embedding: number[] // 3072D flattened
357
- }
358
-
359
- const embeddings: EmbeddingResult[] = []
360
-
361
- fetchEventSource(`${API_ENDPOINT}/lens/sessions/consumer/${sessionId}`, {
362
- headers: { Authorization: `Bearer ${apiKey}` },
363
- onmessage(event) {
364
- const parsed = JSON.parse(event.data)
365
-
366
- if (parsed.type === 'inference.result') {
367
- const response = parsed.event_data.response
368
- const meta = parsed.event_data.query_metadata
369
-
370
- // Flatten 4×768 → 3072D
371
- const flat = Array.isArray(response[0])
372
- ? response.flat()
373
- : response
374
-
375
- embeddings.push({
376
- windowIndex: embeddings.length,
377
- queryTimestamp: meta?.query_timestamp ?? 'N/A',
378
- embedding: flat,
379
- })
380
- console.log(`[${embeddings.length}] Embedding: ${flat.length}D`)
381
- }
382
-
383
- if (parsed.type === 'sse.stream.end') {
384
- console.log('Stream complete')
385
- }
386
- },
387
- })
388
- ```
389
-
390
- ### Step 4: Cleanup
391
-
392
- ```typescript
393
- await apiPost('/lens/sessions/destroy', apiKey, { session_id: sessionId })
394
- ```
395
-
396
- ### Web Lifecycle Summary
397
-
398
- ```
399
- 1. Register lens -> POST /lens/register { lens_config: config }
400
- 2. Create session -> POST /lens/sessions/create { lens_id }
401
- 3. Wait for ready -> POST /lens/sessions/events/process (poll session.status)
402
- 4. (Optional) Delete lens -> POST /lens/delete { lens_id }
403
- 5. Stream windowed data -> POST /lens/sessions/events/process { session_id, event } (loop)
404
- 6. Consume SSE results -> GET /lens/sessions/consumer/{sessionId}
405
- 7. Destroy session -> POST /lens/sessions/destroy { session_id }
406
- ```
407
-
408
- ---
409
-
410
- ## CSV Format Expected
411
-
412
- ```csv
413
- timestamp,a1,a2,a3,a4
414
- 1700000000.0,100,200,300,374
415
- ```
416
-
417
- - Column names configurable via `csv_configs.data_columns`
418
- - `a4` is typically magnitude: sqrt(a1² + a2² + a3²)
419
-
420
- ## Key Differences from Machine State Lens
421
-
422
- | | Embedding Lens | Machine State Lens |
423
- |---|---|---|
424
- | Processor | `lens_timeseries_embedding_processor` | `lens_timeseries_state_processor` |
425
- | N-shot files | Not needed | Required (one per class) |
426
- | KNN config | Not needed | Required |
427
- | Output | Raw embedding vectors (4×768 = 3072D) | Class predictions + confidence scores |
428
- | Use case | Visualization, clustering, similarity | Classification, anomaly detection |