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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
aip/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """AIP: Agent Instruction Protocol runtime, server, and client. `aip.Client` is the SDK (`docs/sdk.md`)."""
2
+
3
+ from importlib.metadata import version as _version
4
+
5
+ __version__ = _version("agent-instruction-protocol") # the distribution; the module and command stay `aip`
6
+
7
+ from aip.errors import AipError
8
+ from aip.sdk import (
9
+ Client, Done, InvalidInput, InvalidSkill, NoServer, NotFound, Paused, RunError, ServerError, configure, settings,
10
+ )
11
+
12
+ __all__ = [
13
+ "AipError", "Client", "Done", "InvalidInput", "InvalidSkill", "NoServer", "NotFound", "Paused", "RunError",
14
+ "ServerError", "configure", "settings",
15
+ ]
aip/client/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ """Client: HTTP api, run/resume runner, and the `aip` CLI."""
2
+
3
+ from pathlib import Path
4
+
5
+ # The `aip-runtime` meta-skill: the one page an agent reads to run published procedures
6
+ # through this client. A plain Agent Skill, versioned with the format; the repo copy is
7
+ # `skills/aip-runtime/SKILL.md` and a test keeps the two identical.
8
+ RUNTIME_SKILL = "aip-runtime"
9
+
10
+
11
+ def runtime_skill_dir() -> Path:
12
+ """The bundled `aip-runtime/` folder (`SKILL.md` only), what `aip skill install` copies."""
13
+ from importlib.resources import files
14
+
15
+ return Path(str(files("aip.client").joinpath(RUNTIME_SKILL)))
16
+
17
+
18
+ def runtime_skill_text() -> str:
19
+ """The text of the bundled `aip-runtime` skill (`aip runtime --skill` prints it)."""
20
+ return (runtime_skill_dir() / "SKILL.md").read_text(encoding="utf-8")
@@ -0,0 +1,117 @@
1
+ ---
2
+ name: aip-runtime
3
+ description: Run published AIP procedures (runbooks, step-by-step workflows) from an AIP server with the `aip` command. Use when a task might match a known procedure, runbook, or workflow, when the user mentions aip or AIP, or when AIP_SERVER is set; search the catalog first, then run the match and answer its pauses instead of doing the steps by hand.
4
+ license: Apache-2.0
5
+ metadata:
6
+ aip-version: "0.6a1"
7
+ ---
8
+
9
+ # Running AIP procedures
10
+
11
+ An AIP procedure is a graph of typed steps that `aip` and its server run: scripts, decisions,
12
+ routers, and tasks it hands back to you. You find the procedure, give it its start input,
13
+ and answer when it pauses. You never execute its steps yourself.
14
+
15
+ ## Check once
16
+
17
+ ```
18
+ aip --help # the client is installed
19
+ aip config # prints `server: <url>`; else set AIP_SERVER=http://host:port
20
+ # and `decision model: TypeSafe` or `none`
21
+ ```
22
+
23
+ No server and no `aip`: this skill does not apply; do the task as you normally would.
24
+ A skill folder on disk (`aip run <folder>`) runs locally with the same loop below.
25
+
26
+ ## The loop
27
+
28
+ 1. **Search** whenever the task might match a known procedure. Use the task's own words.
29
+
30
+ ```
31
+ aip search "<a few words from the task>" # name@revision score description
32
+ ```
33
+
34
+ Read the descriptions. Pick the one that says it is for this task, or none; a high
35
+ score alone is not a match. `aip list` shows every published name.
36
+
37
+ 2. **Inspect** the match. `info` is all you need to read; do not fetch its SKILL.md.
38
+
39
+ ```
40
+ aip info <name> # purpose, when to use, start input, steps, result
41
+ aip info <name> --example-input # a JSON object with every start key, example values
42
+ ```
43
+
44
+ Write the start input to a file, replacing the example values with the task's real
45
+ ones. Keys and types must match the START INPUT table.
46
+
47
+ 3. **Run** it.
48
+
49
+ ```
50
+ aip run <name> --input start.json
51
+ ```
52
+
53
+ It prints one JSON object. Exit 0 with `"done": true`: finished, `state` is the result.
54
+ Exit 0 with `"paused"`: answer it (step 4). Exit 1 with `"error"`: see step 5.
55
+
56
+ 4. **Answer** each pause by its `paused` kind: write the answer as a JSON object and run
57
+ `aip resume <run_id> --input answer.json`. Repeat until `"done": true`.
58
+
59
+ | `paused` | what the pause carries | what you put in the answer file |
60
+ |---------------|------------------------------------------------------|--------------------------------------------------------------------|
61
+ | `decision` | `questions` (`type`, `instructions`, `criteria`) and `state`: no decision model here | one key per question: `true`/`false` for `noul`, a `criteria` label for `choice`, the level number (list position from 0) for `score`; judge from `state` |
62
+ | `review` | `proposed_answers` from this machine's decision model, and `review`: the ones under their confidence threshold | only the keys you override, e.g. `{"tone": "calm"}`; `{}` accepts every proposed answer |
63
+ | `client_task` | `task`: what to do; `state`; `references`; `answer_with` | the work product under every key in `answer_with`, with those types |
64
+
65
+ `state` is only what this step needs. The run holds the rest (the server, for a published
66
+ procedure) and your answer is merged over it, so send only the keys asked for. Load a `references` entry only if the
67
+ task says you need it.
68
+
69
+ 5. **On an error**, read `error`, `step` and `message`. `invalid_input` / `invalid_output`
70
+ name the keys in `missing` and `invalid`: fix your input or answer and resume again (a
71
+ bad answer leaves the pause in place). `script_failed` carries the script's `exit_code`
72
+ and `stderr`; if `resumable` is true, `aip resume <run_id>` with no input retries that
73
+ step once the cause is fixed. `requires_unmet` lists in `missing` what the machine running
74
+ the scripts lacks; install it if you may, then retry the same way. Otherwise report the error.
75
+
76
+ ## Rules
77
+
78
+ - **Do not do the steps by hand** when the procedure can run them. The scripts, routing,
79
+ and validation are the procedure; your job is the pauses and the final result.
80
+ - **Scripts run here, on this machine,** for a published procedure too: `aip` fetches them
81
+ from the server and runs them itself. Files they read and write are relative to the run's
82
+ working directory, the directory `aip run` started in (or `--workdir`), kept for `resume`.
83
+ - **Decisions are resolved here too.** With a TypeSafe key on this machine (`TYPESAFE_API_KEY`,
84
+ or `aip config --decision-model KEY`) `aip` asks the model and pauses only for a `review`;
85
+ without one every decision pauses as `decision` for you to answer. Either way the run's
86
+ history records who answered (`resolver`: `typesafe` or `manual`). Do not set a key unless asked.
87
+ - **One run, one run id.** Every outcome prints `run_id`; `aip resume <run_id>` finds the
88
+ run file (`run_file`, under `~/.aip/runs/`) from any directory and rewrites it. Do not edit it. Do not start a second run of the same task.
89
+ - **Report the result** from `state` (the end step's declared keys) in the task's terms,
90
+ and say which procedure ran, by name. What each step produced is in the run's history:
91
+ on the server for a published procedure (`GET /runs/<run_id>`), in the run file's
92
+ `history` for a folder. If the run stops with an error you cannot fix, report the
93
+ error; do not improvise the remaining steps.
94
+ - **Do not publish, pin, or retire** anything unless asked; those change the catalog for
95
+ everyone.
96
+
97
+ ## Example
98
+
99
+ Task: "A customer wrote: I was charged twice! Handle it."
100
+
101
+ ```
102
+ $ aip search "customer charged twice billing"
103
+ billing-support@124d4a7b6208abed 0.812 Triage an inbound billing message ...
104
+ $ aip info billing-support --example-input > start.json # edit: real message
105
+ $ aip run billing-support --input start.json
106
+ { "paused": "decision", "step": "triage",
107
+ "questions": { "billing": {"type": "noul", ...}, "tone": {"type": "choice", "criteria": {"angry": ..., "calm": ...}} },
108
+ "state": { "message": "I was charged twice!" },
109
+ "run_id": "4f1c9a2e7b3d5068", "run_file": "~/.aip/runs/4f1c9a2e7b3d5068.json" }
110
+ $ echo '{"billing": true, "tone": "angry"}' > answer.json
111
+ $ aip resume 4f1c9a2e7b3d5068 --input answer.json
112
+ { "done": true, "run_id": "4f1c9a2e7b3d5068", "state": { "message": "I was charged twice!" }, "run_file": "..." }
113
+ ```
114
+
115
+ The angry branch ran the procedure's script here and opened the ticket (its `ticket_id` is in
116
+ the run's history); you answered one pause. The calm branch would instead pause with
117
+ `client_task` asking you to draft the reply, and your `{"reply": "..."}` would end the run.
aip/client/backend.py ADDED
@@ -0,0 +1,306 @@
1
+ """What the runner talks to. One method shape, two homes.
2
+
3
+ `LocalBackend` steps a Procedure in-process with `aip.model.engine`, which is what
4
+ `aip run <skill-dir>` uses; the run's cursor (state, history, pause) lives in the run file.
5
+ `HttpBackend` opens and continues the run on an AIP server (`POST /runs`,
6
+ `POST /runs/{id}/result`); the server holds the cursor, and the run file only the run's id,
7
+ server, revision, version and pending pause.
8
+
9
+ Both answer `open(payload)` and `submit(run, answer)` with a `Step`: the outcome object the
10
+ CLI prints (without `run_id` and `run_file`), the `--progress` lines, and what to write to the
11
+ run file, so the runner does not know which one it has.
12
+
13
+ Either way this process runs the scripts (`aip.client.executor`): the loop stops at each
14
+ execution step with a request, the client runs the script next to its data, from the skill
15
+ folder or the revision's cached `scripts/` and `assets/`, with the run's working directory
16
+ (`workdir`, recorded in the run file) as `AIP_WORKDIR`, and carries the report back to the loop.
17
+
18
+ And either way this process resolves the decisions (`aip.client.resolver`): the loop stops at
19
+ each decision, and with a decision model configured on this client the answers go back with
20
+ their attribution, or the run pauses for review, a pause only the client holds (the loop still
21
+ waits at the decision); the agent's answer to the review, or to a decision with no model,
22
+ goes back the same way.
23
+ """
24
+
25
+ import time
26
+ from dataclasses import dataclass, field
27
+ from pathlib import Path
28
+ from typing import Any, Dict, List, Protocol
29
+
30
+ JSON = Dict[str, Any]
31
+
32
+
33
+ @dataclass
34
+ class Step:
35
+ """Where a run stopped after one call.
36
+
37
+ outcome: `{"paused": kind, ...}`, `{"done": true, "state"}`, or `{"error": kind, ...}`
38
+ lines: the `--progress` line of every step the call completed
39
+ run: the run file to write; None when there is nothing to keep (the start input was
40
+ rejected before any step ran) or when the run did not move (`kept`)
41
+ kept: an answer that does not fit its pause: the pause stands and the run file is unchanged
42
+ run_id: the run's id
43
+ exc: the exception behind an error, for `--debug`
44
+ """
45
+ outcome: JSON
46
+ lines: List[JSON] = field(default_factory=list)
47
+ run: Any = None
48
+ kept: bool = False
49
+ run_id: str | None = None
50
+ exc: BaseException | None = None
51
+
52
+ @property
53
+ def resumable(self) -> bool:
54
+ return self.kept or self.run is not None
55
+
56
+
57
+ class Backend(Protocol):
58
+ def describe(self) -> JSON: ...
59
+
60
+ def open(self, payload: JSON) -> Step:
61
+ """Start a run on the start input and step it until it stops."""
62
+
63
+ def submit(self, run: Any, answer: JSON | None) -> Step:
64
+ """Carry the answer to the run's pause, or (None, at a failed step) retry the step."""
65
+
66
+
67
+ def _workdir(workdir: Path | str | None) -> Path:
68
+ return Path(workdir if workdir is not None else Path.cwd()).resolve()
69
+
70
+
71
+ class LocalBackend:
72
+ """`workdir` is the run's working directory, where its scripts read and write files (default
73
+ the current directory)."""
74
+
75
+ def __init__(self, skill_dir: Path, client: Any = None, python: Path | None = None,
76
+ workdir: Path | str | None = None):
77
+ """`client` is an injected decision-model client (tests); otherwise the configured key decides."""
78
+ from aip.client.executor import Executor
79
+ from aip.client.resolver import Resolver
80
+ from aip.spec.loader import load_procedure
81
+
82
+ self.skill_dir = Path(skill_dir)
83
+ self.procedure = load_procedure(self.skill_dir, python=python)
84
+ self.resolver = Resolver.configured(client)
85
+ self.workdir = _workdir(workdir)
86
+ self.executor = Executor(self.skill_dir, self.workdir, python)
87
+
88
+ def describe(self) -> JSON:
89
+ return self.procedure.describe()
90
+
91
+ def open(self, payload: JSON, run_id: str | None = None) -> Step:
92
+ from aip.client.runner import new_run_id
93
+ from aip.model import engine
94
+
95
+ advance = engine.start(self.procedure, payload, scripts=False)
96
+ return self._step(self._perform(advance), run_id or new_run_id())
97
+
98
+ def submit(self, run: Any, answer: JSON | None) -> Step:
99
+ from aip.client.resolver import reviewed
100
+ from aip.model import engine
101
+ from aip.model.engine import Advance, Cursor, error_object
102
+ from aip.model.types import OutputValidationError
103
+
104
+ if getattr(run, "workdir", None):
105
+ self.executor.workdir = Path(run.workdir)
106
+ cursor = Cursor(run.after, run.state, run.history, run.pause)
107
+ kind = run.pause.get("kind")
108
+ if kind == "execute" and answer is None:
109
+ advance = engine.submit(self.procedure, cursor, self.executor.perform(run.pause), scripts=False)
110
+ elif kind == "decision" and answer is None and self.resolver is not None:
111
+ advance = Advance(cursor) # resolve it now
112
+ elif kind == "review":
113
+ try:
114
+ decided = reviewed(run.pause, answer)
115
+ except OutputValidationError as exc:
116
+ return Step(error_object(exc), kept=True, run_id=run.run_id, exc=exc)
117
+ cursor.pause = {"kind": "decision", "step": run.pause["step"]}
118
+ advance = engine.submit(self.procedure, cursor, decided["answer"], scripts=False,
119
+ attribution=decided["attribution"])
120
+ else:
121
+ advance = engine.submit(self.procedure, cursor, answer, scripts=False)
122
+ return self._step(self._perform(advance), run.run_id, created=run.created)
123
+
124
+ def _perform(self, advance: Any) -> Any:
125
+ """Run each script the loop stops at, here, and resolve each decision with the decision
126
+ model, carrying the result back, until the run stops for something else (a review is
127
+ one); the lines of every call, in order. A decision model that fails leaves the run
128
+ waiting at the decision: `resume` asks again."""
129
+ from aip.model import engine
130
+ from aip.model.engine import Advance, error_object
131
+
132
+ lines = list(advance.lines)
133
+ while advance.error is None and advance.cursor is not None:
134
+ pause = advance.cursor.pause
135
+ if pause["kind"] == "execute":
136
+ advance = engine.submit(self.procedure, advance.cursor, self.executor.perform(pause), scripts=False)
137
+ elif pause["kind"] == "decision" and self.resolver is not None:
138
+ try:
139
+ decided = self.resolver.resolve(pause)
140
+ except Exception as exc:
141
+ advance = Advance(advance.cursor, error={**error_object(exc), "step": pause["step"]}, exc=exc)
142
+ break
143
+ if "answer" not in decided:
144
+ advance.cursor.pause = decided # the review: the loop still waits at the decision
145
+ break
146
+ advance = engine.submit(self.procedure, advance.cursor, decided["answer"], scripts=False,
147
+ attribution=decided["attribution"])
148
+ else:
149
+ break
150
+ lines += advance.lines
151
+ advance.lines = lines
152
+ return advance
153
+
154
+ def _step(self, advance: Any, run_id: str, created: float | None = None) -> Step:
155
+ """The run file holds the whole cursor: `resume` rebuilds the run from it alone, from any
156
+ directory (so the folder is recorded as an absolute path)."""
157
+ from aip.client.runner import RunFile
158
+
159
+ run = None
160
+ if advance.cursor is not None and not advance.kept:
161
+ c = advance.cursor
162
+ run = RunFile(pause=c.pause, run_id=run_id, skill_dir=str(self.skill_dir.resolve()),
163
+ after=c.after, state=c.state, history=c.history, workdir=str(self.executor.workdir),
164
+ created=created or time.time())
165
+ return Step(advance.outcome(), advance.lines, run, advance.kept, run_id if advance.resumable else None,
166
+ advance.exc)
167
+
168
+
169
+ class HttpBackend:
170
+ """A run on an AIP server (design §8): `POST /runs` and `POST /runs/{id}/result`.
171
+
172
+ `server` is a URL or a `Server`; `name` is `name`, `name@<revision>`, or `name@latest`. The
173
+ server resolves the ref to an exact revision when it opens the run, and the run stays on it,
174
+ so a run never straddles a re-pin. A served run's file holds only the run's id, server,
175
+ name, revision, version, working directory and pending pause: the server holds the state
176
+ and the history, and `resume` sends only the answer.
177
+
178
+ When the server replies with an execution step, this client fetches the revision's
179
+ `scripts/` and `assets/` into its cache (once), runs the script with `workdir` as the run's
180
+ working directory, and posts the report, until the server replies with something else.
181
+ When it replies with a decision and this client has a decision model, the client asks it
182
+ and posts the answers with their attribution, or keeps a review pause in the run file
183
+ until the agent answers it. `client` is an injected decision-model client (tests).
184
+ """
185
+
186
+ def __init__(self, server: Any, token: str | None = None, name: str = "", *, session: Any = None,
187
+ workdir: Path | str | None = None, python: Path | None = None, client: Any = None):
188
+ from aip.client.resolver import Resolver
189
+ from aip.client.server import Server
190
+
191
+ self.server = server if isinstance(server, Server) else Server(str(server), token, session=session)
192
+ self.ref = name
193
+ self.workdir = _workdir(workdir)
194
+ self.python = python
195
+ self.resolver = Resolver.configured(client)
196
+ self._executors: Dict[str, Any] = {}
197
+
198
+ def describe(self) -> JSON:
199
+ return self.server.info(self.ref)
200
+
201
+ def open(self, payload: JSON) -> Step:
202
+ name, _, revision = self.ref.partition("@")
203
+ body = {"name": name, "input": payload, **({"revision": revision} if revision else {})}
204
+ return self._call("/runs", body, None)
205
+
206
+ def submit(self, run: Any, answer: JSON | None) -> Step:
207
+ from aip.client.resolver import manual, reviewed
208
+ from aip.model.engine import error_object
209
+ from aip.model.types import OutputValidationError
210
+
211
+ if getattr(run, "workdir", None):
212
+ self.workdir = Path(run.workdir)
213
+ kind = run.pause.get("kind")
214
+ if kind == "execute" and answer is None:
215
+ # the client stopped before it reported the script: run it now
216
+ return self._perform(run, [])
217
+ if kind == "decision" and answer is None and self.resolver is not None:
218
+ return self._decide(run, [])
219
+ attribution = None
220
+ if kind == "review":
221
+ try:
222
+ decided = reviewed(run.pause, answer)
223
+ except OutputValidationError as exc:
224
+ return Step(error_object(exc), kept=True, run_id=run.run_id, exc=exc)
225
+ answer, attribution = decided["answer"], decided["attribution"]
226
+ elif kind == "decision":
227
+ attribution = manual()
228
+ body = {"step": run.pause.get("step"), "version": run.version,
229
+ **({"answer": answer} if answer is not None else {}),
230
+ **({"attribution": attribution} if attribution is not None else {})}
231
+ return self._call(f"/runs/{run.run_id}/result", body, run)
232
+
233
+ def executor(self, name: str, revision: str) -> Any:
234
+ """The executor for a revision, its scripts and assets fetched into the cache."""
235
+ from aip.client.executor import Executor, fetch
236
+
237
+ key = f"{name}@{revision}"
238
+ if key not in self._executors:
239
+ self._executors[key] = Executor(fetch(self.server, name, revision), self.workdir, self.python)
240
+ executor = self._executors[key]
241
+ executor.workdir = self.workdir
242
+ return executor
243
+
244
+ def _perform(self, run: Any, lines: List[JSON]) -> Step:
245
+ """Run the script the run waits at and post the report. If the scripts cannot be fetched
246
+ the run waits at the step (an error, resumable: `resume` tries again)."""
247
+ from aip.client.runner import error_object
248
+
249
+ try:
250
+ report = self.executor(run.name, run.revision).perform(run.pause)
251
+ except Exception as exc:
252
+ return Step({**error_object(exc), "step": run.pause["step"]}, lines, run, run_id=run.run_id, exc=exc)
253
+ body = {"step": run.pause["step"], "version": run.version, "answer": report}
254
+ return self._call(f"/runs/{run.run_id}/result", body, run, lines)
255
+
256
+ def _decide(self, run: Any, lines: List[JSON]) -> Step:
257
+ """Resolve the decision the run waits at with the decision model and post the answers, or
258
+ stop at a review, which only this client holds. If the model fails the run waits at the
259
+ decision (an error, resumable: `resume` asks again)."""
260
+ from aip.client.runner import error_object
261
+
262
+ try:
263
+ decided = self.resolver.resolve(run.pause)
264
+ except Exception as exc:
265
+ return Step({**error_object(exc), "step": run.pause["step"]}, lines, run, run_id=run.run_id, exc=exc)
266
+ if "answer" not in decided:
267
+ run.pause = decided
268
+ return Step({"paused": "review", **{k: v for k, v in decided.items() if k != "kind"}}, lines, run,
269
+ run_id=run.run_id)
270
+ body = {"step": run.pause["step"], "version": run.version, "answer": decided["answer"],
271
+ "attribution": decided["attribution"]}
272
+ return self._call(f"/runs/{run.run_id}/result", body, run, lines)
273
+
274
+ def _call(self, path: str, body: JSON, run: Any, lines: List[JSON] | None = None) -> Step:
275
+ """Post, and turn the reply into a `Step`. A 422 is a start input or an answer that does
276
+ not fit, a 409 a run that moved on since the run file was written: either way nothing
277
+ changed on the server, so the run file stays as it is. An execution step is run here and
278
+ reported, and the lines of every call are kept, in order."""
279
+ from aip.client.runner import RunFile, error_object
280
+ from aip.client.server import ServerError
281
+
282
+ lines = list(lines or [])
283
+ try:
284
+ reply = self.server.post(path, body)
285
+ except ServerError as exc:
286
+ kept = run is not None and exc.status in (409, 422)
287
+ return Step(error_object(exc), lines, kept=kept, run_id=run.run_id if run is not None else None, exc=exc)
288
+ meta = {k: reply.pop(k) for k in ("run_id", "name", "revision", "version", "steps", "resumable") if k in reply}
289
+ lines += meta.get("steps", [])
290
+ outcome = reply
291
+ if "paused" in outcome:
292
+ pause = {"kind": outcome["paused"], **{k: v for k, v in outcome.items() if k != "paused"}}
293
+ elif "done" in outcome:
294
+ pause = {"kind": "done", "state": outcome["state"]}
295
+ else:
296
+ pause = {"kind": "error", "step": outcome["step"], "error": outcome["error"]}
297
+ saved = RunFile(pause=pause, run_id=meta["run_id"], server=self.server.url, name=meta["name"],
298
+ revision=meta["revision"], version=meta["version"], workdir=str(self.workdir),
299
+ created=run.created if run is not None else time.time())
300
+ if pause["kind"] == "execute":
301
+ return self._perform(saved, lines)
302
+ if pause["kind"] == "decision":
303
+ if self.resolver is not None:
304
+ return self._decide(saved, lines)
305
+ pause.pop("history", None) # for a resolver; the agent answers without it
306
+ return Step(outcome, lines, saved, run_id=meta["run_id"])