machina-cli 0.4.4__tar.gz → 0.4.8__tar.gz

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 (95) hide show
  1. {machina_cli-0.4.4 → machina_cli-0.4.8}/.github/workflows/release.yml +15 -5
  2. {machina_cli-0.4.4 → machina_cli-0.4.8}/CHANGELOG.md +14 -0
  3. {machina_cli-0.4.4 → machina_cli-0.4.8}/PKG-INFO +1 -1
  4. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs/harness-loop-kit/provision.py +101 -4
  5. {machina_cli-0.4.4 → machina_cli-0.4.8}/pyproject.toml +1 -1
  6. machina_cli-0.4.8/src/machina_cli/client.py +134 -0
  7. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/auth.py +71 -36
  8. machina_cli-0.4.8/src/machina_cli/commands/context_graph.py +165 -0
  9. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/main.py +2 -0
  10. machina_cli-0.4.4/src/machina_cli/client.py +0 -101
  11. {machina_cli-0.4.4 → machina_cli-0.4.8}/.github/workflows/ci.yml +0 -0
  12. {machina_cli-0.4.4 → machina_cli-0.4.8}/.gitignore +0 -0
  13. {machina_cli-0.4.4 → machina_cli-0.4.8}/CLAUDE.md +0 -0
  14. {machina_cli-0.4.4 → machina_cli-0.4.8}/README.md +0 -0
  15. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs/agentic-harness-loop.md +0 -0
  16. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs/credentials.md +0 -0
  17. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs/harness-loop-kit/PLAYBOOK-SCORECARD.md +0 -0
  18. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs/harness-loop-kit/README.md +0 -0
  19. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs/harness-loop-kit/VALIDATION.md +0 -0
  20. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs/harness-loop-kit/context-verify.py +0 -0
  21. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs/loop-tools-connector.py +0 -0
  22. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/.gitignore +0 -0
  23. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/.vitepress/config.mts +0 -0
  24. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/.vitepress/theme/custom.css +0 -0
  25. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/.vitepress/theme/index.ts +0 -0
  26. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/README.md +0 -0
  27. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/agent.md +0 -0
  28. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/config.md +0 -0
  29. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/connector.md +0 -0
  30. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/credentials.md +0 -0
  31. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/deploy.md +0 -0
  32. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/document.md +0 -0
  33. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/execution.md +0 -0
  34. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/factory.md +0 -0
  35. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/login.md +0 -0
  36. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/loop.md +0 -0
  37. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/mapping.md +0 -0
  38. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/org.md +0 -0
  39. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/project.md +0 -0
  40. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/prompt.md +0 -0
  41. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/skills.md +0 -0
  42. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/sports.md +0 -0
  43. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/template.md +0 -0
  44. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/update.md +0 -0
  45. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/commands/workflow.md +0 -0
  46. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/guide/authentication.md +0 -0
  47. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/guide/configuration.md +0 -0
  48. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/guide/installation.md +0 -0
  49. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/guide/quickstart.md +0 -0
  50. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/guide/repl.md +0 -0
  51. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/guide/running.md +0 -0
  52. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/index.md +0 -0
  53. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/package-lock.json +0 -0
  54. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/package.json +0 -0
  55. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/public/favicon.ico +0 -0
  56. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/public/machina-logo-dark.png +0 -0
  57. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/public/machina-logo-light.png +0 -0
  58. {machina_cli-0.4.4 → machina_cli-0.4.8}/docs-site/vercel.json +0 -0
  59. {machina_cli-0.4.4 → machina_cli-0.4.8}/install.ps1 +0 -0
  60. {machina_cli-0.4.4 → machina_cli-0.4.8}/install.sh +0 -0
  61. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/__init__.py +0 -0
  62. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/browser_auth.py +0 -0
  63. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/__init__.py +0 -0
  64. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/agent.py +0 -0
  65. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/config_cmd.py +0 -0
  66. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/connect.py +0 -0
  67. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/connector.py +0 -0
  68. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/credentials.py +0 -0
  69. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/deploy.py +0 -0
  70. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/document.py +0 -0
  71. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/execution.py +0 -0
  72. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/factory.py +0 -0
  73. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/loop.py +0 -0
  74. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/mapping.py +0 -0
  75. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/mcp.py +0 -0
  76. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/org.py +0 -0
  77. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/project.py +0 -0
  78. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/prompt.py +0 -0
  79. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/skills.py +0 -0
  80. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/sports.py +0 -0
  81. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/template.py +0 -0
  82. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/commands/workflow.py +0 -0
  83. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/config.py +0 -0
  84. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/factory_client.py +0 -0
  85. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/loop_client.py +0 -0
  86. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/models/__init__.py +0 -0
  87. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/project_client.py +0 -0
  88. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/repl.py +0 -0
  89. {machina_cli-0.4.4 → machina_cli-0.4.8}/src/machina_cli/updater.py +0 -0
  90. {machina_cli-0.4.4 → machina_cli-0.4.8}/tests/__init__.py +0 -0
  91. {machina_cli-0.4.4 → machina_cli-0.4.8}/tests/test_cli_output.py +0 -0
  92. {machina_cli-0.4.4 → machina_cli-0.4.8}/tests/test_connect.py +0 -0
  93. {machina_cli-0.4.4 → machina_cli-0.4.8}/tests/test_mcp_url.py +0 -0
  94. {machina_cli-0.4.4 → machina_cli-0.4.8}/tests/test_org_usage.py +0 -0
  95. {machina_cli-0.4.4 → machina_cli-0.4.8}/tests/test_sports_integration.py +0 -0
@@ -78,15 +78,25 @@ jobs:
78
78
  # Write to file for gh release
79
79
  echo "$notes" > release_notes.md
80
80
 
81
- - name: Create GitHub Release
81
+ - name: Create or update GitHub Release
82
82
  env:
83
83
  GH_TOKEN: ${{ github.token }}
84
84
  run: |
85
85
  tag="${GITHUB_REF#refs/tags/}"
