spatial-computing 0.17.0__tar.gz → 0.19.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 (145) hide show
  1. {spatial_computing-0.17.0/spatial_computing.egg-info → spatial_computing-0.19.0}/PKG-INFO +2 -1
  2. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/pyproject.toml +2 -2
  3. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/__init__.py +1 -1
  4. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/cli.py +8 -2
  5. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/kernel/__init__.py +1 -1
  6. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/kernel/dsl.py +101 -7
  7. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/db.py +6 -4
  8. spatial_computing-0.19.0/spatial/platform/invoice_rules.py +71 -0
  9. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/mailer.py +6 -2
  10. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/pdf.py +12 -5
  11. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/server.py +44 -4
  12. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/service.py +157 -51
  13. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/static/app.js +35 -10
  14. spatial_computing-0.19.0/spatial/platform/ubl.py +127 -0
  15. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/runtime/desktop/Dockerfile +1 -1
  16. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/runtime/desktop/__init__.py +40 -2
  17. {spatial_computing-0.17.0 → spatial_computing-0.19.0/spatial_computing.egg-info}/PKG-INFO +2 -1
  18. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial_computing.egg-info/SOURCES.txt +3 -0
  19. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial_computing.egg-info/requires.txt +1 -0
  20. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_interconnect.py +2 -1
  21. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_kernel.py +29 -0
  22. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_platform2.py +191 -1
  23. spatial_computing-0.19.0/tests/test_real_servers.py +176 -0
  24. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_runtime.py +40 -6
  25. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/LICENSE +0 -0
  26. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/README.md +0 -0
  27. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/setup.cfg +0 -0
  28. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/ai/__init__.py +0 -0
  29. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/ai/kvcache.py +0 -0
  30. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/ai/llm.py +0 -0
  31. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/compute/__init__.py +0 -0
  32. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/compute/cost.py +0 -0
  33. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/compute/detect.py +0 -0
  34. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/compute/monitor.py +0 -0
  35. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/compute/scheduler.py +0 -0
  36. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/compute/taskqueue.py +0 -0
  37. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/compute/worker.py +0 -0
  38. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/compute/workloads.py +0 -0
  39. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/core/__init__.py +0 -0
  40. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/core/auth.py +0 -0
  41. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/core/energy.py +0 -0
  42. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/core/ledger.py +0 -0
  43. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/core/model.py +0 -0
  44. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/core/protocol.py +0 -0
  45. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/core/registry.py +0 -0
  46. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/fabric/__init__.py +0 -0
  47. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/fabric/cuda.py +0 -0
  48. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/fabric/devices.py +0 -0
  49. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/fabric/metal.py +0 -0
  50. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/fabric/metal_mandel.swift +0 -0
  51. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/fabric/metal_run.swift +0 -0
  52. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/fleet/__init__.py +0 -0
  53. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/fleet/agent.py +0 -0
  54. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/fleet/alerts.py +0 -0
  55. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/fleet/dashboard.py +0 -0
  56. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/fleet/ha.py +0 -0
  57. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/fleet/hub.py +0 -0
  58. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/holographic/__init__.py +0 -0
  59. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/holographic/cgh.py +0 -0
  60. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/holographic/model.py +0 -0
  61. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/intelligence/__init__.py +0 -0
  62. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/intelligence/predictor.py +0 -0
  63. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/interconnect/__init__.py +0 -0
  64. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/interconnect/collectives.py +0 -0
  65. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/interconnect/comm.py +0 -0
  66. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/interconnect/model.py +0 -0
  67. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/interconnect/tasks.py +0 -0
  68. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/kernel/library.py +0 -0
  69. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/memory/__init__.py +0 -0
  70. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/memory/fararray.py +0 -0
  71. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/memory/pageserver.py +0 -0
  72. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/memory/secure.py +0 -0
  73. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/memory/shared.py +0 -0
  74. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/memory/tiered.py +0 -0
  75. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/__init__.py +0 -0
  76. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/billing.py +0 -0
  77. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/oidc.py +0 -0
  78. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/qr.py +0 -0
  79. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/security.py +0 -0
  80. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/static/fonts/DMMono-normal-400.woff2 +0 -0
  81. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/static/fonts/DMMono-normal-500.woff2 +0 -0
  82. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/static/fonts/InstrumentSerif-italic-400.woff2 +0 -0
  83. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/static/fonts/InstrumentSerif-normal-400.woff2 +0 -0
  84. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/static/fonts/Inter-normal-400.woff2 +0 -0
  85. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/static/fonts/Inter-normal-500.woff2 +0 -0
  86. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/static/fonts/Inter-normal-600.woff2 +0 -0
  87. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/static/fonts.css +0 -0
  88. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/static/index.html +0 -0
  89. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/static/logo.svg +0 -0
  90. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/static/style.css +0 -0
  91. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/totp.py +0 -0
  92. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/platform/vat.py +0 -0
  93. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/q/__init__.py +0 -0
  94. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/q/__main__.py +0 -0
  95. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/q/backends/__init__.py +0 -0
  96. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/q/codegen.py +0 -0
  97. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/q/compiler.py +0 -0
  98. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/q/ir.py +0 -0
  99. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/q/lexer.py +0 -0
  100. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/q/parser.py +0 -0
  101. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/q/qir.py +0 -0
  102. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/q/runtime.py +0 -0
  103. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/q/sim.py +0 -0
  104. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/runtime/__init__.py +0 -0
  105. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/runtime/desktop/start.sh +0 -0
  106. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/runtime/envs.py +0 -0
  107. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/runtime/inspect.py +0 -0
  108. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/runtime/microvm.py +0 -0
  109. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/runtime/planner.py +0 -0
  110. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/runtime/runner.py +0 -0
  111. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/runtime/toolchain.py +0 -0
  112. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/scientific/__init__.py +0 -0
  113. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/scientific/jobs.py +0 -0
  114. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/simulation/__init__.py +0 -0
  115. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/simulation/heat.py +0 -0
  116. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/simulation/nbody.py +0 -0
  117. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/unified/__init__.py +0 -0
  118. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/unified/model.py +0 -0
  119. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/unified/planner.py +0 -0
  120. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial/unified/providers.py +0 -0
  121. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
  122. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial_computing.egg-info/entry_points.txt +0 -0
  123. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/spatial_computing.egg-info/top_level.txt +0 -0
  124. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_auth.py +0 -0
  125. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_compute.py +0 -0
  126. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_core.py +0 -0
  127. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_dashboard.py +0 -0
  128. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_domains.py +0 -0
  129. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_engines.py +0 -0
  130. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_fabric.py +0 -0
  131. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_fleet.py +0 -0
  132. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_ha.py +0 -0
  133. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_hardening.py +0 -0
  134. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_memory.py +0 -0
  135. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_optimizer.py +0 -0
  136. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_platform.py +0 -0
  137. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_q.py +0 -0
  138. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_qr.py +0 -0
  139. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_quorum.py +0 -0
  140. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_sso.py +0 -0
  141. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_unified.py +0 -0
  142. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_v02.py +0 -0
  143. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_v03.py +0 -0
  144. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_v05.py +0 -0
  145. {spatial_computing-0.17.0 → spatial_computing-0.19.0}/tests/test_v07.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spatial-computing
