omni-ai-cli 0.0.0-stage → 1.0.0

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 (177) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +615 -2
  3. package/bin/ai.js +84 -0
  4. package/docs/README.en.md +615 -0
  5. package/docs/README.es.md +618 -0
  6. package/docs/README.fr.md +630 -0
  7. package/omni_ai/__init__.py +1 -0
  8. package/omni_ai/__main__.py +6 -0
  9. package/omni_ai/chat.py +1458 -0
  10. package/omni_ai/cli.py +991 -0
  11. package/omni_ai/config.py +531 -0
  12. package/omni_ai/deepseek.py +57 -0
  13. package/omni_ai/grok.py +111 -0
  14. package/omni_ai/onboarding.py +196 -0
  15. package/omni_ai/openrouter.py +335 -0
  16. package/omni_ai/osutils.py +86 -0
  17. package/omni_ai/pii.py +281 -0
  18. package/omni_ai/profiles.json +69 -0
  19. package/omni_ai/skills.py +124 -0
  20. package/omni_ai/sync.py +199 -0
  21. package/omni_ai/tools.py +75 -0
  22. package/omni_ai/ui.py +595 -0
  23. package/omni_ai/usage.py +305 -0
  24. package/omni_ai/vendor/prompt_toolkit/LICENSE +27 -0
  25. package/omni_ai/vendor/prompt_toolkit/__init__.py +52 -0
  26. package/omni_ai/vendor/prompt_toolkit/application/__init__.py +32 -0
  27. package/omni_ai/vendor/prompt_toolkit/application/application.py +1626 -0
  28. package/omni_ai/vendor/prompt_toolkit/application/current.py +195 -0
  29. package/omni_ai/vendor/prompt_toolkit/application/dummy.py +55 -0
  30. package/omni_ai/vendor/prompt_toolkit/application/run_in_terminal.py +114 -0
  31. package/omni_ai/vendor/prompt_toolkit/auto_suggest.py +177 -0
  32. package/omni_ai/vendor/prompt_toolkit/buffer.py +2029 -0
  33. package/omni_ai/vendor/prompt_toolkit/cache.py +127 -0
  34. package/omni_ai/vendor/prompt_toolkit/clipboard/__init__.py +17 -0
  35. package/omni_ai/vendor/prompt_toolkit/clipboard/base.py +109 -0
  36. package/omni_ai/vendor/prompt_toolkit/clipboard/in_memory.py +44 -0
  37. package/omni_ai/vendor/prompt_toolkit/clipboard/pyperclip.py +42 -0
  38. package/omni_ai/vendor/prompt_toolkit/completion/__init__.py +43 -0
  39. package/omni_ai/vendor/prompt_toolkit/completion/base.py +438 -0
  40. package/omni_ai/vendor/prompt_toolkit/completion/deduplicate.py +45 -0
  41. package/omni_ai/vendor/prompt_toolkit/completion/filesystem.py +118 -0
  42. package/omni_ai/vendor/prompt_toolkit/completion/fuzzy_completer.py +213 -0
  43. package/omni_ai/vendor/prompt_toolkit/completion/nested.py +109 -0
  44. package/omni_ai/vendor/prompt_toolkit/completion/word_completer.py +94 -0
  45. package/omni_ai/vendor/prompt_toolkit/contrib/__init__.py +0 -0
  46. package/omni_ai/vendor/prompt_toolkit/contrib/completers/__init__.py +5 -0
  47. package/omni_ai/vendor/prompt_toolkit/contrib/completers/system.py +64 -0
  48. package/omni_ai/vendor/prompt_toolkit/contrib/regular_languages/__init__.py +80 -0
  49. package/omni_ai/vendor/prompt_toolkit/contrib/regular_languages/compiler.py +579 -0
  50. package/omni_ai/vendor/prompt_toolkit/contrib/regular_languages/completion.py +100 -0
  51. package/omni_ai/vendor/prompt_toolkit/contrib/regular_languages/lexer.py +94 -0
  52. package/omni_ai/vendor/prompt_toolkit/contrib/regular_languages/regex_parser.py +279 -0
  53. package/omni_ai/vendor/prompt_toolkit/contrib/regular_languages/validation.py +60 -0
  54. package/omni_ai/vendor/prompt_toolkit/contrib/ssh/__init__.py +8 -0
  55. package/omni_ai/vendor/prompt_toolkit/contrib/ssh/server.py +178 -0
  56. package/omni_ai/vendor/prompt_toolkit/contrib/telnet/__init__.py +7 -0
  57. package/omni_ai/vendor/prompt_toolkit/contrib/telnet/log.py +13 -0
  58. package/omni_ai/vendor/prompt_toolkit/contrib/telnet/protocol.py +209 -0
  59. package/omni_ai/vendor/prompt_toolkit/contrib/telnet/server.py +428 -0
  60. package/omni_ai/vendor/prompt_toolkit/cursor_shapes.py +117 -0
  61. package/omni_ai/vendor/prompt_toolkit/data_structures.py +18 -0
  62. package/omni_ai/vendor/prompt_toolkit/document.py +1182 -0
  63. package/omni_ai/vendor/prompt_toolkit/enums.py +19 -0
  64. package/omni_ai/vendor/prompt_toolkit/eventloop/__init__.py +31 -0
  65. package/omni_ai/vendor/prompt_toolkit/eventloop/async_generator.py +125 -0
  66. package/omni_ai/vendor/prompt_toolkit/eventloop/inputhook.py +191 -0
  67. package/omni_ai/vendor/prompt_toolkit/eventloop/utils.py +101 -0
  68. package/omni_ai/vendor/prompt_toolkit/eventloop/win32.py +72 -0
  69. package/omni_ai/vendor/prompt_toolkit/filters/__init__.py +71 -0
  70. package/omni_ai/vendor/prompt_toolkit/filters/app.py +419 -0
  71. package/omni_ai/vendor/prompt_toolkit/filters/base.py +261 -0
  72. package/omni_ai/vendor/prompt_toolkit/filters/cli.py +65 -0
  73. package/omni_ai/vendor/prompt_toolkit/filters/utils.py +41 -0
  74. package/omni_ai/vendor/prompt_toolkit/formatted_text/__init__.py +59 -0
  75. package/omni_ai/vendor/prompt_toolkit/formatted_text/ansi.py +297 -0
  76. package/omni_ai/vendor/prompt_toolkit/formatted_text/base.py +179 -0
  77. package/omni_ai/vendor/prompt_toolkit/formatted_text/html.py +145 -0
  78. package/omni_ai/vendor/prompt_toolkit/formatted_text/pygments.py +32 -0
  79. package/omni_ai/vendor/prompt_toolkit/formatted_text/utils.py +103 -0
  80. package/omni_ai/vendor/prompt_toolkit/history.py +306 -0
  81. package/omni_ai/vendor/prompt_toolkit/input/__init__.py +14 -0
  82. package/omni_ai/vendor/prompt_toolkit/input/ansi_escape_sequences.py +344 -0
  83. package/omni_ai/vendor/prompt_toolkit/input/base.py +153 -0
  84. package/omni_ai/vendor/prompt_toolkit/input/defaults.py +79 -0
  85. package/omni_ai/vendor/prompt_toolkit/input/posix_pipe.py +118 -0
  86. package/omni_ai/vendor/prompt_toolkit/input/posix_utils.py +97 -0
  87. package/omni_ai/vendor/prompt_toolkit/input/typeahead.py +78 -0
  88. package/omni_ai/vendor/prompt_toolkit/input/vt100.py +309 -0
  89. package/omni_ai/vendor/prompt_toolkit/input/vt100_parser.py +250 -0
  90. package/omni_ai/vendor/prompt_toolkit/input/win32.py +749 -0
  91. package/omni_ai/vendor/prompt_toolkit/input/win32_pipe.py +156 -0
  92. package/omni_ai/vendor/prompt_toolkit/key_binding/__init__.py +22 -0
  93. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/__init__.py +0 -0
  94. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/auto_suggest.py +66 -0
  95. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/basic.py +257 -0
  96. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/completion.py +206 -0
  97. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/cpr.py +30 -0
  98. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/emacs.py +563 -0
  99. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/focus.py +26 -0
  100. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/mouse.py +348 -0
  101. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/named_commands.py +691 -0
  102. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/open_in_editor.py +52 -0
  103. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/page_navigation.py +85 -0
  104. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/scroll.py +190 -0
  105. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/search.py +96 -0
  106. package/omni_ai/vendor/prompt_toolkit/key_binding/bindings/vi.py +2233 -0
  107. package/omni_ai/vendor/prompt_toolkit/key_binding/defaults.py +63 -0
  108. package/omni_ai/vendor/prompt_toolkit/key_binding/digraphs.py +1378 -0
  109. package/omni_ai/vendor/prompt_toolkit/key_binding/emacs_state.py +36 -0
  110. package/omni_ai/vendor/prompt_toolkit/key_binding/key_bindings.py +670 -0
  111. package/omni_ai/vendor/prompt_toolkit/key_binding/key_processor.py +526 -0
  112. package/omni_ai/vendor/prompt_toolkit/key_binding/vi_state.py +107 -0
  113. package/omni_ai/vendor/prompt_toolkit/keys.py +222 -0
  114. package/omni_ai/vendor/prompt_toolkit/layout/__init__.py +147 -0
  115. package/omni_ai/vendor/prompt_toolkit/layout/containers.py +2738 -0
  116. package/omni_ai/vendor/prompt_toolkit/layout/controls.py +945 -0
  117. package/omni_ai/vendor/prompt_toolkit/layout/dimension.py +220 -0
  118. package/omni_ai/vendor/prompt_toolkit/layout/dummy.py +40 -0
  119. package/omni_ai/vendor/prompt_toolkit/layout/layout.py +412 -0
  120. package/omni_ai/vendor/prompt_toolkit/layout/margins.py +304 -0
  121. package/omni_ai/vendor/prompt_toolkit/layout/menus.py +748 -0
  122. package/omni_ai/vendor/prompt_toolkit/layout/mouse_handlers.py +56 -0
  123. package/omni_ai/vendor/prompt_toolkit/layout/processors.py +1010 -0
  124. package/omni_ai/vendor/prompt_toolkit/layout/screen.py +323 -0
  125. package/omni_ai/vendor/prompt_toolkit/layout/scrollable_pane.py +494 -0
  126. package/omni_ai/vendor/prompt_toolkit/layout/utils.py +80 -0
  127. package/omni_ai/vendor/prompt_toolkit/lexers/__init__.py +21 -0
  128. package/omni_ai/vendor/prompt_toolkit/lexers/base.py +85 -0
  129. package/omni_ai/vendor/prompt_toolkit/lexers/pygments.py +328 -0
  130. package/omni_ai/vendor/prompt_toolkit/log.py +13 -0
  131. package/omni_ai/vendor/prompt_toolkit/mouse_events.py +85 -0
  132. package/omni_ai/vendor/prompt_toolkit/output/__init__.py +15 -0
  133. package/omni_ai/vendor/prompt_toolkit/output/base.py +332 -0
  134. package/omni_ai/vendor/prompt_toolkit/output/color_depth.py +64 -0
  135. package/omni_ai/vendor/prompt_toolkit/output/conemu.py +65 -0
  136. package/omni_ai/vendor/prompt_toolkit/output/defaults.py +106 -0
  137. package/omni_ai/vendor/prompt_toolkit/output/flush_stdout.py +87 -0
  138. package/omni_ai/vendor/prompt_toolkit/output/plain_text.py +143 -0
  139. package/omni_ai/vendor/prompt_toolkit/output/vt100.py +748 -0
  140. package/omni_ai/vendor/prompt_toolkit/output/win32.py +683 -0
  141. package/omni_ai/vendor/prompt_toolkit/output/windows10.py +128 -0
  142. package/omni_ai/vendor/prompt_toolkit/patch_stdout.py +297 -0
  143. package/omni_ai/vendor/prompt_toolkit/py.typed +0 -0
  144. package/omni_ai/vendor/prompt_toolkit/renderer.py +814 -0
  145. package/omni_ai/vendor/prompt_toolkit/search.py +226 -0
  146. package/omni_ai/vendor/prompt_toolkit/selection.py +58 -0
  147. package/omni_ai/vendor/prompt_toolkit/shortcuts/__init__.py +46 -0
  148. package/omni_ai/vendor/prompt_toolkit/shortcuts/dialogs.py +330 -0
  149. package/omni_ai/vendor/prompt_toolkit/shortcuts/progress_bar/__init__.py +33 -0
  150. package/omni_ai/vendor/prompt_toolkit/shortcuts/progress_bar/base.py +449 -0
  151. package/omni_ai/vendor/prompt_toolkit/shortcuts/progress_bar/formatters.py +431 -0
  152. package/omni_ai/vendor/prompt_toolkit/shortcuts/prompt.py +1513 -0
  153. package/omni_ai/vendor/prompt_toolkit/shortcuts/utils.py +239 -0
  154. package/omni_ai/vendor/prompt_toolkit/styles/__init__.py +67 -0
  155. package/omni_ai/vendor/prompt_toolkit/styles/base.py +184 -0
  156. package/omni_ai/vendor/prompt_toolkit/styles/defaults.py +236 -0
  157. package/omni_ai/vendor/prompt_toolkit/styles/named_colors.py +162 -0
  158. package/omni_ai/vendor/prompt_toolkit/styles/pygments.py +70 -0
  159. package/omni_ai/vendor/prompt_toolkit/styles/style.py +401 -0
  160. package/omni_ai/vendor/prompt_toolkit/styles/style_transformation.py +374 -0
  161. package/omni_ai/vendor/prompt_toolkit/token.py +9 -0
  162. package/omni_ai/vendor/prompt_toolkit/utils.py +327 -0
  163. package/omni_ai/vendor/prompt_toolkit/validation.py +192 -0
  164. package/omni_ai/vendor/prompt_toolkit/widgets/__init__.py +63 -0
  165. package/omni_ai/vendor/prompt_toolkit/widgets/base.py +995 -0
  166. package/omni_ai/vendor/prompt_toolkit/widgets/dialogs.py +108 -0
  167. package/omni_ai/vendor/prompt_toolkit/widgets/menus.py +374 -0
  168. package/omni_ai/vendor/prompt_toolkit/widgets/toolbars.py +370 -0
  169. package/omni_ai/vendor/prompt_toolkit/win32_types.py +229 -0
  170. package/omni_ai/vendor/wcwidth/LICENSE +27 -0
  171. package/omni_ai/vendor/wcwidth/__init__.py +29 -0
  172. package/omni_ai/vendor/wcwidth/table_vs16.py +125 -0
  173. package/omni_ai/vendor/wcwidth/table_wide.py +1493 -0
  174. package/omni_ai/vendor/wcwidth/table_zero.py +4843 -0
  175. package/omni_ai/vendor/wcwidth/unicode_versions.py +38 -0
  176. package/omni_ai/vendor/wcwidth/wcwidth.py +345 -0
  177. package/package.json +40 -4
