formist-cli 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.
- formist_cli/__init__.py +1 -0
- formist_cli/__main__.py +3 -0
- formist_cli/airtable.py +238 -0
- formist_cli/alerts.py +207 -0
- formist_cli/api.py +1027 -0
- formist_cli/chat.py +618 -0
- formist_cli/chats.py +517 -0
- formist_cli/cli.py +1367 -0
- formist_cli/cli_support.py +221 -0
- formist_cli/connectors.py +358 -0
- formist_cli/context.py +164 -0
- formist_cli/diff.py +943 -0
- formist_cli/doctor.py +128 -0
- formist_cli/export.py +427 -0
- formist_cli/files.py +670 -0
- formist_cli/importer.py +425 -0
- formist_cli/kb.py +185 -0
- formist_cli/login.py +615 -0
- formist_cli/logs.py +781 -0
- formist_cli/meetings.py +200 -0
- formist_cli/messages.py +414 -0
- formist_cli/participants.py +402 -0
- formist_cli/prefs.py +328 -0
- formist_cli/privileges.py +375 -0
- formist_cli/projects.py +127 -0
- formist_cli/resolve.py +443 -0
- formist_cli/settings.py +199 -0
- formist_cli/skill_library.py +246 -0
- formist_cli/skills.py +308 -0
- formist_cli/space_plan.py +411 -0
- formist_cli/spaces.py +693 -0
- formist_cli/targets.py +153 -0
- formist_cli/textnorm.py +26 -0
- formist_cli/tokens.py +339 -0
- formist_cli/update.py +433 -0
- formist_cli/uploads.py +928 -0
- formist_cli/usage_tokens.py +152 -0
- formist_cli/users.py +384 -0
- formist_cli/whatsapp.py +451 -0
- formist_cli-0.1.0.dist-info/METADATA +176 -0
- formist_cli-0.1.0.dist-info/RECORD +44 -0
- formist_cli-0.1.0.dist-info/WHEEL +4 -0
- formist_cli-0.1.0.dist-info/entry_points.txt +2 -0
- formist_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""``fm skill-library-install``: install one skill-library package into a space.
|
|
2
|
+
|
|
3
|
+
Uses the member-facing routes (``GET /projects/{id}/skill-library/packages`` and
|
|
4
|
+
``POST /projects/{id}/skill-library/packages/{package_id}/install``), so it needs
|
|
5
|
+
a member/writer credential, not platform admin. Dry run unless ``--apply``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import sys
|
|
13
|
+
from uuid import UUID
|
|
14
|
+
|
|
15
|
+
from formist_cli import api
|
|
16
|
+
from formist_cli.cli_support import require_object
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SkillLibraryError(Exception):
|
|
20
|
+
"""A refusal about the skill-library surface, written for an operator."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _looks_like_uuid(value: str) -> bool:
|
|
24
|
+
try:
|
|
25
|
+
UUID(value)
|
|
26
|
+
except ValueError:
|
|
27
|
+
return False
|
|
28
|
+
return True
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _version_sort_key(version: object) -> tuple:
|
|
32
|
+
"""Best-effort numeric-aware ordering for a package's freeform ``version``
|
|
33
|
+
string (a plain, non-null string defaulting to 1.0.0, never guaranteed
|
|
34
|
+
semver). Each dot-separated segment sorts as an int when it parses as
|
|
35
|
+
one (numeric segments always rank above textual ones, so "2" cannot
|
|
36
|
+
lose to a stray "10-beta"), else as text. Ties are the caller's
|
|
37
|
+
business (:func:`resolve_package` breaks them on ``created_at``).
|
|
38
|
+
"""
|
|
39
|
+
parts: list[tuple[int, int, str]] = []
|
|
40
|
+
for segment in str(version or "").split("."):
|
|
41
|
+
try:
|
|
42
|
+
parts.append((1, int(segment), ""))
|
|
43
|
+
except ValueError:
|
|
44
|
+
parts.append((0, 0, segment))
|
|
45
|
+
return tuple(parts)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def fetch_packages(target, space: str, *, token: str | None, get=None) -> list[dict]:
|
|
49
|
+
"""Every skill-library package visible to ``space``:
|
|
50
|
+
``GET /projects/{id}/skill-library/packages``, the member-facing,
|
|
51
|
+
product-filtered listing (unlike the admin, membership-free catalog
|
|
52
|
+
sync uses). Not paginated: the route takes no ``limit``/``offset``
|
|
53
|
+
and returns every visible row in one envelope.
|
|
54
|
+
"""
|
|
55
|
+
get = get or api.get
|
|
56
|
+
payload = get(target, f"/projects/{space}/skill-library/packages", token=token)
|
|
57
|
+
envelope = require_object(payload, what="the skill-library packages list", error=SkillLibraryError)
|
|
58
|
+
items = envelope.get("items")
|
|
59
|
+
if not isinstance(items, list):
|
|
60
|
+
raise SkillLibraryError(
|
|
61
|
+
f"expected an 'items' list from the skill-library packages list, got {envelope!r}"
|
|
62
|
+
)
|
|
63
|
+
return [i for i in items if isinstance(i, dict)]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def fetch_space_skills(target, space: str, *, token: str | None, get=None, page_size: int = 200) -> list[dict]:
|
|
67
|
+
"""Every skill already in ``space``, paged to the end:
|
|
68
|
+
``GET /projects/{id}/skills`` (the generic resource-router listing), so
|
|
69
|
+
:func:`already_installed` can check ``package_id`` against ALL of them, not
|
|
70
|
+
only the first page.
|
|
71
|
+
"""
|
|
72
|
+
get = get or api.get
|
|
73
|
+
out: list[dict] = []
|
|
74
|
+
offset = 0
|
|
75
|
+
while True:
|
|
76
|
+
payload = get(
|
|
77
|
+
target, f"/projects/{space}/skills", token=token,
|
|
78
|
+
params={"limit": str(page_size), "offset": str(offset)},
|
|
79
|
+
)
|
|
80
|
+
envelope = require_object(payload, what="the space's skills list", error=SkillLibraryError)
|
|
81
|
+
items = [i for i in (envelope.get("items") or []) if isinstance(i, dict)]
|
|
82
|
+
out.extend(items)
|
|
83
|
+
total = envelope.get("total")
|
|
84
|
+
offset += len(items)
|
|
85
|
+
if not items or total is None or offset >= int(total):
|
|
86
|
+
break
|
|
87
|
+
return out
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def resolve_package(packages: list[dict], package_ref: str) -> tuple[dict, list[dict]]:
|
|
91
|
+
"""``(chosen, all_candidates)`` for ``package_ref``: a package row UUID
|
|
92
|
+
(matched exactly, one row) or the reverse-DNS ``package`` id, which
|
|
93
|
+
several rows can share, one per version seeded over time. For the
|
|
94
|
+
reverse-DNS form, the newest version wins (:func:`_version_sort_key`,
|
|
95
|
+
``created_at`` as the tiebreaker) and the caller is expected to print
|
|
96
|
+
every candidate it passed over: this function only decides, it never
|
|
97
|
+
announces.
|
|
98
|
+
"""
|
|
99
|
+
ref = str(package_ref).strip()
|
|
100
|
+
if _looks_like_uuid(ref):
|
|
101
|
+
matches = [p for p in packages if str(p.get("id")) == ref]
|
|
102
|
+
if not matches:
|
|
103
|
+
raise SkillLibraryError(
|
|
104
|
+
f"no skill-library package with id {ref!r} is visible to this space."
|
|
105
|
+
)
|
|
106
|
+
return matches[0], matches
|
|
107
|
+
|
|
108
|
+
matches = [p for p in packages if p.get("package") == ref]
|
|
109
|
+
if not matches:
|
|
110
|
+
raise SkillLibraryError(
|
|
111
|
+
f"no skill-library package with package id {ref!r} is visible to this space.\n"
|
|
112
|
+
"PACKAGE is the reverse-DNS id (SkillPackage.package, e.g. "
|
|
113
|
+
"'com.wecarbon.esg-report') or the package row's own UUID. "
|
|
114
|
+
"`fm get SKILL_LIBRARY_PACKAGE` is not wired up yet, so check "
|
|
115
|
+
"`GET /projects/{space}/skill-library/packages` (or the gallery UI) "
|
|
116
|
+
"for the id."
|
|
117
|
+
)
|
|
118
|
+
chosen = max(
|
|
119
|
+
matches,
|
|
120
|
+
key=lambda p: (_version_sort_key(p.get("version")), str(p.get("created_at") or "")),
|
|
121
|
+
)
|
|
122
|
+
return chosen, matches
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def already_installed(skills: list[dict], package_id: str) -> dict | None:
|
|
126
|
+
"""The space's own ``Skill`` row installed FROM ``package_id``, or ``None``.
|
|
127
|
+
|
|
128
|
+
``package_id`` provenance is stamped only by the real install path
|
|
129
|
+
(the same server-side function both the gallery's "Install" button and
|
|
130
|
+
this command's ``--apply`` call reach), so an exact match is
|
|
131
|
+
unambiguous: this space already has this row, whoever or whatever
|
|
132
|
+
installed it.
|
|
133
|
+
"""
|
|
134
|
+
for row in skills:
|
|
135
|
+
if row.get("package_id") == package_id:
|
|
136
|
+
return row
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def add_install_parser(sub) -> None:
|
|
141
|
+
p = sub.add_parser(
|
|
142
|
+
"skill-library-install",
|
|
143
|
+
help="install one skill-library package into a space (idempotent; dry run unless --apply)",
|
|
144
|
+
description=(
|
|
145
|
+
"Installs PACKAGE, the reverse-DNS package id (SkillPackage.package, "
|
|
146
|
+
"e.g. 'com.wecarbon.esg-report') or the package row's own UUID, into "
|
|
147
|
+
"--space, through the SAME member-facing route the gallery's own "
|
|
148
|
+
"'Install' button uses (POST /projects/{id}/skill-library/packages/"
|
|
149
|
+
"{package_id}/install), so the installed Skill carries real "
|
|
150
|
+
"package_id/package_version provenance.\n\n"
|
|
151
|
+
"PACKAGE resolves against GET /projects/{id}/skill-library/packages. "
|
|
152
|
+
"If several rows share the reverse-DNS id (one per version seeded "
|
|
153
|
+
"over time), the NEWEST version is picked and every candidate is "
|
|
154
|
+
"printed so the choice is checkable.\n\n"
|
|
155
|
+
"IDEMPOTENT: if the space already has a skill installed from this "
|
|
156
|
+
"exact package (GET /projects/{id}/skills, matched by package_id), "
|
|
157
|
+
"this says so and does nothing: no request is sent.\n\n"
|
|
158
|
+
"DRY RUN by default: prints the plan and touches nothing. --apply "
|
|
159
|
+
"performs the install."
|
|
160
|
+
),
|
|
161
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
162
|
+
)
|
|
163
|
+
from formist_cli.cli import _add_env, _add_space
|
|
164
|
+
|
|
165
|
+
_add_env(p, for_write=True)
|
|
166
|
+
_add_space(p)
|
|
167
|
+
p.add_argument("package", help="reverse-DNS package id, or the package row UUID")
|
|
168
|
+
p.add_argument("--apply", action="store_true", help="perform the install (default: dry run)")
|
|
169
|
+
p.add_argument("--json", action="store_true", help="machine-readable output")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def run_install(args) -> int:
|
|
173
|
+
from formist_cli.cli import _effective, _token_for
|
|
174
|
+
|
|
175
|
+
eff = _effective(args, for_write=True, need_space=True)
|
|
176
|
+
token = _token_for(eff)
|
|
177
|
+
target, space = eff.target, eff.space
|
|
178
|
+
|
|
179
|
+
packages = fetch_packages(target, space, token=token)
|
|
180
|
+
chosen, matches = resolve_package(packages, args.package)
|
|
181
|
+
if len(matches) > 1:
|
|
182
|
+
print(
|
|
183
|
+
f" {len(matches)} package rows share package id {args.package!r}; "
|
|
184
|
+
f"picked the newest version {chosen.get('version')!r} (id={chosen['id']}):",
|
|
185
|
+
file=sys.stderr,
|
|
186
|
+
)
|
|
187
|
+
for m in matches:
|
|
188
|
+
marker = "*" if m is chosen else " "
|
|
189
|
+
print(f" {marker} id={m.get('id')} version={m.get('version')}", file=sys.stderr)
|
|
190
|
+
|
|
191
|
+
skills = fetch_space_skills(target, space, token=token)
|
|
192
|
+
existing = already_installed(skills, str(chosen["id"]))
|
|
193
|
+
if existing is not None:
|
|
194
|
+
result = {
|
|
195
|
+
"already_installed": True,
|
|
196
|
+
"package": {"id": chosen.get("id"), "name": chosen.get("name"), "version": chosen.get("version")},
|
|
197
|
+
"skill": {"id": existing.get("id"), "name": existing.get("name")},
|
|
198
|
+
}
|
|
199
|
+
if args.json:
|
|
200
|
+
print(json.dumps(result, indent=2, ensure_ascii=False))
|
|
201
|
+
else:
|
|
202
|
+
print(
|
|
203
|
+
f"already installed: nothing to do.\n"
|
|
204
|
+
f" package: {chosen.get('name')!r} v{chosen.get('version')} (id={chosen.get('id')})\n"
|
|
205
|
+
f" skill: id={existing.get('id')} name={existing.get('name')!r}"
|
|
206
|
+
)
|
|
207
|
+
return 0
|
|
208
|
+
|
|
209
|
+
if not args.apply:
|
|
210
|
+
print(
|
|
211
|
+
f"DRY RUN: nothing was changed.\n"
|
|
212
|
+
f"Would install package {chosen.get('name')!r} v{chosen.get('version')} "
|
|
213
|
+
f"(id={chosen.get('id')}, package={chosen.get('package')!r}) into space "
|
|
214
|
+
f"{space} ({target.env}).\n"
|
|
215
|
+
f"To apply: re-run with --apply.",
|
|
216
|
+
file=sys.stderr,
|
|
217
|
+
)
|
|
218
|
+
return 0
|
|
219
|
+
|
|
220
|
+
payload = api.post(
|
|
221
|
+
target, f"/projects/{space}/skill-library/packages/{chosen['id']}/install", {}, token=token
|
|
222
|
+
)
|
|
223
|
+
envelope = require_object(payload, what="the skill-library install endpoint", error=SkillLibraryError)
|
|
224
|
+
item = envelope.get("item")
|
|
225
|
+
if not isinstance(item, dict) or not item.get("id"):
|
|
226
|
+
raise SkillLibraryError(f"install returned an unexpected shape: {envelope!r}")
|
|
227
|
+
|
|
228
|
+
result = {
|
|
229
|
+
"already_installed": False,
|
|
230
|
+
"package": {"id": chosen.get("id"), "name": chosen.get("name"), "version": chosen.get("version")},
|
|
231
|
+
"skill": {"id": item.get("id"), "name": item.get("name")},
|
|
232
|
+
}
|
|
233
|
+
if args.json:
|
|
234
|
+
print(json.dumps(result, indent=2, ensure_ascii=False))
|
|
235
|
+
else:
|
|
236
|
+
print(
|
|
237
|
+
f"installed.\n"
|
|
238
|
+
f" package: {chosen.get('name')!r} v{chosen.get('version')} (id={chosen.get('id')})\n"
|
|
239
|
+
f" skill: id={item.get('id')} name={item.get('name')!r}"
|
|
240
|
+
)
|
|
241
|
+
return 0
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
# ===========================================================================
|
|
245
|
+
# fm skill-library-publish: one package into a deployment's catalog, as data
|
|
246
|
+
# ===========================================================================
|
formist_cli/skills.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""``fm skills-add`` / ``fm skills-update`` - install or replace ONE project's
|
|
2
|
+
own skill from a local ``SKILL.md`` (+ optional attachments), never from a
|
|
3
|
+
repo-shipped tree.
|
|
4
|
+
|
|
5
|
+
Skills are data, stored in the database rather than shipped as files in a
|
|
6
|
+
repo; these two commands are the operator's per-space way to put a skill's
|
|
7
|
+
starting text there. They read a ``SKILL.md`` off a local directory (or a
|
|
8
|
+
``.zip`` of one) and write it into one named space, through the same two
|
|
9
|
+
routes a member's own "create skill" / "edit skill" UI action uses
|
|
10
|
+
underneath, parsed server-side, never by this module (an HTTP client,
|
|
11
|
+
stdlib only).
|
|
12
|
+
|
|
13
|
+
``skills-add`` always creates a new row; ``skills-update`` always replaces an
|
|
14
|
+
existing one (resolved by id or exact name, the same resolver ``fm get SKILL``
|
|
15
|
+
uses) and never creates a second. Deliberately no bulk "seed every space" verb.
|
|
16
|
+
|
|
17
|
+
Attachments (any file in SOURCE besides ``SKILL.md``) are registered the same
|
|
18
|
+
way ``fm skill-attach`` already does: this module calls that mechanism
|
|
19
|
+
directly (``formist_cli.uploads.upload_file`` + ``attach_file_to_skill``) rather
|
|
20
|
+
than re-implementing it.
|
|
21
|
+
|
|
22
|
+
Dry run by default, same contract as every other write command here
|
|
23
|
+
(``fm upload``, ``fm skill-attach``); ``--apply`` performs the write.
|
|
24
|
+
|
|
25
|
+
Run:
|
|
26
|
+
fm skills-add --space <id> <dir-or-zip>
|
|
27
|
+
fm skills-update --space <id> --skill <id-or-name> <dir-or-zip>
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import argparse
|
|
33
|
+
import json as json_mod
|
|
34
|
+
import sys
|
|
35
|
+
import tempfile
|
|
36
|
+
import zipfile
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
|
|
39
|
+
from formist_cli import api
|
|
40
|
+
|
|
41
|
+
#: Deliberately not named `SKILL_FILENAME`: that name already exists
|
|
42
|
+
#: server-side, and this module must never import server code (pure HTTP
|
|
43
|
+
#: client, stdlib only). Same literal value, two independent constants.
|
|
44
|
+
SKILL_MD_NAME = "SKILL.md"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class SkillSourceError(SystemExit):
|
|
48
|
+
"""A local ``source`` argument that is not a usable SKILL.md source."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _read_skill_dir(path: Path) -> tuple[str, list[Path]]:
|
|
52
|
+
"""``(markdown text, [attachment file paths])`` from a directory holding
|
|
53
|
+
``SKILL.md``: every OTHER file directly inside it is an attachment,
|
|
54
|
+
exactly the shape ``fm skill-attach`` registers one file at a time."""
|
|
55
|
+
md_path = path / SKILL_MD_NAME
|
|
56
|
+
if not md_path.is_file():
|
|
57
|
+
raise SkillSourceError(f"error: no {SKILL_MD_NAME} under {path}")
|
|
58
|
+
markdown = md_path.read_text(encoding="utf-8")
|
|
59
|
+
attachments = sorted(
|
|
60
|
+
p for p in path.iterdir() if p.is_file() and p.name != SKILL_MD_NAME
|
|
61
|
+
)
|
|
62
|
+
return markdown, attachments
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def resolve_source(source: str) -> tuple[str, list[Path], tempfile.TemporaryDirectory | None]:
|
|
66
|
+
"""``source`` (a directory, or a ``.zip`` of one) -> ``(markdown,
|
|
67
|
+
attachments, cleanup)``, where ``cleanup`` is the extracted-zip tempdir the
|
|
68
|
+
caller must ``.cleanup()`` when not ``None``, or ``None`` for a plain
|
|
69
|
+
directory (nothing to clean up).
|
|
70
|
+
|
|
71
|
+
A zip may wrap its ``SKILL.md`` in one top-level directory (how most zip
|
|
72
|
+
tools produce one) or not; both are accepted; anything else refuses
|
|
73
|
+
rather than guessing which nested directory was meant.
|
|
74
|
+
"""
|
|
75
|
+
path = Path(source)
|
|
76
|
+
if path.is_dir():
|
|
77
|
+
markdown, attachments = _read_skill_dir(path)
|
|
78
|
+
return markdown, attachments, None
|
|
79
|
+
if path.is_file() and path.suffix.lower() == ".zip":
|
|
80
|
+
tmp = tempfile.TemporaryDirectory(prefix="fm-skills-")
|
|
81
|
+
try:
|
|
82
|
+
with zipfile.ZipFile(path) as zf:
|
|
83
|
+
zf.extractall(tmp.name)
|
|
84
|
+
except Exception:
|
|
85
|
+
tmp.cleanup()
|
|
86
|
+
raise
|
|
87
|
+
extracted = Path(tmp.name)
|
|
88
|
+
for candidate in (extracted, *sorted(p for p in extracted.iterdir() if p.is_dir())):
|
|
89
|
+
if (candidate / SKILL_MD_NAME).is_file():
|
|
90
|
+
markdown, attachments = _read_skill_dir(candidate)
|
|
91
|
+
return markdown, attachments, tmp
|
|
92
|
+
tmp.cleanup()
|
|
93
|
+
raise SkillSourceError(f"error: no {SKILL_MD_NAME} found anywhere in {path}")
|
|
94
|
+
raise SkillSourceError(f"error: {source!r} is neither a directory nor a .zip file")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _attach_all(
|
|
98
|
+
target,
|
|
99
|
+
space: str,
|
|
100
|
+
item: dict,
|
|
101
|
+
attachments: list[Path],
|
|
102
|
+
*,
|
|
103
|
+
token: str | None,
|
|
104
|
+
upload_file=None,
|
|
105
|
+
attach_file_to_skill=None,
|
|
106
|
+
) -> dict:
|
|
107
|
+
"""Upload + register every attachment on the just-created/updated skill,
|
|
108
|
+
reusing ``fm skill-attach``'s own functions rather than a second copy.
|
|
109
|
+
|
|
110
|
+
``upload_file``/``attach_file_to_skill`` are injectable (default: the real
|
|
111
|
+
``formist_cli.uploads`` functions), the same dependency-injection shape those
|
|
112
|
+
two functions themselves already accept, so a test can pass a fake
|
|
113
|
+
transport all the way through without patching module globals.
|
|
114
|
+
"""
|
|
115
|
+
from formist_cli import uploads as uploads_mod
|
|
116
|
+
|
|
117
|
+
upload_file = upload_file or uploads_mod.upload_file
|
|
118
|
+
attach_file_to_skill = attach_file_to_skill or uploads_mod.attach_file_to_skill
|
|
119
|
+
for att in attachments:
|
|
120
|
+
uploaded = upload_file(target, space, att, token=token)
|
|
121
|
+
file_id = uploaded["item"]["id"]
|
|
122
|
+
item = attach_file_to_skill(target, space, item, file_id, token=token)
|
|
123
|
+
return item
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def add_skill_from_source(
|
|
127
|
+
target,
|
|
128
|
+
space: str,
|
|
129
|
+
source: str,
|
|
130
|
+
*,
|
|
131
|
+
token: str | None,
|
|
132
|
+
post=None,
|
|
133
|
+
upload_file=None,
|
|
134
|
+
attach_file_to_skill=None,
|
|
135
|
+
) -> dict:
|
|
136
|
+
"""The testable core of ``fm skills-add``: read SOURCE, POST it, attach
|
|
137
|
+
whatever else SOURCE held. ``post`` is injectable (default:
|
|
138
|
+
``formist_cli.api.post``), the fake-transport convention every other
|
|
139
|
+
write command in this test suite uses."""
|
|
140
|
+
post = post or api.post
|
|
141
|
+
markdown, attachments, tmp = resolve_source(source)
|
|
142
|
+
try:
|
|
143
|
+
item = post(target, f"/projects/{space}/skills/import", {"markdown": markdown}, token=token)
|
|
144
|
+
if not isinstance(item, dict) or not item.get("id"):
|
|
145
|
+
raise SystemExit(f"error: import returned an unexpected shape: {item!r}")
|
|
146
|
+
return _attach_all(
|
|
147
|
+
target,
|
|
148
|
+
space,
|
|
149
|
+
item,
|
|
150
|
+
attachments,
|
|
151
|
+
token=token,
|
|
152
|
+
upload_file=upload_file,
|
|
153
|
+
attach_file_to_skill=attach_file_to_skill,
|
|
154
|
+
)
|
|
155
|
+
finally:
|
|
156
|
+
if tmp is not None:
|
|
157
|
+
tmp.cleanup()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def update_skill_from_source(
|
|
161
|
+
target,
|
|
162
|
+
space: str,
|
|
163
|
+
skill: dict,
|
|
164
|
+
source: str,
|
|
165
|
+
*,
|
|
166
|
+
token: str | None,
|
|
167
|
+
patch=None,
|
|
168
|
+
upload_file=None,
|
|
169
|
+
attach_file_to_skill=None,
|
|
170
|
+
) -> dict:
|
|
171
|
+
"""The testable core of ``fm skills-update``: read SOURCE, PATCH the
|
|
172
|
+
already-resolved ``skill`` dict (see ``formist_cli.uploads.resolve_skill``),
|
|
173
|
+
attach whatever else SOURCE held. Never resolves ``skill`` itself: same
|
|
174
|
+
split ``formist_cli.uploads.attach_file_to_skill`` uses, so a caller controls
|
|
175
|
+
exactly when the resolve-by-name network round trip happens."""
|
|
176
|
+
patch = patch or api.patch
|
|
177
|
+
markdown, attachments, tmp = resolve_source(source)
|
|
178
|
+
try:
|
|
179
|
+
item = patch(
|
|
180
|
+
target,
|
|
181
|
+
f"/projects/{space}/skills/{skill['id']}/import",
|
|
182
|
+
{"markdown": markdown},
|
|
183
|
+
token=token,
|
|
184
|
+
)
|
|
185
|
+
if not isinstance(item, dict) or not item.get("id"):
|
|
186
|
+
raise SystemExit(f"error: import returned an unexpected shape: {item!r}")
|
|
187
|
+
return _attach_all(
|
|
188
|
+
target,
|
|
189
|
+
space,
|
|
190
|
+
item,
|
|
191
|
+
attachments,
|
|
192
|
+
token=token,
|
|
193
|
+
upload_file=upload_file,
|
|
194
|
+
attach_file_to_skill=attach_file_to_skill,
|
|
195
|
+
)
|
|
196
|
+
finally:
|
|
197
|
+
if tmp is not None:
|
|
198
|
+
tmp.cleanup()
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# ===========================================================================
|
|
202
|
+
# The CLI surface. Per-module `add_parser` is the convention, see chats.py.
|
|
203
|
+
# ===========================================================================
|
|
204
|
+
def add_parser(sub) -> None:
|
|
205
|
+
from formist_cli.cli import _add_env, _add_space
|
|
206
|
+
|
|
207
|
+
p = sub.add_parser(
|
|
208
|
+
"skills-add",
|
|
209
|
+
help="install a local SKILL.md (+ attachments) as a NEW skill in a space (WRITE)",
|
|
210
|
+
description=(
|
|
211
|
+
"Reads SOURCE/SKILL.md and creates a brand-new Skill in the target "
|
|
212
|
+
"space (POST .../skills/import; the server parses SKILL.md). "
|
|
213
|
+
"Every OTHER file directly under SOURCE is uploaded and registered as "
|
|
214
|
+
"a template attachment (the same mechanism `fm skill-attach` uses).\n\n"
|
|
215
|
+
"SOURCE is a local directory holding SKILL.md, or a .zip of one.\n\n"
|
|
216
|
+
"DRY RUN by default: prints what would be created and touches "
|
|
217
|
+
"nothing. --apply performs the write."
|
|
218
|
+
),
|
|
219
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
220
|
+
)
|
|
221
|
+
_add_env(p, for_write=True)
|
|
222
|
+
_add_space(p)
|
|
223
|
+
p.add_argument("source", help="a directory holding SKILL.md, or a .zip of one")
|
|
224
|
+
p.add_argument("--apply", action="store_true", help="perform the write (default: dry run)")
|
|
225
|
+
p.add_argument("--json", action="store_true", help="machine-readable output")
|
|
226
|
+
|
|
227
|
+
p = sub.add_parser(
|
|
228
|
+
"skills-update",
|
|
229
|
+
help="replace an EXISTING skill's content from a local SKILL.md (+ attachments) (WRITE)",
|
|
230
|
+
description=(
|
|
231
|
+
"Reads SOURCE/SKILL.md and REPLACES --skill's content/description/etc "
|
|
232
|
+
"in place (PATCH .../skills/{id}/import), never creates a second "
|
|
233
|
+
"row. --skill is a skill id (UUID) or its exact name (resolved the "
|
|
234
|
+
"same way `fm get SKILL --name ...` does; refuses on more than one "
|
|
235
|
+
"match). Attachments under SOURCE are uploaded and registered "
|
|
236
|
+
"additively (existing ones are never removed), same as "
|
|
237
|
+
"`fm skill-attach`.\n\n"
|
|
238
|
+
"SOURCE is a local directory holding SKILL.md, or a .zip of one.\n\n"
|
|
239
|
+
"DRY RUN by default: prints what would change and touches nothing. "
|
|
240
|
+
"--apply performs the write."
|
|
241
|
+
),
|
|
242
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
243
|
+
)
|
|
244
|
+
_add_env(p, for_write=True)
|
|
245
|
+
_add_space(p)
|
|
246
|
+
p.add_argument("--skill", required=True, help="skill id (UUID) or exact name")
|
|
247
|
+
p.add_argument("source", help="a directory holding SKILL.md, or a .zip of one")
|
|
248
|
+
p.add_argument("--apply", action="store_true", help="perform the write (default: dry run)")
|
|
249
|
+
p.add_argument("--json", action="store_true", help="machine-readable output")
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def cmd_skills_add(args) -> int:
|
|
253
|
+
from formist_cli.cli import _effective, _token_for
|
|
254
|
+
|
|
255
|
+
eff = _effective(args, for_write=True)
|
|
256
|
+
token = _token_for(eff)
|
|
257
|
+
if not args.apply:
|
|
258
|
+
markdown, attachments, tmp = resolve_source(args.source)
|
|
259
|
+
if tmp is not None:
|
|
260
|
+
tmp.cleanup()
|
|
261
|
+
print(
|
|
262
|
+
f"DRY RUN: nothing was changed.\n"
|
|
263
|
+
f"Would create a new skill in space {eff.space} ({eff.target.name}) "
|
|
264
|
+
f"from {args.source} ({len(markdown)} chars of {SKILL_MD_NAME}"
|
|
265
|
+
+ (f", {len(attachments)} attachment(s)" if attachments else "")
|
|
266
|
+
+ ").\nTo apply: re-run with --apply.",
|
|
267
|
+
file=sys.stderr,
|
|
268
|
+
)
|
|
269
|
+
return 0
|
|
270
|
+
item = add_skill_from_source(eff.target, eff.space, args.source, token=token)
|
|
271
|
+
if args.json:
|
|
272
|
+
print(json_mod.dumps(item, indent=2, ensure_ascii=False))
|
|
273
|
+
else:
|
|
274
|
+
print(f"created: id={item['id']} name={item['name']!r} hook={item.get('hook')!r}")
|
|
275
|
+
if item.get("files"):
|
|
276
|
+
print(f" attached {len(item['files'])} file(s)")
|
|
277
|
+
return 0
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def cmd_skills_update(args) -> int:
|
|
281
|
+
from formist_cli.cli import _effective, _token_for
|
|
282
|
+
from formist_cli.uploads import resolve_skill
|
|
283
|
+
|
|
284
|
+
eff = _effective(args, for_write=True)
|
|
285
|
+
token = _token_for(eff)
|
|
286
|
+
skill = resolve_skill(args.skill, target=eff.target, space=eff.space, token=token)
|
|
287
|
+
if not args.apply:
|
|
288
|
+
markdown, attachments, tmp = resolve_source(args.source)
|
|
289
|
+
if tmp is not None:
|
|
290
|
+
tmp.cleanup()
|
|
291
|
+
print(
|
|
292
|
+
f"DRY RUN: nothing was changed.\n"
|
|
293
|
+
f"Would replace skill {skill['id']} ({skill.get('name')!r}) in "
|
|
294
|
+
f"space {eff.space} ({eff.target.name}) from {args.source} "
|
|
295
|
+
f"({len(markdown)} chars of {SKILL_MD_NAME}"
|
|
296
|
+
+ (f", {len(attachments)} attachment(s)" if attachments else "")
|
|
297
|
+
+ ").\nTo apply: re-run with --apply.",
|
|
298
|
+
file=sys.stderr,
|
|
299
|
+
)
|
|
300
|
+
return 0
|
|
301
|
+
item = update_skill_from_source(eff.target, eff.space, skill, args.source, token=token)
|
|
302
|
+
if args.json:
|
|
303
|
+
print(json_mod.dumps(item, indent=2, ensure_ascii=False))
|
|
304
|
+
else:
|
|
305
|
+
print(f"updated: id={item['id']} name={item['name']!r}")
|
|
306
|
+
if item.get("files"):
|
|
307
|
+
print(f" attached {len(item['files'])} file(s)")
|
|
308
|
+
return 0
|