3
- Version: 0.17.0
3
+ Version: 0.19.0
4
4
  Summary: Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)
5
5
  Author: Spatial Computing contributors
6
6
  License-Expression: Apache-2.0
@@ -29,6 +29,7 @@ Requires-Dist: qiskit>=2.0; extra == "qpu"
29
29
  Requires-Dist: qiskit-ibm-runtime>=0.40; extra == "qpu"
30
30
  Provides-Extra: dev
31
31
  Requires-Dist: pytest>=8; extra == "dev"
32
+ Requires-Dist: lxml>=5; extra == "dev"
32
33
  Dynamic: license-file
33
34
 
34
35
  # Spatial Computing
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "spatial-computing"
7
- version = "0.17.0"
7
+ version = "0.19.0"
8
8
  description = "Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -18,7 +18,7 @@ dependencies = ["numpy>=1.26,<2.2", "psutil>=5.9", "numba>=0.59,<0.62", "lz4>=4.
18
18
  quantum = ["qiskit>=2.0", "qiskit-aer>=0.17", "qiskit-qasm3-import>=0.5", "pyqir>=0.10"]
19
19
  build = ["ziglang>=0.13"]
20
20
  qpu = ["qiskit>=2.0", "qiskit-ibm-runtime>=0.40"]
21
- dev = ["pytest>=8"]
21
+ dev = ["pytest>=8", "lxml>=5"]
22
22
 
23
23
  [project.urls]
24
24
  Homepage = "https://spatial-computing-ecru.vercel.app"
@@ -3,4 +3,4 @@
3
3
  Status of every engine is declared in spatial.core.registry and must be backed
4
4
  by a test or benchmark before being set to OPERATIONAL.
5
5
  """
6
- __version__ = "0.17.0"
6
+ __version__ = "0.19.0"
@@ -111,6 +111,11 @@ def cmd_desktop(a):
111
111
  print(f"spatial: {e}", file=sys.stderr)
112
112
  return 1
113
113
  print(f"desktop ({a.app}, {d.runtime}), loopback only: {d.url}", flush=True)
114
+ for f in a.upload:
115
+ try:
116
+ print(f"uploaded {f} to {d.upload(f)}", flush=True)
117
+ except DesktopError as e:
118
+ print(f"spatial: {e}", file=sys.stderr)
114
119
  if d.view_url:
115
120
  print(f"view-only link (watch, cannot type or click): {d.view_url}", flush=True)
116
121
  print("Ctrl+C removes it", flush=True)
@@ -340,10 +345,11 @@ def main(argv=None):
340
345
  p.add_argument("--workload"); p.add_argument("--params", default="{}"); p.add_argument("--needs", default="{}")
341
346
  p.add_argument("--task-id", type=int)
342
347
  p.set_defaults(fn=cmd_fleet)
343
- p = sub.add_parser("desktop", help="run a graphical Linux app (xterm, xclock, mousepad) in a container and open it in your browser (noVNC, loopback only)")
344
- p.add_argument("app", nargs="?", default="xterm", choices=["xterm", "xclock", "mousepad"])
348
+ p = sub.add_parser("desktop", help="run a graphical Linux app (xterm, xclock, xcalc, mousepad) in a container and open it in your browser (noVNC, loopback only)")
349
+ p.add_argument("app", nargs="?", default="xterm", choices=["xterm", "xclock", "xcalc", "mousepad"])
345
350
  p.add_argument("--no-clipboard", action="store_true", help="no copy and paste between your machine and the desktop")
346
351
  p.add_argument("--view-link", action="store_true", help="also print a view-only link for people who only need to watch")
352
+ p.add_argument("--upload", action="append", default=[], metavar="FILE", help="copy this file into the desktop's ~/transfer folder (repeatable, 16 MiB each)")
347
353
  p.set_defaults(fn=cmd_desktop)
348
354
  p = sub.add_parser("platform", help="account service: sign up, sign in, apps, API keys, usage, billing (`spatial platform serve --help`)")
349
355
  p.add_argument("rest", nargs=argparse.REMAINDER)
@@ -1,3 +1,3 @@
1
- """Portable kernels: write once in a typed Python subset, run on CPU (Numba), Metal, or emit CUDA C."""
1
+ """Portable kernels: write once in a typed Python subset, run on CPU (Numba), Metal, or emit CUDA C, HIP, or Triton."""
2
2
  from .dsl import Kernel, KernelError, kernel # noqa: F401
3
3
  from . import library # noqa: F401
@@ -1,9 +1,11 @@
1
1
  """Portable kernel language: write a per-pixel kernel ONCE in a small, typed subset of Python and run
