ltcai 3.6.0 → 4.0.0

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 (169) hide show
  1. package/README.md +11 -7
  2. package/docs/V4_BRAIN_ARCHITECTURE.md +322 -0
  3. package/docs/V4_DIGITAL_BRAIN_RECOVERY.md +509 -0
  4. package/docs/V4_IMPLEMENTATION_PLAN.md +470 -0
  5. package/docs/kg-schema.md +47 -53
  6. package/kg_schema.py +93 -10
  7. package/knowledge_graph.py +362 -33
  8. package/knowledge_graph_api.py +11 -127
  9. package/latticeai/__init__.py +1 -1
  10. package/latticeai/api/admin.py +1 -1
  11. package/latticeai/api/agents.py +7 -1
  12. package/latticeai/api/auth.py +27 -4
  13. package/latticeai/api/chat.py +112 -76
  14. package/latticeai/api/health.py +1 -1
  15. package/latticeai/api/hooks.py +1 -1
  16. package/latticeai/api/knowledge_graph.py +146 -0
  17. package/latticeai/api/local_files.py +1 -1
  18. package/latticeai/api/mcp.py +23 -11
  19. package/latticeai/api/memory.py +1 -1
  20. package/latticeai/api/models.py +1 -1
  21. package/latticeai/api/network.py +81 -0
  22. package/latticeai/api/realtime.py +1 -1
  23. package/latticeai/api/search.py +26 -2
  24. package/latticeai/api/security_dashboard.py +2 -3
  25. package/latticeai/api/setup.py +2 -2
  26. package/latticeai/api/static_routes.py +2 -4
  27. package/latticeai/api/tools.py +3 -0
  28. package/latticeai/api/workflow_designer.py +46 -0
  29. package/latticeai/api/workspace.py +71 -49
  30. package/latticeai/app_factory.py +1710 -0
  31. package/latticeai/brain/__init__.py +18 -0
  32. package/latticeai/brain/context.py +213 -0
  33. package/latticeai/brain/conversations.py +236 -0
  34. package/latticeai/brain/identity.py +175 -0
  35. package/latticeai/brain/memory.py +102 -0
  36. package/latticeai/brain/network.py +205 -0
  37. package/latticeai/core/agent.py +31 -7
  38. package/latticeai/core/audit.py +0 -7
  39. package/latticeai/core/config.py +1 -1
  40. package/latticeai/core/context_builder.py +1 -2
  41. package/latticeai/core/enterprise.py +1 -1
  42. package/latticeai/core/graph_curator.py +2 -2
  43. package/latticeai/core/marketplace.py +1 -1
  44. package/latticeai/core/mcp_registry.py +791 -0
  45. package/latticeai/core/model_compat.py +1 -1
  46. package/latticeai/core/model_resolution.py +0 -1
  47. package/latticeai/core/multi_agent.py +238 -4
  48. package/latticeai/core/security.py +1 -1
  49. package/latticeai/core/sessions.py +37 -7
  50. package/latticeai/core/workflow_engine.py +114 -2
  51. package/latticeai/core/workspace_os.py +58 -10
  52. package/latticeai/models/__init__.py +7 -0
  53. package/latticeai/models/router.py +779 -0
  54. package/latticeai/server_app.py +29 -1536
  55. package/latticeai/services/agent_runtime.py +1 -0
  56. package/latticeai/services/app_context.py +75 -14
  57. package/latticeai/services/ingestion.py +47 -0
  58. package/latticeai/services/kg_portability.py +33 -3
  59. package/latticeai/services/memory_service.py +39 -11
  60. package/latticeai/services/model_runtime.py +2 -5
  61. package/latticeai/services/platform_runtime.py +100 -23
  62. package/latticeai/services/search_service.py +17 -8
  63. package/latticeai/services/tool_dispatch.py +12 -2
  64. package/latticeai/services/triggers.py +241 -0
  65. package/latticeai/services/upload_service.py +37 -12
  66. package/latticeai/services/workspace_service.py +31 -0
  67. package/llm_router.py +29 -772
  68. package/ltcai_cli.py +1 -2
  69. package/mcp_registry.py +25 -788
  70. package/p_reinforce.py +124 -14
  71. package/package.json +9 -7
  72. package/scripts/bump_version.py +99 -0
  73. package/scripts/generate_diagrams.py +0 -1
  74. package/scripts/lint_v3.mjs +82 -18
  75. package/scripts/validate_release_artifacts.py +0 -1
  76. package/scripts/wheel_smoke.py +142 -0
  77. package/server.py +11 -7
  78. package/setup_wizard.py +1142 -0
  79. package/static/account.html +2 -4
  80. package/static/admin.html +3 -5
  81. package/static/chat.html +3 -6
  82. package/static/graph.html +2 -4
  83. package/static/sw.js +81 -52
  84. package/static/v3/asset-manifest.json +20 -19
  85. package/static/v3/css/{lattice.base.e4cdd05d.css → lattice.base.49deefb5.css} +1 -1
  86. package/static/v3/css/lattice.base.css +1 -1
  87. package/static/v3/css/{lattice.components.9b49d614.css → lattice.components.cde18231.css} +1 -1
  88. package/static/v3/css/lattice.components.css +1 -1
  89. package/static/v3/css/{lattice.shell.8fcc9d33.css → lattice.shell.29d36d85.css} +1 -1
  90. package/static/v3/css/lattice.shell.css +1 -1
  91. package/static/v3/css/{lattice.tokens.e7018963.css → lattice.tokens.304cbc40.css} +3 -0
  92. package/static/v3/css/lattice.tokens.css +3 -0
  93. package/static/v3/css/{lattice.views.22f69117.css → lattice.views.0a18b6c5.css} +2 -2
  94. package/static/v3/css/lattice.views.css +2 -2
  95. package/static/v3/index.html +3 -4
  96. package/static/v3/js/{app.c541f955.js → app.356e6452.js} +1 -1
  97. package/static/v3/js/core/{api.33d6320e.js → api.7a308b89.js} +1 -1
  98. package/static/v3/js/core/{routes.2ce3815a.js → routes.7222343d.js} +22 -22
  99. package/static/v3/js/core/routes.js +22 -22
  100. package/static/v3/js/core/{shell.8c163e0e.js → shell.a1657f20.js} +4 -4
  101. package/static/v3/js/core/shell.js +1 -1
  102. package/static/v3/js/core/{store.34ebd5e6.js → store.204a08b2.js} +1 -1
  103. package/static/v3/js/core/store.js +1 -1
  104. package/static/v3/js/views/graph-canvas.17c15d65.js +509 -0
  105. package/static/v3/js/views/graph-canvas.js +509 -0
  106. package/static/v3/js/views/{hybrid-search.b22b97e0.js → hybrid-search.2fb63ed9.js} +1 -2
  107. package/static/v3/js/views/hybrid-search.js +1 -2
  108. package/static/v3/js/views/{knowledge-graph.a96040a5.js → knowledge-graph.5e40cbeb.js} +33 -37
  109. package/static/v3/js/views/knowledge-graph.js +33 -37
  110. package/static/vendor/chart.umd.min.js +20 -0
  111. package/static/vendor/fonts/inter-latin-300-normal.woff2 +0 -0
  112. package/static/vendor/fonts/inter-latin-400-normal.woff2 +0 -0
  113. package/static/vendor/fonts/inter-latin-500-normal.woff2 +0 -0
  114. package/static/vendor/fonts/inter-latin-600-normal.woff2 +0 -0
  115. package/static/vendor/fonts/inter-latin-700-normal.woff2 +0 -0
  116. package/static/vendor/fonts/inter-latin-800-normal.woff2 +0 -0
  117. package/static/vendor/fonts/inter.css +44 -0
  118. package/static/vendor/icons/tabler-icons.min.css +4 -0
  119. package/static/vendor/icons/tabler-icons.woff2 +0 -0
  120. package/static/vendor/marked.min.js +69 -0
  121. package/static/workspace.html +2 -2
  122. package/telegram_bot.py +1 -2
  123. package/tools/commands.py +4 -2
  124. package/tools/computer.py +1 -1
  125. package/tools/documents.py +1 -3
  126. package/tools/filesystem.py +0 -4
  127. package/tools/knowledge.py +1 -3
  128. package/tools/network.py +1 -3
  129. package/codex_telegram_bot.py +0 -195
  130. package/docs/assets/v3.4.0/agent-run.png +0 -0
  131. package/docs/assets/v3.4.0/agents.png +0 -0
  132. package/docs/assets/v3.4.0/before/chat-before.png +0 -0
  133. package/docs/assets/v3.4.0/before/files-before.png +0 -0
  134. package/docs/assets/v3.4.0/chat.png +0 -0
  135. package/docs/assets/v3.4.0/connect-folder.png +0 -0
  136. package/docs/assets/v3.4.0/files.png +0 -0
  137. package/docs/assets/v3.4.0/home.png +0 -0
  138. package/docs/assets/v3.4.0/hooks-dispatch.png +0 -0
  139. package/docs/assets/v3.4.0/knowledge-graph.png +0 -0
  140. package/docs/assets/v3.4.0/local-agent.png +0 -0
  141. package/docs/assets/v3.4.0/memory.png +0 -0
  142. package/docs/assets/v3.4.0/settings.png +0 -0
  143. package/docs/assets/v3.4.0/vision-input.png +0 -0
  144. package/docs/assets/v3.4.0/workflows.png +0 -0
  145. package/docs/assets/v3.4.1/e2e_runtime_log.txt +0 -42
  146. package/docs/assets/v3.4.1/hooks-dispatch.png +0 -0
  147. package/docs/assets/v3.4.1/local-agent.png +0 -0
  148. package/docs/images/admin-dashboard.png +0 -0
  149. package/docs/images/architecture.png +0 -0
  150. package/docs/images/enterprise.png +0 -0
  151. package/docs/images/graph.png +0 -0
  152. package/docs/images/hero.gif +0 -0
  153. package/docs/images/knowledge-graph.png +0 -0
  154. package/docs/images/lattice-ai-demo.gif +0 -0
  155. package/docs/images/lattice-ai-hero.png +0 -0
  156. package/docs/images/logo.svg +0 -33
  157. package/docs/images/mobile-responsive.png +0 -0
  158. package/docs/images/model-recommendation.png +0 -0
  159. package/docs/images/onboarding.png +0 -0
  160. package/docs/images/organization.png +0 -0
  161. package/docs/images/pipeline.png +0 -0
  162. package/docs/images/screenshot-admin.png +0 -0
  163. package/docs/images/screenshot-chat.png +0 -0
  164. package/docs/images/screenshot-graph.png +0 -0
  165. package/docs/images/skills.png +0 -0
  166. package/docs/images/workspace-dark.png +0 -0
  167. package/docs/images/workspace-light.png +0 -0
  168. package/docs/images/workspace.png +0 -0
  169. package/requirements.txt +0 -16
