modelos-secure 0.3.9__py3-none-win_amd64.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 (32) hide show
  1. modelos_secure/__init__.py +0 -0
  2. modelos_secure/_cli/README.md +63 -0
  3. modelos_secure/_cli/assets/login-D0M0qeoI.js +1 -0
  4. modelos_secure/_cli/assets/login-UmFsH3I5.js +936 -0
  5. modelos_secure/_cli/cli.js +23653 -0
  6. modelos_secure/_cli/hook/clients.mjs +278 -0
  7. modelos_secure/_cli/hook/edge.mjs +411 -0
  8. modelos_secure/_cli/hook/hook.mjs +338 -0
  9. modelos_secure/_cli/hook/hosts.d.mts +2 -0
  10. modelos_secure/_cli/hook/hosts.mjs +26 -0
  11. modelos_secure/_cli/hook/loader.mjs +12 -0
  12. modelos_secure/_cli/hook/rewrite.mjs +95 -0
  13. modelos_secure/_cli/node.exe +4 -0
  14. modelos_secure/_cli/python/modelos_secure/__init__.py +0 -0
  15. modelos_secure/_cli/python/modelos_secure/clients.py +457 -0
  16. modelos_secure/_cli/python/modelos_secure/edge.py +365 -0
  17. modelos_secure/_cli/python/modelos_secure/hook.py +574 -0
  18. modelos_secure/_cli/python/requirements.txt +0 -0
  19. modelos_secure/_cli/python/sitecustomize.py +13 -0
  20. modelos_secure/_cli/wasm/tree-sitter-javascript.wasm +0 -0
  21. modelos_secure/_cli/wasm/tree-sitter-python.wasm +0 -0
  22. modelos_secure/_cli/wasm/tree-sitter-tsx.wasm +0 -0
  23. modelos_secure/_cli/wasm/tree-sitter-typescript.wasm +0 -0
  24. modelos_secure/_cli/wasm/web-tree-sitter.wasm +0 -0
  25. modelos_secure/_launcher.py +11 -0
  26. modelos_secure/clients.py +457 -0
  27. modelos_secure/edge.py +365 -0
  28. modelos_secure/hook.py +574 -0
  29. modelos_secure-0.3.9.dist-info/METADATA +71 -0
  30. modelos_secure-0.3.9.dist-info/RECORD +32 -0
  31. modelos_secure-0.3.9.dist-info/WHEEL +4 -0
  32. modelos_secure-0.3.9.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,574 @@
