optophi 0.0.1__py3-none-any.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.
optophi/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Local Optophi onboarding; no service or pipeline-runtime dependencies."""
optophi/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
optophi/charter.py ADDED
@@ -0,0 +1,141 @@
1
+ """Invoke an explicitly selected installed native CLI without an engine dependency."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+ from tempfile import TemporaryDirectory
10
+
11
+ # Check only module availability in the selected interpreter, then use CPython's
12
+ # own -m handoff. The private stdlib entry point is qualified on 3.11/3.13; its
13
+ # absence refuses explicitly. Native initialization and shutdown must happen in
14
+ # the same process with a persistent __main__, without bootstrap-only globals.
15
+ # Do not catch native exceptions or interpret stdout/stderr as availability.
16
+ _BOOTSTRAP = """\
17
+ def _handoff(started):
18
+ import importlib.util
19
+ import runpy
20
+ import sys
21
+
22
+ def refuse(reason):
23
+ print("PyCharter invocation refused: " + reason, file=sys.stderr)
24
+ print("Selected interpreter: " + sys.executable, file=sys.stderr)
25
+ print("Select --python from an environment provisioned with a reviewed "
26
+ "PyCharter CLI artifact; see its qualification/install instructions.",
27
+ file=sys.stderr)
28
+ raise SystemExit(1)
29
+
30
+ try:
31
+ with open(started, "xb"):
32
+ pass
33
+ except OSError:
34
+ refuse("could not record Python bootstrap startup.")
35
+
36
+ run_main = getattr(runpy, "_run_module_as_main", None)
37
+ if not callable(run_main):
38
+ refuse("selected interpreter lacks the qualified runpy native -m handoff.")
39
+ # Native package initialization sees the same argv[0] as direct Python -m.
40
+ sys.argv[0] = "-m"
41
+ if importlib.util.find_spec("pycharter") is None:
42
+ refuse("no installed pycharter package.")
43
+ if importlib.util.find_spec("pycharter.cli") is None:
44
+ refuse("installed PyCharter has no pycharter.cli module.")
45
+ del globals()["_handoff"]
46
+ run_main("pycharter.cli")
47
+ """
48
+
49
+
50
+ def run(
51
+ python: Path, root: Path, arguments: list[str], *, timeout: float | None = None
52
+ ) -> int:
53
+ """Run the installed PyCharter CLI and preserve its output and exit status.
54
+
55
+ Args:
56
+ python: Selected interpreter path, relative to the caller if not absolute.
57
+ root: Existing working directory for native relative paths.
58
+ arguments: Native CLI arguments, optionally preceded by ``--``.
59
+ timeout: Optional positive finite deadline in seconds for the direct child.
60
+
61
+ Returns:
62
+ Native exit status (shell convention for signals), 124 on timeout,
63
+ or 130 when the wrapper is interrupted.
64
+
65
+ Raises:
66
+ ValueError: A supplied timeout is not a positive finite int or float.
67
+ Invalid deadlines are rejected before starting the native child.
68
+ """
69
+ if timeout is not None:
70
+ try:
71
+ valid_timeout = (
72
+ not isinstance(timeout, bool)
73
+ and isinstance(timeout, (int, float))
74
+ and timeout > 0
75
+ and math.isfinite(timeout)
76
+ )
77
+ except OverflowError:
78
+ valid_timeout = False
79
+ if not valid_timeout:
80
+ raise ValueError("timeout must be a positive finite number or None")
81
+ # Keep the venv entry point: resolving this symlink would select its base
82
+ # interpreter instead. Anchor it before changing the child's working directory.
83
+ try:
84
+ interpreter = python.expanduser().absolute()
85
+ except (OSError, RuntimeError):
86
+ print(
87
+ "PyCharter invocation refused: cannot resolve --python. "
88
+ "Supply an absolute path to the selected Python executable.",
89
+ file=sys.stderr,
90
+ )
91
+ return 1
92
+ native = arguments[1:] if arguments[:1] == ["--"] else arguments
93
+ try:
94
+ with TemporaryDirectory(
95
+ prefix="optophi-charter-", ignore_cleanup_errors=True
96
+ ) as temporary:
97
+ started = Path(temporary) / "started"
98
+ bootstrap = f"{_BOOTSTRAP}\n_handoff({str(started)!r})\n"
99
+ result = subprocess.run(
100
+ [str(interpreter), "-I", "-c", bootstrap, *(native or ["--help"])],
101
+ cwd=root,
102
+ check=False,
103
+ timeout=timeout,
104
+ )
105
+ if result.returncode == 0 and not started.is_file():
106
+ print(
107
+ "PyCharter invocation refused: the selected executable did not "
108
+ "run the Optophi Python bootstrap. Check --python names a Python "
109
+ "executable in the intended runtime environment.",
110
+ file=sys.stderr,
111
+ )
112
+ return 1
113
+ except subprocess.TimeoutExpired:
114
+ # subprocess.run kills and waits for its direct child on timeout. Streams
115
+ # are inherited, so already-written native diagnostics remain visible.
116
+ print(
117
+ f"PyCharter deadline exceeded ({timeout} seconds): outcome UNKNOWN. "
118
+ "The directly invoked child was stopped and reaped; effects may remain. "
119
+ "The command was not retried. Inspect native evidence and reconcile "
120
+ "destination state before deciding whether to retry.",
121
+ file=sys.stderr,
122
+ )
123
+ return 124
124
+ except OSError as exc:
125
+ print(
126
+ f"PyCharter invocation refused: cannot start selected interpreter "
127
+ f"{interpreter}: {exc}. Check --python names an existing executable "
128
+ "in the intended runtime environment and --project still exists.",
129
+ file=sys.stderr,
130
+ )
131
+ return 1
132
+ except KeyboardInterrupt:
133
+ print(
134
+ "PyCharter invocation interrupted: outcome UNKNOWN. "
135
+ "Native effects or descendant work may remain. "
136
+ "The command was not retried. Inspect native evidence and reconcile "
137
+ "destination state before deciding whether to retry.",
138
+ file=sys.stderr,
139
+ )
140
+ return 130
141
+ return result.returncode if result.returncode >= 0 else 128 - result.returncode
optophi/cli.py ADDED
@@ -0,0 +1,352 @@
1
+ """Optophi local setup and native-artifact references."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import csv
7
+ import json
8
+ import math
9
+ import re
10
+ import sys
11
+ from importlib import metadata
12
+ from io import StringIO
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from . import charter, plugin, preparation, project, reference_update
17
+ from . import status as project_status
18
+
19
+
20
+ def _refuse_shared_installation(parser: argparse.ArgumentParser) -> None:
21
+ # The retired distribution can still own the console script in this environment.
22
+ try:
23
+ site = [str(Path(__file__).resolve().parent.parent)]
24
+ legacy = next(
25
+ iter(metadata.distributions(name="optophi-onboarding", path=site)), None
26
+ )
27
+ if legacy is None:
28
+ return
29
+ current = next(iter(metadata.distributions(name="optophi", path=site)), None)
30
+ except (OSError, ValueError):
31
+ return
32
+ if current is not None:
33
+ parser.exit(
34
+ 1,
35
+ "optophi: the retired optophi-onboarding distribution also owns this command. "
36
+ "Use a fresh virtual environment and keep the old one for rollback.\n",
37
+ )
38
+
39
+
40
+ def _installed_identity() -> str | None:
41
+ """Read the supported distribution identity beside the loaded CLI."""
42
+ try:
43
+ module = Path(__file__).resolve()
44
+ candidates = list(
45
+ metadata.distributions(name="optophi", path=[str(module.parent.parent)])
46
+ )
47
+ if len(candidates) != 1:
48
+ return None
49
+ (distribution,) = candidates
50
+ record = distribution.read_text("RECORD")
51
+ if not record:
52
+ return None
53
+ relative_module = Path("optophi/cli.py")
54
+ if Path(str(distribution.locate_file(relative_module))).resolve() != module:
55
+ return None
56
+ entries = [
57
+ row
58
+ for row in csv.reader(StringIO(record, newline=""), strict=True)
59
+ if row and Path(row[0]) in (relative_module, module)
60
+ ]
61
+ if len(entries) != 1 or len(entries[0]) != 3:
62
+ return None
63
+ headers = distribution.metadata
64
+ names = headers.get_all("Name") or []
65
+ versions = headers.get_all("Version") or []
66
+ if (
67
+ len(names) != 1
68
+ or not isinstance(names[0], str)
69
+ or not re.fullmatch(r"optophi", names[0], re.I | re.ASCII)
70
+ or len(versions) != 1
71
+ ):
72
+ return None
73
+ version = versions[0]
74
+ if not isinstance(version, str) or not re.fullmatch(
75
+ r"[A-Za-z0-9][A-Za-z0-9.!+_-]{0,127}", version
76
+ ):
77
+ return None
78
+ return version
79
+ except (OSError, ValueError, csv.Error):
80
+ return None
81
+
82
+
83
+ class InstalledVersion(argparse.Action):
84
+ def __call__(
85
+ self,
86
+ parser: argparse.ArgumentParser,
87
+ namespace: argparse.Namespace,
88
+ values: Any,
89
+ option_string: str | None = None,
90
+ ) -> None:
91
+ _refuse_shared_installation(parser)
92
+ version = _installed_identity()
93
+ if version is None:
94
+ parser.exit(1, "optophi: installed distribution version is unavailable.\n")
95
+ print(f"optophi {version}")
96
+ parser.exit()
97
+
98
+
99
+ def positive_seconds(value: str) -> float:
100
+ """Reject invalid deadlines before selecting or invoking a native runtime."""
101
+ try:
102
+ seconds = float(value)
103
+ except ValueError as exc:
104
+ raise argparse.ArgumentTypeError("expected positive finite seconds") from exc
105
+ if not math.isfinite(seconds) or seconds <= 0:
106
+ raise argparse.ArgumentTypeError("expected positive finite seconds")
107
+ return seconds
108
+
109
+
110
+ def _build_parser() -> argparse.ArgumentParser:
111
+ parser = argparse.ArgumentParser(
112
+ prog="optophi",
113
+ allow_abbrev=False,
114
+ description=__doc__,
115
+ formatter_class=argparse.RawDescriptionHelpFormatter,
116
+ epilog=(
117
+ "Day 1: attach your agent to Optophi MCP.\n"
118
+ "This CLI previews thin native-file references. Connection and governed\n"
119
+ "approval/activity require their separately qualified profile.\nGuide:\n"
120
+ "https://github.com/optophi/optophi-platform/blob/develop/"
121
+ "docs/optophi-mcp-day-one.md"
122
+ ),
123
+ )
124
+ parser.add_argument(
125
+ "--version",
126
+ action=InstalledVersion,
127
+ nargs=0,
128
+ help="Show the loaded CLI's installed distribution and version",
129
+ )
130
+ commands = parser.add_subparsers(dest="command", required=True)
131
+ supplied = commands.add_parser(
132
+ "inspect-preparation",
133
+ allow_abbrev=False,
134
+ help="Inspect explicitly supplied DevOps preparation JSON; never authorizes execution",
135
+ )
136
+ preparation.arguments(supplied)
137
+ native = commands.add_parser(
138
+ "charter",
139
+ allow_abbrev=False,
140
+ help="Run native PyCharter CLI in an explicitly selected environment",
141
+ )
142
+ native.add_argument(
143
+ "--python",
144
+ required=True,
145
+ type=Path,
146
+ help="Interpreter path in the selected runtime environment",
147
+ )
148
+ native.add_argument("--project", type=Path, default=Path("."))
149
+ native.add_argument(
150
+ "--timeout",
151
+ type=positive_seconds,
152
+ metavar="SECONDS",
153
+ help="Optional subprocess deadline; expiry exits 124 with UNKNOWN effects",
154
+ )
155
+ native.add_argument(
156
+ "native_args",
157
+ nargs=argparse.REMAINDER,
158
+ help="Native arguments after --; defaults to native --help",
159
+ )
160
+ init = commands.add_parser(
161
+ "init",
162
+ allow_abbrev=False,
163
+ help="Preview project guidance and native-file references",
164
+ )
165
+ init.add_argument("--project", type=Path, default=Path("."))
166
+ init.add_argument("--manager", choices=[*project.MANAGERS, "none"])
167
+ init.add_argument("--client", choices=["codex", "none"])
168
+ init.add_argument("--pipeline", action="append")
169
+ init.add_argument("--contract", action="append")
170
+ init.add_argument(
171
+ "--remove", action="store_true", help="Preview removal of owned setup only"
172
+ )
173
+ init.add_argument(
174
+ "--apply", action="store_true", help="Apply an exactly reviewed preview"
175
+ )
176
+ init.add_argument(
177
+ "--expect-plan", default="", help="plan_id from the reviewed preview"
178
+ )
179
+ update = commands.add_parser(
180
+ "update-references",
181
+ allow_abbrev=False,
182
+ help="Preview reference changes in intact owned v1 setup",
183
+ )
184
+ update.add_argument("--project", type=Path, default=Path("."))
185
+ update.add_argument("--pipeline", action="append")
186
+ update.add_argument("--contract", action="append")
187
+ update.add_argument("--apply", action="store_true")
188
+ update.add_argument("--expect-plan", default="")
189
+ inspect = commands.add_parser(
190
+ "status",
191
+ allow_abbrev=False,
192
+ help="Inspect setup/references; no native validation or execution",
193
+ )
194
+ inspect.add_argument("--project", type=Path, default=Path("."))
195
+ inspect.add_argument(
196
+ "--handoff",
197
+ action="store_true",
198
+ help="Print the authoring prompt for intact setup",
199
+ )
200
+ export = commands.add_parser(
201
+ "export-plugin",
202
+ allow_abbrev=False,
203
+ help="Preview/export the bundled local plugin; no client changes",
204
+ )
205
+ export.add_argument(
206
+ "--destination",
207
+ type=Path,
208
+ required=True,
209
+ help="New directory below an existing parent",
210
+ )
211
+ export.add_argument(
212
+ "--marketplace-name",
213
+ default="optophi-local",
214
+ help="Explicit exported catalog name (1-64 ASCII letters/digits/_/-); no client changes",
215
+ )
216
+ export.add_argument("--apply", action="store_true")
217
+ export.add_argument("--expect-plan", default="")
218
+ return parser
219
+
220
+
221
+ def main(argv: list[str] | None = None) -> int:
222
+ selected = list(sys.argv[1:] if argv is None else argv)
223
+ if selected and selected[0] == "inspect-preparation":
224
+ return preparation.main(
225
+ selected[1:], before_inspection=_refuse_shared_installation
226
+ )
227
+ parser = _build_parser()
228
+ args = parser.parse_args(argv)
229
+ _refuse_shared_installation(parser)
230
+ try:
231
+ if args.command == "export-plugin":
232
+ print(
233
+ json.dumps(
234
+ plugin.export(
235
+ args.destination,
236
+ apply=args.apply,
237
+ expected_id=args.expect_plan,
238
+ marketplace_name=args.marketplace_name,
239
+ ),
240
+ indent=2,
241
+ )
242
+ )
243
+ return 0
244
+ root = args.project.resolve(strict=True)
245
+ if not root.is_dir():
246
+ raise project.Refusal("--project must be an existing directory.")
247
+ if args.command == "charter":
248
+ return charter.run(
249
+ args.python, root, args.native_args, timeout=args.timeout
250
+ )
251
+ if args.command == "update-references":
252
+ print(
253
+ json.dumps(
254
+ reference_update.update(
255
+ root,
256
+ pipeline=args.pipeline,
257
+ contract=args.contract,
258
+ apply=args.apply,
259
+ expected_id=args.expect_plan,
260
+ ),
261
+ indent=2,
262
+ )
263
+ )
264
+ return 0
265
+ if args.command == "status":
266
+ result = project_status.inspect(root)
267
+ if args.handoff:
268
+ if result["setup"] != "intact":
269
+ raise project.Refusal(
270
+ "Review/init project guidance before requesting the authoring handoff."
271
+ )
272
+ print(project_status.HANDOFF)
273
+ else:
274
+ print(json.dumps(result, indent=2))
275
+ return 0
276
+ directories = project.setup_directories(root)
277
+ changes = project.plan(
278
+ root,
279
+ manager=args.manager,
280
+ client=args.client,
281
+ pipeline=args.pipeline,
282
+ contract=args.contract,
283
+ remove=args.remove,
284
+ )
285
+ preconditions, instruction_guard = project.instruction_preconditions(
286
+ root,
287
+ changes,
288
+ remove=args.remove,
289
+ expected_root=directories["."],
290
+ )
291
+ if project.setup_directories(root) != directories:
292
+ raise project.Refusal("Project/setup directory replaced; preview again.")
293
+ summary: dict[str, Any] = {
294
+ "project": str(root),
295
+ "operation": "remove" if args.remove else "setup",
296
+ "directory_identities": directories,
297
+ "instruction_preconditions": preconditions,
298
+ "changes": [
299
+ {
300
+ "path": path,
301
+ "before_sha256": project.digest(old),
302
+ "after_sha256": project.digest(new),
303
+ }
304
+ for path, (old, new) in changes.items()
305
+ ],
306
+ }
307
+ plan_id = project.digest(project.encoded(summary))
308
+ if args.apply:
309
+ project.apply(
310
+ root,
311
+ changes,
312
+ args.expect_plan,
313
+ plan_id,
314
+ guard=instruction_guard,
315
+ expected_directories=directories,
316
+ )
317
+ status = "no_changes"
318
+ if changes:
319
+ status = (
320
+ ("removed" if args.apply else "removal_preview")
321
+ if args.remove
322
+ else ("guidance_only" if args.apply else "setup_preview")
323
+ )
324
+ summary.update({"plan_id": plan_id, "applied": args.apply, "status": status})
325
+ # Only generated content is shown; unrelated instructions and native data stay private.
326
+ if not args.remove and changes:
327
+ summary["generated_preview"] = {
328
+ path: new.decode()
329
+ for path, (_, new) in changes.items()
330
+ if path in (project.PROJECT, project.GUIDANCE) and new is not None
331
+ }
332
+ state_data = changes[project.STATE][1]
333
+ assert state_data is not None
334
+ summary["instruction_block"] = json.loads(state_data)["block"]
335
+ print(json.dumps(summary, indent=2))
336
+ return 0
337
+ except (project.Refusal, OSError) as exc:
338
+ # OSError text can contain user-controlled paths; do not echo file contents.
339
+ operation = {
340
+ "status": "Status",
341
+ "export-plugin": "Plugin export",
342
+ "update-references": "Reference update",
343
+ "charter": "PyCharter invocation",
344
+ }.get(args.command, "Setup")
345
+ interrupted = isinstance(exc, project.Interrupted)
346
+ outcome = "interrupted" if interrupted else "refused"
347
+ print(f"{operation} {outcome}: {exc}", file=sys.stderr)
348
+ return 130 if interrupted else 1
349
+
350
+
351
+ if __name__ == "__main__":
352
+ raise SystemExit(main())
Binary file