kymoscope-mcp 0.1.0__tar.gz

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 (44) hide show
  1. kymoscope_mcp-0.1.0/.gitignore +87 -0
  2. kymoscope_mcp-0.1.0/LICENSE.md +62 -0
  3. kymoscope_mcp-0.1.0/PKG-INFO +96 -0
  4. kymoscope_mcp-0.1.0/README.md +13 -0
  5. kymoscope_mcp-0.1.0/build_mcpb.py +13 -0
  6. kymoscope_mcp-0.1.0/mcpb/manifest.json +24 -0
  7. kymoscope_mcp-0.1.0/mcpb/pyproject.toml +12 -0
  8. kymoscope_mcp-0.1.0/mcpb/server.py +3 -0
  9. kymoscope_mcp-0.1.0/pyproject.toml +32 -0
  10. kymoscope_mcp-0.1.0/src/kymoscope_mcp/__init__.py +1 -0
  11. kymoscope_mcp-0.1.0/src/kymoscope_mcp/account.py +183 -0
  12. kymoscope_mcp-0.1.0/src/kymoscope_mcp/actions.py +216 -0
  13. kymoscope_mcp-0.1.0/src/kymoscope_mcp/bundle.py +433 -0
  14. kymoscope_mcp-0.1.0/src/kymoscope_mcp/catalog.py +43 -0
  15. kymoscope_mcp-0.1.0/src/kymoscope_mcp/collector.py +786 -0
  16. kymoscope_mcp-0.1.0/src/kymoscope_mcp/contract.py +30 -0
  17. kymoscope_mcp-0.1.0/src/kymoscope_mcp/docs.json +1762 -0
  18. kymoscope_mcp-0.1.0/src/kymoscope_mcp/docs.py +90 -0
  19. kymoscope_mcp-0.1.0/src/kymoscope_mcp/health.py +332 -0
  20. kymoscope_mcp-0.1.0/src/kymoscope_mcp/host.py +437 -0
  21. kymoscope_mcp-0.1.0/src/kymoscope_mcp/paths.py +58 -0
  22. kymoscope_mcp-0.1.0/src/kymoscope_mcp/result.py +336 -0
  23. kymoscope_mcp-0.1.0/src/kymoscope_mcp/server.py +285 -0
  24. kymoscope_mcp-0.1.0/src/kymoscope_mcp/service.py +286 -0
  25. kymoscope_mcp-0.1.0/src/kymoscope_mcp/templates/polled.py +63 -0
  26. kymoscope_mcp-0.1.0/src/kymoscope_mcp/templates/streaming.py +62 -0
  27. kymoscope_mcp-0.1.0/src/kymoscope_mcp/writes.py +566 -0
  28. kymoscope_mcp-0.1.0/tests/conftest.py +25 -0
  29. kymoscope_mcp-0.1.0/tests/test_account_host.py +578 -0
  30. kymoscope_mcp-0.1.0/tests/test_actions.py +204 -0
  31. kymoscope_mcp-0.1.0/tests/test_bundle.py +510 -0
  32. kymoscope_mcp-0.1.0/tests/test_classify.py +127 -0
  33. kymoscope_mcp-0.1.0/tests/test_collector.py +914 -0
  34. kymoscope_mcp-0.1.0/tests/test_failures.py +689 -0
  35. kymoscope_mcp-0.1.0/tests/test_health.py +793 -0
  36. kymoscope_mcp-0.1.0/tests/test_knowledge.py +96 -0
  37. kymoscope_mcp-0.1.0/tests/test_mcpb.py +36 -0
  38. kymoscope_mcp-0.1.0/tests/test_paths.py +41 -0
  39. kymoscope_mcp-0.1.0/tests/test_regressions.py +134 -0
  40. kymoscope_mcp-0.1.0/tests/test_result.py +106 -0
  41. kymoscope_mcp-0.1.0/tests/test_server.py +820 -0
  42. kymoscope_mcp-0.1.0/tests/test_service.py +345 -0
  43. kymoscope_mcp-0.1.0/tests/test_windows_lock.py +152 -0
  44. kymoscope_mcp-0.1.0/tests/test_writes.py +818 -0