2
- it on the CPU (Numba), a Metal GPU (generated Metal Shading Language) or an NVIDIA GPU (generated
3
- CUDA C, never compiled or run here).
2
+ it on the CPU (Numba), a Metal GPU (generated Metal Shading Language), or emit CUDA C, HIP, or
3
+ **Triton** (OpenAI's Python GPU language) source for NVIDIA, AMD, or Triton's own targets.
4
4
 
5
5
  This is not a translator of CUDA and uses nothing from NVIDIA: the source language is ours, the
6
- back ends are generated from its AST. Same idea as Triton or SYCL at a much smaller scale.
6
+ back ends are generated from its AST. Same idea as Triton or SYCL at a much smaller scale; the
7
+ Triton back end itself is generated-only here (section "Triton" below) since no GPU Triton can
8
+ target is available on this machine.
7
9
 
8
10
  Kernel shape: def k(i: int, j: int, n: int, <params>) -> int (i, j = row, column; n = grid size)
9
11
  Params annotated int or float; floats are float32, ints are 32-bit on every back end
@@ -99,7 +101,8 @@ class Kernel:
99
101
  self._err(e, f"unknown function '{f}'")
100
102
  self._err(e, f"unsupported expression ({type(e).__name__})")
101
103
 
102
- RESERVED = {"out", "partial", "gid", "lid", "tgid", "ngroups", "blockIdx", "blockDim", "threadIdx", "gridDim", "total"}
104
+ RESERVED = {"out", "partial", "gid", "lid", "tgid", "ngroups", "blockIdx", "blockDim", "threadIdx", "gridDim", "total",
105
+ "tl", "triton", "out_ptr"}
103
106
 
104
107
  def _check_names(self, names) -> None:
105
108
  for nm in names:
@@ -279,6 +282,96 @@ class Kernel:
279
282
  Generated only: no AMD GPU, no ROCm here, so it has never been compiled or run."""
280
283
  return self.to_c(cuda=True, reduce=reduce, hip=True)
281
284
 
285
+ # ------------------------------------------------------------------ Triton (generated only: no Triton install, no
286
+ # NVIDIA/AMD/Intel GPU for it to target here; never loaded by triton.jit, never executed)
287
+ TL_MATH = {"sqrt": "tl.sqrt", "sin": "tl.sin", "cos": "tl.cos", "exp": "tl.exp", "log": "tl.log", "floor": "tl.math.floor"}
288
+
289
+ def _expr_triton(self, e, env) -> str:
290
+ t = lambda x: self.type_of(x, env)
291
+ rec = lambda x: self._expr_triton(x, env)
292
+ tof = lambda x: rec(x) if t(x) == "float" else f"({rec(x)}).to(tl.float32)"
293
+ if isinstance(e, ast.Constant):
294
+ return repr(float(e.value)) if isinstance(e.value, float) else str(e.value)
295
+ if isinstance(e, ast.Name):
296
+ return e.id
297
+ if isinstance(e, ast.UnaryOp):
298
+ if isinstance(e.op, ast.Not):
299
+ return f"({rec(e.operand)} == 0)"
300
+ return f"(-{rec(e.operand)})" if isinstance(e.op, ast.USub) else rec(e.operand)
301
+ if isinstance(e, ast.BinOp):
302
+ a, b = e.left, e.right
303
+ if isinstance(e.op, ast.Div):
304
+ return f"({tof(a)} / {tof(b)})"
305
+ if isinstance(e.op, ast.FloorDiv):
306
+ return f"({tof(a)} / {tof(b)}).to(tl.int32)" # truncates toward zero (a cast), like the C back ends; Triton's own // floors
307
+ op = {ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Mod: "%"}[type(e.op)]
308
+ if t(e) == "float":
309
+ return f"({tof(a)} {op} {tof(b)})"
310
+ return f"({rec(a)} {op} {rec(b)})" # int %: trusted to match C, like the CUDA back end trusts its compiler
311
+ if isinstance(e, ast.Compare):
312
+ op = {ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">=", ast.Eq: "==", ast.NotEq: "!="}[type(e.ops[0])]
313
+ a, b = e.left, e.comparators[0]
314
+ if "float" in (t(a), t(b)):
315
+ return f"({tof(a)} {op} {tof(b)})"
316
+ return f"({rec(a)} {op} {rec(b)})"
317
+ if isinstance(e, ast.BoolOp):
318
+ op = " & " if isinstance(e.op, ast.And) else " | " # tensors have no short-circuit and/or: boolify, then bitwise-combine
319
+ return "(" + op.join(f"({rec(v)} != 0)" for v in e.values) + ")"
320
+ fn, args = e.func.id, e.args
321
+ if fn in self.TL_MATH:
322
+ return f"{self.TL_MATH[fn]}({tof(args[0])})"
323
+ if fn == "int":
324
+ return f"({tof(args[0])}).to(tl.int32)" if t(args[0]) == "float" else rec(args[0])
325
+ if fn == "float":
326
+ return f"({rec(args[0])}).to(tl.float32)"
327
+ if fn == "abs":
328
+ return f"tl.abs({rec(args[0])})"
329
+ if fn in ("min", "max"):
330
+ fname = "tl.minimum" if fn == "min" else "tl.maximum"
331
+ return f"{fname}({tof(args[0])}, {tof(args[1])})" if t(e) == "float" else f"{fname}({rec(args[0])}, {rec(args[1])})"
332
+ raise KernelError("internal: unsupported expression in Triton code generation")
333
+
334
+ def _stmts_triton(self, stmts, env, ind) -> list[str]:
335
+ out = []
336
+ cast = lambda name, v: (lambda e: e if self.type_of(v, env) == env[name] else
337
+ (f"({e}).to(tl.float32)" if env[name] == "float" else f"({e}).to(tl.int32)"))(self._expr_triton(v, env))
338
+ for s in stmts:
339
+ if isinstance(s, ast.Assign):
340
+ out.append(f"{ind}{s.targets[0].id} = {cast(s.targets[0].id, s.value)}")
341
+ elif isinstance(s, ast.AugAssign):
342
+ op = {ast.Add: "+", ast.Sub: "-", ast.Mult: "*"}[type(s.op)]
343
+ v = s.target.id
344
+ out.append(f"{ind}{v} = {v} {op} {cast(v, s.value)}")
345
+ elif isinstance(s, ast.While):
346
+ out.append(f"{ind}while {self._expr_triton(s.test, env)} != 0:")
347
+ out += self._stmts_triton(s.body, env, ind + " ") or [ind + " pass"]
348
+ elif isinstance(s, ast.If):
349
+ out.append(f"{ind}if {self._expr_triton(s.test, env)} != 0:")
350
+ out += self._stmts_triton(s.body, env, ind + " ") or [ind + " pass"]
351
+ if s.orelse:
352
+ out.append(f"{ind}else:")
353
+ out += self._stmts_triton(s.orelse, env, ind + " ")
354
+ elif isinstance(s, ast.For):
355
+ out.append(f"{ind}for {s.target.id} in range({self._expr_triton(s.iter.args[0], env)}):")
356
+ out += self._stmts_triton(s.body, env, ind + " ") or [ind + " pass"]
357
+ return out
358
+
359
+ def to_triton(self) -> str:
360
+ """Triton (github.com/openai/triton, a Python GPU kernel language, now co-maintained across several GPU
361
+ vendors) source: one `tl.program_id` per output pixel, the same "one thread per pixel" shape as the CUDA
362
+ back end. GENERATED ONLY: Triton needs an NVIDIA, AMD, or Intel GPU (plus the `triton` package) to actually
363
+ trace and compile a kernel; none is available here, so this source has never been passed to `triton.jit`,
364
+ never compiled, never run. No reduction variant: Triton's own cross-program reduction (atomics or a second
365
+ pass) does not map onto the single-pass threadgroup/shared-memory shape used by `to_metal`/`to_cuda_c`."""
366
+ env = self._env()
367
+ body = self._stmts_triton(self.body, env, " ")
368
+ ret = self._expr_triton(self.ret, env)
369
+ sig = ", ".join(["out_ptr", "n"] + [p for p, _ in self.params])
370
+ lines = ["import triton", "import triton.language as tl", "", "", "@triton.jit", f"def {self.name}({sig}):",
371
+ " j = tl.program_id(axis=0)", " i = tl.program_id(axis=1)"] + body
372
+ lines.append(f" tl.store(out_ptr + i * n + j, ({ret}).to(tl.uint32))")
373
+ return "\n".join(lines) + "\n"
374
+
282
375
  def _expr_py(self, e, env) -> str:
283
376
  t = lambda x: self.type_of(x, env)
284
377
  rec = lambda x: self._expr_py(x, env)
@@ -370,7 +463,7 @@ class Kernel:
370
463
  if device == "metal":
371
464
  from ..fabric import metal
372
465
  return metal.run_kernel(self, n, params, reduce=True)
373
- if device in ("cuda", "hip"):
466
+ if device in ("cuda", "hip", "triton"):
374
467
  raise KernelError(f"the {device} back end only generates source; it has never been run on that hardware")
375
468
  raise KernelError(f"unknown device '{device}'")
376
469
 
@@ -385,8 +478,9 @@ class Kernel:
385
478
  if device == "metal":
386
479
  from ..fabric import metal
387
480
  return metal.run_kernel(self, n, params)
388
- if device == "cuda":
389
- raise KernelError("the CUDA back end only generates source (to_cuda_c); it has never been run on NVIDIA hardware")
481
+ if device in ("cuda", "hip", "triton"):
482
+ raise KernelError(f"the {device} back end only generates source (to_{'cuda_c' if device == 'cuda' else device}); "
483
+ f"it has never been run on {'NVIDIA' if device == 'cuda' else 'AMD' if device == 'hip' else 'any Triton-targeted'} hardware")
390
484
  raise KernelError(f"unknown device '{device}'")
391
485
 
392
486
  def _run_cpu(self, n, params, reduce: bool = False):
@@ -14,13 +14,14 @@ CREATE TABLE IF NOT EXISTS users(
14
14
  recovery TEXT NOT NULL DEFAULT '[]', personal_org INTEGER);
15
15
  CREATE TABLE IF NOT EXISTS orgs(
16
16
  id INTEGER PRIMARY KEY, name TEXT NOT NULL, created REAL NOT NULL, personal INTEGER NOT NULL DEFAULT 0,
17
- billing_name TEXT NOT NULL DEFAULT '', billing_address TEXT NOT NULL DEFAULT '', billing_country TEXT NOT NULL DEFAULT '', vat_id TEXT NOT NULL DEFAULT '', vat_status TEXT NOT NULL DEFAULT '');
18
- CREATE TABLE IF NOT EXISTS members(org_id INTEGER NOT NULL, user_id INTEGER NOT NULL, role TEXT NOT NULL, created REAL NOT NULL, PRIMARY KEY(org_id, user_id));
17
+ billing_name TEXT NOT NULL DEFAULT '', billing_address TEXT NOT NULL DEFAULT '', billing_country TEXT NOT NULL DEFAULT '', vat_id TEXT NOT NULL DEFAULT '', vat_status TEXT NOT NULL DEFAULT '',
18
+ billing_city TEXT NOT NULL DEFAULT '', billing_postal TEXT NOT NULL DEFAULT '', billing_email TEXT NOT NULL DEFAULT '');
19
+ CREATE TABLE IF NOT EXISTS members(org_id INTEGER NOT NULL, user_id INTEGER NOT NULL, role TEXT NOT NULL, created REAL NOT NULL, app_ids TEXT, PRIMARY KEY(org_id, user_id));
19
20
  CREATE TABLE IF NOT EXISTS org_roles(org_id INTEGER NOT NULL, name TEXT NOT NULL, perms TEXT NOT NULL, created REAL NOT NULL, PRIMARY KEY(org_id, name));
20
21
  CREATE TABLE IF NOT EXISTS sso_states(state_hash TEXT PRIMARY KEY, nonce TEXT NOT NULL, verifier TEXT NOT NULL, expires REAL NOT NULL, ip TEXT);
21
22
  CREATE TABLE IF NOT EXISTS invites(
22
23
  id INTEGER PRIMARY KEY, org_id INTEGER NOT NULL, email TEXT NOT NULL, role TEXT NOT NULL, token_hash TEXT UNIQUE NOT NULL, invited_by INTEGER NOT NULL,
23
- created REAL NOT NULL, expires REAL NOT NULL, accepted REAL);
24
+ created REAL NOT NULL, expires REAL NOT NULL, accepted REAL, app_ids TEXT);
24
25
  CREATE TABLE IF NOT EXISTS verifications(token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, expires REAL NOT NULL);
25
26
  CREATE TABLE IF NOT EXISTS challenges(token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, expires REAL NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, ip TEXT, ua TEXT);
26
27
  CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY, value TEXT NOT NULL, updated REAL NOT NULL);
@@ -87,7 +88,8 @@ class DB:
87
88
  "apps": [("org_id", "INTEGER")],
88
89
  "invoices": [("org_id", "INTEGER"), ("number", "TEXT"), ("subtotal_usd", "REAL"), ("tax_rate", "REAL"), ("tax_usd", "REAL"), ("billing", "TEXT"), ("seller", "TEXT"),
89
90
  ("payment_ref", "TEXT"), ("credited_usd", "REAL NOT NULL DEFAULT 0")],
90
- "orgs": [("vat_status", "TEXT NOT NULL DEFAULT ''")],
91
+ "orgs": [("vat_status", "TEXT NOT NULL DEFAULT ''"), ("billing_city", "TEXT NOT NULL DEFAULT ''"), ("billing_postal", "TEXT NOT NULL DEFAULT ''"), ("billing_email", "TEXT NOT NULL DEFAULT ''")],
92
+ "members": [("app_ids", "TEXT")], "invites": [("app_ids", "TEXT")],
91
93
  "outbox": [("attempts", "INTEGER NOT NULL DEFAULT 0"), ("next_try", "REAL NOT NULL DEFAULT 0"), ("last_error", "TEXT")]}
92
94
 
93
95
  def _migrate(self) -> None:
@@ -0,0 +1,71 @@
1
+ """What an invoice must carry, by the seller's country, and the legal mentions printed on it. A SMALL table for the countries a
2
+ first customer is most likely to be in (FR, DE, ES, IT, NL, BE, GB): it covers the mandatory fields commonly listed by those tax
3
+ authorities, not every rule. It is a checklist for the operator, not legal advice."""
4
+ from __future__ import annotations
5
+
6
+ COMPANY_FIELDS = {
7
+ "name": "company name", "address": "address", "city": "city", "postal_code": "postal code", "country": "country",
8
+ "vat_id": "VAT identification number", "registration_no": "company registration number", "legal_form": "legal form",
9
+ "share_capital": "share capital", "tax_no": "national tax number", "iban": "IBAN", "bic": "BIC",
10
+ }
11
+ COMPANY_FORMS_WITH_CAPITAL = {"SAS", "SARL", "SA", "SASU", "EURL", "SCA", "SNC", "GMBH", "AG", "UG", "SL", "SLU", "SRL", "BV", "NV", "LTD"}
12
+
13
+ # fields that must be present on every invoice, by seller country (the base list applies everywhere)
14
+ BASE = ["name", "address", "city", "postal_code", "country"]
15
+ BY_COUNTRY = {
16
+ "FR": ["registration_no", "legal_form"], # SIREN and form; capital added below for companies
17
+ "DE": [], # vat_id OR tax_no, checked separately
18
+ "ES": ["vat_id"], "IT": ["vat_id"], "NL": ["vat_id", "registration_no"], "BE": ["vat_id"],
19
+ "GB": ["registration_no"], # company number for limited companies
20
+ }
21
+
22
+ REVERSE_CHARGE = {
23
+ "FR": "Autoliquidation de la TVA (art. 283-2 du CGI, art. 196 de la directive 2006/112/CE).",
24
+ "DE": "Steuerschuldnerschaft des Leistungsempfängers (Reverse Charge, Art. 196 MwStSystRL).",
25
+ "ES": "Inversión del sujeto pasivo (art. 196 Directiva 2006/112/CE).",
26
+ "IT": "Inversione contabile (art. 196 Direttiva 2006/112/CE).",
27
+ "NL": "BTW verlegd (art. 196 Richtlijn 2006/112/EG).",
28
+ "BE": "Autoliquidation / BTW verlegd (art. 196 directive 2006/112/CE).",
29
+ }
30
+ REVERSE_CHARGE_DEFAULT = "Reverse charge: VAT to be accounted for by the customer (Article 196, Directive 2006/112/EC)."
31
+
32
+
33
+ def required(company: dict, taxed: bool) -> list[str]:
34
+ """Names of company fields that are required but empty."""
35
+ cc = (company.get("country") or "").upper()
36
+ need = list(BASE) + list(BY_COUNTRY.get(cc, []))
37
+ if taxed and "vat_id" not in need:
38
+ need.append("vat_id")
39
+ if cc == "FR" and (company.get("legal_form") or "").upper().replace(" ", "") in COMPANY_FORMS_WITH_CAPITAL:
40
+ need.append("share_capital")
41
+ missing = [f for f in need if not (company.get(f) or "").strip()]
42
+ if cc == "DE" and not ((company.get("vat_id") or "").strip() or (company.get("tax_no") or "").strip()):
43
+ missing.append("vat_id or tax_no")
44
+ return missing
45
+
46
+
47
+ def reverse_charge_text(seller_country: str) -> str:
48
+ return REVERSE_CHARGE.get((seller_country or "").upper(), REVERSE_CHARGE_DEFAULT)
49
+
50
+
51
+ def mentions(seller: dict, customer: dict, tax_rate: float, reverse_charge: bool, due: str) -> list[str]:
52
+ """Mentions printed at the foot of the invoice."""
53
+ out = []
54
+ cc = (seller.get("country") or "").upper()
55
+ if reverse_charge:
56
+ out.append(reverse_charge_text(cc))
57
+ elif tax_rate == 0 and seller.get("tax_exempt_note"):
58
+ out.append(seller["tax_exempt_note"])
59
+ if cc == "FR":
60
+ out.append("Pénalités de retard : trois fois le taux d'intérêt légal. Indemnité forfaitaire pour frais de recouvrement : 40 EUR (art. L441-10 du Code de commerce).")
61
+ if seller.get("registration_no"):
62
+ form = " ".join(x for x in [seller.get("legal_form"), ("au capital de " + seller["share_capital"]) if seller.get("share_capital") else ""] if x)
63
+ out.append(f"{seller.get('name', '')} {form} - SIREN {seller['registration_no']}".strip())
64
+ elif cc == "DE":
65
+ out.append("Leistungszeitraum: siehe Rechnungsperiode. " + ("Steuernummer: " + seller["tax_no"] if seller.get("tax_no") else ""))
66
+ elif cc == "GB" and seller.get("registration_no"):
67
+ out.append(f"Registered in England and Wales, company number {seller['registration_no']}.")
68
+ out.append(f"Payment due by {due}.")
69
+ if seller.get("legal_footer"):
70
+ out.append(seller["legal_footer"])
71
+ return [m.strip() for m in out if m.strip()]
@@ -19,16 +19,20 @@ class Mailer:
19
19
  self.deliver(mid)
20
20
  return mid
21
21
 
22
+ def _tls(self) -> ssl.SSLContext:
23
+ """Verified TLS: system CAs, or the operator's own CA file (a private relay with an internal certificate). Never unverified."""
24
+ return ssl.create_default_context(cafile=self.smtp.get("ca_file") or None)
25
+
22
26
  def _send(self, to: str, subject: str, body: str) -> None:
