ragfly-cli 2.1.0__tar.gz → 2.2.0__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 (32) hide show
  1. {ragfly_cli-2.1.0/ragfly_cli.egg-info → ragfly_cli-2.2.0}/PKG-INFO +37 -4
  2. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/README.md +36 -3
  3. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/pyproject.toml +1 -1
  4. ragfly_cli-2.2.0/ragfly_cli/__init__.py +1 -0
  5. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli/cli.py +266 -21
  6. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli/cloud_commands.py +40 -5
  7. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0/ragfly_cli.egg-info}/PKG-INFO +37 -4
  8. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli.egg-info/SOURCES.txt +3 -0
  9. ragfly_cli-2.2.0/tests/test_idioma_errores.py +41 -0
  10. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/tests/test_login_summary_cli.py +2 -2
  11. ragfly_cli-2.2.0/tests/test_login_two_step_cli.py +79 -0
  12. ragfly_cli-2.2.0/tests/test_long_answers_and_ingestion_cli.py +154 -0
  13. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/tests/test_surface_parity_cli.py +27 -0
  14. ragfly_cli-2.1.0/ragfly_cli/__init__.py +0 -1
  15. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/LICENSE +0 -0
  16. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli/__main__.py +0 -0
  17. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli/_http.py +0 -0
  18. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli/_runtime.py +0 -0
  19. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli/config.py +0 -0
  20. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli/grupo_activo.py +0 -0
  21. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli/keyring_store.py +0 -0
  22. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli/oop/__init__.py +0 -0
  23. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli/oop/cli_command.py +0 -0
  24. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli/oop/http_client.py +0 -0
  25. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli/version_check.py +0 -0
  26. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli.egg-info/dependency_links.txt +0 -0
  27. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli.egg-info/entry_points.txt +0 -0
  28. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli.egg-info/requires.txt +0 -0
  29. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/ragfly_cli.egg-info/top_level.txt +0 -0
  30. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/setup.cfg +0 -0
  31. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/tests/test_agent_context_cli.py +0 -0
  32. {ragfly_cli-2.1.0 → ragfly_cli-2.2.0}/tests/test_api_key_group_override.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ragfly-cli
3
- Version: 2.1.0
3
+ Version: 2.2.0
4
4
  Summary: RAGfly CLI — operate RAGfly from the terminal and CI (login + cloud API). Lightweight, no desktop dependencies.
5
5
  Author: CAB Ltda
6
6
  License: MIT
@@ -47,6 +47,10 @@ ragfly login
47
47
  export RAGFLY_API_KEY=rf_xxxxxxxxxx
48
48
  ```
49
49
 
50
+ If your account has two-step verification, `ragfly login` asks for the code of your
51
+ authenticator app. An account that manages an organization needs it to use a session;
52
+ an API key does not.
53
+
50
54
  `cloud group` and `cloud api-key` manage a person's session and credentials: they
51
55
  need `ragfly login`, and the server refuses them for an API key.
52
56
 
@@ -81,16 +85,18 @@ ragfly
81
85
  ├── location list
82
86
  ├── group list | switch | clear (signed-in person)
83
87
  ├── api-key create | list | revoke (signed-in person)
84
- ├── document list | show | edges
85
- ├── collection list | show | compose | read | refresh | save
88
+ ├── document list | show | edges | ingest | ingest-status
89
+ ├── collection list | show | from-search | compose | read | refresh | save
86
90
  ├── queue show | runs
87
91
  ├── skill list | show | run
88
92
  ├── catalog
89
93
  ├── document-type list
90
94
  ├── characteristic list
91
95
  ├── function show
96
+ ├── destinations
97
+ ├── answering-guide
92
98
  ├── search
93
- ├── chat ask
99
+ ├── chat ask | answer
94
100
  ├── agent context | tool
95
101
  ├── usage
96
102
  ├── conversation list | delete
@@ -122,6 +128,33 @@ ragfly cloud search "statements" --filter @filter.json --collection 12
122
128
  ragfly cloud chat ask "How do I release the workspace of my key?" --mode help
123
129
  ```
124
130
 
131
+ ### Long answers
132
+
133
+ `cloud chat ask` waits up to 300 seconds for an answer (`--wait`). If it does not arrive
134
+ in time, the exit code is 2 and you read it later, at no extra quota:
135
+
136
+ ```bash
137
+ ragfly cloud chat ask "Compare the two contracts" --wait 60
138
+ ragfly cloud chat answer 2121
139
+ ```
140
+
141
+ ### Published corpora
142
+
143
+ ```bash
144
+ ragfly cloud destinations # what you can read
145
+ ragfly cloud answering-guide --module regulation --country CL # give it to your own model
146
+ ragfly cloud search "board quorum" --module regulation --country CL -o json
147
+ ragfly cloud chat ask "What quorum does a board need?" --module regulation --country CL
148
+ ```
149
+
150
+ ### Documents from a public URL, and a search kept as a collection
151
+
152
+ ```bash
153
+ ragfly cloud document ingest https://example.com/manual.pdf
154
+ ragfly cloud document ingest-status PROCESS_CODE
155
+ ragfly cloud collection from-search "lease contracts" --name "Leases"
156
+ ```
157
+
125
158
  Full reference: <https://api.ragfly.ai/docs>.
126
159
 
127
160
  > **Local operations** (`ragfly local scan/sync/daemon`) require the local file
@@ -26,6 +26,10 @@ ragfly login
26
26
  export RAGFLY_API_KEY=rf_xxxxxxxxxx
27
27
  ```
28
28
 
29
+ If your account has two-step verification, `ragfly login` asks for the code of your
30
+ authenticator app. An account that manages an organization needs it to use a session;
31
+ an API key does not.
32
+
29
33
  `cloud group` and `cloud api-key` manage a person's session and credentials: they
30
34
  need `ragfly login`, and the server refuses them for an API key.
31
35
 
@@ -60,16 +64,18 @@ ragfly
60
64
  ├── location list
61
65
  ├── group list | switch | clear (signed-in person)
62
66
  ├── api-key create | list | revoke (signed-in person)
63
- ├── document list | show | edges
64
- ├── collection list | show | compose | read | refresh | save
67
+ ├── document list | show | edges | ingest | ingest-status
68
+ ├── collection list | show | from-search | compose | read | refresh | save
65
69
  ├── queue show | runs
66
70
  ├── skill list | show | run
67
71
  ├── catalog
68
72
  ├── document-type list
69
73
  ├── characteristic list
70
74
  ├── function show
75
+ ├── destinations
76
+ ├── answering-guide
71
77
  ├── search
72
- ├── chat ask
78
+ ├── chat ask | answer
73
79
  ├── agent context | tool
74
80
  ├── usage
75
81
  ├── conversation list | delete
@@ -101,6 +107,33 @@ ragfly cloud search "statements" --filter @filter.json --collection 12
101
107
  ragfly cloud chat ask "How do I release the workspace of my key?" --mode help
102
108
  ```
103
109
 
