gotsimplified 0.1.0__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,520 @@
1
+ """Grouped functions: c.notes, c.files, c.datalake.
2
+
3
+ Each function sends one tool call to the server and returns the tool's text.
4
+
5
+ Preview rule: anything that changes or deletes data defaults to confirm=False, which
6
+ returns a preview and changes nothing. Pass confirm=True to apply it. Where the server has
7
+ no preview, the client itself requires confirm=True and says so.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import re
14
+ import zipfile
15
+ from typing import Optional, Sequence
16
+
17
+ from .ask import Scope
18
+ from .errors import GSError
19
+ from .validate import check_name
20
+
21
+
22
+ def _need_confirm(action: str) -> None:
23
+ raise GSError(f"{action} needs confirm=True. Nothing was changed.")
24
+
25
+
26
+ def _first_link(text: str) -> str:
27
+ """The first https link in a tool's reply, such as an export's download link."""
28
+ match = re.search(r"https://[^\s)>\]\"']+", text)
29
+ if not match:
30
+ raise GSError("The server did not return a download link for the result.")
31
+ return match.group(0)
32
+
33
+
34
+ class Notes(Scope):
35
+ """Notes: create, read, search, change and delete."""
36
+
37
+ def __init__(self, client):
38
+ super().__init__(client, "note", "notes")
39
+
40
+ def create(self, content: str, title: Optional[str] = None, tags: Optional[list] = None) -> str:
41
+ """Save a new note.
42
+
43
+ Args:
44
+ content: the note body (required).
45
+ title: optional title. Default "Untitled Note".
46
+ tags: optional list of tag strings.
47
+ Returns: the tool's confirmation text.
48
+ """
49
+ return self._client._call("note", "note_manage",
50
+ {"action": "create", "content": content, "title": title, "tags": tags})
51
+
52
+ def get(self, note_id: str) -> str:
53
+ """Read one note by its id, for example "note-a1b2c3d4"."""
54
+ return self._client._call("note", "note_query", {"note_id": note_id})
55
+
56
+ def search(self, query: str, limit: int = 10) -> str:
57
+ """Find notes whose title or content has these words.
58
+
59
+ Args:
60
+ query: keywords (required).
61
+ limit: most notes to return, 1 to 50. Default 10.
62
+ """
63
+ return self._client._call("note", "note_query", {"query": query, "limit": limit})
64
+
65
+ def list(self, limit: Optional[int] = None) -> str:
66
+ """List recent notes. Args: limit, 1 to 50 (server default 10 when omitted)."""
67
+ return self._client._call("note", "note_query", {"limit": limit})
68
+
69
+ def update(self, note_id: str, title: Optional[str] = None, content: Optional[str] = None,
70
+ tags: Optional[list] = None) -> str:
71
+ """Change a note. Give at least one of title, content or tags; other fields stay as they are."""
72
+ if title is None and content is None and tags is None:
73
+ raise GSError("Give at least one of title, content or tags to update.")
74
+ return self._client._call("note", "note_manage", {
75
+ "action": "update", "note_id": note_id, "title": title, "content": content, "tags": tags})
76
+
77
+ def delete(self, note_id: str, confirm: bool = False) -> str:
78
+ """Delete a note. The server has no preview, so confirm=True is required."""
79
+ if not confirm:
80
+ _need_confirm("Deleting a note")
81
+ return self._client._call("note", "note_manage", {"action": "delete", "note_id": note_id})
82
+
83
+
84
+ class Files(Scope):
85
+ """Files: upload, list, find, move, share and restore files in the Files app."""
86
+
87
+ def __init__(self, client):
88
+ super().__init__(client, "files", "files")
89
+
90
+ def upload(self, local_path: str, folder: str = "/Uploads", replace: bool = False) -> str:
91
+ """Upload a file from disk.
92
+
93
+ Args:
94
+ local_path: path to the file on this computer.
95
+ folder: target folder in the Files app. Default "/Uploads".
96
+ replace: replace a file with the same name. Default False (refused if it exists).
97
+ Returns: the file's path in the Files app, for example "/Uploads/data.csv".
98
+ """
99
+ with open(local_path, "rb") as f:
100
+ data = f.read()
101
+ return self._client._upload_bytes(data, os.path.basename(local_path), folder, replace)
102
+
103
+ def upload_bytes(self, data: bytes, name: str, folder: str = "/Uploads", replace: bool = False) -> str:
104
+ """Upload bytes already in memory. Same arguments as upload, with data and name instead of a path."""
105
+ return self._client._upload_bytes(data, name, folder, replace)
106
+
107
+ def list(self, folder: str = "/", limit: int = 50) -> str:
108
+ """List one folder. Args: folder (default "/"), limit 1 to 500 (default 50)."""
109
+ return self._client._call("files", "file_query", {"folder": folder, "limit": limit})
110
+
111
+ def info(self, path: str) -> str:
112
+ """Details of one file, for example "/Reports/sales.csv"."""
113
+ return self._client._call("files", "file_query", {"path": path})
114
+
115
+ def find(self, pattern: Optional[str] = None, query: Optional[str] = None, exclude: Optional[str] = None,
116
+ modified_after: Optional[str] = None, modified_before: Optional[str] = None,
117
+ limit: int = 50) -> str:
118
+ """Find files.
119
+
120
+ Args:
121
+ pattern: glob over full paths, for example "/Reports/**/*.pdf" or "*.csv".
122
+ query: words that must appear in the path (case-insensitive).
123
+ exclude: glob of paths to leave out, for example "**/drafts/**".
124
+ modified_after / modified_before: dates as YYYY-MM-DD.
125
+ limit: 1 to 500, default 50.
126
+ """
127
+ return self._client._call("files", "file_query", {
128
+ "pattern": pattern, "query": query, "exclude": exclude, "modified_after": modified_after,
129
+ "modified_before": modified_before, "limit": limit})
130
+
131
+ def trash(self, limit: int = 50) -> str:
132
+ """List files in the Trash. Deleted files are kept there for 30 days."""
133
+ return self._client._call("files", "file_query", {"trash": True, "limit": limit})
134
+
135
+ def shared_with_me(self, limit: int = 50) -> str:
136
+ """List files other people have shared with you."""
137
+ return self._client._call("files", "file_query", {"shared": True, "limit": limit})
138
+
139
+ def shares(self, limit: int = 50) -> str:
140
+ """List your active share links and named shares, with their share ids."""
141
+ return self._client._call("files", "file_query", {"shares": True, "limit": limit})
142
+
143
+ def job_status(self, job_id: str) -> str:
144
+ """Check a zip job started by download(..., confirm=True)."""
145
+ return self._client._call("files", "file_query", {"job_id": job_id})
146
+
147
+ def create_folder(self, folder: str) -> str:
148
+ """Create a folder, for example "/Clients/Acme"."""
149
+ return self._client._call("files", "file_manage", {"action": "create_folder", "folder": folder})
150
+
151
+ def move(self, paths: Sequence[str], destination: str) -> str:
152
+ """Move files or folders into a destination folder."""
153
+ return self._client._call("files", "file_manage",
154
+ {"action": "move", "paths": list(paths), "destination": destination})
155
+
156
+ def rename(self, path: str, new_name: str) -> str:
157
+ """Rename a file or folder. new_name is the name only, not a path."""
158
+ return self._client._call("files", "file_manage",
159
+ {"action": "rename", "path": path, "new_name": new_name})
160
+
161
+ def delete(self, paths: Optional[Sequence[str]] = None, pattern: Optional[str] = None,
162
+ exclude: Optional[str] = None, confirm: bool = False) -> str:
163
+ """Move files to the Trash. Preview first; confirm=True applies. Give paths or a pattern."""
164
+ return self._client._call("files", "file_manage", {
165
+ "action": "delete", "paths": list(paths) if paths else None, "pattern": pattern,
166
+ "exclude": exclude, "confirm": confirm})
167
+
168
+ def restore(self, paths: Optional[Sequence[str]] = None, pattern: Optional[str] = None) -> str:
169
+ """Restore files from the Trash to where they were."""
170
+ return self._client._call("files", "file_manage", {
171
+ "action": "restore", "paths": list(paths) if paths else None, "pattern": pattern})
172
+
173
+ def empty_trash(self, paths: Optional[Sequence[str]] = None, pattern: Optional[str] = None,
174
+ confirm: bool = False) -> str:
175
+ """Delete files in the Trash for good. Permanent: preview first, confirm=True applies."""
176
+ return self._client._call("files", "file_manage", {
177
+ "action": "empty_trash", "paths": list(paths) if paths else None, "pattern": pattern,
178
+ "confirm": confirm})
179
+
180
+ def download_link(self, path: str) -> str:
181
+ """A download link for one file. Opening it in a browser needs the owner to be signed in;
182
+ from code, send the token as a Bearer header."""
183
+ return self._client._call("files", "file_manage", {"action": "download", "paths": [path]})
184
+
185
+ def download(self, paths: Optional[Sequence[str]] = None, pattern: Optional[str] = None,
186
+ exclude: Optional[str] = None, modified_after: Optional[str] = None,
187
+ modified_before: Optional[str] = None, confirm: bool = False) -> str:
188
+ """Several files as one zip. Preview first; confirm=True starts the zip job (see job_status)."""
189
+ return self._client._call("files", "file_manage", {
190
+ "action": "download", "paths": list(paths) if paths else None, "pattern": pattern,
191
+ "exclude": exclude, "modified_after": modified_after, "modified_before": modified_before,
192
+ "confirm": confirm})
193
+
194
+ def share(self, paths: Optional[Sequence[str]] = None, pattern: Optional[str] = None,
195
+ expires: str = "7 days", password: Optional[str] = None, with_user: Optional[str] = None,
196
+ confirm: bool = False) -> str:
197
+ """Create a share link (or share with a registered user). Preview first; confirm=True applies.
198
+
199
+ Args:
200
+ expires: "1 hour", "1 day", "7 days" or "30 days" at most. Default "7 days".
201
+ password: optional, at least 6 characters. Not stored in plain text.
202
+ with_user: email of a registered user. Not combined with password.
203
+ """
204
+ return self._client._call("files", "file_manage", {
205
+ "action": "share", "paths": list(paths) if paths else None, "pattern": pattern,
206
+ "expires": expires, "password": password, "with_user": with_user, "confirm": confirm})
207
+
208
+ def unshare(self, share_id: str) -> str:
209
+ """Turn a share off at once. Find share ids with shares()."""
210
+ return self._client._call("files", "file_manage", {"action": "unshare", "share_id": share_id})
211
+
212
+
213
+ class DataLake(Scope):
214
+ """Data lake: query, load, change rows, change structure and share tables.
215
+
216
+ Names are letters (any language), digits and underscore. A namespace is created by the
217
+ first import into it.
218
+ """
219
+
220
+ def __init__(self, client):
221
+ super().__init__(client, "datalake", "data lake")
222
+
223
+ # ----- read -------------------------------------------------------------
224
+
225
+ def query(self, sql: str, save_to: Optional[str] = None) -> bytes:
226
+ """Run a query and return every row as Parquet data.
227
+
228
+ Parquet keeps column types and loads straight into pandas, Polars or Spark:
229
+ import polars as pl; df = pl.read_parquet(io.BytesIO(data))
230
+ Args:
231
+ sql: a SELECT, SHOW or DESCRIBE. Put a LIMIT in it to get fewer rows.
232
+ save_to: optional file path. If given, the Parquet is written there and the path is returned.
233
+ Returns: the Parquet bytes, or the path when save_to is given.
234
+ """
235
+ text = self._client._call("datalake", "datalake_query", {
236
+ "sql": sql, "export_to_s3": True, "export_format": "parquet", "wait": True})
237
+ data = self._client._download(_first_link(text))
238
+ if save_to:
239
+ with open(save_to, "wb") as f:
240
+ f.write(data)
241
+ return save_to
242
+ return data
243
+
244
+ def query_text(self, sql: str, limit: int = 10, wait: bool = True) -> str:
245
+ """Run a query and return the answer as text (a Markdown table), as the chat shows it.
246
+
247
+ Args:
248
+ sql: a SELECT, SHOW or DESCRIBE.
249
+ limit: rows shown in the text, default 10, -1 for all. A LIMIT in the SQL decides the rows
250
+ the query returns; this decides how many of them the text shows.
251
+ wait: True waits for the result. False returns a job id (see job()).
252
+ """
253
+ return self._client._call("datalake", "datalake_query", {"sql": sql, "limit": limit, "wait": wait})
254
+
255
+ def export(self, sql: str, export_format: str = "csv") -> str:
256
+ """Run a query, save every row to a file, and return a download link to share.
257
+
258
+ Args:
259
+ sql: the query. Put a LIMIT in it to export fewer rows.
260
+ export_format: "csv" (default, opens in any spreadsheet or by people who don't use code)
261
+ or "parquet" (for pandas, Polars and Spark).
262
+ Returns: the tool's text, including the download link.
263
+ """
264
+ return self._client._call("datalake", "datalake_query", {
265
+ "sql": sql, "export_to_s3": True, "export_format": export_format, "wait": True})
266
+
267
+ def job(self, job_id: str) -> str:
268
+ """Status and result of a job started with wait=False."""
269
+ return self._client._call("datalake", "datalake_query", {"sql": f"SHOW JOB {job_id}", "wait": True})
270
+
271
+ def namespaces(self) -> str:
272
+ """List all namespaces."""
273
+ return self.query_text("SHOW NAMESPACES")
274
+
275
+ def tables(self, namespace: str) -> str:
276
+ """List the tables in one namespace."""
277
+ check_name(namespace, "namespace")
278
+ return self.query_text(f"SHOW TABLES IN {namespace}")
279
+
280
+ def describe(self, namespace: str, table: str) -> str:
281
+ """Columns and types of one table."""
282
+ check_name(namespace, "namespace")
283
+ check_name(table, "table")
284
+ return self.query_text(f"DESCRIBE {namespace}.{table}")
285
+
286
+ # ----- load -------------------------------------------------------------
287
+
288
+ def import_file(self, files_path: str, namespace: str, table: str, wait: bool = True) -> str:
289
+ """Load a file from the Files app into a table. CSV, Excel, Parquet or JSON.
290
+
291
+ Args:
292
+ files_path: path in the Files app, for example "/Uploads/sales.csv".
293
+ namespace, table: where to load it. Created if they don't exist.
294
+ wait: True waits for the import to finish.
295
+ """
296
+ check_name(namespace, "namespace")
297
+ check_name(table, "table")
298
+ return self._client._call("datalake", "datalake_mutate", {
299
+ "action": "insert", "namespace": namespace, "table_name": table, "file": files_path, "wait": wait})
300
+
301
+ def import_url(self, url: str, namespace: str, table: str, file_format: Optional[str] = None,
302
+ wait: bool = True) -> str:
303
+ """Load a file from an https:// or s3:// link. file_format: "csv", "xlsx", "parquet" or "json"
304
+ when the link has no file extension."""
305
+ check_name(namespace, "namespace")
306
+ check_name(table, "table")
307
+ return self._client._call("datalake", "datalake_mutate", {
308
+ "action": "insert", "namespace": namespace, "table_name": table, "url": url,
309
+ "file_format": file_format, "wait": wait})
310
+
311
+ def insert_records(self, records: list, namespace: str, table: str, wait: bool = True) -> str:
312
+ """Add rows from a small list of dictionaries, for example [{"day": "2026-12-01", "units": 10}]."""
313
+ check_name(namespace, "namespace")
314
+ check_name(table, "table")
315
+ return self._client._call("datalake", "datalake_mutate", {
316
+ "action": "insert", "namespace": namespace, "table_name": table, "records": records, "wait": wait})
317
+
318
+ def import_zip(self, zip_path: str, namespace: str) -> list:
319
+ """Load each CSV in a zip into its own table in one namespace.
320
+
321
+ Other files and unsafe paths are skipped and listed. Nothing is extracted to disk.
322
+ Returns a list of (table, result) pairs.
323
+ """
324
+ check_name(namespace, "namespace")
325
+ results = []
326
+ with zipfile.ZipFile(zip_path) as zf:
327
+ for info in zf.infolist():
328
+ name = info.filename
329
+ if info.is_dir():
330
+ continue
331
+ if name.startswith("/") or ".." in name.split("/") or "\\" in name:
332
+ results.append((name, "skipped: unsafe path"))
333
+ continue
334
+ base = name.rsplit("/", 1)[-1]
335
+ if not base.lower().endswith(".csv"):
336
+ results.append((name, "skipped: not a CSV file"))
337
+ continue
338
+ table = check_name(base[:-4], f"table (from file name {base})")
339
+ files_path = self._client._upload_bytes(zf.read(info), base, f"/Uploads/{namespace}", True)
340
+ results.append((table, self.import_file(files_path, namespace, table)))
341
+ return results
342
+
343
+ # ----- change rows (preview first, confirm=True applies) -----------------
344
+
345
+ def _source(self, records, url, file_path) -> dict:
346
+ given = [x for x in (records, url, file_path) if x]
347
+ if len(given) != 1:
348
+ raise GSError("Give exactly one of records, url or file_path.")
349
+ return {"records": records, "url": url, "file": file_path}
350
+
351
+ def overwrite(self, namespace: str, table: str, records: Optional[list] = None, url: Optional[str] = None,
352
+ file_path: Optional[str] = None, confirm: bool = False) -> str:
353
+ """Replace ALL rows in a table with the new data. Preview first; confirm=True applies."""
354
+ check_name(namespace, "namespace")
355
+ check_name(table, "table")
356
+ args = {"action": "overwrite", "namespace": namespace, "table_name": table, "confirm": confirm}
357
+ args.update(self._source(records, url, file_path))
358
+ return self._client._call("datalake", "datalake_mutate", args)
359
+
360
+ def upsert(self, namespace: str, table: str, key_columns: list, records: Optional[list] = None,
361
+ url: Optional[str] = None, file_path: Optional[str] = None, confirm: bool = False) -> str:
362
+ """Update rows whose key already exists and add the rest. key_columns, for example ["id"].
363
+ Preview first; confirm=True applies."""
364
+ check_name(namespace, "namespace")
365
+ check_name(table, "table")
366
+ args = {"action": "upsert", "namespace": namespace, "table_name": table,
367
+ "key_columns": key_columns, "confirm": confirm}
368
+ args.update(self._source(records, url, file_path))
369
+ return self._client._call("datalake", "datalake_mutate", args)
370
+
371
+ def update(self, namespace: str, table: str, where: str, set_values: dict, all_rows: bool = False,
372
+ confirm: bool = False) -> str:
373
+ """Change matching rows. where, for example "id = 4"; set_values, for example {"units": 12}.
374
+ all_rows=True is needed when the condition matches every row. Preview first."""
375
+ check_name(namespace, "namespace")
376
+ check_name(table, "table")
377
+ return self._client._call("datalake", "datalake_mutate", {
378
+ "action": "update", "namespace": namespace, "table_name": table, "where": where,
379
+ "set_values": set_values, "all_rows": all_rows, "confirm": confirm})
380
+
381
+ def delete_rows(self, namespace: str, table: str, where: str, all_rows: bool = False,
382
+ confirm: bool = False) -> str:
383
+ """Remove matching rows. where, for example "id = 4". Preview first; confirm=True applies."""
384
+ check_name(namespace, "namespace")
385
+ check_name(table, "table")
386
+ return self._client._call("datalake", "datalake_mutate", {
387
+ "action": "delete", "namespace": namespace, "table_name": table, "where": where,
388
+ "all_rows": all_rows, "confirm": confirm})
389
+
390
+ # ----- structure -------------------------------------------------------
391
+
392
+ def create_table(self, namespace: str, table: str, columns: dict, key_columns: Optional[list] = None,
393
+ partition_by: Optional[list] = None) -> str:
394
+ """Create an empty table. columns maps names to types, for example {"day": "date", "units": "int64"}.
395
+ key_columns declares a key that later inserts can't duplicate (cannot be changed later)."""
396
+ check_name(namespace, "namespace")
397
+ check_name(table, "table")
398
+ return self._client._call("datalake", "datalake_manage", {
399
+ "action": "create_table", "namespace": namespace, "table_name": table, "columns": columns,
400
+ "key_columns": key_columns, "partition_by": partition_by})
401
+
402
+ def add_column(self, namespace: str, table: str, column: str, data_type: str = "string") -> str:
403
+ """Add a column. data_type: "string", "int64", "double", "date" and others. Default "string"."""
404
+ check_name(namespace, "namespace")
405
+ check_name(table, "table")
406
+ check_name(column, "column")
407
+ return self._client._call("datalake", "datalake_manage", {
408
+ "action": "add_column", "namespace": namespace, "table_name": table,
409
+ "column_name": column, "data_type": data_type})
410
+
411
+ def rename_column(self, namespace: str, table: str, column: str, new_column: str) -> str:
412
+ """Rename a column. Refused while a share uses it."""
413
+ check_name(namespace, "namespace")
414
+ check_name(table, "table")
415
+ check_name(column, "column")
416
+ check_name(new_column, "new column name")
417
+ return self._client._call("datalake", "datalake_manage", {
418
+ "action": "rename_column", "namespace": namespace, "table_name": table,
419
+ "column_name": column, "new_column_name": new_column})
420
+
421
+ def drop_column(self, namespace: str, table: str, column: str, confirm: bool = False) -> str:
422
+ """Remove a column and its data. Refused while a share uses it. confirm=True is required."""
423
+ check_name(namespace, "namespace")
424
+ check_name(table, "table")
425
+ if not confirm:
426
+ _need_confirm("Dropping a column")
427
+ return self._client._call("datalake", "datalake_manage", {
428
+ "action": "drop_column", "namespace": namespace, "table_name": table, "column_name": column})
429
+
430
+ def drop_table(self, namespace: str, table: str, force: bool = False, confirm: bool = False) -> str:
431
+ """Delete a table and its data. New tables are protected: force=True overrides that.
432
+ confirm=True is required."""
433
+ check_name(namespace, "namespace")
434
+ check_name(table, "table")
435
+ if not confirm:
436
+ _need_confirm("Dropping a table")
437
+ return self._client._call("datalake", "datalake_manage", {
438
+ "action": "drop_table", "namespace": namespace, "table_name": table, "force": force})
439
+
440
+ def drop_namespace(self, namespace: str, cascade: bool = True, confirm: bool = False) -> str:
441
+ """Delete a namespace. cascade=True also deletes every table in it. confirm=True is required."""
442
+ check_name(namespace, "namespace")
443
+ if not confirm:
444
+ _need_confirm("Dropping a namespace")
445
+ return self._client._call("datalake", "datalake_manage", {
446
+ "action": "drop_namespace", "namespace": namespace, "cascade": cascade})
447
+
448
+ def move_table(self, namespace: str, table: str, target_namespace: str, target_table: str) -> str:
449
+ """Move or rename a table into another namespace."""
450
+ for value, what in ((namespace, "namespace"), (table, "table"),
451
+ (target_namespace, "target namespace"), (target_table, "target table")):
452
+ check_name(value, what)
453
+ return self._client._call("datalake", "datalake_manage", {
454
+ "action": "move", "namespace": namespace, "table_name": table,
455
+ "target_namespace": target_namespace, "target_table": target_table})
456
+
457
+ def rollback(self, namespace: str, table: str, snapshot_id: str) -> str:
458
+ """Restore a table to an earlier version. snapshot_id: the id as text (see snapshots())."""
459
+ check_name(namespace, "namespace")
460
+ check_name(table, "table")
461
+ return self._client._call("datalake", "datalake_manage", {
462
+ "action": "rollback", "namespace": namespace, "table_name": table,
463
+ "target_snapshot_id": str(snapshot_id)})
464
+
465
+ def set_partition(self, namespace: str, table: str, partition_by: list, confirm: bool = False) -> str:
466
+ """Change how a table is partitioned, for example ["month(order_date)", "region"].
467
+ Preview first; confirm=True applies."""
468
+ check_name(namespace, "namespace")
469
+ check_name(table, "table")
470
+ return self._client._call("datalake", "datalake_manage", {
471
+ "action": "set_partition", "namespace": namespace, "table_name": table,
472
+ "partition_by": partition_by, "confirm": confirm})
473
+
474
+ def snapshots(self, namespace: str, table: str) -> str:
475
+ """List the saved versions of a table, with their snapshot ids."""
476
+ check_name(namespace, "namespace")
477
+ check_name(table, "table")
478
+ return self._client._call("datalake", "datalake_manage", {
479
+ "action": "list_snapshots", "namespace": namespace, "table_name": table})
480
+
481
+ def expire_snapshots(self, namespace: str, table: str, older_than_days: Optional[int] = None,
482
+ keep_last: Optional[int] = None, purge_history: bool = False,
483
+ confirm: bool = False) -> str:
484
+ """Delete old versions of a table, so rollback() can no longer reach them. The server has no
485
+ preview, so confirm=True is required. Give older_than_days, keep_last, or purge_history=True."""
486
+ check_name(namespace, "namespace")
487
+ check_name(table, "table")
488
+ if not confirm:
489
+ _need_confirm("Expiring snapshots")
490
+ return self._client._call("datalake", "datalake_manage", {
491
+ "action": "expire_snapshots", "namespace": namespace, "table_name": table,
492
+ "older_than_days": older_than_days, "keep_last": keep_last, "purge_history": purge_history,
493
+ "confirm": True}) # the server previews unless confirm is sent; the client already required confirm=True
494
+
495
+ # ----- sharing ----------------------------------------------------------
496
+
497
+ def share_table(self, namespace: str, table: str, share_with: str, allowed_columns: list,
498
+ permission: str = "read", row_filter: Optional[str] = None) -> str:
499
+ """Share a table with another user's email.
500
+
501
+ Args:
502
+ allowed_columns: required. ["*"] for all columns, or a list of column names.
503
+ permission: "read" (default) or "write" (insert, update and delete within the grant).
504
+ row_filter: SQL condition on rows, for example "region = 'east'". Default: all rows.
505
+ """
506
+ check_name(namespace, "namespace")
507
+ check_name(table, "table")
508
+ if not allowed_columns:
509
+ raise GSError("allowed_columns is required. Use ['*'] for all columns.")
510
+ return self._client._call("datalake", "datalake_share", {
511
+ "action": "grant", "namespace": namespace, "table_name": table, "share_with": share_with,
512
+ "permission": permission, "allowed_columns": allowed_columns, "row_filter": row_filter})
513
+
514
+ def grants(self) -> str:
515
+ """List the grants you have made."""
516
+ return self._client._call("datalake", "datalake_share", {"action": "list"})
517
+
518
+ def revoke_grant(self, grant_id: str) -> str:
519
+ """Remove one grant by its grant_id (see grants())."""
520
+ return self._client._call("datalake", "datalake_share", {"action": "revoke", "grant_id": grant_id})
@@ -0,0 +1,16 @@
1
+ """Name checks shared by the client. Names are refused, never rewritten."""
2
+
3
+ import re
4
+
5
+ from .errors import GSError
6
+
7
+ NAME_PATTERN = re.compile(r"\w+") # letters of any language, digits and underscore
8
+
9
+
10
+ def check_name(value: str, what: str) -> str:
11
+ if not isinstance(value, str) or not NAME_PATTERN.fullmatch(value):
12
+ raise GSError(
13
+ f"Invalid {what} '{value}': use letters, digits and underscore only "
14
+ "(no spaces or hyphens). Rename it and try again."
15
+ )
16
+ return value
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.4
2
+ Name: gotsimplified
3
+ Version: 0.1.0
4
+ Summary: Python client for Got Simplified: notes, files, data lake, ML and graphs. Ask in plain words with your own model, see every step, and approve every change.
5
+ Author: Got Simplified LLC
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Documentation, https://gotsimplified.com/
8
+ Project-URL: Homepage, https://gotsimplified.com/
9
+ Keywords: got simplified,data lake,notes,files,mcp
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: llm
19
+ Requires-Dist: litellm==1.112.2; extra == "llm"
20
+ Dynamic: license-file
21
+
22
+ # Got Simplified Python client
23
+
24
+ Use it from scripts and notebooks to work with your notes, files, data lake, machine learning and graphs.
25
+
26
+ ## What makes it different
27
+
28
+ - **Ask in plain words, with your own model.** `ask()` works with Claude, OpenAI or a local Ollama, using the key you choose. Snowflake's comparable feature (Cortex Analyst) runs on Snowflake's own models.
29
+ - **Every step is shown.** Each answer lists the tool calls behind it, so you can check the work.
30
+ - **Keep the model on your own machine.** With Ollama, your prompts and the results they produce never go to a model provider. Your data still lives on Got Simplified's servers, and the tools still run there. Smaller local models can struggle with tool calls, so test your model first with `llm_check.py`.
31
+ - **Changes need your approval.** Anything that changes or deletes data previews first, and `ask()` asks before any change.
32
+ - **Works without a model.** Every function runs on your Got Simplified token alone; the model key is only for `ask()`.
33
+ - **Several apps in one package:** notes, files, data lake, ML and graph, with the same safety rules for each.
34
+
35
+ Full function list with every parameter, default and description: [docs/reference.md](docs/reference.md).
36
+
37
+ ## Setup
38
+
39
+ ```bash
40
+ pip install gotsimplified
41
+ export GS_API_TOKEN="your-got-simplified-token"
42
+ ```
43
+
44
+ Optional, for plain-language requests with `ask()`:
45
+
46
+ ```bash
47
+ export LLM_API_KEY="your-claude-key"
48
+ export LLM_PROVIDER="anthropic"
49
+ ```
50
+
51
+ You can also pass the tokens in code: `Client(gs_token=..., llm_token=..., llm_provider="anthropic")`.
52
+ Tokens are never printed and never written to disk.
53
+
54
+ **Writes go to the account the token belongs to.** The default server is production.
55
+
56
+ ## Quick start
57
+
58
+ ```python
59
+ from gotsimplified import Client
60
+
61
+ c = Client()
62
+
63
+ # Notes
64
+ c.notes.create("Call Jane about the Tuesday pickup", title="Follow up", tags=["yard"])
65
+ print(c.notes.search("pickup"))
66
+
67
+ # Files
68
+ path = c.files.upload("sales.csv", folder="/Uploads/demo") # returns /Uploads/demo/sales.csv
69
+
70
+ # Data lake
71
+ c.datalake.import_file(path, namespace="sales", table="daily")
72
+ print(c.datalake.query("SELECT * FROM sales.daily LIMIT 10"))
73
+ ```
74
+
75
+ ## How the functions work
76
+
77
+ - **Grouped by app:** `c.notes`, `c.files`, `c.datalake`.
78
+ - **Preview first:** anything that changes or deletes data shows a preview by default (`confirm=False`). Pass `confirm=True` to apply it. Where the server has no preview, the client requires `confirm=True` and says so.
79
+ - **Names:** letters (any language), digits and underscore. Names with spaces or hyphens are refused with a fix, never renamed.
80
+ - **Results:** text, as the chat shows it.
81
+ - **Help in a notebook:** `help(c.datalake.overwrite)` shows the same text as the reference.
82
+
83
+ ## Plain-language requests with `ask()`
84
+
85
+ ```python
86
+ result = c.notes.ask("Find my notes about the Acme call and summarise them")
87
+ print(result.answer)
88
+ for step in result.steps: # each tool call, its result and any error
89
+ print(step.tool, step.arguments, step.result)
90
+ ```
91
+
92
+ `c.files.ask(...)` and `c.datalake.ask(..., table="sales.daily")` work the same way. The model sees only that app's tools. Any change waits for your yes in the terminal, and without a terminal it is refused.
93
+
94
+ ## Tests
95
+
96
+ ```bash
97
+ cd clients/python
98
+ PYTHONPATH=src python3 -m unittest discover -s tests -v
99
+ ```
100
+
101
+ The tests use fake servers and models. They don't need a token or network access.
102
+
103
+ ## Maintainers
104
+
105
+ - `PYTHONPATH=src python3 tools/gen_reference.py` regenerates `docs/reference.md` from the code.
106
+ - `GS_API_TOKEN=... PYTHONPATH=src python3 tools/check_server.py` compares the tools the package calls with the live server (read-only).
107
+ - `./deploy.sh --build-only` builds and checks the package. `./deploy.sh` uploads to TestPyPI.
108
+
109
+ ## License and trademark
110
+
111
+ This package is licensed under the Apache License 2.0. See `LICENSE`.
112
+
113
+ "Got Simplified" and the Got Simplified logo are trademarks of Got Simplified LLC. The Apache License 2.0 does not grant rights to use them. A fork or product built on this code must not use the name or logo to suggest it is made by or endorsed by Got Simplified LLC.