23
27
  c = self.smtp
24
28
  m = EmailMessage(); m["From"], m["To"], m["Subject"] = c["from"], to, subject; m.set_content(body)
25
29
  if c.get("ssl"):
26
- s = smtplib.SMTP_SSL(c["host"], c.get("port", 465), timeout=15, context=ssl.create_default_context())
30
+ s = smtplib.SMTP_SSL(c["host"], c.get("port", 465), timeout=15, context=self._tls())
27
31
  else:
28
32
  s = smtplib.SMTP(c["host"], c.get("port", 587), timeout=15)
29
33
  with s:
30
34
  if c.get("starttls", True) and not c.get("ssl"):
31
- s.starttls(context=ssl.create_default_context())
35
+ s.starttls(context=self._tls())
32
36
  if c.get("user"):
33
37
  s.login(c["user"], c["password"])
34
38
  s.send_message(m)
@@ -59,7 +59,9 @@ def invoice_pdf(inv: dict) -> bytes:
59
59
  pg.text(R - 150, 790, "CREDIT NOTE" if credit else "INVOICE", 18, True)
60
60
  pg.text(R - 150, 770, "No. " + inv["number"], 10, True)
61
61
  pg.text(R - 150, 757, "Issued: " + inv["issued"], 9)
62
- pg.text(R - 150, 744, "Period: " + inv["period"], 9)
62
+ pg.text(R - 150, 744, "Period: " + inv.get("period_start", inv["period"]) + (" to " + inv["period_end"] if inv.get("period_end") else ""), 9)
63
+ if inv.get("due") and inv.get("kind") != "credit":
64
+ pg.text(R - 150, 718, "Due: " + inv["due"], 9, True)
63
65
  pg.text(R - 150, 731, ("Refers to " + inv["refers_to"]) if credit else "Status: " + inv["status"].upper(), 9, True)