110
+ ### Long answers
111
+
112
+ `cloud chat ask` waits up to 300 seconds for an answer (`--wait`). If it does not arrive
113
+ in time, the exit code is 2 and you read it later, at no extra quota:
114
+
115
+ ```bash
116
+ ragfly cloud chat ask "Compare the two contracts" --wait 60
117
+ ragfly cloud chat answer 2121
118
+ ```
119
+
120
+ ### Published corpora
121
+
122
+ ```bash
123
+ ragfly cloud destinations # what you can read
124
+ ragfly cloud answering-guide --module regulation --country CL # give it to your own model
125
+ ragfly cloud search "board quorum" --module regulation --country CL -o json
126
+ ragfly cloud chat ask "What quorum does a board need?" --module regulation --country CL
127
+ ```
128
+
129
+ ### Documents from a public URL, and a search kept as a collection
130
+
131
+ ```bash
132
+ ragfly cloud document ingest https://example.com/manual.pdf
133
+ ragfly cloud document ingest-status PROCESS_CODE
134
+ ragfly cloud collection from-search "lease contracts" --name "Leases"
135
+ ```
136
+
104
137
  Full reference: <https://api.ragfly.ai/docs>.
105
138
 
106
139
  > **Local operations** (`ragfly local scan/sync/daemon`) require the local file
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ragfly-cli"
7
- version = "2.1.0"
7
+ version = "2.2.0"
8
8
  description = "RAGfly CLI — operate RAGfly from the terminal and CI (login + cloud API). Lightweight, no desktop dependencies."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -0,0 +1 @@
1
+ __version__ = "2.2.0"
@@ -11,12 +11,16 @@ Commands:
11
11
  ragfly cloud me
12
12
  ragfly cloud group list | switch | clear (signed-in person only)
13
13
  ragfly cloud api-key create | list | revoke (signed-in person only)
14
- ragfly cloud document list | show | edges
15
- ragfly cloud workspace set
16
- ragfly cloud collection list | show | compose | read | refresh | save
14
+ ragfly cloud document list | show | edges | ingest | ingest-status
15
+ ragfly cloud workspace set | unset
16
+ ragfly cloud area set | list
17
+ ragfly cloud location list
18
+ ragfly cloud collection list | show | from-search | compose | read | refresh | save
17
19
  ragfly cloud queue show | runs
18
20
  ragfly cloud skill list | show | run
19
- ragfly cloud catalog | function show | search | chat ask
21
+ ragfly cloud catalog | document-type list | characteristic list | function show
22
+ ragfly cloud destinations | answering-guide | search
23
+ ragfly cloud chat ask | answer
20
24
  ragfly cloud agent context | tool
21
25
  ragfly cloud usage
22
26
  ragfly cloud conversation list | delete
@@ -33,6 +37,8 @@ placed before the subcommand: `ragfly -v cloud document list`.
33
37
 
34
38
  import json
35
39
  import sys
40
+ import time
41
+ import uuid
36
42
  from pathlib import Path
37
43
  from urllib.parse import quote
38
44
 
@@ -131,13 +137,17 @@ def _json_argument(value: str, option: str) -> dict:
131
137
  return parsed
132
138
 
133
139
 
134
- def _v1(method: str, path: str, *, params: dict | None = None, body=None):
140
+ # A search over a large corpus may take the server up to 180 s: give up after it, not before.
141
+ SEARCH_TIMEOUT = 190
142
+
143
+
144
+ def _v1(method: str, path: str, *, params: dict | None = None, body=None, timeout: int | None = None):
135
145
  """Call a `/v1` route with uniform error handling (exits on failure)."""
136
146
  from .cloud_commands import cloud_request
137
147
  from .oop import CliCommand
138
148
 
139
149
  clean = {k: v for k, v in (params or {}).items() if v is not None} or None
140
- return CliCommand().protegido(cloud_request, method, path, params=clean, body=body)
150
+ return CliCommand().protegido(cloud_request, method, path, params=clean, body=body, timeout=timeout)
141
151
 
142
152
 
143
153
  def _segment(value) -> str:
@@ -159,7 +169,8 @@ def app(verbose: bool):
159
169
  @app.command()
160
170
  @click.option("--email", "-e", default=None, help="Email (for non-interactive use)")
161
171
  @click.option("--password-stdin", is_flag=True, help="Read the password from stdin")
162
- def login(email: str | None, password_stdin: bool):
172
+ @click.option("--code", default=None, help="Two-step verification code (asked for when the account needs it)")
173
+ def login(email: str | None, password_stdin: bool, code: str | None):
163
174
  """Authenticate a person against the cloud and store the session."""
164
175
  from .cloud_commands import CloudError, login as _login
165
176
 
@@ -171,7 +182,7 @@ def login(email: str | None, password_stdin: bool):
171
182
  console.print()
172
183
  console.print("[dim] Connecting...[/dim]", end="")
173
184
  try:
174
- data = _login(email, password)
185
+ data = _login(email, password, lambda: code or click.prompt("\n Verification code"), intentos=1 if code else 3)
175
186
  except CloudError as e:
176
187
  console.print()
177
188
  err_console.print(f"[red]✗ {e}[/red]")
@@ -184,6 +195,10 @@ def login(email: str | None, password_stdin: bool):
184
195
  try:
185
196
  from .cloud_commands import cloud_request
186
197
  sesion = cloud_request("GET", "/v1/session", token=data.get("access_token") or data.get("token"), timeout=15) or {}
198
+ except CloudError as e:
199
+ sesion = {}
200
+ if e.exit_code == 1: # the server refuses this session: say so now, not at the next command
201
+ err_console.print(f"⚠ {e}", style="yellow", markup=False)
187
202
  except Exception:
188
203
  sesion = {}
189
204
  console.print(f" Active group: {sesion.get('active_group') or '—'}")
@@ -500,6 +515,47 @@ def cloud_document_edges(document_code: str, neighbor_limit: int):
500
515
  _emit_json(_v1("GET", f"/v1/documents/{_segment(document_code)}/edges", params={"neighbor_limit": neighbor_limit}))
501
516
 
502
517
 
518
+ INGESTION_FIELDS = [("Process", "process_code"), ("Status", "status"), ("Document", "document_code"), ("Error", "error")]
519
+
520
+
521
+ def _show_ingestion(data: dict, output: str) -> None:
522
+ _show(data, output, "Public URL ingestion", INGESTION_FIELDS)
523
+ if data.get("status") == "ERROR":
524
+ raise SystemExit(2)
525
+
526
+
527
+ @cloud_document.command("ingest")
528
+ @click.argument("url")
529
+ @click.option("--workspace", default=None, help="Target workspace; it must be the active one")
530
+ @click.option("--idempotency-key", default=None,
531
+ help="Repeat a key to get the same ingestion back; use a new one to refresh the URL. Default: a new key")
532
+ @click.option("-o", "--output", type=OUTPUT_TABLE, default="table")
533
+ def cloud_document_ingest(url: str, workspace: str | None, idempotency_key: str | None, output: str):
534
+ """Download and ingest one document that anyone can open at its public HTTPS URL.
535
+
536
+ It declares the document public for its AI preparation; the indexed copy stays in your workspace. The URL is
537
+ not refreshed on its own. Needs document upload permission."""
538
+ key = (idempotency_key or "").strip() or str(uuid.uuid4())
539
+ if not idempotency_key:
540
+ # Before the request: if the connection drops, the same key repeats it without ingesting twice.
541
+ click.echo(f"Idempotency key: {key}", err=True)
542
+ body = {"url": url, "idempotency_key": key}
543
+ if workspace:
544
+ body["workspace_code"] = workspace
545
+ data = _v1("POST", "/v1/documents/public-url", body=body)
546
+ _show_ingestion(data, output)
547
+ if output == "table" and data.get("status") in ("PENDING", "IN_PROGRESS"):
548
+ click.echo(f"Track it: ragfly cloud document ingest-status {data.get('process_code')}", err=True)
549
+
550
+
551
+ @cloud_document.command("ingest-status")
552
+ @click.argument("process_code")
553
+ @click.option("-o", "--output", type=OUTPUT_TABLE, default="table")
554
+ def cloud_document_ingest_status(process_code: str, output: str):
555
+ """Status of an earlier `document ingest`, without fetching the URL again."""
556
+ _show_ingestion(_v1("GET", f"/v1/documents/public-url/{_segment(process_code)}"), output)
557
+
558
+
503
559
  # ── cloud collection ──────────────────────────────────────────────────────────────