@@ -0,0 +1,531 @@
1
+ #!/usr/bin/env python3
2
+ """Model and Claude account settings for Omni AI.
3
+
4
+ python -m omni_ai.config env shell assignments (SMART_AI_* model variables)
5
+ python -m omni_ai.config model [KEY [VALUE|default]]
6
+ python -m omni_ai.config account list|add NAME|login NAME|remove NAME|enable NAME|disable NAME
7
+ python -m omni_ai.config account list|add|login|remove|enable|disable codex|agy|grok NAME
8
+ python -m omni_ai.config key [list|set PROVIDER|remove PROVIDER|get PROVIDER]
9
+ """
10
+ import getpass
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ import re
15
+ import shlex
16
+ import shutil
17
+ import subprocess
18
+ import sys
19
+ import tempfile
20
+
21
+ from .osutils import link, resolve_bin
22
+ from .tools import TOOLS, keys as tool_keys
23
+
24
+ ROOT = Path(__file__).resolve().parent
25
+ CONFIG_DIR = Path(os.environ.get('SMART_AI_HOME', '~/.config/smart-ai')).expanduser()
26
+ MODELS_FILE = CONFIG_DIR / 'models.json'
27
+ ACCOUNTS_DIR = Path(os.environ.get('SMART_AI_ACCOUNTS', '~/.claude-accounts')).expanduser()
28
+ TEMPLATE_PROFILES = ROOT / 'profiles.json'
29
+
30
+
31
+ def profiles_path():
32
+ """User's accounts and routing live outside the install folder, so updates never overwrite them."""
33
+ if os.environ.get('SMART_AI_CONFIG'):
34
+ return Path(os.environ['SMART_AI_CONFIG'])
35
+ user = CONFIG_DIR / 'profiles.json'
36
+ if not user.exists() and TEMPLATE_PROFILES.exists():
37
+ user.parent.mkdir(parents=True, exist_ok=True)
38
+ shutil.copy2(TEMPLATE_PROFILES, user)
39
+ return user
40
+
41
+ # key: (default, env override, description); one per tool, plus the two settings that are not a model
42
+ MODELS = {name: (tool.model_default, tool.model_env, tool.model_help) for name, tool in TOOLS.items()}
43
+ MODELS = dict(list(MODELS.items())[:2] + [('codex_effort', ('high', 'SMART_AI_CODEX_EFFORT', 'Codex: minimal, low, medium, high, xhigh'))]
44
+ + list(MODELS.items())[2:]
45
+ + [('openrouter_paid', ('off', 'SMART_AI_OPENROUTER_PAID', 'OpenRouter: on autoriza modelos pagos (cobrados na sua conta)'))])
46
+ # provider: (env var the CLI reads, expected prefix or None, where to create one)
47
+ KEYS = tool_keys()
48
+ KEYS_DIR = CONFIG_DIR / 'keys'
49
+ LEGACY_OPENROUTER = CONFIG_DIR / 'openrouter_key'
50
+ EFFORTS = ('minimal', 'low', 'medium', 'high', 'xhigh')
51
+ NAME = re.compile(r'[a-z0-9][a-z0-9_-]{0,31}')
52
+
53
+
54
+ def read_json(path, default):
55
+ try:
56
+ return json.loads(Path(path).read_text())
57
+ except (OSError, ValueError):
58
+ return default
59
+
60
+
61
+ def write_json(path, data):
62
+ path = Path(path)
63
+ path.parent.mkdir(parents=True, exist_ok=True)
64
+ fd, name = tempfile.mkstemp(dir=path.parent, prefix='.tmp-')
65
+ with os.fdopen(fd, 'w') as stream:
66
+ json.dump(data, stream, ensure_ascii=False, indent=2)
67
+ stream.write('\n')
68
+ os.replace(name, path)
69
+
70
+
71
+ def model_values():
72
+ saved = read_json(MODELS_FILE, {})
73
+ values = {}
74
+ for key, (default, env, _) in MODELS.items():
75
+ values[key] = os.environ.get(env) or saved.get(key) or default
76
+ return values
77
+
78
+
79
+ def validate_model(key, value):
80
+ if key not in MODELS:
81
+ raise SystemExit(f'Chave inválida: {key}. Use: {", ".join(MODELS)}')
82
+ if not re.fullmatch(r'[A-Za-z0-9._:/@\[\]-]*', value):
83
+ raise SystemExit('Valor com caracteres inválidos.')
84
+ if key == 'codex_effort' and value not in EFFORTS:
85
+ raise SystemExit('Esforço inválido: ' + ', '.join(EFFORTS))
86
+ if key == 'openrouter_paid' and value not in ('on', 'off'):
87
+ raise SystemExit('Use: /model openrouter_paid on|off')
88
+ if key == 'openrouter' and value and value != 'openrouter/free' and not value.endswith(':free') \
89
+ and model_values()['openrouter_paid'] != 'on':
90
+ raise SystemExit('Modelo pago não autorizado. Autorize antes com: /model openrouter_paid on')
91
+
92
+
93
+ def cmd_model(args):
94
+ if not args:
95
+ values = model_values()
96
+ saved = read_json(MODELS_FILE, {})
97
+ for key, (default, env, help_text) in MODELS.items():
98
+ origin = 'env' if os.environ.get(env) else ('salvo' if saved.get(key) else 'padrão')
99
+ print(f' {key:<13} {values[key] or "(automático)":<24} [{origin}] {help_text}')
100
+ print('\nAlterar: /model codex gpt-6-astra · voltar ao padrão: /model codex default')
101
+ return
102
+ key = args[0]
103
+ if len(args) == 1:
104
+ validate_model(key, '' if key != 'codex_effort' else 'high')
105
+ print(f"{key} = {model_values()[key] or '(automático)'} · {MODELS[key][2]}")
106
+ return
107
+ value = args[1]
108
+ saved = read_json(MODELS_FILE, {})
109
+ if value == 'default':
110
+ validate_model(key, MODELS[key][0] if key in MODELS else '')
111
+ saved.pop(key, None)
112
+ else:
113
+ validate_model(key, value)
114
+ saved[key] = value
115
+ current = saved.get('openrouter', '')
116
+ if key == 'openrouter_paid' and value == 'off' and current and current != 'openrouter/free' \
117
+ and not current.endswith(':free'):
118
+ saved.pop('openrouter')
119
+ print(' Modelo pago do OpenRouter removido; voltou ao automático gratuito.')
120
+ write_json(MODELS_FILE, saved)
121
+ print(f'✓ {key} = {model_values()[key] or "(automático)"}')
122
+ if key == 'openrouter_paid' and model_values()[key] == 'on':
123
+ print(' Atenção: modelos pagos do OpenRouter serão cobrados na sua conta OpenRouter.')
124
+ print(' Escolha o modelo com /model openrouter ID · desligue com /model openrouter_paid off')
125
+ if os.environ.get(MODELS[key][1]):
126
+ print(f' Aviso: a variável {MODELS[key][1]} está definida e tem prioridade.')
127
+
128
+
129
+ def cmd_env():
130
+ values = model_values()
131
+ for key, (_, env, _) in MODELS.items():
132
+ print(f'{env}={shlex.quote(values[key])}')
133
+
134
+
135
+ def profiles():
136
+ data = read_json(profiles_path(), None)
137
+ if data is None:
138
+ raise SystemExit(f'Não consegui ler {profiles_path()}')
139
+ data.setdefault('profiles', {})
140
+ return data
141
+
142
+
143
+ def ordered(data):
144
+ return sorted(data['profiles'].items(), key=lambda item: item[1].get('priority', 99))
145
+
146
+
147
+ def logged_in(profile):
148
+ config_dir = profile.get('config_dir')
149
+ env = dict(os.environ)
150
+ if config_dir:
151
+ folder = Path(config_dir).expanduser()
152
+ if not folder.is_dir():
153
+ return False
154
+ env['CLAUDE_CONFIG_DIR'] = str(folder)
155
+ elif profile.get('credentials_file') and not Path(profile['credentials_file']).expanduser().exists():
156
+ return False
157
+ try:
158
+ result = subprocess.run([resolve_bin(os.environ.get('CLAUDE_BIN', 'claude')) or 'claude', 'auth', 'status', '--json'],
159
+ env=env, capture_output=True, text=True, timeout=20)
160
+ except (OSError, subprocess.TimeoutExpired):
161
+ return None
162
+ try:
163
+ status = json.loads(result.stdout)
164
+ except ValueError:
165
+ return result.returncode == 0 and 'not logged' not in (result.stdout + result.stderr).lower()
166
+ # "authMethod": "none" means no login, even though the command itself succeeds
167
+ return bool(status.get('loggedIn', status.get('authMethod') not in (None, '', 'none')))
168
+
169
+
170
+ SHARED = ('skills', 'plugins', 'agents', 'commands', 'hooks', 'CLAUDE.md', 'settings.json')
171
+
172
+
173
+ def share_claude_setup(config_dir):
174
+ """Give an isolated account the main account's skills, plugins and MCP servers; login stays separate."""
175
+ main = Path(os.environ.get('SMART_AI_CLAUDE_HOME', '~/.claude')).expanduser()
176
+ for item in SHARED:
177
+ source, target = main / item, config_dir / item
178
+ if source.exists() and not target.exists() and not target.is_symlink():
179
+ link(target, source)
180
+ main_state = read_json(main.parent / '.claude.json', {})
181
+ servers = main_state.get('mcpServers')
182
+ if servers:
183
+ state_file = config_dir / '.claude.json'
184
+ state = read_json(state_file, {})
185
+ state['mcpServers'] = servers
186
+ write_json(state_file, state)
187
+ os.chmod(state_file, 0o600)
188
+
189
+
190
+ def login(name, profile):
191
+ config_dir = Path(profile['config_dir']).expanduser()
192
+ config_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
193
+ print(f'Abrindo login do Claude para a conta "{name}" (pasta isolada {config_dir}).')
194
+ print('Sua conta principal não é afetada.')
195
+ env = dict(os.environ, CLAUDE_CONFIG_DIR=str(config_dir))
196
+ code = subprocess.call([resolve_bin(os.environ.get('CLAUDE_BIN', 'claude')) or 'claude', 'auth', 'login'], env=env)
197
+ if code == 0:
198
+ share_claude_setup(config_dir)
199
+ print('Skills, plugins, CLAUDE.md, settings e MCPs compartilhados com a conta principal.')
200
+ return code
201
+
202
+
203
+ def cmd_account(args):
204
+ action = args[0] if args else 'list'
205
+ if len(args) > 1 and args[1] in TOOL_HOMES:
206
+ return cmd_tool_account(args[1], action, args[2:])
207
+ if len(args) > 1 and args[1] == 'claude':
208
+ args = args[:1] + args[2:]
209
+ data = profiles()
210
+ if action == 'sync-all':
211
+ for name, profile in ordered(data):
212
+ if profile.get('config_dir') and Path(profile['config_dir']).expanduser().is_dir():
213
+ share_claude_setup(Path(profile['config_dir']).expanduser())
214
+ print(f' ✓ conta Claude "{name}" atualizada')
215
+ return
216
+ if action == 'list':
217
+ for name, profile in ordered(data):
218
+ state = {True: 'logada', False: 'sem login', None: '?'}[logged_in(profile)]
219
+ enabled = 'ativa' if profile.get('enabled', True) else 'desativada'
220
+ print(f" {profile.get('priority', '?')}. {name:<12} {state:<10} {enabled:<11} {profile.get('name', '')}")
221
+ for tool in TOOL_HOMES:
222
+ extra = tool_accounts(tool)
223
+ if extra:
224
+ print(f'\n {tool}: principal + ' + ', '.join(name for name, _ in extra))
225
+ print('\nAdicionar: /account add NOME (Claude) · /account add codex|agy|grok NOME · refazer login: /account login NOME')
226
+ return
227
+ if len(args) < 2 or not NAME.fullmatch(args[1]):
228
+ raise SystemExit('Informe um nome: letras minúsculas, números, - ou _ (ex.: /account add pessoal)')
229
+ name = args[1]
230
+ profile = data['profiles'].get(name)
231
+ if action == 'add':
232
+ if profile and profile.get('config_dir') and logged_in(profile):
233
+ raise SystemExit(f'Conta "{name}" já existe e está logada. Use /account login {name} para trocar.')
234
+ priority = max([p.get('priority', 0) for p in data['profiles'].values()] or [0]) + 1
235
+ profile = dict(profile or {}, name=(profile or {}).get('name') or name, enabled=True,
236
+ status='active', last_rate_limit=None, cooldown_minutes=(profile or {}).get('cooldown_minutes', 60),
237
+ priority=(profile or {}).get('priority', priority), config_dir=str(ACCOUNTS_DIR / name))
238
+ profile.pop('credentials_file', None)
239
+ if login(name, profile) != 0:
240
+ raise SystemExit('Login não concluído; nada foi alterado.')
241
+ data['profiles'][name] = profile
242
+ write_json(profiles_path(), data)
243
+ print(f'✓ Conta "{name}" adicionada com prioridade {profile["priority"]}.')
244
+ elif not profile:
245
+ raise SystemExit(f'Conta "{name}" não existe. Veja /account list.')
246
+ elif action == 'login':
247
+ if not profile.get('config_dir'):
248
+ if name == 'primary':
249
+ print('A conta primary usa o login normal do Claude: rode "claude auth login".')
250
+ return
251
+ profile['config_dir'] = str(ACCOUNTS_DIR / name)
252
+ profile.pop('credentials_file', None)
253
+ if login(name, profile) == 0:
254
+ write_json(profiles_path(), data)
255
+ print(f'✓ Login da conta "{name}" atualizado.')
256
+ elif action == 'sync':
257
+ if not profile.get('config_dir'):
258
+ print(f'A conta "{name}" usa a configuração principal; nada a sincronizar.')
259
+ return
260
+ share_claude_setup(Path(profile['config_dir']).expanduser())
261
+ print(f'✓ Conta "{name}" sincronizada com skills, plugins e MCPs da principal.')
262
+ elif action in ('enable', 'disable'):
263
+ profile['enabled'] = action == 'enable'
264
+ write_json(profiles_path(), data)
265
+ print(f'✓ Conta "{name}" ' + ('ativada.' if profile['enabled'] else 'desativada.'))
266
+ elif action == 'remove':
267
+ if name == 'primary':
268
+ raise SystemExit('A conta primary não pode ser removida; use /account disable primary.')
269
+ del data['profiles'][name]
270
+ write_json(profiles_path(), data)
271
+ folder = profile.get('config_dir')
272
+ if folder and Path(folder).expanduser().is_dir():
273
+ # Log out first: on macOS the login lives in the Keychain, not only in the folder
274
+ subprocess.run([resolve_bin(os.environ.get('CLAUDE_BIN', 'claude')) or 'claude', 'auth', 'logout'],
275
+ env=dict(os.environ, CLAUDE_CONFIG_DIR=str(Path(folder).expanduser())),
276
+ capture_output=True, timeout=30)
277
+ shutil.rmtree(Path(folder).expanduser())
278
+ print(f'✓ Conta "{name}" removida.')
279
+ else:
280
+ raise SystemExit('Ação inválida: list, add, login, sync, enable, disable, remove')
281
+
282
+
283
+ # Extra subscription accounts for the other CLIs. Each one gets its own home folder (the env var the CLI
284
+ # reads); the main login keeps the normal folder. Shared items are linked so every account sees the same setup.
285
+ TOOL_HOMES = {
286
+ 'codex': ('CODEX_HOME', '~/.codex', ('config.toml', 'AGENTS.md', 'prompts', 'skills'), ['codex', 'login']),
287
+ 'grok': ('GROK_HOME', '~/.grok', ('config.toml', 'AGENTS.md', 'skills', 'plugins', 'hooks'), ['grok', 'login']),
288
+ # agy has no folder variable, so the account runs under its own HOME; git, ssh and gh keep working through links
289
+ 'agy': ('HOME', '~', ('.gitconfig', '.ssh', '.config/gh', '.gemini/config'), ['agy']),
290
+ }
291
+ TOOL_ACCOUNTS_DIR = CONFIG_DIR / 'accounts'
292
+
293
+
294
+ def tool_accounts(tool, enabled_only=False):
295
+ """Extra accounts of a tool by priority; the main login is not listed (it always runs first)."""
296
+ items = sorted(profiles().get('accounts', {}).get(tool, {}).items(), key=lambda item: item[1].get('priority', 99))
297
+ return [(name, conf) for name, conf in items if conf.get('enabled', True) or not enabled_only]
298
+
299
+
300
+ def tool_env(tool, conf):
301
+ return {TOOL_HOMES[tool][0]: str(Path(conf['config_dir']).expanduser())}
302
+
303
+
304
+ def tool_logged_in(tool, conf):
305
+ folder = Path(conf['config_dir']).expanduser()
306
+ if not folder.is_dir():
307
+ return False
308
+ if tool == 'codex':
309
+ try:
310
+ return subprocess.run([resolve_bin('codex') or 'codex', 'login', 'status'], env=dict(os.environ, **tool_env(tool, conf)),
311
+ capture_output=True, timeout=20).returncode == 0
312
+ except (OSError, subprocess.TimeoutExpired):
313
+ return None
314
+ return (folder / ('auth.json' if tool == 'grok' else '.gemini/jetski-standalone-oauth-token')).is_file()
315
+
316
+
317
+ def share_tool_setup(tool, folder):
318
+ main = Path(TOOL_HOMES[tool][1]).expanduser()
319
+ for item in TOOL_HOMES[tool][2]:
320
+ source, target = main / item, folder / item
321
+ if source.exists() and not target.exists() and not target.is_symlink():
322
+ target.parent.mkdir(parents=True, exist_ok=True)
323
+ link(target, source)
324
+
325
+
326
+ def tool_login(tool, name, conf):
327
+ folder = Path(conf['config_dir']).expanduser()
328
+ folder.mkdir(parents=True, exist_ok=True, mode=0o700)
329
+ share_tool_setup(tool, folder)
330
+ print(f'Abrindo login do {tool} para a conta "{name}" (pasta isolada {folder}).')
331
+ print('Sua conta principal não é afetada.' + (' Faça o login com o Google e saia com Ctrl-C.' if tool == 'agy' else ''))
332
+ command = TOOL_HOMES[tool][3]
333
+ return subprocess.call([resolve_bin(command[0]) or command[0]] + command[1:], env=dict(os.environ, **tool_env(tool, conf)))
334
+
335
+
336
+ def cmd_tool_account(tool, action, args):
337
+ data = profiles()
338
+ accounts = data.setdefault('accounts', {}).setdefault(tool, {})
339
+ if action == 'list':
340
+ print(f' {tool}: principal (login normal) sempre primeiro')
341
+ for name, conf in tool_accounts(tool):
342
+ state = {True: 'logada', False: 'sem login', None: '?'}[tool_logged_in(tool, conf)]
343
+ print(f" {conf.get('priority', '?')}. {name:<12} {state:<10} {'ativa' if conf.get('enabled', True) else 'desativada'}")
344
+ print(f'\nAdicionar: /account add {tool} NOME · refazer login: /account login {tool} NOME')
345
+ return
346
+ if not args or not NAME.fullmatch(args[0]) or args[0] == 'primary':
347
+ raise SystemExit(f'Informe um nome: letras minúsculas, números, - ou _ (ex.: /account add {tool} trabalho)')
348
+ name = args[0]
349
+ conf = accounts.get(name)
350
+ if action == 'add':
351
+ if conf and tool_logged_in(tool, conf):
352
+ raise SystemExit(f'Conta "{name}" do {tool} já existe e está logada. Use /account login {tool} {name} para trocar.')
353
+ conf = conf or {'priority': max([c.get('priority', 0) for c in accounts.values()] or [0]) + 1,
354
+ 'config_dir': str(TOOL_ACCOUNTS_DIR / tool / name), 'enabled': True}
355
+ tool_login(tool, name, conf)
356
+ if tool_logged_in(tool, conf) is False:
357
+ raise SystemExit('Login não concluído; nada foi alterado.')
358
+ accounts[name] = conf
359
+ write_json(profiles_path(), data)
360
+ print(f'✓ Conta "{name}" do {tool} adicionada com prioridade {conf["priority"]}.')
361
+ elif not conf:
362
+ raise SystemExit(f'Conta "{name}" do {tool} não existe. Veja /account list {tool}.')
363
+ elif action == 'login':
364
+ tool_login(tool, name, conf)
365
+ elif action in ('enable', 'disable'):
366
+ conf['enabled'] = action == 'enable'
367
+ write_json(profiles_path(), data)
368
+ print(f'✓ Conta "{name}" do {tool} ' + ('ativada.' if conf['enabled'] else 'desativada.'))
369
+ elif action == 'remove':
370
+ del accounts[name]
371
+ write_json(profiles_path(), data)
372
+ folder = Path(conf['config_dir']).expanduser()
373
+ if tool in ('codex', 'grok') and folder.is_dir():
374
+ subprocess.run([resolve_bin(tool) or tool, 'logout'], env=dict(os.environ, **tool_env(tool, conf)),
375
+ capture_output=True, timeout=30)
376
+ if folder.is_dir() and folder.is_relative_to(TOOL_ACCOUNTS_DIR):
377
+ shutil.rmtree(folder)
378
+ print(f'✓ Conta "{name}" do {tool} removida.')
379
+ else:
380
+ raise SystemExit('Ação inválida: list, add, login, enable, disable, remove')
381
+
382
+
383
+ def key_path(provider):
384
+ return KEYS_DIR / provider
385
+
386
+
387
+ def extra_key_path(provider, name):
388
+ return KEYS_DIR / f'{provider}.{name}'
389
+
390
+
391
+ def stored_keys(provider):
392
+ """Every key of a tool in the order they are tried: the env variable, the main saved key, then the
393
+ extra ones (/key add TOOL NAME) by name. Each item: (name, value, origin)."""
394
+ found = []
395
+ env = os.environ.get(KEYS[provider][0])
396
+ if env:
397
+ found.append(('env', env, 'env'))
398
+ for path in (key_path(provider), LEGACY_OPENROUTER if provider == 'openrouter' else None):
399
+ if path and path.is_file() and path.read_text().strip():
400
+ found.append(('principal', path.read_text().strip(), 'salva'))
401
+ break
402
+ extras = sorted(KEYS_DIR.glob(provider + '.*'), key=lambda p: (len(p.name), p.name)) if KEYS_DIR.is_dir() else []
403
+ for path in extras:
404
+ value = path.read_text().strip()
405
+ if value:
406
+ found.append((path.name[len(provider) + 1:], value, 'salva'))
407
+ return found
408
+
409
+
410
+ def stored_key(provider):
411
+ keys = stored_keys(provider)
412
+ if keys:
413
+ return keys[0][1], keys[0][2]
414
+ return '', ''
415
+
416
+
417
+ def ask_key(provider, inline):
418
+ env, prefix, url = KEYS[provider]
419
+ if inline:
420
+ value = inline.strip() # typed inline: /key openrouter sk-or-...
421
+ else:
422
+ print(f'Chave de {provider} ({url}). Cole e tecle Enter; ela não aparece na tela.')
423
+ try:
424
+ value = getpass.getpass('> ').strip()
425
+ except (EOFError, KeyboardInterrupt):
426
+ raise SystemExit('\nCancelado.')
427
+ if not value or not re.fullmatch(r'[A-Za-z0-9._-]{16,}', value):
428
+ raise SystemExit('Chave vazia ou com formato inválido.')
429
+ if prefix and not value.startswith(prefix):
430
+ raise SystemExit(f'Chave de {provider} deve começar com {prefix}')
431
+ return value
432
+
433
+
434
+ def save_key(path, value):
435
+ KEYS_DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
436
+ os.chmod(KEYS_DIR, 0o700)
437
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
438
+ with os.fdopen(fd, 'w') as stream:
439
+ stream.write(value)
440
+ os.chmod(path, 0o600)
441
+
442
+
443
+ def next_key_name(provider):
444
+ taken = {name for name, _, _ in stored_keys(provider)}
445
+ return next(f'chave{n}' for n in range(2, 1000) if f'chave{n}' not in taken)
446
+
447
+
448
+ def cmd_key(args):
449
+ """/key list · /key TOOL [value] (main key) · /key add TOOL [NAME] [value] (one more key)
450
+ · /key remove TOOL [NAME]. Keys of a tool are tried in order when one fails or hits its limit."""
451
+ action = args[0] if args else 'list'
452
+ if action == 'list':
453
+ for provider, (env, _, url) in KEYS.items():
454
+ keys = stored_keys(provider)
455
+ if not keys:
456
+ print(f' {provider:<11} {"—":<34} {env:<19} {url}')
457
+ for i, (name, value, origin) in enumerate(keys):
458
+ shown = f'{name}: {value[:7]}…{value[-4:]} [{origin}]'
459
+ print(f' {provider if i == 0 else "":<11} {shown:<34} {env if i == 0 else "":<19} {url if i == 0 else ""}')
460
+ print('\nPrincipal: /key claude · mais uma: /key add claude [NOME] · remover: /key remove claude [NOME]')
461
+ print('Assinatura vem primeiro; as chaves são usadas em ordem quando ela falha ou bate no limite.')
462
+ print('OpenRouter funciona só com chave.')
463
+ return
464
+ if action in KEYS:
465
+ action = 'set'
466
+ else:
467
+ args = args[1:]
468
+ if not args or args[0] not in KEYS:
469
+ raise SystemExit('Informe a ferramenta: ' + ', '.join(KEYS))
470
+ provider = args[0]
471
+ env = KEYS[provider][0]
472
+ if action == 'get':
473
+ print(stored_key(provider)[0])
474
+ elif action == 'set':
475
+ save_key(key_path(provider), ask_key(provider, args[1] if len(args) > 1 else ''))
476
+ print(f'✓ Chave principal de {provider} salva em {key_path(provider)} (permissão 600).')
477
+ if os.environ.get(env):
478
+ print(f' Aviso: a variável {env} está definida e é tentada primeiro.')
479
+ elif action == 'add':
480
+ rest = args[1:]
481
+ name = rest.pop(0) if rest and NAME.fullmatch(rest[0]) and len(rest[0]) < 16 else next_key_name(provider)
482
+ if name in ('env', 'principal') or extra_key_path(provider, name).exists():
483
+ raise SystemExit(f'Já existe uma chave {name} para {provider}.')
484
+ if not key_path(provider).is_file() and not (provider == 'openrouter' and LEGACY_OPENROUTER.is_file()):
485
+ path, name = key_path(provider), 'principal'
486
+ else:
487
+ path = extra_key_path(provider, name)
488
+ save_key(path, ask_key(provider, rest[0] if rest else ''))
489
+ print(f'✓ Chave {name} de {provider} salva ({len(stored_keys(provider))} no total, usadas em ordem).')
490
+ elif action == 'remove':
491
+ name = args[1] if len(args) > 1 else 'principal'
492
+ paths = [key_path(provider), LEGACY_OPENROUTER if provider == 'openrouter' else None] if name == 'principal' \
493
+ else [extra_key_path(provider, name) if NAME.fullmatch(name) else None]
494
+ removed = False
495
+ for path in paths:
496
+ if path and path.exists():
497
+ path.unlink()
498
+ removed = True
499
+ print(f'✓ Chave {name} de {provider} removida.' if removed else f'Nenhuma chave {name} salva para {provider}.')
500
+ else:
501
+ raise SystemExit('Ação inválida: list, set, add, remove')
502
+
503
+
504
+ def enabled_profiles():
505
+ """Names of enabled profiles by priority, for the fallback loop."""
506
+ return [name for name, profile in ordered(profiles()) if profile.get('enabled', True)]
507
+
508
+
509
+ def cmd_profiles():
510
+ for name in enabled_profiles():
511
+ print(name)
512
+
513
+
514
+ def main(argv):
515
+ command, args = (argv[0], argv[1:]) if argv else ('model', [])
516
+ if command == 'env':
517
+ cmd_env()
518
+ elif command == 'model':
519
+ cmd_model(args)
520
+ elif command == 'account':
521
+ cmd_account(args)
522
+ elif command == 'key':
523
+ cmd_key(args)
524
+ elif command == 'profiles':
525
+ cmd_profiles()
526
+ else:
527
+ raise SystemExit(__doc__)
528
+
529
+
530
+ if __name__ == '__main__':
531
+ main(sys.argv[1:])
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ DeepSeek Client — Chama a API da DeepSeek (paga por uso, barata) com PII masking.
4
+
5
+ Uso:
6
+ export DEEPSEEK_API_KEY="sk-..."
7
+ echo "Olá mundo" | python -m omni_ai.deepseek
8
+ python -m omni_ai.deepseek --model deepseek-reasoner "Olá mundo"
9
+ """
10
+
11
+ import json
12
+ import os
13
+ import sys
14
+
15
+ from . import grok
16
+
17
+ DEEPSEEK_BASE = "https://api.deepseek.com"
18
+ DEFAULT_MODEL = "deepseek-chat"
19
+
20
+
21
+ def chat(key, prompt, model="", system_prompt=None, mask=True):
22
+ return grok.chat(key, prompt, model or DEFAULT_MODEL, system_prompt, mask, base=DEEPSEEK_BASE, name="DeepSeek")
23
+
24
+
25
+ def main():
26
+ import argparse
27
+
28
+ parser = argparse.ArgumentParser(description="DeepSeek client com PII masking")
29
+ parser.add_argument("prompt", nargs="*", help="Prompt para o modelo")
30
+ parser.add_argument("--model", "-m", default="", help=f"Modelo a usar (vazio = {DEFAULT_MODEL})")
31
+ parser.add_argument("--system", "-s", default=None, help="System prompt")
32
+ parser.add_argument("--no-mask", action="store_true", help="Desabilitar PII masking")
33
+ args = parser.parse_args()
34
+
35
+ key = os.environ.get("DEEPSEEK_API_KEY", "")
36
+ if not key:
37
+ print("❌ DEEPSEEK_API_KEY não configurada. Crie em https://platform.deepseek.com/api_keys e rode: ai --key deepseek", file=sys.stderr)
38
+ sys.exit(1)
39
+ prompt = " ".join(args.prompt) or (sys.stdin.read().strip() if not sys.stdin.isatty() else "")
40
+ if not prompt:
41
+ parser.print_help()
42
+ sys.exit(1)
43
+ try:
44
+ result = chat(key, prompt, args.model, args.system, mask=not args.no_mask)
45
+ except RuntimeError as e:
46
+ print(f"❌ Erro: {e}", file=sys.stderr)
47
+ sys.exit(1)
48
+ except KeyboardInterrupt:
49
+ sys.exit(130)
50
+ if os.environ.get("SMART_AI_EVENTS") == "1":
51
+ print(json.dumps({"type": "smart.answer", **result}, ensure_ascii=False), flush=True)
52
+ else:
53
+ print(result["content"])
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()