agentjam 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. agentjam/__init__.py +435 -0
  2. agentjam/_adapters/__init__.py +0 -0
  3. agentjam/_adapters/responses.py +73 -0
  4. agentjam/_adapters/shared.py +435 -0
  5. agentjam/_agent.py +1032 -0
  6. agentjam/_agent_access.py +360 -0
  7. agentjam/_agent_delegations.py +376 -0
  8. agentjam/_agent_executions.py +566 -0
  9. agentjam/_agent_judging.py +288 -0
  10. agentjam/_agent_options.py +122 -0
  11. agentjam/_agent_routing.py +214 -0
  12. agentjam/_agent_session.py +195 -0
  13. agentjam/_agent_support.py +415 -0
  14. agentjam/_artifacts.py +565 -0
  15. agentjam/_attachments.py +112 -0
  16. agentjam/_connections.py +1282 -0
  17. agentjam/_content.py +29 -0
  18. agentjam/_cron.py +302 -0
  19. agentjam/_errors.py +238 -0
  20. agentjam/_events.py +113 -0
  21. agentjam/_files.py +55 -0
  22. agentjam/_github.py +742 -0
  23. agentjam/_idempotency.py +68 -0
  24. agentjam/_inputs.py +79 -0
  25. agentjam/_models.py +21 -0
  26. agentjam/_polling.py +139 -0
  27. agentjam/_profile.py +244 -0
  28. agentjam/_protocol.py +480 -0
  29. agentjam/_providers.py +365 -0
  30. agentjam/_recaps.py +67 -0
  31. agentjam/_relay/__init__.py +0 -0
  32. agentjam/_relay/actions.py +234 -0
  33. agentjam/_relay/artifacts.py +96 -0
  34. agentjam/_relay/base.py +387 -0
  35. agentjam/_relay/commits.py +77 -0
  36. agentjam/_relay/copies.py +66 -0
  37. agentjam/_relay/credentials.py +127 -0
  38. agentjam/_relay/endpoints.py +39 -0
  39. agentjam/_relay/follow_ups.py +548 -0
  40. agentjam/_relay/frames.py +443 -0
  41. agentjam/_relay/guest_store.py +114 -0
  42. agentjam/_relay/guests.py +55 -0
  43. agentjam/_relay/inputs.py +119 -0
  44. agentjam/_relay/lineage.py +294 -0
  45. agentjam/_relay/memory.py +1045 -0
  46. agentjam/_relay/payments.py +204 -0
  47. agentjam/_relay/profiles.py +95 -0
  48. agentjam/_relay/remote.py +826 -0
  49. agentjam/_relay/resumptions.py +65 -0
  50. agentjam/_relay/revisions.py +43 -0
  51. agentjam/_relay/schedule_follow_ups.py +274 -0
  52. agentjam/_relay/schedules.py +547 -0
  53. agentjam/_relay/secrets.py +275 -0
  54. agentjam/_relay/sessions.py +640 -0
  55. agentjam/_relay/uploads.py +71 -0
  56. agentjam/_requests.py +178 -0
  57. agentjam/_screening.py +368 -0
  58. agentjam/_secrets.py +153 -0
  59. agentjam/_sentry.py +233 -0
  60. agentjam/_signals.py +98 -0
  61. agentjam/_slack.py +468 -0
  62. agentjam/_stripe.py +93 -0
  63. agentjam/_tasks/__init__.py +0 -0
  64. agentjam/_tasks/access.py +142 -0
  65. agentjam/_tasks/incoming.py +952 -0
  66. agentjam/_tasks/outgoing.py +472 -0
  67. agentjam/_tasks/scheduled.py +206 -0
  68. agentjam/_tasks/serial.py +40 -0
  69. agentjam/_tasks/triggers.py +258 -0
  70. agentjam/_tasks/watches.py +77 -0
  71. agentjam/_tools.py +1035 -0
  72. agentjam/_types.py +965 -0
  73. agentjam/_utils.py +75 -0
  74. agentjam/_verdicts.py +21 -0
  75. agentjam/_watermarks.py +59 -0
  76. agentjam/anthropic.py +442 -0
  77. agentjam/mpp.py +233 -0
  78. agentjam/openai.py +141 -0
  79. agentjam/openai_agents.py +253 -0
  80. agentjam/py.typed +0 -0
  81. agentjam/pydantic_ai.py +301 -0
  82. agentjam/skills.py +69 -0
  83. agentjam-0.1.0.dist-info/METADATA +210 -0
  84. agentjam-0.1.0.dist-info/RECORD +86 -0
  85. agentjam-0.1.0.dist-info/WHEEL +4 -0
  86. agentjam-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,119 @@