504
560
 
505
561
  @cloud.group("collection")
@@ -535,6 +591,41 @@ def cloud_collection_show(collection_id: int, document_limit: int, output: str):
535
591
  _table("Documents", data.get("documents") or [], [("Code", "code"), ("Name", "name"), ("Status", "status")])
536
592
 
537
593
 
594
+ @cloud_collection.command("from-search")
595
+ @click.argument("query", nargs=-1, required=True)
596
+ @click.option("--name", default=None, help="Name of the collection (generated when empty)")
597
+ @click.option("--max-documents", type=click.IntRange(1, 200), default=100, show_default=True)
598
+ @click.option("--type", "collection_type", type=click.Choice(["TEMPORARY", "SAVED"]), default="SAVED", show_default=True)
599
+ @click.option("--collection", "collection_id", type=int, default=None, help="Search only inside this collection")
600
+ @click.option("--filter", "filter_json", default=None, help="Structured filter as JSON, @file or - (as in `cloud search`)")
601
+ @click.option("--location", "location_code", default=None, help="Search only this visible folder and its subfolders")
602
+ @click.option("-o", "--output", type=OUTPUT_TABLE, default="table")
603
+ def cloud_collection_from_search(query: tuple[str, ...], name: str | None, max_documents: int, collection_type: str,
604
+ collection_id: int | None, filter_json: str | None, location_code: str | None,
605
+ output: str):
606
+ """Run a search over your documents and keep its candidates as a new collection of the active workspace."""
607
+ text = " ".join(query).strip()
608
+ if not text:
609
+ raise click.UsageError("The query cannot be empty.")
610
+ body = {"query": text, "max_documents": max_documents, "collection_type": collection_type}
611
+ if name:
612
+ body["name"] = name
613
+ if collection_id is not None:
614
+ body["collection_id"] = collection_id
615
+ if filter_json:
616
+ body["filter"] = _json_argument(filter_json, "--filter")
617
+ if location_code:
618
+ body["location_code"] = location_code
619
+ data = _v1("POST", "/v1/collections/from-search", body=body, timeout=SEARCH_TIMEOUT)
620
+ if output == "json":
621
+ _emit_json(data)
622
+ elif not data.get("created"):
623
+ console.print("[yellow]No results: no collection was created.[/yellow]")
624
+ else:
625
+ _fields("New collection", data.get("collection") or {}, [
626
+ ("ID", "collection_id"), ("Name", "name"), ("Type", "type"), ("Documents", "total_documents")])
627
+
628
+
538
629
  @cloud_collection.command("compose")
539
630
  @click.argument("operation", type=click.Choice(["union", "intersection", "difference", "symmetric_difference"]))
540
631
  @click.argument("collection_a", type=int)
@@ -722,6 +813,75 @@ def cloud_function_show(function_code: str, output: str):
722
813
  _table("Operations", data.get("operations") or [], [("Code", "code"), ("Kind", "kind")])
723
814
 
724
815
 
816
+ def _destination(module: str | None, country: str | None, workspace: str | None, area: str | None) -> dict | None:
817
+ """`destination` of /v1 from the CLI options. Only `--module regulation` reads a published corpus."""
818
+ if not module or module == "private":
819
+ if country or area:
820
+ raise click.UsageError("--country and --area need --module regulation.")
821
+ return None
822
+ if not country:
823
+ raise click.UsageError("--module regulation needs --country, e.g. --country CL.")
824
+ if area and not workspace:
825
+ raise click.UsageError("--area needs --workspace.")
826
+ destino = {"module": "regulation", "country": country.upper()}
827
+ if workspace:
828
+ destino["workspace_code"] = workspace
829
+ if area:
830
+ destino["area_code"] = area
831
+ return destino
832
+
833
+
834
+ _DESTINATION_OPTIONS = [
835
+ click.option("--module", type=click.Choice(["private", "regulation"]), default=None,
836
+ help="regulation: read a published corpus (see `ragfly cloud destinations`) instead of your documents"),
837
+ click.option("--country", default=None, help="Country of the published corpus, ISO alpha-2 (with --module regulation)"),
838
+ click.option("--area", default=None, help="Supervisor within --workspace (with --module regulation)"),
839
+ ]
840
+
841
+
842
+ def _destination_options(func):
843
+ for opcion in reversed(_DESTINATION_OPTIONS):
844
+ func = opcion(func)
845
+ return func
846
+
847
+
848
+ @cloud.command("destinations")
849
+ @click.option("-o", "--output", type=OUTPUT_TABLE, default="table")
850
+ def cloud_destinations(output: str):
851
+ """Published corpora you can read with --module regulation, and whether your organization may."""
852
+ data = _v1("GET", "/v1/destinations")
853
+ if output == "json":
854
+ _emit_json(data)
855
+ return
856
+ rows = [{"country": d.get("country"), "module": d.get("module"),
857
+ "workspaces": ", ".join(w.get("workspace_code") or "" for w in d.get("workspaces") or []),
858
+ "enabled": "yes" if d.get("enabled") else "no"} for d in data.get("destinations") or []]
859
+ if not rows:
860
+ console.print("[yellow]No published corpora.[/yellow]")
861
+ return
862
+ _table("Destinations", rows, [("Country", "country"), ("Module", "module"), ("Workspaces", "workspaces"),
863
+ ("Enabled", "enabled")])
864
+
865
+
866
+ @cloud.command("answering-guide")
867
+ @click.option("--module", type=click.Choice(["private", "regulation"]), default=None,
868
+ help="regulation: a published corpus; private: your own documents. Default: what your searches read")
869
+ @click.option("--country", default=None, help="Country of the published corpus, ISO alpha-2 (with --module regulation)")
870
+ @click.option("--workspace", default=None, help="Workspace whose instructions to include (default: the active one)")
871
+ @click.option("-o", "--output", type=click.Choice(["text", "json"]), default="text")
872
+ def cloud_answering_guide(module: str | None, country: str | None, workspace: str | None, output: str):
873
+ """How to answer from a corpus with your own model after `cloud search`.
874
+
875
+ Give it to your agent once per workspace, before its first answer."""
876
+ destino = _destination(module, country, workspace, None)
877
+ params = destino or {"module": module, "workspace_code": workspace}
878
+ data = _v1("GET", "/v1/answering-guide", params=params)
879
+ if output == "json":
880
+ _emit_json(data)
881
+ else:
882
+ click.echo(data.get("guide") or "")
883
+
884
+
725
885
  @cloud.command("search")
726
886
  @click.argument("query", nargs=-1, required=True)
727
887
  @click.option("--limit", type=int, default=10, show_default=True)
@@ -732,14 +892,21 @@ def cloud_function_show(function_code: str, output: str):
732
892
  help="Structured filter as JSON, @file or - (document_types, attributes, characteristics)")
733
893
  @click.option("--location", "location_code", default=None,
734
894
  help="Search only this visible folder and its subfolders (this request only)")
895
+ @_destination_options
735
896
  @click.option("-o", "--output", type=OUTPUT_TABLE, default="table")
736
897
  def cloud_search(query: tuple[str, ...], limit: int, min_similarity: float, workspace: str | None,
737
- collection_id: int | None, filter_json: str | None, location_code: str | None, output: str):
738
- """Semantic search over the group's vectorized documents."""
898
+ collection_id: int | None, filter_json: str | None, location_code: str | None,
899
+ module: str | None, country: str | None, area: str | None, output: str):
900
+ """Semantic search over the group's vectorized documents, or a published corpus with --module regulation."""
739
901
  text = " ".join(query).strip()
740
902
  if not text:
741
903
  raise click.UsageError("The query cannot be empty.")
742
904
  body = {"query": text, "limit": limit, "min_similarity": min_similarity}
905
+ destino = _destination(module, country, workspace, area)
906
+ if destino:
907
+ # With a destination, --workspace is a regulatory area of that country, not one of yours.
908
+ body["destination"] = destino
909
+ workspace = None
743
910
  if workspace:
744
911
  body["workspace_code"] = workspace
745
912
  if collection_id is not None:
@@ -748,7 +915,7 @@ def cloud_search(query: tuple[str, ...], limit: int, min_similarity: float, work
748
915
  body["filter"] = _json_argument(filter_json, "--filter")
749
916
  if location_code:
750
917
  body["location_code"] = location_code
751
- data = _v1("POST", "/v1/documents/search", body=body)
918
+ data = _v1("POST", "/v1/documents/search", body=body, timeout=SEARCH_TIMEOUT)
752
919
  if output == "json":
753
920
  _emit_json(data)
754
921
  return
@@ -756,8 +923,13 @@ def cloud_search(query: tuple[str, ...], limit: int, min_similarity: float, work
756
923
  if not rows:
757
924
  console.print("[yellow]No results.[/yellow]")
758
925
  return
759
- _table(f"Search: {text[:60]}", rows, [("Code", "code"), ("Document", "name"),
760
- ("Similarity", "max_similarity"), ("Fragment", "fragment")])
926
+ columns = [("Code", "code"), ("Document", "name"), ("Similarity", "max_similarity"), ("Fragment", "fragment")]
927
+ if any(row.get("validity") for row in rows):
928
+ # A published corpus also returns texts that are no longer in force: the table has to say which.
929
+ for row in rows:
930
+ row["validity_status"] = (row.get("validity") or {}).get("status")
931
+ columns.insert(2, ("Validity", "validity_status"))
932
+ _table(f"Search: {text[:60]}", rows, columns)
761
933
 
762
934
 
763
935
  @cloud.group("chat")
@@ -765,6 +937,63 @@ def cloud_chat():
765
937
  """Ask your documents (RAG)."""
766
938
 
767
939
 
940
+ ANSWER_POLL_SECONDS = 3
941
+ WAIT_OPTION = click.option(
942
+ "--wait", "wait", type=click.IntRange(min=0), default=300, show_default=True, metavar="SECONDS",
943
+ help="How long to wait for an answer that is still being generated. 0: do not wait")
944
+
945
+
946
+ def _wait_for_answer(data: dict, wait: int) -> dict:
947
+ """Read the answer of a conversation until it stops being IN_PROGRESS or `wait` seconds pass.
948
+
949
+ `POST /v1/ask` holds the connection for about 25 s and then answers IN_PROGRESS; the answer keeps being
950
+ generated and reading it does not use quota again. A read that fails on the network is tried again."""
951
+ from .cloud_commands import CloudError, cloud_request
952
+
953
+ conversation_id = data.get("conversation_id")
954
+ if data.get("status") != "IN_PROGRESS" or not wait:
955
+ return data
956
+ click.echo(f"Still being generated (conversation #{conversation_id}); waiting up to {wait} s…", err=True)
957
+ deadline = time.monotonic() + wait
958
+ try:
959
+ while data.get("status") == "IN_PROGRESS":
960
+ remaining = deadline - time.monotonic()
961
+ if remaining <= 0:
962
+ break
963
+ time.sleep(min(ANSWER_POLL_SECONDS, remaining))
964
+ try:
965
+ data = cloud_request("GET", f"/v1/conversations/{conversation_id}/answer") or data
966
+ except CloudError as exc:
967
+ if exc.exit_code == 1: # the server refused it: asking again will not change that
968
+ err_console.print(f"✗ {exc}", style="red", markup=False)
969
+ raise SystemExit(1)
970
+ except KeyboardInterrupt:
971
+ click.echo(f"\nRead it later: ragfly cloud chat answer {conversation_id}", err=True)
972
+ raise SystemExit(130)
973
+ return data
974
+
975
+
976
+ def _show_answer(data: dict, output: str, wait: int) -> None:
977
+ """Print an answer. Exit code 2 when there is none: it failed, or it did not arrive within --wait."""
978
+ conversation_id, status = data.get("conversation_id"), data.get("status")
979
+ if output == "json":
980
+ _emit_json(data)
981
+ elif data.get("answer"):
982
+ click.echo(data["answer"])
983
+ console.print(f"[dim]Conversation #{conversation_id}[/dim]")
984
+ if status == "IN_PROGRESS":
985
+ click.echo(f"The answer is still being generated. Read it later, at no extra quota: "
986
+ f"ragfly cloud chat answer {conversation_id}", err=True)
987
+ if wait:
988
+ raise SystemExit(2)
989
+ elif status == "FAILED":
990
+ click.echo(f"The answer of conversation #{conversation_id} was not generated. Ask again.", err=True)
991
+ raise SystemExit(2)
992
+ elif status == "NO_QUESTION":
993
+ click.echo(f"Conversation #{conversation_id} has no question yet.", err=True)
994
+ raise SystemExit(1)
995
+
996
+
768
997
  @cloud_chat.command("ask")
769
998
  @click.argument("message", nargs=-1, required=True)
770
999
  @click.option("--function", "function_code", default="CHAT-USER", show_default=True, help="Chat function code")
@@ -773,26 +1002,42 @@ def cloud_chat():
773
1002
  help="help: answer questions about RAGfly itself (how to use or integrate it), without links to web screens")
774
1003
  @click.option("--location", "location_code", default=None,
775
1004
  help="Answer only from this visible folder and its subfolders (this request only)")
1005
+ @click.option("--workspace", default=None, help="Regulatory area of the country (with --module regulation)")
1006
+ @_destination_options
1007
+ @WAIT_OPTION
776
1008
  @click.option("-o", "--output", type=click.Choice(["text", "json"]), default="text")
777
1009
  def cloud_chat_ask(message: tuple[str, ...], function_code: str, conversation_id: int | None, mode: str | None,
778
- location_code: str | None, output: str):
779
- """Ask a question. Creates a conversation unless --conversation is given."""
1010
+ location_code: str | None, workspace: str | None, module: str | None, country: str | None,
1011
+ area: str | None, wait: int, output: str):
1012
+ """Ask a question. Creates a conversation unless --conversation is given. With --module regulation the
1013
+ answer comes from that country's published corpus and the conversation stays bound to it.
1014
+
1015
+ A long answer is waited for (--wait). If it does not arrive in time, read it with `chat answer`."""
780
1016
  question = " ".join(message).strip()
781
1017
  if not question:
782
1018
  raise click.UsageError("The message cannot be empty.")
1019
+ if workspace and module != "regulation":
1020
+ raise click.UsageError("--workspace on ask needs --module regulation.")
783
1021
  body = {"question": question, "function_code": function_code}
1022
+ destino = _destination(module, country, workspace, area)
1023
+ if destino:
1024
+ body["destination"] = destino
784
1025
  if conversation_id:
785
1026
  body["conversation_id"] = conversation_id
786
1027
  if mode:
787
1028
  body["mode"] = mode
788
1029
  if location_code:
789
1030
  body["location_code"] = location_code
790
- data = _v1("POST", "/v1/ask", body=body)
791
- if output == "json":
792
- _emit_json(data)
793
- return
794
- click.echo(data.get("answer", ""))
795
- console.print(f"[dim]Conversation #{data.get('conversation_id')}[/dim]")
1031
+ _show_answer(_wait_for_answer(_v1("POST", "/v1/ask", body=body), wait), output, wait)
1032
+
1033
+
1034
+ @cloud_chat.command("answer")
1035
+ @click.argument("conversation_id", type=int)
1036
+ @WAIT_OPTION
1037
+ @click.option("-o", "--output", type=click.Choice(["text", "json"]), default="text")
1038
+ def cloud_chat_answer(conversation_id: int, wait: int, output: str):
1039
+ """Read the answer to the last question of a conversation. It does not use quota again."""
1040
+ _show_answer(_wait_for_answer(_v1("GET", f"/v1/conversations/{conversation_id}/answer"), wait), output, wait)
796
1041
 
797
1042
 
798
1043
  # ── cloud agent ──────────────────────────────────────────────────────────────
@@ -16,7 +16,7 @@ from __future__ import annotations
16
16
  import json
17
17
  import os
18
18
  from pathlib import Path
19
- from typing import Any
19
+ from typing import Any, Callable
20
20
 
21
21
  import httpx
22
22
 
@@ -37,9 +37,10 @@ TOKEN_ENV_VARS = ("RAGFLY_API_KEY", "RAGFLY_TOKEN")
37
37
  class CloudError(Exception):
38
38
  """Network or cloud API error."""
39
39
 
40
- def __init__(self, mensaje: str, exit_code: int = 2):
40
+ def __init__(self, mensaje: str, exit_code: int = 2, status: int | None = None):
41
41
  super().__init__(mensaje)
42
42
  self.exit_code = exit_code
43
+ self.status = status # HTTP status, when the server answered
43
44
 
44
45
 
45
46
  # ── Auth ─────────────────────────────────────────────────────────────────────
@@ -151,8 +152,15 @@ def _mensaje_de_error(response: httpx.Response) -> str:
151
152
  def _manejar_http_error(e: httpx.HTTPStatusError) -> None:
152
153
  status = e.response.status_code
153
154
  mensaje = _mensaje_de_error(e.response)
155
+ if e.response.headers.get("X-MFA-Enrollment-Required"):
156
+ raise CloudError(
157
+ "This account manages an organization, so its session needs two-step verification. Turn it on in your "
158
+ "profile at app.ragfly.ai and run `ragfly login` again, or use an API key (RAGFLY_API_KEY).", exit_code=1)
159
+ if e.response.headers.get("X-MFA-Required"):
160
+ raise CloudError("This session has not passed two-step verification. Run `ragfly login` again.", exit_code=1)
154
161
  if status == 401:
155
- raise CloudError(f"Not authenticated: {mensaje}. Run `ragfly login` or check RAGFLY_API_KEY.", exit_code=1)
162
+ raise CloudError(f"Not authenticated: {mensaje}. Run `ragfly login` or check RAGFLY_API_KEY.", exit_code=1,
163
+ status=status)
156
164
  if status == 403:
157
165
  raise CloudError(f"Forbidden: {mensaje}", exit_code=1)
158
166
  if status == 404:
@@ -164,8 +172,30 @@ def _manejar_http_error(e: httpx.HTTPStatusError) -> None:
164
172
 
165
173
  # ── Login ────────────────────────────────────────────────────────────────────
166
174
 
167
- def login(email: str, password: str) -> dict:
168
- """Authenticate a person against /auth/login and store the session."""
175
+ def _verificar_dos_pasos(data: dict, pedir_codigo: Callable[[], str], intentos: int) -> dict:
176
+ """Trade the first-step token for a verified session: challenge + the code of the authenticator app.
177
+ Until then the server refuses that token everywhere else, so it is never stored."""
178
+ token = data.get("access_token") or ""
179
+ while True:
180
+ codigo = pedir_codigo().replace(" ", "")
181
+ intentos -= 1
182
+ try:
183
+ desafio = cloud_request("POST", "/auth/mfa/challenge", body={"factor_id": data.get("factor_id")}, token=token)
184
+ return cloud_request("POST", "/auth/mfa/verify", token=token, body={
185
+ "factor_id": desafio["factor_id"], "challenge_id": desafio["challenge_id"], "code": codigo})
186
+ except CloudError as e:
187
+ if e.status == 401 and intentos > 0:
188
+ continue
189
+ if e.status == 401:
190
+ raise CloudError("The verification code is not valid or has expired.", exit_code=1)
191
+ raise
192
+
193
+
194
+ def login(email: str, password: str, pedir_codigo: Callable[[], str] | None = None, intentos: int = 1) -> dict:
195
+ """Authenticate a person against /auth/login and store the session.
196
+
197
+ `pedir_codigo` returns the code of the authenticator app; it is called only when the account has two-step
198
+ verification, up to `intentos` times."""
169
199
  try:
170
200
  r = httpx.post(f"{CLOUD_URL}/auth/login", json={"email": email, "password": password},
171
201
  headers=CLIENT_HEADER, timeout=30)
@@ -181,6 +211,11 @@ def login(email: str, password: str) -> dict:
181
211
  token = data.get("access_token") or data.get("token", "")
182
212
  if not token:
183
213
  raise CloudError("The server did not return a token.", exit_code=2)
214
+ if data.get("mfa_required"):
215
+ if pedir_codigo is None:
216
+ raise CloudError("This account has two-step verification: a code is required.", exit_code=1)
217
+ data = _verificar_dos_pasos(data, pedir_codigo, intentos)
218
+ token = data["access_token"]
184
219
  try:
185
220
  guardar_credenciales(token, email, data.get("expires_in", 3600))
186
221
  except keyring_store.KeyringStoreError:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ragfly-cli
3
- Version: 2.1.0
3
+ Version: 2.2.0
4
4
  Summary: RAGfly CLI — operate RAGfly from the terminal and CI (login + cloud API). Lightweight, no desktop dependencies.
5
5
  Author: CAB Ltda
6
6
  License: MIT
@@ -47,6 +47,10 @@ ragfly login
47
47
  export RAGFLY_API_KEY=rf_xxxxxxxxxx