64
66
  y = 690
65
67
  pg.text(L, y, "Billed to", 9, True)
@@ -78,9 +80,14 @@ def invoice_pdf(inv: dict) -> bytes:
78
80
  y -= 14; pg.line(L, y, R, y)
79
81
  for label, val, bold in (("Subtotal", inv["subtotal"], False), (f"Tax ({inv['tax_rate']:g}%)", inv["tax"], False), ("Total", inv["total"], True)):
80
82
  y -= 18; pg.text(400, y, label, 10, bold); pg.text(490, y, f"{val:.2f} {cur}", 10, bold)
81
- if inv.get("note"):
82
- y -= 40
83
- for ln in inv["note"].splitlines()[:5]:
84
- pg.text(L, y, ln, 9); y -= 12
83
+ y -= 30
84
+ pay = [x for x in [("IBAN: " + inv["seller"]["iban"]) if inv["seller"].get("iban") else "", ("BIC: " + inv["seller"]["bic"]) if inv["seller"].get("bic") else ""] if x]
85
+ if pay and inv.get("kind") != "credit":
86
+ pg.text(L, y, "Payment details", 9, True); y -= 13
87
+ pg.text(L, y, " ".join(pay), 9); y -= 18
88
+ for ln in ([inv["note"]] if inv.get("note") else []) + list(inv.get("mentions", [])):
89
+ while ln:
90
+ pg.text(L, y, ln[:105], 8); ln = ln[105:]; y -= 11
91
+ y -= 2
85
92
  pg.text(L, 40, "Usage is metered per finished task on the Spatial Computing fleet.", 8)
