egzoscore 0.2.0__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.
Files changed (62) hide show
  1. egzos/__init__.py +11 -0
  2. egzos/_ids.py +29 -0
  3. egzos/_signals.py +39 -0
  4. egzos/_term.py +33 -0
  5. egzos/_types.py +1023 -0
  6. egzos/api/__init__.py +150 -0
  7. egzos/api/app.py +1574 -0
  8. egzos/api/blobs.py +92 -0
  9. egzos/api/throttle.py +190 -0
  10. egzos/auth.py +176 -0
  11. egzos/authz/__init__.py +5 -0
  12. egzos/authz/presence.py +778 -0
  13. egzos/authz/values.py +32 -0
  14. egzos/backends/__init__.py +8 -0
  15. egzos/backends/base.py +91 -0
  16. egzos/backends/postgres.py +490 -0
  17. egzos/backends/sqlite.py +524 -0
  18. egzos/binding.py +309 -0
  19. egzos/cli/__init__.py +1092 -0
  20. egzos/cli/__main__.py +11 -0
  21. egzos/confirm.py +455 -0
  22. egzos/container.py +222 -0
  23. egzos/identity.py +1104 -0
  24. egzos/ledger.py +167 -0
  25. egzos/mcp/__init__.py +3 -0
  26. egzos/mcp/http.py +90 -0
  27. egzos/mcp/server.py +287 -0
  28. egzos/model.py +242 -0
  29. egzos/py.typed +0 -0
  30. egzos/resolver.py +115 -0
  31. egzos/store/__init__.py +10 -0
  32. egzos/store/autotitle.py +31 -0
  33. egzos/store/blobs.py +120 -0
  34. egzos/store/find.py +120 -0
  35. egzos/store/items.py +233 -0
  36. egzos/store/nodes.py +193 -0
  37. egzos/store/objects.py +143 -0
  38. egzos/store/uploads.py +369 -0
  39. egzos/trust.py +675 -0
  40. egzos/web/__init__.py +88 -0
  41. egzos/web/app.py +965 -0
  42. egzos/web/static/htmx.LICENSE +13 -0
  43. egzos/web/static/htmx.min.js +1 -0
  44. egzos/web/static/lifeboat.css +140 -0
  45. egzos/web/static/lifeboat.js +12 -0
  46. egzos/web/strings.py +133 -0
  47. egzos/web/templates/_manifest_row.html +3 -0
  48. egzos/web/templates/_shell.html +29 -0
  49. egzos/web/templates/_window.html +7 -0
  50. egzos/web/templates/base.html +24 -0
  51. egzos/web/templates/error.html +10 -0
  52. egzos/web/templates/home.html +39 -0
  53. egzos/web/templates/item.html +91 -0
  54. egzos/web/templates/notfound.html +6 -0
  55. egzos/web/templates/pending.html +107 -0
  56. egzos/web/tokens.css +294 -0
  57. egzoscore-0.2.0.dist-info/METADATA +135 -0
  58. egzoscore-0.2.0.dist-info/RECORD +62 -0
  59. egzoscore-0.2.0.dist-info/WHEEL +4 -0
  60. egzoscore-0.2.0.dist-info/entry_points.txt +2 -0
  61. egzoscore-0.2.0.dist-info/licenses/LICENSE +65 -0
  62. egzoscore-0.2.0.dist-info/licenses/NOTICE +6 -0
