ailands 0.5.2__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.
ailands/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """The Ailands developer CLI: sign in, scaffold, publish to the Ailands store.
2
+
3
+ The API an agent's code imports is the kernel's, `aipelago.sdk`, the same on every
4
+ distribution, so an agent written for Ailands runs wherever that kernel runs.
5
+ `pip install ailands` brings it in as a dependency (`aipelago-sdk`).
6
+ """
ailands/cli.py ADDED
@@ -0,0 +1,428 @@
1
+ """The `ailands` command — a developer's whole loop, from their own machine.
2
+
3
+ ailands login sign in with your Ailands account
4
+ ailands init my-agent start from a working skeleton
5
+ ailands publish . upload it as a draft (only you can take it)
6
+ ailands submit weather 1.0 ask for review
7
+ ailands status where everything stands
8
+
9
+ It talks to the developer platform over HTTPS and never to a kernel. That is why
10
+ it can be public while the kernel is not: publishing needs an account and a
11
+ signature, neither of which requires the thing that runs agents.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import base64
17
+ import hashlib
18
+ import json
19
+ import secrets
20
+ import sys
21
+ import time
22
+ from collections.abc import Iterator
23
+ from contextlib import suppress
24
+ from pathlib import Path
25
+
26
+ import click
27
+ import httpx
28
+
29
+ from ailands import config
30
+ from ailands.pack import PackError, build
31
+
32
+ _TIMEOUT = 60.0
33
+
34
+
35
+ def _pkce_pair() -> tuple[str, str]:
36
+ """A PKCE `(verifier, challenge)` for the device flow.
37
+
38
+ An identity provider may require proof of key exchange from a public client
39
+ even on the device flow (RFC 7636); one that does not ask ignores these two
40
+ parameters.
41
+ """
42
+ verifier = secrets.token_urlsafe(64)
43
+ digest = hashlib.sha256(verifier.encode("ascii")).digest()
44
+ return verifier, base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
45
+
46
+
47
+ def _refresh() -> bool:
48
+ """Spend the stored refresh token on a new access token. True if it worked.
49
+
50
+ The access token is short-lived; the refresh token outlives it so that an
51
+ expiry mid-build renews silently instead of asking you to sign in again.
52
+ """
53
+ creds = config.load_credentials()
54
+ token = str(creds.get("refresh_token") or "")
55
+ if not token:
56
+ return False
57
+ try:
58
+ info = _api("GET", "/v1/platform", auth=False)
59
+ issuer, client_id = info.get("oidc_issuer", ""), info.get("oidc_client_id", "")
60
+ if not issuer or not client_id:
61
+ return False
62
+ meta = httpx.get(f"{issuer}/.well-known/openid-configuration", timeout=_TIMEOUT).json()
63
+ resp = httpx.post(
64
+ meta["token_endpoint"],
65
+ data={
66
+ "grant_type": "refresh_token",
67
+ "refresh_token": token,
68
+ "client_id": client_id,
69
+ },
70
+ timeout=_TIMEOUT,
71
+ )
72
+ except (httpx.HTTPError, KeyError, click.ClickException):
73
+ # An unreachable IdP is not a bad refresh token: say nothing here and let
74
+ # the caller report the 401 it already has.
75
+ return False
76
+ if resp.status_code != 200:
77
+ return False
78
+ config.save_credentials(resp.json())
79
+ return True
80
+
81
+
82
+ def _api(method: str, path: str, *, auth: bool = True, _retried: bool = False, **kwargs) -> dict:
83
+ headers = dict(kwargs.pop("headers", {}))
84
+ if auth:
85
+ token = config.access_token()
86
+ if not token:
87
+ raise click.ClickException("not signed in — run `ailands login`")
88
+ headers["Authorization"] = f"Bearer {token}"
89
+ url = f"{config.platform_url()}{path}"
90
+ try:
91
+ resp = httpx.request(
92
+ method, url, headers=headers, timeout=_TIMEOUT, follow_redirects=True, **kwargs
93
+ )
94
+ except httpx.HTTPError as exc:
95
+ raise click.ClickException(f"cannot reach {config.platform_url()}: {exc}") from exc
96
+ if resp.status_code == 401:
97
+ # Once, and only on an authenticated call: a second 401 after a fresh
98
+ # access token is a real refusal, not an expiry, and retrying it forever
99
+ # would turn "you may not do that" into a hang.
100
+ if auth and not _retried and _refresh():
101
+ return _api(method, path, auth=auth, _retried=True, **kwargs)
102
+ raise click.ClickException("your session has expired — run `ailands login` again")
103
+ if resp.status_code >= 400:
104
+ detail = resp.text
105
+ # A non-JSON error body is still the best thing to show a person.
106
+ with suppress(json.JSONDecodeError, ValueError):
107
+ detail = resp.json().get("detail", detail)
108
+ raise click.ClickException(f"{resp.status_code}: {detail}")
109
+ return resp.json() if resp.content else {}
110
+
111
+
112
+ def _pages(path: str, key: str) -> Iterator[dict]:
113
+ """Every row of a paged list, one request per page: the platform sends a
114
+ list a page at a time with `next` as the cursor for the following one."""
115
+ after = None
116
+ while True:
117
+ page = _api("GET", path, params={"after": after} if after else None)
118
+ yield from page.get(key, [])
119
+ after = page.get("next")
120
+ if not after:
121
+ return
122
+
123
+
124
+ def _my_publishers(me: dict) -> list[dict]:
125
+ """All of `/v1/me`'s publishers: its first page, then the rest."""
126
+ publishers = list(me.get("publishers", []))
127
+ if me.get("publishers_next"):
128
+ after = me["publishers_next"]
129
+ while after:
130
+ page = _api("GET", "/v1/me/publishers", params={"after": after})
131
+ publishers += page.get("publishers", [])
132
+ after = page.get("next")
133
+ return publishers
134
+
135
+
136
+ @click.group()
137
+ @click.version_option(package_name="ailands")
138
+ def main() -> None:
139
+ """Build and publish agents for Ailands."""
140
+
141
+
142
+ # ─── signing in ──────────────────────────────────────────────────────────────
143
+ @main.command()
144
+ def login() -> None:
145
+ """Sign in with your Ailands account.
146
+
147
+ The OAuth device flow, so the browser step happens where a browser already
148
+ is: this works over SSH and inside a container, where a redirect to
149
+ `localhost` would not.
150
+ """
151
+ info = _api("GET", "/v1/platform", auth=False)
152
+ issuer, client_id = info.get("oidc_issuer", ""), info.get("oidc_client_id", "")
153
+ if not issuer or not client_id:
154
+ raise click.ClickException(
155
+ f"{config.platform_url()} is not accepting logins (it publishes no identity provider)"
156
+ )
157
+ try:
158
+ meta = httpx.get(f"{issuer}/.well-known/openid-configuration", timeout=_TIMEOUT).json()
159
+ device_endpoint = meta["device_authorization_endpoint"]
160
+ token_endpoint = meta["token_endpoint"]
161
+ verifier, challenge = _pkce_pair()
162
+ start = httpx.post(
163
+ device_endpoint,
164
+ data={
165
+ "client_id": client_id,
166
+ "scope": "openid email profile",
167
+ "code_challenge": challenge,
168
+ "code_challenge_method": "S256",
169
+ },
170
+ timeout=_TIMEOUT,
171
+ )
172
+ start.raise_for_status()
173
+ device = start.json()
174
+ except (httpx.HTTPError, KeyError) as exc:
175
+ raise click.ClickException(f"could not start sign-in: {exc}") from exc
176
+
177
+ click.echo(f"\n Open: {device.get('verification_uri_complete') or device['verification_uri']}")
178
+ click.echo(f" Code: {device['user_code']}\n")
179
+
180
+ deadline = time.monotonic() + int(device.get("expires_in", 600))
181
+ interval = int(device.get("interval", 5))
182
+ while time.monotonic() < deadline:
183
+ time.sleep(interval)
184
+ resp = httpx.post(
185
+ token_endpoint,
186
+ data={
187
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
188
+ "device_code": device["device_code"],
189
+ "client_id": client_id,
190
+ # The other half of the pair sent above. Omitting it here fails at
191
+ # the very last step, after the person has already approved.
192
+ "code_verifier": verifier,
193
+ },
194
+ timeout=_TIMEOUT,
195
+ )
196
+ if resp.status_code == 200:
197
+ config.save_credentials(resp.json())
198
+ me = _api("GET", "/v1/me")
199
+ click.echo(f"Signed in as {me.get('email') or me['subject']}.")
200
+ names = [p["name"] for p in _my_publishers(me)]
201
+ click.echo(
202
+ f"Publishers: {', '.join(names)}"
203
+ if names
204
+ else "You act for no publisher yet — run `ailands publisher create <name>`."
205
+ )
206
+ return
207
+ error = resp.json().get("error", "")
208
+ if error == "authorization_pending":
209
+ continue
210
+ if error == "slow_down":
211
+ interval += 5
212
+ continue
213
+ raise click.ClickException(f"sign-in failed: {error or resp.text}")
214
+ raise click.ClickException("sign-in timed out")
215
+
216
+
217
+ @main.command()
218
+ def whoami() -> None:
219
+ """Who this machine is signed in as, and what it may publish under."""
220
+ me = _api("GET", "/v1/me")
221
+ click.echo(f"{me.get('email') or me['subject']}")
222
+ for pub in _my_publishers(me):
223
+ mark = "verified" if pub["verified"] else "unverified"
224
+ key = "key registered" if pub["public_key"] else "NO KEY — run `ailands publisher key`"
225
+ click.echo(f" {pub['name']} ({mark}, {key})")
226
+ if me.get("is_reviewer"):
227
+ click.echo(" (platform reviewer)")
228
+
229
+
230
+ # ─── publishers ──────────────────────────────────────────────────────────────
231
+ @main.group()
232
+ def publisher() -> None:
233
+ """The name your agents are published under."""
234
+
235
+
236
+ @publisher.command("create")
237
+ @click.argument("name")
238
+ @click.option("--display-name", default="", help="what users see on a listing")
239
+ @click.option("--contact", default="", help="where users can reach you for support")
240
+ def publisher_create(name: str, display_name: str, contact: str) -> None:
241
+ """Claim a publisher name and register this machine's signing key.
242
+
243
+ The name is what users see on a listing, and it is first-come. Agents are
244
+ published under it, so it is the thing people will hold you to.
245
+ """
246
+ _api(
247
+ "POST",
248
+ "/v1/publishers",
249
+ json={"name": name, "display_name": display_name, "contact": contact},
250
+ )
251
+ click.echo(f"Publisher {name!r} is yours. Registering this machine's signing key…")
252
+ publisher_key.callback(name) # type: ignore[misc]
253
+
254
+
255
+ @publisher.command("key")
256
+ @click.argument("name")
257
+ def publisher_key(name: str) -> None:
258
+ """Register this machine's public signing key for a publisher."""
259
+ _, public = config.signing_key()
260
+ _api("PUT", f"/v1/publishers/{name}/key", json={"public_key": public})
261
+ click.echo(f"Key registered for {name}. The private half stays in {config.home()}.")
262
+
263
+
264
+ @publisher.command("add-member")
265
+ @click.argument("name")
266
+ @click.argument("subject")
267
+ def publisher_add_member(name: str, subject: str) -> None:
268
+ """Let another person publish under this publisher (their account subject)."""
269
+ _api("POST", f"/v1/publishers/{name}/members", json={"subject": subject})
270
+ click.echo(f"{subject} can now publish as {name}.")
271
+
272
+
273
+ # ─── the loop ────────────────────────────────────────────────────────────────
274
+ _SKELETON_MANIFEST = """\
275
+ id: {agent_id}
276
+ version: "0.1.0"
277
+ publisher: {publisher}
278
+
279
+ # The lowest Ailands version this agent runs on. Leave it out and it runs
280
+ # anywhere; set it once you rely on something a newer Ailands added.
281
+ # requires:
282
+ # min_platform_version: "2.0"
283
+
284
+ provides:
285
+ personas:
286
+ - id: web
287
+ prompt_file: personas/web.md
288
+ """
289
+
290
+ _SKELETON_PROMPT = """\
291
+ You are {agent_id}. Say what you are for in one sentence, then help.
292
+ """
293
+
294
+ _SKELETON_STRINGS = """\
295
+ agent:
296
+ name: "{agent_id}"
297
+ description: "An agent."
298
+ icon: "🌱"
299
+ """
300
+
301
+
302
+ @main.command()
303
+ @click.argument("directory")
304
+ @click.option("--publisher", "publisher_name", default="", help="publisher to publish under")
305
+ def init(directory: str, publisher_name: str) -> None:
306
+ """Create a working agent skeleton in DIRECTORY."""
307
+ root = Path(directory)
308
+ if root.exists() and any(root.iterdir()):
309
+ raise click.ClickException(f"{root} already exists and is not empty")
310
+ agent_id = root.name.replace("-", "_")
311
+ if not publisher_name:
312
+ publishers = _api("GET", "/v1/me").get("publishers", [])
313
+ if not publishers:
314
+ raise click.ClickException(
315
+ "you act for no publisher — run `ailands publisher create <name>` first"
316
+ )
317
+ publisher_name = publishers[0]["name"]
318
+ (root / "personas").mkdir(parents=True)
319
+ (root / "strings").mkdir(parents=True)
320
+ (root / "manifest.yaml").write_text(
321
+ _SKELETON_MANIFEST.format(agent_id=agent_id, publisher=publisher_name), encoding="utf-8"
322
+ )
323
+ (root / "personas" / "web.md").write_text(
324
+ _SKELETON_PROMPT.format(agent_id=agent_id), encoding="utf-8"
325
+ )
326
+ (root / "strings" / "en.yaml").write_text(
327
+ _SKELETON_STRINGS.format(agent_id=agent_id), encoding="utf-8"
328
+ )
329
+ click.echo(f"Created {root}. Next: edit personas/web.md, then `ailands publish {root}`.")
330
+
331
+
332
+ @main.command()
333
+ @click.argument("directory", default=".")
334
+ @click.option("--out", default="", help="write the bundle here instead of publishing")
335
+ def pack(directory: str, out: str) -> None:
336
+ """Build and sign a bundle without uploading it."""
337
+ private, _ = config.signing_key()
338
+ try:
339
+ tarball, meta = build(directory, private)
340
+ except PackError as exc:
341
+ raise click.ClickException(str(exc)) from exc
342
+ target = Path(out or f"{meta['id']}-{meta['version']}.tar.gz")
343
+ target.write_bytes(tarball)
344
+ click.echo(f"{target} ({len(tarball) / 1024:.0f} KB, signed as {meta['publisher']})")
345
+
346
+
347
+ @main.command()
348
+ @click.argument("directory", default=".")
349
+ def publish(directory: str) -> None:
350
+ """Upload a bundle as a DRAFT.
351
+
352
+ A draft is live for exactly one person: you. Take it on your own island, try
353
+ it against the real thing, publish again over the same version as often as you
354
+ like — then `ailands submit` when it is worth someone's time to review.
355
+ """
356
+ private, _ = config.signing_key()
357
+ try:
358
+ tarball, meta = build(directory, private)
359
+ except PackError as exc:
360
+ raise click.ClickException(str(exc)) from exc
361
+ result = _api(
362
+ "POST",
363
+ "/v1/agents/publish",
364
+ files={"tarball": (f"{meta['id']}.tar.gz", tarball, "application/gzip")},
365
+ )
366
+ click.echo(
367
+ f"{result['agent_id']}@{result['version']} is a draft — only you can take it.\n"
368
+ f" ailands submit {result['agent_id']} {result['version']}"
369
+ )
370
+
371
+
372
+ @main.command()
373
+ @click.argument("agent_id")
374
+ @click.argument("version")
375
+ def submit(agent_id: str, version: str) -> None:
376
+ """Send a draft for review."""
377
+ result = _api("POST", f"/v1/agents/{agent_id}/versions/{version}/submit")
378
+ click.echo(f"{agent_id}@{version} is {result['state']}. `ailands status` to follow it.")
379
+
380
+
381
+ @main.command()
382
+ @click.option("--publisher", "publisher_name", default="", help="limit to one publisher")
383
+ def status(publisher_name: str) -> None:
384
+ """Where every version you have published stands."""
385
+ me = _api("GET", "/v1/me")
386
+ names = [publisher_name] if publisher_name else [p["name"] for p in _my_publishers(me)]
387
+ if not names:
388
+ click.echo("You act for no publisher yet.")
389
+ return
390
+ for name in names:
391
+ click.echo(f"\n{name}")
392
+ shown = 0
393
+ for v in _pages(f"/v1/publishers/{name}/versions", "versions"):
394
+ note = f" — {v['review_note']}" if v.get("review_note") else ""
395
+ click.echo(f" {v['agent_id']}@{v['version']:<10} {v['state']}{note}")
396
+ shown += 1
397
+ if not shown:
398
+ click.echo(" (nothing published yet)")
399
+
400
+
401
+ @main.command()
402
+ @click.argument("directory", default=".")
403
+ @click.option("--interval", default=2.0, help="seconds between checks")
404
+ def watch(directory: str, interval: float) -> None:
405
+ """Republish the draft whenever a file changes — the inner loop.
406
+
407
+ Polling rather than an OS watcher: one dependency fewer, and the loop that
408
+ matters is bounded by the upload anyway.
409
+ """
410
+ root = Path(directory)
411
+ click.echo(f"Watching {root.resolve()} — Ctrl-C to stop.")
412
+ last: float | None = None
413
+ while True:
414
+ newest = max(
415
+ (p.stat().st_mtime for p in root.rglob("*") if p.is_file()),
416
+ default=0.0,
417
+ )
418
+ if last is None or newest > last:
419
+ last = newest
420
+ try:
421
+ publish.callback(directory) # type: ignore[misc]
422
+ except click.ClickException as exc:
423
+ click.echo(f" ! {exc.format_message()}", err=True)
424
+ time.sleep(interval)
425
+
426
+
427
+ if __name__ == "__main__": # pragma: no cover
428
+ sys.exit(main())
ailands/config.py ADDED
@@ -0,0 +1,103 @@
1
+ """Where the CLI keeps a developer's credentials and signing key.
2
+
3
+ One directory, `~/.config/ailands` (`$XDG_CONFIG_HOME/ailands`; `$AILANDS_HOME`
4
+ overrides it), with two things in it: the token this machine signed in with, and
5
+ the Ed25519 private key it signs bundles with.
6
+
7
+ The private key is generated here and never leaves — the platform only ever sees
8
+ the public half. That is what makes "who published this" a question with an
9
+ answer: a key the platform generated for you would be a key the platform could
10
+ also sign with.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import base64
16
+ import json
17
+ import os
18
+ import stat
19
+ from pathlib import Path
20
+
21
+ import click
22
+
23
+ DEFAULT_PLATFORM = "https://developers.ailands.app"
24
+
25
+
26
+ def home() -> Path:
27
+ env = os.environ.get("AILANDS_HOME")
28
+ if env:
29
+ root = Path(env).expanduser()
30
+ else:
31
+ # The XDG spec ignores a relative XDG_CONFIG_HOME.
32
+ xdg = os.environ.get("XDG_CONFIG_HOME", "")
33
+ root = (Path(xdg) if os.path.isabs(xdg) else Path.home() / ".config") / "ailands"
34
+ _adopt_legacy_home(root)
35
+ root.mkdir(parents=True, exist_ok=True)
36
+ root.chmod(stat.S_IRWXU)
37
+ return root
38
+
39
+
40
+ def _adopt_legacy_home(root: Path) -> None:
41
+ """Move a pre-0.4.0 `~/.ailands` into place. Moved, not copied or ignored: the
42
+ signing key in it is the one the platform knows this publisher by, and a fresh
43
+ key would publish as someone the platform has never seen."""
44
+ legacy = Path.home() / ".ailands"
45
+ if not legacy.is_dir():
46
+ return
47
+ if root.exists():
48
+ raise click.ClickException(
49
+ f"both {legacy} and {root} exist; keep the one whose signing-key your publisher "
50
+ "registered and remove the other"
51
+ )
52
+ root.parent.mkdir(parents=True, exist_ok=True)
53
+ legacy.rename(root)
54
+
55
+
56
+ def platform_url() -> str:
57
+ return os.environ.get("AILANDS_PLATFORM", DEFAULT_PLATFORM).rstrip("/")
58
+
59
+
60
+ def _credentials_path() -> Path:
61
+ return home() / "credentials.json"
62
+
63
+
64
+ def save_credentials(data: dict) -> None:
65
+ path = _credentials_path()
66
+ path.write_text(json.dumps(data, indent=2), encoding="utf-8")
67
+ path.chmod(stat.S_IRUSR | stat.S_IWUSR)
68
+
69
+
70
+ def load_credentials() -> dict:
71
+ path = _credentials_path()
72
+ if not path.exists():
73
+ return {}
74
+ try:
75
+ return json.loads(path.read_text(encoding="utf-8"))
76
+ except json.JSONDecodeError:
77
+ return {}
78
+
79
+
80
+ def access_token() -> str:
81
+ return str(load_credentials().get("access_token") or "")
82
+
83
+
84
+ def signing_key() -> tuple[str, str]:
85
+ """This machine's (private_b64, public_b64), generating one on first use.
86
+
87
+ Generated rather than prompted for: a key the developer has to create by hand
88
+ is a key most people will skip, and the whole publisher-attribution chain
89
+ rests on there being one. Written 0600 and never uploaded.
90
+ """
91
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
92
+
93
+ path = home() / "signing-key"
94
+ if path.exists():
95
+ private = Ed25519PrivateKey.from_private_bytes(base64.b64decode(path.read_text().strip()))
96
+ else:
97
+ private = Ed25519PrivateKey.generate()
98
+ path.write_text(base64.b64encode(private.private_bytes_raw()).decode(), encoding="utf-8")
99
+ path.chmod(stat.S_IRUSR | stat.S_IWUSR)
100
+ return (
101
+ base64.b64encode(private.private_bytes_raw()).decode(),
102
+ base64.b64encode(private.public_key().public_bytes_raw()).decode(),
103
+ )
ailands/pack.py ADDED
@@ -0,0 +1,86 @@
1
+ """Turning a directory into a publishable, signed bundle.
2
+
3
+ The format is a gzipped tar of the agent directory with a detached
4
+ `manifest.yaml.sig` at its root — the same bytes the platform verifies on publish
5
+ and the same layout a kernel unpacks on install. Deliberately boring: an author
6
+ should be able to look at what they are shipping.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import io
13
+ import tarfile
14
+ from pathlib import Path
15
+
16
+ #: Never ship these. Not a security control — a bundle is signed and reviewed —
17
+ #: but a build that silently packed a `.venv` or a `.git` would produce a
18
+ #: hundred-megabyte upload and a rejection nobody could explain.
19
+ _SKIP_DIRS = {
20
+ ".git",
21
+ ".venv",
22
+ "venv",
23
+ "__pycache__",
24
+ "node_modules",
25
+ ".mypy_cache",
26
+ ".pytest_cache",
27
+ }
28
+ _SKIP_SUFFIXES = {".pyc", ".pyo"}
29
+
30
+
31
+ class PackError(Exception):
32
+ """The directory is not a publishable agent."""
33
+
34
+
35
+ def _included(path: Path, root: Path) -> bool:
36
+ rel = path.relative_to(root)
37
+ if any(part in _SKIP_DIRS for part in rel.parts):
38
+ return False
39
+ return path.suffix not in _SKIP_SUFFIXES
40
+
41
+
42
+ def sign_manifest(manifest_bytes: bytes, private_key_b64: str) -> str:
43
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
44
+
45
+ private = Ed25519PrivateKey.from_private_bytes(base64.b64decode(private_key_b64))
46
+ return base64.b64encode(private.sign(manifest_bytes)).decode()
47
+
48
+
49
+ def build(agent_dir: str | Path, private_key_b64: str) -> tuple[bytes, dict]:
50
+ """Sign the manifest and return `(tarball, {id, version, publisher})`.
51
+
52
+ The manifest is read as BYTES and signed as bytes, never re-serialized from
53
+ parsed YAML: a round trip through a parser can reorder keys or normalize
54
+ quoting, and then the signature covers text nobody will ever see again.
55
+ """
56
+ root = Path(agent_dir).resolve()
57
+ manifest_path = root / "manifest.yaml"
58
+ if not manifest_path.is_file():
59
+ raise PackError(f"{root} has no manifest.yaml — is this an agent directory?")
60
+ manifest_bytes = manifest_path.read_bytes()
61
+
62
+ import yaml
63
+
64
+ try:
65
+ parsed = yaml.safe_load(manifest_bytes.decode("utf-8")) or {}
66
+ except yaml.YAMLError as exc:
67
+ raise PackError(f"manifest.yaml does not parse: {exc}") from exc
68
+ for required in ("id", "version", "publisher"):
69
+ if not parsed.get(required):
70
+ raise PackError(f"manifest.yaml must declare `{required}` before publishing")
71
+
72
+ signature = sign_manifest(manifest_bytes, private_key_b64)
73
+ buf = io.BytesIO()
74
+ with tarfile.open(fileobj=buf, mode="w:gz") as tar:
75
+ for path in sorted(root.rglob("*")):
76
+ if path.is_file() and _included(path, root):
77
+ tar.add(path, arcname=str(path.relative_to(root)))
78
+ raw = signature.encode("utf-8")
79
+ info = tarfile.TarInfo(name="manifest.yaml.sig")
80
+ info.size = len(raw)
81
+ tar.addfile(info, io.BytesIO(raw))
82
+ return buf.getvalue(), {
83
+ "id": str(parsed["id"]),
84
+ "version": str(parsed["version"]),
85
+ "publisher": str(parsed["publisher"]),
86
+ }
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: ailands
3
+ Version: 0.5.2
4
+ Summary: Build and publish agents for Ailands.
5
+ Project-URL: Homepage, https://developers.ailands.app
6
+ Author-email: Jiaan Liu <jiaanliux@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: agent,ai,ailands
10
+ Requires-Python: >=3.11
11
+ Requires-Dist: aipelago-sdk==0.6.1
12
+ Requires-Dist: click==8.1.8
13
+ Requires-Dist: cryptography==44.0.0
14
+ Requires-Dist: httpx==0.28.1
15
+ Requires-Dist: pyyaml==6.0.2
16
+ Description-Content-Type: text/markdown
17
+
18
+ # ailands
19
+
20
+ Build and publish agents for [Ailands](https://ailands.app).
21
+
22
+ ```bash
23
+ pip install ailands
24
+ ailands login
25
+ ailands publisher create acme
26
+ ailands init my-agent
27
+ ailands publish my-agent # a draft — live for you alone
28
+ ailands submit my_agent 0.1.0 # ask for review
29
+ ailands status
30
+ ```
31
+
32
+ And in your agent's code (`pip install ailands` brings in the `aipelago-sdk` it
33
+ imports from):
34
+
35
+ ```python
36
+ from aipelago.sdk import tool, ToolContext
37
+
38
+ @tool("my_agent.hello")
39
+ async def hello(ctx: ToolContext, args: dict) -> dict:
40
+ return {"text": "hi"}
41
+ ```
42
+
43
+ A **draft** is installable by you and nobody else, so you can iterate against the
44
+ real platform before anyone reviews it. `ailands watch` republishes on save.
@@ -0,0 +1,9 @@
1
+ ailands/__init__.py,sha256=1XpWvz8ErU3AGb7M6df3Z1DDyX6TfQ9kdaIGSIwutXo,314
2
+ ailands/cli.py,sha256=GLWxRcHc6HOyQLFRL1d4B4BuGJ1YWfCJopWCfkU9oRk,16534
3
+ ailands/config.py,sha256=lRoF4YFnjEBpgrONLL83rvkSg3tE4iSvUSXYo3LNNa8,3433
4
+ ailands/pack.py,sha256=q5bc2L7uzI3jfPlZbBMId7rQrHqtzPCEUmnjFcbdnNc,3102
5
+ ailands-0.5.2.dist-info/METADATA,sha256=JHufQgPxuhI0RsT2ndTFY7V_T95QgYv4-u9zlMeHn8w,1216
6
+ ailands-0.5.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
+ ailands-0.5.2.dist-info/entry_points.txt,sha256=PoibeKbpqBOKy0OnG5OX4B1dApUqEEgg6Bcst16aK90,45
8
+ ailands-0.5.2.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
9
+ ailands-0.5.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ailands = ailands.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.