48
48
  ```
49
49
 
50
+ If your account has two-step verification, `ragfly login` asks for the code of your
51
+ authenticator app. An account that manages an organization needs it to use a session;
52
+ an API key does not.
53
+
50
54
  `cloud group` and `cloud api-key` manage a person's session and credentials: they
51
55
  need `ragfly login`, and the server refuses them for an API key.
52
56
 
@@ -81,16 +85,18 @@ ragfly
81
85
  ├── location list
82
86
  ├── group list | switch | clear (signed-in person)
83
87
  ├── api-key create | list | revoke (signed-in person)
84
- ├── document list | show | edges
85
- ├── collection list | show | compose | read | refresh | save
88
+ ├── document list | show | edges | ingest | ingest-status
89
+ ├── collection list | show | from-search | compose | read | refresh | save
86
90
  ├── queue show | runs
87
91
  ├── skill list | show | run
88
92
  ├── catalog
89
93
  ├── document-type list
90
94
  ├── characteristic list
91
95
  ├── function show
96
+ ├── destinations
97
+ ├── answering-guide
92
98
  ├── search
93
- ├── chat ask
99
+ ├── chat ask | answer
94
100
  ├── agent context | tool
95
101
  ├── usage
96
102
  ├── conversation list | delete
@@ -122,6 +128,33 @@ ragfly cloud search "statements" --filter @filter.json --collection 12
122
128
  ragfly cloud chat ask "How do I release the workspace of my key?" --mode help
123
129
  ```
124
130
 
131
+ ### Long answers
132
+
133
+ `cloud chat ask` waits up to 300 seconds for an answer (`--wait`). If it does not arrive
134
+ in time, the exit code is 2 and you read it later, at no extra quota:
135
+
136
+ ```bash
137
+ ragfly cloud chat ask "Compare the two contracts" --wait 60
138
+ ragfly cloud chat answer 2121
139
+ ```
140
+
141
+ ### Published corpora
142
+
143
+ ```bash
144
+ ragfly cloud destinations # what you can read
145
+ ragfly cloud answering-guide --module regulation --country CL # give it to your own model
146
+ ragfly cloud search "board quorum" --module regulation --country CL -o json
147
+ ragfly cloud chat ask "What quorum does a board need?" --module regulation --country CL
148
+ ```
149
+
150
+ ### Documents from a public URL, and a search kept as a collection
151
+
152
+ ```bash
153
+ ragfly cloud document ingest https://example.com/manual.pdf
154
+ ragfly cloud document ingest-status PROCESS_CODE
155
+ ragfly cloud collection from-search "lease contracts" --name "Leases"
156
+ ```
157
+
125
158
  Full reference: <https://api.ragfly.ai/docs>.
126
159
 
127
160
  > **Local operations** (`ragfly local scan/sync/daemon`) require the local file
@@ -22,5 +22,8 @@ ragfly_cli/oop/cli_command.py
22
22
  ragfly_cli/oop/http_client.py
23
23
  tests/test_agent_context_cli.py
24
24
  tests/test_api_key_group_override.py
25
+ tests/test_idioma_errores.py
25
26
  tests/test_login_summary_cli.py
27
+ tests/test_login_two_step_cli.py
28
+ tests/test_long_answers_and_ingestion_cli.py
26
29
  tests/test_surface_parity_cli.py
@@ -0,0 +1,41 @@
1
+ """CLI publica errores propios en inglés y conserva sus códigos de salida."""
2
+ import httpx
3
+ import pytest
4
+
5
+ from ragfly_cli import grupo_activo
6
+ from ragfly_cli.cloud_commands import CloudError
7
+ from ragfly_cli.oop.cli_command import CliCommand
8
+ from ragfly_cli.oop.http_client import CloudHttpClient
9
+
10
+
11
+ def test_archivo_de_configuracion_ausente(tmp_path, monkeypatch):
12
+ monkeypatch.setattr(grupo_activo, '_config_path', lambda: tmp_path / 'config.env')
13
+ with pytest.raises(FileNotFoundError, match='does not exist.*ragfly setup'):
14
+ grupo_activo.set_grupo_activo('GROUP')
15
+
16
+
17
+ def test_error_de_conexion_es_ingles_y_conserva_codigo(monkeypatch):
18
+ monkeypatch.setattr('ragfly_cli.oop.http_client._headers', lambda token: {})
19
+ def fallar(*args, **kwargs):
20
+ raise httpx.ConnectError('connection refused')
21
+ monkeypatch.setattr(httpx, 'request', fallar)
22
+ with pytest.raises(CloudError, match='Could not connect to the server') as exc:
23
+ CloudHttpClient().get('/v1/test')
24
+ assert exc.value.exit_code == 2
25
+
26
+
27
+ def test_interrupcion_y_error_inesperado_en_ingles(monkeypatch):
28
+ comando = CliCommand()
29
+ mensajes = []
30
+ monkeypatch.setattr(comando, 'aviso', mensajes.append)
31
+ monkeypatch.setattr(comando, 'error', mensajes.append)
32
+ def interrumpir():
33
+ raise KeyboardInterrupt
34
+ with pytest.raises(SystemExit) as exc:
35
+ comando.protegido(interrumpir)
36
+ assert exc.value.code == 130 and mensajes.pop() == 'Interrupted.'
37
+ def fallar():
38
+ raise ValueError('technical detail')
39
+ with pytest.raises(SystemExit) as exc:
40
+ comando.protegido(fallar)
41
+ assert exc.value.code == 2 and mensajes.pop() == 'Unexpected error: technical detail'
@@ -7,7 +7,7 @@ from ragfly_cli.cli import app
7
7
 
8
8
  def test_login_summary_reads_the_public_session(monkeypatch):
9
9
  internal = {"access_token": "jwt.a.b", "grupo_activo": "OLD-G", "entidad_activa": "OLD-E"}
10
- monkeypatch.setattr(cloud_commands, "login", lambda email, password: internal)
10
+ monkeypatch.setattr(cloud_commands, "login", lambda email, password, *_, **__: internal)
11
11
  calls = []
12
12
 
13
13
  def fake_request(method, path, params=None, body=None, token=None, timeout=None):
@@ -23,7 +23,7 @@ def test_login_summary_reads_the_public_session(monkeypatch):
23
23
 
24
24
 
25
25
  def test_login_summary_survives_an_unreachable_session(monkeypatch):
26
- monkeypatch.setattr(cloud_commands, "login", lambda email, password: {"access_token": "jwt.a.b"})
26
+ monkeypatch.setattr(cloud_commands, "login", lambda email, password, *_, **__: {"access_token": "jwt.a.b"})
27
27
 
28
28
  def failing(*args, **kwargs):
29
29
  raise cloud_commands.CloudError("down", exit_code=2)
