-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·1048 lines (869 loc) · 34.4 KB
/
cli.js
File metadata and controls
executable file
·1048 lines (869 loc) · 34.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const { execSync, spawn } = require('child_process');
const readline = require('readline');
// Configuration
const REGISTRY_URL = 'https://registry.tessl.io';
const INSTALL_URL = 'https://get.tessl.io';
const TIMEOUT_MS = 600000; // 10 minutes max
const POLL_INTERVAL_MS = 15000; // 15 seconds
// ANSI colors for terminal output
const colors = {
reset: '\x1b[0m',
green: '\x1b[32m',
yellow: '\x1b[33m',
red: '\x1b[31m',
blue: '\x1b[34m',
gray: '\x1b[90m',
};
// Helper: Print colored output
function log(message, color = 'reset') {
console.log(`${colors[color]}${message}${colors.reset}`);
}
// Helper: Print progress
function progress(step, total, message) {
log(`[${step}/${total}] ${message}`, 'blue');
}
// Helper: Execute shell command and return output
function exec(command, options = {}) {
try {
return execSync(command, {
encoding: 'utf8',
stdio: options.silent ? 'pipe' : 'inherit',
...options,
});
} catch (error) {
if (options.ignoreErrors) {
return null;
}
throw error;
}
}
// Helper: Check if command exists
function commandExists(command) {
const result = exec(`which ${command}`, { silent: true, ignoreErrors: true });
return result !== null && result.trim().length > 0;
}
// Helper: Detect if running in headless environment
function isHeadless() {
// Check common headless indicators
return (
!process.env.DISPLAY || // No X display
process.env.CI === 'true' || // CI environment
process.env.SSH_CONNECTION || // SSH session
process.env.SSH_CLIENT || // SSH client
!process.stdout.isTTY // No TTY
);
}
// Helper: Prompt user for input
function promptUser(question, defaultValue = '') {
return new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const promptText = defaultValue
? `${question} [${defaultValue}]: `
: `${question}: `;
rl.question(promptText, (answer) => {
rl.close();
resolve(answer.trim() || defaultValue);
});
});
}
// Helper: Retry with exponential backoff
async function retry(fn, maxAttempts = 3) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt === maxAttempts) throw error;
const delay = Math.pow(2, attempt) * 1000;
log(`Retrying in ${delay / 1000}s...`, 'yellow');
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
// Helper: Increment tile version
function incrementTileVersion(tilePath) {
const tileJsonPath = path.join(tilePath, 'tile.json');
const tileJson = JSON.parse(fs.readFileSync(tileJsonPath, 'utf8'));
// Parse version (e.g., "0.1.0" -> [0, 1, 0])
const [major, minor, patch] = tileJson.version.split('.').map(Number);
// Increment patch version
const newVersion = `${major}.${minor}.${patch + 1}`;
tileJson.version = newVersion;
// Write back to file
fs.writeFileSync(tileJsonPath, JSON.stringify(tileJson, null, 2) + '\n');
return newVersion;
}
// Helper: Copy directory recursively
function copyDir(src, dest) {
fs.mkdirSync(dest, { recursive: true });
const entries = fs.readdirSync(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
copyDir(srcPath, destPath);
} else {
fs.copyFileSync(srcPath, destPath);
}
}
}
// Main onboarding flow
async function main() {
// Change to script directory so all relative paths work correctly
const scriptDir = path.dirname(__filename);
process.chdir(scriptDir);
log(`Working directory: ${scriptDir}`, 'gray');
console.clear();
log('╔════════════════════════════════════════╗', 'blue');
log('║ Tessl Onboarding - Learn by Doing ║', 'blue');
log('╚════════════════════════════════════════╝', 'blue');
console.log();
const startTime = Date.now();
const totalSteps = 12;
// Step 0: Get permission
progress(0, totalSteps, 'Getting permission...');
console.log(`
This will:
- Install Tessl CLI (if needed) - ~30 seconds
- Authenticate with Tessl registry - ~30 seconds
- Create a sample skill - ~10 seconds
- Run quality checks - ~2-3 minutes
Total time: ~5 minutes. Safe and reversible.
`);
// In a real implementation, you'd use a library like 'prompts' for interactive input
// For now, we'll assume consent
log('✓ Permission granted', 'green');
console.log();
try {
// Step 1: Check prerequisites
progress(1, totalSteps, 'Checking prerequisites...');
const hasTessl = commandExists('tessl');
const hasNetwork = checkNetwork();
if (hasTessl) {
const version = exec('tessl --version', { silent: true }).trim();
log(` ✓ Tessl CLI installed (${version})`, 'green');
} else {
log(' ⚠ Tessl CLI not installed (will install)', 'yellow');
}
if (hasNetwork) {
log(' ✓ Network reachable', 'green');
} else {
throw new Error('Cannot reach registry - check internet connection');
}
console.log();
// Step 2: Install Tessl (if needed)
if (!hasTessl) {
progress(2, totalSteps, 'Installing Tessl CLI...');
await retry(() => {
exec(`curl -fsSL ${INSTALL_URL} | sh`);
});
// Add common install locations to PATH for this session
const homedir = require('os').homedir();
const tesslPaths = [
`${homedir}/.local/bin`,
`${homedir}/.tessl/bin`,
'/usr/local/bin'
];
process.env.PATH = `${tesslPaths.join(':')}:${process.env.PATH}`;
// Add to shell config for persistence
const shellConfigs = [
`${homedir}/.bashrc`,
`${homedir}/.zshrc`,
`${homedir}/.profile`
];
const pathExport = `\n# Added by Tessl onboarding\nexport PATH="${homedir}/.local/bin:$PATH"\n`;
for (const configFile of shellConfigs) {
if (fs.existsSync(configFile)) {
const content = fs.readFileSync(configFile, 'utf8');
if (!content.includes('.local/bin')) {
fs.appendFileSync(configFile, pathExport);
log(` ✓ Added to PATH in ${path.basename(configFile)}`, 'gray');
}
}
}
log(' ✓ Tessl CLI installed', 'green');
log(' ✓ PATH updated in shell config (will persist in new terminals)', 'gray');
console.log();
} else {
progress(2, totalSteps, 'Tessl CLI already installed (skipping)');
console.log();
}
// Step 3: Authenticate
progress(3, totalSteps, 'Authenticating with Tessl...');
await authenticate();
console.log();
// Step 4: Initialize project
progress(4, totalSteps, 'Initializing project...');
await initProject();
console.log();
// Step 5: Create skill-builder example
progress(5, totalSteps, 'Creating skill-builder example...');
const workspace = await createExample();
console.log();
// Step 6: Create repo eval scenarios
progress(6, totalSteps, 'Adding repo eval scenarios...');
await createRepoEvals();
console.log();
// Step 7: Run skill review
progress(7, totalSteps, 'Running skill review...');
const reviewResults = await runSkillReview();
console.log();
// Step 8: Run tile eval
progress(8, totalSteps, 'Running tile eval (this may take 2-3 minutes)...');
const tileEvalResults = await runTileEval();
console.log();
// Step 9: Run repo eval
progress(9, totalSteps, 'Running repo eval (optional bonus)...');
const repoEvalResults = await runRepoEval(workspace);
console.log();
// Step 10: Generate outputs
progress(10, totalSteps, 'Generating summary and report...');
await generateOutputs(reviewResults, tileEvalResults, repoEvalResults, startTime);
console.log();
// Step 11: Publish tile
progress(11, totalSteps, 'Publishing skill-builder tile...');
await publishTile();
console.log();
// Step 12: Success!
progress(12, totalSteps, 'Complete!');
displaySuccess();
} catch (error) {
log(`\n✗ Error: ${error.message}`, 'red');
log('Check onboarding-report.md for details', 'gray');
process.exit(1);
}
}
// Helper functions for each step
function checkNetwork() {
try {
exec(`curl -I ${REGISTRY_URL}`, { silent: true, ignoreErrors: false });
return true;
} catch {
return false;
}
}
async function authenticate() {
// Check if already authenticated
try {
const whoami = exec('tessl whoami', { silent: true }).trim();
if (whoami) {
log(` ✓ Already authenticated as ${whoami}`, 'green');
return;
}
} catch {
// Not authenticated, proceed with login
}
const headless = isHeadless();
log(' Starting login flow...', 'blue');
if (headless) {
log(' (Headless environment detected - authentication URL will be displayed)', 'gray');
} else {
log(' (Browser will open for authentication)', 'gray');
}
console.log();
// Start login in background and capture output as it streams
return new Promise((resolve, reject) => {
const loginProcess = spawn('tessl', ['login'], {
stdio: ['inherit', 'pipe', 'pipe']
});
let output = '';
let urlDisplayed = false;
// Capture stdout and stderr
const captureOutput = (data) => {
const chunk = data.toString();
output += chunk;
// Try to parse URL and code from accumulated output
if (!urlDisplayed) {
const urlMatch = output.match(/https?:\/\/[^\s]+/);
const codeMatch = output.match(/code[:\s]*\n\s*([A-Z0-9-]+)/i) ||
output.match(/following code[:\s]*\n\s*([A-Z0-9-]+)/i);
if (urlMatch || codeMatch) {
urlDisplayed = true;
console.log();
log(' ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', 'blue');
if (urlMatch) {
log(` Authentication URL:`, 'blue');
log(` ${urlMatch[0]}`, 'green');
}
if (codeMatch) {
log(` Code: ${codeMatch[1]}`, 'yellow');
}
log(' ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', 'blue');
console.log();
}
}
};
loginProcess.stdout.on('data', captureOutput);
loginProcess.stderr.on('data', captureOutput);
loginProcess.on('close', async (code) => {
if (!urlDisplayed) {
log(' Login flow initiated', 'gray');
console.log();
}
log(' Waiting for authentication...', 'gray');
if (headless) {
log(' (Open the URL above in a browser and enter the code)', 'gray');
} else {
log(' (Complete the browser flow or use the URL above if needed)', 'gray');
}
console.log();
// Poll for authentication completion
const maxWait = 180000; // 3 minutes
const pollInterval = 5000; // 5 seconds
const startTime = Date.now();
while (Date.now() - startTime < maxWait) {
await new Promise(r => setTimeout(r, pollInterval));
try {
const whoami = exec('tessl whoami', { silent: true }).trim();
if (whoami) {
log(` ✓ Authenticated as ${whoami}`, 'green');
return resolve();
}
} catch {
// Not authenticated yet, continue polling
}
}
reject(new Error('Authentication timeout - please try again'));
});
loginProcess.on('error', (err) => {
reject(new Error(`Failed to start login: ${err.message}`));
});
});
}
async function initProject() {
// Check if already initialized
if (fs.existsSync('tessl.json')) {
log(' ✓ Project already initialized', 'green');
return;
}
exec('tessl init');
log(' ✓ Project initialized', 'green');
}
async function createExample() {
const examplePath = 'examples/skill-builder';
// Create directory structure
fs.mkdirSync(path.join(examplePath, 'evals'), { recursive: true });
// Copy only SKILL.md from package
const packagePath = path.dirname(__filename);
fs.copyFileSync(
path.join(packagePath, 'examples/skill-builder/SKILL.md'),
path.join(examplePath, 'SKILL.md')
);
// Get username and available workspaces
let username = 'user';
let availableWorkspaces = [];
try {
const whoamiOutput = exec('tessl whoami', { silent: true });
log(` tessl whoami output: ${whoamiOutput.substring(0, 200)}`, 'gray');
// Extract username
const usernameMatch = whoamiOutput.match(/Username\s+([^\s]+)/);
if (usernameMatch) {
username = usernameMatch[1];
log(` ✓ Extracted username: ${username}`, 'gray');
} else {
log(` ⚠ Could not extract username from whoami, using default: ${username}`, 'yellow');
}
// Get workspaces using tessl workspace list
try {
const workspaceListOutput = exec('tessl workspace list', { silent: true });
// Parse table format: extract lines with ║ that contain workspace names
const workspaceLines = workspaceListOutput.split('\n')
.filter(line => line.includes('║') && !line.includes('Name') && !line.includes('═') && !line.includes('─'))
.map(line => {
// Extract first column (workspace name) from table
const match = line.match(/║\s*([^\s│]+)\s*│/);
return match ? match[1].trim() : null;
})
.filter(ws => ws && ws.length > 0);
if (workspaceLines.length > 0) {
availableWorkspaces = workspaceLines;
log(` ✓ Found ${availableWorkspaces.length} workspaces: ${availableWorkspaces.slice(0, 3).join(', ')}${availableWorkspaces.length > 3 ? '...' : ''}`, 'gray');
} else {
availableWorkspaces = [username];
log(` ⚠ No workspaces found in list, using username as workspace`, 'yellow');
}
} catch (e) {
availableWorkspaces = [username];
log(` ⚠ Could not list workspaces: ${e.message}, using username as workspace`, 'yellow');
}
} catch (e) {
log(` ⚠ tessl whoami failed: ${e.message}, using default: ${username}`, 'yellow');
availableWorkspaces = [username];
}
// Prompt for workspace (default to first available workspace)
const defaultWorkspace = availableWorkspaces[0];
log('\n Which workspace should skill-builder use?', 'blue');
if (availableWorkspaces.length > 1) {
log(` Available: ${availableWorkspaces.join(', ')}`, 'gray');
}
log(` Default: ${defaultWorkspace}`, 'gray');
const workspace = await promptUser(' Workspace', defaultWorkspace);
log(` ✓ Selected workspace: ${workspace}`, 'gray');
// Validate workspace
if (!availableWorkspaces.includes(workspace)) {
log(` ⚠ Warning: "${workspace}" not found in available workspaces`, 'yellow');
log(` Available: ${availableWorkspaces.join(', ')}`, 'yellow');
log(` Continuing anyway - eval may fail if you lack access`, 'yellow');
}
// Check if tile.json exists and preserve/increment version
let tileVersion = '0.1.0';
const existingTilePath = path.join(examplePath, 'tile.json');
if (fs.existsSync(existingTilePath)) {
try {
const existingTile = JSON.parse(fs.readFileSync(existingTilePath, 'utf8'));
const [major, minor, patch] = existingTile.version.split('.').map(Number);
tileVersion = `${major}.${minor}.${patch + 1}`;
log(` ✓ Found existing tile at v${existingTile.version}, incrementing to v${tileVersion}`, 'gray');
} catch (e) {
log(` ⚠ Could not read existing tile.json, starting at v0.1.0`, 'yellow');
}
}
// Generate tile.json with workspace-scoped name
const tileJson = {
name: `${workspace}/skill-builder`,
version: tileVersion,
summary: 'Scaffold new Tessl skills with best practices',
description: 'Helps you scaffold new Tessl skills with best practices and proper structure',
type: 'skill',
private: true,
skills: {
'skill-builder': {
path: 'SKILL.md'
}
},
metadata: {
tags: ['scaffolding', 'development', 'meta'],
author: 'Tessl',
license: 'MIT'
}
};
fs.writeFileSync(
path.join(examplePath, 'tile.json'),
JSON.stringify(tileJson, null, 2) + '\n'
);
log(` ✓ Generated tile.json for ${workspace}/skill-builder`, 'gray');
// Create basic eval scenarios
const scenario1Path = path.join(examplePath, 'evals/scenario-1');
const scenario2Path = path.join(examplePath, 'evals/scenario-2');
fs.mkdirSync(scenario1Path, { recursive: true });
fs.mkdirSync(scenario2Path, { recursive: true });
// Scenario 1: Basic scaffolding
fs.writeFileSync(
path.join(scenario1Path, 'task.md'),
`# Scenario 1: Basic Skill Scaffolding
Test that skill-builder can create a basic skill structure.
## Task
Use skill-builder to create a new skill called "hello-world" that prints a greeting.
## Expected Behavior
- Creates skill directory with SKILL.md
- Includes proper frontmatter (name, description)
- Has clear usage instructions
`
);
fs.writeFileSync(
path.join(scenario1Path, 'criteria.json'),
JSON.stringify({
context: 'Test basic skill scaffolding functionality',
type: 'weighted_checklist',
checklist: [
{
name: 'Directory Creation',
description: 'Creates skill directory with proper structure',
max_score: 25
},
{
name: 'SKILL.md File',
description: 'Generates SKILL.md with proper frontmatter',
max_score: 25
},
{
name: 'Name and Description',
description: 'Includes name and description in frontmatter',
max_score: 25
},
{
name: 'Usage Instructions',
description: 'Provides clear usage instructions in the skill',
max_score: 25
}
]
}, null, 2) + '\n'
);
// Scenario 2: Skill with examples
fs.writeFileSync(
path.join(scenario2Path, 'task.md'),
`# Scenario 2: Skill with Examples
Test that skill-builder can create a skill with usage examples.
## Task
Use skill-builder to create a skill called "code-formatter" that includes usage examples.
## Expected Behavior
- Creates skill with examples section
- Examples are clear and functional
- Follows Tessl skill best practices
`
);
fs.writeFileSync(
path.join(scenario2Path, 'criteria.json'),
JSON.stringify({
context: 'Test skill creation with examples',
type: 'weighted_checklist',
checklist: [
{
name: 'Examples Section',
description: 'Includes a clear examples section',
max_score: 30
},
{
name: 'Example Quality',
description: 'Examples are clear and demonstrate usage',
max_score: 35
},
{
name: 'Best Practices',
description: 'Follows Tessl skill best practices',
max_score: 35
}
]
}, null, 2) + '\n'
);
// Verify tile.json was created
const tileJsonPath = path.join(examplePath, 'tile.json');
if (!fs.existsSync(tileJsonPath)) {
throw new Error(`Failed to create tile.json at ${tileJsonPath}`);
}
log(` ✓ Verified tile.json exists at ${examplePath}/tile.json`, 'gray');
// Import skill (--force to skip prompts, --no-public to keep private, --workspace to set correct workspace)
exec(`cd ${examplePath} && tessl skill import --workspace ${workspace} --force --no-public && cd ../..`);
log(' ✓ skill-builder example created with tile and scenarios', 'green');
return workspace; // Return workspace for use in repo eval
}
async function createRepoEvals() {
const evalsPath = '.tessl/evals';
fs.mkdirSync(evalsPath, { recursive: true });
// Copy repo scenarios
const packagePath = path.dirname(__filename);
fs.copyFileSync(
path.join(packagePath, '.tessl/evals/repo-scenarios.json'),
path.join(evalsPath, 'repo-scenarios.json')
);
log(' ✓ Repo eval scenarios added', 'green');
}
async function runSkillReview() {
const tilePath = path.join(process.cwd(), 'examples/skill-builder');
const output = exec(`tessl skill review ${tilePath} --json`, { silent: true });
const results = JSON.parse(output);
log(` ✓ Review complete: ${results.score}/100`, 'green');
log(` (Review validates structure and quality)`, 'gray');
return results;
}
async function runTileEval() {
// Verify working directory and paths
const cwd = process.cwd();
const tilePath = path.join(cwd, 'examples/skill-builder');
const tileJsonPath = path.join(tilePath, 'tile.json');
log(` Current working directory: ${cwd}`, 'gray');
log(` Looking for tile at: ${tilePath}`, 'gray');
log(` tile.json exists: ${fs.existsSync(tileJsonPath) ? '✓' : '✗'}`, fs.existsSync(tileJsonPath) ? 'green' : 'red');
if (!fs.existsSync(tileJsonPath)) {
log(` ERROR: tile.json not found at expected location`, 'red');
log(` Checking alternate locations...`, 'gray');
const altPath = '/examples/skill-builder/tile.json';
log(` ${altPath}: ${fs.existsSync(altPath) ? '✓ FOUND' : '✗'}`, fs.existsSync(altPath) ? 'yellow' : 'gray');
}
// Proactively increment version to ensure fresh eval (not reusing old results)
const newVersion = incrementTileVersion(tilePath);
log(` ✓ Incremented tile version to ${newVersion}`, 'gray');
let evalRunId;
let retryCount = 0;
const maxRetries = 3;
// Try to start eval, increment version on conflict
while (retryCount < maxRetries) {
try {
const output = exec(`tessl eval run ${tilePath} --json`, { silent: true });
log(` Raw eval output (first 300 chars): ${output.substring(0, 300)}`, 'gray');
// Try to parse as JSON first
let parsed;
try {
parsed = JSON.parse(output);
evalRunId = parsed.evalRunId;
} catch (parseError) {
// JSON parsing failed, try extracting ID from text output
// Format: "View results at: https://tessl.io/eval-runs/{id}" or "Run tessl eval view {id}"
const idMatch = output.match(/eval-runs\/([a-f0-9-]+)|eval view ([a-f0-9-]+)/i);
if (idMatch) {
evalRunId = idMatch[1] || idMatch[2];
log(` ✓ Extracted eval run ID from text output: ${evalRunId}`, 'gray');
} else {
log(` ✗ Could not extract eval run ID from output`, 'red');
log(` Full output: ${output}`, 'yellow');
throw new Error(`Could not parse eval run ID from output: ${output.substring(0, 200)}`);
}
}
break;
} catch (error) {
const errorMessage = error.message || '';
// Check if it's a version conflict
if (errorMessage.includes('version') && errorMessage.includes('already exists')) {
retryCount++;
const newVersion = incrementTileVersion(tilePath);
log(` Version conflict detected, incrementing to ${newVersion}...`, 'yellow');
} else {
throw error;
}
}
}
if (!evalRunId) {
throw new Error('Failed to start eval after version increments');
}
log(` Eval started: ${evalRunId}`, 'gray');
log(' Polling for results...', 'gray');
// Poll for completion
const maxWait = 300000; // 5 minutes
const pollInterval = 15000; // 15 seconds
const startTime = Date.now();
while (Date.now() - startTime < maxWait) {
await new Promise(resolve => setTimeout(resolve, pollInterval));
const statusOutput = exec(`tessl eval view ${evalRunId} --json`, { silent: true });
const response = JSON.parse(statusOutput);
// Status is nested under data.attributes.status
const status = response.data.attributes.status;
const scenarios = response.data.attributes.scenarios;
log(` Status: ${status}, Scenarios: ${scenarios?.length || 0}`, 'gray');
if (status === 'completed') {
// Calculate pass rate from scenarios
const passed = scenarios.filter(s => s.solutions?.some(sol =>
sol.assessmentResults?.every(r => r.score === r.max_score)
)).length;
const total = scenarios.length;
const passRate = Math.round((passed / total) * 100);
log(` ✓ Eval complete: ${passed}/${total} scenarios passed (${passRate}%)`, 'green');
log(` (Evals test functional correctness)`, 'gray');
return response;
}
}
throw new Error('Eval timeout - check results later with tessl eval view');
}
async function runRepoEval(workspace) {
// Ask if user wants to perform repo eval
log('\n Would you like to perform a repository evaluation?', 'blue');
log(' This will analyze commits from a GitHub repository', 'gray');
const performEval = await promptUser(' Perform repo eval? (y/n)', 'n');
if (performEval.toLowerCase() !== 'y' && performEval.toLowerCase() !== 'yes') {
log(' ⚠ Repo eval skipped (user declined)', 'yellow');
return null;
}
try {
// Get GitHub repo URL
log('\n Enter GitHub repository URL:', 'blue');
log(' Example: https://github.com/pandas-dev/pandas', 'gray');
const repoUrl = await promptUser(' GitHub URL', '');
if (!repoUrl) {
log(' ⚠ No URL provided, skipping repo eval', 'yellow');
return null;
}
// Parse URL to extract org/repo
// Handles: github.com/org/repo, www.github.com/org/repo, https://github.com/org/repo
const urlMatch = repoUrl.match(/(?:https?:\/\/)?(?:www\.)?github\.com\/([^\/]+\/[^\/\s]+)/);
if (!urlMatch) {
log(' ✗ Invalid GitHub URL format', 'red');
log(' Expected format: github.com/org/repo', 'gray');
return null;
}
const orgRepo = urlMatch[1].replace(/\.git$/, ''); // Remove .git suffix if present
log(` ✓ Parsed repository: ${orgRepo}`, 'gray');
// Select commits
log('\n Selecting commits for evaluation...', 'blue');
const commitsOutput = exec(`tessl repo select-commits ${orgRepo} --workspace ${workspace}`, { silent: true });
const commits = commitsOutput.trim().split('\n').filter(c => c.length > 0);
if (commits.length === 0) {
log(' ✗ No commits found', 'red');
return null;
}
log(` ✓ Found ${commits.length} commits`, 'gray');
log(` Commits: ${commits.slice(0, 3).join(', ')}${commits.length > 3 ? '...' : ''}`, 'gray');
// Generate scenarios
log('\n Generating evaluation scenarios...', 'blue');
const commitsArg = commits.join(',');
const scenariosOutput = exec(`tessl scenarios generate-scenarios ${orgRepo} --commits=${commitsArg}`);
log(` ✓ Scenarios generated`, 'green');
// Get scenarios path (typically .tessl/evals)
const evalsPath = '.tessl/evals';
// Ask for agent and model
log('\n Select agent and model for evaluation:', 'blue');
log(' Available agents: (many more available)', 'gray');
log(' - claude: Claude Code (claude-sonnet-4-5, claude-opus-4-6, claude-haiku-4-5)', 'gray');
log(' - cursor: Cursor AI (claude-sonnet-4-5, gpt-4o, claude-opus-4-6)', 'gray');
const agent = await promptUser(' Agent', 'claude');
let modelOptions = [];
if (agent === 'claude') {
modelOptions = ['claude-sonnet-4-5', 'claude-opus-4-6', 'claude-haiku-4-5'];
} else if (agent === 'cursor') {
modelOptions = ['claude-sonnet-4-5', 'gpt-4o', 'claude-opus-4-6'];
} else {
// Default to claude options
modelOptions = ['claude-sonnet-4-5', 'claude-opus-4-6', 'claude-haiku-4-5'];
}
log(` Available models: ${modelOptions.join(', ')}`, 'gray');
const model = await promptUser(' Model', modelOptions[0]);
log(` ✓ Selected: ${agent}:${model}`, 'gray');
// Run eval with selected agent and model
log('\n Starting repository evaluation...', 'blue');
const evalCommand = `tessl eval run ${evalsPath} --agent=${agent}:${model}`;
const output = exec(evalCommand, { silent: true });
// Parse eval run ID from text output
const idMatch = output.match(/eval-runs\/([a-f0-9-]+)|eval view ([a-f0-9-]+)/i);
let evalRunId;
if (idMatch) {
evalRunId = idMatch[1] || idMatch[2];
log(` ✓ Eval started: ${evalRunId}`, 'gray');
} else {
log(' ✗ Could not extract eval run ID', 'red');
return null;
}
// Poll for completion
log(' Polling for results...', 'gray');
const maxWait = 600000; // 10 minutes for repo evals
const pollInterval = 15000; // 15 seconds
const startTime = Date.now();
while (Date.now() - startTime < maxWait) {
await new Promise(resolve => setTimeout(resolve, pollInterval));
const statusOutput = exec(`tessl eval view ${evalRunId} --json`, { silent: true });
const response = JSON.parse(statusOutput);
const status = response.data.attributes.status;
const scenarios = response.data.attributes.scenarios;
log(` Status: ${status}, Scenarios: ${scenarios?.length || 0}`, 'gray');
if (status === 'completed') {
const passed = scenarios.filter(s => s.solutions?.some(sol =>
sol.assessmentResults?.every(r => r.score === r.max_score)
)).length;
const total = scenarios.length;
log(` ✓ Repo eval complete: ${passed}/${total} scenarios passed`, 'green');
log(` (Repository: ${orgRepo}, Agent: ${agent}:${model})`, 'gray');
return response;
}
}
log(' ⚠ Repo eval timeout (check results later)', 'yellow');
log(` Run: tessl eval view ${evalRunId}`, 'gray');
return null;
} catch (error) {
log(` ⚠ Repo eval failed: ${error.message}`, 'yellow');
return null;
}
}
async function publishTile() {
try {
const tilePath = path.join(process.cwd(), 'examples/skill-builder');
const tileJsonPath = path.join(tilePath, 'tile.json');
// Publish the tile (private remains true in tile.json)
exec(`cd ${tilePath} && tessl skill publish`, { silent: true });
const tileJson = JSON.parse(fs.readFileSync(tileJsonPath, 'utf8'));
log(` ✓ Published ${tileJson.name}@${tileJson.version} (private)`, 'green');
log(` (Tile is published to your workspace but remains private)`, 'gray');
} catch (error) {
log(' ⚠ Publishing skipped (non-fatal)', 'yellow');
log(` Error: ${error.message}`, 'gray');
}
}
async function generateOutputs(reviewResults, tileEvalResults, repoEvalResults, startTime) {
const duration = Math.round((Date.now() - startTime) / 1000);
const username = exec('tessl whoami', { silent: true }).trim();
// Generate human summary
const summary = `# Tessl Setup Complete! 🎉
You now have Tessl installed and configured. Here's what you have:
**✓ Tessl CLI** - Installed and authenticated as ${username}
**✓ skill-builder Skill** - A working example in \`examples/skill-builder/\` that helps you create more skills
**✓ Quality Checks Passed**
- Skill Review: ${reviewResults.score}/100 (structure ✓)
- Tile Eval: ${tileEvalResults.passed}/${tileEvalResults.total} scenarios passed (function ✓)
${repoEvalResults ? `- Repo Eval: ${repoEvalResults.passed}/${repoEvalResults.total} scenarios passed (integration ✓)` : '- Repo Eval: skipped (optional)'}
## What You Can Do Now
1. **Try skill-builder:** Use it to create your first skill
2. **Explore the registry:** Run \`tessl skill search\` to see what's available
3. **Read the docs:** Visit https://docs.tessl.io for more
## What You Learned
- **Skills** are tested, versioned agent capabilities
- **Review** validates structure before function
- **Evals** test real behavior with scenarios
- **The quality pipeline** ensures production readiness
Setup took ${duration} seconds. Happy building! 🚀
`;
fs.writeFileSync('onboarding-summary.md', summary);
// Generate agent report (detailed)
const report = `# Tessl Onboarding Report
**Completed:** ${new Date().toISOString()}
**Duration:** ${duration} seconds
**User:** ${username}
## Execution Summary
All onboarding steps completed successfully.
## Results
### Skill Review
- Score: ${reviewResults.score}/100
- Status: ${reviewResults.score >= 80 ? 'Passed' : 'Needs improvement'}
### Tile Eval
- Scenarios: ${tileEvalResults.total}
- Passed: ${tileEvalResults.passed}
- Failed: ${tileEvalResults.total - tileEvalResults.passed}
- Pass Rate: ${Math.round((tileEvalResults.passed / tileEvalResults.total) * 100)}%
${repoEvalResults ? `### Repo Eval
- Scenarios: ${repoEvalResults.total}
- Passed: ${repoEvalResults.passed}
- Pass Rate: ${Math.round((repoEvalResults.passed / repoEvalResults.total) * 100)}%
` : '### Repo Eval\nSkipped (optional step)\n'}
## Artifacts Created
- \`examples/skill-builder/\` - Example skill
- \`.tessl/evals/\` - Repo eval scenarios
- \`onboarding-summary.md\` - Human summary
- \`onboarding-report.md\` - This report
## Next Steps
User should:
1. Try skill-builder to create a new skill
2. Explore the registry
3. Read documentation
Agents should: