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,595 @@
1
+ """`maximem-synap instances ...` — provision and manage memory instances."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import sys
8
+ import time
9
+ from datetime import datetime, timezone
10
+ import webbrowser
11
+ from pathlib import Path
12
+ from typing import Any, Dict, Optional, Tuple
13
+
14
+ import typer
15
+
16
+ from synap.cli import interactive, render
17
+ from synap.cli.api import EXIT_GENERIC, EXIT_TIMEOUT, EXIT_USAGE, CliError
18
+ from synap.cli.config import dashboard_base
19
+ from synap.cli.validate import json_object, one_of, usage_error
20
+
21
+ app = typer.Typer(no_args_is_help=True)
22
+
23
+ _RELATIONSHIPS = ("b2c", "b2b", "internal", "agent_to_agent")
24
+ _COPY_MODES = ("config_only", "config_and_memories")
25
+
26
+ _LIST_COLUMNS = [
27
+ ("id", "ID"),
28
+ ("name", "NAME"),
29
+ ("status", "STATUS"),
30
+ ("agent_type", "AGENT"),
31
+ ("relationship", "RELATIONSHIP"),
32
+ ("build", "BUILD"),
33
+ ("config_status", "CONFIG"),
34
+ ("memories_count", "MEMORIES"),
35
+ ("created_at", "CREATED"),
36
+ ]
37
+
38
+
39
+ def with_display_columns(rows):
40
+ """Table rows with the two facts an agent needs to pick an instance: who it
41
+ serves (fixed at creation) and whether its memory architecture is built.
42
+ JSON output keeps the server's rows untouched."""
43
+ out = []
44
+ for r in rows or []:
45
+ if not isinstance(r, dict):
46
+ out.append(r)
47
+ continue
48
+ state, _raw, _why = maca_state(r)
49
+ out.append({**r, "relationship": r.get("user_relationship") or "—", "build": state})
50
+ return out
51
+
52
+
53
+ @app.command(name="list")
54
+ def list_instances(
55
+ ctx: typer.Context,
56
+ page: int = typer.Option(1, "--page", min=1),
57
+ page_size: int = typer.Option(20, "--page-size", min=1, max=50),
58
+ status_filter: Optional[str] = typer.Option(None, "--status"),
59
+ ) -> None:
60
+ """List the instances in your client."""
61
+ cc = ctx.obj
62
+ resp = cc.client().get(
63
+ "/instances",
64
+ params={"page": page, "page_size": page_size, "status_filter": status_filter},
65
+ )
66
+ rows = resp.get("data", [])
67
+ if render.is_json() or render.is_csv():
68
+ # Machine formats keep their long-standing shape.
69
+ cols = [c for c in _LIST_COLUMNS if c[0] not in ("relationship", "build")]
70
+ render.print_table(rows, cols, empty="No instances yet.", full_keys=("id",))
71
+ return
72
+ render.print_table(with_display_columns(rows), _LIST_COLUMNS,
73
+ empty="No instances yet.", full_keys=("id",))
74
+
75
+
76
+ @app.command()
77
+ def get(ctx: typer.Context, instance_id: str = typer.Argument(...)) -> None:
78
+ """Show one instance in detail."""
79
+ cc = ctx.obj
80
+ inst = cc.client().get(f"/instances/{instance_id}")
81
+ if not inst:
82
+ raise CliError(f"Instance '{instance_id}' not found.")
83
+ render.print_detail(inst, title=inst.get("name"))
84
+
85
+
86
+ @app.command()
87
+ def template(
88
+ ctx: typer.Context,
89
+ output_file: Optional[str] = typer.Option(
90
+ None, "--output-file", help="Write the template markdown here instead of stdout.",
91
+ ),
92
+ ) -> None:
93
+ """Print (or save) the use-case template that `instances create` expects."""
94
+ cc = ctx.obj
95
+ tpl = cc.client().get("/instances/usecase-template")
96
+ if not isinstance(tpl, dict) or "content" not in tpl:
97
+ raise CliError("The server returned no use-case template.", code="bad_response",
98
+ exit_code=8)
99
+ if output_file:
100
+ path = Path(output_file)
101
+ path.write_text(tpl["content"], encoding="utf-8")
102
+ if render.is_json():
103
+ render.print_json({**tpl, "written_to": str(path)})
104
+ else:
105
+ render.success(f"Template written to {path}.")
106
+ return
107
+ if render.is_json():
108
+ render.print_json(tpl)
109
+ return
110
+ sys.stdout.write(tpl["content"])
111
+ if not tpl["content"].endswith("\n"):
112
+ sys.stdout.write("\n")
113
+
114
+
115
+ @app.command()
116
+ def create(
117
+ ctx: typer.Context,
118
+ name: str = typer.Option(..., "--name", "-n", help="Instance name."),
119
+ user_relationship: Optional[str] = typer.Option(
120
+ None, "--relationship", "-r",
121
+ help="REQUIRED, no default, chosen when the instance is created (to change it later, email gaurav@maximem.ai): b2c (each end user has "
122
+ "private memory; recommended for per-person apps such as assistants and "
123
+ "consumer products) | b2b (memory shared across a customer's users) | "
124
+ "internal (a team's own tools) | agent_to_agent (agents talking to agents). "
125
+ "Ask the human.",
126
+ ),
127
+ agent_type: Optional[str] = typer.Option(None, "--agent-type"),
128
+ metadata: Optional[str] = typer.Option(
129
+ None, "--metadata", help="Instance metadata as a JSON object.",
130
+ ),
131
+ from_file: Optional[str] = typer.Option(
132
+ None, "--from-file", help="The use-case markdown file.",
133
+ ),
134
+ from_stdin: bool = typer.Option(
135
+ False, "--from-stdin", help="Read the use-case markdown from stdin.",
136
+ ),
137
+ idempotency_key: Optional[str] = typer.Option(
138
+ None, "--idempotency-key",
139
+ help="Override the automatic Idempotency-Key (derived from workspace, name, "
140
+ "relationship and use-case text). A repeat with the same key never "
141
+ "creates a second instance.",
142
+ ),
143
+ deletion_period_days: Optional[int] = typer.Option(
144
+ None, "--deletion-period-days", min=0, max=30,
145
+ help="Days a deleted memory stays hidden and restorable before it is purged "
146
+ "for good, 0 to 30 (default 30). Needs a key with update:instances.",
147
+ ),
148
+ ) -> None:
149
+ """Create a new instance (MACA config generation starts server-side)."""
150
+ cc = ctx.obj
151
+ if user_relationship is None:
152
+ # Immutable choice: never defaulted, in any mode. Interactively the human
153
+ # picks; otherwise fail naming the flag.
154
+ user_relationship = interactive.prompt_choice(
155
+ "Who will use this memory? This is chosen when the instance is created; to change it later, email gaurav@maximem.ai",
156
+ _RELATIONSHIPS, flag="--relationship",
157
+ hint="Pass --relationship with one of: b2c (private memory per end user; "
158
+ "recommended for per-person apps), b2b (shared across a customer's users), "
159
+ "internal, agent_to_agent. Ask the human; it is chosen when the instance is created, and to change it later, email gaurav@maximem.ai.",
160
+ )
161
+ one_of(user_relationship, _RELATIONSHIPS, flag="--relationship")
162
+ if from_file and from_stdin:
163
+ raise usage_error("Pass either --from-file or --from-stdin, not both.")
164
+ if not from_file and not from_stdin:
165
+ raise usage_error(
166
+ "A use-case document is required: pass --from-file PATH or --from-stdin.",
167
+ hint="Get the template with `maximem-synap instances template`.",
168
+ )
169
+ if from_stdin:
170
+ if sys.stdin.isatty():
171
+ raise usage_error("--from-stdin needs piped input, but stdin is a terminal.")
172
+ content = sys.stdin.read()
173
+ file_name = "usecase.md"
174
+ if not content.strip():
175
+ raise usage_error("--from-stdin: stdin was empty.")
176
+ else:
177
+ path = Path(from_file)
178
+ if not path.is_file():
179
+ raise usage_error(f"--from-file: no such file '{from_file}'.")
180
+ content = path.read_text(encoding="utf-8")
181
+ file_name = path.name
182
+ if not content.strip():
183
+ raise usage_error(f"--from-file: '{from_file}' is empty.")
184
+ body = {
185
+ "name": name,
186
+ "userRelationship": user_relationship,
187
+ "agentType": agent_type,
188
+ "metadata": json_object(metadata, flag="--metadata"),
189
+ "usecaseMarkdown": {"content": content, "fileName": file_name},
190
+ "deletionPeriodDays": deletion_period_days,
191
+ }
192
+ client = cc.client()
193
+ key = (idempotency_key or "").strip() or derive_idempotency_key(
194
+ _workspace_id(cc), name, user_relationship, content)
195
+ inst = client.post(
196
+ "/instances", json={k: v for k, v in body.items() if v is not None},
197
+ headers={"Idempotency-Key": key}, retry_once_on_network_error=True,
198
+ )
199
+ replay = (getattr(client, "last_response_headers", None) or {}).get(
200
+ "idempotent-replay") == "true"
201
+ if replay:
202
+ print(f"Instance already created by this request: {inst.get('id')} (not creating another). "
203
+ "This is the instance the identical earlier `instances create` made (same name, "
204
+ "relationship and use-case, within the last 24 hours), not a new one. To make a "
205
+ "separate instance, change the name or pass a different --idempotency-key.",
206
+ file=sys.stderr)
207
+ if isinstance(inst, dict):
208
+ inst = {**inst, "idempotent_replay": True}
209
+ render.print_detail(inst)
210
+ return
211
+ print(f"Created instance {inst.get('id')} ({inst.get('name')}, {user_relationship}). "
212
+ "The memory architecture build started: usually 15 to 20 minutes.", file=sys.stderr)
213
+ render.success(f"Created instance [bold]{inst.get('name')}[/bold] ({inst.get('id')}).")
214
+ render.print_detail(inst)
215
+
216
+
217
+ def _workspace_id(cc) -> str:
218
+ try:
219
+ return cc.active_profile().client_id or ""
220
+ except Exception:
221
+ return ""
222
+
223
+
224
+ def derive_idempotency_key(workspace_id: str, name: str, relationship: str, usecase: str) -> str:
225
+ """Deterministic key: the same command retried yields the same key."""
226
+ digest = hashlib.sha256(usecase.encode("utf-8")).hexdigest()
227
+ blob = json.dumps([workspace_id, name, relationship, digest], separators=(",", ":"))
228
+ return "syn-cli-" + hashlib.sha256(blob.encode("utf-8")).hexdigest()[:48]
229
+
230
+
231
+ _READY = {"ready", "done", "complete", "completed", "built", "approved", "active"}
232
+ _FAILED = {"failed", "error", "errored", "maca_failed", "rejected"}
233
+ # Explicit build-status fields win. `config_status` is only a fallback because
234
+ # it reads "approved" as soon as a config row exists, which may be before the
235
+ # build is finished.
236
+ _STATUS_KEYS = ("maca_status", "macaStatus", "maca_build_status", "build_status")
237
+ _FALLBACK_KEYS = ("configStatus", "config_status")
238
+
239
+
240
+ def _maca(inst: Dict[str, Any]) -> Dict[str, Any]:
241
+ build = inst.get("maca") or inst.get("maca_build") or inst.get("macaBuild")
242
+ return build if isinstance(build, dict) else {}
243
+
244
+
245
+ def _int(value: Any) -> Optional[int]:
246
+ try:
247
+ return None if value is None or isinstance(value, bool) else int(value)
248
+ except (TypeError, ValueError):
249
+ return None
250
+
251
+
252
+ def _left(seconds: Optional[int]) -> str:
253
+ if seconds is None:
254
+ return "taking longer than usual"
255
+ if seconds < 60:
256
+ return "less than a minute left"
257
+ return f"about {-(-seconds // 60)} min left"
258
+
259
+
260
+ def build_facts(inst: Dict[str, Any]) -> Dict[str, Any]:
261
+ """The supervision fields of the maca object, read tolerantly (snake or camel)."""
262
+ m = _maca(inst)
263
+
264
+ def pick(*keys):
265
+ for k in keys:
266
+ if k in m:
267
+ return m[k]
268
+ return None
269
+
270
+ restartable = pick("restartable")
271
+ build_seconds = _int(pick("elapsed_seconds", "elapsedSeconds"))
272
+ if build_seconds is None:
273
+ start = _parse_ts(pick("started_at", "startedAt"))
274
+ end = _parse_ts(pick("ready_at", "readyAt", "finished_at", "finishedAt"))
275
+ if start is not None and end is not None and end >= start:
276
+ build_seconds = int((end - start).total_seconds())
277
+ return {
278
+ "build_seconds": build_seconds,
279
+ "attempt": _int(pick("attempt")),
280
+ "max_attempts": _int(pick("max_attempts", "maxAttempts")),
281
+ "elapsed_seconds": _int(pick("elapsed_seconds", "elapsedSeconds")),
282
+ "estimated_remaining_seconds": _int(
283
+ pick("estimated_remaining_seconds", "estimatedRemainingSeconds")),
284
+ "restartable": bool(restartable) if restartable is not None else None,
285
+ "stage": m.get("stage"),
286
+ "message": m.get("message"),
287
+ }
288
+
289
+
290
+ def _parse_ts(value: Any) -> Optional[datetime]:
291
+ if not isinstance(value, str) or not value:
292
+ return None
293
+ try:
294
+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
295
+ except ValueError:
296
+ return None
297
+ return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
298
+
299
+
300
+ def _duration(seconds: int) -> str:
301
+ m, s = divmod(max(int(seconds), 0), 60)
302
+ return f"{m}m {s}s" if m else f"{s}s"
303
+
304
+
305
+ def progress_line(raw: Optional[str], facts: Dict[str, Any]) -> str:
306
+ """One stderr line, e.g. 'attempt 2 of 3, about 6 min left (stage: x)'."""
307
+ parts = []
308
+ if facts["attempt"] is not None:
309
+ of = f" of {facts['max_attempts']}" if facts["max_attempts"] else ""
310
+ parts.append(f"attempt {facts['attempt']}{of}")
311
+ if facts["attempt"] is not None or facts["estimated_remaining_seconds"] is not None:
312
+ parts.append(_left(facts["estimated_remaining_seconds"]))
313
+ line = ", ".join(parts) if parts else (raw or "building")
314
+ extra = facts["stage"] or facts["message"]
315
+ if extra:
316
+ line += f" ({extra})"
317
+ return line
318
+
319
+
320
+ def maca_state(inst: Dict[str, Any]) -> Tuple[str, Optional[str], Optional[str]]:
321
+ """Classify an instance payload as (state, raw_status, reason).
322
+
323
+ state is "ready", "failed", "building" or "review" (the configuration is
324
+ waiting for Synap to review it; nothing the caller can do).
325
+ """
326
+ # The backend exposes {"maca": {"state": building|ready|failed|unknown,
327
+ # "stage"?, "message"?, "error"?}}. "unknown" (e.g. awaiting review) is not
328
+ # terminal, so it keeps waiting and the stage/message is shown as progress.
329
+ build = inst.get("maca") or inst.get("maca_build") or inst.get("macaBuild")
330
+ raw: Any = None
331
+ reason = None
332
+ if isinstance(build, dict):
333
+ raw = build.get("state") or build.get("status")
334
+ reason = build.get("error") or build.get("reason") or build.get("failure_reason")
335
+ if raw == "unknown" and build.get("stage") == "awaiting_review":
336
+ return "review", "unknown (awaiting_review)", build.get("message")
337
+ if raw == "unknown" and (build.get("stage") or build.get("message")):
338
+ raw = f"unknown ({build.get('stage') or build.get('message')})"
339
+ if raw is None:
340
+ for key in _STATUS_KEYS:
341
+ if inst.get(key) is not None:
342
+ raw = inst[key]
343
+ break
344
+ if raw is None:
345
+ for key in _FALLBACK_KEYS:
346
+ if inst.get(key) is not None:
347
+ raw = inst[key]
348
+ break
349
+ reason = reason or inst.get("maca_error") or inst.get("maca_failure_reason")
350
+ norm = str(raw).strip().lower() if raw is not None else None
351
+ if norm in _FAILED:
352
+ return "failed", norm, reason
353
+ if norm in _READY:
354
+ return "ready", norm, None
355
+ return "building", norm, None
356
+
357
+
358
+ @app.command()
359
+ def wait(
360
+ ctx: typer.Context,
361
+ instance_id: str = typer.Argument(...),
362
+ timeout: int = typer.Option(1200, "--timeout", min=1, help="Give up after this many seconds."),
363
+ interval: int = typer.Option(10, "--interval", min=1, help="Seconds between checks."),
364
+ ) -> None:
365
+ """Wait until the instance's memory architecture (MACA) has finished building.
366
+
367
+ Progress goes to stderr; stdout gets one final JSON object. Exit 0 when
368
+ ready, 7 on timeout, 1 if the build failed.
369
+ """
370
+ cc = ctx.obj
371
+ client = cc.pinned_client()
372
+ start = time.monotonic()
373
+ consecutive_errors = 0
374
+ last_raw = None
375
+ last_facts: Dict[str, Any] = {}
376
+ while True:
377
+ try:
378
+ inst = client.get(f"/instances/{instance_id}")
379
+ consecutive_errors = 0
380
+ except CliError as e:
381
+ # A blip should not abort a 15 minute wait; real answers should.
382
+ if e.exit_code != 8 or consecutive_errors >= 4:
383
+ raise
384
+ consecutive_errors += 1
385
+ inst = None
386
+ render.err_console.print(f" [dim]transient error ({e.message}); retrying[/dim]")
387
+ elapsed = int(time.monotonic() - start)
388
+ if inst is not None:
389
+ if not inst:
390
+ raise CliError(f"Instance '{instance_id}' not found.", code="not_found",
391
+ exit_code=4)
392
+ state, raw, reason = maca_state(inst)
393
+ facts = build_facts(inst)
394
+ extra = {k: facts[k] for k in ("attempt", "max_attempts",
395
+ "estimated_remaining_seconds", "restartable")}
396
+ extra["build_seconds"] = facts["build_seconds"]
397
+ extra["waited_seconds"] = elapsed
398
+ build_s = facts["build_seconds"]
399
+ elapsed_total = build_s if build_s is not None else elapsed
400
+ if state == "ready":
401
+ if build_s is not None:
402
+ render.err_console.print(f" [dim]ready, the build took {_duration(build_s)}[/dim]")
403
+ else:
404
+ render.err_console.print(
405
+ f" [dim]ready (waited {_duration(elapsed)}; build time not reported)[/dim]")
406
+ else:
407
+ render.err_console.print(
408
+ f" [dim]{elapsed}s: {progress_line(raw, facts)}[/dim]")
409
+ last_raw = raw
410
+ last_facts = extra
411
+ if state == "ready":
412
+ _final({"instance_id": instance_id, "status": "ready",
413
+ "maca_status": raw, **extra, "elapsed_seconds": elapsed_total})
414
+ return
415
+ if state == "review":
416
+ _final({"instance_id": instance_id, "status": "awaiting_review",
417
+ "maca_status": raw, **extra, "elapsed_seconds": elapsed_total})
418
+ raise CliError(
419
+ "The configuration is waiting for review by Synap; nothing you can "
420
+ "do from here.",
421
+ code="awaiting_review", exit_code=EXIT_GENERIC,
422
+ hint="Tell the human the build is paused for review on Synap's side. "
423
+ f"Re-run `instances wait {instance_id}` later; do not create a "
424
+ "second instance for this.",
425
+ )
426
+ if state == "failed":
427
+ reason = reason or facts["message"]
428
+ _final({"instance_id": instance_id, "status": "failed",
429
+ "maca_status": raw, "reason": reason, **extra,
430
+ "elapsed_seconds": elapsed_total})
431
+ tries = (f" after {facts['attempt']} of {facts['max_attempts']} attempts"
432
+ if facts["attempt"] and facts["max_attempts"] else "")
433
+ if facts["restartable"] is False:
434
+ hint = ("Tell the human why it failed (the reason is in the error). "
435
+ "This build cannot be restarted from here; ask whether to "
436
+ "create a new instance.")
437
+ else:
438
+ hint = (f"Run: maximem-synap instances rebuild {instance_id}. Tell the "
439
+ "human why it failed and that you are restarting the build; if "
440
+ "a rebuild fails too, say so plainly and ask what to do.")
441
+ raise CliError(
442
+ f"The memory architecture build failed{tries}"
443
+ + (f": {reason}" if reason else "."),
444
+ code="build_failed", exit_code=EXIT_GENERIC, hint=hint,
445
+ )
446
+ if time.monotonic() - start + interval > timeout:
447
+ _final({"instance_id": instance_id, "status": "timeout",
448
+ "maca_status": last_raw, **last_facts, "elapsed_seconds": elapsed})
449
+ raise CliError(
450
+ f"Timed out after {timeout}s waiting for the build.",
451
+ code="wait_timeout", exit_code=EXIT_TIMEOUT,
452
+ hint=f"The build may still be running. Re-run `instances wait {instance_id}`.",
453
+ )
454
+ time.sleep(interval)
455
+
456
+
457
+ @app.command()
458
+ def rebuild(ctx: typer.Context, instance_id: str = typer.Argument(...)) -> None:
459
+ """Restart the memory architecture build of an instance whose build failed.
460
+
461
+ Re-runs the build from the stored use-case (nothing is re-uploaded). Allowed only
462
+ when the build has failed, and at most 3 times per instance per 24 hours. Never
463
+ prompts. Then run `instances wait <id>`.
464
+ """
465
+ cc = ctx.obj
466
+ resp = cc.client().post(f"/instances/{instance_id}/rebuild")
467
+ resp = resp if isinstance(resp, dict) else {}
468
+ facts = build_facts(resp if _maca(resp) else {"maca": resp})
469
+ if render.is_json():
470
+ render.print_json({"instance_id": instance_id, "status": "rebuild_started",
471
+ **{k: facts[k] for k in ("attempt", "max_attempts",
472
+ "estimated_remaining_seconds")},
473
+ "response": resp})
474
+ return
475
+ tries = (f" (attempt {facts['attempt']} of {facts['max_attempts']})"
476
+ if facts["attempt"] and facts["max_attempts"] else "")
477
+ left = facts["estimated_remaining_seconds"]
478
+ how_long = _left(left) if left is not None else "usually 15 to 20 minutes"
479
+ render.success(f"Rebuild started for {instance_id}{tries}: {how_long}.")
480
+ render.info(f"Next: maximem-synap instances wait {instance_id}")
481
+
482
+
483
+ def _final(payload: Dict[str, Any]) -> None:
484
+ """The wait result: always one JSON object on stdout, whatever --output says."""
485
+ print(json.dumps(payload, default=str))
486
+
487
+
488
+ @app.command()
489
+ def update(
490
+ ctx: typer.Context,
491
+ instance_id: str = typer.Argument(...),
492
+ name: Optional[str] = typer.Option(None, "--name", "-n"),
493
+ metadata: Optional[str] = typer.Option(
494
+ None, "--metadata", help="Replace instance metadata with this JSON object.",
495
+ ),
496
+ deletion_period_days: Optional[int] = typer.Option(
497
+ None, "--deletion-period-days", min=0, max=30,
498
+ help="Days a deleted memory stays hidden and restorable before it is purged "
499
+ "for good, 0 to 30 (default 30). Needs a key with update:instances.",
500
+ ),
501
+ ) -> None:
502
+ """Rename or edit an instance, or change how long deleted memories stay restorable."""
503
+ cc = ctx.obj
504
+ patch = {
505
+ k: v for k, v in {
506
+ "name": name,
507
+ "metadata": json_object(metadata, flag="--metadata"),
508
+ "deletionPeriodDays": deletion_period_days,
509
+ }.items() if v is not None
510
+ }
511
+ if not patch:
512
+ raise CliError("Nothing to update. Pass --name, --metadata and/or --deletion-period-days.")
513
+ inst = cc.client().patch(f"/instances/{instance_id}", json=patch)
514
+ render.success("Instance updated.")
515
+ render.print_detail(inst)
516
+
517
+
518
+ @app.command()
519
+ def promote(
520
+ ctx: typer.Context,
521
+ instance_id: str = typer.Argument(...),
522
+ target_name: str = typer.Option(..., "--target-name", help="Name for the prod sibling."),
523
+ copy_mode: str = typer.Option(
524
+ "config_only", "--copy-mode", help="config_only | config_and_memories",
525
+ ),
526
+ ) -> None:
527
+ """Create a production sibling from an existing instance."""
528
+ cc = ctx.obj
529
+ one_of(copy_mode, _COPY_MODES, flag="--copy-mode")
530
+ result = cc.client().post(
531
+ f"/instances/{instance_id}/promote",
532
+ json={"targetName": target_name, "copyMode": copy_mode},
533
+ )
534
+ render.success(
535
+ f"Promoted to [bold]{target_name}[/bold] "
536
+ f"(copied {result.get('copied_memories_count', 0)} memories)."
537
+ )
538
+ render.print_detail(result.get("instance", {}))
539
+
540
+
541
+ @app.command(name="open")
542
+ def open_instance(
543
+ ctx: typer.Context,
544
+ instance_id: Optional[str] = typer.Argument(
545
+ None, help="Instance to open (omit for the instances list page).",
546
+ ),
547
+ no_browser: bool = typer.Option(
548
+ False, "--no-browser", help="Print the URL instead of opening a browser.",
549
+ ),
550
+ ) -> None:
551
+ """Open an instance (or the instances list) in the dashboard."""
552
+ cc = ctx.obj
553
+ base = dashboard_base(cc.api_base())
554
+ if not base:
555
+ raise CliError(
556
+ f"No known dashboard for {cc.api_base()}. `open` supports the prod/staging servers."
557
+ )
558
+ url = f"{base}/dashboard/instances/{instance_id}" if instance_id else f"{base}/dashboard/instances"
559
+ if no_browser:
560
+ print(url)
561
+ return
562
+ opened = False
563
+ try:
564
+ opened = webbrowser.open(url)
565
+ except Exception:
566
+ opened = False
567
+ if opened:
568
+ render.success(f"Opened {url}")
569
+ else:
570
+ render.info(url)
571
+
572
+
573
+ @app.command()
574
+ def delete(
575
+ ctx: typer.Context,
576
+ instance_id: str = typer.Argument(...),
577
+ yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation prompt (required without a terminal)."),
578
+ ) -> None:
579
+ """Delete an instance (async). Asks you to confirm unless --yes."""
580
+ cc = ctx.obj
581
+ client = cc.client()
582
+ inst = client.get(f"/instances/{instance_id}")
583
+ name = inst.get("name", instance_id)
584
+
585
+ if not yes:
586
+ typed = interactive.prompt_text(
587
+ f"Type the instance name '{name}' to confirm deletion", flag="--yes",
588
+ )
589
+ if typed != name:
590
+ raise CliError("Name did not match — aborted.")
591
+
592
+ result = client.delete(f"/instances/{instance_id}")
593
+ render.success(
594
+ f"Deletion queued for '{name}' (job {result.get('job_id', '—')})."
595
+ )