@@ -0,0 +1,79 @@
1
+ """`ragfly login` on an account with two-step verification stores the verified session, never the first-step token."""
2
+ import httpx
3
+ import pytest
4
+ from click.testing import CliRunner
5
+
6
+ from ragfly_cli import cloud_commands
7
+ from ragfly_cli.cli import app
8
+
9
+
10
+ @pytest.fixture
11
+ def server(monkeypatch):
12
+ monkeypatch.setattr("ragfly_cli.config.get_config", lambda: type("C", (), {"codigo_grupo": ""})())
13
+
14
+ class Server:
15
+ good_code = "123456"
16
+ mfa = True
17
+ session = (200, {"active_group": "G1", "active_workspace": "W1"}, {})
18
+ calls: list = []
19
+ stored: list = []
20
+
21
+ Server.calls, Server.stored = [], []
22
+
23
+ def reply(method, url, status, payload, headers=None):
24
+ return httpx.Response(status, json=payload, headers=headers or {}, request=httpx.Request(method, url))
25
+
26
+ def post(url, **kwargs):
27
+ return reply("POST", url, 200, {"access_token": "first", "expires_in": 3600, "mfa_required": Server.mfa,
28
+ "factor_id": "F" if Server.mfa else None})
29
+
30
+ def request(method, url, **kwargs):
31
+ Server.calls.append((url.rsplit("/", 1)[1], kwargs["headers"]["Authorization"], kwargs.get("json")))
32
+ if url.endswith("/auth/mfa/challenge"):
33
+ return reply(method, url, 200, {"factor_id": "F", "challenge_id": "C"})
34
+ if url.endswith("/auth/mfa/verify"):
35
+ if kwargs["json"]["code"] != Server.good_code:
36
+ return reply(method, url, 401, {"detail": "invalid code"})
37
+ return reply(method, url, 200, {"access_token": "verified", "refresh_token": "r", "expires_in": 3600})
38
+ return reply(method, url, *Server.session)
39
+
40
+ monkeypatch.setattr(httpx, "post", post)
41
+ monkeypatch.setattr(httpx, "request", request)
42
+ monkeypatch.setattr(cloud_commands.keyring_store, "guardar", lambda token, email: Server.stored.append(token))
43
+ return Server
44
+
45
+
46
+ def login(*args, input="pw\n"):
47
+ return CliRunner().invoke(app, ["login", "--email", "a@b.c", "--password-stdin", *args], input=input)
48
+
49
+
50
+ def test_the_code_is_asked_for_and_the_verified_session_is_stored(server):
51
+ result = login(input="pw\n123 456\n")
52
+ assert result.exit_code == 0, result.output
53
+ assert server.stored == ["verified"] and "Active group: G1" in result.output
54
+ assert server.calls[1] == ("verify", "Bearer first", {"factor_id": "F", "challenge_id": "C", "code": "123456"})
55
+ assert server.calls[2][:2] == ("session", "Bearer verified")
56
+
57
+
58
+ def test_a_wrong_code_can_be_typed_again(server):
59
+ assert login(input="pw\n000000\n123456\n").exit_code == 0
60
+ assert server.stored == ["verified"]
61
+
62
+
63
+ def test_a_wrong_code_option_fails_and_stores_nothing(server):
64
+ result = login("--code", "000000")
65
+ assert result.exit_code == 1 and "not valid or has expired" in result.output and server.stored == []
66
+
67
+
68
+ def test_an_account_without_two_step_is_not_asked_for_a_code(server):
69
+ server.mfa = False
70
+ assert login().exit_code == 0
71
+ assert server.stored == ["first"] and [c[0] for c in server.calls] == ["session"]
72
+
73
+
74
+ def test_an_administrator_without_two_step_is_told_what_to_do(server):
75
+ server.mfa = False
76
+ server.session = (403, {"code": "FORBIDDEN", "message": "no"}, {"X-MFA-Enrollment-Required": "1"})
77
+ result = login()
78
+ output = " ".join(result.output.split()) # the console wraps long lines
79
+ assert "two-step verification" in output and "RAGFLY_API_KEY" in output
@@ -0,0 +1,154 @@
1
+ """Answers that outlive the request, the answering guide, public URL ingestion and collections from a search."""
2
+ import json
3
+
4
+ import httpx
5
+ import pytest
6
+ from click.testing import CliRunner
7
+
8
+ from ragfly_cli import cli
9
+ from ragfly_cli.cli import app
10
+
11
+ PENDING = {"conversation_id": 7, "status": "IN_PROGRESS", "answer": None}
12
+ DONE = {"conversation_id": 7, "status": "COMPLETED", "answer": "Article 59."}
13
+
14
+
15
+ @pytest.fixture
16
+ def wire(monkeypatch):
17
+ monkeypatch.setenv("RAGFLY_API_KEY", "rf_test")
18
+ monkeypatch.delenv("RAGFLY_TOKEN", raising=False)
19
+ monkeypatch.setattr("ragfly_cli.config.get_config", lambda: type("C", (), {"codigo_grupo": ""})())
20
+
21
+ class Wire:
22
+ replies: list = []
23
+ calls: list = []
24
+ now = 0.0
25
+
26
+ Wire.replies, Wire.calls, Wire.now = [], [], 0.0
27
+
28
+ def fake_request(method, url, **kwargs):
29
+ Wire.calls.append({"method": method, "url": url, **kwargs})
30
+ reply = Wire.replies.pop(0) if len(Wire.replies) > 1 else Wire.replies[0]
31
+ if isinstance(reply, Exception):
32
+ raise reply
33
+ status, payload = reply if isinstance(reply, tuple) else (200, reply)
34
+ return httpx.Response(status, json=payload, request=httpx.Request(method, url))
35
+
36
+ def sleep(seconds):
37
+ Wire.now += seconds
38
+
39
+ monkeypatch.setattr(httpx, "request", fake_request)
40
+ monkeypatch.setattr(cli.time, "sleep", sleep)
41
+ monkeypatch.setattr(cli.time, "monotonic", lambda: Wire.now)
42
+ return Wire
43
+
44
+
45
+ def run(*args):
46
+ return CliRunner().invoke(app, list(args))
47
+
48
+
49
+ def test_ask_waits_for_an_answer_that_is_still_being_generated(wire):
50
+ wire.replies = [PENDING, PENDING, DONE]
51
+ result = run("cloud", "chat", "ask", "which article?")
52
+ assert result.exit_code == 0, result.output
53
+ assert "Article 59." in result.stdout and "Still being generated" not in result.stdout
54
+ assert [c["method"] for c in wire.calls] == ["POST", "GET", "GET"]
55
+ assert wire.calls[1]["url"].endswith("/v1/conversations/7/answer")
56
+
57
+
58
+ def test_ask_json_prints_only_the_final_answer(wire):
59
+ wire.replies = [PENDING, DONE]
60
+ result = run("cloud", "chat", "ask", "q", "-o", "json")
61
+ assert result.exit_code == 0 and json.loads(result.stdout) == DONE
62
+
63
+
64
+ def test_a_dropped_read_is_tried_again_and_a_refused_one_is_not(wire):
65
+ wire.replies = [PENDING, httpx.ConnectError("down"), (502, {"message": "bad gateway"}), DONE]
66
+ assert run("cloud", "chat", "ask", "q").exit_code == 0
67
+ wire.replies, wire.calls[:] = [PENDING, (404, {"message": "gone"})], []
68
+ assert run("cloud", "chat", "ask", "q").exit_code == 1
69
+ assert len(wire.calls) == 2
70
+
71
+
72
+ def test_an_answer_that_does_not_arrive_in_time_says_how_to_read_it(wire):
73
+ wire.replies = [PENDING]
74
+ result = run("cloud", "chat", "ask", "q", "--wait", "10")
75
+ assert result.exit_code == 2 and wire.now == 10
76
+ assert result.stdout == "" and "ragfly cloud chat answer 7" in result.stderr
77
+
78
+
79
+ def test_wait_zero_returns_at_once_without_error(wire):
80
+ wire.replies = [PENDING]
81
+ result = run("cloud", "chat", "ask", "q", "--wait", "0", "-o", "json")
82
+ assert result.exit_code == 0 and json.loads(result.stdout) == PENDING and len(wire.calls) == 1
83
+
84
+
85
+ @pytest.mark.parametrize("status, code", [("FAILED", 2), ("NO_QUESTION", 1)])
86
+ def test_answer_reports_failures_with_an_exit_code(wire, status, code):
87
+ wire.replies = [{"conversation_id": 7, "status": status, "answer": None}]
88
+ result = run("cloud", "chat", "answer", "7")
89
+ assert result.exit_code == code and result.stdout == "" and "#7" in result.stderr
90
+
91
+
92
+ def test_a_server_without_status_still_prints_the_answer(wire):
93
+ wire.replies = [{"answer": "A", "conversation_id": 1}]
94
+ result = run("cloud", "chat", "ask", "q")
95
+ assert result.exit_code == 0 and result.stdout.startswith("A\n") and len(wire.calls) == 1
96
+
97
+
98
+ def test_answering_guide_prints_the_guide_of_the_corpus(wire):
99
+ wire.replies = [{"application": "REGfly", "guide": "Cite [the source].", "answer_check": "Check."}]
100
+ result = run("cloud", "answering-guide", "--module", "regulation", "--country", "cl", "--workspace", "W")
101
+ assert result.exit_code == 0 and result.stdout == "Cite [the source].\n"
102
+ assert wire.calls[0]["params"] == {"module": "regulation", "country": "CL", "workspace_code": "W"}
103
+ run("cloud", "answering-guide")
104
+ assert wire.calls[1]["params"] is None
105
+ run("cloud", "answering-guide", "--module", "private", "--workspace", "E1")
106
+ assert wire.calls[2]["params"] == {"module": "private", "workspace_code": "E1"}
107
+ assert run("cloud", "answering-guide", "--module", "regulation").exit_code != 0
108
+
109
+
110
+ def test_ingest_sends_a_key_and_shows_the_one_it_made_up(wire):
111
+ reply = {"process_code": "P-1", "status": "PENDING", "document_code": None}
112
+ wire.replies = [(202, reply)]
113
+ result = run("cloud", "document", "ingest", "https://example.com/a.pdf", "-o", "json")
114
+ assert result.exit_code == 0 and json.loads(result.stdout) == reply
115
+ body = wire.calls[0]["json"]
116
+ assert wire.calls[0]["url"].endswith("/v1/documents/public-url")
117
+ assert body["url"] == "https://example.com/a.pdf" and body["idempotency_key"] in result.stderr
118
+ run("cloud", "document", "ingest", "https://example.com/a.pdf", "--idempotency-key", "k1", "--workspace", "E1")
119
+ assert wire.calls[1]["json"] == {"url": "https://example.com/a.pdf", "idempotency_key": "k1", "workspace_code": "E1"}
120
+
121
+
122
+ def test_ingest_status_fails_when_the_ingestion_failed(wire):
123
+ wire.replies = [{"process_code": "P-1", "status": "ERROR", "error": "ROBOTS_DISALLOWED"}]
124
+ result = run("cloud", "document", "ingest-status", "P-1")
125
+ assert result.exit_code == 2 and "ROBOTS_DISALLOWED" in result.stdout
126
+ assert wire.calls[0]["url"].endswith("/v1/documents/public-url/P-1")
127
+
128
+
129
+ def test_collection_from_search(wire):
130
+ wire.replies = [{"created": True, "candidates": 3, "collection": {"collection_id": 9, "name": "N"}}]
131
+ result = run("cloud", "collection", "from-search", "lease", "contracts", "--name", "N", "--max-documents", "20",
132
+ "--location", "L1", "--filter", '{"document_types": ["T1"]}')
133
+ assert result.exit_code == 0 and "9" in result.stdout
134
+ assert wire.calls[0]["url"].endswith("/v1/collections/from-search")
135
+ assert wire.calls[0]["json"] == {"query": "lease contracts", "name": "N", "max_documents": 20,
136
+ "collection_type": "SAVED", "location_code": "L1",
137
+ "filter": {"document_types": ["T1"]}}
138
+ wire.replies = [{"created": False, "candidates": 0, "collection": None}]
139
+ assert "no collection was created" in run("cloud", "collection", "from-search", "x").stdout
140
+
141
+
142
+ def test_search_table_says_which_texts_are_not_in_force(wire):
143
+ wire.replies = [{"documents": [{"code": "1", "name": "Act", "validity": {"status": "VALID"}},
144
+ {"code": "2", "name": "Act 2017", "validity": {"status": "NOT_VALID"}}]}]
145
+ assert "NOT_VALID" in run("cloud", "search", "x").stdout
146
+ wire.replies = [{"documents": [{"code": "1", "name": "Mine"}]}]
147
+ assert "Validity" not in run("cloud", "search", "x").stdout
148
+
149
+
150
+ def test_searches_wait_longer_than_the_server(wire):
151
+ wire.replies = [{"documents": []}]
152
+ run("cloud", "search", "x")
153
+ run("cloud", "collection", "from-search", "x")
154
+ assert [c["timeout"] for c in wire.calls] == [190, 190]
@@ -126,3 +126,30 @@ def test_workspace_unset_calls_the_delete_route_and_matches_set_clear(wire):
126
126
  assert call["url"].endswith("/v1/session/active-workspace")