egzos/cli/__init__.py ADDED
@@ -0,0 +1,1092 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """
4
+ The CLI — first surface, doubles as the test harness (v0.3 §10). Daily one-worders: fetch, add,
5
+ ls, serve, find; noun-verb for the rest; --json everywhere; sticky scope (v0.4 §9).
6
+
7
+ Walking skeleton verbs: init · whoami · add · ls · fetch · find · cd · pwd · mk · mv · trust
8
+ (pending / approve / deny / quarantine) · token (create / ls) · audit (tail / verify) · serve --mcp.
9
+ `%n` handles act on the numbered results of the last `find` and resolve to real ids underneath.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import shlex
17
+ import shutil
18
+ import subprocess
19
+ import sys
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ import typer
24
+
25
+ from egzos._term import safe
26
+ from egzos._types import CONTAINER_CONFIG_FIELD_FROM_WIRE_KEY, StorageBusy
27
+ from egzos.backends.base import holds_nul
28
+ from egzos.container import OWNER, Container, HomeBindingError
29
+ from egzos.identity import ConfigError, LastAdmin
30
+ from egzos.model import Node
31
+ from egzos.store.items import StoreError
32
+ from egzos.store.nodes import AmbiguousRef, StructureError
33
+ from egzos.trust import TrustError
34
+
35
+ #: The command this program installs. The cloud's command line is a different program, `egzos`.
36
+ PROG = "egzoscore"
37
+ #: The name `connect` registers the server under in an agent's configuration. It stays `egzos`
38
+ #: (the product's name), so a second `connect` replaces the first entry and adds no other.
39
+ MCP_NAME = "egzos"
40
+
41
+ app = typer.Typer(
42
+ add_completion=False, no_args_is_help=False, help="egzoscore — your context, your container."
43
+ )
44
+ trust_app = typer.Typer(help="Trust: pending queue, promotion, quarantine.")
45
+ audit_app = typer.Typer(help="Audit: the hash-chained ledger.")
46
+ token_app = typer.Typer(help="Tokens: client principals and their capabilities.")
47
+ config_app = typer.Typer(help="Config: the container's settings (container.md §8).")
48
+ credential_app = typer.Typer(help="Credentials: the Face ID / Touch ID keys people confirm with.")
49
+ grant_app = typer.Typer(help="Grants: people who sign in at your provider and may use this.")
50
+ app.add_typer(trust_app, name="trust")
51
+ app.add_typer(audit_app, name="audit")
52
+ app.add_typer(token_app, name="token")
53
+ app.add_typer(config_app, name="config")
54
+ app.add_typer(grant_app, name="grant")
55
+ app.add_typer(credential_app, name="credential")
56
+
57
+ _state: dict[str, Any] = {"json": False}
58
+
59
+
60
+ # -- helpers -----------------------------------------------------------------------------------
61
+ def _out(payload: Any, human: str | None = None) -> None:
62
+ """Everything the CLI prints goes through here, and through `safe`: stored text is data, and
63
+ a control character in it would be a command to the terminal. JSON escapes C0 itself."""
64
+ if _state["json"]:
65
+ typer.echo(safe(json.dumps(payload, indent=2, ensure_ascii=False, default=str), json=True))
66
+ elif human is not None:
67
+ typer.echo(safe(human))
68
+
69
+
70
+ def _fail(msg: str, code: int = 1) -> None:
71
+ _out({"error": msg}, msg)
72
+ raise typer.Exit(code)
73
+
74
+
75
+ def _container() -> Container:
76
+ """The container this command runs on, closed when the command ends, as a door's command ends
77
+ once its server shuts down: a bound home then records the newest entry it has seen
78
+ (storage.md §3.7)."""
79
+ try:
80
+ c = Container()
81
+ except HomeBindingError as e: # its message names the case and the variable, never its value
82
+ _fail(str(e), 2)
83
+ if (ctx := _state.get("ctx")) is not None:
84
+ ctx.call_on_close(c.close)
85
+ return c
86
+
87
+
88
+ def _scope_file() -> Path:
89
+ return Path.cwd() / ".egzos"
90
+
91
+
92
+ def _resolve(c: Container, ref: str, token) -> Node | None:
93
+ """`resolve_ref`, with an ambiguous tail refused and the matching scopes named — all of them
94
+ ones this token can see — so the caller can give a longer path or the id."""
95
+ try:
96
+ return c.nodes.resolve_ref(ref, token)
97
+ except AmbiguousRef as e:
98
+ _fail(f"{ref} {e} — give more of the path, or the id")
99
+
100
+
101
+ def _sticky_scope(c: Container) -> Node | None:
102
+ """Sticky scope per shell/project: the `.egzos` file in the working directory (v0.3 §4).
103
+ Only a file is one: in the home directory `.egzos` is the container itself, a directory."""
104
+ f = _scope_file()
105
+ if f.is_file():
106
+ return _resolve(c, f.read_text().strip(), c.require_token())
107
+ return None
108
+
109
+
110
+ def _scope_or(c: Container, ref: str | None, default: Node | None) -> Node | None:
111
+ """Resolve a scope as the shell's token sees it: an uncovered scope is "scope not found",
112
+ exactly like an absent one (silence-not-errors), on every verb that takes a scope."""
113
+ if ref:
114
+ node = _resolve(c, ref, c.require_token())
115
+ if not node:
116
+ _fail("scope not found")
117
+ return node
118
+ return _sticky_scope(c) or default
119
+
120
+
121
+ def _find_map(c: Container, token) -> Path:
122
+ """`%n` belongs to the principal whose `find` produced it: one map per token, so no other
123
+ principal's `find` can retarget what the owner's `%n` names."""
124
+ return c.home / f"last-find-{token.id}.json"
125
+
126
+
127
+ def _item_ref(c: Container, ref: str):
128
+ """Exact ids for machines, `%n` for humans (v0.3 §4); `%n` resolves to the real id."""
129
+ token = c.require_token()
130
+ if ref.startswith("%"):
131
+ f = _find_map(c, token)
132
+ if not f.exists():
133
+ _fail("no previous `find` to take %n from")
134
+ mapping = json.loads(f.read_text())
135
+ real = mapping.get(ref[1:])
136
+ if not real:
137
+ _fail(f"{ref} is not in the last find")
138
+ ref = real
139
+ item = c.store.get(ref)
140
+ node = c.backend.get_node(item.scope) if item else None
141
+ if not item or not node or not c.trust.covers(token, node):
142
+ _fail("not found") # silence-not-errors: the same answer whether absent or out of scope
143
+ return item
144
+
145
+
146
+ def _owner(c: Container, what: str):
147
+ """The owner's views and acts: the interactive principal only. A client principal sees what its
148
+ scopes cover through `fetch` / `find` / `ls`, never the whole container."""
149
+ token = c.require_token()
150
+ if token.principal != "interactive":
151
+ _fail(f"{what} is the owner's; a client principal sees only what its scopes cover")
152
+ return token
153
+
154
+
155
+ def _p(c: Container, node_id: str) -> str:
156
+ node = c.backend.get_node(node_id)
157
+ return c.nodes.path(node) if node else node_id
158
+
159
+
160
+ @app.callback()
161
+ def _root(
162
+ ctx: typer.Context,
163
+ json_: bool = typer.Option(False, "--json", help="Machine-readable output on every command."),
164
+ ):
165
+ _state["json"] = json_
166
+ _state["ctx"] = ctx # what `_container` opens is closed when this invocation ends
167
+
168
+
169
+ # -- init / whoami ------------------------------------------------------------------------
170
+ @app.command()
171
+ def init():
172
+ """Create the container: roots, inbox, the owner's interactive token."""
173
+ c = _container()
174
+ token = c.init()
175
+ roots = {
176
+ "user": c.nodes.path(c.nodes.user_root()),
177
+ "global": c.nodes.path(c.nodes.global_root()),
178
+ }
179
+ _out(
180
+ {"home": str(c.home), "roots": roots, "token": token.id},
181
+ f"container at {c.home}\nroots: {roots['user']} · {roots['global']} · "
182
+ "inbox under user:self\n"
183
+ f"interactive token {token.id[:8]}… in the keychain stand-in ({c.home / 'keychain.json'})",
184
+ )
185
+
186
+
187
+ @app.command()
188
+ def whoami():
189
+ """Which principal and capabilities this shell holds."""
190
+ c = _container()
191
+ token = c.require_token()
192
+ _out(
193
+ token.to_dict(),
194
+ f"{token.owner} · principal={token.principal} · client={token.client} · "
195
+ f"capabilities={','.join(token.capabilities)} · scopes={','.join(token.scopes)}",
196
+ )
197
+
198
+
199
+ # -- capture ------------------------------------------------------------------------------
200
+ @app.command()
201
+ def add(
202
+ what: str = typer.Argument(
203
+ ..., help="Text to remember, ./file for an artifact, or - for stdin."
204
+ ),
205
+ kind: str | None = typer.Option(None, "--kind", "-k"),
206
+ key: str | None = typer.Option(None, "--key", help="Enables cross-scope override."),
207
+ tag: list[str] = typer.Option([], "--tag", "-t"),
208
+ scope: str | None = typer.Option(
209
+ None, "--scope", "-s", help="Node id or path; default: inbox."
210
+ ),
211
+ ):
212
+ """Capture. No scope → the inbox, in a fresh auto-titled thread. Lands unverified."""
213
+ c = _container()
214
+ token = c.require_token()
215
+ node = _scope_or(c, scope, None)
216
+ body: str | None = None
217
+ file: Path | None = None
218
+ if what == "-":
219
+ body = sys.stdin.read()
220
+ elif Path(what).is_file():
221
+ file = Path(what)
222
+ else:
223
+ body = what
224
+ try:
225
+ item = c.store.add(
226
+ body=body,
227
+ file=file,
228
+ kind=kind,
229
+ scope=node,
230
+ key=key,
231
+ tags=tag,
232
+ token=token,
233
+ actor=OWNER,
234
+ principal=token.principal,
235
+ )
236
+ except StoreError as e:
237
+ _fail(str(e))
238
+ _out(
239
+ item.to_dict(),
240
+ f"{item.id} {item.kind:<10} unverified {_p(c, item.scope)}\n"
241
+ f" “{item.content['auto_title']}”",
242
+ )
243
+
244
+
245
+ @app.command()
246
+ def ls(
247
+ inbox: bool = typer.Option(
248
+ False, "--inbox", help="The incoming bucket (default when no scope)."
249
+ ),
250
+ scope: str | None = typer.Option(None, "--scope", "-s"),
251
+ ):
252
+ """List items. `ls --inbox` is the capture queue."""
253
+ if inbox and scope:
254
+ _fail("--inbox lists the capture queue, which has no scope: pass one of --inbox, --scope")
255
+ c = _container()
256
+ token = c.require_token()
257
+ node = _scope_or(c, scope, None)
258
+ if node and not c.trust.covers(token, node):
259
+ _fail("scope not found") # the same answer as a scope that does not exist
260
+ if node and not inbox:
261
+ rows = [(node, i) for i in c.backend.query([node.id])]
262
+ else:
263
+ rows = [(n, i) for n, i in c.store.inbox_items() if c.trust.covers(token, n)]
264
+ held = len(rows)
265
+ if token.principal != "interactive":
266
+ # A client is SERVED, never shown the store: the same policy as fetch — rules
267
+ # verified-only everywhere, quarantined never, each layer's serving policy.
268
+ rows = [(n, i) for n, i in rows if c.resolver.serve(i, n)]
269
+ c.ledger.append(
270
+ "context.fetch",
271
+ actor=OWNER,
272
+ principal=token.principal,
273
+ subject=node.id if node and not inbox else None,
274
+ scope=node.id if node and not inbox else None,
275
+ client=token.client,
276
+ view="ls" if node and not inbox else "ls --inbox",
277
+ items=[i.id for _, i in rows],
278
+ layers=[],
279
+ withheld=held - len(rows), # what the serving policy kept back, as the door records it
280
+ )
281
+ _out(
282
+ [{"scope": c.nodes.path(n), **i.to_dict()} for n, i in rows],
283
+ "\n".join(
284
+ f"{i.id} {i.kind:<10} {i.status:<10} {c.nodes.path(n)} "
285
+ f"“{i.content.get('auto_title', '')}”"
286
+ for n, i in rows
287
+ )
288
+ or "(empty)",
289
+ )
290
+
291
+
292
+ # -- resolve --------------------------------------------------------------------------------
293
+ @app.command()
294
+ def fetch(
295
+ scope: str | None = typer.Argument(
296
+ None, help="Node id or path; default: sticky scope, then user:self."
297
+ ),
298
+ kind: list[str] = typer.Option([], "--kind", "-k"),
299
+ key: str | None = typer.Option(None, "--key"),
300
+ no_global: bool = typer.Option(False, "--no-global"),
301
+ ):
302
+ """Read merged context for a scope: the chain, innermost first, most-specific-wins."""
303
+ c = _container()
304
+ token = c.require_token()
305
+ node = _scope_or(c, scope, c.nodes.user_root())
306
+ r = c.resolver.resolve(
307
+ node, token=token, actor=OWNER, kinds=kind or None, key=key, include_global=not no_global
308
+ )
309
+ lines = [
310
+ f"scope {r['scope']}",
311
+ "chain: " + " → ".join(f"{layer['path']} [{layer['policy']}]" for layer in r["chain"]),
312
+ ]
313
+ for e in r["items"]:
314
+ it = e["item"]
315
+ flag = f" (shadowed by {e['shadowed_by'][:8]}…)" if e["shadowed_by"] else ""
316
+ keyf = f" key={it['key']}" if it.get("key") else ""
317
+ lines.append(
318
+ f" {it['id']} {it['kind']:<10} {e['trust']:<10} @{e['layer']}{keyf}{flag}\n"
319
+ f" “{it['content'].get('auto_title', '')}”"
320
+ )
321
+ if r["withheld"]:
322
+ lines.append(f" ({r['withheld']} item(s) not served under the layer policies)")
323
+ _out(r, "\n".join(lines))
324
+
325
+
326
+ @app.command()
327
+ def find(
328
+ description: str = typer.Argument(...), kind: list[str] = typer.Option([], "--kind", "-k")
329
+ ):
330
+ """Numbered results across every kind/scope the token sees, recency-ranked; act with %n.
331
+ The grammar is the lifeboat's search (`egzos.store.find`): free text plus `kind:` `scope:`
332
+ `trust:` `tag:` `key:` `ring:`."""
333
+ from egzos.store.find import QueryError
334
+ from egzos.store.find import find as run_find
335
+
336
+ c = _container()
337
+ token = c.require_token()
338
+ query = " ".join([description, *(f"kind:{k}" for k in kind)])
339
+ try:
340
+ hits = run_find(c, token, query)
341
+ except QueryError:
342
+ _fail("That query isn't valid. Check the prefixes: kind: scope: trust: tag: key: ring:")
343
+ mapping = {str(i + 1): item.id for i, (_, item) in enumerate(hits)}
344
+ _find_map(c, token).write_text(json.dumps(mapping))
345
+ c.ledger.append(
346
+ "context.fetch",
347
+ actor=OWNER,
348
+ principal=token.principal,
349
+ subject=None,
350
+ scope=None,
351
+ client=token.client,
352
+ query=description,
353
+ items=list(mapping.values()),
354
+ layers=[],
355
+ withheld=0,
356
+ )
357
+ _out(
358
+ [
359
+ {"n": i + 1, "scope": c.nodes.path(n), **item.to_dict()}
360
+ for i, (n, item) in enumerate(hits)
361
+ ],
362
+ "\n".join(
363
+ f"%{i + 1:<3} {item.kind:<10} {item.status:<10} {c.nodes.path(n)} "
364
+ f"“{item.content.get('auto_title', '')}”"
365
+ for i, (n, item) in enumerate(hits)
366
+ )
367
+ or "(no matches)",
368
+ )
369
+
370
+
371
+ # -- scope ------------------------------------------------------------------------------------
372
+ @app.command()
373
+ def cd(
374
+ scope: str = typer.Argument(
375
+ ..., help="Node id or path — makes it the sticky scope for this directory."
376
+ ),
377
+ ):
378
+ """Sticky scope: writes `.egzos` in the working directory (alias for `scope use`)."""
379
+ c = _container()
380
+ node = _scope_or(c, scope, None)
381
+ if _scope_file().is_dir():
382
+ _fail(
383
+ "`.egzos` here is a directory (the container lives here); "
384
+ "set a sticky scope in a project directory"
385
+ )
386
+ _scope_file().write_text(node.id)
387
+ _out({"scope": node.id, "path": c.nodes.path(node)}, c.nodes.path(node))
388
+
389
+
390
+ @app.command()
391
+ def pwd():
392
+ """The sticky scope, if any."""
393
+ c = _container()
394
+ c.require_token()
395
+ node = _sticky_scope(c)
396
+ _out(
397
+ {"scope": node.id if node else None, "path": c.nodes.path(node) if node else None},
398
+ c.nodes.path(node) if node else "(no sticky scope — inbox)",
399
+ )
400
+
401
+
402
+ @app.command()
403
+ def mk(
404
+ type: str = typer.Argument(..., help="thread | project | team | org | exo"),
405
+ name: str = typer.Argument(...),
406
+ parent: str | None = typer.Option(
407
+ None, "--in", help="Parent node; default: sticky scope, then user:self."
408
+ ),
409
+ ):
410
+ """Create a container (SKELETON verb — the log says only 'creating wrappers is free')."""
411
+ c = _container()
412
+ token = c.require_token()
413
+ p = _scope_or(c, parent, c.nodes.user_root())
414
+ try:
415
+ node = c.nodes.create(type, name, p, token=token, actor=OWNER, principal=token.principal)
416
+ except StructureError as e:
417
+ _fail(str(e))
418
+ _out(node.to_dict(), f"{node.id} {c.nodes.path(node)}")
419
+
420
+
421
+ @app.command()
422
+ def mv(
423
+ item: str = typer.Argument(..., help="Item id or %n"),
424
+ to: str = typer.Argument(..., help="Target scope"),
425
+ ):
426
+ """Move an item. Inward = instant. Outward = the gate: resolved audience, then a human yes."""
427
+ c = _container()
428
+ token = c.require_token()
429
+ it = _item_ref(c, item)
430
+ target = _scope_or(c, to, None)
431
+ try:
432
+ r = c.trust.move(it, target, token=token, actor=OWNER)
433
+ except TrustError as e:
434
+ _fail(str(e))
435
+ if r["moved"]:
436
+ _out(r, f"moved → {c.nodes.path(target)} (audience delta: none — silent gate pass logged)")
437
+ else:
438
+ p = r["proposal"]
439
+ who = ", ".join(
440
+ f"{a['client']} ({a['role']}, {a['principal']})" for a in p["audience_delta"]
441
+ )
442
+ _out(
443
+ r,
444
+ f"GATE — this move widens the audience.\n {p['from_path']} → {p['to_path']}\n"
445
+ f" new audience: {who}\n"
446
+ f" inheritance: {p['blast_radius']} container(s) under the target inherit it\n"
447
+ f" parked as proposal {p['id']} · `egzoscore trust approve {p['id']}` to confirm",
448
+ )
449
+
450
+
451
+ @app.command()
452
+ def rm(item: str = typer.Argument(..., help="Item id or %n")):
453
+ """Tombstone an item no person has promoted, so no read serves it again (an inbox thread a
454
+ capture opened keeps its name). An agent's file still staged goes with it, unless another upload
455
+ or staged item holds the same bytes. A promoted item is tombstoned only at the door, where the
456
+ confirm asks the person: any process that can run this terminal could run `rm` (rest.md §4)."""
457
+ c = _container()
458
+ token = _admin(c, "tombstoning an item")
459
+ from egzos.store.uploads import Promoted
460
+
461
+ try: # the store decides under its lock, so an item promoted since `_item_ref` read it stays
462
+ gone = c.uploads.tombstone(token, _item_ref(c, item).id, unpromoted_only=True)
463
+ except Promoted:
464
+ _fail("a promoted item is tombstoned at the door, where the confirm asks you")
465
+ if gone is None:
466
+ _fail("not found") # quarantined, or gone since: as absent (silence-not-errors)
467
+ _out({"id": gone.id, "tombstoned": True}, f"tombstoned {gone.id}")
468
+
469
+
470
+ # -- trust ------------------------------------------------------------------------------------
471
+ @trust_app.command("pending")
472
+ def trust_pending():
473
+ """Unverified items awaiting promotion, and open proposals awaiting a human yes."""
474
+ c = _container()
475
+ token = _owner(c, "the pending queue")
476
+ pend = c.trust.pending()
477
+ c.ledger.append(
478
+ "context.fetch",
479
+ actor=OWNER,
480
+ principal=token.principal,
481
+ client=token.client,
482
+ view="trust pending",
483
+ items=[i.id for i in pend["items"]],
484
+ proposals=[p["id"] for p in pend["proposals"]],
485
+ layers=[],
486
+ withheld=0,
487
+ )
488
+ lines = ["items awaiting promotion:"] + [
489
+ f" {i.id} {i.kind:<10} @{_p(c, i.scope)} “{i.content.get('auto_title', '')}”"
490
+ f" by {i.provenance.get('client')}"
491
+ for i in pend["items"]
492
+ ] or []
493
+ lines.append("open proposals:")
494
+ lines += [
495
+ f" {p['id']} move {len(p['items'])} item(s) {p['from_path']} → {p['to_path']} widens to "
496
+ f"{', '.join(a['client'] for a in p['audience_delta'])} ({p['reason']})"
497
+ for p in pend["proposals"]
498
+ ] or [" (none)"]
499
+ _out(
500
+ {"items": [i.to_dict() for i in pend["items"]], "proposals": pend["proposals"]},
501
+ "\n".join(lines),
502
+ )
503
+
504
+
505
+ def _decide(c: Container, token, ref: str, *, asked: str = "approve") -> None:
506
+ """Open the decision page for an item or a proposal. The terminal only ASKS; the page — two
507
+ deliberate presses, or Deny — is where the human decides (the step-up tap). An open window
508
+ stands in for the presses, never for the answer: it carries out what was `asked`."""
509
+ from egzos.authz.presence import Presence, build_act
510
+
511
+ prop = c.backend.get_proposal(ref)
512
+ prop = prop if prop and prop.get("status") == "open" else None
513
+ act = build_act(c, prop["id"] if prop else _item_ref(c, ref).id, token=token)
514
+ if act is None:
515
+ _fail("nothing to decide: it is not pending")
516
+ from egzos.authz.presence import TAP_COPY, outcome_text
517
+
518
+ presence = Presence(c)
519
+ result: dict[str, Any] = {}
520
+
521
+ def perform(outcome: str, windowed: bool, closes: str | None) -> str:
522
+ """Runs while the page waits, so the page shows the container's answer, never a guess."""
523
+ try:
524
+ if outcome == "denied":
525
+ if prop:
526
+ p = c.trust.deny(prop["id"], token=token, actor=OWNER)
527
+ result["out"] = (p, f"denied {p['id']}")
528
+ else:
529
+ result["out"] = ({"id": act["subject"], "denied": True},
530
+ f"{act['subject']} stays unverified")
531
+ return outcome_text(act, "denied", closes=None)
532
+ if prop:
533
+ p = c.trust.execute(prop["id"], token=token, actor=OWNER)
534
+ landed = [i.status for i in (c.backend.get(x) for x in p["items"]) if i]
535
+ result["out"] = (p, f"executed proposal {p['id']} → {p['to_path']} "
536
+ f"(manifest {p['manifest'][:12]}… matched)")
537
+ return outcome_text(act, "approved", closes=closes, landed=landed)
538
+ # Approve what you saw: the item the page showed, never `ref` resolved a second time
539
+ # (a `%n` map can be rewritten while the page waits).
540
+ item = c.store.get(act["subject"])
541
+ if not item or item.status != "unverified":
542
+ result["error"] = "nothing to decide: it is no longer pending"
543
+ return TAP_COPY["tap.invalid"]
544
+ item = c.trust.promote(item, token=token, actor=OWNER)
545
+ by = item.provenance["approved_by"]
546
+ result["out"] = (item.to_dict(), f"{item.id} → verified (approved_by {by}, "
547
+ f"manifest {item.trust['manifest'][:12]}…)")
548
+ return outcome_text(act, "approved", closes=closes)
549
+ except TrustError as e:
550
+ result["error"] = str(e)
551
+ # Presence was proven and the engine refused the act: that is on the chain too.
552
+ presence.act_failed(act, e, reason="refused")
553
+ # R11 (the standalone /tap/<token> page): a proposal invalidated under it reads
554
+ # `tap.invalid`, as an item that is no longer pending does.
555
+ return TAP_COPY["tap.invalid"]
556
+
557
+ outcome = presence.require(act, decide=perform)
558
+ if outcome == "window":
559
+ try:
560
+ perform("denied" if asked == "deny" else "approved", False, None)
561
+ except Exception as e:
562
+ # As on the tap: the act rolled back whole, and the chain says it did not land.
563
+ presence.act_failed(act, e)
564
+ _fail(f"That didn't go through. Nothing changed. ({e})")
565
+ elif outcome not in ("approved", "denied"):
566
+ _fail(f"not approved: {outcome} in the presence check")
567
+ if "error" in result:
568
+ _fail(result["error"])
569
+ _out(*result["out"])
570
+
571
+
572
+ @trust_app.command("approve")
573
+ def trust_approve(ref: str = typer.Argument(..., help="Item id, %n, or proposal id")):
574
+ """Human-only: promote an item, or execute a parked proposal — decided on the presence page."""
575
+ c = _container()
576
+ token = c.require_token()
577
+ if token.principal != "interactive":
578
+ _fail("approve is a human-only act; a client principal can only propose")
579
+ _decide(c, token, ref)
580
+
581
+
582
+ @trust_app.command("deny")
583
+ def trust_deny(proposal: str):
584
+ """Human-only: deny a parked proposal — decided on the same presence page as approve."""
585
+ c = _container()
586
+ token = c.require_token()
587
+ if token.principal != "interactive":
588
+ _fail("deny is a human-only act; a client principal can only propose")
589
+ p = c.backend.get_proposal(proposal)
590
+ if not p or p.get("status") != "open":
591
+ _fail("no open proposal with that id")
592
+ _decide(c, token, proposal, asked="deny")
593
+
594
+
595
+ @trust_app.command("close-window")
596
+ def trust_close_window():
597
+ """Close every open presence window now: the next human-only act taps again."""
598
+ from egzos.authz.presence import Presence
599
+
600
+ c = _container()
601
+ _owner(c, "closing a presence window")
602
+ Presence(c).close_windows()
603
+ _out({"closed": True}, "presence windows closed")
604
+
605
+
606
+ @trust_app.command("quarantine")
607
+ def trust_quarantine(item: str, reason: str = typer.Option(..., "--reason")):
608
+ """Curate: stop serving an item and everything derived from it, immediately."""
609
+ c = _container()
610
+ token = c.require_token()
611
+ it = _item_ref(c, item)
612
+ try:
613
+ affected = c.trust.quarantine(it, token=token, actor=OWNER, reason=reason)
614
+ except TrustError as e:
615
+ _fail(str(e))
616
+ _out({"affected": affected}, f"quarantined {len(affected)} item(s): {', '.join(affected)}")
617
+
618
+
619
+ # -- tokens ------------------------------------------------------------------------------------
620
+ @token_app.command("create")
621
+ def token_create(
622
+ client: str = typer.Option(..., "--client"),
623
+ role: str = typer.Option(
624
+ "contributor", "--role", help="reader|contributor|operator|curator|admin"
625
+ ),
626
+ scope: list[str] = typer.Option(
627
+ [], "--scope", help="Node ids/paths covered; default: user:self"
628
+ ),
629
+ ):
630
+ """Mint a CLIENT principal for a machine client. Machine clients never touch web auth.
631
+
632
+ The secret IS this command's output, to any stdout, pipe included: it is the deliberate mint
633
+ for scripts and CI, where the caller captures the secret. `connect` is the person-facing
634
+ wrapper, so it prints a pasteable command only to a terminal."""
635
+ c = _container()
636
+ token = _owner(c, "minting a token")
637
+ if not token.has("admin"):
638
+ _fail("token create needs `admin`")
639
+ if role == "admin":
640
+ typer.echo(
641
+ "warning: admin for an agent — it may create any node type in its scopes; it still "
642
+ "cannot mint, approve or read the owner's views",
643
+ err=True,
644
+ )
645
+ scopes = []
646
+ for ref in scope or ["user:self"]:
647
+ if ref == "*":
648
+ scopes.append("*")
649
+ continue
650
+ n = _resolve(c, ref, token)
651
+ if not n:
652
+ _fail(f"scope not found: {ref}")
653
+ scopes.append(n.id)
654
+ t = c.auth.mint(
655
+ principal="client",
656
+ owner=OWNER,
657
+ client=client,
658
+ role=role,
659
+ scopes=scopes,
660
+ actor=OWNER,
661
+ by_principal=token.principal,
662
+ )
663
+ _out(
664
+ {**t.to_dict(), "secret": t.secret},
665
+ f"{t.id}\n client={client} principal=client role={role} "
666
+ f"scopes={','.join(_p(c, s) if s != '*' else '*' for s in scopes)}\n"
667
+ f" export EGZOS_TOKEN={t.secret}\n"
668
+ " # shown once: hand it to the client, never to a human shell",
669
+ )
670
+
671
+
672
+ @token_app.command("revoke")
673
+ def token_revoke(
674
+ token_id: str = typer.Argument(..., help="A client token's id (`egzoscore token ls`)"),
675
+ ):
676
+ """Take a client token back: it stops working at once, and leaves every audience it was in."""
677
+ c = _container()
678
+ token = _owner(c, "revoking a token")
679
+ if not token.has("admin"):
680
+ _fail("token revoke needs `admin`")
681
+ target = c.backend.get_token(token_id)
682
+ if target is None or target.principal != "client":
683
+ # Never the owner's interactive token: it is the key to this container, and nothing
684
+ # re-mints it.
685
+ _fail("no client token with that id")
686
+ if target.revoked:
687
+ _fail(f"{target.id} is already revoked")
688
+ c.auth.revoke(target.id, actor=OWNER, principal=token.principal)
689
+ _out({"id": target.id, "revoked": True}, f"revoked {target.id} (client {target.client})")
690
+
691
+
692
+ @token_app.command("ls")
693
+ def token_ls():
694
+ """Every token: who holds what. An admin over the whole container's view, as `grant ls` is:
695
+ who else holds access is not served to a narrower interactive grant."""
696
+ c = _container()
697
+ owner = _admin(c, "the token list")
698
+ ts = c.backend.list_tokens()
699
+ # An owner view like the others: every principal, its scopes and last use — a read on the chain.
700
+ c.ledger.append("context.fetch", actor=OWNER, principal=owner.principal, client=owner.client,
701
+ view="token ls", items=[], tokens=[t.id for t in ts], layers=[], withheld=0)
702
+ _out(
703
+ [t.to_dict() for t in ts],
704
+ "\n".join(
705
+ f"{t.id} {t.principal:<11} {t.client:<14} {','.join(t.capabilities):<45} "
706
+ f"last_used={t.last_used or '-'}"
707
+ f"{' REVOKED' if t.revoked else ' EXPIRED' if not t.live else ''}"
708
+ for t in ts
709
+ ),
710
+ )
711
+
712
+
713
+ # -- config and identity (container.md §8, identity.md) ----------------------------------------
714
+ def _admin(c: Container, what: str):
715
+ """An owner act over the whole container: the interactive principal with `admin` over `*`."""
716
+ token = _owner(c, what)
717
+ if not token.has("admin") or "*" not in token.scopes:
718
+ _fail(f"{what} needs `admin` over the whole container")
719
+ return token
720
+
721
+
722
+ @config_app.command("get")
723
+ def config_get(key: str | None = typer.Argument(None, help="One key; default: all of them")):
724
+ """The container's settings as they stand, defaults included. None of them is a secret."""
725
+ c = _container()
726
+ token = _owner(c, "the container's config")
727
+ if key is not None and key not in CONTAINER_CONFIG_FIELD_FROM_WIRE_KEY:
728
+ _fail(f"{key}: not a config key")
729
+ keys = [key] if key else list(CONTAINER_CONFIG_FIELD_FROM_WIRE_KEY)
730
+ values = {k: c.config_value(k) for k in keys}
731
+ c.ledger.append(
732
+ "context.fetch", actor=OWNER, principal=token.principal, client=token.client,
733
+ view="config get", items=[], layers=[], withheld=0, keys=keys,
734
+ )
735
+ _out(values, "\n".join(f"{k} = {'(absent)' if v is None else v}" for k, v in values.items()))
736
+
737
+
738
+ @config_app.command("set")
739
+ def config_set(
740
+ key: str = typer.Argument(..., help="A wire key, e.g. identity.issuer"),
741
+ value: str | None = typer.Argument(None, help="The new value"),
742
+ unset: bool = typer.Option(False, "--unset", help="Set the key to absent"),
743
+ ):
744
+ """Change one setting: an admin act, recorded as `config.set`. Only the keys this version
745
+ reads are settable (identity.*, confirm.allow_button); the others are built-in constants."""
746
+ c = _container()
747
+ token = _admin(c, "changing the config")
748
+ if unset == (value is not None):
749
+ _fail("give a value, or --unset")
750
+ try:
751
+ stored = c.set_config(key, None if unset else value, token=token)
752
+ except (ConfigError, PermissionError) as e:
753
+ _fail(str(e))
754
+ _out({key: stored}, f"{key} = {'(absent)' if stored is None else stored}")
755
+
756
+
757
+ @app.command()
758
+ def link(
759
+ issuer: str = typer.Option(
760
+ ..., "--issuer", help="The provider's issuer, e.g. https://<project>.supabase.co/auth/v1"
761
+ ),
762
+ client_id: str = typer.Option(
763
+ ..., "--client-id", help="This container's own OAuth client at the provider"
764
+ ),
765
+ sub: str = typer.Option(..., "--sub", help="Your user id at the provider"),
766
+ name: str = typer.Option("owner", "--name", help="A display name for your grant"),
767
+ ):
768
+ """Link this container to an identity provider (identity.md §4): set its issuer and its own
769
+ client, and grant your provider user everything here. After this, egzos.io can reach the
770
+ container as you, with one sign-in. The owner token keeps working, as the way back in."""
771
+ c = _container()
772
+ token = _admin(c, "linking the container")
773
+ try:
774
+ with c.backend.atomic():
775
+ c.set_config("identity.issuer", issuer, token=token)
776
+ c.set_config("identity.client_id", client_id, token=token)
777
+ grant = c.identity.grant_user(
778
+ sub, name=name, role="admin", scopes=["*"], actor=token.owner,
779
+ principal=token.principal,
780
+ )
781
+ except (ConfigError, PermissionError, ValueError) as e:
782
+ _fail(str(e))
783
+ _out(
784
+ {"issuer": issuer, "client_id": client_id, "grant": grant},
785
+ f"linked to {issuer}\n client {client_id}\n {sub} may do everything here (admin over *)",
786
+ )
787
+
788
+
789
+ @grant_app.command("ls")
790
+ def grant_ls():
791
+ """Who may sign in here, with what: user grants, the agents registered for them, and the
792
+ terminals they signed in at, each kind apart (identity.md §4). An admin over the whole
793
+ container's view: who else holds access is not served to a narrower grant."""
794
+ c = _container()
795
+ token = _admin(c, "the grant list")
796
+ grants = c.backend.list_user_grants()
797
+ agents = c.identity.registrations("agent")
798
+ terminals = c.identity.registrations("terminal")
799
+ c.ledger.append(
800
+ "context.fetch", actor=OWNER, principal=token.principal, client=token.client,
801
+ view="grant ls", items=[], layers=[], withheld=0,
802
+ grants=[g["sub"] for g in grants], agents=[a["client_id"] for a in agents],
803
+ terminals=[t["client_id"] for t in terminals],
804
+ )
805
+ rows = [
806
+ f"{g['sub']} {g['name']:<14} {','.join(g['capabilities']):<45} "
807
+ f"scopes={','.join(_p(c, s) if s != '*' else '*' for s in g['scopes'])}"
808
+ f"{' REVOKED' if g['revoked'] else ''}"
809
+ for g in grants
810
+ ] + [
811
+ f"agent {a['client_id']} for {a['sub']} {a['name']:<14} {','.join(a['capabilities'])}"
812
+ f"{' REVOKED' if a['revoked'] else ''}"
813
+ for a in agents
814
+ ] + [
815
+ f"terminal {t['client_id']} for {t['sub']} {t['name']:<14}"
816
+ f"{' ENDED' if t['revoked'] else ''}"
817
+ for t in terminals
818
+ ]
819
+ _out({"grants": grants, "agents": agents, "terminals": terminals},
820
+ "\n".join(rows) or "(no grants)")
821
+
822
+
823
+ @grant_app.command("rm")
824
+ def grant_rm(sub: str = typer.Argument(..., help="The provider user id to revoke")):
825
+ """Revoke a person's grant: it stops working on their next request. The last grant holding
826
+ admin over the whole container stays."""
827
+ c = _container()
828
+ token = _admin(c, "revoking a grant")
829
+ try:
830
+ revoked = c.identity.revoke_user(sub, actor=token.owner, principal=token.principal)
831
+ except LastAdmin:
832
+ _fail("that is the last admin grant over the whole container; it stays")
833
+ if not revoked:
834
+ _fail("no live grant for that user")
835
+ _out({"sub": sub, "revoked": True}, f"revoked {sub}")
836
+
837
+
838
+ @credential_app.command("ls")
839
+ def credential_ls():
840
+ """Every confirm credential registered here, whose and for which site. Never the key."""
841
+ c = _container()
842
+ token = _admin(c, "the credential list")
843
+ creds = [x for x in c.backend.list_credentials() if not x["removed"]]
844
+ c.ledger.append(
845
+ "context.fetch", actor=OWNER, principal=token.principal, client=token.client,
846
+ read="credentials", items=[], layers=[], withheld=0,
847
+ )
848
+ rows = [{k: x[k] for k in ("id", "person", "name", "rp_id", "created_at", "last_used")}
849
+ for x in creds]
850
+ _out(rows, "\n".join(f"{r['id']} {r['person']:<24} {r['name']:<16} {r['rp_id']:<20} "
851
+ f"last_used={r['last_used'] or '-'}" for r in rows) or "(none)")
852
+
853
+
854
+ @credential_app.command("rm")
855
+ def credential_rm(credential_id: str = typer.Argument(..., help="An id from `credential ls`")):
856
+ """Remove a confirm credential: the owner's recovery path (rest.md §4.3), held by the owner
857
+ token. The person then confirms with the button until they enrol again, where buttons are on."""
858
+ c = _container()
859
+ token = _admin(c, "removing a credential")
860
+ cred = c.backend.get_credential(credential_id)
861
+ if cred is None or cred["removed"]:
862
+ _fail("no credential with that id")
863
+ with c.backend.atomic():
864
+ c.confirm.remove(token, cred)
865
+ _out({"id": credential_id, "removed": True}, f"removed {credential_id} ({cred['person']})")
866
+
867
+
868
+ # -- audit ------------------------------------------------------------------------------------
869
+ @audit_app.command("tail")
870
+ def audit_tail(n: int = typer.Option(20, "-n")):
871
+ """The last n audit entries — reads included."""
872
+ c = _container()
873
+ token = _owner(c, "the audit chain")
874
+ entries = c.ledger.tail(n)
875
+ c.ledger.append(
876
+ "context.fetch", actor=OWNER, principal=token.principal, client=token.client,
877
+ view="audit tail", items=[], layers=[], withheld=0, entries=len(entries),
878
+ )
879
+ _out(
880
+ entries,
881
+ "\n".join(
882
+ f"{e['seq']:>5} {e['ts']} {e['event']:<18} {e['principal']:<11} "
883
+ f"{(e.get('subject') or '-')[:26]:<26} "
884
+ f"{json.dumps(e.get('details') or {}, ensure_ascii=False)[:70]}"
885
+ for e in entries
886
+ )
887
+ or "(empty)",
888
+ )
889
+
890
+
891
+ @audit_app.command("verify")
892
+ def audit_verify():
893
+ """Walk the hash chain from genesis. Exit 1 if it is broken."""
894
+ c = _container()
895
+ token = _owner(c, "the audit chain")
896
+ result = c.ledger.verify()
897
+ c.ledger.append(
898
+ "context.fetch", actor=OWNER, principal=token.principal, client=token.client,
899
+ view="audit verify", items=[], layers=[], withheld=0, entries=result["entries"],
900
+ )
901
+ _out(
902
+ result,
903
+ (
904
+ f"chain ok · {result['entries']} entries · head {result['head'][:16]}…"
905
+ if result["ok"]
906
+ else f"CHAIN BROKEN at seq {result['broken_at']}: {result['reason']}"
907
+ ),
908
+ )
909
+ if not result["ok"]:
910
+ raise typer.Exit(1)
911
+
912
+
913
+ # -- serve ------------------------------------------------------------------------------------
914
+ @app.command()
915
+ def serve(
916
+ mcp: bool = typer.Option(False, "--mcp", help="Speak MCP over stdio."),
917
+ http: bool = typer.Option(False, "--http", help="Serve the REST door: /v1/ and MCP at /mcp."),
918
+ host: str = typer.Option("127.0.0.1", "--host", help="The door's listening address."),
919
+ port: int = typer.Option(7426, "--port", help="The door's port."),
920
+ tls_cert: Path | None = typer.Option(None, "--tls-cert", help="TLS certificate (PEM)."),
921
+ tls_key: Path | None = typer.Option(None, "--tls-key", help="TLS private key (PEM)."),
922
+ token: str | None = typer.Option(
923
+ None, "--token", help="Client token value; default: $EGZOS_TOKEN"
924
+ ),
925
+ ):
926
+ """Open a door. `--mcp` speaks MCP over stdio as the CLIENT principal it was started with —
927
+ never as you. `--http` serves the REST door, and MCP over HTTP at `/mcp`, where every request
928
+ brings its own credential: a container token, or a sign-in from the provider
929
+ `egzoscore link` set (rest.md, identity.md)."""
930
+ if mcp == http:
931
+ _fail("choose one door: --mcp (stdio) or --http (the REST door)", 2)
932
+ c = _container()
933
+ if http:
934
+ from egzos.api import serve_http
935
+
936
+ try:
937
+ serve_http(c, host=host, port=port, tls_cert=tls_cert, tls_key=tls_key)
938
+ except (PermissionError, ValueError) as e:
939
+ _fail(str(e), 2)
940
+ return
941
+ tid = token or os.environ.get("EGZOS_TOKEN")
942
+ if not tid:
943
+ _fail(
944
+ "serve needs a client token: `egzoscore token create --client <name>` "
945
+ "then --token / EGZOS_TOKEN",
946
+ 2,
947
+ )
948
+ t = c.auth.use(tid)
949
+ if not t:
950
+ _fail("token unknown or revoked", 2)
951
+ if t.principal == "interactive":
952
+ _fail(
953
+ "refusing to serve on an interactive token — agents never hold the human's principal", 2
954
+ )
955
+ from egzos.mcp.server import serve_stdio
956
+
957
+ serve_stdio(c, t)
958
+
959
+
960
+ @app.command()
961
+ def web(
962
+ port: int = typer.Option(7425, "--port", help="Loopback port."),
963
+ no_open: bool = typer.Option(False, "--no-open", help="Don't open a browser."),
964
+ ):
965
+ """The lifeboat: search, items and the pending queue in your browser, on loopback only."""
966
+ c = _container()
967
+ _owner(c, "the lifeboat")
968
+ from egzos.web import serve_web
969
+
970
+ serve_web(c, port=port, open_browser=not no_open)
971
+
972
+
973
+ @app.command()
974
+ def connect(
975
+ client: str = typer.Argument("claude-code", help="Client to connect: claude-code"),
976
+ role: str = typer.Option("contributor", "--role", help="reader|contributor|operator|curator"),
977
+ scope: list[str] = typer.Option([], "--scope", help="Scopes it may see; default: user:self"),
978
+ apply: bool = typer.Option(False, "--apply", help="Run `claude mcp add` for you."),
979
+ ):
980
+ """Mint a client token for an MCP client and wire it up (Claude Code by default)."""
981
+ c = _container()
982
+ token = _owner(c, "minting a token")
983
+ if not token.has("admin"):
984
+ _fail("minting a token needs `admin`")
985
+ if role == "admin":
986
+ _fail("connect never mints admin for an agent; use `egzoscore token create` deliberately")
987
+ from egzos.authz.presence import is_terminal
988
+
989
+ if not apply and not is_terminal():
990
+ # The printed command carries the client secret: it goes to a person at a terminal, or
991
+ # straight to `claude mcp add` with --apply — never to a program's pipe.
992
+ _fail("connect prints a secret: run it from a terminal, or pass --apply")
993
+ scopes = []
994
+ for ref in scope or ["user:self"]:
995
+ n = _resolve(c, ref, token)
996
+ if not n:
997
+ _fail(f"scope not found: {ref}")
998
+ scopes.append(n.id)
999
+ t = c.auth.mint(
1000
+ principal="client",
1001
+ owner=OWNER,
1002
+ client=client,
1003
+ role=role,
1004
+ scopes=scopes,
1005
+ actor=OWNER,
1006
+ by_principal=token.principal,
1007
+ )
1008
+ egzos_bin = shutil.which(PROG) or PROG
1009
+ cmd = [
1010
+ "claude", "mcp", "add", "--scope", "user", MCP_NAME,
1011
+ "-e", f"EGZOS_TOKEN={t.secret}",
1012
+ "-e", f"EGZOS_HOME={c.home}",
1013
+ "--", egzos_bin, "serve", "--mcp",
1014
+ ]
1015
+ if apply:
1016
+ # Residual, named: the secret rides `claude mcp add`'s argv while that process runs,
1017
+ # readable by other local users on a shared host — the class of the tap URL in the
1018
+ # launcher's argv (authz/presence.py). A shell running as the user is the user.
1019
+ if not shutil.which("claude"):
1020
+ _fail("`claude` is not on PATH; run the printed command once Claude Code is installed")
1021
+ # An entry from an earlier run, written when this program's command was `egzos`, holds
1022
+ # the same name: take it away first, so the add replaces it and never stops on it. The
1023
+ # name is not changed, and an entry that is not there is no error.
1024
+ subprocess.run(
1025
+ ["claude", "mcp", "remove", "--scope", "user", MCP_NAME],
1026
+ check=False, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
1027
+ stderr=subprocess.DEVNULL,
1028
+ )
1029
+ subprocess.run(cmd, check=True)
1030
+ _out(
1031
+ {
1032
+ "token": t.id,
1033
+ "client": client,
1034
+ "role": role,
1035
+ # Once `claude mcp add` holds the secret, no output repeats it.
1036
+ "command": [
1037
+ "EGZOS_TOKEN=<registered>" if apply and a.startswith("EGZOS_TOKEN=") else a
1038
+ for a in cmd
1039
+ ],
1040
+ "applied": apply,
1041
+ },
1042
+ f"client token minted for {client} (role {role}, principal client)\n"
1043
+ + ("registered with Claude Code." if apply else
1044
+ "register it with Claude Code:\n " + " ".join(shlex.quote(x) for x in cmd)),
1045
+ )
1046
+
1047
+
1048
+ def _json_requested(args: list[str]) -> bool:
1049
+ """Whether `--json` was typed as an option: anywhere before a `--`, after which it is data."""
1050
+ return "--json" in (args[: args.index("--")] if "--" in args else args)
1051
+
1052
+
1053
+ def _answer(args: list[str], word: str, code: int) -> int:
1054
+ """rest.md §3 in the CLI's channel: the door's word, as JSON to a `--json` caller, and a
1055
+ non-zero exit status, never a driver's message."""
1056
+ if _json_requested(args):
1057
+ typer.echo(json.dumps({"error": word}, indent=2))
1058
+ else:
1059
+ typer.echo(f"Error: {word}", err=True)
1060
+ return code
1061
+
1062
+
1063
+ def main(argv: list[str] | None = None) -> int:
1064
+ """Entry point. Returns an exit code (tests call main([]))."""
1065
+ args = sys.argv[1:] if argv is None else argv
1066
+ if holds_nul(args): # a real argv cannot carry U+0000; a caller in process can (rest.md §3)
1067
+ return _answer(args, "invalid_request", 2)
1068
+ try:
1069
+ rv = app(args=args or ["--help"], prog_name=PROG, standalone_mode=False)
1070
+ return int(rv) if isinstance(rv, int) else 0
1071
+ except typer.Exit as e:
1072
+ return int(e.exit_code)
1073
+ except typer.TyperException as e:
1074
+ # A usage error (unknown command or option, missing argument): one line and a hint on
1075
+ # stderr, never a traceback. The message can echo what was typed, so it goes through safe.
1076
+ msg = e.format_message() if hasattr(e, "format_message") else str(e)
1077
+ if _json_requested(args):
1078
+ # A `--json` caller gets JSON every time, as `_fail` gives it (#203). Parsing failed
1079
+ # before the app callback ran, so the flag is read from the arguments, not `_state`.
1080
+ typer.echo(safe(json.dumps({"error": msg}, indent=2, ensure_ascii=False), json=True))
1081
+ else:
1082
+ ctx = getattr(e, "ctx", None)
1083
+ path = safe(ctx.command_path if ctx else PROG)
1084
+ typer.echo(f"Error: {safe(msg)}\nTry '{path} --help'.", err=True)
1085
+ return int(getattr(e, "exit_code", 2))
1086
+ except SystemExit as e:
1087
+ return int(e.code or 0)
1088
+ except PermissionError as e:
1089
+ typer.echo(safe(str(e)), err=True)
1090
+ return 2
1091
+ except StorageBusy: # the write lock was not taken in time, so nothing was written
1092
+ return _answer(args, "busy", 1)