@@ -10,11 +10,11 @@ export const MODE_RANK = { basic: 0, advanced: 1, admin: 2 };
10
10
 
11
11
  /** Nav groups in display order. */
12
12
  export const GROUPS = [
13
- { id: "workspace", label: "Workspace" },
14
- { id: "data", label: "Data" },
15
- { id: "retrieval", label: "Retrieval" },
16
- { id: "compute", label: "Compute" },
17
- { id: "platform", label: "Platform" },
13
+ { id: "brain", label: "Brain" },
14
+ { id: "ask", label: "Ask" },
15
+ { id: "capture", label: "Capture" },
16
+ { id: "act", label: "Act" },
17
+ { id: "library", label: "Library" },
18
18
  { id: "system", label: "System" },
19
19
  { id: "admin", label: "Administration", adminOnly: true },
20
20
  ];
@@ -25,37 +25,37 @@ export const GROUPS = [
25
25
  */
26
26
  export const ROUTES = [
27
27
  // Workspace
28
- { key: "home", label: "Home", icon: "layout-dashboard", group: "workspace", minMode: "basic", view: "home", title: "Home", desc: "Your local-first AI workspace at a glance." },
29
- { key: "chat", label: "Chat", icon: "message-2", group: "workspace", minMode: "basic", view: "chat", title: "Chat", desc: "Grounded conversation over your indexed workspace." },
28
+ { key: "home", label: "Overview", icon: "layout-dashboard", group: "system", minMode: "basic", view: "home", title: "Overview", desc: "Your digital brain at a glance." },
29
+ { key: "chat", label: "Chat", icon: "message-2", group: "ask", minMode: "basic", view: "chat", title: "Chat", desc: "Grounded conversation over your brain — memories, knowledge, and notes assembled with provenance." },
30
30
 
31
31
  // Data
32
- { key: "files", label: "Files", icon: "folders", group: "data", minMode: "basic", view: "files", title: "Files", desc: "Connected sources and indexed documents." },
32
+ { key: "files", label: "Files", icon: "folders", group: "capture", minMode: "basic", view: "files", title: "Files", desc: "Connected sources and indexed documents." },
33
33
 
34
34
  // Retrieval (the product identity)
35
- { key: "hybrid-search", label: "Search", icon: "arrows-join", group: "retrieval", minMode: "basic", view: "hybrid-search", title: "Hybrid Search", desc: "Graph structure fused with vector similarity." },
36
- { key: "knowledge-graph", label: "Knowledge", icon: "chart-dots-3", group: "retrieval", minMode: "basic", view: "knowledge-graph", title: "Knowledge Graph", desc: "Your digital brain — every source converges here. Explore, ingest, and export." },
37
- { key: "memory", label: "Memory", icon: "brain", group: "retrieval", minMode: "basic", view: "memory", title: "Memory", desc: "Long-term workspace, project, agent, and conversation memory." },
35
+ { key: "hybrid-search", label: "Search", icon: "arrows-join", group: "brain", minMode: "basic", view: "hybrid-search", title: "Hybrid Search", desc: "Graph structure fused with vector similarity." },
36
+ { key: "knowledge-graph", label: "Knowledge Graph", icon: "chart-dots-3", group: "brain", minMode: "basic", view: "knowledge-graph", title: "Knowledge Graph", desc: "Your digital brain — every source converges here. Explore, ingest, and export." },
37
+ { key: "memory", label: "Memory", icon: "brain", group: "brain", minMode: "basic", view: "memory", title: "Memory", desc: "Long-term workspace, project, agent, and conversation memory." },
38
38
 
39
39
  // Compute
40
- { key: "models", label: "Models", icon: "cpu", group: "compute", minMode: "basic", view: "models", title: "Models", desc: "Local MLX models and embeddings." },
41
- { key: "agents", label: "Agents", icon: "robot", group: "compute", minMode: "advanced", view: "agents", title: "Agents", desc: "Multi-agent roles, runs, and handoffs." },
42
- { key: "workflows", label: "Workflows", icon: "sitemap", group: "compute", minMode: "advanced", view: "workflows", title: "Workflow Agents", desc: "Trigger → agent chain → tools → memory → result." },
40
+ { key: "models", label: "Models", icon: "cpu", group: "library", minMode: "basic", view: "models", title: "Models", desc: "Local MLX models and embeddings." },
41
+ { key: "agents", label: "Agents", icon: "robot", group: "act", minMode: "advanced", view: "agents", title: "Agents", desc: "Multi-agent roles, runs, and handoffs." },
42
+ { key: "workflows", label: "Workflows", icon: "sitemap", group: "act", minMode: "advanced", view: "workflows", title: "Workflow Agents", desc: "Trigger → agent chain → tools → memory → result." },
43
43
 
44
44
  // Platform (the agent ecosystem)
45
- { key: "skills", label: "Skills", icon: "puzzle", group: "platform", minMode: "advanced", view: "skills", title: "Skills", desc: "Install, enable, and manage skills." },
46
- { key: "hooks", label: "Hooks", icon: "webhook", group: "platform", minMode: "advanced", view: "hooks", title: "Hooks", desc: "Lifecycle hooks across runs, tools, and workflows." },
47
- { key: "mcp", label: "MCP", icon: "plug-connected", group: "platform", minMode: "advanced", view: "mcp", title: "MCP Manager", desc: "Connected MCP servers, available tools, and health." },
45
+ { key: "skills", label: "Skills", icon: "puzzle", group: "library", minMode: "advanced", view: "skills", title: "Skills", desc: "Install, enable, and manage skills." },
46
+ { key: "hooks", label: "Hooks", icon: "webhook", group: "act", minMode: "advanced", view: "hooks", title: "Hooks", desc: "Lifecycle hooks across runs, tools, and workflows." },
47
+ { key: "mcp", label: "MCP", icon: "plug-connected", group: "library", minMode: "advanced", view: "mcp", title: "MCP Manager", desc: "Connected MCP servers, available tools, and health." },
48
48
 
49
49
  // System
50
50
  { key: "settings", label: "Settings", icon: "settings", group: "system", minMode: "basic", view: "settings", title: "Settings", desc: "Appearance, workspace, and integrations." },
51
51
 
52
52
  // Deep-linkable legacy/experimental surfaces. They remain renderable for
53
53
  // compatibility, but are not promoted in the production navigation.
54
- { key: "pipeline", label: "Pipeline", icon: "git-branch", group: "data", minMode: "advanced", view: "pipeline", title: "Pipeline", desc: "Ingest, embed, and graph-build flows.", hidden: true },
55
- { key: "planning", label: "Planning", icon: "target-arrow", group: "compute", minMode: "advanced", view: "planning", title: "Autonomous Planning", desc: "Goal → plan → execute → review → replan.", hidden: true },
56
- { key: "my-computer", label: "My Computer", icon: "device-desktop-analytics", group: "compute", minMode: "advanced", view: "my-computer", title: "My Computer", desc: "Local hardware, memory, and runtime.", hidden: true },
57
- { key: "marketplace", label: "Marketplace", icon: "building-store", group: "platform", minMode: "advanced", view: "marketplace", title: "Marketplace", desc: "Agent templates, agents, plugins, and skills.", hidden: true },
58
- { key: "tools", label: "Tools", icon: "tools", group: "platform", minMode: "advanced", view: "tools", title: "Tool Registry", desc: "Local, workspace, and MCP tools with governance.", hidden: true },
54
+ { key: "pipeline", label: "Pipeline", icon: "git-branch", group: "capture", minMode: "advanced", view: "pipeline", title: "Pipeline", desc: "Ingest, embed, and graph-build flows.", hidden: true },
55
+ { key: "planning", label: "Planning", icon: "target-arrow", group: "act", minMode: "advanced", view: "planning", title: "Autonomous Planning", desc: "Goal → plan → execute → review → replan.", hidden: true },
56
+ { key: "my-computer", label: "My Computer", icon: "device-desktop-analytics", group: "system", minMode: "advanced", view: "my-computer", title: "My Computer", desc: "Local hardware, memory, and runtime.", hidden: true },
57
+ { key: "marketplace", label: "Marketplace", icon: "building-store", group: "library", minMode: "advanced", view: "marketplace", title: "Marketplace", desc: "Agent templates, agents, plugins, and skills.", hidden: true },
58
+ { key: "tools", label: "Tools", icon: "tools", group: "act", minMode: "advanced", view: "tools", title: "Tool Registry", desc: "Local, workspace, and MCP tools with governance.", hidden: true },
59
59
 
60
60
  // Admin
61
61
  { key: "admin/users", label: "Users", icon: "users", group: "admin", minMode: "admin", view: "admin-users", title: "Users", desc: "Workspace members and access.", admin: true },
@@ -6,11 +6,11 @@
6
6
  * ========================================================================== */
7
7
 
8
8
  import { h, icon, $, $$ } from "./dom.a2773eb0.js";
9
- import { store } from "./store.34ebd5e6.js";
10
- import { api } from "./api.33d6320e.js";
9
+ import { store } from "./store.204a08b2.js";
10
+ import { api } from "./api.7a308b89.js";
11
11
  import * as c from "./components.f25b3b93.js";
12
12
  import { createRouter } from "./router.584570f2.js";
13
- import { GROUPS, ROUTES, ROUTE_BY_KEY, MODE_RANK, visibleRoutes, loadView } from "./routes.2ce3815a.js";
13
+ import { GROUPS, ROUTES, ROUTE_BY_KEY, MODE_RANK, visibleRoutes, loadView } from "./routes.7222343d.js";
14
14
 
15
15
  const MODES = [
16
16
  { key: "basic", label: "Basic", icon: "circle" },
@@ -36,7 +36,7 @@ export function boot(rootEl) {
36
36
  cacheEls(rootEl);
37
37
  store.subscribe(onStateChange);
38
38
 
39
- router = createRouter({ onRoute: renderRoute, fallback: "home" });
39
+ router = createRouter({ onRoute: renderRoute, fallback: "knowledge-graph" });
40
40
  wireGlobalKeys();
41
41
  router.start();
42
42
 
@@ -36,7 +36,7 @@ export function boot(rootEl) {
36
36
  cacheEls(rootEl);
37
37
  store.subscribe(onStateChange);
38
38
 
39
- router = createRouter({ onRoute: renderRoute, fallback: "home" });
39
+ router = createRouter({ onRoute: renderRoute, fallback: "knowledge-graph" });
40
40
  wireGlobalKeys();
41
41
  router.start();
42
42
 
@@ -30,7 +30,7 @@ const state = {
30
30
  ],
31
31
  user: { email: "", nickname: "You", role: "user" },
32
32
  indexStatus: null,
33
- route: { key: "home", params: {} },
33
+ route: { key: "knowledge-graph", params: {} },
34
34
  };
35
35
 
36
36
  const subscribers = new Set();
@@ -30,7 +30,7 @@ const state = {
30
30
  ],
31
31
  user: { email: "", nickname: "You", role: "user" },
32
32
  indexStatus: null,
33
- route: { key: "home", params: {} },
33
+ route: { key: "knowledge-graph", params: {} },
34
34
  };
35
35
 
36
36
  const subscribers = new Set();
@@ -0,0 +1,509 @@
1
+ /* ============================================================================
2
+ * Graph canvas — force-directed renderer for the Knowledge Graph explorer.
3
+ * Ports the legacy static/scripts/graph.js physics (pairwise repulsion +
4
+ * edge springs + center gravity + velocity damping) onto a dependency-free
5
+ * <canvas>. Interactions: pointer-event node drag, wheel zoom + drag pan,
6
+ * two-pointer pinch zoom, hover highlight, click-to-select callback,
7
+ * double-click to refit.
8
+ *
9
+ * Honesty + design rules:
10
+ * - Renders ONLY the nodes/edges it is given — never fabricates data.
11
+ * - Every color is resolved from design tokens via getComputedStyle at draw
12
+ * time (light/dark aware); nothing is hardcoded.
13
+ * - The RAF loop self-suspends when the simulation settles, when the
14
+ * document is hidden, and when the canvas leaves the DOM; interactions,
15
+ * resize, theme flips and re-attachment wake it.
16
+ * ========================================================================== */
17
+
18
+ const WORLD_W = 1000; // seed-layout world units (camera-independent)
19
+ const WORLD_H = 620;
20
+ const MIN_SCALE = 0.15;
21
+ const MAX_SCALE = 4;
22
+ const SETTLE_ENERGY = 0.05; // total kinetic energy below which RAF pauses
23
+ const REPULSION = 2200;
24
+ const SPRING = 0.0042;
25
+ const DAMPING = 0.85;
26
+ const REST_LENGTH = 120;
27
+ const CLICK_SLOP_PX = 5; // pointer travel under this counts as a click
28
+
29
+ /**
30
+ * createGraphCanvas({ colorFor, onSelect })
31
+ * - colorFor(type) → a token reference like "var(--lt3-pillar-graph)".
32
+ * - onSelect(id|null) — fired on canvas click (toggle) and empty-space click.
33
+ * Returns { el, setData({nodes, edges}), setSelected(id|null), destroy() }.
34
+ */
35
+ export function createGraphCanvas({ colorFor, onSelect } = {}) {
36
+ const canvas = document.createElement("canvas");
37
+ canvas.setAttribute("role", "img");
38
+ canvas.setAttribute("aria-label", "Knowledge graph");
39
+ const ctx = canvas.getContext("2d");
40
+
41
+ let nodes = [];
42
+ let edges = [];
43
+ let byId = new Map();
44
+ let cam = { scale: 1, tx: 0, ty: 0 };
45
+ let width = 0;
46
+ let height = 0;
47
+ let hovered = null;
48
+ let selectedId = null;
49
+ let dragging = null;
50
+ let panning = null;
51
+ let pinch = null;
52
+ let pressTravel = Infinity;
53
+ const pointers = new Map();
54
+ let raf = 0;
55
+ let needsFit = false;
56
+ let tokens = null;
57
+ const typeColors = new Map();
58
+ let destroyed = false;
59
+
60
+ /* ── design tokens (resolved, never hardcoded) ─────────────────────────── */
61
+ function readVar(style, name, fallback) {
62
+ const v = (style.getPropertyValue(name) || "").trim();
63
+ return v || fallback;
64
+ }
65
+
66
+ function refreshTokens() {
67
+ const style = getComputedStyle(canvas.isConnected ? canvas : document.documentElement);
68
+ const text = readVar(style, "--text", style.color);
69
+ tokens = {
70
+ text,
71
+ surface: readVar(style, "--surface", readVar(style, "--bg", text)),
72
+ edge: readVar(style, "--border-strong", readVar(style, "--border", text)),
73
+ accent: readVar(style, "--accent", text),
74
+ muted: readVar(style, "--muted", text),
75
+ font: style.fontFamily || "system-ui",
76
+ };
77
+ typeColors.clear();
78
+ }
79
+
80
+ function nodeColor(type) {
81
+ if (!typeColors.has(type)) {
82
+ const ref = colorFor ? String(colorFor(type) || "") : "";
83
+ const m = /^var\((--[\w-]+)/.exec(ref.trim());
84
+ const style = getComputedStyle(document.documentElement);
85
+ typeColors.set(type, m ? readVar(style, m[1], tokens.accent) : tokens.accent);
86
+ }
87
+ return typeColors.get(type);
88
+ }
89
+
90
+ /* ── data ──────────────────────────────────────────────────────────────── */
91
+ function setData(data) {
92
+ const src = data || {};
93
+ byId = new Map();
94
+ nodes = (src.nodes || []).map((n) => {
95
+ const node = {
96
+ id: n.id,
97
+ label: String(n.label || n.id || ""),
98
+ type: n.type || "Entity",
99
+ weight: clamp(Number(n.weight) || 0, 0, 1),
100
+ seedX: Number.isFinite(n.x) ? n.x : null,
101
+ seedY: Number.isFinite(n.y) ? n.y : null,
102
+ x: 0, y: 0, vx: 0, vy: 0, r: 10, degree: 0,
103
+ };
104
+ byId.set(node.id, node);
105
+ return node;
106
+ });
107
+ edges = (src.edges || [])
108
+ .filter((e) => byId.has(e.from) && byId.has(e.to))
109
+ .map((e) => ({
110
+ from: e.from,
111
+ to: e.to,
112
+ weight: Number(e.weight) || 1,
113
+ source: byId.get(e.from),
114
+ target: byId.get(e.to),
115
+ }));
116
+ edges.forEach((e) => { e.source.degree++; e.target.degree++; });
117
+ nodes.forEach((n) => {
118
+ n.r = clamp(8 + n.weight * 10 + Math.sqrt(n.degree) * 1.6, 8, 28);
119
+ });
120
+ if (selectedId && !byId.has(selectedId)) selectedId = null;
121
+ hovered = null;
122
+ dragging = null;
123
+ seedLayout();
124
+ needsFit = true;
125
+ canvas.dataset.nodeCount = String(nodes.length);
126
+ canvas.setAttribute("aria-label",
127
+ `Knowledge graph: ${nodes.length} entities, ${edges.length} relations. Use the inspector list for keyboard access.`);
128
+ wake();
129
+ }
130
+
131
+ function seedLayout() {
132
+ if (!nodes.length) return;
133
+ const hasCoords = nodes.every((n) => n.seedX !== null && n.seedY !== null);
134
+ if (hasCoords) {
135
+ // Backend-provided normalized [0..1] coordinates seed the simulation.
136
+ nodes.forEach((n) => {
137
+ n.x = 60 + n.seedX * (WORLD_W - 120);
138
+ n.y = 50 + n.seedY * (WORLD_H - 100);
139
+ });
140
+ return;
141
+ }
142
+ // Golden-angle spiral by weight rank: heavy nodes near the center.
143
+ const golden = Math.PI * (3 - Math.sqrt(5));
144
+ const maxR = Math.min(WORLD_W, WORLD_H) * 0.42;
145
+ const order = [...nodes].sort((a, b) => b.weight - a.weight);
146
+ order.forEach((n, rank) => {
147
+ const radius = rank === 0 ? 0 : maxR * Math.sqrt(rank / Math.max(1, nodes.length - 1));
148
+ const angle = rank * golden;
149
+ n.x = WORLD_W / 2 + Math.cos(angle) * radius;
150
+ n.y = WORLD_H / 2 + Math.sin(angle) * radius * 0.72;
151
+ });
152
+ }
153
+
154
+ /* ── physics (ported from legacy graph.js step()) ──────────────────────── */
155
+ function step() {
156
+ const centerPull = selectedId ? 0.00035 : 0.00055;
157
+ for (let i = 0; i < nodes.length; i++) {
158
+ for (let j = i + 1; j < nodes.length; j++) {
159
+ const a = nodes[i];
160
+ const b = nodes[j];
161
+ const dx = a.x - b.x;
162
+ const dy = a.y - b.y;
163
+ const d2 = Math.max(120, dx * dx + dy * dy);
164
+ const force = REPULSION / d2;
165
+ a.vx += dx * force; a.vy += dy * force;
166
+ b.vx -= dx * force; b.vy -= dy * force;
167
+ }
168
+ }
169
+ edges.forEach((e) => {
170
+ const dx = e.target.x - e.source.x;
171
+ const dy = e.target.y - e.source.y;
172
+ const dist = Math.max(1, Math.hypot(dx, dy));
173
+ const force = (dist - REST_LENGTH) * (SPRING + Math.min(0.003, e.weight * 0.0012));
174
+ e.source.vx += (dx / dist) * force;
175
+ e.source.vy += (dy / dist) * force;
176
+ e.target.vx -= (dx / dist) * force;
177
+ e.target.vy -= (dy / dist) * force;
178
+ });
179
+ let energy = 0;
180
+ nodes.forEach((n) => {
181
+ if (n === dragging) return;
182
+ n.vx += (WORLD_W / 2 - n.x) * centerPull;
183
+ n.vy += (WORLD_H / 2 - n.y) * centerPull;
184
+ n.vx *= DAMPING;
185
+ n.vy *= DAMPING;
186
+ n.x += n.vx;
187
+ n.y += n.vy;
188
+ energy += n.vx * n.vx + n.vy * n.vy;
189
+ });
190
+ return energy;
191
+ }
192
+
193
+ /* ── camera ────────────────────────────────────────────────────────────── */
194
+ function toWorld(px, py) {
195
+ return { x: (px - cam.tx) / cam.scale, y: (py - cam.ty) / cam.scale };
196
+ }
197
+
198
+ function applyZoom(px, py, factor) {
199
+ const next = clamp(cam.scale * factor, MIN_SCALE, MAX_SCALE);
200
+ cam.tx = px - (px - cam.tx) * (next / cam.scale);
201
+ cam.ty = py - (py - cam.ty) * (next / cam.scale);
202
+ cam.scale = next;
203
+ }
204
+
205
+ function fitToScreen() {
206
+ if (!nodes.length || !width || !height) return;
207
+ let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
208
+ nodes.forEach((n) => {
209
+ x0 = Math.min(x0, n.x - n.r); x1 = Math.max(x1, n.x + n.r);
210
+ y0 = Math.min(y0, n.y - n.r); y1 = Math.max(y1, n.y + n.r);
211
+ });
212
+ const margin = 48;
213
+ cam.scale = clamp(Math.min(
214
+ (width - margin * 2) / Math.max(1, x1 - x0),
215
+ (height - margin * 2) / Math.max(1, y1 - y0),
216
+ ), MIN_SCALE, 2.5);
217
+ cam.tx = (width - (x0 + x1) * cam.scale) / 2;
218
+ cam.ty = (height - (y0 + y1) * cam.scale) / 2;
219
+ }
220
+
221
+ function centerOnNode(node) {
222
+ cam.tx = width / 2 - node.x * cam.scale;
223
+ cam.ty = height / 2 - node.y * cam.scale;
224
+ }
225
+
226
+ function nodeOnScreen(node) {
227
+ const sx = node.x * cam.scale + cam.tx;
228
+ const sy = node.y * cam.scale + cam.ty;
229
+ return sx >= 0 && sx <= width && sy >= 0 && sy <= height;
230
+ }
231
+
232
+ function nodeAt(px, py) {
233
+ const w = toWorld(px, py);
234
+ let best = null;
235
+ let bestDist = Infinity;
236
+ nodes.forEach((n) => {
237
+ const dist = Math.hypot(n.x - w.x, n.y - w.y);
238
+ if (dist < n.r + 8 / cam.scale && dist < bestDist) { best = n; bestDist = dist; }
239
+ });
240
+ return best;
241
+ }
242
+
243
+ /* ── render loop (self-suspending) ─────────────────────────────────────── */
244
+ function wake() {
245
+ if (destroyed || raf || document.hidden || !canvas.isConnected) return;
246
+ raf = requestAnimationFrame(draw);
247
+ }
248
+
249
+ function neighborSetOf(node) {
250
+ const ids = new Set([node.id]);
251
+ edges.forEach((e) => {
252
+ if (e.from === node.id) ids.add(e.to);
253
+ if (e.to === node.id) ids.add(e.from);
254
+ });
255
+ return ids;
256
+ }
257
+
258
+ function draw() {
259
+ raf = 0;
260
+ if (destroyed || document.hidden || !canvas.isConnected) return;
261
+ if (!tokens) refreshTokens();
262
+ const energy = step();
263
+ if (needsFit) { fitToScreen(); needsFit = false; }
264
+
265
+ ctx.clearRect(0, 0, width, height);
266
+ ctx.save();
267
+ ctx.translate(cam.tx, cam.ty);
268
+ ctx.scale(cam.scale, cam.scale);
269
+
270
+ const selected = selectedId ? byId.get(selectedId) : null;
271
+ const active = hovered || selected;
272
+ const neighbors = active ? neighborSetOf(active) : null;
273
+ // LOD: drop labels when zoomed far out or the mesh is dense.
274
+ const showLabels = cam.scale >= 0.55 && nodes.length <= 200;
275
+
276
+ edges.forEach((e) => {
277
+ const lit = neighbors && neighbors.has(e.from) && neighbors.has(e.to);
278
+ ctx.globalAlpha = neighbors ? (lit ? 0.85 : 0.07) : 0.35;
279
+ ctx.strokeStyle = tokens.edge;
280
+ ctx.lineWidth = (1 + Math.min(2.4, e.weight * 0.6) + (lit ? 0.5 : 0)) / cam.scale;
281
+ ctx.beginPath();
282
+ ctx.moveTo(e.source.x, e.source.y);
283
+ ctx.lineTo(e.target.x, e.target.y);
284
+ ctx.stroke();
285
+ });
286
+
287
+ nodes.forEach((n) => {
288
+ const isSelected = n === selected;
289
+ const isHovered = n === hovered;
290
+ const alpha = neighbors ? (neighbors.has(n.id) ? 1 : 0.14) : 1;
291
+ const radius = n.r + (isSelected ? 3 : isHovered ? 2 : 0);
292
+
293
+ ctx.globalAlpha = alpha;
294
+ ctx.fillStyle = nodeColor(n.type);
295
+ ctx.beginPath();
296
+ ctx.arc(n.x, n.y, radius, 0, Math.PI * 2);
297
+ ctx.fill();
298
+ ctx.strokeStyle = tokens.surface;
299
+ ctx.lineWidth = 2 / cam.scale;
300
+ ctx.stroke();
301
+
302
+ if (isSelected || isHovered) {
303
+ ctx.strokeStyle = isSelected ? tokens.accent : nodeColor(n.type);
304
+ ctx.lineWidth = (isSelected ? 2.6 : 1.8) / cam.scale;
305
+ ctx.globalAlpha = alpha * 0.6;
306
+ ctx.beginPath();
307
+ ctx.arc(n.x, n.y, radius + 5 / cam.scale, 0, Math.PI * 2);
308
+ ctx.stroke();
309
+ ctx.globalAlpha = alpha;
310
+ }
311
+
312
+ if (showLabels || isSelected || isHovered) {
313
+ const label = n.label.length > 22 ? n.label.slice(0, 21) + "…" : n.label;
314
+ const fs = Math.max(9.5, 12 / cam.scale);
315
+ ctx.font = `600 ${fs}px ${tokens.font}`;
316
+ const lw = ctx.measureText(label).width;
317
+ const lx = n.x - lw / 2;
318
+ const ly = n.y + radius + (8 / cam.scale) + fs;
319
+ const pad = 4 / cam.scale;
320
+ ctx.globalAlpha = alpha > 0.5 ? alpha * 0.85 : alpha * 0.25;
321
+ ctx.fillStyle = tokens.surface;
322
+ ctx.beginPath();
323
+ if (ctx.roundRect) ctx.roundRect(lx - pad, ly - fs, lw + pad * 2, fs + pad * 1.6, 5 / cam.scale);
324
+ else ctx.rect(lx - pad, ly - fs, lw + pad * 2, fs + pad * 1.6);
325
+ ctx.fill();
326
+ ctx.globalAlpha = alpha;
327
+ ctx.fillStyle = tokens.text;
328
+ ctx.fillText(label, lx, ly);
329
+ }
330
+ });
331
+
332
+ ctx.globalAlpha = 1;
333
+ ctx.restore();
334
+ if (energy > SETTLE_ENERGY || dragging) raf = requestAnimationFrame(draw);
335
+ }
336
+
337
+ /* ── interactions (pointer events: mouse + touch + pen) ────────────────── */
338
+ function localPoint(e) {
339
+ const rect = canvas.getBoundingClientRect();
340
+ return { x: e.clientX - rect.left, y: e.clientY - rect.top };
341
+ }
342
+
343
+ function pinchState() {
344
+ const [a, b] = [...pointers.values()];
345
+ return { d: Math.hypot(a.x - b.x, a.y - b.y), cx: (a.x + b.x) / 2, cy: (a.y + b.y) / 2 };
346
+ }
347
+
348
+ function onPointerDown(e) {
349
+ canvas.setPointerCapture(e.pointerId);
350
+ pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
351
+ if (pointers.size === 2) {
352
+ dragging = null;
353
+ panning = null;
354
+ pinch = pinchState();
355
+ return;
356
+ }
357
+ pressTravel = 0;
358
+ const p = localPoint(e);
359
+ const node = nodeAt(p.x, p.y);
360
+ if (node) {
361
+ dragging = node;
362
+ } else {
363
+ panning = { sx: e.clientX, sy: e.clientY, tx0: cam.tx, ty0: cam.ty };
364
+ canvas.style.cursor = "grabbing";
365
+ }
366
+ wake();
367
+ }
368
+
369
+ function onPointerMove(e) {
370
+ const prev = pointers.get(e.pointerId);
371
+ if (prev) {
372
+ pressTravel += Math.hypot(e.clientX - prev.x, e.clientY - prev.y);
373
+ pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
374
+ }
375
+ if (pinch && pointers.size === 2) {
376
+ const next = pinchState();
377
+ const rect = canvas.getBoundingClientRect();
378
+ applyZoom(next.cx - rect.left, next.cy - rect.top, next.d / Math.max(1, pinch.d));
379
+ pinch = next;
380
+ wake();
381
+ return;
382
+ }
383
+ if (dragging) {
384
+ const p = localPoint(e);
385
+ const w = toWorld(p.x, p.y);
386
+ dragging.x = w.x; dragging.y = w.y;
387
+ dragging.vx = 0; dragging.vy = 0;
388
+ wake();
389
+ } else if (panning) {
390
+ cam.tx = panning.tx0 + (e.clientX - panning.sx);
391
+ cam.ty = panning.ty0 + (e.clientY - panning.sy);
392
+ wake();
393
+ } else {
394
+ const p = localPoint(e);
395
+ const node = nodeAt(p.x, p.y);
396
+ if (node !== hovered) { hovered = node; wake(); }
397
+ canvas.style.cursor = node ? "pointer" : "grab";
398
+ }
399
+ }
400
+
401
+ function onPointerUp(e) {
402
+ pointers.delete(e.pointerId);
403
+ if (pointers.size < 2) pinch = null;
404
+ dragging = null;
405
+ panning = null;
406
+ canvas.style.cursor = "grab";
407
+ if (pressTravel < CLICK_SLOP_PX) {
408
+ const p = localPoint(e);
409
+ const node = nodeAt(p.x, p.y);
410
+ const next = node && node.id !== selectedId ? node.id : null;
411
+ selectedId = next;
412
+ if (onSelect) onSelect(next);
413
+ }
414
+ pressTravel = Infinity;
415
+ wake();
416
+ }
417
+
418
+ function onPointerCancel(e) {
419
+ pointers.delete(e.pointerId);
420
+ pinch = null;
421
+ dragging = null;
422
+ panning = null;
423
+ pressTravel = Infinity;
424
+ }
425
+
426
+ function onPointerLeave() {
427
+ if (hovered) { hovered = null; wake(); }
428
+ }
429
+
430
+ function onWheel(e) {
431
+ e.preventDefault();
432
+ const p = localPoint(e);
433
+ applyZoom(p.x, p.y, e.deltaY < 0 ? 1.12 : 1 / 1.12);
434
+ wake();
435
+ }
436
+
437
+ function onDblClick() {
438
+ fitToScreen();
439
+ wake();
440
+ }
441
+
442
+ function onVisibility() {
443
+ if (!document.hidden) wake();
444
+ }
445
+
446
+ /* ── environment: resize (DPR-aware) + theme flips ─────────────────────── */
447
+ function resize() {
448
+ const rect = canvas.getBoundingClientRect();
449
+ if (!rect.width || !rect.height) return;
450
+ width = rect.width;
451
+ height = rect.height;
452
+ const dpr = window.devicePixelRatio || 1;
453
+ canvas.width = Math.floor(width * dpr);
454
+ canvas.height = Math.floor(height * dpr);
455
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
456
+ wake();
457
+ }
458
+
459
+ const resizeObserver = new ResizeObserver(resize);
460
+ resizeObserver.observe(canvas);
461
+
462
+ const themeObserver = new MutationObserver(() => { refreshTokens(); wake(); });
463
+ themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["data-lt-theme"] });
464
+ const colorScheme = window.matchMedia("(prefers-color-scheme: dark)");
465
+ const onScheme = () => { refreshTokens(); wake(); };
466
+ colorScheme.addEventListener("change", onScheme);
467
+
468
+ canvas.addEventListener("pointerdown", onPointerDown);
469
+ canvas.addEventListener("pointermove", onPointerMove);
470
+ canvas.addEventListener("pointerup", onPointerUp);
471
+ canvas.addEventListener("pointercancel", onPointerCancel);
472
+ canvas.addEventListener("pointerleave", onPointerLeave);
473
+ canvas.addEventListener("wheel", onWheel, { passive: false });
474
+ canvas.addEventListener("dblclick", onDblClick);
475
+ document.addEventListener("visibilitychange", onVisibility);
476
+
477
+ function setSelected(id) {
478
+ selectedId = id || null;
479
+ const node = selectedId ? byId.get(selectedId) : null;
480
+ if (node && width && !nodeOnScreen(node)) centerOnNode(node);
481
+ wake();
482
+ }
483
+
484
+ function destroy() {
485
+ destroyed = true;
486
+ if (raf) { cancelAnimationFrame(raf); raf = 0; }
487
+ resizeObserver.disconnect();
488
+ themeObserver.disconnect();
489
+ colorScheme.removeEventListener("change", onScheme);
490
+ document.removeEventListener("visibilitychange", onVisibility);
491
+ canvas.removeEventListener("pointerdown", onPointerDown);
492
+ canvas.removeEventListener("pointermove", onPointerMove);
493
+ canvas.removeEventListener("pointerup", onPointerUp);
494
+ canvas.removeEventListener("pointercancel", onPointerCancel);
495
+ canvas.removeEventListener("pointerleave", onPointerLeave);
496
+ canvas.removeEventListener("wheel", onWheel);
497
+ canvas.removeEventListener("dblclick", onDblClick);
498
+ pointers.clear();
499
+ nodes = [];
500
+ edges = [];
501
+ byId = new Map();
502
+ }
503
+
504
+ return { el: canvas, setData, setSelected, destroy };
505
+ }
506
+
507
+ function clamp(v, min, max) {
508
+ return Math.max(min, Math.min(max, v));
509
+ }