127
127
  assert not call.get("json")
128
128
  assert json.loads(result.output) == {"active_workspace": None}
129
+
130
+
131
+ def test_search_with_destination(wire):
132
+ wire.reply = httpx.Response(200, json={"documents": []})
133
+ result = CliRunner().invoke(app, ["cloud", "search", "board", "meetings", "--module", "regulation",
134
+ "--country", "cl", "--workspace", "MERCADO_VALORES", "-o", "json"])
135
+ assert result.exit_code == 0, result.output
136
+ assert wire.calls[0]["json"]["destination"] == {"module": "regulation", "country": "CL",
137
+ "workspace_code": "MERCADO_VALORES"}
138
+ assert "workspace_code" not in wire.calls[0]["json"]
139
+
140
+
141
+ def test_ask_with_destination_and_destinations(wire):
142
+ wire.reply = httpx.Response(200, json={"answer": "A", "conversation_id": 1})
143
+ result = CliRunner().invoke(app, ["cloud", "chat", "ask", "which", "rule?", "--module", "regulation", "--country", "CL"])
144
+ assert result.exit_code == 0, result.output
145
+ assert wire.calls[0]["json"]["destination"] == {"module": "regulation", "country": "CL"}
146
+ wire.reply = httpx.Response(200, json={"destinations": [{"country": "CL", "module": "regulation", "enabled": False,
147
+ "workspaces": [{"workspace_code": "MERCADO_VALORES"}]}]})
148
+ result = CliRunner().invoke(app, ["cloud", "destinations", "-o", "json"])
149
+ assert result.exit_code == 0, result.output
150
+ assert wire.calls[-1]["method"] == "GET" and wire.calls[-1]["url"].endswith("/v1/destinations")
151
+
152
+
153
+ def test_regulation_without_country_is_a_usage_error(wire):
154
+ result = CliRunner().invoke(app, ["cloud", "search", "x", "--module", "regulation"])
155
+ assert result.exit_code != 0 and "--country" in result.output
@@ -1 +0,0 @@
1
- __version__ = "2.1.0"
File without changes
File without changes