ster 1.1.0__py3-none-win_arm64.whl

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 (506) hide show
  1. agent_app/__init__.py +5 -0
  2. agent_app/__main__.py +9 -0
  3. agent_app/choice.py +47 -0
  4. agent_app/cli.py +83 -0
  5. agent_app/departure.py +22 -0
  6. agent_app/graph_switch.py +64 -0
  7. agent_app/history.py +203 -0
  8. agent_app/launcher.py +161 -0
  9. agent_app/native.py +474 -0
  10. agent_app/oneshot.py +206 -0
  11. agent_app/recipes/README.md +107 -0
  12. agent_app/recipes/claude-code.json +26 -0
  13. agent_app/recipes/copilot.json +23 -0
  14. agent_app/recipes/examples/codex.json +23 -0
  15. agent_app/recipes/ollama.json +7 -0
  16. agent_app/recipes/opencode.json +18 -0
  17. agent_app/reported.py +27 -0
  18. agent_app/rules.py +198 -0
  19. agent_app/runner.py +508 -0
  20. agent_app/server.py +1082 -0
  21. agent_app/static/i18n.js +41 -0
  22. agent_app/static/index.html +1044 -0
  23. agent_app/static/locales/en.json +243 -0
  24. agent_app/static/locales/fr.json +243 -0
  25. agent_app/static/render.js +119 -0
  26. agent_app/static/viz.js +141 -0
  27. agent_app/trace_steps.py +81 -0
  28. ster/__init__.py +1 -0
  29. ster/__main__.py +6 -0
  30. ster/_bin/turtle-lsp.exe +0 -0
  31. ster/_version.py +75 -0
  32. ster/agent_view.py +147 -0
  33. ster/analysis_base.py +67 -0
  34. ster/analysis_cache.py +173 -0
  35. ster/annotation_properties.py +92 -0
  36. ster/api.py +1255 -0
  37. ster/api_server.py +469 -0
  38. ster/ask.py +49 -0
  39. ster/assets/graph_app.js +2218 -0
  40. ster/assets/reload_notice.js +53 -0
  41. ster/assets/taxonomy_app.js +698 -0
  42. ster/branding.py +18 -0
  43. ster/browser.py +23 -0
  44. ster/builtin_uri.py +18 -0
  45. ster/cli/__init__.py +324 -0
  46. ster/cli/__main__.py +8 -0
  47. ster/cli/_agent.py +30 -0
  48. ster/cli/_app.py +236 -0
  49. ster/cli/_cache_cmd.py +19 -0
  50. ster/cli/_commands_edit.py +496 -0
  51. ster/cli/_constants.py +38 -0
  52. ster/cli/_discovery.py +30 -0
  53. ster/cli/_editor.py +49 -0
  54. ster/cli/_endpoint.py +288 -0
  55. ster/cli/_endpoint_plan.py +250 -0
  56. ster/cli/_examples.py +101 -0
  57. ster/cli/_exit.py +30 -0
  58. ster/cli/_export.py +108 -0
  59. ster/cli/_file_picker.py +458 -0
  60. ster/cli/_folder_arg.py +21 -0
  61. ster/cli/_history.py +47 -0
  62. ster/cli/_home.py +317 -0
  63. ster/cli/_inspect_cmd.py +27 -0
  64. ster/cli/_lint_cmd.py +56 -0
  65. ster/cli/_lint_gate.py +41 -0
  66. ster/cli/_login.py +59 -0
  67. ster/cli/_mcp_option.py +24 -0
  68. ster/cli/_options.py +104 -0
  69. ster/cli/_publish.py +215 -0
  70. ster/cli/_query_launcher.py +82 -0
  71. ster/cli/_rdfxml.py +61 -0
  72. ster/cli/_serve.py +237 -0
  73. ster/cli/_state.py +10 -0
  74. ster/cli/_taxonomy_io.py +112 -0
  75. ster/cli/_tty_input.py +71 -0
  76. ster/cli/_viewer.py +192 -0
  77. ster/cli/_viz_cmd.py +29 -0
  78. ster/cli/_workspace_ui.py +520 -0
  79. ster/clipboard.py +85 -0
  80. ster/compose.py +126 -0
  81. ster/compose_query.py +188 -0
  82. ster/compose_tools.py +38 -0
  83. ster/core/__init__.py +9 -0
  84. ster/core/commands/__init__.py +153 -0
  85. ster/core/commands/base.py +89 -0
  86. ster/core/commands/cross.py +172 -0
  87. ster/core/commands/onto.py +99 -0
  88. ster/core/commands/owl.py +678 -0
  89. ster/core/commands/skos.py +274 -0
  90. ster/core/history.py +102 -0
  91. ster/core/iri_check.py +102 -0
  92. ster/core/locked_references.py +71 -0
  93. ster/core/ports.py +282 -0
  94. ster/core/quality_coverage.py +123 -0
  95. ster/core/service.py +232 -0
  96. ster/core/validation.py +61 -0
  97. ster/dependencies.py +129 -0
  98. ster/desktop/__init__.py +7 -0
  99. ster/desktop/assets/shell.html +85 -0
  100. ster/desktop/launcher.py +77 -0
  101. ster/desktop/serve.py +81 -0
  102. ster/desktop/shell.py +128 -0
  103. ster/desktop/smoke.py +80 -0
  104. ster/desktop/tabs.py +86 -0
  105. ster/desktop/tui_process.py +106 -0
  106. ster/desktop/tui_server.py +47 -0
  107. ster/desktop/window.py +17 -0
  108. ster/desktop_app.py +71 -0
  109. ster/diagnosis.py +105 -0
  110. ster/display.py +189 -0
  111. ster/domain/__init__.py +12 -0
  112. ster/domain/_shared.py +9 -0
  113. ster/domain/cross.py +350 -0
  114. ster/domain/onto.py +319 -0
  115. ster/domain/owl.py +757 -0
  116. ster/domain/skos.py +597 -0
  117. ster/edit_target.py +129 -0
  118. ster/editor_extension.py +128 -0
  119. ster/editor_launch.py +147 -0
  120. ster/endpoint_advice.py +83 -0
  121. ster/endpoint_cache.py +151 -0
  122. ster/endpoint_credentials.py +60 -0
  123. ster/endpoint_history.py +19 -0
  124. ster/endpoint_probe.py +267 -0
  125. ster/endpoint_sessions.py +56 -0
  126. ster/entity_source.py +240 -0
  127. ster/entity_view.py +45 -0
  128. ster/exceptions.py +65 -0
  129. ster/file_stamps.py +58 -0
  130. ster/generated_prefixes.py +64 -0
  131. ster/git/__init__.py +8 -0
  132. ster/git/activity.py +15 -0
  133. ster/git/manager/__init__.py +88 -0
  134. ster/git/manager/_activity.py +27 -0
  135. ster/git/manager/_commit.py +151 -0
  136. ster/git/manager/_commit_check.py +28 -0
  137. ster/git/manager/_config.py +49 -0
  138. ster/git/manager/_config_store.py +35 -0
  139. ster/git/manager/_console.py +14 -0
  140. ster/git/manager/_diff.py +21 -0
  141. ster/git/manager/_push.py +189 -0
  142. ster/git/manager/_release.py +63 -0
  143. ster/git/manager/_setup.py +403 -0
  144. ster/git/manager/_staging.py +33 -0
  145. ster/git/manager/_state.py +49 -0
  146. ster/git/manager/_subprocess.py +51 -0
  147. ster/git/manager/_sync.py +124 -0
  148. ster/graph_api/__init__.py +4 -0
  149. ster/graph_api/entities.py +101 -0
  150. ster/graph_api/errors.py +20 -0
  151. ster/graph_api/models.py +62 -0
  152. ster/graph_api/naming.py +53 -0
  153. ster/graph_api/places.py +27 -0
  154. ster/graph_api/service.py +109 -0
  155. ster/graph_http/__init__.py +5 -0
  156. ster/graph_http/page_host.py +115 -0
  157. ster/graph_layout.py +141 -0
  158. ster/graph_origin.py +86 -0
  159. ster/graph_overview.py +190 -0
  160. ster/graph_source.py +80 -0
  161. ster/handles.py +82 -0
  162. ster/help.py +129 -0
  163. ster/host_link.py +58 -0
  164. ster/init_ci.py +76 -0
  165. ster/knowledge.py +169 -0
  166. ster/link_opener.py +55 -0
  167. ster/lint_lines.py +11 -0
  168. ster/live_breaker.py +244 -0
  169. ster/live_engine_errors.py +51 -0
  170. ster/live_entity.py +147 -0
  171. ster/live_facts.py +83 -0
  172. ster/live_guard.py +71 -0
  173. ster/live_overview.py +77 -0
  174. ster/live_schema.py +146 -0
  175. ster/live_search.py +177 -0
  176. ster/live_source.py +141 -0
  177. ster/live_vocabulary.py +304 -0
  178. ster/live_watch.py +120 -0
  179. ster/lsp_setup.py +307 -0
  180. ster/mcp_context.py +828 -0
  181. ster/mcp_server.py +852 -0
  182. ster/mcp_tools.py +272 -0
  183. ster/mcp_views.py +168 -0
  184. ster/mcp_viz.py +79 -0
  185. ster/metadata_coverage.py +127 -0
  186. ster/model.py +586 -0
  187. ster/nav/__init__.py +44 -0
  188. ster/nav/actions.py +203 -0
  189. ster/nav/logic/__init__.py +436 -0
  190. ster/nav/logic/_concept.py +647 -0
  191. ster/nav/logic/_fields.py +664 -0
  192. ster/nav/logic/_global_.py +475 -0
  193. ster/nav/logic/_individual.py +284 -0
  194. ster/nav/logic/_mixed_tree.py +488 -0
  195. ster/nav/logic/_overview.py +795 -0
  196. ster/nav/logic/_property_.py +254 -0
  197. ster/nav/logic/_rdf_class.py +715 -0
  198. ster/nav/logic/_tree.py +547 -0
  199. ster/nav/prefs.py +186 -0
  200. ster/nav/shortcuts_doc.py +70 -0
  201. ster/operations.py +97 -0
  202. ster/owl_analysis.py +526 -0
  203. ster/paths.py +31 -0
  204. ster/plugins/__init__.py +33 -0
  205. ster/plugins/dependency.py +26 -0
  206. ster/plugins/lint/__init__.py +6 -0
  207. ster/plugins/lint/config.py +132 -0
  208. ster/plugins/lint/fixes.py +275 -0
  209. ster/plugins/lint/lint_cache.py +139 -0
  210. ster/plugins/lint/project_shapes.py +91 -0
  211. ster/plugins/lint/report.py +47 -0
  212. ster/plugins/lint/shapes_author.py +150 -0
  213. ster/plugins/query_trace/__init__.py +28 -0
  214. ster/plugins/query_trace/sessions.py +88 -0
  215. ster/plugins/registry.py +69 -0
  216. ster/plugins/semanticdiff/__init__.py +17 -0
  217. ster/plugins/semanticdiff/deps.py +26 -0
  218. ster/plugins/semanticdiff/history.py +183 -0
  219. ster/plugins/state.py +66 -0
  220. ster/plugins/talk_to_graph/__init__.py +136 -0
  221. ster/plugins/talk_to_graph/service.py +33 -0
  222. ster/plugins/turtle_lsp/__init__.py +11 -0
  223. ster/plugins/turtle_lsp/binary.py +40 -0
  224. ster/plugins/turtle_lsp/commit_check.py +84 -0
  225. ster/plugins/turtle_lsp/gate.py +29 -0
  226. ster/plugins/turtle_lsp/report.py +73 -0
  227. ster/plugins/turtle_lsp/runner.py +60 -0
  228. ster/plugins/turtle_lsp/service.py +106 -0
  229. ster/project.py +233 -0
  230. ster/provenance.py +107 -0
  231. ster/query_fault.py +55 -0
  232. ster/query_shaping.py +297 -0
  233. ster/query_trace/__init__.py +32 -0
  234. ster/query_trace/agent.py +74 -0
  235. ster/query_trace/answers.py +116 -0
  236. ster/query_trace/cli.py +57 -0
  237. ster/query_trace/jsonl.py +125 -0
  238. ster/query_trace/layout.py +77 -0
  239. ster/query_trace/materialize.py +186 -0
  240. ster/query_trace/model.py +71 -0
  241. ster/query_trace/recorder.py +81 -0
  242. ster/query_trace/retention.py +102 -0
  243. ster/query_trace/subgraph.py +35 -0
  244. ster/query_trace/validation.py +48 -0
  245. ster/rdf_files.py +67 -0
  246. ster/reload_notice.py +37 -0
  247. ster/result_profile.py +196 -0
  248. ster/schema_check.py +111 -0
  249. ster/search_result.py +33 -0
  250. ster/serve_target.py +130 -0
  251. ster/server_app.py +42 -0
  252. ster/server_settings.py +161 -0
  253. ster/session.py +69 -0
  254. ster/session_files.py +235 -0
  255. ster/single_flight.py +31 -0
  256. ster/source_lines.py +115 -0
  257. ster/sources.py +20 -0
  258. ster/sparql_endpoint.py +839 -0
  259. ster/sparql_presets.py +294 -0
  260. ster/sparql_query/__init__.py +141 -0
  261. ster/sparql_query/_autocomplete.py +239 -0
  262. ster/sparql_query/_caching.py +171 -0
  263. ster/sparql_query/_execute.py +253 -0
  264. ster/sparql_query/_sandbox.py +202 -0
  265. ster/sparql_query/_uri_index.py +397 -0
  266. ster/sparql_run.py +160 -0
  267. ster/sparql_runner.py +16 -0
  268. ster/sparql_types.py +33 -0
  269. ster/store/__init__.py +250 -0
  270. ster/store/_cache.py +282 -0
  271. ster/store/_comments.py +290 -0
  272. ster/store/_constants.py +54 -0
  273. ster/store/_convert.py +23 -0
  274. ster/store/_format.py +113 -0
  275. ster/store/_from_graph.py +456 -0
  276. ster/store/_graph_io.py +291 -0
  277. ster/store/_load_save.py +723 -0
  278. ster/store/_normalize.py +72 -0
  279. ster/store/_snapshot.py +87 -0
  280. ster/store/_to_graph.py +372 -0
  281. ster/store/graphs.py +21 -0
  282. ster/store/repository.py +68 -0
  283. ster/taxonomy.ttl +29 -0
  284. ster/taxonomy_analysis.py +672 -0
  285. ster/taxonomy_treemap.py +170 -0
  286. ster/templates/onto-ci.yml +30 -0
  287. ster/templates/taxonomy-ci.yml +68 -0
  288. ster/test-ontology.txt +90 -0
  289. ster/tui/__init__.py +11 -0
  290. ster/tui/__main__.py +18 -0
  291. ster/tui/_launch.py +89 -0
  292. ster/tui/_run.py +141 -0
  293. ster/tui/agent.py +76 -0
  294. ster/tui/annotation_library.py +316 -0
  295. ster/tui/annotation_library_modal.py +111 -0
  296. ster/tui/app/__init__.py +347 -0
  297. ster/tui/app/_actions.py +284 -0
  298. ster/tui/app/_busy_save.py +168 -0
  299. ster/tui/app/_config.py +306 -0
  300. ster/tui/app/_constants.py +69 -0
  301. ster/tui/app/_context_menu.py +216 -0
  302. ster/tui/app/_copy_on_select.py +116 -0
  303. ster/tui/app/_detail.py +143 -0
  304. ster/tui/app/_editing_modals.py +514 -0
  305. ster/tui/app/_entity_search.py +28 -0
  306. ster/tui/app/_file_watch.py +120 -0
  307. ster/tui/app/_graph.py +115 -0
  308. ster/tui/app/_helpers.py +134 -0
  309. ster/tui/app/_lifecycle.py +726 -0
  310. ster/tui/app/_lint.py +153 -0
  311. ster/tui/app/_loading_quips.py +104 -0
  312. ster/tui/app/_lsp_setup.py +35 -0
  313. ster/tui/app/_menu_bar.py +61 -0
  314. ster/tui/app/_ontology_identity.py +192 -0
  315. ster/tui/app/_open_editor.py +155 -0
  316. ster/tui/app/_open_endpoint.py +111 -0
  317. ster/tui/app/_open_files.py +104 -0
  318. ster/tui/app/_panels.py +162 -0
  319. ster/tui/app/_placement.py +64 -0
  320. ster/tui/app/_problems.py +178 -0
  321. ster/tui/app/_project_tools.py +67 -0
  322. ster/tui/app/_rebuild.py +75 -0
  323. ster/tui/app/_row_actions.py +261 -0
  324. ster/tui/app/_shacl.py +106 -0
  325. ster/tui/app/_source.py +149 -0
  326. ster/tui/app/_state.py +426 -0
  327. ster/tui/app/_tree_build.py +362 -0
  328. ster/tui/app/_tree_events.py +92 -0
  329. ster/tui/app/_tree_widget.py +249 -0
  330. ster/tui/app/_turtle.py +32 -0
  331. ster/tui/app/_working_file.py +184 -0
  332. ster/tui/check.py +25 -0
  333. ster/tui/choice_modal.py +57 -0
  334. ster/tui/class_modal.py +41 -0
  335. ster/tui/config_modal/__init__.py +270 -0
  336. ster/tui/config_modal/_agent_choice.py +36 -0
  337. ster/tui/config_modal/_general_mixin.py +108 -0
  338. ster/tui/config_modal/_general_widgets.py +60 -0
  339. ster/tui/config_modal/_graphviz_mixin.py +97 -0
  340. ster/tui/config_modal/_labels.py +22 -0
  341. ster/tui/config_modal/_lint_mixin.py +186 -0
  342. ster/tui/config_modal/_messages.py +38 -0
  343. ster/tui/config_modal/_metadata_catalog.py +318 -0
  344. ster/tui/config_modal/_metadata_widgets.py +77 -0
  345. ster/tui/config_modal/_navigation_mixin.py +81 -0
  346. ster/tui/config_modal/_percent.py +25 -0
  347. ster/tui/config_modal/_plugins_mixin.py +82 -0
  348. ster/tui/config_modal/_props_mixin.py +57 -0
  349. ster/tui/config_modal/_state.py +80 -0
  350. ster/tui/config_modal/_state_mixin.py +50 -0
  351. ster/tui/context_menu.py +97 -0
  352. ster/tui/data.py +430 -0
  353. ster/tui/demo.ttl +21 -0
  354. ster/tui/detail.py +307 -0
  355. ster/tui/detail_view.py +495 -0
  356. ster/tui/edit_modal.py +154 -0
  357. ster/tui/edits.py +614 -0
  358. ster/tui/endpoint_modal.py +84 -0
  359. ster/tui/endpoints.py +49 -0
  360. ster/tui/entity_form.py +139 -0
  361. ster/tui/file_activity.py +33 -0
  362. ster/tui/focus_group.py +150 -0
  363. ster/tui/graphs.py +38 -0
  364. ster/tui/help_screen.py +92 -0
  365. ster/tui/hint_bar.py +76 -0
  366. ster/tui/individual_modal.py +184 -0
  367. ster/tui/instructions_modal.py +38 -0
  368. ster/tui/launcher.py +36 -0
  369. ster/tui/lint.py +191 -0
  370. ster/tui/lint_modal.py +142 -0
  371. ster/tui/local_property_modal.py +41 -0
  372. ster/tui/menu_bar.py +147 -0
  373. ster/tui/mixed-gear-demo.ttl +443 -0
  374. ster/tui/modal.py +158 -0
  375. ster/tui/multi_picker_modal.py +89 -0
  376. ster/tui/object_property_modal.py +63 -0
  377. ster/tui/ontology_identity_modal.py +111 -0
  378. ster/tui/open_choice.py +52 -0
  379. ster/tui/open_files_modal.py +391 -0
  380. ster/tui/overview_fields.py +26 -0
  381. ster/tui/picker_modal.py +147 -0
  382. ster/tui/plugin_screens.py +84 -0
  383. ster/tui/plugins/__init__.py +3 -0
  384. ster/tui/plugins/lint_ui/__init__.py +27 -0
  385. ster/tui/plugins/lint_ui/hooks.py +69 -0
  386. ster/tui/plugins/lint_ui/problems_modal.py +206 -0
  387. ster/tui/plugins/query_trace_ui/__init__.py +34 -0
  388. ster/tui/plugins/query_trace_ui/panel.py +117 -0
  389. ster/tui/plugins/semanticdiff_ui/screen.py +267 -0
  390. ster/tui/ports.py +73 -0
  391. ster/tui/presenters/__init__.py +30 -0
  392. ster/tui/presenters/base.py +83 -0
  393. ster/tui/presenters/class_.py +53 -0
  394. ster/tui/presenters/concept_.py +58 -0
  395. ster/tui/presenters/context.py +26 -0
  396. ster/tui/presenters/coverage.py +113 -0
  397. ster/tui/presenters/health.py +59 -0
  398. ster/tui/presenters/overview.py +179 -0
  399. ster/tui/presenters/property_.py +45 -0
  400. ster/tui/presenters/pun.py +69 -0
  401. ster/tui/project_tools.py +40 -0
  402. ster/tui/property_edit_modal.py +40 -0
  403. ster/tui/query.py +292 -0
  404. ster/tui/query_ask.py +106 -0
  405. ster/tui/query_screen.py +251 -0
  406. ster/tui/remembered_context.py +68 -0
  407. ster/tui/repository.py +40 -0
  408. ster/tui/source_view.py +247 -0
  409. ster/tui/sparql.py +41 -0
  410. ster/tui/sparql_complete.py +247 -0
  411. ster/tui/sparql_editor.py +155 -0
  412. ster/tui/sparql_highlight.py +70 -0
  413. ster/tui/theme.py +35 -0
  414. ster/tui/unreadable_modal.py +94 -0
  415. ster/tui/uri_edit.py +50 -0
  416. ster/tui/uri_modal.py +102 -0
  417. ster/tui/urls.py +61 -0
  418. ster/tui/view_actions.py +31 -0
  419. ster/tui/view_catalog.py +45 -0
  420. ster/tui/viewer_server.py +73 -0
  421. ster/tui/working_file_chip.py +207 -0
  422. ster/type_vocabulary.py +120 -0
  423. ster/validator.py +167 -0
  424. ster/vendored/assets/cose-base.js +3214 -0
  425. ster/vendored/assets/cytoscape-expand-collapse.js +1 -0
  426. ster/vendored/assets/cytoscape-fcose.js +1549 -0
  427. ster/vendored/assets/d3-hierarchy.min.js +2 -0
  428. ster/vendored/assets/d3-path.min.js +2 -0
  429. ster/vendored/assets/d3-shape.min.js +2 -0
  430. ster/vendored/assets/layout-base.js +5230 -0
  431. ster/vendored/assets/leaflet.css +661 -0
  432. ster/vendored/assets/leaflet.js +6 -0
  433. ster/vendored/assets/vendored.json +65 -0
  434. ster/vendored/assets/vis-timeline-graph2d.min.css +1 -0
  435. ster/vendored/assets/vis-timeline-graph2d.min.js +50 -0
  436. ster/view_catalog.py +82 -0
  437. ster/view_links.py +375 -0
  438. ster/view_names.py +15 -0
  439. ster/view_payload.py +55 -0
  440. ster/viewer_server.py +97 -0
  441. ster/viz.py +247 -0
  442. ster/viz_charts/__init__.py +5 -0
  443. ster/viz_charts/assets/chart.umd.min.js +14 -0
  444. ster/viz_charts/assets/chartjs-LICENSE.md +9 -0
  445. ster/viz_charts/assets/charts.css +29 -0
  446. ster/viz_charts/assets/charts.js +109 -0
  447. ster/viz_charts/assets/charts_core.js +198 -0
  448. ster/viz_charts/assets/vendored.json +9 -0
  449. ster/viz_charts/choice.py +138 -0
  450. ster/viz_charts/tool.py +102 -0
  451. ster/viz_discovery.py +33 -0
  452. ster/viz_graph/__init__.py +5 -0
  453. ster/viz_graph/assets/cytoscape-LICENSE.md +19 -0
  454. ster/viz_graph/assets/cytoscape.min.js +32 -0
  455. ster/viz_graph/assets/graph.css +30 -0
  456. ster/viz_graph/assets/graph.js +114 -0
  457. ster/viz_graph/assets/vendored.json +9 -0
  458. ster/viz_graph/payload.py +150 -0
  459. ster/viz_graph/tool.py +128 -0
  460. ster/viz_kit/__init__.py +1 -0
  461. ster/viz_kit/scaffold.py +165 -0
  462. ster/viz_kit/testing.py +296 -0
  463. ster/viz_map/__init__.py +5 -0
  464. ster/viz_map/focus.py +21 -0
  465. ster/viz_map/geo_map_html.py +1632 -0
  466. ster/viz_map/geo_results.py +261 -0
  467. ster/viz_map/geo_shapes.py +1256 -0
  468. ster/viz_map/named_rows.py +23 -0
  469. ster/viz_map/places.py +88 -0
  470. ster/viz_map/tool.py +131 -0
  471. ster/viz_offers.py +43 -0
  472. ster/viz_registry.py +116 -0
  473. ster/viz_shared.py +242 -0
  474. ster/viz_timeline/__init__.py +5 -0
  475. ster/viz_timeline/assets/timeline_app.js +569 -0
  476. ster/viz_timeline/focus.py +19 -0
  477. ster/viz_timeline/lanes.py +39 -0
  478. ster/viz_timeline/named_rows.py +16 -0
  479. ster/viz_timeline/time_results.py +169 -0
  480. ster/viz_timeline/time_shapes.py +595 -0
  481. ster/viz_timeline/timeline_html.py +291 -0
  482. ster/viz_timeline/tool.py +159 -0
  483. ster/viz_timeline/validation.py +91 -0
  484. ster/viz_tool.py +209 -0
  485. ster/viz_vowl/__init__.py +193 -0
  486. ster/viz_vowl/_claim.py +148 -0
  487. ster/viz_vowl/_detail.py +176 -0
  488. ster/viz_vowl/_graph_builders.py +758 -0
  489. ster/viz_vowl/_html_template.py +241 -0
  490. ster/viz_vowl/_js_assets.py +248 -0
  491. ster/viz_vowl/_query_result.py +245 -0
  492. ster/viz_vowl/_relations.py +327 -0
  493. ster/viz_vowl/_render.py +226 -0
  494. ster/viz_vowl/_search.py +140 -0
  495. ster/viz_vowl/_server.py +286 -0
  496. ster/warmup.py +126 -0
  497. ster/wind-bigood.ttl +11 -0
  498. ster/wizard.py +260 -0
  499. ster/working_file.py +73 -0
  500. ster/workspace.py +146 -0
  501. ster/workspace_ops.py +36 -0
  502. ster-1.1.0.dist-info/METADATA +436 -0
  503. ster-1.1.0.dist-info/RECORD +506 -0
  504. ster-1.1.0.dist-info/WHEEL +4 -0
  505. ster-1.1.0.dist-info/entry_points.txt +10 -0
  506. ster-1.1.0.dist-info/licenses/LICENSE +21 -0
