agent-instruction-protocol 0.7.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.
aip/client/cli.py ADDED
@@ -0,0 +1,702 @@
1
+ """The `aip` command line entry point.
2
+
3
+ Local: validate, schema, runtime (the block, or `--skill` for the `aip-runtime` meta-skill),
4
+ skill (install both skills into the agents on this machine), info, run, resume, db, server.
5
+ Against a configured server (`aip config`, or `AIP_SERVER`): search, list, publish, get, pin,
6
+ retire, runs, governance, and `info`/`run` by name. A folder path always bypasses the server.
7
+
8
+ Every client command is a wrapper over the SDK (`aip.Client`, `docs/sdk.md`): it parses its
9
+ arguments, calls one SDK method, and prints the result. schema, runtime and skill are the
10
+ format's tooling, db loads Neo4j directly, and server serves: none of them is a client call.
11
+ """
12
+
13
+ import argparse
14
+ import json
15
+ import sys
16
+ from pathlib import Path
17
+
18
+
19
+ def _emit(issues) -> tuple[int, int]:
20
+ errors = warnings = 0
21
+ for issue in issues:
22
+ print(json.dumps(issue.to_record()), file=sys.stderr)
23
+ if issue.severity == "warning":
24
+ warnings += 1
25
+ else:
26
+ errors += 1
27
+ return errors, warnings
28
+
29
+
30
+ def validate_command(argv: list[str]) -> int:
31
+ parser = argparse.ArgumentParser(prog="aip validate", description="Validate an AIP skill folder.")
32
+ parser.add_argument("skill_dir", type=Path, help="path to the skill folder (containing SKILL.md)")
33
+ args = parser.parse_args(argv)
34
+
35
+ result = _client().validate(args.skill_dir)
36
+ errors, warnings = _emit(result.issues)
37
+ suffix = f" ({warnings} warning(s) — see stderr)" if warnings else ""
38
+ if result.valid:
39
+ print(f"VALID: {args.skill_dir} (name: {result.name}){suffix}")
40
+ return 0
41
+ print(f"INVALID: {errors} error(s){suffix} — see stderr")
42
+ return 1
43
+
44
+
45
+ def schema_command(argv: list[str]) -> int:
46
+ from aip_spec import json_schema
47
+
48
+ parser = argparse.ArgumentParser(prog="aip schema", description="Print the JSON Schema generated from the format models.")
49
+ parser.add_argument("--write", type=Path, default=None, help="write to this path instead of stdout")
50
+ args = parser.parse_args(argv)
51
+
52
+ text = json.dumps(json_schema(), indent=2) + "\n"
53
+ if args.write:
54
+ args.write.write_text(text)
55
+ print(f"wrote {args.write}")
56
+ else:
57
+ sys.stdout.write(text)
58
+ return 0
59
+
60
+
61
+ def runtime_command(argv: list[str]) -> int:
62
+ from aip_spec import runtime_text
63
+
64
+ from aip.client import runtime_skill_text
65
+
66
+ parser = argparse.ArgumentParser(prog="aip runtime", description="Print the AIP runtime block every authored skill carries "
67
+ "at the top of its body; with --skill, the `aip-runtime` Agent Skill that tells an agent "
68
+ "how to run published procedures through this client.")
69
+ parser.add_argument("--skill", action="store_true", help="the `aip-runtime` meta-skill instead of the runtime block")
70
+ parser.add_argument("--out", type=Path, default=None, metavar="DIR",
71
+ help="with --skill: write it as DIR/aip-runtime/SKILL.md (a skills directory)")
72
+ parser.add_argument("--write", type=Path, default=None, help="write to this path instead of stdout")
73
+ args = parser.parse_args(argv)
74
+ if args.out is not None and not args.skill:
75
+ parser.error("--out goes with --skill; use --write for the runtime block")
76
+ text = runtime_skill_text() if args.skill else runtime_text()
77
+ target = args.out / "aip-runtime" / "SKILL.md" if args.out is not None else args.write
78
+ if target is not None:
79
+ target.parent.mkdir(parents=True, exist_ok=True)
80
+ target.write_text(text)
81
+ print(f"wrote {target}")
82
+ else:
83
+ sys.stdout.write(text)
84
+ return 0
85
+
86
+
87
+ def skill_command(argv: list[str]) -> int:
88
+ """Install, list, or remove the two AIP skills: the `aip-compile` authoring skill, bundled
89
+ in `aip-spec`, and the `aip-runtime` meta-skill, bundled here. Agent detection is
90
+ `aip_spec.agents`, the same catalog `aip-spec skill install` uses. `install` records what
91
+ it wrote and removes its own earlier folders that left the set; `prune` removes folders
92
+ under names this tool retired (the authoring skill's old `aip/`)."""
93
+ from aip_spec import agents, skill_dir
94
+ from aip_spec.cli import _prune
95
+ from aip_spec.resources import LEGACY_SKILL_NAMES, SKILL_ENTRIES as AUTHORING_ENTRIES, SKILL_NAME as AUTHORING
96
+
97
+ from aip.client import RUNTIME_SKILL, runtime_skill_dir
98
+
99
+ names = [AUTHORING, RUNTIME_SKILL]
100
+ parser = argparse.ArgumentParser(prog="aip skill", description=f"Install the AIP skills ({', '.join(names)}) "
101
+ "into the agents on this machine.")
102
+ sub = parser.add_subparsers(dest="action", required=True)
103
+ p = sub.add_parser("install", help="into every detected agent, one named agent, or a skills directory")
104
+ p.add_argument("agent", nargs="?", help=f"one of: {', '.join(agents.AGENTS)}")
105
+ p.add_argument("--path", type=Path, default=None, metavar="DIR", help="a skills directory; writes DIR/<skill>/ for each")
106
+ sub.add_parser("list", help="supported agents, whether each is detected, and which skills are installed")
107
+ p = sub.add_parser("remove", help="from one agent, or from every agent that has either skill")
108
+ p.add_argument("agent", nargs="?")
109
+ p.add_argument("--path", type=Path, default=None, metavar="DIR")
110
+ p = sub.add_parser("prune", help=f"remove skill folders installed under a retired name ({', '.join(LEGACY_SKILL_NAMES)}) "
111
+ "from every detected agent, one agent, or a skills directory")
112
+ p.add_argument("agent", nargs="?")
113
+ p.add_argument("--path", type=Path, default=None, metavar="DIR")
114
+ p.add_argument("--dry-run", action="store_true", help="report what would be removed, remove nothing")
115
+ args = parser.parse_args(argv)
116
+
117
+ if args.action == "list":
118
+ print(agents.table(names))
119
+ return 0
120
+ if args.action == "prune":
121
+ return _prune(args, "aip skill prune")
122
+ try:
123
+ if args.action == "install":
124
+ sources = [(skill_dir(), AUTHORING_ENTRIES), (runtime_skill_dir(), ("SKILL.md",))]
125
+ written, removed = agents.install(sources, args.agent, args.path, tool="aip")
126
+ for label, folder in written:
127
+ print(f"installed {folder.name} -> {folder} ({label})")
128
+ for folder in removed:
129
+ print(f"removed {folder} (installed by an earlier aip, no longer one of its skills)")
130
+ return 0
131
+ removed = agents.remove(names, args.agent, args.path)
132
+ for folder in removed:
133
+ print(f"removed {folder}")
134
+ if not removed:
135
+ print(f"neither {' nor '.join(names)} is installed anywhere `aip skill list` looks")
136
+ return 0
137
+ except (KeyError, agents.NoAgentDetected) as exc:
138
+ print(f"aip skill: {exc.args[0]}", file=sys.stderr)
139
+ return 1
140
+
141
+
142
+ def _server():
143
+ """The configured server, or None. One seam for tests to point at an in-process app."""
144
+ from aip.client.server import configured
145
+
146
+ return configured()
147
+
148
+
149
+ def _client():
150
+ """The SDK client every command is a wrapper over, on `_server()`."""
151
+ from aip.sdk import Client
152
+
153
+ return Client.over(_server())
154
+
155
+
156
+ def _serving(call):
157
+ """Run a client action. A server error becomes one line on stderr and exit 1; no server, or a
158
+ name that is not a folder, exits with the message."""
159
+ from aip.sdk import InvalidInput, NoServer, NotFound, ServerError
160
+
161
+ try:
162
+ return call()
163
+ except ServerError as exc:
164
+ print(f"aip: {exc}", file=sys.stderr)
165
+ return 1
166
+ except (NoServer, NotFound, InvalidInput) as exc:
167
+ raise SystemExit(f"aip: {exc}") from exc
168
+
169
+
170
+ def info_command(argv: list[str]) -> int:
171
+ from aip.sdk import InvalidSkill
172
+
173
+ parser = argparse.ArgumentParser(prog="aip info", description="Describe a skill: what it does, the input it expects, and how it flows.")
174
+ parser.add_argument("skill", metavar="skill_dir|name", help="a skill folder, or a published name (`name`, `name@rev`, `name@latest`)")
175
+ parser.add_argument("--json", action="store_true", help="machine-readable description instead of the summary")
176
+ parser.add_argument("--example-input", action="store_true", help="print only an example start input as JSON")
177
+ args = parser.parse_args(argv)
178
+
179
+ def go() -> int:
180
+ try:
181
+ info = _client().info(args.skill)
182
+ if args.json:
183
+ print(json.dumps(info.data, indent=2))
184
+ elif args.example_input:
185
+ print(json.dumps(info.example_input, indent=2))
186
+ else:
187
+ sys.stdout.write(info.summary())
188
+ except InvalidSkill as exc:
189
+ print(exc, file=sys.stderr)
190
+ return 1
191
+ return 0
192
+ return _serving(go)
193
+
194
+
195
+ class _BadInput(ValueError):
196
+ """`--input` is not a readable JSON object."""
197
+
198
+
199
+ def _read_input(spec: str | None) -> dict | None:
200
+ """`--input path.json`, `--input -` for stdin, or None."""
201
+ if spec is None:
202
+ return None
203
+ try:
204
+ text = sys.stdin.read() if spec == "-" else Path(spec).read_text()
205
+ data = json.loads(text)
206
+ except (OSError, ValueError) as exc:
207
+ raise _BadInput(f"--input {spec}: {exc}") from exc
208
+ if not isinstance(data, dict):
209
+ raise _BadInput(f"--input {spec}: must be a JSON object, got {type(data).__name__}")
210
+ return data
211
+
212
+
213
+ def _outcome(call, debug: bool, progress: bool) -> int:
214
+ """`run` and `resume`: whatever escapes the runner is still one error object on stdout, exit 1,
215
+ with the traceback on stderr only under --debug (`docs/cli-json.md`). A skill or run that
216
+ cannot be found, or an input that is not an object, is `invalid_input`."""
217
+ from aip.client.runner import EXIT_ERROR, error_object
218
+ from aip.sdk import AipError, ServerError
219
+
220
+ try:
221
+ return call()
222
+ except Exception as exc:
223
+ if debug:
224
+ import traceback
225
+ traceback.print_exception(exc, file=sys.stderr)
226
+ error = ({"error": "invalid_input", "step": None, "message": str(exc), "missing": [], "invalid": []}
227
+ if isinstance(exc, (_BadInput, AipError)) and not isinstance(exc, ServerError) else error_object(exc))
228
+ block = {**error, "run_id": None, "resumable": False}
229
+ print(json.dumps(block) if progress else json.dumps(block, indent=2))
230
+ return EXIT_ERROR
231
+
232
+
233
+ def _outcome_flags(parser: argparse.ArgumentParser) -> None:
234
+ parser.add_argument("--progress", action="store_true",
235
+ help="print one JSON line per completed step before the final object (itself one line)")
236
+ parser.add_argument("--debug", action="store_true", help="print a traceback on stderr when the run fails")
237
+
238
+
239
+ def run_command(argv: list[str]) -> int:
240
+ from aip.client.runner import Runner
241
+
242
+ parser = argparse.ArgumentParser(prog="aip run", description="Run a procedure, pausing when the client must decide: "
243
+ "a skill folder runs locally, a published name runs on the server. Prints one "
244
+ "JSON object: paused or done (exit 0), or error (exit 1); see docs/cli-json.md.")
245
+ parser.add_argument("skill", metavar="skill_dir|name")
246
+ parser.add_argument("--input", "-i", help="JSON object for the start step; `-` reads stdin")
247
+ parser.add_argument("--interactive", action="store_true", help="prompt on the terminal instead of pausing to a run file")
248
+ parser.add_argument("--run-file", type=Path, default=None,
249
+ help="where to write the run file (default ~/.aip/runs/<run-id>.json; AIP_HOME moves it)")
250
+ parser.add_argument("--workdir", type=Path, default=None,
251
+ help="the run's working directory, where its scripts read and write files (AIP_WORKDIR); "
252
+ "recorded in the run file so resume works from anywhere (default the current directory)")
253
+ _outcome_flags(parser)
254
+ args = parser.parse_args(argv)
255
+
256
+ def go() -> int:
257
+ client = _client()
258
+ payload = _read_input(args.input)
259
+ runner = Runner(None, interactive=args.interactive, progress=args.progress, debug=args.debug)
260
+ if payload is None and args.interactive:
261
+ payload = runner.start_input({"inputs": client.info(args.skill).inputs})
262
+ return runner.show(lambda on_step, on_pause: client.run(
263
+ args.skill, payload, workdir=args.workdir, run_file=args.run_file, on_step=on_step, on_pause=on_pause)).code
264
+ return _outcome(go, args.debug, args.progress)
265
+
266
+
267
+ def resume_command(argv: list[str]) -> int:
268
+ from aip.client.runner import RunFile, Runner
269
+
270
+ parser = argparse.ArgumentParser(prog="aip resume", description="Continue a run, locally or on the server the run "
271
+ "file names: answer its pause, or with no input retry the step that failed.")
272
+ parser.add_argument("run", metavar="run_id|run_file",
273
+ help="the run id every outcome prints, or a run file's path")
274
+ parser.add_argument("--input", "-i", help="JSON object answering the pause; `-` reads stdin")
275
+ parser.add_argument("--interactive", action="store_true")
276
+ _outcome_flags(parser)
277
+ args = parser.parse_args(argv)
278
+
279
+ def go() -> int:
280
+ client = _client()
281
+ payload = _read_input(args.input)
282
+ runner = Runner(None, interactive=args.interactive, progress=args.progress, debug=args.debug)
283
+ if payload is None and args.interactive:
284
+ pause = RunFile.load(client.run_file(args.run)).pause
285
+ if pause["kind"] not in ("error", "done"):
286
+ payload = runner.ask(pause)
287
+ return runner.show(lambda on_step, on_pause: client.resume(
288
+ args.run, payload, on_step=on_step, on_pause=on_pause)).code
289
+ return _outcome(go, args.debug, args.progress)
290
+
291
+
292
+ # ----------------------------------------------------------------------- catalog
293
+
294
+
295
+ def search_command(argv: list[str]) -> int:
296
+ parser = argparse.ArgumentParser(prog="aip search", description="Find published procedures by what they do; the ranking is the server's.")
297
+ parser.add_argument("query")
298
+ parser.add_argument("--limit", type=int, default=10)
299
+ parser.add_argument("--json", action="store_true")
300
+ args = parser.parse_args(argv)
301
+
302
+ def go() -> int:
303
+ hits = _client().search(args.query, args.limit)
304
+ if args.json:
305
+ print(json.dumps([h.data for h in hits], indent=2))
306
+ return 0
307
+ if not hits:
308
+ print("no matches")
309
+ return 0
310
+ for h in hits:
311
+ print(f"{h.name}@{h.revision} {h.score:.3f} {h.description or ''}".rstrip())
312
+ return 0
313
+ return _serving(go)
314
+
315
+
316
+ def list_command(argv: list[str]) -> int:
317
+ parser = argparse.ArgumentParser(prog="aip list", description="Every published name with the revision it resolves to.")
318
+ parser.add_argument("--json", action="store_true")
319
+ args = parser.parse_args(argv)
320
+
321
+ def go() -> int:
322
+ rows = _client().list()
323
+ if args.json:
324
+ print(json.dumps([r.data for r in rows], indent=2))
325
+ return 0
326
+ if not rows:
327
+ print("no skills published")
328
+ return 0
329
+ width = max(len(r.name) for r in rows)
330
+ for r in rows:
331
+ flag = " pinned" if r.pinned else ""
332
+ print(f"{r.name.ljust(width)} {r.resolves or '-'} {len(r.revisions)} revision(s){flag} {r.description or ''}".rstrip())
333
+ return 0
334
+ return _serving(go)
335
+
336
+
337
+ def publish_command(argv: list[str]) -> int:
338
+ from aip.sdk import InvalidSkill
339
+
340
+ parser = argparse.ArgumentParser(prog="aip publish", description="Validate a skill folder locally, upload it, and print `name@revision`.")
341
+ parser.add_argument("skill_dir", type=Path)
342
+ args = parser.parse_args(argv)
343
+
344
+ def go() -> int:
345
+ try:
346
+ result = _client().publish(args.skill_dir)
347
+ except InvalidSkill as exc:
348
+ errors, _ = _emit(exc.validation.issues)
349
+ print(f"INVALID: {errors} error(s) — not published", file=sys.stderr)
350
+ return 1
351
+ _emit(result.validation.issues)
352
+ for w in result.warnings:
353
+ print(json.dumps(w), file=sys.stderr)
354
+ print(f"{result.name}@{result.revision}")
355
+ return 0
356
+ return _serving(go)
357
+
358
+
359
+ def get_command(argv: list[str]) -> int:
360
+ parser = argparse.ArgumentParser(prog="aip get", description="Download a published revision losslessly to <out>/<name>/, "
361
+ "verify every file against the manifest, and validate it.")
362
+ parser.add_argument("ref", help="`name`, `name@rev`, or `name@latest`")
363
+ parser.add_argument("--out", type=Path, default=Path("."), help="parent folder; the skill lands at <out>/<name>")
364
+ args = parser.parse_args(argv)
365
+
366
+ def go() -> int:
367
+ fetched = _client().get(args.ref, args.out)
368
+ errors, _ = _emit(fetched.validation.issues)
369
+ if not fetched.validation.valid:
370
+ print(f"wrote {fetched.path}, but it does not validate here ({errors} error(s))", file=sys.stderr)
371
+ return 1
372
+ print(f"wrote {fetched.path}")
373
+ return 0
374
+ return _serving(go)
375
+
376
+
377
+ def pin_command(argv: list[str]) -> int:
378
+ parser = argparse.ArgumentParser(prog="aip pin", description="Make a name resolve to one revision; --clear removes the pin.")
379
+ parser.add_argument("name")
380
+ parser.add_argument("revision", nargs="?", default=None)
381
+ parser.add_argument("--clear", action="store_true")
382
+ args = parser.parse_args(argv)
383
+ if (args.revision is None) == (not args.clear):
384
+ parser.error("give a revision, or --clear")
385
+
386
+ def go() -> int:
387
+ pinned = _client().pin(args.name, None if args.clear else args.revision)
388
+ print(f"{pinned.name} pin cleared" if pinned.revision is None else f"{pinned.name} -> {pinned.revision}")
389
+ return 0
390
+ return _serving(go)
391
+
392
+
393
+ def retire_command(argv: list[str]) -> int:
394
+ parser = argparse.ArgumentParser(prog="aip retire", description="Stop a name resolving to a revision (kept for the runs that reference it).")
395
+ parser.add_argument("ref", help="`name@revision`")
396
+ args = parser.parse_args(argv)
397
+ _, sep, revision = args.ref.partition("@")
398
+ if not sep or not revision or revision == "latest":
399
+ parser.error("retire takes `name@revision`")
400
+
401
+ def go() -> int:
402
+ retired = _client().retire(args.ref)
403
+ print(f"retired {retired.name}@{retired.revision}")
404
+ return 0
405
+ return _serving(go)
406
+
407
+
408
+ def runs_command(argv: list[str]) -> int:
409
+ parser = argparse.ArgumentParser(prog="aip runs", description="The server's runs, newest first; with a run id, that "
410
+ "run's state and history (a local run's from its run file).")
411
+ parser.add_argument("run_id", nargs="?", default=None)
412
+ parser.add_argument("--name", default=None, help="only runs of this skill")
413
+ parser.add_argument("--status", default=None, help="only runs with this status (paused, done, failed, ...)")
414
+ parser.add_argument("--limit", type=int, default=50)
415
+ parser.add_argument("--json", action="store_true")
416
+ args = parser.parse_args(argv)
417
+
418
+ def go() -> int:
419
+ if args.run_id is not None:
420
+ print(json.dumps(_client().run_record(args.run_id).data, indent=2))
421
+ return 0
422
+ rows = _client().runs(args.name, args.status, args.limit)
423
+ if args.json:
424
+ print(json.dumps([r.data for r in rows], indent=2))
425
+ return 0
426
+ if not rows:
427
+ print("no runs")
428
+ return 0
429
+ for r in rows:
430
+ print(f"{r.run_id} {r.name}@{r.revision} {r.status} {r.steps} step(s) {r.updated_at}")
431
+ return 0
432
+ return _serving(go)
433
+
434
+
435
+ def governance_command(argv: list[str]) -> int:
436
+ parser = argparse.ArgumentParser(prog="aip governance", description="The server's governance queries; with a query, "
437
+ "its rows as JSON.")
438
+ parser.add_argument("query", nargs="?", default=None)
439
+ parser.add_argument("--name", default=None, help="only this skill")
440
+ parser.add_argument("--window", type=int, default=None, help="how many recent runs to look at")
441
+ parser.add_argument("--limit", type=int, default=None)
442
+ parser.add_argument("--repeats", type=int, default=None, help="repeated-cycles: more than this many times round")
443
+ args = parser.parse_args(argv)
444
+
445
+ def go() -> int:
446
+ rows = _client().governance(args.query, name=args.name, window=args.window, limit=args.limit,
447
+ repeats=args.repeats)
448
+ if args.query is None:
449
+ width = max((len(q.query) for q in rows), default=0)
450
+ for q in rows:
451
+ print(f"{q.query.ljust(width)} {q.description}")
452
+ return 0
453
+ print(json.dumps(rows, indent=2))
454
+ return 0
455
+ return _serving(go)
456
+
457
+
458
+ def config_command(argv: list[str]) -> int:
459
+ from aip.sdk import configure
460
+
461
+ parser = argparse.ArgumentParser(prog="aip config", description="Where the client points. With no flags, show it. "
462
+ "AIP_SERVER and AIP_TOKEN override the file.")
463
+ parser.add_argument("--server", default=None, help="the server URL")
464
+ parser.add_argument("--token", default=None, help="the bearer token")
465
+ parser.add_argument("--decision-model", default=None, metavar="KEY",
466
+ help="the TypeSafe API key this client resolves decisions with (TYPESAFE_API_KEY overrides; "
467
+ "an empty string forgets it). Without one, every decision pauses for you to answer")
468
+ parser.add_argument("--clear", action="store_true", help="forget the server, token, and decision-model key")
469
+ args = parser.parse_args(argv)
470
+ writes = args.clear or any(v is not None for v in (args.server, args.token, args.decision_model))
471
+ s = configure(args.server, args.token, args.decision_model, clear=args.clear)
472
+ if args.clear:
473
+ print(f"cleared {s.path}")
474
+ return 0
475
+ if writes:
476
+ print(f"wrote {s.path}")
477
+ if s.server is None:
478
+ print(f"no server configured (local folders only); set AIP_SERVER or `aip config --server URL` ({s.path})")
479
+ else:
480
+ print(f"server: {s.server} (from {s.source})")
481
+ print(f"token: {'set' if s.token_set else 'none'}")
482
+ print(s.decision_model)
483
+ return 0
484
+
485
+
486
+ def db_command(argv: list[str]) -> int:
487
+ """`aip db load|list|export`: the Neo4j backend, 0.4 shape. Connection from NEO4J_* env or flags."""
488
+ from aip.db.neo4j import Connection, export, list_skills, load
489
+
490
+ connection = argparse.ArgumentParser(add_help=False)
491
+ connection.add_argument("--uri", default=None, help="Neo4j URI; default $NEO4J_URI or neo4j://localhost:7687")
492
+ connection.add_argument("--user", default=None, help="default $NEO4J_USERNAME or neo4j")
493
+ connection.add_argument("--password", default=None, help="default $NEO4J_PASSWORD")
494
+ connection.add_argument("--database", default=None, help="default $NEO4J_DATABASE or neo4j")
495
+
496
+ parser = argparse.ArgumentParser(prog="aip db", description="Load skills into Neo4j losslessly, list them, export them back.")
497
+ sub = parser.add_subparsers(dest="op", required=True)
498
+ p_load = sub.add_parser("load", parents=[connection], help="validate a skill folder and write it to the database")
499
+ p_load.add_argument("skill_dir", type=Path)
500
+ sub.add_parser("list", parents=[connection], help="skills in the database, newest revision first")
501
+ p_export = sub.add_parser("export", parents=[connection], help="rebuild a skill folder from the database, byte for byte")
502
+ p_export.add_argument("name")
503
+ p_export.add_argument("--revision", default=None, help="a specific revision; default is the latest")
504
+ p_export.add_argument("--out", type=Path, default=Path("."), help="parent folder; the skill lands at <out>/<name>")
505
+ args = parser.parse_args(argv)
506
+
507
+ conn = Connection()
508
+ for attr, value in (("uri", args.uri), ("user", args.user), ("password", args.password), ("database", args.database)):
509
+ if value is not None:
510
+ setattr(conn, attr, value)
511
+
512
+ if args.op == "load":
513
+ try:
514
+ skill_id = load(args.skill_dir, conn)
515
+ except ValueError as exc:
516
+ print(exc, file=sys.stderr)
517
+ return 1
518
+ print(f"loaded {skill_id}")
519
+ return 0
520
+ if args.op == "list":
521
+ rows = list_skills(conn)
522
+ if not rows:
523
+ print("no skills loaded")
524
+ return 0
525
+ width = max(len(r["name"]) for r in rows)
526
+ for r in rows:
527
+ flags = "".join(f" {flag}" for flag, on in (("pinned", r.get("pinned")), ("retired", r.get("retired"))) if on)
528
+ print(f"{r['name'].ljust(width)} {r['revision']} aip {r['aip_version']} {r['steps']} steps "
529
+ f"{r['files']} files {r['published_at']}{flags}")
530
+ return 0
531
+ try:
532
+ target = export(args.name, args.out, revision=args.revision, conn=conn)
533
+ except KeyError as exc:
534
+ print(f"aip: {exc}", file=sys.stderr)
535
+ return 1
536
+ print(f"exported {target}")
537
+ return 0
538
+
539
+
540
+ def server_command(argv: list[str]) -> int:
541
+ """`aip server`: the HTTP API over the filesystem or Neo4j backend. Scripts run in this process."""
542
+ from aip.server.config import (CONFIG_ENV, CONFIG_FILE, DEFAULT_ROOT, ENV_FILE, EXAMPLE, ConfigError, apply_config,
543
+ find_config, load_env_file, read_config, user_config_path, write_example)
544
+
545
+ parser = argparse.ArgumentParser(prog="aip server", description="Serve the AIP catalog and execution API.",
546
+ epilog="Configuration, highest precedence first: these flags, the environment "
547
+ "(NEO4J_*; a .env file is loaded into it), the config file, "
548
+ "defaults. `--example-config` prints a complete file. The server runs no "
549
+ "scripts and holds no decision-model key: clients run scripts and resolve "
550
+ "decisions (`aip config --decision-model`), and the server records them. "
551
+ "Without --token the server is open; keep --host on localhost.")
552
+ parser.add_argument("--config", type=Path, default=None, metavar="FILE",
553
+ help=f"TOML config file (default ${CONFIG_ENV}, else ./{CONFIG_FILE}, else "
554
+ f"{user_config_path()})")
555
+ parser.add_argument("--init", nargs="?", const=True, default=None, metavar="FILE",
556
+ help=f"write a complete config file to edit, to {user_config_path()} or FILE, and exit")
557
+ parser.add_argument("--env-file", type=Path, default=None, metavar="FILE",
558
+ help=f"KEY=value file loaded into the environment without overriding it (default ./{ENV_FILE} if present)")
559
+ parser.add_argument("--example-config", action="store_true", help=f"print a complete {CONFIG_FILE} and exit")
560
+ parser.add_argument("--backend", choices=["filesystem", "neo4j"], default="filesystem")
561
+ parser.add_argument("--root", type=Path, default=None, help=f"filesystem backend: the root directory (default {DEFAULT_ROOT})")
562
+ parser.add_argument("--uri", default=None, help="neo4j backend: bolt URI; default $NEO4J_URI or neo4j://localhost:7687")
563
+ parser.add_argument("--user", default=None, help="neo4j: default $NEO4J_USERNAME or neo4j")
564
+ parser.add_argument("--password", default=None, help="neo4j: default $NEO4J_PASSWORD")
565
+ parser.add_argument("--database", default=None, help="neo4j: default $NEO4J_DATABASE or neo4j")
566
+ parser.add_argument("--cache-dir", type=Path, default=None, help="neo4j: where revisions are materialised (default ~/.cache/aip)")
567
+ parser.add_argument("--host", default="127.0.0.1")
568
+ parser.add_argument("--port", type=int, default=8000)
569
+ parser.add_argument("--token", default=None, help="bearer token granting the read and publish scopes")
570
+ parser.add_argument("--read-token", default=None, help="bearer token granting the read scope only")
571
+ parser.add_argument("--no-localhost", action="store_true", help="require a token from loopback clients too")
572
+ parser.add_argument("--allow-origin", action="append", default=None, metavar="ORIGIN",
573
+ help="a web origin whose pages may call this server (CORS); repeatable. Loopback origins, "
574
+ "where the console runs, always may")
575
+ parser.add_argument("--log-level", default="info")
576
+
577
+ # Files first, so their values become the defaults the flags override.
578
+ pre, _ = parser.parse_known_args(argv)
579
+ if pre.example_config:
580
+ print(EXAMPLE, end="")
581
+ return 0
582
+ if pre.init is not None:
583
+ target = user_config_path() if pre.init is True else Path(pre.init)
584
+ try:
585
+ write_example(target)
586
+ except ConfigError as exc:
587
+ print(f"aip server: {exc}", file=sys.stderr)
588
+ return 1
589
+ print(f"wrote {target}\nedit it (the backend, the tokens), then run: aip server")
590
+ return 0
591
+ env_file = pre.env_file if pre.env_file is not None else (Path(ENV_FILE) if Path(ENV_FILE).is_file() else None)
592
+ config_file = find_config(pre.config)
593
+ loaded: list[str] = []
594
+ try:
595
+ if env_file is not None:
596
+ applied = load_env_file(env_file)
597
+ loaded.append(f"{env_file} ({len(applied)} set)")
598
+ if config_file is not None:
599
+ parser.set_defaults(**apply_config(read_config(config_file)))
600
+ loaded.append(str(config_file))
601
+ except ConfigError as exc:
602
+ print(f"aip server: {exc}", file=sys.stderr)
603
+ return 1
604
+ args = parser.parse_args(argv)
605
+
606
+ try:
607
+ import uvicorn
608
+ from aip.server.app import create_app
609
+ except ImportError:
610
+ print("aip server needs the server extra: `uv sync --extra server` (or `pip install 'aip[server]'`)", file=sys.stderr)
611
+ return 1
612
+
613
+ if args.backend == "filesystem":
614
+ from aip.server.backends.filesystem import FilesystemBackend
615
+ root = args.root or DEFAULT_ROOT.expanduser()
616
+ backend = FilesystemBackend(root)
617
+ where = f"filesystem backend at {root.resolve()}"
618
+ else:
619
+ from aip.server.backends.neo4j import Connection, Neo4jBackend
620
+ conn = Connection()
621
+ for attr, value in (("uri", args.uri), ("user", args.user), ("password", args.password), ("database", args.database)):
622
+ if value is not None:
623
+ setattr(conn, attr, value)
624
+ try:
625
+ backend = Neo4jBackend(conn, cache_dir=args.cache_dir)
626
+ except Exception as exc: # driver missing, unreachable, bad credentials
627
+ print(f"aip server: cannot open the neo4j backend at {conn.uri}: {exc}", file=sys.stderr)
628
+ return 1
629
+ where = f"neo4j backend at {conn.uri}"
630
+
631
+ tokens = {}
632
+ if args.token:
633
+ tokens[args.token] = {"read", "publish"}
634
+ if args.read_token:
635
+ tokens[args.read_token] = {"read"}
636
+ if not tokens and args.host not in ("127.0.0.1", "localhost", "::1"):
637
+ print(f"aip server: warning: listening on {args.host} with no --token; anyone who can reach it can publish "
638
+ "and execute code here", file=sys.stderr)
639
+ app = create_app(backend, tokens=tokens, localhost_open=not args.no_localhost, allow_origins=args.allow_origin)
640
+ if loaded:
641
+ print(f"aip server: configured from {', '.join(loaded)}", file=sys.stderr)
642
+ print(f"aip server: {where}; http://{args.host}:{args.port}", file=sys.stderr)
643
+ if tokens:
644
+ print(f"aip server: {len(tokens)} bearer token(s); loopback clients "
645
+ f"{'need one too' if args.no_localhost else 'need none'}", file=sys.stderr)
646
+ try:
647
+ uvicorn.run(app, host=args.host, port=args.port, log_level=args.log_level)
648
+ finally:
649
+ if hasattr(backend, "close"):
650
+ backend.close()
651
+ return 0
652
+
653
+
654
+ COMMANDS = {
655
+ "validate": validate_command,
656
+ "schema": schema_command,
657
+ "runtime": runtime_command,
658
+ "skill": skill_command,
659
+ "info": info_command,
660
+ "run": run_command,
661
+ "resume": resume_command,
662
+ "search": search_command,
663
+ "list": list_command,
664
+ "publish": publish_command,
665
+ "get": get_command,
666
+ "pin": pin_command,
667
+ "retire": retire_command,
668
+ "runs": runs_command,
669
+ "governance": governance_command,
670
+ "config": config_command,
671
+ "db": db_command,
672
+ "server": server_command,
673
+ }
674
+
675
+
676
+ def version_line() -> str:
677
+ """`aip --version`: `aip <version> format <format>` on one line, which the console checks at startup."""
678
+ import aip
679
+ from aip.spec import FORMAT_VERSION
680
+
681
+ return f"aip {aip.__version__} format {FORMAT_VERSION}"
682
+
683
+
684
+ def main(argv: list[str] | None = None) -> int:
685
+ argv = sys.argv[1:] if argv is None else argv
686
+ if argv and argv[0] == "--version":
687
+ print(version_line())
688
+ return 0
689
+ if not argv or argv[0] in ("-h", "--help"):
690
+ print("usage: aip <command> [args]\n aip --version\n\ncommands:\n " + "\n ".join(COMMANDS)
691
+ + "\n\n`info` and `run` take a skill folder, or a published name when a server is configured "
692
+ "(`aip config`, or AIP_SERVER).")
693
+ return 0
694
+ command, rest = argv[0], argv[1:]
695
+ if command in COMMANDS:
696
+ return COMMANDS[command](rest)
697
+ print(f"aip: unknown command {command!r}", file=sys.stderr)
698
+ return 2
699
+
700
+
701
+ if __name__ == "__main__":
702
+ raise SystemExit(main())