maximem-synap-cli 0.3.5__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.
@@ -0,0 +1,178 @@
1
+ Metadata-Version: 2.4
2
+ Name: maximem-synap-cli
3
+ Version: 0.3.5
4
+ Summary: maximem-synap — provision and operate Synap from your terminal
5
+ Author-email: Maximem <hello@maximem.ai>
6
+ License: Proprietary
7
+ Project-URL: Homepage, https://maximem.ai
8
+ Project-URL: Documentation, https://docs.maximem.ai
9
+ Keywords: synap,maximem,memory,cli,agents
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ Requires-Dist: typer>=0.12
19
+ Requires-Dist: httpx>=0.27
20
+ Requires-Dist: rich>=13
21
+
22
+ # maximem-synap
23
+
24
+ The **developer CLI** for [Synap](https://maximem.ai) — provision and operate
25
+ your Synap account from the terminal.
26
+
27
+ > **CLI vs SDK.** This CLI is the *control plane* for developers. It is **not**
28
+ > the runtime SDK. Your agents/apps integrate Synap with `@maximem/synap-js-sdk`
29
+ > or the Python SDK (`recall`, `save_memories`, `context`). The CLI is for
30
+ > humans: logging in, creating instances, minting keys, managing your team.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ npx @maximem/synap-cli@latest auth login
36
+ ```
37
+
38
+ That bootstraps the Python CLI onto your PATH (`~/.local/bin/maximem-synap`) and
39
+ then runs it — the gcloud model: install a package, then `auth login`.
40
+
41
+ Requires Python 3.10+ on the host (the CLI itself is Python; the npm package is
42
+ just the installer).
43
+
44
+ > **npx is the only supported channel right now.** Homebrew,
45
+ > `curl | sh`, and `pipx install maximem-synap-cli` all resolve the CLI from
46
+ > PyPI, and it has not been published there yet — those channels will fail. The
47
+ > npm package bundles the wheel, which is why it works. See
48
+ > [`packaging/README.md`](../../packaging/README.md) for the publish checklist.
49
+
50
+ ## Log in (browser, like `gcloud auth login`)
51
+
52
+ ```bash
53
+ maximem-synap auth login
54
+ ```
55
+
56
+ Prints a short code and opens your browser. Confirm the code, pick your client,
57
+ approve — and you're logged in. Works over SSH too (just open the printed URL).
58
+
59
+ ```bash
60
+ maximem-synap whoami # which account am I? Also shows user_context_isolation
61
+ maximem-synap auth list # profile, workspace, environment, active marker
62
+ ```
63
+
64
+ `whoami` shows `user_context_isolation` as `b2c` or `b2b` so you can tell them apart without a
65
+ second call. It comes from the server's `/whoami`; if that lacks it, it is read from the one
66
+ instance the key is scoped to, and otherwise it says `unknown` (never a guess).
67
+
68
+ ### Profiles: logins never overwrite another workspace
69
+
70
+ - `auth login --code` names the profile after the workspace (lowercase `a-z0-9-`, at most 30
71
+ characters; `-2`, `-3` on a name clash with another workspace). Logging in again to the same
72
+ workspace and environment updates that profile in place. A different workspace or environment
73
+ always gets its own profile; the old one is left byte for byte as it was.
74
+ - `--profile NAME` always means NAME. If NAME holds a different workspace or environment the
75
+ login is refused with exit 6 (`profile_conflict`) unless you pass `--force`.
76
+ - A one-time-code login (the agent flow) always becomes the active profile, so later commands
77
+ need no `--profile`. If another profile was active, the CLI says so and how to switch back
78
+ (`maximem-synap auth use <name>`); `--output json` carries `previous_active_profile`.
79
+ - Browser login is more conservative: it becomes active only if nothing was active or the active
80
+ profile is the same workspace. Otherwise it prints `Your active profile is still <other>`.
81
+ - Long-running commands (`instances wait`) capture the profile and key once at start, so a login
82
+ that rewrites the config mid-run does not change who they talk to.
83
+
84
+ ## What you can do
85
+
86
+ ```bash
87
+ maximem-synap instances list
88
+ maximem-synap instances create --name "Acme Support" --relationship b2c
89
+ maximem-synap api-keys create --instance <id> --label prod # shown once
90
+ maximem-synap client members list
91
+ maximem-synap --help
92
+ ```
93
+
94
+ Use `--output json` (or its alias `--json`) on any command for scripting, and
95
+ `--profile <name>` to keep multiple accounts side by side. Global flags (`--output`,
96
+ `--json`, `--profile`, `--env`, `--api-base`, `--verbose`) may be placed before or after the
97
+ command. `--json` together with `--output table|csv` is a usage error (exit 2).
98
+
99
+ ## CI / non-interactive
100
+
101
+ No browser? Authenticate with a key instead of `auth login`:
102
+
103
+ ```bash
104
+ export SYNAP_API_KEY=synap_... # from `maximem-synap api-keys create`
105
+ maximem-synap instances list --output json
106
+ ```
107
+
108
+ `SYNAP_API_KEY` overrides any profile and writes nothing to disk. Or persist a key
109
+ with `maximem-synap auth activate --key synap_...`.
110
+
111
+ ## Agent-driven setup (no browser, no prompts)
112
+
113
+ Everything a coding agent needs runs without a TTY or a browser:
114
+
115
+ ```bash
116
+ maximem-synap auth login --code syn_ob_XXXX-XXXX-XXXX # or SYNAP_ONBOARDING_CODE=...
117
+ maximem-synap onboard status -o json # where is setup up to?
118
+ maximem-synap instances template --output-file usecase.md # the use-case template
119
+ maximem-synap instances create --name "Acme" --relationship <b2c|b2b|internal|agent_to_agent> --from-file usecase.md
120
+ # or: ... --from-stdin < usecase.md (--relationship is always required: no default, asked of the human)
121
+ maximem-synap api-keys create -i <id> --write-env # key goes to ./.env, never printed
122
+ maximem-synap api-keys rotate <key-id> --yes --write-env # new key to ./.env, old one revoked, never printed
123
+ maximem-synap instances wait <id> --timeout 1200 # blocks until the memory build is done
124
+ maximem-synap onboard report integrating in_progress # steps: use_case_drafted, use_case_approved,
125
+ # integrating, env_written
126
+ maximem-synap onboard ask "Is this B2C or B2B?" # tell the dashboard you are waiting; --clear to clear
127
+ maximem-synap skill install [--agent claude-code|cursor|codex|auto]
128
+ ```
129
+
130
+ Onboarding codes work once, expire after 10 minutes and are accepted in any letter case; copy a
131
+ fresh prompt from the dashboard if one is rejected. The code is never printed or logged. Without
132
+ `--code` (or `SYNAP_ONBOARDING_CODE`), `auth login` under `--non-interactive` exits 3 instead of
133
+ opening a browser. Onboarding keys last exactly 7 days and cannot be renewed (`auth refresh` answers 403 `onboarding_key_not_refreshable`, exit 3); after expiry a fresh prompt with a new code is needed. `whoami` only warns in the last 24 hours.
134
+
135
+ `--write-env [PATH]` (default `./.env`) writes `SYNAP_API_KEY` and `SYNAP_INSTANCE_ID`, and for a
136
+ non-production environment also `SYNAP_BASE_URL`, `SYNAP_GRPC_HOST`, `SYNAP_GRPC_PORT` and
137
+ `SYNAP_GRPC_USE_TLS`. It creates the file with mode `0600` and updates existing lines in place: a
138
+ variable already there (also as `export NAME=...` or with a quoted value, even if added by hand
139
+ and repeated) is replaced and kept exactly once, never duplicated. It also adds the file to `.gitignore`, and prints only a masked key
140
+ (`synap_…abcd`) and the path. An existing file keeps its mode, CRLF line endings and `export ` prefixes;
141
+ the gitignore check understands patterns and `!` negations. `api-keys rotate` takes the same flags. `--write-env PATH` is shorthand for `--write-env --env-file PATH`.
142
+
143
+ `instances wait` prints progress on stderr and one JSON object on stdout. If the configuration is
144
+ waiting for review by Synap it exits 1 at once instead of waiting for the timeout.
145
+
146
+ If `SYNAP_API_KEY` holds a runtime key (for example you sourced the project `.env`), management
147
+ calls return 401/403 and the CLI says so; run `env -u SYNAP_API_KEY maximem-synap ...`.
148
+
149
+ ### `--non-interactive`
150
+
151
+ Global flag, also on automatically when stdin is not a TTY or `SYNAP_NON_INTERACTIVE=1`
152
+ (`SYNAP_NON_INTERACTIVE=0` forces prompts back on). A command that would ask a question
153
+ fails instead, naming the flag that answers it (for example `--yes`).
154
+
155
+ ### Exit codes and JSON errors
156
+
157
+ | Code | Meaning |
158
+ |---|---|
159
+ | 0 | ok |
160
+ | 1 | generic error (also: `instances wait` build failed) |
161
+ | 2 | usage / invalid argument / confirmation needed |
162
+ | 3 | auth: not logged in, expired or invalid key or code |
163
+ | 4 | not found |
164
+ | 5 | permission / missing scope |
165
+ | 6 | conflict |
166
+ | 7 | timeout (request or `instances wait`) |
167
+ | 8 | server error or network failure |
168
+
169
+ With `--output json`, errors go to stderr as
170
+ `{"error": {"code": "<snake_case>", "message": "...", "exit_code": N, "hint": "..."}}`.
171
+ When the server sent a structured error body (for example the credits needed and available on a 402, code `insufficient_credits`, exit 1), it is passed through as `error.details`.
172
+ In table mode they stay plain text (a `Hint:` line is added when there is one).
173
+
174
+ ## Config
175
+
176
+ Credentials live in `~/.config/synap/config.json` (mode `0600`). One key per
177
+ profile, bound to one client. `maximem-synap auth logout` revokes server-side and
178
+ removes it locally.
@@ -0,0 +1,30 @@
1
+ synap/cli/README.md,sha256=l_bofTKb6XZkCFo0mkiPP-nnuBkkjk-ZFIgb2zeFxFc,8274
2
+ synap/cli/__init__.py,sha256=A4NhbzVj35dNqsXomzUjtoBji_lGSBvJc89bVLcPHds,430
3
+ synap/cli/__main__.py,sha256=ohItVx9ZOw-HFRuO836NqgBJ0rrUZFDURW_oaQkptcY,5568
4
+ synap/cli/action_rows.py,sha256=jSC0vHrgvwF7-l8UoHSsTOoXAwBID5WtSkPjrk5SZLI,1370
5
+ synap/cli/api.py,sha256=fFd36fJs4lO-DVaUzkvj4dbLeDx4Tr4UEMfWkxTFyY0,15659
6
+ synap/cli/app.py,sha256=uAFuz0Efwedex1e6DEk5MGj3hTP09TS9TJ3oXB0LUaM,15867
7
+ synap/cli/config.py,sha256=ngp9Tf9b00aT_HeB00C5gPNAT2FJamH8rtxu4W7mv60,10217
8
+ synap/cli/envfile.py,sha256=Hjf5blQYvQACJtNWu7s24B87yyECP2AAWsewZIlW94c,8476
9
+ synap/cli/interactive.py,sha256=EHPkCu5Gw669JKbQfyavZ6gHzqcvwdkl9hjFXccYjtw,3261
10
+ synap/cli/render.py,sha256=xdfutyp-E91wKysiePUF91gFpSaaucVPOZOM2Z5g8WA,4887
11
+ synap/cli/validate.py,sha256=x7RGzSrHIlYsjBLmfaDD3jgFLkybrQHlzu_DoysxjQY,2587
12
+ synap/cli/commands/__init__.py,sha256=q0vmTplIp5tcDIHpxu2tWKk8H_WTHfapUP74jFR0_ww,40
13
+ synap/cli/commands/api_keys.py,sha256=seKTueD9lFBsVbLyCDpXn1uDU5rJo5ZP1CTsu7LSKAs,16919
14
+ synap/cli/commands/auth.py,sha256=kysZBg7ToaOOcio0_it-BIn0jFgQtNI9UiOAHXRVPL0,57150
15
+ synap/cli/commands/billing.py,sha256=ccp5S2reHPq7P4wN70-PUxa6xVkYE375LL4XRf5Sk5U,13520
16
+ synap/cli/commands/client.py,sha256=XK_bJuCF-vkiDmhnRmZpCo6qijQ9BHO6wKGzMThnyZQ,3113
17
+ synap/cli/commands/config_cmd.py,sha256=GeWUAHjJBhlHhrfRtjw61GStJn41z5EXy9mKdk7Hg1Q,1594
18
+ synap/cli/commands/instances.py,sha256=FKtUbBTuYfUK9x4WkB_TYr7yhGDiDwPFSIN6YQJeu4E,25041
19
+ synap/cli/commands/memories.py,sha256=AQ5OjB0ocOWWLkes9n1sBh2vGJ2SUhqPRo7kY543FWU,5237
20
+ synap/cli/commands/onboard.py,sha256=yWGhja7Q-eop7KjJO_o3yhxsp2U3C0mE_-HhVkfrS5U,8759
21
+ synap/cli/commands/privacy.py,sha256=4NtdzrNZRbnrS80m5jAatIMnV1y4TBrpfDjjbUf0eEk,26964
22
+ synap/cli/commands/requests.py,sha256=bEYuZRwif9GkAxB2SprFaGM5fOhzeJ_ZpwVYP7LZiCs,7390
23
+ synap/cli/commands/scoping.py,sha256=fnOUtVr3Fl0EcYvYY0Raor9InGbWBUsBeA3TqHKY1SQ,17535
24
+ synap/cli/commands/skill.py,sha256=hfyZMioI_By4u7uv4fpRozGbSkjCFEb7utuX5kZ5K9k,3399
25
+ synap/cli/commands/visibility.py,sha256=O2Zvs7sRkC0V8slYhjtcr6voxOfR8PFkSb65G-_wiv0,10551
26
+ maximem_synap_cli-0.3.5.dist-info/METADATA,sha256=Mw8nlEoaOBJuJqhR6QySG7Q8-gnTJRVuymVK7ummEJk,9030
27
+ maximem_synap_cli-0.3.5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
28
+ maximem_synap_cli-0.3.5.dist-info/entry_points.txt,sha256=OQJkV59r_brlX-rYPOnM07wP8RwGq0IwiGhlQKh5LyI,90
29
+ maximem_synap_cli-0.3.5.dist-info/top_level.txt,sha256=KI0xCAwpcOCX9nvJvjLnbkHPlW9IA2Jp_dCqpOAmDR4,6
30
+ maximem_synap_cli-0.3.5.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ maximem-synap = synap.cli.__main__:main
3
+ synap = synap.cli.__main__:main
@@ -0,0 +1 @@
1
+ synap
synap/cli/README.md ADDED
@@ -0,0 +1,157 @@
1
+ # maximem-synap
2
+
3
+ The **developer CLI** for [Synap](https://maximem.ai) — provision and operate
4
+ your Synap account from the terminal.
5
+
6
+ > **CLI vs SDK.** This CLI is the *control plane* for developers. It is **not**
7
+ > the runtime SDK. Your agents/apps integrate Synap with `@maximem/synap-js-sdk`
8
+ > or the Python SDK (`recall`, `save_memories`, `context`). The CLI is for
9
+ > humans: logging in, creating instances, minting keys, managing your team.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npx @maximem/synap-cli@latest auth login
15
+ ```
16
+
17
+ That bootstraps the Python CLI onto your PATH (`~/.local/bin/maximem-synap`) and
18
+ then runs it — the gcloud model: install a package, then `auth login`.
19
+
20
+ Requires Python 3.10+ on the host (the CLI itself is Python; the npm package is
21
+ just the installer).
22
+
23
+ > **npx is the only supported channel right now.** Homebrew,
24
+ > `curl | sh`, and `pipx install maximem-synap-cli` all resolve the CLI from
25
+ > PyPI, and it has not been published there yet — those channels will fail. The
26
+ > npm package bundles the wheel, which is why it works. See
27
+ > [`packaging/README.md`](../../packaging/README.md) for the publish checklist.
28
+
29
+ ## Log in (browser, like `gcloud auth login`)
30
+
31
+ ```bash
32
+ maximem-synap auth login
33
+ ```
34
+
35
+ Prints a short code and opens your browser. Confirm the code, pick your client,
36
+ approve — and you're logged in. Works over SSH too (just open the printed URL).
37
+
38
+ ```bash
39
+ maximem-synap whoami # which account am I? Also shows user_context_isolation
40
+ maximem-synap auth list # profile, workspace, environment, active marker
41
+ ```
42
+
43
+ `whoami` shows `user_context_isolation` as `b2c` or `b2b` so you can tell them apart without a
44
+ second call. It comes from the server's `/whoami`; if that lacks it, it is read from the one
45
+ instance the key is scoped to, and otherwise it says `unknown` (never a guess).
46
+
47
+ ### Profiles: logins never overwrite another workspace
48
+
49
+ - `auth login --code` names the profile after the workspace (lowercase `a-z0-9-`, at most 30
50
+ characters; `-2`, `-3` on a name clash with another workspace). Logging in again to the same
51
+ workspace and environment updates that profile in place. A different workspace or environment
52
+ always gets its own profile; the old one is left byte for byte as it was.
53
+ - `--profile NAME` always means NAME. If NAME holds a different workspace or environment the
54
+ login is refused with exit 6 (`profile_conflict`) unless you pass `--force`.
55
+ - A one-time-code login (the agent flow) always becomes the active profile, so later commands
56
+ need no `--profile`. If another profile was active, the CLI says so and how to switch back
57
+ (`maximem-synap auth use <name>`); `--output json` carries `previous_active_profile`.
58
+ - Browser login is more conservative: it becomes active only if nothing was active or the active
59
+ profile is the same workspace. Otherwise it prints `Your active profile is still <other>`.
60
+ - Long-running commands (`instances wait`) capture the profile and key once at start, so a login
61
+ that rewrites the config mid-run does not change who they talk to.
62
+
63
+ ## What you can do
64
+
65
+ ```bash
66
+ maximem-synap instances list
67
+ maximem-synap instances create --name "Acme Support" --relationship b2c
68
+ maximem-synap api-keys create --instance <id> --label prod # shown once
69
+ maximem-synap client members list
70
+ maximem-synap --help
71
+ ```
72
+
73
+ Use `--output json` (or its alias `--json`) on any command for scripting, and
74
+ `--profile <name>` to keep multiple accounts side by side. Global flags (`--output`,
75
+ `--json`, `--profile`, `--env`, `--api-base`, `--verbose`) may be placed before or after the
76
+ command. `--json` together with `--output table|csv` is a usage error (exit 2).
77
+
78
+ ## CI / non-interactive
79
+
80
+ No browser? Authenticate with a key instead of `auth login`:
81
+
82
+ ```bash
83
+ export SYNAP_API_KEY=synap_... # from `maximem-synap api-keys create`
84
+ maximem-synap instances list --output json
85
+ ```
86
+
87
+ `SYNAP_API_KEY` overrides any profile and writes nothing to disk. Or persist a key
88
+ with `maximem-synap auth activate --key synap_...`.
89
+
90
+ ## Agent-driven setup (no browser, no prompts)
91
+
92
+ Everything a coding agent needs runs without a TTY or a browser:
93
+
94
+ ```bash
95
+ maximem-synap auth login --code syn_ob_XXXX-XXXX-XXXX # or SYNAP_ONBOARDING_CODE=...
96
+ maximem-synap onboard status -o json # where is setup up to?
97
+ maximem-synap instances template --output-file usecase.md # the use-case template
98
+ maximem-synap instances create --name "Acme" --relationship <b2c|b2b|internal|agent_to_agent> --from-file usecase.md
99
+ # or: ... --from-stdin < usecase.md (--relationship is always required: no default, asked of the human)
100
+ maximem-synap api-keys create -i <id> --write-env # key goes to ./.env, never printed
101
+ maximem-synap api-keys rotate <key-id> --yes --write-env # new key to ./.env, old one revoked, never printed
102
+ maximem-synap instances wait <id> --timeout 1200 # blocks until the memory build is done
103
+ maximem-synap onboard report integrating in_progress # steps: use_case_drafted, use_case_approved,
104
+ # integrating, env_written
105
+ maximem-synap onboard ask "Is this B2C or B2B?" # tell the dashboard you are waiting; --clear to clear
106
+ maximem-synap skill install [--agent claude-code|cursor|codex|auto]
107
+ ```
108
+
109
+ Onboarding codes work once, expire after 10 minutes and are accepted in any letter case; copy a
110
+ fresh prompt from the dashboard if one is rejected. The code is never printed or logged. Without
111
+ `--code` (or `SYNAP_ONBOARDING_CODE`), `auth login` under `--non-interactive` exits 3 instead of
112
+ opening a browser. Onboarding keys last exactly 7 days and cannot be renewed (`auth refresh` answers 403 `onboarding_key_not_refreshable`, exit 3); after expiry a fresh prompt with a new code is needed. `whoami` only warns in the last 24 hours.
113
+
114
+ `--write-env [PATH]` (default `./.env`) writes `SYNAP_API_KEY` and `SYNAP_INSTANCE_ID`, and for a
115
+ non-production environment also `SYNAP_BASE_URL`, `SYNAP_GRPC_HOST`, `SYNAP_GRPC_PORT` and
116
+ `SYNAP_GRPC_USE_TLS`. It creates the file with mode `0600` and updates existing lines in place: a
117
+ variable already there (also as `export NAME=...` or with a quoted value, even if added by hand
118
+ and repeated) is replaced and kept exactly once, never duplicated. It also adds the file to `.gitignore`, and prints only a masked key
119
+ (`synap_…abcd`) and the path. An existing file keeps its mode, CRLF line endings and `export ` prefixes;
120
+ the gitignore check understands patterns and `!` negations. `api-keys rotate` takes the same flags. `--write-env PATH` is shorthand for `--write-env --env-file PATH`.
121
+
122
+ `instances wait` prints progress on stderr and one JSON object on stdout. If the configuration is
123
+ waiting for review by Synap it exits 1 at once instead of waiting for the timeout.
124
+
125
+ If `SYNAP_API_KEY` holds a runtime key (for example you sourced the project `.env`), management
126
+ calls return 401/403 and the CLI says so; run `env -u SYNAP_API_KEY maximem-synap ...`.
127
+
128
+ ### `--non-interactive`
129
+
130
+ Global flag, also on automatically when stdin is not a TTY or `SYNAP_NON_INTERACTIVE=1`
131
+ (`SYNAP_NON_INTERACTIVE=0` forces prompts back on). A command that would ask a question
132
+ fails instead, naming the flag that answers it (for example `--yes`).
133
+
134
+ ### Exit codes and JSON errors
135
+
136
+ | Code | Meaning |
137
+ |---|---|
138
+ | 0 | ok |
139
+ | 1 | generic error (also: `instances wait` build failed) |
140
+ | 2 | usage / invalid argument / confirmation needed |
141
+ | 3 | auth: not logged in, expired or invalid key or code |
142
+ | 4 | not found |
143
+ | 5 | permission / missing scope |
144
+ | 6 | conflict |
145
+ | 7 | timeout (request or `instances wait`) |
146
+ | 8 | server error or network failure |
147
+
148
+ With `--output json`, errors go to stderr as
149
+ `{"error": {"code": "<snake_case>", "message": "...", "exit_code": N, "hint": "..."}}`.
150
+ When the server sent a structured error body (for example the credits needed and available on a 402, code `insufficient_credits`, exit 1), it is passed through as `error.details`.
151
+ In table mode they stay plain text (a `Hint:` line is added when there is one).
152
+
153
+ ## Config
154
+
155
+ Credentials live in `~/.config/synap/config.json` (mode `0600`). One key per
156
+ profile, bound to one client. `maximem-synap auth logout` revokes server-side and
157
+ removes it locally.
synap/cli/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """`maximem-synap` — the Synap management CLI.
2
+
3
+ A thin Typer client over the Management API plane (`/api/v1/management/*`).
4
+ Login is a gcloud-style browser device-pairing flow; everything else is
5
+ dashboard-parity operations driven by a `synap_` key + scopes.
6
+
7
+ This package is intentionally dependency-light (typer, httpx, rich, stdlib) and
8
+ imports nothing from `synap.cloud` so it can run standalone.
9
+ """
10
+
11
+ __version__ = "0.3.5"
synap/cli/__main__.py ADDED
@@ -0,0 +1,157 @@
1
+ """Console entry point for `maximem-synap` (also `python -m synap.cli`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ from typing import List
9
+
10
+
11
+ # Root-level (global) options declared on the Typer callback. Click only accepts
12
+ # these BEFORE the subcommand, but users reasonably expect gh/kubectl-style
13
+ # trailing flags (`instances list --output json`) to work too — and our docs and
14
+ # README show them that way. We hoist any recognized global flag (and its value)
15
+ # to the front so both orders behave identically. None of these short forms
16
+ # collide with a subcommand's own short options.
17
+ _GLOBAL_VALUE_OPTS = {"-o", "--output", "-p", "--profile", "--env", "--api-base"}
18
+ _GLOBAL_FLAG_OPTS = {"-v", "--verbose", "--version", "--quiet", "--non-interactive", "--json"}
19
+
20
+
21
+ def _expand_write_env(argv: List[str]) -> List[str]:
22
+ """Turn ``--write-env PATH`` into ``--write-env --env-file PATH``.
23
+
24
+ Click has no optional-value options, but the contract wants ``--write-env
25
+ [PATH]``. A token directly after ``--write-env`` that is not itself an option
26
+ is its path (``api-keys create`` takes no positionals, so this is unambiguous).
27
+ """
28
+ out: List[str] = []
29
+ i = 0
30
+ while i < len(argv):
31
+ tok = argv[i]
32
+ if tok == "--":
33
+ out.extend(argv[i:])
34
+ break
35
+ if tok == "--write-env" and i + 1 < len(argv) and not argv[i + 1].startswith("-"):
36
+ out.extend(["--write-env", "--env-file", argv[i + 1]])
37
+ i += 2
38
+ continue
39
+ if tok.startswith("--write-env="):
40
+ out.extend(["--write-env", "--env-file", tok.split("=", 1)[1]])
41
+ i += 1
42
+ continue
43
+ out.append(tok)
44
+ i += 1
45
+ return out
46
+
47
+
48
+ def _hoist_global_flags(argv: List[str]) -> List[str]:
49
+ """Move recognized global options ahead of the subcommand.
50
+
51
+ Preserves relative order, respects the ``--`` end-of-options marker, and
52
+ supports both ``--output json`` and ``--output=json`` forms. Anything it
53
+ doesn't recognize is left in place, so subcommand options/arguments (and a
54
+ subcommand that happens to share a global's *value*) are untouched.
55
+ """
56
+ argv = _expand_write_env(argv)
57
+ hoisted: List[str] = []
58
+ rest: List[str] = []
59
+ i = 0
60
+ n = len(argv)
61
+ while i < n:
62
+ tok = argv[i]
63
+ if tok == "--": # end-of-options: leave the remainder exactly as-is
64
+ rest.extend(argv[i:])
65
+ break
66
+ name = tok.split("=", 1)[0]
67
+ if name in _GLOBAL_VALUE_OPTS:
68
+ hoisted.append(tok)
69
+ if "=" not in tok and i + 1 < n:
70
+ hoisted.append(argv[i + 1])
71
+ i += 2
72
+ else:
73
+ i += 1
74
+ continue
75
+ if name in _GLOBAL_FLAG_OPTS:
76
+ hoisted.append(tok)
77
+ i += 1
78
+ continue
79
+ rest.append(tok)
80
+ i += 1
81
+ return hoisted + rest
82
+
83
+
84
+ def _completion_active() -> bool:
85
+ """True while a shell-completion request is in flight — Click reads argv/env
86
+ itself then, so we must not reorder or pass args explicitly."""
87
+ return any(k.endswith("_COMPLETE") for k in os.environ)
88
+
89
+
90
+ def _argv_wants_json(argv: List[str]) -> bool:
91
+ """True if argv asks for ``--output json`` (needed before Click parses it)."""
92
+ for i, tok in enumerate(argv):
93
+ if tok == "--":
94
+ break
95
+ if tok == "--json":
96
+ return True
97
+ if tok in ("-o", "--output") and i + 1 < len(argv):
98
+ return argv[i + 1] == "json"
99
+ if tok in ("--output=json", "-o=json"):
100
+ return True
101
+ return False
102
+
103
+
104
+ def _emit_error(exc, *, as_json: bool) -> None:
105
+ """Print a CliError: JSON on stderr in json mode, plain text otherwise."""
106
+ from synap.cli import render
107
+
108
+ if as_json:
109
+ print(json.dumps(exc.to_json()), file=sys.stderr)
110
+ else:
111
+ render.error(exc.message)
112
+ if getattr(exc, "hint", None):
113
+ render.err_console.print(f"[dim]Hint: {exc.hint}[/dim]")
114
+
115
+
116
+ def main() -> None:
117
+ from synap.cli import render
118
+ from synap.cli.api import EXIT_USAGE, CliError
119
+ from synap.cli.app import app
120
+
121
+ argv = sys.argv[1:]
122
+ as_json = _argv_wants_json(argv)
123
+ try:
124
+ if _completion_active():
125
+ app()
126
+ elif as_json:
127
+ # standalone_mode=False lets us turn Click usage errors into the
128
+ # JSON error shape instead of Click's rich text.
129
+ rc = app(args=_hoist_global_flags(argv), standalone_mode=False)
130
+ sys.exit(rc if isinstance(rc, int) else 0)
131
+ else:
132
+ app(args=_hoist_global_flags(argv))
133
+ except CliError as exc:
134
+ _emit_error(exc, as_json=as_json)
135
+ sys.exit(exc.exit_code)
136
+ except KeyboardInterrupt: # pragma: no cover
137
+ render.error("Aborted.")
138
+ sys.exit(130)
139
+ except Exception as exc:
140
+ # Only reachable with standalone_mode=False (JSON mode). Duck-typed because
141
+ # newer Typer ships its own copy of Click's exception classes.
142
+ if type(exc).__name__ == "Exit":
143
+ sys.exit(getattr(exc, "exit_code", 0))
144
+ if type(exc).__name__ == "Abort":
145
+ _emit_error(CliError("Aborted.", code="aborted"), as_json=as_json)
146
+ sys.exit(1)
147
+ if hasattr(exc, "format_message") and hasattr(exc, "exit_code"):
148
+ _emit_error(
149
+ CliError(exc.format_message(), code="usage_error", exit_code=EXIT_USAGE),
150
+ as_json=as_json,
151
+ )
152
+ sys.exit(EXIT_USAGE)
153
+ raise
154
+
155
+
156
+ if __name__ == "__main__":
157
+ main()
@@ -0,0 +1,36 @@
1
+ """Table rows for memory actions (create, update, supersede, delete), as the server sends them.
2
+
3
+ The server's action rows carry ``created_at``, ``content``, ``previous_content`` and ``reason``
4
+ (DashboardManager.get_client_memory_history and get_request_events). There is no ``timestamp`` or
5
+ ``summary`` key, so the table shows ``created_at`` and a ``detail`` built here.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Dict, List
11
+
12
+ _MAX_DETAIL = 80
13
+
14
+
15
+ def _clip(text: str) -> str:
16
+ text = " ".join(str(text).split())
17
+ return text if len(text) <= _MAX_DETAIL else text[: _MAX_DETAIL - 1] + "…"
18
+
19
+
20
+ def action_detail(row: Dict[str, Any]) -> str:
21
+ """What the action did, in one short line: the new text, with the reason after it."""
22
+ content = row.get("content")
23
+ reason = row.get("reason")
24
+ if content:
25
+ return _clip(content) + (f" ({_clip(reason)})" if reason else "")
26
+ previous = row.get("previous_content")
27
+ if previous:
28
+ return _clip(previous) + (f" ({_clip(reason)})" if reason else "")
29
+ return _clip(reason) if reason else "—"
30
+
31
+
32
+ def action_rows(events: Any) -> List[Dict[str, Any]]:
33
+ """``events`` (a list from the server) with a ``detail`` field on each row."""
34
+ if not isinstance(events, list):
35
+ return []
36
+ return [{**e, "detail": action_detail(e)} for e in events if isinstance(e, dict)]