86
- gh release create "$tag" \
87
- --title "$tag" \
88
- --notes-file release_notes.md \
89
- artifacts/**/*
86
+ # Idempotent: a release may already exist if it was created from the GitHub
87
+ # UI / `gh release create` (which also creates the tag that triggers this
88
+ # workflow). In that case `gh release create` errors ("already exists") and
89
+ # the built binaries never get attached — leaving an empty release. So if the
90
+ # release exists, refresh its notes and upload the assets with --clobber.
91
+ if gh release view "$tag" >/dev/null 2>&1; then
92
+ gh release edit "$tag" --title "$tag" --notes-file release_notes.md
93
+ gh release upload "$tag" artifacts/**/* --clobber
94
+ else
95
+ gh release create "$tag" \
96
+ --title "$tag" \
97
+ --notes-file release_notes.md \
98
+ artifacts/**/*
99
+ fi
90
100
 
91
101
  publish-pypi:
92
102
  needs: [github-release]
@@ -2,6 +2,20 @@
2
2
 
3
3
  All notable changes to machina-cli are documented here.
4
4
 
5
+ ## [0.4.8] - 2026-06-30
6
+
7
+ ### Added
8
+ - **`machina context-graph status`** — see the self-healing / monitoring layer from the CLI (the same truth the Studio Context Graph page shows). Per project it lists the verified edges + health (e.g. `market → team linked 52.5%`, `market ↔ price quality degraded 34.1%`), the live surface verdict (odds/errors, with session-normalized signals + exception count), and the self-heal agents with their beat status — and warns when a beat is `active` but `scheduled=True` (silently not firing). `--org` rolls it up across every project in the org; `--json` for scripts. Answers "what self-healing is running, where, and how healthy" without opening each project one by one.
9
+
10
+ ## [0.4.7] - 2026-06-30
11
+
12
+ ### Added
13
+ - **The harness loop can now read documents and real conversations.** Its tool catalog gained `read_documents` (read any document on the project pod by name — copilot threads, harness sessions, fixtures, config docs, via the same `document_search` the MCP uses) and `fetch_conversations` (recent real SportingBOT end-user chat transcripts from PostHog — user context + bot answer + category, read from `posthog.ai_events`). Before, the loop only had `find_fixtures`/`calculate`/`get_datetime`/`echo`, so "analyse the recent chats and suggest bot improvements" got "give me the logs"; it now pulls live transcripts and returns grounded, evaluator-checked findings. (#41)
14
+
15
+ ### Fixed
16
+ - **`machina login --api-key` no longer discards a valid key.** The key was verified against `login/session`, which returns 5xx for API-key auth; the client read that as "key invalid", deleted the just-stored key, and silently fell back to the session token (printing "Authenticated as Unknown"). The client now never clears the key on a 5xx — it falls back for the current request only, and only when a session-token retry actually succeeds — and `login --api-key` verifies without that fallback and reports an honest result. The key is always kept. (#42)
17
+ - **Release pipeline no longer ships empty releases.** The `github-release` CI step used `gh release create`, which errors when the release already exists (e.g. cut from the GitHub UI, which also creates the triggering tag) and then dies before attaching the binaries. It is now idempotent — create, or upload assets onto the existing release. (#43)
18
+
5
19
  ## [0.4.4] - 2026-06-30
6
20
 
7
21
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: machina-cli
3
- Version: 0.4.4
3
+ Version: 0.4.8
4
4
  Summary: CLI for the Machina AI Agent platform
5
5
  Project-URL: Homepage, https://machina.gg
6
6
  Project-URL: Repository, https://github.com/machina-sports/machina-cli
@@ -23,7 +23,7 @@ What it creates (maps to the Loop-Engineering five moves — see VALIDATION.md):
23
23
  prompt loop-evaluate INDEPENDENT verifier: judge the answer (verification)
24
24
  prompt loop-repair bounded self-repair of a rejected answer (Cap 8.2)
25
25
  prompt loop-evaluate-2 re-verify the repaired answer (Cap 8.2)
26
- connector loop-tools dispatcher: calculate / get_datetime / echo / find_fixtures
26
+ connector loop-tools dispatcher: calculate / get_datetime / echo / find_fixtures / read_documents / fetch_conversations
27
27
  workflow loop-turn load -> ingest -> reason -> tool -> respond -> EVALUATE -> [repair -> re-eval] -> finalize
28
28
  workflow loop-resume beat path: resume an orphaned `active` session (scheduling)
29
29
  agent loop-runner executor path (inactive; CLI/MCP invokes it)
@@ -98,7 +98,7 @@ def _create(kind, body):
98
98
  # --- loop-tools connector source (pyscript, exec'd from the DB at call time) ---
99
99
  # Returns {status: True, data: {...}} — the connector contract; a bare dict is
100
100
  # treated as a FAILED connector. Inputs arrive under request_data['params'].
101
- LOOP_TOOLS_SRC = r'''"""Machina Loop Tools — meta-dispatcher (calculate/get_datetime/echo/find_fixtures)."""
101
+ LOOP_TOOLS_SRC = r'''"""Machina Loop Tools — meta-dispatcher (calculate/get_datetime/echo/find_fixtures/read_documents/fetch_conversations)."""
102
102
  import ast, json, operator
103
103
  from datetime import datetime, timezone
104
104
  _OPS={ast.Add:operator.add,ast.Sub:operator.sub,ast.Mult:operator.mul,ast.Div:operator.truediv,ast.Pow:operator.pow,ast.Mod:operator.mod,ast.USub:operator.neg,ast.UAdd:operator.pos,ast.FloorDiv:operator.floordiv}
@@ -136,6 +136,91 @@ def _find_fixtures(a):
136
136
  "home_analysis":(tf.get("home") or {}).get("analysis","")[:300] if v.get("has_pre_match_research") else "",
137
137
  "away_analysis":(tf.get("away") or {}).get("analysis","")[:300] if v.get("has_pre_match_research") else ""})
138
138
  return out if out else "no upcoming fixtures found"+((" for team "+team) if team else "")
139
+ def _read_documents(a):
140
+ # General doc reader: reads recent documents on THIS pod by exact name, using the
141
+ # SAME core.document.controller the MCP uses. Gives the loop eyes on its own pod
142
+ # (copilot-thread, harness_session, sportradar-fixture, config docs, ...).
143
+ try:
144
+ from core.document.controller import document_search
145
+ except Exception as ex:
146
+ return "read_documents unavailable: "+str(ex)
147
+ name=str(a.get("name","")).strip()
148
+ if not name:
149
+ return "read_documents needs name (e.g. copilot-thread, harness_session, sportradar-fixture)"
150
+ try: limit=int(a.get("limit",5))
151
+ except Exception: limit=5
152
+ contains=str(a.get("contains","")).strip().lower()
153
+ r=document_search(filters={"name":name},page=1,page_size=max(1,min(limit,10)),sorters=["created",-1])
154
+ dd=r.get("data") if isinstance(r,dict) else None
155
+ docs=dd.get("data") if isinstance(dd,dict) else (dd if isinstance(dd,list) else [])
156
+ out=[]
157
+ for d in (docs or []):
158
+ s=json.dumps(d.get("value",{}) or {},ensure_ascii=False,default=str)
159
+ if contains and contains not in s.lower(): continue
160
+ out.append({"name":d.get("name"),"created":str(d.get("created","")),"value":s[:900]})
161
+ return out if out else ("no '"+name+"' documents found")
162
+ def _fetch_conversations(a):
163
+ # Real SportingBOT end-user chats from PostHog. Verbatim text lives on the
164
+ # posthog.ai_events table (input/output_choices, anchored on trace_id, 30d retention);
165
+ # events carries only metadata. Key read from the posthog-surface-config doc (same as
166
+ # the surface-verify defense). Returns recent (user-context, bot-answer, category).
167
+ import urllib.request, urllib.error, time
168
+ try:
169
+ from core.document.controller import document_search
170
+ except Exception as ex:
171
+ return "fetch_conversations unavailable: "+str(ex)
172
+ key=""; pid_doc=""
173
+ try:
174
+ r=document_search(filters={"name":"posthog-surface-config"},page=1,page_size=1)
175
+ dd=r.get("data") if isinstance(r,dict) else None
176
+ docs=dd.get("data") if isinstance(dd,dict) else (dd if isinstance(dd,list) else [])
177
+ if docs:
178
+ v=docs[0].get("value",{}) or {}
179
+ key=v.get("query_key","") or v.get("posthog_query_key","") or v.get("key","") or v.get("posthog_key","")
180
+ pid_doc=str(v.get("project","") or "")
181
+ except Exception as ex:
182
+ return "fetch_conversations: cannot read posthog key: "+str(ex)
183
+ if not key or str(key).startswith("$"):
184
+ return "fetch_conversations: no posthog key in posthog-surface-config doc"
185
+ pid=str(a.get("project_id") or pid_doc or "257767").strip() or "257767"
186
+ try: limit=int(a.get("limit",4))
187
+ except Exception: limit=4
188
+ limit=max(1,min(limit,6))
189
+ cat=str(a.get("category","")).replace("'","").strip()
190
+ catf=("AND properties.sbot_category = '"+cat+"' ") if cat else ""
191
+ q=("WITH t AS (SELECT properties.$ai_trace_id AS tid, properties.sbot_category AS cat, timestamp AS ts "
192
+ "FROM events WHERE event='$ai_generation' AND timestamp >= now() - INTERVAL 72 HOUR "
193
+ "AND properties.$ai_trace_id != '' "+catf+
194
+ "ORDER BY timestamp DESC LIMIT "+str(limit)+") "
195
+ "SELECT t.cat AS category, right(toString(a.input),260) AS user_ctx, "
196
+ "substring(toString(a.output_choices),1,300) AS bot "
197
+ "FROM posthog.ai_events AS a INNER JOIN t ON a.trace_id=t.tid "
198
+ "ORDER BY t.ts DESC LIMIT "+str(limit))
199
+ body=json.dumps({"query":{"kind":"HogQLQuery","query":q}}).encode()
200
+ url="https://us.posthog.com/api/projects/"+pid+"/query/"
201
+ hdr={"Authorization":"Bearer "+key,"Content-Type":"application/json"}
202
+ data=None
203
+ # The PostHog query API returns intermittent 5xx under load (same class as the
204
+ # org-usage scan). Retry transient failures before giving up so a flaky moment
205
+ # doesn't fail the whole turn.
206
+ for attempt in range(3):
207
+ try:
208
+ req=urllib.request.Request(url,data=body,headers=hdr,method="POST")
209
+ with urllib.request.urlopen(req,timeout=45) as resp:
210
+ data=json.loads(resp.read() or "{}")
211
+ break
212
+ except urllib.error.HTTPError as ex:
213
+ if ex.code>=500 and attempt<2:
214
+ time.sleep(1.5*(attempt+1)); continue
215
+ return "fetch_conversations posthog error: HTTP %s"%ex.code
216
+ except Exception as ex:
217
+ if attempt<2:
218
+ time.sleep(1.5*(attempt+1)); continue
219
+ return "fetch_conversations posthog error: "+str(ex)[:140]
220
+ out=[]
221
+ for row in (data.get("results") or []):
222
+ out.append({"category":row[0],"user_ctx":(row[1] or "")[:240],"bot":(row[2] or "")[:240]})
223
+ return out if out else "no recent conversations found"
139
224
  def dispatch(request_data: dict) -> dict:
140
225
  p=request_data.get("params",{}) or request_data
141
226
  tool=(p.get("tool_name") or "").strip()
@@ -145,17 +230,23 @@ def dispatch(request_data: dict) -> dict:
145
230
  except Exception:
146
231
  args={}
147
232
  if tool=="find_fixtures": r=_find_fixtures(args)
233
+ elif tool=="read_documents": r=_read_documents(args)
234
+ elif tool=="fetch_conversations": r=_fetch_conversations(args)
148
235
  elif tool=="get_datetime": r=datetime.now(timezone.utc).strftime("%A, %d %B %Y, %H:%M UTC")
149
236
  elif tool=="calculate": r=_calc(args)
150
237
  elif tool=="echo": r=str(args.get("text",""))
151
238
  else: r="unknown tool: "+tool
152
239
  return {"status": True, "data": {"tool_result": json.dumps(r, ensure_ascii=False, default=str)[:2800],
153
- "tool_ok": tool in ("find_fixtures","get_datetime","calculate","echo")}}
240
+ "tool_ok": tool in ("find_fixtures","read_documents","fetch_conversations","get_datetime","calculate","echo")}}
154
241
  '''
155
242
 
156
243
  CATALOG = [
157
244
  {"name": "find_fixtures", "params_hint": "team(str), limit(int=5)",
158
245
  "description": "Upcoming football fixtures (real project data) + AI pre-match analysis. Use for schedule / who-plays / pre-match questions."},
246
+ {"name": "read_documents", "params_hint": "name*(str), limit(int=5), contains(str?)",
247
+ "description": "Read recent documents stored on THIS project pod by exact name (e.g. copilot-thread, harness_session, sportradar-fixture, config docs). Use to inspect saved conversations/state on the pod before answering."},
248
+ {"name": "fetch_conversations", "params_hint": "limit(int=4), category(str?)",
249
+ "description": "Recent REAL SportingBOT end-user chat transcripts from PostHog (user context + bot answer + category). Use to analyze conversation quality and suggest concrete bot improvements."},
159
250
  {"name": "calculate", "params_hint": "expression*(str)", "description": "Evaluate arithmetic; never compute it yourself."},
160
251
  {"name": "get_datetime", "params_hint": "(no args)", "description": "Current UTC date/time."},
161
252
  {"name": "echo", "params_hint": "text*(str)", "description": "Echo text back verbatim."},
@@ -247,6 +338,8 @@ REASON_INSTR = (
247
338
  "- For ANY math -> needs_tool_call=true, call calculate {expression}. Never compute yourself.\n"
248
339
  "- For current date/time -> call get_datetime.\n"
249
340
  "- For upcoming matches / schedule / pre-match analysis -> call find_fixtures {team?, limit?}.\n"
341
+ "- To inspect saved documents/conversations/state on this pod (copilot-thread, harness_session, fixtures, config) -> call read_documents {name, limit?, contains?}.\n"
342
+ "- To analyze recent SportingBOT user chats or suggest bot improvements -> call fetch_conversations {limit?, category?}.\n"
250
343
  "- To repeat text -> call echo {text}.\n"
251
344
  "- Otherwise answer directly: needs_tool_call=false.\n"
252
345
  "name = exact tool from _3-available-tools; arguments_json = JSON-stringified args ('{}' if none). short_message = 1 line.")
@@ -376,7 +469,11 @@ def definitions():
376
469
  "outputs": {"session_id": "$.get('session_id')", "assistant_message": "$.get('assistant_message','')"}}]}
377
470
  # loop-beat is the durability tick (scheduling move). Created INACTIVE so it
378
471
  # does not run in a shared pod until a reviewer opts in by setting status:active.
379
- beat = {"name": "loop-beat", "title": "Loop Beat", "status": "inactive", "scheduled": True,
472
+ # NOTE scheduled=False: the platform's frequency beat (_tick_legacy_agent_frequency)
473
+ # only dispatches agents with scheduled=False + status=active + config-frequency.
474
+ # scheduled=True marks an agent as cron-driven (needs a real schedule) and, without
475
+ # one, it is silently NEVER dispatched — so a freq-based beat MUST be scheduled=False.
476
+ beat = {"name": "loop-beat", "title": "Loop Beat", "status": "inactive", "scheduled": False,
380
477
  "description": "durability tick: resume orphaned active sessions (set status:active to enable)",
381
478
  "context": {"config-frequency": 0.5}, "context-agent": {},
382
479
  "workflows": [{"name": "loop-resume", "description": "resume an orphaned active session", "inputs": {}, "outputs": {"resumed_session": "$.get('resumed_session')"}}]}
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "machina-cli"
7
- version = "0.4.4"
7
+ version = "0.4.8"
8
8
  description = "CLI for the Machina AI Agent platform"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -0,0 +1,134 @@
1
+ """HTTP client for Machina Core API."""
2
+
3
+ from typing import Optional
4
+
5
+ import httpx
6
+ from rich.console import Console
7
+
8
+ from machina_cli.config import get_api_url, get_credential, resolve_auth_token
9
+
10
+ console = Console(stderr=True)
11
+
12
+ TIMEOUT = 30.0
13
+
14
+
15
+ class MachinaClient:
16
+ """HTTP client that handles authentication and error formatting."""
17
+
18
+ def __init__(self, api_url: Optional[str] = None):
19
+ self.api_url = (api_url or get_api_url()).rstrip("/")
20
+
21
+ def _headers(self) -> dict:
22
+ header_name, token = resolve_auth_token()
23
+ headers = {"Content-Type": "application/json"}
24
+ if header_name and token:
25
+ headers[header_name] = token
26
+ else:
27
+ console.print("[red]Not authenticated. Run `machina login` first.[/red]")
28
+ raise SystemExit(1)
29
+ return headers
30
+
31
+ def _handle_response(self, response: httpx.Response, quiet: bool = False) -> dict:
32
+ data = {}
33
+ try:
34
+ data = response.json()
35
+ except Exception:
36
+ pass
37
+
38
+ # Extract error message from response body if available
39
+ error_msg = ""
40
+ if isinstance(data, dict):
41
+ error = data.get("error", {})
42
+ if isinstance(error, dict):
43
+ error_msg = error.get("message", "")
44
+
45
+ def emit(*args):
46
+ if not quiet:
47
+ console.print(*args)
48
+
49
+ if response.status_code == 401:
50
+ emit(f"[red]{error_msg or 'Session expired.'}[/red]")
51
+ emit("[yellow]Run `machina login` to re-authenticate.[/yellow]")
52
+ raise SystemExit(1)
53
+ if response.status_code == 403:
54
+ emit(f"[red]{error_msg or 'Permission denied.'}[/red]")
55
+ raise SystemExit(1)
56
+ if response.status_code == 404:
57
+ emit(f"[red]{error_msg or 'Resource not found.'}[/red]")
58
+ raise SystemExit(1)
59
+ if response.status_code >= 500:
60
+ emit(f"[red]{error_msg or 'Server error. Try again later.'}[/red]")
61
+ raise SystemExit(1)
62
+
63
+ if isinstance(data, dict) and data.get("status") == "error":
64
+ emit(f"[red]Error: {error_msg or 'Unknown error'}[/red]")
65
+ raise SystemExit(1)
66
+
67
+ return data
68
+
69
+ def _request(self, method: str, path: str, **kwargs) -> dict:
70
+ """Execute a request, optionally falling back from API key to session token on 5xx."""
71
+ url = f"{self.api_url}/{path.lstrip('/')}"
72
+ skip_auth = kwargs.pop("skip_auth", False)
73
+ allow_fallback = kwargs.pop("allow_fallback", True)
74
+ quiet = kwargs.pop("quiet", False)
75
+ headers = {"Content-Type": "application/json"} if skip_auth else self._headers()
76
+ try:
77
+ with httpx.Client(timeout=TIMEOUT) as client:
78
+ response = getattr(client, method)(url, headers=headers, **kwargs)
79
+
80
+ # A 5xx while sending an API key is ambiguous: the key may be invalid,
81
+ # the endpoint may not accept API-key auth (it 500s instead of 401), or
82
+ # the server may simply be faulting. Fall back to the session token for
83
+ # THIS request only — never delete the stored key on a 5xx (that would
84
+ # silently discard a possibly-valid key, e.g. during `login --api-key`).
85
+ if allow_fallback and response.status_code >= 500 and headers.get("X-Api-Token"):
86
+ session = get_credential("session_token")
87
+ if session:
88
+ retry_headers = {k: v for k, v in headers.items() if k != "X-Api-Token"}
89
+ retry_headers["X-Session-Token"] = session
90
+ retry = getattr(client, method)(url, headers=retry_headers, **kwargs)
91
+ if retry.status_code < 500:
92
+ if not quiet:
93
+ console.print(
94
+ "[yellow]API key not accepted by the server here; "
95
+ "used your session token for this request.[/yellow]"
96
+ )
97
+ response = retry
98
+
99
+ return self._handle_response(response, quiet=quiet)
100
+ except httpx.ConnectError:
101
+ if not quiet:
102
+ console.print(
103
+ f"[red]Cannot reach Machina API at {self.api_url}. Check your connection.[/red]"
104
+ )
105
+ raise SystemExit(1)
106
+
107
+ def get(
108
+ self,
109
+ path: str,
110
+ params: Optional[dict] = None,
111
+ allow_fallback: bool = True,
112
+ quiet: bool = False,
113
+ ) -> dict:
114
+ return self._request("get", path, params=params, allow_fallback=allow_fallback, quiet=quiet)
115
+
116
+ def post(
117
+ self,
118
+ path: str,
119
+ json_data: Optional[dict] = None,
120
+ skip_auth: bool = False,
121
+ allow_fallback: bool = True,
122
+ quiet: bool = False,
123
+ ) -> dict:
124
+ return self._request(
125
+ "post",
126
+ path,
127
+ json=json_data or {},
128
+ skip_auth=skip_auth,
129
+ allow_fallback=allow_fallback,
130
+ quiet=quiet,
131
+ )
132
+
133
+ def delete(self, path: str, allow_fallback: bool = True, quiet: bool = False) -> dict:
134
+ return self._request("delete", path, allow_fallback=allow_fallback, quiet=quiet)
@@ -68,29 +68,44 @@ def do_login(
68
68
  # Mode 1: API key
69
69
  if api_key:
70
70
  store_credential("api_key", api_key)
71
- console.print("[green]API key stored successfully.[/green]")
71
+ console.print("[green]API key stored.[/green]")
72
72
 
73
- # Verify the key works — try login/session first, fall back to org search
73
+ # Best-effort identity. CRITICAL: allow_fallback=False so a 5xx never swaps in
74
+ # the session token (which would report the wrong identity), and the key is
75
+ # NEVER cleared on failure — verification is informational only. quiet=True so
76
+ # we own the messaging instead of leaking raw error lines. A 5xx here is
77
+ # commonly the server faulting on API-key auth, not a bad key.
74
78
  client = MachinaClient()
79
+ label = ""
75
80
  try:
76
- result = client.get("login/session")
77
- user_data = result.get("data", {})
78
- name = user_data.get("name", "Unknown")
79
- console.print(f"Authenticated as [bold]{name}[/bold]")
81
+ data = (
82
+ client.get("login/session", allow_fallback=False, quiet=True).get("data", {}) or {}
83
+ )
84
+ label = data.get("name") or data.get("email") or ""
80
85
  except SystemExit:
81
- # login/session may not support API key auth — try listing orgs instead
82
86
  try:
83
- result = client.post("user/organizations/search", {
84
- "filters": {}, "page": 1, "page_size": 1, "sorters": ["name", 1],
85
- })
86
- orgs = result.get("data", [])
87
+ orgs = (
88
+ client.post(
89
+ "user/organizations/search",
90
+ {"filters": {}, "page": 1, "page_size": 1, "sorters": ["name", 1]},
91
+ allow_fallback=False,
92
+ quiet=True,
93
+ ).get("data", [])
94
+ or []
95
+ )
87
96
  if orgs:
88
- org_name = orgs[0].get("organization_name", orgs[0].get("name", ""))
89
- console.print(f"Authenticated — org: [bold]{org_name}[/bold]")
90
- else:
91
- console.print("[green]API key verified.[/green]")
97
+ label = orgs[0].get("organization_name") or orgs[0].get("name") or ""
92
98
  except SystemExit:
93
- console.print("[yellow]API key stored but could not verify. Check the key is valid.[/yellow]")
99
+ label = ""
100
+
101
+ if label:
102
+ console.print(f"Authenticated as [bold]{label}[/bold]")
103
+ else:
104
+ console.print(
105
+ "[yellow]Key stored, but the server didn't confirm it (the auth endpoints "
106
+ "may not accept API keys, or returned an error). The key is kept — run a "
107
+ "command to use it, or set the MACHINA_API_KEY env var.[/yellow]"
108
+ )
94
109
  return
95
110
 
96
111
  # Mode 3: Username/password (explicit flag)
@@ -146,17 +161,27 @@ def do_login(
146
161
 
147
162
  @app.command()
148
163
  def login(
149
- api_key: Optional[str] = typer.Option(None, "--api-key", "-k", help="Authenticate with an API key"),
150
- with_credentials: bool = typer.Option(False, "--with-credentials", help="Use username/password instead of browser"),
151
- username: Optional[str] = typer.Option(None, "--username", "-u", help="Username (requires --with-credentials)"),
152
- password: Optional[str] = typer.Option(None, "--password", "-p", help="Password (requires --with-credentials)"),
164
+ api_key: Optional[str] = typer.Option(
165
+ None, "--api-key", "-k", help="Authenticate with an API key"
166
+ ),
167
+ with_credentials: bool = typer.Option(
168
+ False, "--with-credentials", help="Use username/password instead of browser"
169
+ ),
170
+ username: Optional[str] = typer.Option(
171
+ None, "--username", "-u", help="Username (requires --with-credentials)"
172
+ ),
173
+ password: Optional[str] = typer.Option(
174
+ None, "--password", "-p", help="Password (requires --with-credentials)"
175
+ ),
153
176
  ):
154
177
  """Login to the Machina platform.
155
178
 
156
179
  Default: opens browser for Clerk authentication (magic link / SSO).
157
180
  Use --api-key for CI/CD, or --with-credentials for username/password.
158
181
  """
159
- do_login(api_key=api_key, username=username, password=password, with_credentials=with_credentials)
182
+ do_login(
183
+ api_key=api_key, username=username, password=password, with_credentials=with_credentials
184
+ )
160
185
 
161
186
 
162
187
  @app.command()
@@ -168,6 +193,7 @@ def logout():
168
193
  # Open browser logout to clear session cookies (Clerk + machina session)
169
194
  session_url = get_config("session_url") or "https://session.machina.gg"
170
195
  import webbrowser
196
+
171
197
  console.print("[dim]Opening browser to clear session cookies...[/dim]")
172
198
  webbrowser.open(f"{session_url}/logout")
173
199
  console.print("[green]Logged out completely.[/green]")
@@ -186,11 +212,14 @@ def clear_session():
186
212
  # Open browser to clear session cookies on the SESSION app
187
213
  session_url = get_config("session_url") or "https://session.machina.gg"
188
214
  import webbrowser
215
+
189
216
  console.print("[dim]Opening browser to clear server-side cookies...[/dim]")
190
217
  webbrowser.open(f"{session_url}/logout")
191
218
 
192
219
  console.print()
193
- console.print("[bold]Session fully cleared.[/bold] Run [bold #FF5C1F]machina login[/bold #FF5C1F] to re-authenticate.")
220
+ console.print(
221
+ "[bold]Session fully cleared.[/bold] Run [bold #FF5C1F]machina login[/bold #FF5C1F] to re-authenticate."
222
+ )
194
223
 
195
224
 
196
225
  @app.command()
@@ -222,19 +251,25 @@ def whoami(
222
251
  auth_method = "API Key" if header_name == "X-Api-Token" else "Session Token"
223
252
 
224
253
  if json_output:
225
- print(json.dumps({
226
- "authenticated": True,
227
- "name": user_data.get("name"),
228
- "email": user_data.get("email"),
229
- "user_id": user_data.get("_id", user_data.get("id")),
230
- "auth_method": auth_method,
231
- }))
254
+ print(
255
+ json.dumps(
256
+ {
257
+ "authenticated": True,
258
+ "name": user_data.get("name"),
259
+ "email": user_data.get("email"),
260
+ "user_id": user_data.get("_id", user_data.get("id")),
261
+ "auth_method": auth_method,
262
+ }
263
+ )
264
+ )
232
265
  return
233
266
 
234
- console.print(Panel.fit(
235
- f"[bold]Name:[/bold] {user_data.get('name', 'N/A')}\n"
236
- f"[bold]Email:[/bold] {user_data.get('email', 'N/A')}\n"
237
- f"[bold]User ID:[/bold] {user_data.get('_id', user_data.get('id', 'N/A'))}\n"
238
- f"[bold]Auth:[/bold] {auth_method}",
239
- title="Current User",
240
- ))
267
+ console.print(
268
+ Panel.fit(
269
+ f"[bold]Name:[/bold] {user_data.get('name', 'N/A')}\n"
270
+ f"[bold]Email:[/bold] {user_data.get('email', 'N/A')}\n"
271
+ f"[bold]User ID:[/bold] {user_data.get('_id', user_data.get('id', 'N/A'))}\n"
272
+ f"[bold]Auth:[/bold] {auth_method}",
273
+ title="Current User",
274
+ )
275
+ )
@@ -0,0 +1,165 @@
1
+ """Context Graph — self-healing / monitoring status across projects.
2
+
3
+ Answers "what self-healing is running, where, and how healthy is it" — the same
4
+ truth the Studio Context Graph page shows, from the CLI. Derives status live from
5
+ each project's context_graph_* docs + its self-heal agents (no extra state).
6
+ """
7
+
8
+ import json as json_lib
9
+ from typing import Optional
10
+
11
+ import typer
12
+ from rich.console import Console
13
+ from rich.table import Table
14
+
15
+ from machina_cli.client import MachinaClient
16
+ from machina_cli.config import get_config
17
+ from machina_cli.project_client import ProjectClient
18
+
19
+ app = typer.Typer(help="Context Graph — self-healing status")
20
+ console = Console()
21
+
22
+ # agents that make up the self-healing / monitoring layer
23
+ SELF_HEAL_AGENTS = ("surface-watch-beat", "loop-beat", "loop-runner")
24
+
25
+
26
+ def _docs(client: ProjectClient, name: str, page_size: int = 12) -> list:
27
+ r = client.post(
28
+ "document/search",
29
+ {"compact": False, "filters": {"name": name}, "page": 1, "page_size": page_size, "sorters": ["updated", -1]},
30
+ )
31
+ d = r.get("data")
32
+ return (d.get("data") if isinstance(d, dict) else d) or []
33
+
34
+
35
+ def _edge_summary(edge: str, h: dict) -> tuple:
36
+ """(badge, color, detail) for one context_graph_health edge."""
37
+ if edge == "market<->team_urn":
38
+ unresolved = h.get("linkable_unresolved")
39
+ if unresolved and unresolved > 0:
40
+ return ("unlinked", "red", f"{unresolved} unresolved · {h.get('team_markets', 0)} named")
41
+ lr = h.get("link_rate_pct")
42
+ return ("linked", "green", f"{lr}% linked" if lr is not None else f"{h.get('resolved', 0)} linked")
43
+ rate = h.get("broken_rate_pct")
44
+ if rate is not None:
45
+ return ("degraded" if rate > 0 else "ok", "red" if rate > 0 else "green", f"{rate}%")
46
+ return ("ok", "green", "—")
47
+
48
+
49
+ def _collect(project_id: str) -> dict:
50
+ """Live self-healing status for one project. Raises on unreachable/no-access."""
51
+ client = ProjectClient(project_id)
52
+ edges = {}
53
+ for doc in _docs(client, "context_graph_health", 12):
54
+ h = (doc.get("value") or {}).get("health") or {}
55
+ e = h.get("edge")
56
+ if e and e not in edges:
57
+ edges[e] = h
58
+ surf_docs = _docs(client, "context_graph_surface_health", 1)
59
+ surface = (surf_docs[0].get("value") or {}) if surf_docs else None
60
+ agents = {}
61
+ ar = client.post("agent/search", {"filters": {}, "page": 1, "page_size": 100})
62
+ ad = ar.get("data")
63
+ for a in (ad.get("data") if isinstance(ad, dict) else ad) or []:
64
+ if a.get("name") in SELF_HEAL_AGENTS:
65
+ agents[a["name"]] = {
66
+ "status": a.get("status"),
67
+ "scheduled": a.get("scheduled"),
68
+ "freq": (a.get("context") or {}).get("config-frequency"),
69
+ "last": str(a.get("last_execution_date") or a.get("updated") or "")[:19],
70
+ }
71
+ return {"edges": edges, "surface": surface, "agents": agents}
72
+
73
+
74
+ def _render_one(name: str, pid: str, st: dict) -> None:
75
+ console.print(f"\n[bold]{name}[/] [dim]({pid})[/]")
76
+ if not st["edges"] and not st["surface"] and not st["agents"]:
77
+ console.print(" [dim]no self-healing provisioned here[/]")
78
+ return
79
+ for edge, h in st["edges"].items():
80
+ badge, color, detail = _edge_summary(edge, h)
81
+ console.print(f" edge [bold]{edge:24}[/] [{color}]{badge:9}[/] [dim]{detail}[/]")
82
+ s = st["surface"]
83
+ if s:
84
+ v = s.get("verdict", "?")
85
+ h = s.get("health") or {}
86
+ color = "green" if v == "ok" else "yellow" if v == "low_traffic" else "red"
87
+ sig = f"sessions {h.get('sessions', h.get('users', 0))} · {h.get('exceptions', 0)} exc · err/s {h.get('err_per_session', h.get('err_per_user', 0))}"
88
+ console.print(f" surface [bold]odds/errors[/] [{color}]{v:9}[/] [dim]{sig}[/]")
89
+ for an in SELF_HEAL_AGENTS:
90
+ a = st["agents"].get(an)
91
+ if not a:
92
+ continue
93
+ alive = a["status"] == "active" and a["scheduled"] is False
94
+ c = "green" if a["status"] == "active" else "dim"
95
+ note = "" if a["status"] != "active" else (f" · freq={a['freq']}" + ("" if alive else " · [red]scheduled=True (won't fire)[/]"))
96
+ console.print(f" agent [bold]{an:20}[/] [{c}]{a['status']}[/]{note} [dim]{a['last']}[/]")
97
+
98
+
99
+ @app.command("status")
100
+ def status(
101
+ project_id: Optional[str] = typer.Option(None, "--project", "-p", help="Project ID (default: selected project)"),
102
+ org: bool = typer.Option(False, "--org", help="Roll up across all projects in the org"),
103
+ json_output: bool = typer.Option(False, "--json", "-j", help="Output as JSON"),
104
+ ):
105
+ """Show the self-healing / monitoring status (edges, surface, beats)."""
106
+ if not org:
107
+ pid = project_id or get_config("default_project_id")
108
+ if not pid:
109
+ console.print("[red]No project selected. Run `machina project use <id>` or pass --project.[/red]")
110
+ raise typer.Exit(1)
111
+ st = _collect(pid)
112
+ if json_output:
113
+ console.print_json(json_lib.dumps(st, default=str))
114
+ return
115
+ _render_one(get_config("default_project_name") or pid, pid, st)
116
+ return
117
+
118
+ # --org: iterate the org's projects
119
+ core = MachinaClient()
120
+ res = core.post("user/projects/search", {"filters": {}, "page": 1, "page_size": 200, "sorters": ["name", 1]})
121
+ projects = res.get("data", []) or []
122
+ rows, skipped = [], 0
123
+ for p in projects:
124
+ pid = p.get("project_id") or p.get("id")
125
+ pname = p.get("project_name") or p.get("name") or pid
126
+ if not pid:
127
+ continue
128
+ try:
129
+ st = _collect(pid)
130
+ except (SystemExit, Exception): # noqa: BLE001
131
+ skipped += 1
132
+ continue
133
+ if not st["edges"] and not st["surface"] and not st["agents"]:
134
+ continue # not provisioned — omit from the rollup
135
+ rows.append((pname, pid, st))
136
+
137
+ if json_output:
138
+ console.print_json(json_lib.dumps({"projects": [{"name": n, "id": i, **s} for n, i, s in rows], "skipped": skipped}, default=str))
139
+ return
140
+
141
+ if not rows:
142
+ console.print("[yellow]No projects have self-healing provisioned (or reachable).[/yellow]")
143
+ return
144
+ table = Table(title="Self-healing across the org")
145
+ table.add_column("Project", style="bold")
146
+ table.add_column("Edges", justify="right")
147
+ table.add_column("Surface")
148
+ table.add_column("Beat")
149
+ for pname, pid, st in rows:
150
+ n_edges = str(len(st["edges"]))
151
+ s = st["surface"]
152
+ surf = "—"
153
+ if s:
154
+ v = s.get("verdict", "?")
155
+ surf = f"[{'green' if v == 'ok' else 'yellow' if v == 'low_traffic' else 'red'}]{v}[/]"
156
+ beat = st["agents"].get("surface-watch-beat") or st["agents"].get("loop-beat")
157
+ if beat:
158
+ live = beat["status"] == "active" and beat["scheduled"] is False
159
+ beat_s = "[green]live[/]" if live else ("[red]active/scheduled=True[/]" if beat["status"] == "active" else "[dim]off[/]")
160
+ else:
161
+ beat_s = "[dim]none[/]"
162
+ table.add_row(pname, n_edges, surf, beat_s)
163
+ console.print(table)
164
+ if skipped:
165
+ console.print(f"[dim]{skipped} project(s) skipped (unreachable / no access).[/]")
@@ -11,6 +11,7 @@ from machina_cli.commands import (
11
11
  auth, org, project, credentials, deploy, config_cmd,
12
12
  workflow, agent, template, execution, skills,
13
13
  connector, mapping, prompt, document, sports, factory, loop, mcp, connect,
14
+ context_graph,
14
15
  )
15
16
  from machina_cli.commands.auth import do_login
16
17
 
@@ -143,6 +144,7 @@ app.add_typer(template.app, name="template", help="Template management")
143
144
  app.add_typer(skills.app, name="skills", help="Skills management")
144
145
  app.add_typer(execution.app, name="execution", help="Execution management")
145
146
  app.add_typer(loop.app, name="loop", help="Durable agentic turn loop (harness)")
147
+ app.add_typer(context_graph.app, name="context-graph", help="Self-healing / monitoring status across projects")
146
148
  app.add_typer(factory.app, name="factory", help="Trigger Factory coding-agent builds")
147
149
  app.add_typer(connector.app, name="connector", help="Connector management")
148
150
  app.add_typer(mapping.app, name="mapping", help="Mapping management")
@@ -1,101 +0,0 @@
1
- """HTTP client for Machina Core API."""
2
-
3
- from typing import Optional
4
-
5
- import httpx
6
- from rich.console import Console
7
-
8
- from machina_cli.config import _clear_credential, get_api_url, get_credential, resolve_auth_token
9
-
10
- console = Console(stderr=True)
11
-
12
- TIMEOUT = 30.0
13
-
14
-
15
- class MachinaClient:
16
- """HTTP client that handles authentication and error formatting."""
17
-
18
- def __init__(self, api_url: Optional[str] = None):
19
- self.api_url = (api_url or get_api_url()).rstrip("/")
20
-
21
- def _headers(self) -> dict:
22
- header_name, token = resolve_auth_token()
23
- headers = {"Content-Type": "application/json"}
24
- if header_name and token:
25
- headers[header_name] = token
26
- else:
27
- console.print("[red]Not authenticated. Run `machina login` first.[/red]")
28
- raise SystemExit(1)
29
- return headers
30
-
31
- def _handle_response(self, response: httpx.Response) -> dict:
32
- data = {}
33
- try:
34
- data = response.json()
35
- except Exception:
36
- pass
37
-
38
- # Extract error message from response body if available
39
- error_msg = ""
40
- if isinstance(data, dict):
41
- error = data.get("error", {})
42
- if isinstance(error, dict):
43
- error_msg = error.get("message", "")
44
-
45
- if response.status_code == 401:
46
- console.print(f"[red]{error_msg or 'Session expired.'}[/red]")
47
- console.print("[yellow]Run `machina login` to re-authenticate.[/yellow]")
48
- raise SystemExit(1)
49
- if response.status_code == 403:
50
- msg = error_msg or "Permission denied."
51
- console.print(f"[red]{msg}[/red]")
52
- raise SystemExit(1)
53
- if response.status_code == 404:
54
- msg = error_msg or "Resource not found."
55
- console.print(f"[red]{msg}[/red]")
56
- raise SystemExit(1)
57
- if response.status_code >= 500:
58
- msg = error_msg or "Server error. Try again later."
59
- console.print(f"[red]{msg}[/red]")
60
- raise SystemExit(1)
61
-
62
- if isinstance(data, dict) and data.get("status") == "error":
63
- console.print(f"[red]Error: {error_msg or 'Unknown error'}[/red]")
64
- raise SystemExit(1)
65
-
66
- return data
67
-
68
- def _request(self, method: str, path: str, **kwargs) -> dict:
69
- """Execute request with automatic API key fallback on 500."""
70
- url = f"{self.api_url}/{path.lstrip('/')}"
71
- skip_auth = kwargs.pop("skip_auth", False)
72
- headers = {"Content-Type": "application/json"} if skip_auth else self._headers()
73
- try:
74
- with httpx.Client(timeout=TIMEOUT) as client:
75
- response = getattr(client, method)(url, headers=headers, **kwargs)
76
-
77
- # If API key returns 500, it may be invalid/missing from Redis.
78
- # Clear it and retry with session token if available.
79
- if response.status_code >= 500 and headers.get("X-Api-Token"):
80
- if get_credential("session_token"):
81
- console.print(
82
- "[yellow]API key rejected by server. "
83
- "Falling back to session token...[/yellow]"
84
- )
85
- _clear_credential("api_key")
86
- headers = self._headers()
87
- response = getattr(client, method)(url, headers=headers, **kwargs)
88
-
89
- return self._handle_response(response)
90
- except httpx.ConnectError:
91
- console.print(f"[red]Cannot reach Machina API at {self.api_url}. Check your connection.[/red]")
92
- raise SystemExit(1)
93
-
94
- def get(self, path: str, params: Optional[dict] = None) -> dict:
95
- return self._request("get", path, params=params)
96
-
97
- def post(self, path: str, json_data: Optional[dict] = None, skip_auth: bool = False) -> dict:
98
- return self._request("post", path, json=json_data or {}, skip_auth=skip_auth)
99
-
100
- def delete(self, path: str) -> dict:
101
- return self._request("delete", path)
File without changes
File without changes
File without changes
File without changes
File without changes