datasette-agent-edit 0.1a0__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.
- datasette_agent_edit/__init__.py +57 -0
- datasette_agent_edit/operations.py +120 -0
- datasette_agent_edit/store.py +139 -0
- datasette_agent_edit/stores/__init__.py +4 -0
- datasette_agent_edit/stores/disk.py +115 -0
- datasette_agent_edit/stores/sqlite.py +180 -0
- datasette_agent_edit/toolset.py +332 -0
- datasette_agent_edit-0.1a0.dist-info/METADATA +80 -0
- datasette_agent_edit-0.1a0.dist-info/RECORD +12 -0
- datasette_agent_edit-0.1a0.dist-info/WHEEL +5 -0
- datasette_agent_edit-0.1a0.dist-info/licenses/LICENSE +201 -0
- datasette_agent_edit-0.1a0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Storage-agnostic file-editing tools for Datasette Agent plugins.
|
|
2
|
+
|
|
3
|
+
Three layers:
|
|
4
|
+
|
|
5
|
+
1. :mod:`datasette_agent_edit.operations` -- pure string-editing primitives.
|
|
6
|
+
2. :mod:`datasette_agent_edit.store` -- the :class:`EditStore` backend seam,
|
|
7
|
+
plus ready-made :class:`SqliteVersionedStore` / :class:`DiskStore` backends.
|
|
8
|
+
3. :class:`EditToolset` -- builds Datasette Agent tools over any backend with
|
|
9
|
+
a single consistent JSON envelope and optional presentation hook.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from .operations import (
|
|
13
|
+
EditApplyError,
|
|
14
|
+
EditError,
|
|
15
|
+
apply_edit,
|
|
16
|
+
apply_edits,
|
|
17
|
+
insert,
|
|
18
|
+
str_replace,
|
|
19
|
+
view_lines,
|
|
20
|
+
)
|
|
21
|
+
from .store import (
|
|
22
|
+
AsyncTransformStore,
|
|
23
|
+
Conflict,
|
|
24
|
+
Editable,
|
|
25
|
+
EditStore,
|
|
26
|
+
IdCodec,
|
|
27
|
+
NotFound,
|
|
28
|
+
PrefixCodec,
|
|
29
|
+
Transform,
|
|
30
|
+
)
|
|
31
|
+
from .stores import DiskStore, SqliteVersionedStore
|
|
32
|
+
from .toolset import EditToolset
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
# operations
|
|
36
|
+
"view_lines",
|
|
37
|
+
"str_replace",
|
|
38
|
+
"insert",
|
|
39
|
+
"apply_edit",
|
|
40
|
+
"apply_edits",
|
|
41
|
+
"EditError",
|
|
42
|
+
"EditApplyError",
|
|
43
|
+
# store
|
|
44
|
+
"Editable",
|
|
45
|
+
"EditStore",
|
|
46
|
+
"AsyncTransformStore",
|
|
47
|
+
"Transform",
|
|
48
|
+
"IdCodec",
|
|
49
|
+
"PrefixCodec",
|
|
50
|
+
"NotFound",
|
|
51
|
+
"Conflict",
|
|
52
|
+
# backends
|
|
53
|
+
"SqliteVersionedStore",
|
|
54
|
+
"DiskStore",
|
|
55
|
+
# toolset
|
|
56
|
+
"EditToolset",
|
|
57
|
+
]
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Pure, storage-agnostic text-editing primitives.
|
|
2
|
+
|
|
3
|
+
These functions operate on plain strings and never touch a storage backend,
|
|
4
|
+
an event loop, or a Datasette instance. They are the in-memory "surgery" that
|
|
5
|
+
a backend's atomic ``edit()`` critical section applies to content. Keeping
|
|
6
|
+
them pure is what lets the same editing behaviour run unchanged inside a
|
|
7
|
+
SQLite write thread, a disk file lock, or an S3/GitHub compare-and-set loop.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class EditError(ValueError):
|
|
12
|
+
"""Raised when an edit cannot be applied to the given content.
|
|
13
|
+
|
|
14
|
+
Subclasses ``ValueError`` so existing ``except ValueError`` handlers (and
|
|
15
|
+
the test-suite's ``pytest.raises(ValueError, ...)`` expectations) keep
|
|
16
|
+
working.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class EditApplyError(EditError):
|
|
21
|
+
"""Raised by :func:`apply_edits` when one edit in a batch fails.
|
|
22
|
+
|
|
23
|
+
Carries the list of human-readable descriptions of the edits that did
|
|
24
|
+
succeed before the failure, plus the zero-based index of the edit that
|
|
25
|
+
failed, so callers can report partial progress without re-deriving it.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, message, applied, index):
|
|
29
|
+
super().__init__(message)
|
|
30
|
+
self.applied = applied
|
|
31
|
+
self.index = index
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def view_lines(content, view_range=""):
|
|
35
|
+
"""Format ``content`` as numbered lines, optionally sliced to a range.
|
|
36
|
+
|
|
37
|
+
``view_range`` is a string ``"start,end"`` (1-indexed, inclusive). An end
|
|
38
|
+
of ``-1`` means end-of-file. An empty string returns every line.
|
|
39
|
+
"""
|
|
40
|
+
all_lines = content.splitlines(True)
|
|
41
|
+
total_lines = len(all_lines)
|
|
42
|
+
|
|
43
|
+
if view_range:
|
|
44
|
+
parts = view_range.split(",")
|
|
45
|
+
start = int(parts[0])
|
|
46
|
+
end = int(parts[1])
|
|
47
|
+
if end == -1:
|
|
48
|
+
end = total_lines
|
|
49
|
+
lines = all_lines[start - 1 : end]
|
|
50
|
+
start_num = start
|
|
51
|
+
else:
|
|
52
|
+
lines = all_lines
|
|
53
|
+
start_num = 1
|
|
54
|
+
|
|
55
|
+
numbered = []
|
|
56
|
+
for i, line in enumerate(lines, start=start_num):
|
|
57
|
+
numbered.append(f"{i}:\t{line.rstrip()}")
|
|
58
|
+
return "\n".join(numbered)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def str_replace(content, old_str, new_str):
|
|
62
|
+
"""Replace exactly one occurrence of ``old_str`` in ``content``.
|
|
63
|
+
|
|
64
|
+
Raises :class:`EditError` if ``old_str`` is absent or appears more than
|
|
65
|
+
once (the caller should add surrounding context to disambiguate).
|
|
66
|
+
"""
|
|
67
|
+
count = content.count(old_str)
|
|
68
|
+
if count == 0:
|
|
69
|
+
raise EditError("old_str not found in content")
|
|
70
|
+
if count > 1:
|
|
71
|
+
raise EditError(f"old_str appears {count} times in content; must be unique")
|
|
72
|
+
return content.replace(old_str, new_str, 1)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def insert(content, insert_line, insert_text):
|
|
76
|
+
"""Insert ``insert_text`` after line number ``insert_line``.
|
|
77
|
+
|
|
78
|
+
``insert_line=0`` inserts at the very beginning of the content.
|
|
79
|
+
"""
|
|
80
|
+
lines = content.splitlines(True)
|
|
81
|
+
insert_pieces = insert_text.splitlines(True)
|
|
82
|
+
new_lines = lines[:insert_line] + insert_pieces + lines[insert_line:]
|
|
83
|
+
return "".join(new_lines)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def apply_edit(content, edit):
|
|
87
|
+
"""Apply a single ``{"operation": ..., ...}`` edit dict to ``content``.
|
|
88
|
+
|
|
89
|
+
Supported operations:
|
|
90
|
+
|
|
91
|
+
- ``str_replace``: keys ``old_str``, ``new_str``
|
|
92
|
+
- ``insert``: keys ``insert_line``, ``insert_text``
|
|
93
|
+
"""
|
|
94
|
+
op = edit.get("operation")
|
|
95
|
+
if op == "str_replace":
|
|
96
|
+
return str_replace(content, edit["old_str"], edit["new_str"])
|
|
97
|
+
if op == "insert":
|
|
98
|
+
return insert(content, edit["insert_line"], edit["insert_text"])
|
|
99
|
+
raise EditError(
|
|
100
|
+
f"unknown operation {op!r}. Use 'str_replace' or 'insert'."
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def apply_edits(content, edits):
|
|
105
|
+
"""Apply a sequence of edit dicts, returning ``(new_content, applied)``.
|
|
106
|
+
|
|
107
|
+
Edits are applied in order, so each edit sees the result of the previous
|
|
108
|
+
one. If any edit fails, an :class:`EditApplyError` is raised before any
|
|
109
|
+
result is returned, so callers can treat the batch as all-or-nothing.
|
|
110
|
+
``applied`` is a list of strings like ``"str_replace #1: OK"``.
|
|
111
|
+
"""
|
|
112
|
+
applied = []
|
|
113
|
+
for i, edit in enumerate(edits):
|
|
114
|
+
op = edit.get("operation")
|
|
115
|
+
try:
|
|
116
|
+
content = apply_edit(content, edit)
|
|
117
|
+
except EditError as e:
|
|
118
|
+
raise EditApplyError(str(e), applied=applied, index=i) from e
|
|
119
|
+
applied.append(f"{op} #{i + 1}: OK")
|
|
120
|
+
return content, applied
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""The storage seam: :class:`EditStore` and its supporting types.
|
|
2
|
+
|
|
3
|
+
A backend is anything that can create, read and atomically transform a piece
|
|
4
|
+
of text content addressed by a ``ref``. The defining method is
|
|
5
|
+
:meth:`EditStore.edit`, which takes a *synchronous, pure* ``transform``
|
|
6
|
+
callable and is responsible for running it inside whatever critical section
|
|
7
|
+
the backend needs (a SQLite write transaction, a file lock, an S3/GitHub
|
|
8
|
+
compare-and-set retry loop). Because the transform contains no I/O and no
|
|
9
|
+
awaits, the same editing logic is safe inside any of those contexts.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Any, Awaitable, Callable, Optional
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
from typing import Protocol, runtime_checkable
|
|
17
|
+
except ImportError: # pragma: no cover - py<3.8 fallback
|
|
18
|
+
from typing_extensions import Protocol, runtime_checkable
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
#: A pure, synchronous content transform: old content in, new content out.
|
|
22
|
+
#: It must not perform I/O or await; raise :class:`~.operations.EditError`
|
|
23
|
+
#: (a ``ValueError``) to abort the edit before anything is persisted.
|
|
24
|
+
Transform = Callable[[str], str]
|
|
25
|
+
|
|
26
|
+
#: An async transform, for the optional :class:`AsyncTransformStore` capability.
|
|
27
|
+
AsyncTransform = Callable[[str], Awaitable[str]]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class NotFound(Exception):
|
|
31
|
+
"""Raised by a store when ``ref`` does not identify existing content."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Conflict(Exception):
|
|
35
|
+
"""Raised when an atomic edit could not be committed due to contention.
|
|
36
|
+
|
|
37
|
+
Backends that implement optimistic concurrency (S3 ``If-Match``, the
|
|
38
|
+
GitHub contents API ``sha``) raise this after exhausting their retries.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class Editable:
|
|
44
|
+
"""A snapshot of stored content plus its addressing and bookkeeping.
|
|
45
|
+
|
|
46
|
+
``version`` is an opaque token whose meaning is backend-defined: an
|
|
47
|
+
incrementing integer for a versioned SQLite store, an mtime for a disk
|
|
48
|
+
file, an ETag or git blob SHA for object stores. The toolset only echoes
|
|
49
|
+
it back to the model and (optionally) uses it for display; it never
|
|
50
|
+
interprets it.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
ref: str
|
|
54
|
+
content: str
|
|
55
|
+
metadata: dict = field(default_factory=dict)
|
|
56
|
+
version: Any = None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@runtime_checkable
|
|
60
|
+
class EditStore(Protocol):
|
|
61
|
+
"""The interface every storage backend implements."""
|
|
62
|
+
|
|
63
|
+
async def create(
|
|
64
|
+
self, content: str, *, ref: Optional[str] = None, metadata: Optional[dict] = None
|
|
65
|
+
) -> Editable:
|
|
66
|
+
"""Create new content and return its :class:`Editable`.
|
|
67
|
+
|
|
68
|
+
``ref`` may be supplied for path-addressed backends (disk, S3,
|
|
69
|
+
GitHub); id-generating backends (SQLite) generate one when it is
|
|
70
|
+
``None``.
|
|
71
|
+
"""
|
|
72
|
+
...
|
|
73
|
+
|
|
74
|
+
async def read(self, ref: str) -> Editable:
|
|
75
|
+
"""Return the current :class:`Editable` for ``ref``.
|
|
76
|
+
|
|
77
|
+
Raises :class:`NotFound` if it does not exist.
|
|
78
|
+
"""
|
|
79
|
+
...
|
|
80
|
+
|
|
81
|
+
async def edit(self, ref: str, transform: Transform) -> Editable:
|
|
82
|
+
"""Atomically apply ``transform`` to the content at ``ref``.
|
|
83
|
+
|
|
84
|
+
The backend reads the current content, applies ``transform`` inside
|
|
85
|
+
its critical section, persists the result and returns the new
|
|
86
|
+
:class:`Editable`. If ``transform`` raises, nothing is persisted.
|
|
87
|
+
Raises :class:`NotFound` if ``ref`` does not exist and
|
|
88
|
+
:class:`Conflict` if the write could not be committed.
|
|
89
|
+
"""
|
|
90
|
+
...
|
|
91
|
+
|
|
92
|
+
async def delete(self, ref: str) -> None:
|
|
93
|
+
"""Delete the content at ``ref`` (raising :class:`NotFound` if absent)."""
|
|
94
|
+
...
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@runtime_checkable
|
|
98
|
+
class AsyncTransformStore(Protocol):
|
|
99
|
+
"""Opt-in capability for the rare backend that can await mid-edit.
|
|
100
|
+
|
|
101
|
+
Most backends cannot (a SQLite write transform runs on a non-async write
|
|
102
|
+
thread), so this is deliberately separate from :class:`EditStore`. The
|
|
103
|
+
:class:`~.toolset.EditToolset` never calls it; it exists for specialised
|
|
104
|
+
callers whose edit decision must consult something asynchronously and who
|
|
105
|
+
cannot pre-resolve that work before calling :meth:`EditStore.edit`.
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
async def aedit(self, ref: str, transform: AsyncTransform) -> Editable:
|
|
109
|
+
...
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class IdCodec:
|
|
113
|
+
"""Translates between the internal ``ref`` and the id the model sees.
|
|
114
|
+
|
|
115
|
+
The default is an identity mapping. Subclass (or use :class:`PrefixCodec`)
|
|
116
|
+
to expose, for example, ``artifact-01J...`` externally while storing the
|
|
117
|
+
bare ULID internally.
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
def to_external(self, ref: str) -> str:
|
|
121
|
+
return ref
|
|
122
|
+
|
|
123
|
+
def to_internal(self, external_id: str) -> str:
|
|
124
|
+
return external_id
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class PrefixCodec(IdCodec):
|
|
128
|
+
"""An :class:`IdCodec` that adds/strips a fixed prefix."""
|
|
129
|
+
|
|
130
|
+
def __init__(self, prefix: str):
|
|
131
|
+
self.prefix = prefix
|
|
132
|
+
|
|
133
|
+
def to_external(self, ref: str) -> str:
|
|
134
|
+
return self.prefix + ref
|
|
135
|
+
|
|
136
|
+
def to_internal(self, external_id: str) -> str:
|
|
137
|
+
if external_id.startswith(self.prefix):
|
|
138
|
+
return external_id[len(self.prefix) :]
|
|
139
|
+
return external_id
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""A filesystem-backed :class:`~datasette_agent_edit.store.EditStore`.
|
|
2
|
+
|
|
3
|
+
``ref`` is a path relative to a root directory. This backend is unversioned:
|
|
4
|
+
``version`` is the content file's ``mtime_ns``, used purely as a display/
|
|
5
|
+
freshness token. Atomicity within a process comes from a per-store
|
|
6
|
+
``asyncio.Lock`` plus a write-to-temp-then-``os.replace`` swap; blocking file
|
|
7
|
+
I/O is pushed to a worker thread so the event loop is never blocked. For
|
|
8
|
+
cross-process safety you would add an ``fcntl.flock`` around the read/replace,
|
|
9
|
+
which is the disk analogue of the SQLite write transaction.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
|
|
16
|
+
from ulid import ULID
|
|
17
|
+
|
|
18
|
+
from ..store import Editable, NotFound, Transform
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class DiskStore:
|
|
22
|
+
"""Store each piece of content as a file under ``root_dir``.
|
|
23
|
+
|
|
24
|
+
Metadata, if any, is written to a ``<path>.meta.json`` sidecar.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, root_dir):
|
|
28
|
+
self.root_dir = os.path.abspath(root_dir)
|
|
29
|
+
self._lock = asyncio.Lock()
|
|
30
|
+
|
|
31
|
+
def _resolve(self, ref):
|
|
32
|
+
"""Resolve ``ref`` to an absolute path, refusing escapes from root."""
|
|
33
|
+
path = os.path.abspath(os.path.join(self.root_dir, ref))
|
|
34
|
+
if path != self.root_dir and not path.startswith(self.root_dir + os.sep):
|
|
35
|
+
raise ValueError(f"ref escapes storage root: {ref!r}")
|
|
36
|
+
return path
|
|
37
|
+
|
|
38
|
+
def _meta_path(self, path):
|
|
39
|
+
return path + ".meta.json"
|
|
40
|
+
|
|
41
|
+
def _read_sync(self, ref):
|
|
42
|
+
path = self._resolve(ref)
|
|
43
|
+
try:
|
|
44
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
45
|
+
content = f.read()
|
|
46
|
+
except FileNotFoundError:
|
|
47
|
+
raise NotFound(ref)
|
|
48
|
+
metadata = {}
|
|
49
|
+
meta_path = self._meta_path(path)
|
|
50
|
+
if os.path.exists(meta_path):
|
|
51
|
+
with open(meta_path, "r", encoding="utf-8") as f:
|
|
52
|
+
metadata = json.load(f)
|
|
53
|
+
version = os.stat(path).st_mtime_ns
|
|
54
|
+
return Editable(ref=ref, content=content, metadata=metadata, version=version)
|
|
55
|
+
|
|
56
|
+
def _write_sync(self, path, content):
|
|
57
|
+
"""Atomically replace ``path`` with ``content`` (temp file + rename)."""
|
|
58
|
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
|
59
|
+
tmp = f"{path}.{ULID()}.tmp"
|
|
60
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
61
|
+
f.write(content)
|
|
62
|
+
os.replace(tmp, path)
|
|
63
|
+
|
|
64
|
+
async def create(self, content, *, ref=None, metadata=None):
|
|
65
|
+
ref = ref or str(ULID())
|
|
66
|
+
metadata = metadata or {}
|
|
67
|
+
path = self._resolve(ref)
|
|
68
|
+
|
|
69
|
+
def _do():
|
|
70
|
+
if os.path.exists(path):
|
|
71
|
+
raise FileExistsError(ref)
|
|
72
|
+
self._write_sync(path, content)
|
|
73
|
+
if metadata:
|
|
74
|
+
self._write_sync(self._meta_path(path), json.dumps(metadata))
|
|
75
|
+
return os.stat(path).st_mtime_ns
|
|
76
|
+
|
|
77
|
+
async with self._lock:
|
|
78
|
+
version = await asyncio.to_thread(_do)
|
|
79
|
+
return Editable(ref=ref, content=content, metadata=metadata, version=version)
|
|
80
|
+
|
|
81
|
+
async def read(self, ref):
|
|
82
|
+
return await asyncio.to_thread(self._read_sync, ref)
|
|
83
|
+
|
|
84
|
+
async def edit(self, ref, transform: Transform):
|
|
85
|
+
path = self._resolve(ref)
|
|
86
|
+
|
|
87
|
+
def _do():
|
|
88
|
+
current = self._read_sync(ref) # raises NotFound if missing
|
|
89
|
+
# Pure, synchronous surgery between read and atomic replace.
|
|
90
|
+
new_content = transform(current.content)
|
|
91
|
+
self._write_sync(path, new_content)
|
|
92
|
+
return Editable(
|
|
93
|
+
ref=ref,
|
|
94
|
+
content=new_content,
|
|
95
|
+
metadata=current.metadata,
|
|
96
|
+
version=os.stat(path).st_mtime_ns,
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
async with self._lock:
|
|
100
|
+
return await asyncio.to_thread(_do)
|
|
101
|
+
|
|
102
|
+
async def delete(self, ref):
|
|
103
|
+
path = self._resolve(ref)
|
|
104
|
+
|
|
105
|
+
def _do():
|
|
106
|
+
try:
|
|
107
|
+
os.remove(path)
|
|
108
|
+
except FileNotFoundError:
|
|
109
|
+
raise NotFound(ref)
|
|
110
|
+
meta_path = self._meta_path(path)
|
|
111
|
+
if os.path.exists(meta_path):
|
|
112
|
+
os.remove(meta_path)
|
|
113
|
+
|
|
114
|
+
async with self._lock:
|
|
115
|
+
await asyncio.to_thread(_do)
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""A versioned :class:`~datasette_agent_edit.store.EditStore` backed by SQLite.
|
|
2
|
+
|
|
3
|
+
Every edit appends a new row to a versions table and bumps a ``current_version``
|
|
4
|
+
pointer, giving full history. The atomic ``edit()`` runs the pure transform
|
|
5
|
+
*inside* Datasette's write thread via ``db.execute_write_fn``, so the
|
|
6
|
+
read-modify-write is a single serialised transaction with no chance of another
|
|
7
|
+
edit interleaving — and no ``await`` is possible (or needed) in that context.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
|
|
12
|
+
from ulid import ULID
|
|
13
|
+
|
|
14
|
+
from ..store import Editable, NotFound, Transform
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _now():
|
|
18
|
+
return datetime.now(timezone.utc).isoformat()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class SqliteVersionedStore:
|
|
22
|
+
"""Store content in two tables: objects + an append-only versions log.
|
|
23
|
+
|
|
24
|
+
Parameters
|
|
25
|
+
----------
|
|
26
|
+
db:
|
|
27
|
+
A Datasette ``Database`` (e.g. ``datasette.get_internal_database()``).
|
|
28
|
+
table:
|
|
29
|
+
Name of the objects table (one row per piece of content).
|
|
30
|
+
versions_table:
|
|
31
|
+
Name of the append-only versions table.
|
|
32
|
+
metadata_columns:
|
|
33
|
+
Optional mapping of ``column_name -> metadata_key``. Listed metadata
|
|
34
|
+
keys are stored in their own columns (and are filterable in SQL);
|
|
35
|
+
everything else is JSON-encoded into the ``metadata`` column. Defaults
|
|
36
|
+
to ``{}`` (all metadata goes to JSON).
|
|
37
|
+
validate_metadata:
|
|
38
|
+
Optional callable invoked as ``validate_metadata(metadata)`` on
|
|
39
|
+
``create``; raise ``ValueError`` to reject invalid metadata.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
db,
|
|
45
|
+
*,
|
|
46
|
+
table="datasette_agent_edit_objects",
|
|
47
|
+
versions_table="datasette_agent_edit_versions",
|
|
48
|
+
validate_metadata=None,
|
|
49
|
+
):
|
|
50
|
+
self.db = db
|
|
51
|
+
self.table = table
|
|
52
|
+
self.versions_table = versions_table
|
|
53
|
+
self.validate_metadata = validate_metadata
|
|
54
|
+
self._ensured = False
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def schema_sql(self):
|
|
58
|
+
return f"""
|
|
59
|
+
CREATE TABLE IF NOT EXISTS {self.table} (
|
|
60
|
+
id TEXT PRIMARY KEY,
|
|
61
|
+
metadata TEXT NOT NULL DEFAULT '{{}}',
|
|
62
|
+
current_version INTEGER NOT NULL DEFAULT 1,
|
|
63
|
+
created_at TEXT NOT NULL,
|
|
64
|
+
updated_at TEXT NOT NULL
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
CREATE TABLE IF NOT EXISTS {self.versions_table} (
|
|
68
|
+
object_id TEXT NOT NULL REFERENCES {self.table}(id),
|
|
69
|
+
version INTEGER NOT NULL,
|
|
70
|
+
content TEXT NOT NULL,
|
|
71
|
+
created_at TEXT NOT NULL,
|
|
72
|
+
PRIMARY KEY (object_id, version)
|
|
73
|
+
);
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
async def ensure_tables(self):
|
|
77
|
+
if not self._ensured:
|
|
78
|
+
await self.db.execute_write_script(self.schema_sql)
|
|
79
|
+
self._ensured = True
|
|
80
|
+
|
|
81
|
+
async def create(self, content, *, ref=None, metadata=None):
|
|
82
|
+
import json
|
|
83
|
+
|
|
84
|
+
metadata = metadata or {}
|
|
85
|
+
if self.validate_metadata is not None:
|
|
86
|
+
self.validate_metadata(metadata)
|
|
87
|
+
await self.ensure_tables()
|
|
88
|
+
|
|
89
|
+
object_id = ref or str(ULID())
|
|
90
|
+
now = _now()
|
|
91
|
+
metadata_json = json.dumps(metadata)
|
|
92
|
+
|
|
93
|
+
await self.db.execute_write(
|
|
94
|
+
f"INSERT INTO {self.table} "
|
|
95
|
+
"(id, metadata, current_version, created_at, updated_at) "
|
|
96
|
+
"VALUES (?, ?, 1, ?, ?)",
|
|
97
|
+
[object_id, metadata_json, now, now],
|
|
98
|
+
)
|
|
99
|
+
await self.db.execute_write(
|
|
100
|
+
f"INSERT INTO {self.versions_table} "
|
|
101
|
+
"(object_id, version, content, created_at) VALUES (?, 1, ?, ?)",
|
|
102
|
+
[object_id, content, now],
|
|
103
|
+
)
|
|
104
|
+
return Editable(ref=object_id, content=content, metadata=metadata, version=1)
|
|
105
|
+
|
|
106
|
+
async def read(self, ref):
|
|
107
|
+
import json
|
|
108
|
+
|
|
109
|
+
await self.ensure_tables()
|
|
110
|
+
row = (
|
|
111
|
+
await self.db.execute(
|
|
112
|
+
f"SELECT o.metadata, o.current_version, v.content "
|
|
113
|
+
f"FROM {self.versions_table} v "
|
|
114
|
+
f"JOIN {self.table} o ON o.id = v.object_id "
|
|
115
|
+
f"WHERE v.object_id = ? AND v.version = o.current_version",
|
|
116
|
+
[ref],
|
|
117
|
+
)
|
|
118
|
+
).first()
|
|
119
|
+
if not row:
|
|
120
|
+
raise NotFound(ref)
|
|
121
|
+
return Editable(
|
|
122
|
+
ref=ref,
|
|
123
|
+
content=row["content"],
|
|
124
|
+
metadata=json.loads(row["metadata"]),
|
|
125
|
+
version=row["current_version"],
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
async def edit(self, ref, transform: Transform):
|
|
129
|
+
import json
|
|
130
|
+
|
|
131
|
+
await self.ensure_tables()
|
|
132
|
+
now = _now()
|
|
133
|
+
|
|
134
|
+
def _write(conn):
|
|
135
|
+
row = conn.execute(
|
|
136
|
+
f"SELECT o.metadata, o.current_version, v.content "
|
|
137
|
+
f"FROM {self.versions_table} v "
|
|
138
|
+
f"JOIN {self.table} o ON o.id = v.object_id "
|
|
139
|
+
f"WHERE v.object_id = ? AND v.version = o.current_version",
|
|
140
|
+
[ref],
|
|
141
|
+
).fetchone()
|
|
142
|
+
if not row:
|
|
143
|
+
raise NotFound(ref)
|
|
144
|
+
metadata_json, current_version, content = row
|
|
145
|
+
# Pure, synchronous surgery inside the write transaction. If this
|
|
146
|
+
# raises (e.g. a failed str_replace) the transaction is rolled
|
|
147
|
+
# back and nothing is persisted.
|
|
148
|
+
new_content = transform(content)
|
|
149
|
+
new_version = current_version + 1
|
|
150
|
+
conn.execute(
|
|
151
|
+
f"INSERT INTO {self.versions_table} "
|
|
152
|
+
"(object_id, version, content, created_at) VALUES (?, ?, ?, ?)",
|
|
153
|
+
[ref, new_version, new_content, now],
|
|
154
|
+
)
|
|
155
|
+
conn.execute(
|
|
156
|
+
f"UPDATE {self.table} SET current_version = ?, updated_at = ? "
|
|
157
|
+
"WHERE id = ?",
|
|
158
|
+
[new_version, now, ref],
|
|
159
|
+
)
|
|
160
|
+
return new_version, new_content, json.loads(metadata_json)
|
|
161
|
+
|
|
162
|
+
new_version, new_content, metadata = await self.db.execute_write_fn(_write)
|
|
163
|
+
return Editable(
|
|
164
|
+
ref=ref, content=new_content, metadata=metadata, version=new_version
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
async def delete(self, ref):
|
|
168
|
+
await self.ensure_tables()
|
|
169
|
+
|
|
170
|
+
def _write(conn):
|
|
171
|
+
cur = conn.execute(
|
|
172
|
+
f"DELETE FROM {self.table} WHERE id = ?", [ref]
|
|
173
|
+
)
|
|
174
|
+
if cur.rowcount == 0:
|
|
175
|
+
raise NotFound(ref)
|
|
176
|
+
conn.execute(
|
|
177
|
+
f"DELETE FROM {self.versions_table} WHERE object_id = ?", [ref]
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
await self.db.execute_write_fn(_write)
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
"""Layer 3: turn an :class:`~datasette_agent_edit.store.EditStore` into a set
|
|
2
|
+
of Datasette Agent tools with a single, consistent JSON envelope.
|
|
3
|
+
|
|
4
|
+
The toolset is storage- *and* presentation-agnostic. Two extension points
|
|
5
|
+
absorb everything plugin-specific:
|
|
6
|
+
|
|
7
|
+
- ``id_codec`` maps between the internal ``ref`` and the id the model sees
|
|
8
|
+
(e.g. the ``artifact-`` prefix).
|
|
9
|
+
- ``render`` is an optional hook ``(Editable) -> dict`` (sync or async) whose
|
|
10
|
+
result is merged into the tool output, letting a plugin inject e.g. an
|
|
11
|
+
``_html`` preview. With no hook, no ``*_render`` tool is registered and
|
|
12
|
+
edits simply report status — which is exactly what a plain file editor
|
|
13
|
+
wants.
|
|
14
|
+
|
|
15
|
+
Handler methods (``view``, ``str_replace``, ``insert``, ``edit``, ``render``)
|
|
16
|
+
each return a JSON string and are directly callable for testing. :meth:`tools`
|
|
17
|
+
wraps them as ``AgentTool`` instances; that import is deferred so the rest of
|
|
18
|
+
the package works without ``datasette-agent`` installed.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import inspect
|
|
22
|
+
import json
|
|
23
|
+
|
|
24
|
+
from . import operations
|
|
25
|
+
from .operations import EditApplyError, EditError
|
|
26
|
+
from .store import IdCodec, NotFound
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class EditToolset:
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
store,
|
|
33
|
+
*,
|
|
34
|
+
name_prefix="file",
|
|
35
|
+
id_field="id",
|
|
36
|
+
id_codec=None,
|
|
37
|
+
render=None,
|
|
38
|
+
descriptions=None,
|
|
39
|
+
):
|
|
40
|
+
self.store = store
|
|
41
|
+
self.name_prefix = name_prefix
|
|
42
|
+
self.id_field = id_field
|
|
43
|
+
self.codec = id_codec or IdCodec()
|
|
44
|
+
self.render_hook = render
|
|
45
|
+
self.descriptions = {**self._default_descriptions(), **(descriptions or {})}
|
|
46
|
+
|
|
47
|
+
# ------------------------------------------------------------------ #
|
|
48
|
+
# Naming / formatting helpers
|
|
49
|
+
# ------------------------------------------------------------------ #
|
|
50
|
+
def _name(self, op):
|
|
51
|
+
return f"{self.name_prefix}_{op}"
|
|
52
|
+
|
|
53
|
+
def _ok(self, external_id, **extra):
|
|
54
|
+
return json.dumps({self.id_field: external_id, **extra})
|
|
55
|
+
|
|
56
|
+
def _err(self, message, **extra):
|
|
57
|
+
return json.dumps({"error": message, **extra})
|
|
58
|
+
|
|
59
|
+
async def _render_payload(self, editable):
|
|
60
|
+
if self.render_hook is None:
|
|
61
|
+
return {}
|
|
62
|
+
result = self.render_hook(editable)
|
|
63
|
+
if inspect.isawaitable(result):
|
|
64
|
+
result = await result
|
|
65
|
+
return result or {}
|
|
66
|
+
|
|
67
|
+
# ------------------------------------------------------------------ #
|
|
68
|
+
# Handlers (directly callable; each returns a JSON string)
|
|
69
|
+
# ------------------------------------------------------------------ #
|
|
70
|
+
async def view(self, external_id, view_range=""):
|
|
71
|
+
ref = self.codec.to_internal(external_id)
|
|
72
|
+
try:
|
|
73
|
+
editable = await self.store.read(ref)
|
|
74
|
+
except NotFound:
|
|
75
|
+
return self._err(f"Content not found: {external_id}")
|
|
76
|
+
return self._ok(
|
|
77
|
+
external_id,
|
|
78
|
+
metadata=editable.metadata,
|
|
79
|
+
content=operations.view_lines(editable.content, view_range),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
async def str_replace(self, external_id, old_str, new_str):
|
|
83
|
+
ref = self.codec.to_internal(external_id)
|
|
84
|
+
|
|
85
|
+
def transform(content):
|
|
86
|
+
return operations.str_replace(content, old_str, new_str)
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
editable = await self.store.edit(ref, transform)
|
|
90
|
+
except NotFound:
|
|
91
|
+
return self._err(f"Content not found: {external_id}")
|
|
92
|
+
except EditError as e:
|
|
93
|
+
return self._err(str(e))
|
|
94
|
+
return self._ok(
|
|
95
|
+
external_id,
|
|
96
|
+
version=editable.version,
|
|
97
|
+
status=(
|
|
98
|
+
f"Replacement applied. Call {self._name('render')} to display "
|
|
99
|
+
"the updated content."
|
|
100
|
+
if self.render_hook
|
|
101
|
+
else "Replacement applied."
|
|
102
|
+
),
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
async def insert(self, external_id, insert_line, insert_text):
|
|
106
|
+
ref = self.codec.to_internal(external_id)
|
|
107
|
+
|
|
108
|
+
def transform(content):
|
|
109
|
+
return operations.insert(content, insert_line, insert_text)
|
|
110
|
+
|
|
111
|
+
try:
|
|
112
|
+
editable = await self.store.edit(ref, transform)
|
|
113
|
+
except NotFound:
|
|
114
|
+
return self._err(f"Content not found: {external_id}")
|
|
115
|
+
except EditError as e:
|
|
116
|
+
return self._err(str(e))
|
|
117
|
+
return self._ok(
|
|
118
|
+
external_id,
|
|
119
|
+
version=editable.version,
|
|
120
|
+
status=(
|
|
121
|
+
f"Inserted text after line {insert_line}. Call "
|
|
122
|
+
f"{self._name('render')} to display the updated content."
|
|
123
|
+
if self.render_hook
|
|
124
|
+
else f"Inserted text after line {insert_line}."
|
|
125
|
+
),
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
async def edit(self, external_id, edits):
|
|
129
|
+
ref = self.codec.to_internal(external_id)
|
|
130
|
+
holder = {}
|
|
131
|
+
|
|
132
|
+
def transform(content):
|
|
133
|
+
new_content, applied = operations.apply_edits(content, edits)
|
|
134
|
+
holder["applied"] = applied
|
|
135
|
+
return new_content
|
|
136
|
+
|
|
137
|
+
try:
|
|
138
|
+
editable = await self.store.edit(ref, transform)
|
|
139
|
+
except NotFound:
|
|
140
|
+
return self._err(f"Content not found: {external_id}")
|
|
141
|
+
except EditApplyError as e:
|
|
142
|
+
return self._err(
|
|
143
|
+
f"Edit #{e.index + 1} failed: {e}", applied=e.applied
|
|
144
|
+
)
|
|
145
|
+
except EditError as e:
|
|
146
|
+
return self._err(str(e))
|
|
147
|
+
|
|
148
|
+
applied = holder.get("applied", [])
|
|
149
|
+
payload = await self._render_payload(editable)
|
|
150
|
+
return self._ok(
|
|
151
|
+
external_id,
|
|
152
|
+
version=editable.version,
|
|
153
|
+
edits_applied=len(applied),
|
|
154
|
+
status=f"Applied {len(applied)} edits.",
|
|
155
|
+
**payload,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
async def render(self, external_id):
|
|
159
|
+
if self.render_hook is None:
|
|
160
|
+
return self._err("This toolset has no render hook configured.")
|
|
161
|
+
ref = self.codec.to_internal(external_id)
|
|
162
|
+
try:
|
|
163
|
+
editable = await self.store.read(ref)
|
|
164
|
+
except NotFound:
|
|
165
|
+
return self._err(f"Content not found: {external_id}")
|
|
166
|
+
payload = await self._render_payload(editable)
|
|
167
|
+
return self._ok(external_id, status="Rendered.", **payload)
|
|
168
|
+
|
|
169
|
+
# ------------------------------------------------------------------ #
|
|
170
|
+
# AgentTool construction
|
|
171
|
+
# ------------------------------------------------------------------ #
|
|
172
|
+
def _id_arg(self):
|
|
173
|
+
return {
|
|
174
|
+
self.id_field: {
|
|
175
|
+
"type": "string",
|
|
176
|
+
"description": "The id of the content to operate on",
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
def tools(self):
|
|
181
|
+
"""Return the list of ``AgentTool`` instances for this toolset."""
|
|
182
|
+
from datasette_agent.tools import AgentTool
|
|
183
|
+
|
|
184
|
+
idf = self.id_field
|
|
185
|
+
|
|
186
|
+
def adapt(handler):
|
|
187
|
+
async def fn(datasette, actor, **kwargs):
|
|
188
|
+
external_id = kwargs.pop(idf)
|
|
189
|
+
return await handler(external_id, **kwargs)
|
|
190
|
+
|
|
191
|
+
return fn
|
|
192
|
+
|
|
193
|
+
tools = [
|
|
194
|
+
AgentTool(
|
|
195
|
+
name=self._name("view"),
|
|
196
|
+
description=self.descriptions["view"],
|
|
197
|
+
input_schema={
|
|
198
|
+
"type": "object",
|
|
199
|
+
"properties": {
|
|
200
|
+
**self._id_arg(),
|
|
201
|
+
"view_range": {
|
|
202
|
+
"type": "string",
|
|
203
|
+
"description": 'Optional line range "start,end" '
|
|
204
|
+
"(1-indexed, -1 for end-of-file)",
|
|
205
|
+
},
|
|
206
|
+
},
|
|
207
|
+
"required": [idf],
|
|
208
|
+
},
|
|
209
|
+
fn=adapt(self.view),
|
|
210
|
+
),
|
|
211
|
+
AgentTool(
|
|
212
|
+
name=self._name("str_replace"),
|
|
213
|
+
description=self.descriptions["str_replace"],
|
|
214
|
+
input_schema={
|
|
215
|
+
"type": "object",
|
|
216
|
+
"properties": {
|
|
217
|
+
**self._id_arg(),
|
|
218
|
+
"old_str": {
|
|
219
|
+
"type": "string",
|
|
220
|
+
"description": "Exact text to find (must appear once)",
|
|
221
|
+
},
|
|
222
|
+
"new_str": {
|
|
223
|
+
"type": "string",
|
|
224
|
+
"description": "Replacement text",
|
|
225
|
+
},
|
|
226
|
+
},
|
|
227
|
+
"required": [idf, "old_str", "new_str"],
|
|
228
|
+
},
|
|
229
|
+
fn=adapt(self.str_replace),
|
|
230
|
+
),
|
|
231
|
+
AgentTool(
|
|
232
|
+
name=self._name("insert"),
|
|
233
|
+
description=self.descriptions["insert"],
|
|
234
|
+
input_schema={
|
|
235
|
+
"type": "object",
|
|
236
|
+
"properties": {
|
|
237
|
+
**self._id_arg(),
|
|
238
|
+
"insert_line": {
|
|
239
|
+
"type": "integer",
|
|
240
|
+
"description": "Line number after which to insert "
|
|
241
|
+
"(0 for beginning)",
|
|
242
|
+
},
|
|
243
|
+
"insert_text": {
|
|
244
|
+
"type": "string",
|
|
245
|
+
"description": "Text to insert",
|
|
246
|
+
},
|
|
247
|
+
},
|
|
248
|
+
"required": [idf, "insert_line", "insert_text"],
|
|
249
|
+
},
|
|
250
|
+
fn=adapt(self.insert),
|
|
251
|
+
),
|
|
252
|
+
AgentTool(
|
|
253
|
+
name=self._name("edit"),
|
|
254
|
+
description=self.descriptions["edit"],
|
|
255
|
+
input_schema={
|
|
256
|
+
"type": "object",
|
|
257
|
+
"properties": {
|
|
258
|
+
**self._id_arg(),
|
|
259
|
+
"edits": {
|
|
260
|
+
"type": "array",
|
|
261
|
+
"description": "Edit operations applied sequentially",
|
|
262
|
+
"items": {
|
|
263
|
+
"type": "object",
|
|
264
|
+
"properties": {
|
|
265
|
+
"operation": {
|
|
266
|
+
"type": "string",
|
|
267
|
+
"enum": ["str_replace", "insert"],
|
|
268
|
+
},
|
|
269
|
+
"old_str": {"type": "string"},
|
|
270
|
+
"new_str": {"type": "string"},
|
|
271
|
+
"insert_line": {"type": "integer"},
|
|
272
|
+
"insert_text": {"type": "string"},
|
|
273
|
+
},
|
|
274
|
+
"required": ["operation"],
|
|
275
|
+
},
|
|
276
|
+
},
|
|
277
|
+
},
|
|
278
|
+
"required": [idf, "edits"],
|
|
279
|
+
},
|
|
280
|
+
fn=adapt(self.edit),
|
|
281
|
+
),
|
|
282
|
+
]
|
|
283
|
+
|
|
284
|
+
if self.render_hook is not None:
|
|
285
|
+
tools.append(
|
|
286
|
+
AgentTool(
|
|
287
|
+
name=self._name("render"),
|
|
288
|
+
description=self.descriptions["render"],
|
|
289
|
+
input_schema={
|
|
290
|
+
"type": "object",
|
|
291
|
+
"properties": self._id_arg(),
|
|
292
|
+
"required": [idf],
|
|
293
|
+
},
|
|
294
|
+
fn=adapt(self.render),
|
|
295
|
+
)
|
|
296
|
+
)
|
|
297
|
+
return tools
|
|
298
|
+
|
|
299
|
+
# ------------------------------------------------------------------ #
|
|
300
|
+
def _default_descriptions(self):
|
|
301
|
+
p = self.name_prefix
|
|
302
|
+
renders = self.render_hook is not None
|
|
303
|
+
edit_note = (
|
|
304
|
+
f" The {p}_edit tool renders once after applying all edits; the "
|
|
305
|
+
f"single-edit tools do not render, so call {p}_render when done."
|
|
306
|
+
if renders
|
|
307
|
+
else ""
|
|
308
|
+
)
|
|
309
|
+
return {
|
|
310
|
+
"view": (
|
|
311
|
+
f"View the current content with line numbers. Use before "
|
|
312
|
+
f"editing with {p}_str_replace or {p}_insert. Optionally pass "
|
|
313
|
+
'view_range as "start,end" (1-indexed, -1 for end-of-file).'
|
|
314
|
+
),
|
|
315
|
+
"str_replace": (
|
|
316
|
+
"Replace an exact string. old_str must appear exactly once "
|
|
317
|
+
"(add surrounding context to disambiguate)." + edit_note
|
|
318
|
+
),
|
|
319
|
+
"insert": (
|
|
320
|
+
"Insert text after a given line number (0 for the beginning "
|
|
321
|
+
"of the content)." + edit_note
|
|
322
|
+
),
|
|
323
|
+
"edit": (
|
|
324
|
+
"Apply multiple edits in one atomic operation. Pass an array "
|
|
325
|
+
'of {"operation": "str_replace"|"insert", ...} objects applied '
|
|
326
|
+
"sequentially; if any edit fails, none are saved."
|
|
327
|
+
),
|
|
328
|
+
"render": (
|
|
329
|
+
"Render the current content and display it. Call once after "
|
|
330
|
+
"all edits are complete."
|
|
331
|
+
),
|
|
332
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: datasette-agent-edit
|
|
3
|
+
Version: 0.1a0
|
|
4
|
+
Summary: Storage-agnostic file-editing tools (view / str_replace / insert) for Datasette Agent plugins
|
|
5
|
+
Author: Simon Willison
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/datasette/datasette-agent-edit
|
|
8
|
+
Project-URL: Issues, https://github.com/datasette/datasette-agent-edit/issues
|
|
9
|
+
Classifier: Framework :: Datasette
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: datasette>=1.0a31
|
|
14
|
+
Requires-Dist: python-ulid
|
|
15
|
+
Requires-Dist: typing_extensions
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# datasette-agent-edit
|
|
19
|
+
|
|
20
|
+
Storage-agnostic file-editing tools (`view` / `str_replace` / `insert` / batch
|
|
21
|
+
`edit`) for Datasette Agent plugins. The same tool behaviour can sit on top of
|
|
22
|
+
any storage layer — SQLite, the local filesystem, S3, the GitHub contents API,
|
|
23
|
+
…
|
|
24
|
+
|
|
25
|
+
## The three layers
|
|
26
|
+
|
|
27
|
+
1. **`operations`** — pure, synchronous string surgery (`view_lines`,
|
|
28
|
+
`str_replace`, `insert`, `apply_edits`). No I/O, no `await`, no Datasette.
|
|
29
|
+
2. **`EditStore`** — the storage seam. The defining method is
|
|
30
|
+
`edit(ref, transform)`: the backend reads the current content, runs your
|
|
31
|
+
*pure* transform inside whatever critical section it needs, and persists the
|
|
32
|
+
result atomically. A failing transform persists nothing.
|
|
33
|
+
- `SqliteVersionedStore` runs the transform inside Datasette's write thread
|
|
34
|
+
(`execute_write_fn`) and keeps full version history.
|
|
35
|
+
- `DiskStore` uses a lock + atomic `os.replace`.
|
|
36
|
+
- S3 (`If-Match`) and GitHub (`sha`) backends fit the same shape with a
|
|
37
|
+
compare-and-set retry loop.
|
|
38
|
+
3. **`EditToolset`** — turns any `EditStore` into Datasette Agent tools with one
|
|
39
|
+
consistent JSON envelope. Two hooks absorb the plugin-specific parts:
|
|
40
|
+
- `id_codec` maps internal refs to the ids the model sees (e.g. an
|
|
41
|
+
`artifact-` prefix).
|
|
42
|
+
- `render` optionally injects presentation (e.g. an `_html` iframe preview);
|
|
43
|
+
omit it and no `*_render` tool is registered.
|
|
44
|
+
|
|
45
|
+
## Why `transform` is synchronous
|
|
46
|
+
|
|
47
|
+
The transform sits *between* a backend's awaits, never inside them — the SQLite
|
|
48
|
+
backend literally cannot `await` on its write thread, and the S3/GitHub backends
|
|
49
|
+
must not re-run network calls on every compare-and-set retry. If an edit
|
|
50
|
+
decision needs async work, resolve it first and close over the result:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
resolved = await registry.lookup(name)
|
|
54
|
+
await store.edit(ref, lambda c: rewrite(c, resolved))
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
A rare backend that genuinely needs in-transaction async can implement the
|
|
58
|
+
optional `AsyncTransformStore.aedit` capability; the toolset never requires it.
|
|
59
|
+
|
|
60
|
+
## Example
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from datasette_agent_edit import EditToolset, SqliteVersionedStore, PrefixCodec
|
|
64
|
+
|
|
65
|
+
store = SqliteVersionedStore(datasette.get_internal_database())
|
|
66
|
+
toolset = EditToolset(
|
|
67
|
+
store,
|
|
68
|
+
name_prefix="artifact",
|
|
69
|
+
id_field="artifact_id",
|
|
70
|
+
id_codec=PrefixCodec("artifact-"),
|
|
71
|
+
render=lambda editable: {"_html": build_iframe(editable.content, editable.metadata)},
|
|
72
|
+
)
|
|
73
|
+
agent_tools = toolset.tools() # list of AgentTool, ready to register
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Development
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
uv run pytest
|
|
80
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
datasette_agent_edit/__init__.py,sha256=vqc6eD0Mo3ebB1-_E3gKZ44YSmBMMKbN1gic8cmQX9g,1253
|
|
2
|
+
datasette_agent_edit/operations.py,sha256=TBoqOZCkwnDVDMOuXGNpgDa-QrBiVu6Fp4XCP_1SBlE,4213
|
|
3
|
+
datasette_agent_edit/store.py,sha256=5sbps3qH3pfqGVAq9gfvX8nEpiZvzF_zofwIPv8tqAQ,4914
|
|
4
|
+
datasette_agent_edit/toolset.py,sha256=NTGsBBPKg3XqMWkpcX7b94vJXyYMDPMZP2W3YmagTTE,12486
|
|
5
|
+
datasette_agent_edit/stores/__init__.py,sha256=UAqNpnerYQ_IMcekNFM_zO2Vzy05eVB7wwumD_3zrfo,118
|
|
6
|
+
datasette_agent_edit/stores/disk.py,sha256=GrwgImpx353IwRlud34TdzzgxV__fk7BztOg-W8TrwE,4061
|
|
7
|
+
datasette_agent_edit/stores/sqlite.py,sha256=77gRSi5UuFJ7KnBcc1yG-9K5xDcYKZ0KHCNxl_LRuDM,6170
|
|
8
|
+
datasette_agent_edit-0.1a0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
9
|
+
datasette_agent_edit-0.1a0.dist-info/METADATA,sha256=kUpC70ayGCrvZavKQwX1ATjMGrnHON2yJRA-bmln1OU,3122
|
|
10
|
+
datasette_agent_edit-0.1a0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
11
|
+
datasette_agent_edit-0.1a0.dist-info/top_level.txt,sha256=v8buiXT593LwC-j43TAx1Aie-g1fJ3lhGK67ThQyWsc,21
|
|
12
|
+
datasette_agent_edit-0.1a0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
datasette_agent_edit
|