86
93
  return build([pg], f"{'Credit note' if credit else 'Invoice'} {inv['number']}")
@@ -70,6 +70,8 @@ def make_handler(pf: Platform, secure_cookies: bool):
70
70
  route("GET", "/api/admin/invoices", "admin_invoices")
71
71
  route("POST", r"/api/admin/invoices/(\d+)/credit", "admin_credit")
72
72
  route("GET", r"/api/credit-notes/(\d+)/pdf", "credit_pdf")
73
+ route("GET", r"/api/invoices/(\d+)/ubl", "invoice_ubl")
74
+ route("GET", r"/api/credit-notes/(\d+)/ubl", "credit_ubl")
73
75
  route("GET", "/api/admin/mail", "admin_mail")
74
76
  route("POST", "/api/login/2fa", "login_2fa", auth=False, csrf=False)
75
77
  route("GET", "/api/sso/config", "sso_config", auth=False)
@@ -338,7 +340,7 @@ def make_handler(pf: Platform, secure_cookies: bool):
338
340
 
339
341
  def h_invites_create(self, g, u, s):
340
342
  d = self._data()
341
- self._json(201, {"invite": pf.invite(s[0], d.get("email"), d.get("role", "member"))})
343
+ self._json(201, {"invite": pf.invite(s[0], d.get("email"), d.get("role", "member"), d.get("apps"))})
342
344
 