agent_app/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Agent app: ask a ster project's ontology questions in plain language, through the user's own agent or model.
2
+
3
+ Run it with ``python -m agent_app`` from a ster project folder (see README.md). Importing this package is cheap:
4
+ the web server and its dependencies load only when it is started.
5
+ """
agent_app/__main__.py ADDED
@@ -0,0 +1,9 @@
1
+ """``python -m agent_app``: start the agent page."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from .cli import main
8
+
9
+ sys.exit(main())
agent_app/choice.py ADDED
@@ -0,0 +1,47 @@
1
+ """Which agent answers: the project's own pick, else the user's global default, else the environment's.
2
+
3
+ Two small JSON files hold the pick, both ``{"agent": "<recipe file>"}``: one per project (written by the agent page)
4
+ and one for the user (``~/.config/ster/agent.json``, written by ster's config menu). The project's wins, so a project
5
+ can differ from the default. The package reads and writes them itself, so it keeps working when it lives elsewhere.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+
13
+ GLOBAL_FILE = Path.home() / ".config" / "ster" / "agent.json"
14
+
15
+
16
+ def read(path: Path | None) -> str | None:
17
+ """The agent named in *path*, or None when there is no file, it is unreadable, or it names nothing."""
18
+ if path is None:
19
+ return None
20
+ try:
21
+ data = json.loads(path.read_text())
22
+ except (OSError, ValueError):
23
+ return None
24
+ name = data.get("agent") if isinstance(data, dict) else None
25
+ return name if isinstance(name, str) and name else None
26
+
27
+
28
+ def write(path: Path, name: str | None) -> None:
29
+ """Record *name* in *path*; None removes the pick (back to automatic)."""
30
+ if name is None:
31
+ path.unlink(missing_ok=True)
32
+ return
33
+ path.parent.mkdir(parents=True, exist_ok=True)
34
+ path.write_text(json.dumps({"agent": name}))
35
+
36
+
37
+ def global_choice() -> str | None:
38
+ return read(GLOBAL_FILE)
39
+
40
+
41
+ def set_global(name: str | None) -> None:
42
+ write(GLOBAL_FILE, name)
43
+
44
+
45
+ def resolve(project_file: Path | None, default: str | None) -> str | None:
46
+ """The recipe asked for: the project's pick, else the global one, else *default* (e.g. ASK_RECIPE)."""
47
+ return read(project_file) or global_choice() or default
agent_app/cli.py ADDED
@@ -0,0 +1,83 @@
1
+ """The start command: ``python -m agent_app [--project DIR] [--port N] [--ster-host H] [--ster-port N]``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import threading
8
+ import time
9
+ from collections.abc import Callable, Sequence
10
+
11
+ from .departure import CHECK_EVERY_S, Departure
12
+
13
+
14
+ def parse(argv: Sequence[str] | None) -> argparse.Namespace:
15
+ p = argparse.ArgumentParser(
16
+ prog="agent_app", description="Talk to a ster project's graph in plain language."
17
+ )
18
+ p.add_argument("--project", help="the ster project folder (default: the current folder)")
19
+ p.add_argument("--port", type=int, help="port of the page (default 8780)")
20
+ p.add_argument("--ster-host", help="where ster listens (default 127.0.0.1)")
21
+ p.add_argument("--ster-port", type=int, help="where ster listens or is started (default 8765)")
22
+ p.add_argument(
23
+ "--quit-with-ster",
24
+ action="store_true",
25
+ help="exit once ster has been unreachable for a while (set when ster starts the page)",
26
+ )
27
+ return p.parse_args(argv)
28
+
29
+
30
+ def apply(args: argparse.Namespace, env: dict[str, str]) -> None:
31
+ """Command-line options become the ASK_* settings the server reads when it is imported."""
32
+ for value, name in (
33
+ (args.project, "ASK_PROJECT"),
34
+ (args.port, "ASK_PORT"),
35
+ (args.ster_host, "ASK_STER_HOST"),
36
+ (args.ster_port, "ASK_STER_PORT"),
37
+ ):
38
+ if value is not None:
39
+ env[name] = str(value)
40
+
41
+
42
+ def _warm_ster(server) -> None:
43
+ """Start the project's ster in the background; a folder that is not a ster project just leaves the header red."""
44
+ try:
45
+ server.ensure_ster()
46
+ except (OSError, ValueError, KeyError) as exc:
47
+ print(f"ster was not started: {exc}")
48
+
49
+
50
+ def quit_with_ster(
51
+ server,
52
+ uvicorn_server,
53
+ departure: Departure | None = None,
54
+ sleep: Callable[[float], None] = time.sleep,
55
+ clock: Callable[[], float] = time.monotonic,
56
+ ) -> None:
57
+ """Ask the web server to stop once ster is gone (see :class:`Departure`); returns when it has stopped."""
58
+ departure = departure or Departure()
59
+ while not uvicorn_server.should_exit:
60
+ busy = any(not run.finished for run in server.RUNS.values())
61
+ if departure.should_quit(server.ster_up(), busy, clock()):
62
+ uvicorn_server.should_exit = True
63
+ else:
64
+ sleep(CHECK_EVERY_S)
65
+
66
+
67
+ def main(argv: Sequence[str] | None = None) -> int:
68
+ args = parse(argv)
69
+ apply(args, os.environ) # type: ignore[arg-type]
70
+ import uvicorn
71
+
72
+ from . import server # read the settings above, so imported only now
73
+
74
+ # so the header is green on opening instead of after the first question
75
+ threading.Thread(target=_warm_ster, args=(server,), daemon=True).start()
76
+ print(f"Agent page: http://127.0.0.1:{server.WEB_PORT} (project: {server.ROOT})")
77
+ web = uvicorn.Server(
78
+ uvicorn.Config(server.app, host="127.0.0.1", port=server.WEB_PORT, log_level="warning")
79
+ )
80
+ if args.quit_with_ster:
81
+ threading.Thread(target=quit_with_ster, args=(server, web), daemon=True).start()
82
+ web.run()
83
+ return 0
agent_app/departure.py ADDED
@@ -0,0 +1,22 @@
1
+ """A page that ster started goes when ster does, so closing the terminal does not leave it running for days."""
2
+
3
+ from __future__ import annotations
4
+
5
+ GRACE_S = 90.0 # ster restarting, or a laptop waking up, must not take the page with it
6
+ CHECK_EVERY_S = 10.0
7
+
8
+
9
+ class Departure:
10
+ """Decides when the page should quit: ster has been unreachable for *grace* seconds and no answer is running."""
11
+
12
+ def __init__(self, grace: float = GRACE_S) -> None:
13
+ self.grace = grace
14
+ self._gone_since: float | None = None
15
+
16
+ def should_quit(self, ster_up: bool, busy: bool, now: float) -> bool:
17
+ if ster_up or busy: # an answer in progress is never cut off, even without ster
18
+ self._gone_since = None
19
+ return False
20
+ if self._gone_since is None:
21
+ self._gone_since = now
22
+ return now - self._gone_since >= self.grace
@@ -0,0 +1,64 @@
1
+ """A conversation that outlives its graph: the agent starts afresh on the new one instead of trusting old facts.
2
+
3
+ An agent's session holds what it learned about the graph (classes, namespaces, counts). When ster is relaunched on
4
+ another file, a follow-up that resumes that session reuses the old namespace in its first query and finds nothing.
5
+ The page already says so in a banner; this makes the follow-up itself safe: it starts a new agent session and is
6
+ told the graph changed.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ GRAPH, SESSION, MESSAGES, AGENT_PROMPT, FRESH = (
12
+ "graph",
13
+ "session_id",
14
+ "messages",
15
+ "agent_prompt",
16
+ "fresh_session",
17
+ )
18
+ FINGERPRINT, TURNS = "fingerprint", "turns"
19
+
20
+
21
+ def changed(turns: list[dict], fingerprint: str | None) -> bool:
22
+ """True when the graph now served is not the one the conversation's last answered turn was about."""
23
+ last = next((t for t in reversed(turns) if t.get(GRAPH)), None)
24
+ return bool(last and fingerprint and last[GRAPH] != fingerprint)
25
+
26
+
27
+ def name_of(graph: dict | None) -> str:
28
+ """What to call the graph in a note: its title, else its ontology, else its file, with its size."""
29
+ graph = graph or {}
30
+ name = (
31
+ graph.get("title") or graph.get("ontology_uri") or graph.get("file") or "a different graph"
32
+ )
33
+ triples = graph.get("triples")
34
+ return f"{name} ({triples} triples)" if triples is not None else str(name)
35
+
36
+
37
+ def note_for(graph: dict | None) -> str:
38
+ """The line put before the question when the graph changed: not to reuse what the old session knew."""
39
+ return (
40
+ f"[Note from the page: the graph ster serves changed since the previous question; it is now {name_of(graph)}. "
41
+ "Earlier classes, namespaces, counts and answers in this conversation were about another graph: do not reuse "
42
+ "them, and call get_overview and get_vocabulary again before querying.]"
43
+ )
44
+
45
+
46
+ def start_afresh(conv: dict, turn: dict, graph: dict | None) -> None:
47
+ """Make *turn* start a new agent session: forget the old session and transcript, and tell the agent why."""
48
+ conv[SESSION] = None
49
+ conv[MESSAGES] = []
50
+ turn[AGENT_PROMPT] = f"{note_for(graph)}\n\n{turn['prompt']}"
51
+ turn[FRESH] = {GRAPH: (graph or {}).get(FINGERPRINT), "name": name_of(graph)}
52
+
53
+
54
+ def prompt_of(turn: dict) -> str:
55
+ """What the agent is asked for this turn: the question, with the note when the session started afresh."""
56
+ return turn.get(AGENT_PROMPT) or turn["prompt"]
57
+
58
+
59
+ def begin(conv: dict, turn: dict, served: dict) -> None:
60
+ """Called as a turn starts, with what ster serves (see ``ster_state``): when it is not the graph the
61
+ conversation was about, start afresh."""
62
+ graph = served.get(GRAPH)
63
+ if changed(conv[TURNS], (graph or {}).get(FINGERPRINT)):
64
+ start_afresh(conv, turn, graph)
agent_app/history.py ADDED
@@ -0,0 +1,203 @@
1
+ """Conversations rebuilt from what ster recorded, for the ones this page has no copy of.
2
+
3
+ ster's trace folder holds every query any agent ran on the graph (``run-*.jsonl``) and, for answers this page's runner
4
+ reported, the answer text, resume id and the runs it rests on (``answers/*.json``). Read together they give back a
5
+ conversation list: the page's own copy is the live one, and this fills in what it lacks (another machine's history,
6
+ a copy that was deleted, a session an agent ran in a terminal without the page). Everything here is read-only.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ from collections.abc import Callable
14
+ from datetime import UTC, datetime, timedelta
15
+ from pathlib import Path
16
+
17
+ _TITLE = 70
18
+ _ID_LENGTH = 12 # a conversation id: twelve hex digits
19
+ _HEX = "0123456789abcdef"
20
+
21
+
22
+ def _epoch(stamp: str | None) -> float:
23
+ try:
24
+ return datetime.fromisoformat((stamp or "").replace("Z", "+00:00")).timestamp()
25
+ except ValueError:
26
+ return 0.0
27
+
28
+
29
+ def run_files(traces: Path) -> list[Path]:
30
+ """Every run journal ster wrote: in ``YYYY/MM/DD`` folders, or loose from before there were any."""
31
+ return sorted(traces.rglob("run-*.jsonl")) if traces.is_dir() else []
32
+
33
+
34
+ def recent_run_files(traces: Path, now: datetime | None = None) -> list[Path]:
35
+ """The journals of today and yesterday (UTC) and any loose ones: what a run in progress can be writing."""
36
+ now = now or datetime.now(UTC)
37
+ found = list(traces.glob("run-*.jsonl")) if traces.is_dir() else []
38
+ for back in (0, 1):
39
+ day = now - timedelta(days=back)
40
+ folder = traces / f"{day:%Y}" / f"{day:%m}" / f"{day:%d}"
41
+ found += list(folder.glob("run-*.jsonl")) if folder.is_dir() else []
42
+ return found
43
+
44
+
45
+ def find_run(traces: Path, run_id: str) -> Path | None:
46
+ """The journal of one run, wherever it was filed."""
47
+ return next((p for p in recent_run_files(traces) + run_files(traces) if p.stem == run_id), None)
48
+
49
+
50
+ def _first_event(path: Path) -> dict | None:
51
+ try:
52
+ with path.open(encoding="utf-8") as f:
53
+ line = f.readline()
54
+ return json.loads(line) if line.strip() else None
55
+ except (OSError, ValueError):
56
+ return None
57
+
58
+
59
+ def _runs(traces: Path) -> dict[str, dict]:
60
+ """Every recorded run: id -> {tool, input, started, agent_session_id, question, usage}."""
61
+ out: dict[str, dict] = {}
62
+ for path in run_files(traces):
63
+ first = _first_event(path)
64
+ if not first or first.get("event") != "run_started":
65
+ continue
66
+ payload = first.get("payload", {})
67
+ try:
68
+ asked = json.loads(payload.get("question") or "{}")
69
+ except ValueError:
70
+ asked = {}
71
+ usage = payload.get("token_usage")
72
+ out[path.stem] = {
73
+ "id": path.stem,
74
+ "tool": payload.get("tool") or asked.get("tool") or "tool",
75
+ "input": asked.get("arguments") if isinstance(asked, dict) else {},
76
+ "started": _epoch(first.get("timestamp")),
77
+ "agent_session_id": payload.get("agent_session_id"),
78
+ "question": payload.get("agent_question") or payload.get("agent_session_question"),
79
+ "usage": usage if isinstance(usage, dict) else None,
80
+ }
81
+ return out
82
+
83
+
84
+ def _answers(traces: Path) -> list[dict]:
85
+ found = []
86
+ for path in (traces / "answers").glob("*.json") if (traces / "answers").is_dir() else []:
87
+ try:
88
+ data = json.loads(path.read_text(encoding="utf-8"))
89
+ except (OSError, ValueError):
90
+ continue
91
+ if isinstance(data, dict) and isinstance(data.get("id"), str):
92
+ found.append(data)
93
+ return found
94
+
95
+
96
+ def _session_id(agent_session_id: str) -> str:
97
+ return hashlib.sha256(agent_session_id.encode()).hexdigest()[:_ID_LENGTH]
98
+
99
+
100
+ def _turn(prompt: str, started: float, answer: dict | None, runs: list[dict]) -> dict:
101
+ ordered = sorted(runs, key=lambda r: r["started"])
102
+ turn = {
103
+ "id": (answer or {}).get("id") or _session_id(prompt + str(started)),
104
+ "prompt": prompt,
105
+ "status": (answer or {}).get("status", "completed"),
106
+ "agent": (answer or {}).get("agent"),
107
+ "started": started,
108
+ "usage": (answer or {}).get("token_usage"),
109
+ "cost_usd": (answer or {}).get("cost_usd"),
110
+ "answer": (answer or {}).get("answer"),
111
+ "duration_ms": (answer or {}).get("duration_ms"),
112
+ "graph": (answer or {}).get("graph_fingerprint"),
113
+ "run_ids": [r["id"] for r in ordered],
114
+ "_runs": ordered,
115
+ "events": [],
116
+ }
117
+ return turn
118
+
119
+
120
+ def conversations(traces: Path) -> list[dict]:
121
+ """Conversations without their events (``_runs`` holds what builds them), newest first."""
122
+ runs = _runs(traces)
123
+ by_conv: dict[str, dict] = {}
124
+ claimed: set[str] = set()
125
+ for a in sorted(_answers(traces), key=lambda a: str(a.get("started") or a.get("recorded"))):
126
+ cid = a.get("conversation_id") or a["id"]
127
+ if len(cid) != _ID_LENGTH or any(c not in _HEX for c in cid):
128
+ cid = _session_id(cid)
129
+ mine = [runs[r] for r in a.get("run_ids", []) if r in runs]
130
+ claimed.update(r["id"] for r in mine)
131
+ started = _epoch(a.get("started")) or _epoch(a.get("recorded"))
132
+ conv = by_conv.setdefault(
133
+ cid,
134
+ {"id": cid, "title": a.get("question", "")[:_TITLE], "created": started, "turns": []},
135
+ )
136
+ conv["turns"].append(_turn(a.get("question", ""), started, a, mine))
137
+ conv["session_id"] = a.get("resume_session_id") or conv.get("session_id")
138
+ by_agent: dict[str, list[dict]] = {}
139
+ for r in (
140
+ runs.values()
141
+ ): # sessions an agent ran without this page: grouped by the id its calls carried
142
+ if r["id"] not in claimed and r["agent_session_id"]:
143
+ by_agent.setdefault(r["agent_session_id"], []).append(r)
144
+ for sid, group in by_agent.items():
145
+ group.sort(key=lambda r: r["started"])
146
+ prompt = (
147
+ next((r["question"] for r in group if r["question"]), None) or "(no question recorded)"
148
+ )
149
+ cid = _session_id(sid)
150
+ by_conv[cid] = {
151
+ "id": cid,
152
+ "title": prompt[:_TITLE],
153
+ "created": group[0]["started"],
154
+ "turns": [_turn(prompt, group[0]["started"], None, group)],
155
+ }
156
+ for conv in by_conv.values():
157
+ conv["updated"] = max([t["started"] for t in conv["turns"]] + [conv["created"]])
158
+ conv["readonly"] = True
159
+ conv["source"] = "traces"
160
+ return sorted(by_conv.values(), key=lambda c: c["updated"], reverse=True)
161
+
162
+
163
+ def with_events(conv: dict, trace_of: Callable[[str], dict | None]) -> dict:
164
+ """*conv* with each turn's events: a step and a tool call per run, its trace, and the answer."""
165
+ out = {k: v for k, v in conv.items() if k != "turns"}
166
+ out["turns"] = []
167
+ for turn in conv["turns"]:
168
+ base = turn["started"]
169
+ events: list[dict] = [
170
+ {"e": "turn_start", "t": 0, "prompt": turn["prompt"], "resumed": False}
171
+ ]
172
+ for n, run in enumerate(turn["_runs"], 1):
173
+ t = max(0, int((run["started"] - base) * 1000))
174
+ step = f"s{n}"
175
+ events.append({"e": "step_start", "t": t, "step": step})
176
+ if run["usage"]:
177
+ events.append({"e": "usage", "t": t, "step": step, **run["usage"]})
178
+ events.append(
179
+ {
180
+ "e": "tool_call",
181
+ "t": t,
182
+ "step": step,
183
+ "id": run["id"],
184
+ "name": run["tool"],
185
+ "input": run["input"] or {},
186
+ }
187
+ )
188
+ if trace := trace_of(run["id"]):
189
+ events.append({"e": "trace", "t": t, "id": run["id"], **trace})
190
+ events.append(
191
+ {
192
+ "e": "done",
193
+ "t": turn.get("duration_ms") or 0,
194
+ "status": turn["status"],
195
+ "answer": turn["answer"],
196
+ "usage": turn["usage"],
197
+ "cost_usd": turn["cost_usd"],
198
+ }
199
+ )
200
+ shown = {k: v for k, v in turn.items() if k not in ("_runs",)}
201
+ shown["events"] = events
202
+ out["turns"].append(shown)
203
+ return out
agent_app/launcher.py ADDED
@@ -0,0 +1,161 @@
1
+ """What ster needs from the agent app, without importing its web server.
2
+
3
+ ster's menus and shortcuts call three things: is an agent usable right now, is a page already running for this
4
+ project, and if not, start one and say where it is. Nothing here imports FastAPI or the page's server: the CLI
5
+ menu asks this on every redraw, and the page runs in its own process.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import http.client
11
+ import json
12
+ import os
13
+ import socket
14
+ import subprocess
15
+ import sys
16
+ import time
17
+ import urllib.request
18
+ from collections.abc import Mapping
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+
22
+ from . import runner
23
+
24
+ HOST = "127.0.0.1"
25
+ DEFAULT_PORT = 8780
26
+ PORTS = range(
27
+ DEFAULT_PORT, DEFAULT_PORT + 10
28
+ ) # one page per project; each takes the first free port here
29
+ RECIPES = Path(__file__).parent / "recipes"
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Launch:
34
+ """The outcome of asking for the page: where it is, whether this call started it, or why it could not be."""
35
+
36
+ url: str | None
37
+ started: bool
38
+ error: str | None = None
39
+ pid: int | None = None
40
+
41
+
42
+ def has_usable_agent(env: Mapping[str, str] | None = None, recipes_dir: Path | None = None) -> bool:
43
+ """Whether the page could answer a question now: a command or recipe whose program is installed, or a model
44
+ server with a model that can call tools. *env* is where ASK_AGENT_CMD / ASK_MODEL_URL are read from."""
45
+ env = os.environ if env is None else env
46
+ chosen = runner.select(
47
+ runner.load_recipes(recipes_dir or RECIPES),
48
+ runner.from_env(dict(env)),
49
+ env.get("ASK_RECIPE"),
50
+ )
51
+ return chosen is not None
52
+
53
+
54
+ def _status(port: int, timeout: float = 1.0) -> dict | None:
55
+ """The agent page's own /api/status on *port*, or None when nothing there answers as the page does."""
56
+ try:
57
+ with urllib.request.urlopen(f"http://{HOST}:{port}/api/status", timeout=timeout) as r:
58
+ data = json.load(r)
59
+ except (
60
+ OSError,
61
+ ValueError,
62
+ http.client.HTTPException,
63
+ ): # not HTTP at all: BadStatusLine is neither
64
+ return None
65
+ return data if isinstance(data, dict) and "root" in data else None
66
+
67
+
68
+ def _same_folder(a: str | Path, b: str | Path) -> bool:
69
+ return Path(a).resolve() == Path(b).resolve()
70
+
71
+
72
+ def find_page(project: Path, ports: range = PORTS, ster_port: int | None = None) -> str | None:
73
+ """The address of a page already running for *project* on this ster, if any.
74
+
75
+ A page is one open graph: the ster on a port, with the project folder its history and traces live in. It follows
76
+ whatever that ster serves, so nothing about files is compared. *ster_port* left out means "any".
77
+ """
78
+ for port in ports:
79
+ status = _status(port)
80
+ if not status or not _same_folder(status["root"], project):
81
+ continue
82
+ if ster_port is not None and status.get("ster_port") != ster_port:
83
+ continue
84
+ return f"http://{HOST}:{port}"
85
+ return None
86
+
87
+
88
+ def _in_use(port: int) -> bool:
89
+ with socket.socket() as s:
90
+ s.settimeout(0.5)
91
+ return s.connect_ex((HOST, port)) == 0
92
+
93
+
94
+ def _no_port_message(ports: range) -> str:
95
+ """Every port taken: say by what, so that the pages left over can be stopped."""
96
+ taken = []
97
+ for port in ports:
98
+ status = _status(port)
99
+ if status:
100
+ ster = status.get("ster_port")
101
+ taken.append(
102
+ f"{port} ({Path(status['root']).name}, ster {ster}{'' if status.get('ster') else ' gone'})"
103
+ )
104
+ else:
105
+ taken.append(f"{port} (not an agent page)")
106
+ return (
107
+ f"No free port for the agent page between {ports.start} and {ports.stop - 1}. Taken: "
108
+ + ", ".join(taken)
109
+ + f". Stop the ones you no longer need (lsof -nP -iTCP:{ports.start}-{ports.stop - 1} -sTCP:LISTEN)."
110
+ )
111
+
112
+
113
+ FROZEN_ROLE = "--agent-page" # what a built app is started with to be the page: it has no "-m" to run a module by
114
+
115
+
116
+ def page_command() -> list[str]:
117
+ """The command that starts the page: its module under Python, or a built app (which is ster itself) with a flag."""
118
+ if getattr(sys, "frozen", False):
119
+ return [sys.executable, FROZEN_ROLE]
120
+ return [sys.executable, "-m", "agent_app"]
121
+
122
+
123
+ def ensure_running(
124
+ project: Path,
125
+ ster_host: str,
126
+ ster_port: int,
127
+ ports: range = PORTS,
128
+ wait: float = 30.0,
129
+ ) -> Launch:
130
+ """The page for *project* on this ster: the one already running, or a new one started detached."""
131
+ if url := find_page(project, ports, ster_port):
132
+ return Launch(url, started=False)
133
+ port = next((p for p in ports if not _in_use(p)), None)
134
+ if port is None:
135
+ return Launch(None, False, _no_port_message(ports))
136
+ log = project / ".ster" / "agent-app" / "page.log"
137
+ log.parent.mkdir(parents=True, exist_ok=True)
138
+ cmd = [
139
+ *page_command(),
140
+ "--project",
141
+ str(project),
142
+ "--port",
143
+ str(port),
144
+ "--ster-host",
145
+ ster_host,
146
+ "--ster-port",
147
+ str(ster_port),
148
+ "--quit-with-ster", # a page ster starts goes when ster does
149
+ ]
150
+ with open(log, "ab") as out: # the child keeps its own copy of the handle
151
+ proc = subprocess.Popen(cmd, cwd=project, stdout=out, stderr=out, start_new_session=True)
152
+ deadline = time.monotonic() + wait
153
+ while time.monotonic() < deadline:
154
+ if (status := _status(port)) and _same_folder(
155
+ status["root"], project
156
+ ): # ours: it answers on our port
157
+ return Launch(f"http://{HOST}:{port}", started=True, pid=proc.pid)
158
+ if isinstance(code := proc.poll(), int):
159
+ return Launch(None, False, f"The agent page exited with code {code}. Look in {log}.")
160
+ time.sleep(0.2)
161
+ return Launch(None, False, f"The agent page did not answer within {wait:.0f} s. Look in {log}.")