tokensafe 4.4.3 → 4.4.5

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.
@@ -0,0 +1,515 @@
1
+ """
2
+ TokenSafe Greenfield Project Scaffolder.
3
+ Creates deterministic, token-efficient Fullstack, UI, and Backend projects
4
+ instrumented with tokensafe-ui, tokensafe-python, and the UARP/OUMV protocol.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import json
10
+ from typing import Dict, Any, Optional, List
11
+
12
+
13
+ DEFAULT_FRONTEND_PACKAGE_JSON = {
14
+ "name": "{project_name}-ui",
15
+ "version": "0.1.0",
16
+ "private": True,
17
+ "type": "module",
18
+ "scripts": {
19
+ "dev": "vite",
20
+ "build": "vite build",
21
+ "preview": "vite preview",
22
+ "typecheck": "tsc --noEmit"
23
+ },
24
+ "dependencies": {
25
+ "tokensafe-ui": "^0.1.6",
26
+ "zod": "^3.24.1"
27
+ },
28
+ "devDependencies": {
29
+ "typescript": "^5.7.2",
30
+ "vite": "^6.0.7"
31
+ }
32
+ }
33
+
34
+ DEFAULT_TSCONFIG = {
35
+ "compilerOptions": {
36
+ "target": "ES2022",
37
+ "useDefineForClassFields": True,
38
+ "module": "ESNext",
39
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
40
+ "skipLibCheck": True,
41
+ "moduleResolution": "bundler",
42
+ "allowImportingTsExtensions": True,
43
+ "resolveJsonModule": True,
44
+ "isolatedModules": True,
45
+ "noEmit": True,
46
+ "jsx": "preserve",
47
+ "strict": True,
48
+ "noUnusedLocals": True,
49
+ "noUnusedParameters": True,
50
+ "noFallthroughCasesInSwitch": True
51
+ },
52
+ "include": ["src"]
53
+ }
54
+
55
+ DEFAULT_VITE_CONFIG = """import { defineConfig } from 'vite';
56
+
57
+ export default defineConfig({
58
+ server: {
59
+ port: 5173,
60
+ host: true,
61
+ },
62
+ });
63
+ """
64
+
65
+ DEFAULT_HTML = """<!DOCTYPE html>
66
+ <html lang="en">
67
+ <head>
68
+ <meta charset="UTF-8" />
69
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
70
+ <title>{project_name} | TokenSafe App</title>
71
+ <link rel="stylesheet" href="./src/style.css" />
72
+ </head>
73
+ <body>
74
+ <div id="app"></div>
75
+ <script type="module" src="./src/main.ts"></script>
76
+ </body>
77
+ </html>
78
+ """
79
+
80
+ DEFAULT_STYLE_CSS = """* {
81
+ box-sizing: border-box;
82
+ margin: 0;
83
+ padding: 0;
84
+ }
85
+
86
+ body {
87
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
88
+ background-color: #0d1117;
89
+ color: #c9d1d9;
90
+ display: flex;
91
+ justify-content: center;
92
+ align-items: center;
93
+ min-height: 100vh;
94
+ }
95
+
96
+ .container {
97
+ background: #161b22;
98
+ border: 1px solid #30363d;
99
+ border-radius: 12px;
100
+ padding: 2.5rem;
101
+ width: 100%;
102
+ max-width: 480px;
103
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
104
+ }
105
+
106
+ h1 {
107
+ font-size: 1.75rem;
108
+ font-weight: 600;
109
+ margin-bottom: 0.5rem;
110
+ color: #58a6ff;
111
+ }
112
+
113
+ p {
114
+ color: #8b949e;
115
+ margin-bottom: 1.5rem;
116
+ }
117
+
118
+ input {
119
+ width: 100%;
120
+ padding: 0.65rem 0.85rem;
121
+ background: #0d1117;
122
+ border: 1px solid #30363d;
123
+ border-radius: 6px;
124
+ color: #c9d1d9;
125
+ font-size: 1rem;
126
+ margin-bottom: 1.5rem;
127
+ outline: none;
128
+ }
129
+
130
+ input:focus {
131
+ border-color: #58a6ff;
132
+ }
133
+
134
+ .counter-group {
135
+ display: flex;
136
+ align-items: center;
137
+ justify-content: space-between;
138
+ background: #0d1117;
139
+ border: 1px solid #30363d;
140
+ border-radius: 8px;
141
+ padding: 0.5rem 1rem;
142
+ }
143
+
144
+ button {
145
+ background: #238636;
146
+ color: #ffffff;
147
+ border: none;
148
+ border-radius: 6px;
149
+ width: 36px;
150
+ height: 36px;
151
+ font-size: 1.25rem;
152
+ font-weight: 600;
153
+ cursor: pointer;
154
+ transition: background 0.15s ease;
155
+ }
156
+
157
+ button:hover {
158
+ background: #2ea043;
159
+ }
160
+
161
+ .count-value {
162
+ font-size: 1.5rem;
163
+ font-weight: 600;
164
+ color: #f0f6fc;
165
+ }
166
+ """
167
+
168
+ DEFAULT_MAIN_TS = """import { mount } from 'tokensafe-ui';
169
+ import { App } from './App';
170
+
171
+ const container = document.getElementById('app');
172
+ if (container) {
173
+ mount(App, container);
174
+ }
175
+ """
176
+
177
+ DEFAULT_APP_TSX = """import { defineComponent, z, bind, h } from 'tokensafe-ui';
178
+
179
+ export const App = defineComponent({
180
+ id: 'app-root',
181
+ state: {
182
+ count: z.number().default(0),
183
+ name: z.string().default('Agent'),
184
+ },
185
+ actions: {
186
+ inc: (s) => ({ ...s, count: s.count + 1 }),
187
+ dec: (s) => ({ ...s, count: Math.max(0, s.count - 1) }),
188
+ setName: (s, name: string) => ({ ...s, name }),
189
+ },
190
+ render: ({ state, emit }) =>
191
+ h(
192
+ 'div',
193
+ { class: 'container', 'data-agent-id': 'app-root:container' },
194
+ h('h1', { 'data-agent-id': 'app-root:title' }, 'TokenSafe UI'),
195
+ h('p', { 'data-agent-id': 'app-root:greeting' }, `Hello, ${state.name}!`),
196
+ h('input', {
197
+ type: 'text',
198
+ placeholder: 'Enter your name',
199
+ 'data-agent-id': 'app-root:input-name',
200
+ ...bind(emit.setName, state.name),
201
+ }),
202
+ h(
203
+ 'div',
204
+ { class: 'counter-group', 'data-agent-id': 'app-root:counter-group' },
205
+ h(
206
+ 'button',
207
+ { 'data-agent-id': 'app-root:btn-dec', onClick: () => emit.dec() },
208
+ '-'
209
+ ),
210
+ h(
211
+ 'span',
212
+ { class: 'count-value', 'data-agent-id': 'app-root:count-value' },
213
+ String(state.count)
214
+ ),
215
+ h(
216
+ 'button',
217
+ { 'data-agent-id': 'app-root:btn-inc', onClick: () => emit.inc() },
218
+ '+'
219
+ )
220
+ )
221
+ ),
222
+ });
223
+ """
224
+
225
+ DEFAULT_BACKEND_MAIN_PY = """\"\"\"
226
+ {project_name} Backend API instrumented with TokenSafe UARP / OUMV Protocol.
227
+ \"\"\"
228
+
229
+ from typing import List, Optional
230
+ from fastapi import FastAPI, HTTPException
231
+ from fastapi.middleware.cors import CORSMiddleware
232
+ from pydantic import BaseModel, Field
233
+
234
+ from tokensafe_python.adapters.fastapi import mount_tokensafe
235
+
236
+ app = FastAPI(
237
+ title="{project_name} API",
238
+ description="FastAPI service with native TokenSafe OUMV runtime introspection and simulation.",
239
+ version="0.1.0",
240
+ )
241
+
242
+ app.add_middleware(
243
+ CORSMiddleware,
244
+ allow_origins=["*"],
245
+ allow_credentials=True,
246
+ allow_methods=["*"],
247
+ allow_headers=["*"],
248
+ )
249
+
250
+
251
+ class ItemCreate(BaseModel):
252
+ title: str = Field(..., example="Sample Item")
253
+ price: float = Field(..., gt=0, example=19.99)
254
+
255
+
256
+ class ItemResponse(BaseModel):
257
+ id: int
258
+ title: str
259
+ price: float
260
+
261
+
262
+ # Mock in-memory state
263
+ db: List[ItemResponse] = [
264
+ ItemResponse(id=1, title="Initial Product", price=49.99),
265
+ ]
266
+
267
+
268
+ @app.get("/api/items", response_model=List[ItemResponse], tags=["Items"])
269
+ def get_items():
270
+ return db
271
+
272
+
273
+ @app.post("/api/items", response_model=ItemResponse, status_code=201, tags=["Items"])
274
+ def create_item(item: ItemCreate):
275
+ new_item = ItemResponse(id=len(db) + 1, title=item.title, price=item.price)
276
+ db.append(new_item)
277
+ return new_item
278
+
279
+
280
+ # Mount TokenSafe UARP Runtime (registers /__oumv/rpc, /__oumv/health, and writes .tokensafe/runtime.json)
281
+ mount_tokensafe(app, port=8000)
282
+
283
+ if __name__ == "__main__":
284
+ import uvicorn
285
+ uvicorn.run(app, host="127.0.0.1", port=8000)
286
+ """
287
+
288
+ DEFAULT_BACKEND_PYPROJECT = """[project]
289
+ name = "{project_name}-backend"
290
+ version = "0.1.0"
291
+ description = "TokenSafe instrumented FastAPI backend service"
292
+ readme = "README.md"
293
+ requires-python = ">=3.10"
294
+ dependencies = [
295
+ "fastapi>=0.110.0",
296
+ "uvicorn>=0.28.0",
297
+ "pydantic>=2.6.0",
298
+ "tokensafe-python>=0.1.0",
299
+ ]
300
+
301
+ [build-system]
302
+ requires = ["setuptools>=61.0"]
303
+ build-backend = "setuptools.build_meta"
304
+ """
305
+
306
+ DEFAULT_GITIGNORE = """# Dependencies
307
+ node_modules/
308
+ .venv/
309
+ __pycache__/
310
+ *.pyc
311
+
312
+ # Build outputs
313
+ dist/
314
+ build/
315
+ *.egg-info/
316
+
317
+ # Logs & temp
318
+ *.log
319
+ .DS_Store
320
+ .env
321
+ .env.local
322
+ """
323
+
324
+
325
+ class ProjectScaffolder:
326
+ """Creates greenfield TokenSafe ecosystem projects."""
327
+
328
+ @classmethod
329
+ def scaffold(
330
+ cls,
331
+ target_dir: str,
332
+ project_name: str,
333
+ template: str = "fullstack",
334
+ force: bool = False
335
+ ) -> Dict[str, Any]:
336
+ """Generates project template files in target_dir."""
337
+ template = template.lower().strip()
338
+ if template not in ("fullstack", "ui", "backend", "python", "fastapi", "go"):
339
+ raise ValueError(f"Unknown template: '{template}'. Valid options: fullstack, ui, backend, python, go")
340
+
341
+ if template in ("python", "fastapi"):
342
+ template = "backend"
343
+
344
+ os.makedirs(target_dir, exist_ok=True)
345
+ created_files: List[str] = []
346
+
347
+ def _write(rel_path: str, content: str):
348
+ full_path = os.path.join(target_dir, rel_path)
349
+ if os.path.exists(full_path) and not force:
350
+ return
351
+ os.makedirs(os.path.dirname(full_path), exist_ok=True)
352
+ with open(full_path, "w", encoding="utf-8") as f:
353
+ f.write(content)
354
+ created_files.append(rel_path)
355
+
356
+ def _write_json(rel_path: str, data: dict):
357
+ full_path = os.path.join(target_dir, rel_path)
358
+ if os.path.exists(full_path) and not force:
359
+ return
360
+ os.makedirs(os.path.dirname(full_path), exist_ok=True)
361
+ with open(full_path, "w", encoding="utf-8") as f:
362
+ json.dump(data, f, indent=2)
363
+ created_files.append(rel_path)
364
+
365
+ # 1. Base files (.tokensafe/runtime.json, .gitignore, README.md, AGENTS.md)
366
+ _write(".gitignore", DEFAULT_GITIGNORE)
367
+
368
+ # 2. Template-specific layout
369
+ if template == "fullstack":
370
+ cls._scaffold_ui(target_dir, project_name, subpath="frontend", write_fn=_write, write_json_fn=_write_json)
371
+ cls._scaffold_backend(target_dir, project_name, subpath="backend", write_fn=_write)
372
+
373
+ runtime_config = {
374
+ "frontend": {
375
+ "name": "tokensafe-ui",
376
+ "version": "0.1.6",
377
+ "url": "http://localhost:5173/__oumv/rpc"
378
+ },
379
+ "backend": {
380
+ "name": "tokensafe-python",
381
+ "version": "0.1.0",
382
+ "url": "http://localhost:8000/__oumv/rpc"
383
+ }
384
+ }
385
+ _write_json(os.path.join(".tokensafe", "runtime.json"), runtime_config)
386
+
387
+ agents_md = cls._generate_agents_md(project_name, is_fullstack=True)
388
+ _write("AGENTS.md", agents_md)
389
+ readme = cls._generate_readme(project_name, template="fullstack")
390
+ _write("README.md", readme)
391
+
392
+ elif template == "ui":
393
+ cls._scaffold_ui(target_dir, project_name, subpath="", write_fn=_write, write_json_fn=_write_json)
394
+ runtime_config = {
395
+ "frontend": {
396
+ "name": "tokensafe-ui",
397
+ "version": "0.1.6",
398
+ "url": "http://localhost:5173/__oumv/rpc"
399
+ }
400
+ }
401
+ _write_json(os.path.join(".tokensafe", "runtime.json"), runtime_config)
402
+ agents_md = cls._generate_agents_md(project_name, is_fullstack=False, is_ui=True)
403
+ _write("AGENTS.md", agents_md)
404
+ readme = cls._generate_readme(project_name, template="ui")
405
+ _write("README.md", readme)
406
+
407
+ elif template in ("backend", "go"):
408
+ cls._scaffold_backend(target_dir, project_name, subpath="", write_fn=_write)
409
+ runtime_config = {
410
+ "backend": {
411
+ "name": "tokensafe-python" if template != "go" else "tokensafe-backend",
412
+ "version": "0.1.0",
413
+ "url": "http://localhost:8000/__oumv/rpc" if template != "go" else "http://localhost:8080/__oumv/rpc"
414
+ }
415
+ }
416
+ _write_json(os.path.join(".tokensafe", "runtime.json"), runtime_config)
417
+ agents_md = cls._generate_agents_md(project_name, is_fullstack=False, is_ui=False)
418
+ _write("AGENTS.md", agents_md)
419
+ readme = cls._generate_readme(project_name, template="backend")
420
+ _write("README.md", readme)
421
+
422
+ return {
423
+ "success": True,
424
+ "project_name": project_name,
425
+ "template": template,
426
+ "target_dir": target_dir,
427
+ "created_files": created_files,
428
+ }
429
+
430
+ @classmethod
431
+ def _scaffold_ui(cls, target_dir: str, project_name: str, subpath: str, write_fn, write_json_fn):
432
+ p = lambda rel: os.path.join(subpath, rel) if subpath else rel
433
+
434
+ pkg = dict(DEFAULT_FRONTEND_PACKAGE_JSON)
435
+ pkg["name"] = f"{project_name.lower().replace(' ', '-')}-ui"
436
+ write_json_fn(p("package.json"), pkg)
437
+ write_json_fn(p("tsconfig.json"), DEFAULT_TSCONFIG)
438
+ write_fn(p("vite.config.ts"), DEFAULT_VITE_CONFIG)
439
+ write_fn(p("index.html"), DEFAULT_HTML.replace("{project_name}", project_name))
440
+ write_fn(p(os.path.join("src", "style.css")), DEFAULT_STYLE_CSS)
441
+ write_fn(p(os.path.join("src", "main.ts")), DEFAULT_MAIN_TS)
442
+ write_fn(p(os.path.join("src", "App.tsx")), DEFAULT_APP_TSX)
443
+
444
+ @classmethod
445
+ def _scaffold_backend(cls, target_dir: str, project_name: str, subpath: str, write_fn):
446
+ p = lambda rel: os.path.join(subpath, rel) if subpath else rel
447
+ clean_name = project_name.replace("-", " ").title()
448
+
449
+ main_py = DEFAULT_BACKEND_MAIN_PY.replace("{project_name}", clean_name)
450
+ write_fn(p("main.py"), main_py)
451
+
452
+ pyproject = DEFAULT_BACKEND_PYPROJECT.replace("{project_name}", project_name.lower().replace(" ", "-"))
453
+ write_fn(p("pyproject.toml"), pyproject)
454
+
455
+ @classmethod
456
+ def _generate_agents_md(cls, project_name: str, is_fullstack: bool = True, is_ui: bool = False) -> str:
457
+ if is_fullstack:
458
+ return f"""# Project Architecture: {project_name}
459
+
460
+ This project is built using the **TokenSafe Native Ecosystem**:
461
+ - **Frontend** (`frontend/`): `tokensafe-ui` (reactive deterministic components, zero-bundle DOM parity) with Vite on port 5173.
462
+ - **Backend** (`backend/`): `tokensafe-python` (FastAPI with UARP / OUMV protocol runtime) on port 8000.
463
+ - **Auto-Discovery**: Connected via `.tokensafe/runtime.json`.
464
+
465
+ ## AI Coding Agent Directives:
466
+ 1. **Frontend Changes**: Always write components using `defineComponent` from `tokensafe-ui`. Do not convert to React.
467
+ 2. **Backend Changes**: Keep routes instrumented with Pydantic and `mount_tokensafe(app)`.
468
+ 3. **Runtime Verification**: Use `tokensafe:oumv_observe(level="L0")`, `tokensafe:oumv_understand`, and `tokensafe:oumv_verify` to test actions in memory.
469
+ """
470
+ elif is_ui:
471
+ return f"""# Project Architecture: {project_name}
472
+
473
+ This project is built using **tokensafe-ui**:
474
+ - Components are defined with `defineComponent` and Zod state schemas.
475
+ - Interactive elements include `data-agent-id` for deterministic agent discovery.
476
+ - Use `tokensafe:oumv_observe` and `tokensafe:oumv_verify` for UI inspection.
477
+ """
478
+ else:
479
+ return f"""# Project Architecture: {project_name}
480
+
481
+ This project is built using **tokensafe-python** (FastAPI):
482
+ - Exposes `/__oumv/rpc` and `/__oumv/health` for agent introspection.
483
+ - Use `tokensafe:oumv_verify` for transactional testing without touching production databases.
484
+ """
485
+
486
+ @classmethod
487
+ def _generate_readme(cls, project_name: str, template: str) -> str:
488
+ return f"""# {project_name}
489
+
490
+ Greenfield application scaffolded with the **TokenSafe Ecosystem** (`tokensafe create`).
491
+
492
+ ## Tech Stack
493
+ - Template: `{template}`
494
+ - Frontend: `tokensafe-ui` (Reactive signals, deterministic DOM)
495
+ - Backend: `tokensafe-python` (FastAPI + UARP/OUMV protocol)
496
+ - AI Agent Tools: `tokensafe` MCP server with 25 tools (AST slicing + OUMV live runtime)
497
+
498
+ ## Quick Start
499
+
500
+ ### 1. Frontend
501
+ ```bash
502
+ cd frontend # (or root)
503
+ npm install
504
+ npm run dev
505
+ ```
506
+ Open `http://localhost:5173`
507
+
508
+ ### 2. Backend
509
+ ```bash
510
+ cd backend # (or root)
511
+ pip install -e .
512
+ python main.py
513
+ ```
514
+ Backend runs on `http://localhost:8000` with OUMV endpoint at `/__oumv/rpc`.
515
+ """
@@ -241,7 +241,7 @@ class TelemetrySync:
241
241
  current_last_id = last_id
242
242
  headers = {
243
243
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.4.3"
244
+ "User-Agent": "TokenSafe-Sync/4.4.5"
245
245
  }
246
246
  if active_key:
247
247
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.4.3"
20
+ CURRENT_VERSION = "4.4.5"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage