37"imports": {
38"@atproto/oauth-client-browser": "npm:@atproto/oauth-client-browser@0.3.15",
39"@atproto/api": "npm:@atproto/api@0.15.5",
40"three": "npm:three@0.180.0"
41}
qbatbluesky-oauth.ts1 match
4OAuthSession,
5} from "https://esm.sh/@atproto/oauth-client-browser@0.3.15";
6import { Agent } from "https://esm.sh/@atproto/api@0.15.5";
78// OAuth client metadata - should match the backend configuration
weatherAppmain.tsx1 match
16useEffect(() => {
17async function fetchWeather() {
18const url = `https://api.open-meteo.com/v1/forecast?latitude=${city.lat}&longitude=${city.lon}¤t_weather=true`;
19const res = await fetch(url);
20const data = await res.json();
5<meta charset="UTF-8">
6<meta name="viewport" content="width=device-width, initial-scale=1.0">
7<title>NVIDIA API Client</title>
8<style>
9body {
121}
122
123.api-key-group {
124background: #fff3cd;
125border: 1px solid #ffeaa7;
129}
130
131.api-key-group label {
132color: #856404;
133}
161<div class="container">
162<div class="form-panel">
163<h1>NVIDIA API Client</h1>
164
165<form id="apiForm">
166<div class="api-key-group">
167<div class="form-group">
168<label for="apiKey">API Key:</label>
169<input type="password" id="apiKey" name="apiKey" placeholder="Enter your NVIDIA API key">
170</div>
171</div>
229<h2>Response</h2>
230<div id="responseContent" class="response-content">
231Click "Send Request" to see the API response here.
232</div>
233</div>
273errorHtml += '<strong>π Network Error Troubleshooting:</strong>\\n';
274errorHtml += 'β’ Check your internet connection\\n';
275errorHtml += 'β’ Verify the API endpoint is accessible\\n';
276errorHtml += 'β’ Check if CORS is blocking the request\\n';
277errorHtml += 'β’ Ensure the server is running and reachable\\n';
331// Load saved values
332function loadSavedValues() {
333// Load API key from cookie
334const savedApiKey = getCookie('nvidia_api_key');
335if (savedApiKey) {
336document.getElementById('apiKey').value = savedApiKey;
337}
338362// Save current form values
363function saveCurrentValues() {
364const form = document.getElementById('apiForm');
365const formData = new FormData(form);
366const params = {};
367
368// Save API key to cookie
369const apiKey = formData.get('apiKey');
370if (apiKey) {
371setCookie('nvidia_api_key', apiKey);
372}
373374// Save other parameters to localStorage
375for (const [key, value] of formData.entries()) {
376if (key !== 'apiKey') {
377if (key === 'messages') {
378try {
397}
398399// Enhanced API request function
400async function makeApiRequest(requestData, apiKey) {
401const requestHeaders = {
402'Authorization': \`Bearer \${apiKey}\`,
403'Accept': 'application/json',
404'Content-Type': 'application/json'
406407try {
408const response = await fetch('https://integrate.api.nvidia.com/v1/chat/completions', {
409method: 'POST',
410headers: requestHeaders,
519520// Form submission handler with comprehensive error handling
521document.getElementById('apiForm').addEventListener('submit', async (e) => {
522e.preventDefault();
523
538// Get form data
539const formData = new FormData(e.target);
540const apiKey = formData.get('apiKey');
541
542if (!apiKey) {
543throw new Error('API Key is required');
544}
545
560saveCurrentValues();
561
562// Make API request
563const response = await makeApiRequest(requestData, apiKey);
564
565// Handle response based on streaming
1# NVIDIA API Client
23A plain vanilla HTML/JS/CSS web interface for making requests to the NVIDIA API chat completions endpoint.
45## Features
67- **Form Interface**: Clean, user-friendly form with all NVIDIA API parameters
8- **API Key Storage**: Securely stores API key in browser cookies for convenience
9- **Request Persistence**: Remembers last request parameters using localStorage
10- **Streaming Support**: Handles both streaming and non-streaming responses
11- **Real-time Response Display**: Shows API responses in real-time with proper formatting
12- **Error Handling**: Comprehensive error messages with detailed diagnostic information, troubleshooting guidance, and full request/response context
1316The interface includes all parameters from the original curl command:
1718- **API Key**: Your NVIDIA API key (stored in cookies)
19- **Model**: AI model to use (default: `openai/gpt-oss-20b`)
20- **Messages**: JSON array of conversation messages
29## Usage
30311. Enter your NVIDIA API key (will be saved for future use)
322. Modify any parameters as needed
333. Click "Send Request" to make the API call
344. View the response in the right panel
3540- Responsive two-column layout
41- Proper error handling and loading states
42- Cookie-based API key persistence
43- localStorage for form state persistence
4445## API Endpoint
4647Makes requests to: `https://integrate.api.nvidia.com/v1/chat/completions`
4849Equivalent to the provided curl command with all the same headers and data structure.
29app.get("/callback", (c) => c.json(c.req));
3031// Add your API routes here
32// app.get("/api/data", c => c.json({ hello: "world" }));
3334// Unwrap and rethrow Hono errors as the original error
sachersolindex.html4 matches
2021<!-- Google Fonts: thin, airy vibe -->
22<link rel="preconnect" href="https://fonts.googleapis.com">
23<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
24<link href="https://fonts.googleapis.com/css2?family=Lexend+Deca:wght@100..900&display=swap" rel="stylesheet">
2526<!-- Tailwind + Alpine -->
246<ul class="mt-6 space-y-2 text-slate-700">
247<li>β’ Goal decomposition and habit stacking</li>
248<li>β’ Asynchronous checkβins and rapid feedback loops</li>
249<li>β’ Parent coaching for calm collaboration</li>
250</ul>
315};
316try {
317const res = await fetch('/api/email',
318{
319method: 'POST',
untitled-8620main.ts7 matches
81/**
82* Main asynchronous process to build the prerequisite graph level-by-level.
83* Tracks processed nodes to avoid redundant API calls and circular dependencies.
84*/
85async function buildTreeInBackground(jobId: string, rootNode: FactNode) {
136});
137138// Wait for all API calls on the current level to complete.
139await Promise.all(processingPromises);
140171<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
172<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
173<link rel="preconnect" href="https://fonts.googleapis.com">
174<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
175<link href="https://fonts.googleapis.com/css2?family=Source+Serif+4:opsz,wght@8..60,400;8..60,600&family=Source+Sans+3:wght@400;600&display=swap" rel="stylesheet">
176<style>
177:root {
344const { useState, useEffect, useCallback } = React;
345346const API_BASE_URL = '${sourceUrl}';
347const POLLING_INTERVAL = 2000;
348419
420try {
421const response = await fetch(\`\${API_BASE_URL}/start\`, {
422method: 'POST',
423headers: { 'Content-Type': 'application/json' },
442const pollJobStatus = async () => {
443try {
444const response = await fetch(\`\${API_BASE_URL}/status?jobId=\${jobId}\`);
445if (!response.ok) throw new Error('Polling failed');
446
2223The following routes are accessible without authentication:
24- `/api/health` - System health status
2526### Protected Routes
30**User Authentication (Google OAuth via LastLogin):**
31- `/` - Main dashboard (shows user info and system status)
32- `/api/*` - API endpoints (except health)
33- `/views/*` - View routes including `/views/glimpse/:id`
34- `/glimpse/*` - Shortcut routes including `/glimpse/:id` (equivalent to `/views/glimpse/:id`)
3536**Webhook Authentication (X-API-KEY header):**
37- `/tasks/*` - Webhook endpoints for external integrations (POST requests only)
38- GET requests to `/tasks/*` are allowed without authentication for debug endpoints
44β βββ controllers/ # Business logic controllers
45β βββ routes/ # Route definitions and HTTP handling
46β β βββ api/ # API endpoints
47β β βββ glimpse/ # Glimpse routes (enhanced with React frontend)
48β β βββ tasks/ # Task-related routes
8485### **Service Layer** (External Integrations)
86- Handles external API calls (Notion, databases)
87- Manages data persistence
88- Returns structured results with success/error information
122- `GET /glimpse/:id` - **Enhanced with React Frontend** - Content negotiation based on Accept header:
123- **Browser requests** (`Accept: text/html`): Returns rich React frontend with interactive Notion content display
124- **API requests** (`Accept: application/json`): Returns raw JSON data (same as before)
125- **Fallback**: If HTML template fails to load, automatically serves JSON
126159**Note:** The glimpse endpoints now provide both programmatic access (JSON) and user-friendly viewing (React frontend) from the same URL, maintaining backward compatibility while adding rich content display capabilities.
160161### Demo API Endpoints
162163API endpoints for accessing Notion page data with different levels of detail:
164165- `GET /api/demo/:id/properties` - Returns page properties only
166- `GET /api/demo/:id` - Returns page properties + all blocks recursively
167- `GET /api/agent/:id` - Returns agent blob data for a specific page ID
168169**Architecture:**
170- **Routes**: Handle HTTP concerns (parameter extraction, response formatting, status codes)
171- **Controllers**: Contain business logic (`getDemoProperties`, `getDemoFull`)
172- **Services**: Handle Notion API integration
173174**Authentication Behavior:**
196```javascript
197// Internal call from within Val (no authentication needed)
198const response = await fetch('/api/demo/page-id/properties');
199const data = await response.json();
200208- Filter out button properties from Notion page data
209- Return standardized JSON responses (except authentication routes which redirect or show HTML)
210- Use the same controller functions as the API endpoints for consistency
211212### New User Registration Flow
259### Webhook Endpoints
260261- `POST /tasks/notion-webhook` - Main webhook endpoint for Notion integrations (requires `X-API-KEY` header)
262- `POST /tasks/url` - Updates Notion page URL property with glimpse URL (requires `X-API-KEY` header)
263- `POST /tasks/assign` - Assigns agents to tasks based on Assigned property matching (requires `X-API-KEY` header)
264- `POST /tasks/test` - Test endpoint for webhook authentication (requires `X-API-KEY` header)
265- `GET /tasks/debug-webhook` - Debug endpoint to check webhook configuration
266366- **Preserves Same-Demo Assignments**: No clearing when reassigning to the same demo
367- **Prevents Multiple Assignments**: Ensures agents are only assigned to one demo at a time
368- **Efficient**: Minimal API calls - only clears when necessary
369- **Reliable**: Handles new agents, existing agents, and reassignments correctly
370396- **Fast Execution**: Blob scanning is faster than database queries
397- **Targeted Processing**: Only processes pages with empty agent arrays
398- **Resource Efficient**: Minimal API calls to Notion
399400**Monitoring Output:**
416### Authentication
417418Webhook endpoints require the `X-API-KEY` header:
419```bash
420curl -X POST https://your-val.web.val.run/tasks/test \
421-H "X-API-KEY: your-secret-key-here"
422```
423437- `GLANCE_INTERACTIONS_DB_ID` - Notion database ID for interactions
438- `GLANCE_AGENTS_DB_ID` - Notion database ID for agents
439- `NOTION_API_KEY` - Notion API key for database access
440- `NOTION_WEBHOOK_SECRET` - Secret key for webhook authentication
441446### **Authorization & Security**
447- **Email-based Access Control**: Viewing analytics are only tracked when the authenticated user's email matches the page's Email property
448- **Frontend Authorization**: Email comparison happens on the frontend before any API calls are made
449- **Zero Unauthorized Calls**: Users without matching emails generate no viewing API requests
450- **Automatic Detection**: System automatically extracts emails from Notion page properties and user authentication
451483### **Viewing Data Flow**
4841. **Authorization Check**: Frontend compares user email with page Email property
4852. **Authorized Users**: Frontend calls `/api/viewing` β Blob updated β **Notion synced immediately**
486- **Session starts** (`null` β `timestamp`): Updates "Session start" and "Viewing start" (first time) properties
487- **Session stops** (`timestamp` β `null`): Clears "Session start" property (preserves "Viewing start")
4893. **User continues viewing**: Frontend updates blob every 4 seconds (no Notion calls)
4904. **User leaves/session stale**: Cron detects stale session β Blob updated β **Notion synced immediately**
4915. **Unauthorized Users**: No API calls made, no viewing analytics tracked
492493### **Notion Property Behavior**
533### **Frontend Integration**
534- **Email Authorization**: Compares authenticated user email with page Email property before tracking
535- **Page Visibility API**: Tracks when users switch tabs or minimize windows
536- **Periodic updates**: Calls viewing API every 4 seconds while page is active (authorized users only)
537- **Session management**: Automatic cleanup handles crashed browsers and network issues
538- **Performance**: Non-blocking API calls don't impact user experience, zero calls for unauthorized users
9// Simple test endpoint
10app.get("/test", async (c) => {
11return c.json({ message: "API routes working", timestamp: new Date().toISOString() });
12});
13120const { cleanupStaleViewingSessions } = await import("../../controllers/viewing.controller.ts");
121
122console.log("π§ Manual cleanup triggered via API");
123const result = await cleanupStaleViewingSessions();
124