343
345
  def h_invites_revoke(self, g, u, s):
344
346
  pf.revoke_invite(s[0], int(g[0]))
@@ -348,7 +350,11 @@ def make_handler(pf: Platform, secure_cookies: bool):
348
350
  self._json(200, {"org": pf.accept_invite(s[0], self._data().get("token"))})
349
351
 
350
352
  def h_members_role(self, g, u, s):
351
- pf.set_member_role(s[0], int(g[0]), self._data().get("role"))
353
+ d = self._data()
354
+ if "role" in d:
355
+ pf.set_member_role(s[0], int(g[0]), d["role"])
356
+ if "apps" in d:
357
+ pf.set_member_apps(s[0], int(g[0]), d["apps"])
352
358
  self._json(200, {"ok": True})
353
359
 
354
360
  def h_members_remove(self, g, u, s):
@@ -378,6 +384,14 @@ def make_handler(pf: Platform, secure_cookies: bool):
378
384
  d = self._data()
379
385
  self._json(201, {"credit_note": pf.admin_credit_note(s[0], int(g[0]), d.get("amount_usd"), d.get("reason"))})
380
386
 
387
+ def h_invoice_ubl(self, g, u, s):
388
+ xml, name = pf.invoice_ubl(s[0], int(g[0]))
389
+ self._send(200, xml, "application/xml; charset=utf-8", {"Content-Disposition": f'attachment; filename="{name}"'})
390
+
391
+ def h_credit_ubl(self, g, u, s):
392
+ xml, name = pf.credit_note_ubl(s[0], int(g[0]))
393
+ self._send(200, xml, "application/xml; charset=utf-8", {"Content-Disposition": f'attachment; filename="{name}"'})
394
+
381
395
  def h_credit_pdf(self, g, u, s):
382
396
  pdf, name = pf.credit_note_pdf(s[0], int(g[0]))
383
397
  self._send(200, pdf, "application/pdf", {"Content-Disposition": f'attachment; filename="{name}"'})