@@ -0,0 +1,87 @@
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+ pnpm-debug.log*
8
+ lerna-debug.log*
9
+
10
+ node_modules
11
+ dist
12
+ dist-mcpb
13
+ dist-ssr
14
+ *.local
15
+
16
+ # Editor directories and files
17
+ .vscode/*
18
+ !.vscode/extensions.json
19
+ .idea
20
+ .DS_Store
21
+ *.suo
22
+ *.ntvs*
23
+ *.njsproj
24
+ *.sln
25
+ *.sw?
26
+
27
+ # Local env overrides — never commit
28
+ .env.local
29
+ .env.*.local
30
+ .env.production
31
+
32
+ # Brainstorming visual-companion scratch (mockups, server state)
33
+ .superpowers/
34
+
35
+ # Downloaded Kymoscope sender config — contains an API key, never commit
36
+ kymoscope-stream.json
37
+ **/kymoscope-stream.json
38
+ # Native plugin config — holds the stream password
39
+ **/kymoscope-plugin.json
40
+ # Pre-rename (Prism) names of the same local files
41
+ **/prism-stream.json
42
+ **/prism-plugin.json
43
+ **/prism-lmu-sender.zip
44
+ **/.prism_live_state.json
45
+
46
+ # Python caches
47
+ __pycache__/
48
+ *.pyc
49
+ .pytest_cache/
50
+
51
+ # Built client sender bundle (artifact of examples/build_sender_bundle.py)
52
+ kymoscope-lmu-sender.zip
53
+ **/kymoscope-lmu-sender.zip
54
+
55
+ # PyInstaller scratch
56
+ examples/build/
57
+ examples/*.spec
58
+
59
+ # Sender resume state (stream id+salt per name; local, non-secret)
60
+ .kymoscope_live_state.json
61
+ **/.kymoscope_live_state.json
62
+
63
+ # Playwright MCP scratch (screenshots / snapshots from agent runs)
64
+ .playwright-mcp/
65
+ .claude/worktrees/
66
+
67
+ # Large local benchmark dataset — keep out of git (use LFS or external storage)
68
+ public/big-telemetry.csv
69
+ .vercel
70
+ .env.local
71
+
72
+ # Supabase CLI local state (linked project, CLI version cache)
73
+ supabase/.temp/
74
+
75
+ # QA run output (screenshots, sender configs with the run's throwaway keys) and reports
76
+ tests/e2e-prod/out/
77
+ tests/e2e-prod/reports/
78
+
79
+ # Import bench files (generated on demand: tests/fixtures/import/gen_bench.py)
80
+ tests/fixtures/import/bench/
81
+
82
+ # Local state of wrangler dev and the Supabase CLI
83
+ .wrangler/
84
+ supabase/.branches/
85
+
86
+ # Python packaging
87
+ .venv/
@@ -0,0 +1,62 @@
1
+ # Kymoscope Software License
2
+
3
+ Copyright © 2026 Kymoscope. All rights reserved.
4
+
5
+ This license covers the Kymoscope software package it comes with (the "Software"), including its templates and bundled documentation. By installing or using the Software you accept these terms. If you accept them for an organization, you confirm that you may bind it, and "you" means that organization.
6
+
7
+ "Kymoscope" in this license means the owner of the Kymoscope software and service.
8
+
9
+ ## 1. What you may do
10
+
11
+ At no charge, you may install, run and copy the Software to connect systems you are entitled to use to a Kymoscope account, and to operate that connection. You may:
12
+
13
+ 1. use it for your internal business, in production, with no license key;
14
+ 2. keep copies in your organization's internal package mirrors and on the machines that need them;
15
+ 3. let your employees and the contractors working for you do the same, for your benefit; you are responsible for their use.
16
+
17
+ ## 2. What your connectors are
18
+
19
+ You or your AI assistant may use the Software to write adapters, configuration and related files ("Connectors"). As between you and Kymoscope, Connectors are yours, and Kymoscope claims no ownership of them. You may use the templates, examples and any part of the Software that appears in a Connector, as part of that Connector, without restriction.
20
+
21
+ Connectors are not supported or warranted by Kymoscope. Your rights in what an AI assistant produces also depend on that assistant's terms and on applicable law.
22
+
23
+ ## 3. What you may not do
24
+
25
+ You may not:
26
+
27
+ 1. sell, rent or sublicense the Software, or publish it or offer it for download to others outside your organization, except as a Connector under section 2;
28
+ 2. use the Software or a modified copy of it to connect to a service other than Kymoscope. Reading from your own systems and writing to your own sinks, as the Software provides, is allowed;
29
+ 3. remove copyright or license notices from copies of the Software;
30
+ 4. reverse engineer the Software, except to the extent the law allows this regardless of this license. Reading and auditing its source is allowed.
31
+
32
+ ## 4. Other terms
33
+
34
+ Your Kymoscope account and its hosted services are governed by your account terms. Dependencies the Software installs come under their own licenses. An AI assistant you use is governed by its provider's terms.
35
+
36
+ ## 5. Your responsibility
37
+
38
+ You choose what to connect and which changes to approve. In particular:
39
+
40
+ 1. **Code you add or generate runs on your systems**, with the permissions of the account that runs it, which can be an operating system's highest. Tests the Software performs help to review it and do not isolate it.
41
+ 2. **If you use the Software with an AI assistant, what it returns reaches your AI provider**, as described in the documentation at kymoscope.com/docs. Choosing that provider, and what you share with it, is your decision and your responsibility.
42
+ 3. **Not for safety functions.** Don't use the Software or a Connector as part of a safety function, a control function or anything else whose failure could harm people, property or the environment. Use read-only access to the systems you connect.
43
+
44
+ ## 6. No warranty and limitation of liability
45
+
46
+ The Software is provided free of charge and "as is", without warranties of any kind, to the maximum extent the law allows.
47
+
48
+ To the maximum extent the law allows, Kymoscope isn't liable for indirect or consequential damages, loss of data, loss of production or loss of profit arising from the Software or a Connector.
49
+
50
+ Nothing in this license limits liability that the law doesn't allow to be limited, such as for willful misconduct or gross negligence, or rights you have as a consumer that can't be waived.
51
+
52
+ ## 7. Ending
53
+
54
+ You may stop using the Software at any time. This license ends automatically if you materially breach it and don't correct the breach within 30 days of notice; you must then stop using the Software and delete your copies. Sections 2, 5 and 6 and your rights in Connectors continue. A version of the Software you already received stays under this license even if later versions change it.
55
+
56
+ ## 8. Law
57
+
58
+ Mandatory law of the place where you have your seat or residence applies. Otherwise, this license is governed by the law of Spain.
59
+
60
+ ## 9. Contact
61
+
62
+ hola@kymoscope.com
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.5
2
+ Name: kymoscope-mcp
3
+ Version: 0.1.0
4
+ Summary: Lets your AI assistant connect your data to Kymoscope and keep it running
5
+ Project-URL: Homepage, https://kymoscope.com
6
+ Project-URL: Documentation, https://kymoscope.com/docs/mcp
7
+ License: # Kymoscope Software License
8
+
9
+ Copyright © 2026 Kymoscope. All rights reserved.
10
+
11
+ This license covers the Kymoscope software package it comes with (the "Software"), including its templates and bundled documentation. By installing or using the Software you accept these terms. If you accept them for an organization, you confirm that you may bind it, and "you" means that organization.
12
+
13
+ "Kymoscope" in this license means the owner of the Kymoscope software and service.
14
+
15
+ ## 1. What you may do
16
+
17
+ At no charge, you may install, run and copy the Software to connect systems you are entitled to use to a Kymoscope account, and to operate that connection. You may:
18
+
19
+ 1. use it for your internal business, in production, with no license key;
20
+ 2. keep copies in your organization's internal package mirrors and on the machines that need them;
21
+ 3. let your employees and the contractors working for you do the same, for your benefit; you are responsible for their use.
22
+
23
+ ## 2. What your connectors are
24
+
25
+ You or your AI assistant may use the Software to write adapters, configuration and related files ("Connectors"). As between you and Kymoscope, Connectors are yours, and Kymoscope claims no ownership of them. You may use the templates, examples and any part of the Software that appears in a Connector, as part of that Connector, without restriction.
26
+
27
+ Connectors are not supported or warranted by Kymoscope. Your rights in what an AI assistant produces also depend on that assistant's terms and on applicable law.
28
+
29
+ ## 3. What you may not do
30
+
31
+ You may not:
32
+
33
+ 1. sell, rent or sublicense the Software, or publish it or offer it for download to others outside your organization, except as a Connector under section 2;
34
+ 2. use the Software or a modified copy of it to connect to a service other than Kymoscope. Reading from your own systems and writing to your own sinks, as the Software provides, is allowed;
35
+ 3. remove copyright or license notices from copies of the Software;
36
+ 4. reverse engineer the Software, except to the extent the law allows this regardless of this license. Reading and auditing its source is allowed.
37
+
38
+ ## 4. Other terms
39
+
40
+ Your Kymoscope account and its hosted services are governed by your account terms. Dependencies the Software installs come under their own licenses. An AI assistant you use is governed by its provider's terms.
41
+
42
+ ## 5. Your responsibility
43
+
44
+ You choose what to connect and which changes to approve. In particular:
45
+
46
+ 1. **Code you add or generate runs on your systems**, with the permissions of the account that runs it, which can be an operating system's highest. Tests the Software performs help to review it and do not isolate it.
47
+ 2. **If you use the Software with an AI assistant, what it returns reaches your AI provider**, as described in the documentation at kymoscope.com/docs. Choosing that provider, and what you share with it, is your decision and your responsibility.
48
+ 3. **Not for safety functions.** Don't use the Software or a Connector as part of a safety function, a control function or anything else whose failure could harm people, property or the environment. Use read-only access to the systems you connect.
49
+
50
+ ## 6. No warranty and limitation of liability
51
+
52
+ The Software is provided free of charge and "as is", without warranties of any kind, to the maximum extent the law allows.
53
+
54
+ To the maximum extent the law allows, Kymoscope isn't liable for indirect or consequential damages, loss of data, loss of production or loss of profit arising from the Software or a Connector.
55
+
56
+ Nothing in this license limits liability that the law doesn't allow to be limited, such as for willful misconduct or gross negligence, or rights you have as a consumer that can't be waived.
57
+
58
+ ## 7. Ending
59
+
60
+ You may stop using the Software at any time. This license ends automatically if you materially breach it and don't correct the breach within 30 days of notice; you must then stop using the Software and delete your copies. Sections 2, 5 and 6 and your rights in Connectors continue. A version of the Software you already received stays under this license even if later versions change it.
61
+
62
+ ## 8. Law
63
+
64
+ Mandatory law of the place where you have your seat or residence applies. Otherwise, this license is governed by the law of Spain.
65
+
66
+ ## 9. Contact
67
+
68
+ hola@kymoscope.com
69
+ License-File: LICENSE.md
70
+ Requires-Python: >=3.10
71
+ Requires-Dist: anyio>=4.9
72
+ Requires-Dist: kymoscope>=0.8.1
73
+ Requires-Dist: mcp<3,>=2.3
74
+ Requires-Dist: pywin32>=311; sys_platform == 'win32'
75
+ Requires-Dist: pyyaml>=6
76
+ Requires-Dist: requests>=2.28
77
+ Requires-Dist: truststore>=0.10
78
+ Provides-Extra: test
79
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
80
+ Requires-Dist: pytest-timeout>=2.2; extra == 'test'
81
+ Requires-Dist: pytest>=7; extra == 'test'
82
+ Description-Content-Type: text/markdown
83
+
84
+ # kymoscope-mcp
85
+
86
+ Lets your AI assistant connect your data to Kymoscope and keep it running. It runs on your machine; your data never
87
+ passes through it to us. Start it with `uvx --no-config kymoscope-mcp`. Setup, each assistant's configuration and the
88
+ security notes: https://kymoscope.com/docs/mcp
89
+
90
+ Every change shows a preview first and waits for your yes. To skip that, set `KYMOSCOPE_MCP_CONFIRM=off` in the assistant's MCP settings: changes then apply at once, and results and `mcp-actions.log` say `confirmation: off`.
91
+
92
+ ## Privacy Policy
93
+
94
+ The server runs on your machine and collects no telemetry. Apart from checking that hosts are reachable, it contacts
95
+ Kymoscope only with your API key, to check your account and connect the data you choose to send. What you share with
96
+ your AI assistant is governed by that assistant's provider. Kymoscope's privacy policy: https://kymoscope.com/privacy
@@ -0,0 +1,13 @@
1
+ # kymoscope-mcp
2
+
3
+ Lets your AI assistant connect your data to Kymoscope and keep it running. It runs on your machine; your data never
4
+ passes through it to us. Start it with `uvx --no-config kymoscope-mcp`. Setup, each assistant's configuration and the
5
+ security notes: https://kymoscope.com/docs/mcp
6
+
7
+ Every change shows a preview first and waits for your yes. To skip that, set `KYMOSCOPE_MCP_CONFIRM=off` in the assistant's MCP settings: changes then apply at once, and results and `mcp-actions.log` say `confirmation: off`.
8
+
9
+ ## Privacy Policy
10
+
11
+ The server runs on your machine and collects no telemetry. Apart from checking that hosts are reachable, it contacts
12
+ Kymoscope only with your API key, to check your account and connect the data you choose to send. What you share with
13
+ your AI assistant is governed by that assistant's provider. Kymoscope's privacy policy: https://kymoscope.com/privacy
@@ -0,0 +1,13 @@
1
+ """Builds the Claude Desktop extension from mcpb/ with the official CLI, which validates it against the spec's schema
2
+ first: python build_mcpb.py [out], by default dist-mcpb/kymoscope-mcp.mcpb. Needs Node.js. Unsigned."""
3
+ import shutil
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ CLI = "@anthropic-ai/mcpb@2.1.2" # pinned; 2.1.2 came out 2025-12-04
9
+ HERE = Path(__file__).resolve().parent
10
+ out = Path(sys.argv[1]) if len(sys.argv) > 1 else HERE / "dist-mcpb" / "kymoscope-mcp.mcpb"
11
+ npx = shutil.which("npx") or sys.exit("npx not found: install Node.js")
12
+ for args in (["validate", str(HERE / "mcpb")], ["pack", str(HERE / "mcpb"), str(out)]):
13
+ subprocess.run([npx, "--yes", CLI, *args], check=True)
@@ -0,0 +1,24 @@
1
+ {
2
+ "manifest_version": "0.4",
3
+ "name": "kymoscope-mcp",
4
+ "display_name": "Kymoscope",
5
+ "version": "0.1.0",
6
+ "description": "Lets your AI assistant connect your data to Kymoscope and keep it running",
7
+ "author": { "name": "Kymoscope", "url": "https://kymoscope.com" },
8
+ "homepage": "https://kymoscope.com",
9
+ "documentation": "https://kymoscope.com/docs/mcp",
10
+ "privacy_policies": ["https://kymoscope.com/privacy"],
11
+ "server": {
12
+ "type": "uv",
13
+ "entry_point": "server.py",
14
+ "mcp_config": {
15
+ "command": "uv",
16
+ "args": ["tool", "run", "--no-config", "--from", "kymoscope-mcp==0.1.0", "kymoscope-mcp"]
17
+ }
18
+ },
19
+ "compatibility": {
20
+ "platforms": ["win32", "linux"],
21
+ "runtimes": { "python": ">=3.10" }
22
+ },
23
+ "keywords": ["kymoscope", "data", "collector", "telemetry"]
24
+ }
@@ -0,0 +1,12 @@
1
+ # Claude Desktop runs `uv sync` here when it installs the extension, without --no-config, so a uv.toml any Windows
2
+ # user can write is read. So no dependencies: nothing comes from an index here, as the server comes from
3
+ # `uv tool run --no-config` at start. The one download, a Python if there is none, comes from the official source
4
+ # whatever a uv.toml says, as a project's setting wins over a user's or the system's.
5
+ [project]
6
+ name = "kymoscope-mcp-desktop"
7
+ version = "0.1.0"
8
+ requires-python = ">=3.10"
9
+ dependencies = []
10
+
11
+ [tool.uv]
12
+ python-install-mirror = "https://github.com/astral-sh/python-build-standalone/releases/download"
@@ -0,0 +1,3 @@
1
+ """The entry point the bundle format asks for. Claude Desktop doesn't run this file: for a uv extension it runs
2
+ manifest.json's mcp_config args with its own uv, which comes to `uvx --no-config kymoscope-mcp==<version>`, the
3
+ command the docs give every other assistant."""
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "kymoscope-mcp"
7
+ version = "0.1.0"
8
+ description = "Lets your AI assistant connect your data to Kymoscope and keep it running"
9
+ readme = "README.md"
10
+ license = { file = "LICENSE.md" }
11
+ requires-python = ">=3.10"
12
+ dependencies = ["mcp>=2.3,<3", "kymoscope>=0.8.1", "pyyaml>=6", "truststore>=0.10", "requests>=2.28", "anyio>=4.9", "pywin32>=311; sys_platform == 'win32'"]
13
+
14
+ [project.optional-dependencies]
15
+ test = ["pytest>=7", "pytest-asyncio>=0.23", "pytest-timeout>=2.2"]
16
+
17
+ [project.scripts]
18
+ kymoscope-mcp = "kymoscope_mcp.server:main"
19
+
20
+ [project.urls]
21
+ Homepage = "https://kymoscope.com"
22
+ Documentation = "https://kymoscope.com/docs/mcp"
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["src/kymoscope_mcp"]
26
+
27
+ [tool.hatch.build.targets.sdist]
28
+ exclude = ["tests/acceptance"]
29
+
30
+ [tool.pytest.ini_options]
31
+ asyncio_mode = "auto"
32
+ timeout = 120
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,183 @@
1
+ """The API key against Kymoscope. The key lives in a file, is used here and is never returned: whatever a tool returns
2
+ reaches the AI provider."""
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import shlex
7
+ import sys
8
+ from datetime import datetime
9
+
10
+ import requests
11
+ import truststore
12
+ from kymoscope.client import KymoscopeClient, RegistrationError
13
+ from kymoscope.config import DEFAULT_BASE, ConfigError, KymoscopeConfig
14
+
15
+ from . import host, paths
16
+ from .result import classify_kymoscope, classify_network, fail, ok, unknown
17
+
18
+ NO_KEY = ("Save the API key in {path}, alone in the file: {how} Don't paste it in the chat: what's in the chat reaches the AI "
19
+ "provider.")
20
+ _NOTEPAD = ("press Windows+R, type {command} and press Enter (answer Yes to create the file), paste the whole key, save and "
21
+ "close.")
22
+ _HIDDEN = " C:\\ProgramData is a hidden folder, so File Explorer doesn't show it; this command opens the file directly."
23
+ # Who can watch, and how it's protected, by the stream's kind (docs/superpowers/specs/2026-10-31-stream-access-model.md).
24
+ PROJECT = ("A stream of an encrypted project: end-to-end encrypted with the project's key; only the project's members see and "
25
+ "watch it, with nothing to type.")
26
+ # Without project encryption (a personal key, or a project from before it), the stream's own settings decide.
27
+ PERSONAL_LISTED = "A personal stream, listed for every signed-in Kymoscope user: "
28
+ LEGACY_LISTED = "A stream of a project without project encryption, listed for the project's members: "
29
+ SECRET = ("end-to-end encrypted with a key derived from this API key's secret, as it sets no stream_password, so a viewer "
30
+ "types that secret to watch. A stream_password of its own (12 characters or more, in a file: reference) keeps "
31
+ "the API key's secret to its owner.")
32
+ PASSWORD = "end-to-end encrypted with a key derived from its stream password, which a viewer types to watch."
33
+ OPEN = ("open (visibility: open): whoever can see it watches with nothing to type; it is not end-to-end encrypted, only "
34
+ "TLS on the way.")
35
+ BY_SETTINGS = ("end-to-end encrypted with a key derived from the source's stream_password, or from this API key's secret "
36
+ "when it sets none (a viewer types it); one with visibility: open isn't end-to-end encrypted. send_test says "
37
+ "which applies to a source.")
38
+ _PROJECT: dict = {} # the key's project as the last check_account in this process saw it, with the key file's mtime
39
+
40
+
41
+ def _key_mtime() -> float | None:
42
+ try:
43
+ return paths.key_file().stat().st_mtime
44
+ except OSError:
45
+ return None
46
+
47
+
48
+ def remember(project: dict | None) -> None:
49
+ _PROJECT.clear()
50
+ _PROJECT.update(project=project, mtime=_key_mtime())
51
+
52
+
53
+ def _listed(project) -> str:
54
+ return LEGACY_LISTED if project else PERSONAL_LISTED
55
+
56
+
57
+ def protection(source: dict) -> str:
58
+ """How a source's stream is protected, in plain words, so nobody has to guess it. The project comes with the key: what
59
+ was learnt of it holds only while the key file is the same one."""
60
+ own = OPEN if source.get("visibility") == "open" else PASSWORD if source.get("stream_password") else SECRET
61
+ if "project" not in _PROJECT or _PROJECT.get("mtime") != _key_mtime():
62
+ return (f"If this API key belongs to an encrypted project: {PROJECT} Otherwise: {PERSONAL_LISTED}{own} "
63
+ "check_account tells which.")
64
+ project = _PROJECT["project"]
65
+ return PROJECT if project and project.get("e2ee") else _listed(project) + own
66
+
67
+
68
+ def no_key_detail() -> str:
69
+ """Where to save the key, with the command that opens it. On Windows the lock comes first: it moves aside whatever is
70
+ in an unlocked folder."""
71
+ key = paths.key_file()
72
+ if sys.platform == "win32":
73
+ how = _NOTEPAD.format(command=f'notepad {key}' if " " not in str(key) else f'notepad "{key}"')
74
+ how += _HIDDEN if "programdata" in str(key).lower() else ""
75
+ else:
76
+ how = f"open it with a text editor, for example nano {shlex.quote(str(key))}, paste the whole key and save."
77
+ text = NO_KEY.format(path=key, how=how)
78
+ beside = sorted(p.name for p in key.parent.glob("api_key*") if p != key)
79
+ if beside:
80
+ text += f" Next to it is {', '.join(beside)}: if that's the key, rename it to {key.name}."
81
+ return text if host.folder_locked() else f"First lock the folder, which moves aside what's in it:\n{host.folder_detail()}\nThen: {text}"
82
+
83
+
84
+ def _client(http):
85
+ if http is None: # requests' own certificates don't hold a TLS inspection root that IT installed on this machine
86
+ truststore.inject_into_ssl()
87
+ http = requests.Session()
88
+ return KymoscopeClient(DEFAULT_BASE, "", http)
89
+
90
+
91
+ def _key() -> tuple[KymoscopeConfig | None, dict | None]:
92
+ """The key, or why it can't be used. Its text is never quoted."""
93
+ path = paths.key_file()
94
+ try:
95
+ return KymoscopeConfig.from_api_key(path.read_text(encoding="utf-8-sig").strip()), None # Notepad may save a BOM
96
+ except FileNotFoundError:
97
+ return None, fail("no_api_key", no_key_detail())
98
+ except OSError:
99
+ return None, fail("invalid_api_key", f"{path} is there, but this user can't read it. Give it read access:\n"
100
+ + host.handover(host.key_read_commands()))
101
+ except (ValueError, ConfigError): # ValueError: not UTF-8, as PowerShell 5's `>` writes
102
+ pass
103
+ return None, fail("invalid_api_key", no_key_detail())
104
+
105
+
106
+ def _scrub(text: str, cfg: KymoscopeConfig) -> str:
107
+ for part in filter(None, (cfg.secret, cfg.api_key)):
108
+ text = text.replace(part, "***")
109
+ return text
110
+
111
+
112
+ def _refused(what: str, e: RegistrationError, cfg: KymoscopeConfig) -> dict:
113
+ text = _scrub(str(e), cfg)
114
+ code = classify_kymoscope(text)
115
+ return fail(code, text) if code else unknown(what, text)
116
+
117
+
118
+ def _down(e: OSError, cfg: KymoscopeConfig) -> dict: # requests' exceptions are OSErrors
119
+ text = _scrub(repr(e), cfg)
120
+ return fail(classify_network(text) or "firewall", text)
121
+
122
+
123
+ BLOCK_PAGE = "Kymoscope's address answered with something that isn't Kymoscope, as a proxy's block page does."
124
+
125
+
126
+ def check_account(http=None) -> dict:
127
+ cfg, problem = _key()
128
+ if problem:
129
+ return problem
130
+ client = _client(http)
131
+ try:
132
+ client.mint_token(cfg.api_key)
133
+ except RegistrationError as e:
134
+ return _refused("Kymoscope refused the key check.", e, cfg)
135
+ except (ValueError, KeyError, TypeError): # first: requests' JSON error is an OSError too
136
+ return fail("proxy", BLOCK_PAGE)
137
+ except OSError as e:
138
+ return _down(e, cfg)
139
+ warning = host.others_can_read_warning(paths.key_file())
140
+ project = client.publisher["project"]
141
+ remember(project)
142
+ return ok(limits=client.limits, project=project, protection=PROJECT if project and project.get("e2ee") else _listed(project) + BY_SETTINGS,
143
+ **({"warning": warning} if warning else {}))
144
+
145
+
146
+ def relay_url(http=None) -> str | None:
147
+ """Where this key publishes, or None if that can't be known now. The token that comes with it goes no further."""
148
+ cfg, problem = _key()
149
+ if problem:
150
+ return None
151
+ try:
152
+ return _client(http).mint_token(cfg.api_key)[3]
153
+ except (RegistrationError, ValueError, KeyError, TypeError, AttributeError, OSError): # a proxy's page reads as any of the middle ones
154
+ return None
155
+
156
+
157
+ def _instant(text: str) -> float:
158
+ """Postgres trims trailing zeros, and Python 3.10's fromisoformat takes only 3 or 6 decimals."""
159
+ text = re.sub(r"\.(\d+)", lambda m: "." + m.group(1).ljust(6, "0")[:6], text.replace("Z", "+00:00"))
160
+ return datetime.fromisoformat(text).timestamp()
161
+
162
+
163
+ def stream_status(name: str, http=None) -> dict:
164
+ cfg, problem = _key()
165
+ if problem:
166
+ return problem
167
+ client = _client(http)
168
+ try:
169
+ token, *_ = client.mint_token(cfg.api_key)
170
+ body = client._publisher(token, {"action": "status"}, "status")
171
+ except RegistrationError as e:
172
+ return _refused("Kymoscope refused the status check.", e, cfg)
173
+ except (ValueError, KeyError, TypeError):
174
+ return fail("proxy", BLOCK_PAGE)
175
+ except OSError as e:
176
+ return _down(e, cfg)
177
+ row = next((s for s in body["streams"] if s["name"] == name), None)
178
+ if row is None:
179
+ return ok(found=False, streams=[s["name"] for s in body["streams"]])
180
+ if not row.get("last_seen_at"):
181
+ return ok(found=True, stream_id=row["id"], seen_ago_s=None, alive=False)
182
+ ago = _instant(body["now"]) - _instant(row["last_seen_at"])
183
+ return ok(found=True, stream_id=row["id"], seen_ago_s=ago, alive=ago < body["live_window_s"])