1
+ """The hooks for Python apps: the same behaviour and control protocol as hooks/node/src/hook.mjs.
2
+
3
+ Standard library only, Python 3.10+. Customers run this, not us, so when it meets something it
4
+ does not understand it leaves the app's own behaviour alone. docs/spec/05-scan-and-cli.md#5-start
5
+ """
6
+
7
+ import copy
8
+ import functools
9
+ import http.server
10
+ import inspect
11
+ import json
12
+ import os
13
+ import random
14
+ import socket
15
+ import sys
16
+ import threading
17
+ import types
18
+ import urllib.parse
19
+
20
+ from modelos_secure import clients, edge
21
+
22
+ _MARK = "__modelos_secure_wrapped__"
23
+
24
+ _tools = {}
25
+ _ways_in = {}
26
+ _files = set()
27
+ _wrapped = []
28
+ _noted = set()
29
+ _state = None
30
+
31
+
32
+ def _fresh_state():
33
+ return {
34
+ "attempt": None,
35
+ "held": [],
36
+ "modelCalls": [],
37
+ "ran": [],
38
+ "plantDelivered": False,
39
+ "retrieved": [],
40
+ "edge": [],
41
+ # The app's own model calls that failed: an attempt with one is an error, never a hold.
42
+ "modelFailures": [],
43
+ }
44
+
45
+
46
+ def _note(error):
47
+ text = f"modelos-secure hook: {error}"
48
+ if text not in _noted:
49
+ _noted.add(text)
50
+ print(text, file=sys.stderr)
51
+
52
+
53
+ def _safely(fn, *args, fallback=None):
54
+ """Runs a piece of the hook. If it fails, the app carries on as if the hook were not there."""
55
+ try:
56
+ return fn(*args)
57
+ except Exception as error:
58
+ _note(repr(error))
59
+ return fallback
60
+
61
+
62
+ # Planted content and canaries, into whatever shape the way in returns.
63
+
64
+
65
+ def _longest_string_key(fields):
66
+ best = None
67
+ for key, value in fields.items():
68
+ if isinstance(value, str) and (best is None or len(value) > len(fields[best])):
69
+ best = key
70
+ return best
71
+
72
+
73
+ def _plant_into(result, text):
74
+ """Returns result itself, so nothing is delivered, when it is a shape with no place for text."""
75
+ if result is None:
76
+ return text
77
+ if isinstance(result, str):
78
+ return f"{result}\n\n{text}"
79
+ if isinstance(result, (list, tuple)):
80
+ if len(result) == 0 or isinstance(result[0], str):
81
+ return [*result, text]
82
+ planted = _plant_into(result[0], text)
83
+ return result if planted is result[0] else [*result, planted]
84
+ if isinstance(result, dict):
85
+ for key, value in result.items():
86
+ if isinstance(value, list):
87
+ return {**result, key: _plant_into(value, text)}
88
+ key = _longest_string_key(result)
89
+ return {**result, key: f"{result[key]}\n\n{text}"} if key else {**result, "note": text}
90
+ fields = getattr(result, "__dict__", None)
91
+ if fields:
92
+ # Objects with text in them, such as a LangChain Document.
93
+ key = _longest_string_key(fields)
94
+ if key:
95
+ planted = copy.copy(result)
96
+ setattr(planted, key, f"{fields[key]}\n\n{text}")
97
+ return planted
98
+ return result
99
+
100
+
101
+ def _add_canary(result, record):
102
+ if isinstance(result, str):
103
+ return f"{result}\nCustomer reference: {record}"
104
+ if isinstance(result, dict):
105
+ return {**result, "customer_reference": record}
106
+ return result
107
+
108
+
109
+ def _passage_text(result):
110
+ """Q2 grades answers against what was really read, so this is the text and not the way in's name."""
111
+ try:
112
+ if isinstance(result, str):
113
+ text = result
114
+ elif isinstance(result, (list, tuple)):
115
+ text = "\n".join(str(getattr(item, "page_content", item)) for item in result)
116
+ else:
117
+ text = str(getattr(result, "page_content", result))
118
+ except Exception: # A reading we cannot understand must never break the customer's app.
119
+ return ""
120
+ return text[:8000]
121
+
122
+
123
+ def _after_run(name, result):
124
+ attempt = _state["attempt"]
125
+ way_in = _ways_in.get(name)
126
+ out = result
127
+ if way_in is not None and attempt:
128
+ _state["retrieved"].append(_passage_text(result))
129
+ plant = attempt.get("plant")
130
+ if plant and plant.get("wayIn") == way_in["name"]:
131
+ out = _plant_into(out, plant["text"])
132
+ _state["plantDelivered"] = out is not result
133
+ if attempt and _tools.get(name, {}).get("can") == "read private data":
134
+ out = _add_canary(out, attempt["canaries"]["record"])
135
+ return out
136
+
137
+
138
+ def _finish(name, result):
139
+ # A generator hands its content out later, where nothing here can change it.
140
+ if inspect.isgenerator(result) or inspect.isasyncgen(result):
141
+ return result
142
+ return _safely(_after_run, name, result, fallback=result)
143
+
144
+
145
+ # The one place a tool call passes through. Held tools never run.
146
+
147
+
148
+ def _args_object(entry, args, kwargs):
149
+ if len(args) == 1 and isinstance(args[0], dict) and not kwargs:
150
+ return dict(args[0])
151
+ if entry["signature"] is not None:
152
+ bound = entry["signature"].bind_partial(*args, **kwargs)
153
+ out = {}
154
+ for key, value in bound.arguments.items():
155
+ kind = entry["signature"].parameters[key].kind
156
+ if kind is inspect.Parameter.VAR_KEYWORD:
157
+ out.update(value)
158
+ elif key not in ("self", "cls"):
159
+ out[key] = value
160
+ return out
161
+ params = _tools.get(entry["name"], {}).get("params") or []
162
+ named = {params[i] if i < len(params) else f"arg{i}": arg for i, arg in enumerate(args)}
163
+ return {**named, **kwargs}
164
+
165
+
166
+ def _hold(entry, args, kwargs):
167
+ """A realistic answer, so the app carries on as if the action happened."""
168
+ name = entry["name"]
169
+ recorded = _safely(_args_object, entry, args, kwargs, fallback={"args": list(args), **kwargs})
170
+ _state["held"].append({"tool": name, "args": recorded})
171
+ return {"status": "ok", "id": f"{name}-{random.randint(10000, 99999)}"}
172
+
173
+
174
+ def _is_held(name):
175
+ return _tools.get(name, {}).get("mode") == "hold"
176
+
177
+
178
+ def _call(key, args, kwargs):
179
+ entry = _wrapped[key]
180
+ name = entry["name"]
181
+ if _is_held(name):
182
+ held = _hold(entry, args, kwargs)
183
+ if inspect.isasyncgenfunction(entry["original"]):
184
+ return _async_once(held)
185
+ return iter([held]) if inspect.isgeneratorfunction(entry["original"]) else held
186
+ if name in _tools:
187
+ _state["ran"].append(name)
188
+ running = edge.current_tool.set(name)
189
+ try:
190
+ result = entry["original"](*args, **kwargs)
191
+ finally:
192
+ edge.current_tool.reset(running)
193
+ if inspect.isawaitable(result):
194
+ return _finish_later(name, result)
195
+ return _finish(name, result)
196
+
197
+
198
+ async def _acall(key, args, kwargs):
199
+ entry = _wrapped[key]
200
+ name = entry["name"]
201
+ if _is_held(name):
202
+ return _hold(entry, args, kwargs)
203
+ if name in _tools:
204
+ _state["ran"].append(name)
205
+ running = edge.current_tool.set(name)
206
+ try:
207
+ return _finish(name, await entry["original"](*args, **kwargs))
208
+ finally:
209
+ edge.current_tool.reset(running)
210
+
211
+
212
+ async def _finish_later(name, awaitable):
213
+ return _finish(name, await awaitable)
214
+
215
+
216
+ async def _async_once(value):
217
+ yield value
218
+
219
+
220
+ # Wrapping. Replacing the function's code in place, rather than the name in its module, means that
221
+ # every reference to the function now runs the wrapper: other modules that imported it, a
222
+ # {"send_email": send_email} table, the list given to a model client, a LangChain tool.
223
+
224
+
225
+ def _signature_of(fn):
226
+ try:
227
+ return inspect.signature(fn)
228
+ except (TypeError, ValueError, NameError):
229
+ return None
230
+
231
+
232
+ def _register(name, original, signature):
233
+ _wrapped.append({"name": name, "original": original, "signature": signature})
234
+ return len(_wrapped) - 1
235
+
236
+
237
+ _TRAMPOLINE = """def _(*args, **kwargs):
238
+ return __import__("sys").modules["modelos_secure.hook"]._call({key}, args, kwargs)
239
+ """
240
+ _ASYNC_TRAMPOLINE = """async def _(*args, **kwargs):
241
+ return await __import__("sys").modules["modelos_secure.hook"]._acall({key}, args, kwargs)
242
+ """
243
+
244
+
245
+ def _swap_code(name, fn):
246
+ signature = _signature_of(fn)
247
+ original = types.FunctionType(
248
+ fn.__code__, fn.__globals__, fn.__name__, fn.__defaults__, fn.__closure__
249
+ )
250
+ original.__kwdefaults__ = fn.__kwdefaults__
251
+ key = _register(name, original, signature)
252
+ source = _ASYNC_TRAMPOLINE if inspect.iscoroutinefunction(fn) else _TRAMPOLINE
253
+ module_code = compile(source.format(key=key), fn.__code__.co_filename, "exec")
254
+ code = next(c for c in module_code.co_consts if isinstance(c, types.CodeType))
255
+ fn.__code__ = code.replace(co_firstlineno=fn.__code__.co_firstlineno, co_name=fn.__name__)
256
+ fn.__defaults__ = None
257
+ fn.__kwdefaults__ = None
258
+ if signature is not None:
259
+ # Frameworks read a tool's arguments from its signature, so it has to stay the same.
260
+ fn.__signature__ = signature
261
+ setattr(fn, _MARK, True)
262
+
263
+
264
+ def _outer_wrapper(name, fn):
265
+ """For what cannot be changed in place: decorated functions with closures, partials, objects."""
266
+ key = _register(name, fn, _signature_of(fn))
267
+ if inspect.iscoroutinefunction(fn):
268
+
269
+ @functools.wraps(fn)
270
+ async def wrapper(*args, **kwargs):
271
+ return await _acall(key, args, kwargs)
272
+
273
+ else:
274
+
275
+ @functools.wraps(fn)
276
+ def wrapper(*args, **kwargs):
277
+ return _call(key, args, kwargs)
278
+
279
+ setattr(wrapper, _MARK, True)
280
+ return wrapper
281
+
282
+
283
+ def _wrap_callable(name, value):
284
+ """Returns what should now stand where value stood."""
285
+ if not callable(value) or getattr(value, _MARK, False):
286
+ return value
287
+ if isinstance(value, types.FunctionType) and not value.__code__.co_freevars:
288
+ _swap_code(name, value)
289
+ return value
290
+ return _outer_wrapper(name, value)
291
+
292
+
293
+ def _listed(name):
294
+ return name in _tools or name in _ways_in
295
+
296
+
297
+ def _is_langchain_tool(value):
298
+ return any(c.__module__.startswith("langchain_core.tools") for c in type(value).__mro__)
299
+
300
+
301
+ def _wrap_langchain_tool(tool):
302
+ name = getattr(tool, "name", None)
303
+ if not isinstance(name, str) or not _listed(name):
304
+ return
305
+ for field in ("func", "coroutine"):
306
+ fn = getattr(tool, field, None)
307
+ if fn is not None:
308
+ wrapped = _wrap_callable(name, fn)
309
+ if wrapped is not fn:
310
+ setattr(tool, field, wrapped)
311
+
312
+
313
+ def _scan_class(cls):
314
+ for attr, value in list(vars(cls).items()):
315
+ if not _listed(attr):
316
+ continue
317
+ inner = value.__func__ if isinstance(value, (staticmethod, classmethod)) else value
318
+ wrapped = _wrap_callable(attr, inner)
319
+ if wrapped is not inner:
320
+ setattr(cls, attr, type(value)(wrapped) if inner is not value else wrapped)
321
+
322
+
323
+ def _scan_module(module):
324
+ namespace = vars(module)
325
+ for attr, value in list(namespace.items()):
326
+ if attr.startswith("__"):
327
+ continue
328
+ if isinstance(value, type):
329
+ if value.__module__ == module.__name__:
330
+ _safely(_scan_class, value)
331
+ elif _is_langchain_tool(value):
332
+ _safely(_wrap_langchain_tool, value)
333
+ elif _listed(attr):
334
+ wrapped = _safely(_wrap_callable, attr, value, fallback=value)
335
+ if wrapped is not value:
336
+ namespace[attr] = wrapped
337
+
338
+
339
+ def _is_app_file(path):
340
+ if not path or not path.endswith(".py"):
341
+ return False
342
+ if _files:
343
+ return os.path.realpath(path) in _files
344
+ return "site-packages" not in path and not path.startswith(sys.base_prefix)
345
+
346
+
347
+ def _scan_main():
348
+ """The script Python was started with never finishes loading, so it is scanned when a review begins."""
349
+ main = sys.modules.get("__main__")
350
+ if main is not None and _is_app_file(getattr(main, "__file__", None)):
351
+ _scan_module(main)
352
+
353
+
354
+ # Model calls: what the client patches need from here.
355
+
356
+
357
+ def _canary_line():
358
+ attempt = _state["attempt"]
359
+ canary = attempt["canaries"].get("prompt") if attempt else None
360
+ return f"Internal reference: {canary}" if canary else None
361
+
362
+
363
+ def _see_model_call(model, tool_calls, input_tokens, output_tokens):
364
+ _state["modelCalls"].append(
365
+ {
366
+ "model": model,
367
+ "toolCalls": tool_calls,
368
+ "inputTokens": input_tokens or 0,
369
+ "outputTokens": output_tokens or 0,
370
+ }
371
+ )
372
+
373
+
374
+ # Modules as they load.
375
+
376
+
377
+ def _after_load(module):
378
+ patch = clients.LIBRARIES.get(module.__name__)
379
+ if patch:
380
+ _safely(patch, module)
381
+ if _is_app_file(getattr(module, "__file__", None)):
382
+ _safely(_scan_module, module)
383
+
384
+
385
+ class _Finder:
386
+ """Finds nothing itself. It only adds a step after the modules we care about have loaded."""
387
+
388
+ @staticmethod
389
+ def find_spec(name, path=None, target=None):
390
+ for finder in sys.meta_path:
391
+ if finder is _Finder or not hasattr(finder, "find_spec"):
392
+ continue
393
+ spec = finder.find_spec(name, path, target)
394
+ if spec is not None:
395
+ _safely(_watch_spec, spec)
396
+ return spec
397
+ return None
398
+
399
+
400
+ def _watch_spec(spec):
401
+ if spec.name not in clients.LIBRARIES and not _is_app_file(spec.origin):
402
+ return
403
+ original = spec.loader.exec_module
404
+
405
+ def exec_module(module):
406
+ original(module)
407
+ _after_load(module)
408
+
409
+ spec.loader.exec_module = exec_module
410
+
411
+
412
+ # The control port the runner talks to. Loopback only, and it dies with the app.
413
+
414
+
415
+ class _Control(http.server.BaseHTTPRequestHandler):
416
+ def _send(self, body):
417
+ data = json.dumps(body, default=str).encode("utf-8")
418
+ self.send_response(200)
419
+ self.send_header("content-type", "application/json")
420
+ self.send_header("content-length", str(len(data)))
421
+ self.end_headers()
422
+ self.wfile.write(data)
423
+
424
+ def _handle(self):
425
+ global _state
426
+ length = int(self.headers.get("content-length") or 0)
427
+ body = self.rfile.read(length) if length else b""
428
+ if self.path == "/begin":
429
+ _safely(_scan_main)
430
+ _state = _fresh_state()
431
+ _state["attempt"] = json.loads(body.decode("utf-8"))
432
+ return self._send({"ok": True})
433
+ if self.path == "/end":
434
+ seen = _state
435
+ _state = _fresh_state()
436
+ # The edge sees a tool call before its function runs. Where a hook then held the
437
+ # function itself, that record is the one kept, so a call counts once.
438
+ by_hook = {h["tool"] for h in seen["held"] if h.get("at") != "edge"}
439
+ return self._send(
440
+ {
441
+ "heldCalls": [h for h in seen["held"] if h.get("at") != "edge" or h["tool"] not in by_hook],
442
+ "modelCalls": seen["modelCalls"],
443
+ "ranTools": seen["ran"],
444
+ "plantDelivered": seen["plantDelivered"],
445
+ "retrieved": seen["retrieved"],
446
+ "edgeHeld": seen.get("edge", []),
447
+ "modelFailures": seen.get("modelFailures", []),
448
+ }
449
+ )
450
+ if self.path == "/hello":
451
+ return self._send({"ok": True, "hook": "python"})
452
+ self.send_response(404)
453
+ self.send_header("content-length", "0")
454
+ self.end_headers()
455
+ return None
456
+
457
+ do_GET = _handle
458
+ do_POST = _handle
459
+
460
+ def log_message(self, *details):
461
+ pass
462
+
463
+
464
+ def _announce(port):
465
+ """A plain socket, because a server may fork while this runs in its other thread. A forked child
466
+ keeps any lock urllib held at that moment, with nothing left to release it, and hangs."""
467
+ runner = urllib.parse.urlsplit(os.environ.get("MODELOS_SECURE_RUNNER_URL", ""))
468
+ if not runner.hostname:
469
+ return
470
+ body = json.dumps({"instance": os.environ.get("MODELOS_SECURE_INSTANCE"), "port": port})
471
+ request = (
472
+ f"POST /ready HTTP/1.1\r\nhost: {runner.netloc}\r\ncontent-type: application/json\r\n"
473
+ f"content-length: {len(body)}\r\nconnection: close\r\n\r\n{body}"
474
+ )
475
+ with socket.create_connection((runner.hostname, runner.port), timeout=5) as connection:
476
+ connection.sendall(request.encode("utf-8"))
477
+ connection.recv(1024)
478
+
479
+
480
+ def _serve():
481
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Control)
482
+ server.daemon_threads = True
483
+ threading.Thread(target=server.serve_forever, daemon=True).start()
484
+ threading.Thread(
485
+ target=_safely, args=(_announce, server.server_address[1]), daemon=True
486
+ ).start()
487
+
488
+
489
+ def _serve_once_app_port_is_taken():
490
+ """Only the process that takes the app's port is the app.
491
+
492
+ PYTHONPATH reaches every Python process the app starts, and those are not the app: gcloud, run
493
+ by google-auth while it finds credentials, would otherwise announce a control port and exit,
494
+ leaving the runner talking to a dead port. docs/journal/adr/0020-announce-on-the-app-port.md
495
+ """
496
+ wanted = os.environ.get("PORT", "")
497
+ if not wanted.isdigit():
498
+ _serve()
499
+ return
500
+ wanted = int(wanted)
501
+ claimed = False
502
+
503
+ def claim(address):
504
+ nonlocal claimed
505
+ if not claimed and isinstance(address, tuple) and address[1] == wanted:
506
+ claimed = True
507
+ _serve()
508
+
509
+ init = socket.socket.__init__
510
+ bind = socket.socket.bind
511
+ listen = socket.socket.listen
512
+
513
+ @functools.wraps(init)
514
+ def watched_init(self, *args, **kwargs):
515
+ init(self, *args, **kwargs)
516
+ # Flask's reloader hands its child a socket that is already bound and listening.
517
+ fileno = kwargs.get("fileno", args[3] if len(args) > 3 else None)
518
+ if fileno is not None and not claimed:
519
+ _safely(lambda: claim(self.getsockname()))
520
+
521
+ @functools.wraps(bind)
522
+ def watched_bind(self, address):
523
+ bind(self, address)
524
+ _safely(claim, address)
525
+
526
+ @functools.wraps(listen)
527
+ def watched_listen(self, *args):
528
+ listen(self, *args)
529
+ # A reloading server binds in one process and listens in another.
530
+ _safely(lambda: claim(self.getsockname()))
531
+
532
+ socket.socket.__init__ = watched_init
533
+ socket.socket.bind = watched_bind
534
+ socket.socket.listen = watched_listen
535
+
536
+ def after_fork():
537
+ # A forked server worker cannot use the parent's thread, so it serves its own control port.
538
+ # Any other fork, such as a pool of workers, is not the app.
539
+ nonlocal claimed
540
+ if claimed:
541
+ _serve()
542
+
543
+ os.register_at_fork(after_in_child=lambda: _safely(after_fork))
544
+
545
+
546
+ def install():
547
+ global _state
548
+ config = json.loads(os.environ["MODELOS_SECURE_HOOK"])
549
+ _state = _fresh_state()
550
+ _tools.update({tool["name"]: tool for tool in config.get("tools", [])})
551
+ _ways_in.update({way["function"]: way for way in config.get("waysIn", []) if way.get("function")})
552
+ _files.update(os.path.realpath(path) for path in config.get("files", []))
553
+ clients.connect(_canary_line, _see_model_call, _safely)
554
+ # The edge, beneath every framework. http.client is always there; the others patch on import.
555
+ ways = {way["name"]: way for way in config.get("waysIn", [])}
556
+ patches = edge.install(
557
+ {
558
+ "state": lambda: _state,
559
+ "canary_line": _canary_line,
560
+ "mode": lambda name: _tools.get(name, {}).get("mode") if name else None,
561
+ "way_in": ways.get,
562
+ "allow": (config.get("edge") or {}).get("allow", []),
563
+ "safely": _safely,
564
+ }
565
+ )
566
+ import http.client
567
+
568
+ _safely(patches["http.client"], http.client)
569
+ clients.LIBRARIES.update({"httpx": patches["httpx"], "aiohttp": patches["aiohttp"]})
570
+ sys.meta_path.insert(0, _Finder)
571
+ for name in list(clients.LIBRARIES):
572
+ if name in sys.modules:
573
+ _after_load(sys.modules[name])
574
+ _serve_once_app_port_is_taken()
File without changes
@@ -0,0 +1,13 @@
1
+ # Python imports this module before anything else when its folder is on PYTHONPATH.
2
+ # docs/spec/05-scan-and-cli.md#5-start. Outside a review it does nothing, and nothing here may ever
3
+ # stop the customer's app from starting.
4
+ import os
5
+ import sys
6
+
7
+ if os.environ.get("MODELOS_SECURE_HOOK") and sys.version_info >= (3, 10):
8
+ try:
9
+ from modelos_secure import hook
10
+
11
+ hook.install()
12
+ except Exception as error:
13
+ print(f"modelos-secure hook: not attached: {error}", file=sys.stderr)
@@ -0,0 +1,11 @@
1
+ """Runs the bundled CLI with the bundled Node."""
2
+ import os
3
+ import subprocess
4
+ import sys
5
+ from pathlib import Path
6
+
7
+
8
+ def main() -> None:
9
+ here = Path(__file__).parent / "_cli"
10
+ node = here / ("node.exe" if os.name == "nt" else "node")
11
+ raise SystemExit(subprocess.call([str(node), str(here / "cli.js"), *sys.argv[1:]]))