1
+ from collections.abc import Callable
2
+ from typing import Any
3
+
4
+ from jsonschema import Draft202012Validator
5
+ from jsonschema.exceptions import ValidationError, best_match
6
+
7
+ from agentjam._types import JsonObject, JsonSchema, SkillCard
8
+
9
+ Describe = Callable[[ValidationError], str]
10
+
11
+
12
+ def describe_required(error: ValidationError) -> str:
13
+ instance = error.instance if isinstance(error.instance, dict) else {}
14
+ required = error.validator_value if isinstance(error.validator_value, list) else []
15
+ missing = next((name for name in required if name not in instance), "")
16
+
17
+ return f"must have required property '{missing}'"
18
+
19
+
20
+ def describe_type(error: ValidationError) -> str:
21
+ types = error.validator_value
22
+
23
+ return f"must be {','.join(types) if isinstance(types, list) else types}"
24
+
25
+
26
+ DESCRIPTIONS: dict[str, Describe] = {
27
+ "type": describe_type,
28
+ "required": describe_required,
29
+ "additionalProperties": lambda _: "must NOT have additional properties",
30
+ "unevaluatedProperties": lambda _: "must NOT have unevaluated properties",
31
+ "enum": lambda _: "must be equal to one of the allowed values",
32
+ "const": lambda _: "must be equal to constant",
33
+ "format": lambda error: f'must match format "{error.validator_value}"',
34
+ "pattern": lambda error: f'must match pattern "{error.validator_value}"',
35
+ "minimum": lambda error: f"must be >= {error.validator_value}",
36
+ "maximum": lambda error: f"must be <= {error.validator_value}",
37
+ "exclusiveMinimum": lambda error: f"must be > {error.validator_value}",
38
+ "exclusiveMaximum": lambda error: f"must be < {error.validator_value}",
39
+ "multipleOf": lambda error: f"must be multiple of {error.validator_value}",
40
+ "minLength": lambda error: (
41
+ f"must NOT have fewer than {error.validator_value} characters"
42
+ ),
43
+ "maxLength": lambda error: (
44
+ f"must NOT have more than {error.validator_value} characters"
45
+ ),
46
+ "minItems": lambda error: f"must NOT have fewer than {error.validator_value} items",
47
+ "maxItems": lambda error: f"must NOT have more than {error.validator_value} items",
48
+ "minProperties": lambda error: (
49
+ f"must NOT have fewer than {error.validator_value} properties"
50
+ ),
51
+ "maxProperties": lambda error: (
52
+ f"must NOT have more than {error.validator_value} properties"
53
+ ),
54
+ "uniqueItems": lambda _: "must NOT have duplicate items",
55
+ "anyOf": lambda _: "must match a schema in anyOf",
56
+ "oneOf": lambda _: "must match exactly one schema in oneOf",
57
+ "not": lambda _: "must NOT be valid",
58
+ }
59
+
60
+
61
+ def escape_pointer(part: str | int) -> str:
62
+ return str(part).replace("~", "~0").replace("/", "~1")
63
+
64
+
65
+ def describe_violation(error: ValidationError, name: str) -> str:
66
+ """Describes a validation error the way Ajv's `errorsText` does, prefixed with the data's `name` and path."""
67
+ path = "".join(f"/{escape_pointer(part)}" for part in error.absolute_path)
68
+ describe = DESCRIPTIONS.get(str(error.validator))
69
+ message = describe(error) if describe else error.message
70
+
71
+ return f"{name}{path} {message}"
72
+
73
+
74
+ def find_value_problem(schema: JsonSchema, value: Any, name: str) -> str | None:
75
+ validator = Draft202012Validator(
76
+ schema, format_checker=Draft202012Validator.FORMAT_CHECKER
77
+ )
78
+ error = best_match(validator.iter_errors(value))
79
+
80
+ return None if error is None else describe_violation(error, name)
81
+
82
+
83
+ def input_problem(input: JsonObject | None, skill: SkillCard | None) -> str | None:
84
+ """Describes why a proposal's input doesn't suit the skill it names, the way the AgentJam relay does."""
85
+ if input is None:
86
+ if skill and skill.input_schema is not None:
87
+ return f'The "{skill.name}" skill needs input matching its schema'
88
+
89
+ return None
90
+
91
+ if skill is None:
92
+ return "Only a proposal naming a skill with an input schema can send input"
93
+
94
+ if skill.input_schema is None:
95
+ return f'The "{skill.name}" skill takes no input'
96
+
97
+ problem = find_value_problem(skill.input_schema, input, "input")
98
+ if problem is None:
99
+ return None
100
+
101
+ return f'Input for the "{skill.name}" skill doesn\'t match its schema: {problem}'
102
+
103
+
104
+ def output_problem(output: JsonObject | None, skill: SkillCard | None) -> str | None:
105
+ """Describes why a task's output doesn't suit the stored skill it calls for, before the relay refuses it."""
106
+ if output is None:
107
+ if skill and skill.output_schema is not None:
108
+ return f'The "{skill.name}" skill has an output schema, so its tasks must call set_output() before they complete'
109
+
110
+ return None
111
+
112
+ if skill is None or skill.output_schema is None:
113
+ return "Only a task of a skill with an output schema can set output"
114
+
115
+ problem = find_value_problem(skill.output_schema, output, "output")
116
+ if problem is None:
117
+ return None
118
+
119
+ return f'Output for the "{skill.name}" skill doesn\'t match its schema: {problem}'
@@ -0,0 +1,294 @@
1
+ from dataclasses import dataclass, replace
2
+ from typing import Literal, assert_never
3
+
4
+ from agentjam._errors import AgentJamError
5
+ from agentjam._protocol import ParentRef, ProposeEnvelope, RecurEnvelope
6
+ from agentjam._relay.sessions import request_key
7
+ from agentjam._types import ActionOrigin
8
+
9
+ GUEST_PREFIX = "guest:"
10
+
11
+ MAX_DEPTH = 8
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class ChainLink:
16
+ agent: str
17
+ skill: str | None
18
+
19
+
20
+ # Invariant: principal is inherited from the parent, depth counts the chain's tasks down to this one, and
21
+ # chain lists the agents above it: the root's requester followed by each ancestor's executor, oldest first.
22
+ @dataclass(frozen=True)
23
+ class Lineage:
24
+ principal: str
25
+ depth: int
26
+ chain: tuple[ChainLink, ...]
27
+
28
+
29
+ @dataclass
30
+ class WorkRecord:
31
+ kind: Literal["task", "schedule", "run", "preparation"]
32
+ requester: str
33
+ id: str
34
+ parent: ParentRef | None
35
+ executor: str
36
+ skill: str | None
37
+ lineage: Lineage
38
+ accepted: bool = False
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class SkilledWork:
43
+ """The executor of a task or run, and the skill it calls for."""
44
+
45
+ executor: str
46
+ skill: str | None
47
+
48
+
49
+ def find_parent_key(parent: ParentRef) -> str:
50
+ return request_key(parent.requester, parent.id)
51
+
52
+
53
+ def is_looping(lineage: Lineage, executor: str) -> bool:
54
+ return lineage.chain[-1].agent != executor and any(
55
+ link.agent == executor for link in lineage.chain
56
+ )
57
+
58
+
59
+ def find_kind(proposal: ProposeEnvelope) -> Literal["task", "schedule", "preparation"]:
60
+ if proposal.prepare:
61
+ return "preparation"
62
+
63
+ is_scheduled = proposal.cron is not None or proposal.trigger is not None
64
+
65
+ return "schedule" if is_scheduled else "task"
66
+
67
+
68
+ def is_working(record: WorkRecord | None, executor: str) -> bool:
69
+ return (
70
+ record is not None
71
+ and record.kind in ("task", "run")
72
+ and record.accepted
73
+ and record.executor == executor
74
+ )
75
+
76
+
77
+ def is_task(record: WorkRecord | None) -> bool:
78
+ return record is not None and record.kind != "schedule"
79
+
80
+
81
+ def construct_root_lineage(requester: str) -> Lineage:
82
+ return Lineage(f"{GUEST_PREFIX}{requester}", 1, (ChainLink(requester, None),))
83
+
84
+
85
+ def construct_origin(record: WorkRecord) -> ActionOrigin:
86
+ return ActionOrigin(
87
+ requester=record.requester, task_id=record.id, executor=record.executor
88
+ )
89
+
90
+
91
+ class LineageLedger:
92
+ """Tracks where each task and schedule routed through a `MemoryRelay` sits in its chain.
93
+
94
+ An agent can delegate as part of a task it's working on. Agents have no owners here, so every principal is a
95
+ guest's. Invariant: a chain is at most 8 tasks deep, and an agent's consecutive tasks in it are its only ones.
96
+ """
97
+
98
+ def __init__(self) -> None:
99
+ self._work: dict[str, WorkRecord] = {}
100
+
101
+ def propose(self, proposal: ProposeEnvelope) -> str:
102
+ """Records a proposal under the parent it names, or as the root of a new chain, and returns its principal."""
103
+ key = request_key(proposal.sender, proposal.id)
104
+ if known := self._work.get(key):
105
+ return known.lineage.principal
106
+
107
+ lineage = (
108
+ self._resolve_preparation(proposal)
109
+ if proposal.prepare
110
+ else self._resolve_lineage(proposal)
111
+ )
112
+
113
+ self._work[key] = WorkRecord(
114
+ find_kind(proposal),
115
+ proposal.sender,
116
+ proposal.id,
117
+ proposal.parent,
118
+ proposal.to,
119
+ proposal.skill,
120
+ lineage,
121
+ )
122
+
123
+ return lineage.principal
124
+
125
+ def accept(self, requester: str, id: str) -> None:
126
+ """Marks work its executor accepted, or holds for actions, so a task can delegate as part of itself and a schedule takes no more preparations."""
127
+ if record := self._work.get(request_key(requester, id)):
128
+ record.accepted = True
129
+
130
+ def recur(self, recur: RecurEnvelope) -> None:
131
+ """Records a schedule's run, which inherits the schedule's lineage."""
132
+ schedule = self._work.get(request_key(recur.sender, recur.schedule_id))
133
+ key = request_key(recur.sender, recur.task_id)
134
+ if schedule is None or key in self._work:
135
+ return
136
+
137
+ self._work[key] = replace(schedule, kind="run", id=recur.task_id, accepted=True)
138
+
139
+ def find_prepared(self, requester: str, id: str) -> ActionOrigin | None:
140
+ """Finds the schedule the task `id` of `requester` prepares through the preparations above it, if it's a preparation."""
141
+ record = self._work.get(request_key(requester, id))
142
+ while record and record.kind == "preparation" and record.parent:
143
+ record = self._work.get(find_parent_key(record.parent))
144
+
145
+ return (
146
+ construct_origin(record) if record and record.kind == "schedule" else None
147
+ )
148
+
149
+ def follow_up(self, proposal: ProposeEnvelope, schedule_id: str) -> str:
150
+ """Records a run's follow-up, proposed on behalf of the schedule's requester one link below its executor, and returns its principal."""
151
+ lineage = self._chain_follow_up(proposal.sender, schedule_id, proposal.to)
152
+
153
+ self._work[request_key(proposal.sender, proposal.id)] = WorkRecord(
154
+ "task",
155
+ proposal.sender,
156
+ proposal.id,
157
+ proposal.parent,
158
+ proposal.to,
159
+ proposal.skill,
160
+ lineage,
161
+ )
162
+
163
+ return lineage.principal
164
+
165
+ def assert_follow_up(self, requester: str, schedule_id: str, to: str) -> None:
166
+ """Checks that a follow-up to `to` keeps the chain below the schedule `schedule_id` of `requester` valid."""
167
+ self._chain_follow_up(requester, schedule_id, to)
168
+
169
+ def find_skill(self, requester: str, id: str) -> SkilledWork | None:
170
+ """Finds the skill of the task or run `id` of `requester`, or None for a preparation or unknown work."""
171
+ record = self._work.get(request_key(requester, id))
172
+ if record is None or record.kind not in ("task", "run"):
173
+ return None
174
+
175
+ return SkilledWork(record.executor, record.skill)
176
+
177
+ def end(self, requester: str, id: str) -> None:
178
+ self._work.pop(request_key(requester, id), None)
179
+
180
+ def list_children(self, requester: str, id: str) -> list[ActionOrigin]:
181
+ """Lists the open tasks and preparations delegated as part of the task `id` of `requester`, leaving out schedules and runs."""
182
+ return [
183
+ construct_origin(child)
184
+ for child in self._work.values()
185
+ if child.kind in ("task", "preparation")
186
+ and child.parent is not None
187
+ and find_parent_key(child.parent) == request_key(requester, id)
188
+ ]
189
+
190
+ def list_chain(self, requester: str, id: str) -> list[ActionOrigin]:
191
+ """Lists the task, run or preparation `id` of `requester`, then each task above it in its chain that's still open, nearest first."""
192
+ chain: list[ActionOrigin] = []
193
+ record = self._work.get(request_key(requester, id))
194
+ while record is not None and is_task(record):
195
+ chain.append(construct_origin(record))
196
+ parent = record.parent
197
+ record = self._work.get(find_parent_key(parent)) if parent else None
198
+
199
+ return chain
200
+
201
+ def _resolve_lineage(self, proposal: ProposeEnvelope) -> Lineage:
202
+ is_scheduled = proposal.cron is not None or proposal.trigger is not None
203
+ if proposal.sender == proposal.to and is_scheduled:
204
+ raise AgentJamError(
205
+ "An agent can propose tasks to its own skills, but not schedules"
206
+ )
207
+
208
+ parent = proposal.parent
209
+ if parent is None:
210
+ return construct_root_lineage(proposal.sender)
211
+
212
+ if parent.kind != "task":
213
+ raise AgentJamError("Only a preparation names a schedule as its parent")
214
+
215
+ task = self._work.get(find_parent_key(parent))
216
+ if task is None or not is_working(task, proposal.sender):
217
+ raise AgentJamError(
218
+ f'"{proposal.sender}" isn\'t working on task "{parent.id}" of "{parent.requester}", so it can\'t delegate as part of it'
219
+ )
220
+
221
+ return self._extend_chain(task, proposal.sender, proposal.to)
222
+
223
+ def _resolve_preparation(self, proposal: ProposeEnvelope) -> Lineage:
224
+ if proposal.parent is None:
225
+ raise AgentJamError(
226
+ "A preparation names the pending schedule or open task it's for as its parent"
227
+ )
228
+
229
+ prepared = self._get_prepared_work(proposal.sender, proposal.parent)
230
+
231
+ return self._extend_chain(prepared, proposal.sender, proposal.to)
232
+
233
+ def _get_prepared_work(self, sender: str, parent: ParentRef) -> WorkRecord:
234
+ match parent.kind:
235
+ case "schedule":
236
+ return self._get_pending_schedule(sender, parent)
237
+
238
+ case "task":
239
+ return self._get_preparing_task(sender, parent)
240
+
241
+ case _:
242
+ assert_never(parent.kind)
243
+
244
+ def _get_pending_schedule(self, sender: str, parent: ParentRef) -> WorkRecord:
245
+ schedule = self._work.get(find_parent_key(parent))
246
+ if (
247
+ schedule is None
248
+ or schedule.kind != "schedule"
249
+ or schedule.accepted
250
+ or schedule.executor != sender
251
+ ):
252
+ raise AgentJamError(
253
+ f'"{sender}" isn\'t answering schedule "{parent.id}" of "{parent.requester}", so it can\'t prepare for it'
254
+ )
255
+
256
+ return schedule
257
+
258
+ def _get_preparing_task(self, sender: str, parent: ParentRef) -> WorkRecord:
259
+ task = self._work.get(find_parent_key(parent))
260
+ if task is None or not is_task(task) or task.executor != sender:
261
+ raise AgentJamError(
262
+ f'"{sender}" isn\'t working on task "{parent.id}" of "{parent.requester}", so it can\'t prepare for it'
263
+ )
264
+
265
+ return task
266
+
267
+ def _chain_follow_up(self, requester: str, schedule_id: str, to: str) -> Lineage:
268
+ schedule = self._work.get(request_key(requester, schedule_id))
269
+ if schedule is None or schedule.kind != "schedule":
270
+ raise AgentJamError(
271
+ f'Schedule "{schedule_id}" ended before its run\'s follow-up'
272
+ )
273
+
274
+ return self._extend_chain(schedule, schedule.executor, to)
275
+
276
+ def _extend_chain(self, parent: WorkRecord, sender: str, to: str) -> Lineage:
277
+ inherited = parent.lineage
278
+ lineage = Lineage(
279
+ inherited.principal,
280
+ inherited.depth + 1,
281
+ (*inherited.chain, ChainLink(sender, parent.skill)),
282
+ )
283
+
284
+ if lineage.depth > MAX_DEPTH:
285
+ raise AgentJamError(
286
+ f'A chain of tasks is at most {MAX_DEPTH} deep, so "{sender}" can\'t delegate as part of task "{parent.id}"'
287
+ )
288
+
289
+ if is_looping(lineage, to):
290
+ raise AgentJamError(
291
+ f'"{to}" already worked on an earlier task in this chain, so "{sender}" can\'t delegate back to it'
292
+ )
293
+
294
+ return lineage