@@ -539,6 +553,7 @@ def main(argv=None):
539
553
  ap.add_argument("--smtp-user")
540
554
  ap.add_argument("--smtp-from", default="no-reply@localhost")
541
555
  ap.add_argument("--smtp-ssl", action="store_true", help="implicit TLS (port 465) instead of STARTTLS")
556
+ ap.add_argument("--smtp-ca-file", help="CA certificate (PEM) that signed the SMTP server's certificate, for a private relay; certificates are always verified")
542
557
  ap.add_argument("--smtp-no-starttls", action="store_true", help="plain SMTP, for a local relay only")
543
558
  ap.add_argument("--oidc-issuer", help="OpenID Connect provider URL (enables 'Sign in with ...'); the client secret goes in OIDC_CLIENT_SECRET")
544
559
  ap.add_argument("--oidc-client-id")
@@ -546,16 +561,41 @@ def main(argv=None):
546
561
  ap.add_argument("--oidc-domains", default="", help="comma list: only these e-mail domains may sign in this way")
547
562
  ap.add_argument("--oidc-no-create", action="store_true", help="only existing accounts may sign in this way")
548
563
  ap.add_argument("--require-verified", choices=["auto", "yes", "no"], default="auto", help="e-mail verification before keys and jobs (auto: only when SMTP is configured)")
564
+ ap.add_argument("--embedded-hub", action="store_true", help="run the fleet hub inside this process (one container, one command): needs --master-key-file")
565
+ ap.add_argument("--hub-listen", default="127.0.0.1:7700", help="with --embedded-hub: host:port the hub listens on (use 0.0.0.0:7700 for a container; remote binding is allowed only with --allow-remote)")
549
566
  ap.add_argument("--dev-outbox", action="store_true", help="expose /api/dev/outbox (reset links) for local development")
550
567
  a = ap.parse_args(argv)
551
568
  Path(a.db).parent.mkdir(parents=True, exist_ok=True)
569
+ if not a.master_key_file and os.environ.get("HUB_MASTER_KEY"): # hosts that give secrets as environment variables only
570
+ kf = Path(a.db).with_name("master.key")
571
+ fd = os.open(kf, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
572
+ with os.fdopen(fd, "w") as f:
573
+ f.write(os.environ["HUB_MASTER_KEY"])
574
+ a.master_key_file = str(kf)
575
+ embedded = None
576
+ if a.embedded_hub:
577
+ if not a.master_key_file:
578
+ raise SystemExit("--embedded-hub needs --master-key-file (the hub authenticates every call with credentials this service issues)")
579
+ if a.hub:
580
+ raise SystemExit("--embedded-hub and --hub are exclusive")
581
+ from ..fleet.hub import serve_hub
582
+ hh, _, hp = a.hub_listen.rpartition(":")
583
+ a.usage_file = a.usage_file or str(Path(a.db).with_name("hub-usage.jsonl"))
584
+ a.revoked_file = a.revoked_file or str(Path(a.db).with_name("hub-revoked.txt"))
585
+ hub_auth = authorizer_from_file(a.master_key_file, revoked_file=a.revoked_file)
586
+ hsrv, hub = serve_hub(None, hh or "127.0.0.1", int(hp), a.allow_remote, hub_auth)
587
+ hub.usage_path = a.usage_file
588
+ hsrv.start()
589
+ a.hub = f"127.0.0.1:{hsrv.port}"
590
+ a.hub_public = a.hub_public or f"{hh or '127.0.0.1'}:{hsrv.port}"
591
+ embedded = hsrv
552
592
  auth = authorizer_from_file(a.master_key_file, revoked_file=a.revoked_file) if a.master_key_file else None
553
593
  smtp = None
554
594
  host = a.smtp_host or os.environ.get("SMTP_HOST")
555
595
  if host:
556
596
  smtp = {"host": host, "port": a.smtp_port if a.smtp_host else int(os.environ.get("SMTP_PORT", "587")), "user": a.smtp_user or os.environ.get("SMTP_USER"),
557
597
  "password": os.environ.get("SMTP_PASSWORD"), "from": a.smtp_from if a.smtp_host else os.environ.get("SMTP_FROM", "no-reply@localhost"),
558
- "ssl": a.smtp_ssl, "starttls": not a.smtp_no_starttls}
598
+ "ssl": a.smtp_ssl, "starttls": not a.smtp_no_starttls, "ca_file": a.smtp_ca_file or os.environ.get("SMTP_CA_FILE")}
559
599
  pf = Platform(DB(a.db), auth, a.hub, a.hub_public, a.usage_file, a.revoked_file, Pricing.load(a.pricing_file),
560
600
  Stripe(os.environ.get("STRIPE_SECRET_KEY"), os.environ.get("STRIPE_WEBHOOK_SECRET")),
561
601
  a.public_url or f"http://{a.host}:{a.port}", smtp=smtp, docs_url=a.docs_url,
@@ -580,7 +620,7 @@ def main(argv=None):
580
620
  time.sleep(10)
581
621
  threading.Thread(target=ingest_loop, daemon=True).start()
582
622
  print(f"platform on http://{a.host}:{srv.server_address[1]}/ (payments: {'Stripe' if pf.stripe.configured else 'not configured'}; "
583
- f"hub keys: {'yes' if auth else 'no'})", flush=True)
623
+ f"hub keys: {'yes' if auth else 'no'}" + (f"; embedded hub on {a.hub_public}" if embedded else "") + ")", flush=True)
584
624
  srv.serve_forever()
585
625
 
586
626