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
agentjam/_tools.py ADDED
@@ -0,0 +1,1035 @@
1
+ import asyncio
2
+ import contextlib
3
+ import json
4
+ import math
5
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
6
+ from dataclasses import dataclass, field
7
+ from typing import Literal, Protocol, TypeAlias, TypeVar, assert_never, get_args
8
+ from weakref import WeakKeyDictionary
9
+
10
+ from agentjam._content import ContentSource, LabeledContent
11
+ from agentjam._errors import AgentJamError, TaskCanceledError, describe_error
12
+ from agentjam._files import File
13
+ from agentjam._protocol import TaskRef
14
+ from agentjam._tasks.incoming import IncomingTask, current_task
15
+ from agentjam._tasks.outgoing import OutgoingTask
16
+ from agentjam._types import (
17
+ AgentCard,
18
+ Artifact,
19
+ Attachment,
20
+ Delegate,
21
+ Dispute,
22
+ JsonObject,
23
+ JsonSchema,
24
+ MessageReply,
25
+ Review,
26
+ ReviewPage,
27
+ TaskPage,
28
+ TaskRecap,
29
+ TaskStatus,
30
+ TaskWatch,
31
+ TextArtifact,
32
+ )
33
+ from agentjam._utils import encode_json, omit_none, spawn, to_json_data
34
+
35
+ ChoiceT = TypeVar("ChoiceT", bound=str)
36
+
37
+ ToolName = Literal[
38
+ "find_agents",
39
+ "prepare_delegates",
40
+ "send_message",
41
+ "delegate_task",
42
+ "wait_for_tasks",
43
+ "list_tasks",
44
+ "recall_task",
45
+ "list_past_tasks",
46
+ "publish_update",
47
+ "deliver_file",
48
+ "forward_artifact",
49
+ "rate_agent",
50
+ "dispute_task",
51
+ "list_reviews",
52
+ ]
53
+ """The name of a network tool, which `network_tools` in `connect()` and the adapters' tool converters take."""
54
+
55
+ network_tool_names: tuple[ToolName, ...] = get_args(ToolName)
56
+ """Every network tool's name, in the order agents list their tools."""
57
+
58
+ WaitMode = Literal["all", "any"]
59
+
60
+ FieldType = Literal["string", "integer", "number", "boolean", "array"]
61
+
62
+ ToolArguments: TypeAlias = Mapping[str, object]
63
+
64
+ WAIT_MODES: tuple[WaitMode, ...] = get_args(WaitMode)
65
+
66
+ TASK_STATUSES: tuple[TaskStatus, ...] = get_args(TaskStatus)
67
+
68
+ IRREVERSIBLE_HINT = "A task of a skill marked irreversible can't be canceled once its agent commits to an action it can't undo, such as a purchase, so confirm with your human before delegating one."
69
+
70
+ FOLLOW_UP_HINT = "To change or build on an ended task's result, delegate to the same agent again with follows set to its taskId, describing only what to change: the agent sees what that task asked for and produced, and the same skill reuses its input when you omit input. A skill that lists revisions runs that many follow-ups of a completed task for free."
71
+
72
+ PREPARE_HINT = "Before long work, pass the agents you'll delegate to whose skills list connections to prepare_delegates, so your human connects their accounts at the start rather than partway through."
73
+
74
+
75
+ class Peer(Protocol):
76
+ """The slice of an agent that network tools act through."""
77
+
78
+ @property
79
+ def name(self) -> str: ...
80
+
81
+ async def find(
82
+ self, *, skill: str | None = None, query: str | None = None
83
+ ) -> list[AgentCard]: ...
84
+
85
+ async def send(
86
+ self,
87
+ to: str,
88
+ text: str,
89
+ *,
90
+ conversation_id: str | None = None,
91
+ task_id: str | None = None,
92
+ steer: bool = False,
93
+ ) -> MessageReply: ...
94
+
95
+ async def propose(
96
+ self,
97
+ to: str,
98
+ text: str,
99
+ *,
100
+ skill: str | None = None,
101
+ input: JsonObject | None = None,
102
+ max_price_cents: float | None = None,
103
+ watch: TaskWatch | None = None,
104
+ follows: str | None = None,
105
+ ) -> OutgoingTask: ...
106
+
107
+ async def rate(
108
+ self, task_id: str, rating: int, text: str | None = None
109
+ ) -> Review: ...
110
+
111
+ async def dispute(self, task_id: str, reason: str) -> Dispute: ...
112
+
113
+ async def reviews(
114
+ self, name: str, *, cursor: str | None = None, limit: int | None = None
115
+ ) -> ReviewPage: ...
116
+
117
+ async def list_tasks(
118
+ self,
119
+ *,
120
+ statuses: list[TaskStatus] | None = None,
121
+ agent: str | None = None,
122
+ watch: TaskWatch | None = None,
123
+ unread: bool | None = None,
124
+ task_ids: list[str] | None = None,
125
+ cursor: str | None = None,
126
+ limit: int | None = None,
127
+ ) -> TaskPage: ...
128
+
129
+ async def recall_task(self, task: TaskRef) -> TaskRecap: ...
130
+
131
+
132
+ @dataclass(frozen=True, kw_only=True)
133
+ class ToolSettings:
134
+ """How the agent behind the network tools handles delegated tasks."""
135
+
136
+ watching: bool
137
+ """Whether the agent has an `on_watch_resolved` handler, which delegating without waiting reports to."""
138
+ forwarding: bool
139
+ """Whether to offer `forward_artifact`, which delivers a delegated task's artifact as a result of the current task."""
140
+
141
+
142
+ @dataclass(frozen=True, kw_only=True)
143
+ class ToolResult:
144
+ """What a network tool returns: text for the model, and the files the tool received."""
145
+
146
+ text: str
147
+ """The tool's result, or a description of what went wrong, as text that also describes `files`."""
148
+ files: list[File] = field(default_factory=list)
149
+ """The files the tool received, such as those on a reply, to show the model where its SDK allows."""
150
+
151
+
152
+ ToolRunner: TypeAlias = Callable[[ToolArguments], Awaitable[str | ToolResult]]
153
+
154
+
155
+ @dataclass(frozen=True, kw_only=True)
156
+ class NetworkTool:
157
+ """A network tool in an SDK-neutral shape, which adapters convert into each SDK's tool format.
158
+
159
+ Inputs are validated at runtime, and expected failures are returned as text for the model.
160
+ """
161
+
162
+ name: str
163
+ """The tool's name, as the model calls it."""
164
+ description: str
165
+ """What the tool does, shown to the model."""
166
+ input_schema: JsonSchema
167
+ """The JSON Schema of the tool's arguments, where every field is required and optional ones are nullable."""
168
+ run: ToolRunner = field(repr=False)
169
+ """Runs the tool with the model's arguments."""
170
+
171
+ async def execute(self, input: object) -> ToolResult:
172
+ """Runs the tool with the model's arguments.
173
+
174
+ Cancelling the call cancels the tasks it delegated and still waits on.
175
+
176
+ Args:
177
+ input: The model's arguments, validated against `input_schema` at runtime.
178
+ Returns:
179
+ The tool's result, or a description of what went wrong, as text, and the files it received.
180
+ Raises:
181
+ Exception: Any error other than an `AgentJamError`.
182
+ """
183
+ arguments = input if isinstance(input, dict) else {}
184
+
185
+ try:
186
+ output = await self.run(arguments)
187
+ except AgentJamError as error:
188
+ return ToolResult(text=f"Error: {error}")
189
+
190
+ return ToolResult(text=output) if isinstance(output, str) else output
191
+
192
+
193
+ @dataclass(frozen=True)
194
+ class TypedField:
195
+ type: FieldType
196
+ description: str
197
+ values: Sequence[str] | None = None
198
+ """The strings a string or array field allows."""
199
+ fields: "Mapping[str, Field] | None" = None
200
+ """Makes an array field a list of objects that each have every one of these fields."""
201
+
202
+
203
+ Field: TypeAlias = str | TypedField
204
+ """A tool argument: a string described by the text, or a typed field."""
205
+
206
+
207
+ def construct_items(typed: TypedField) -> JsonSchema:
208
+ if typed.fields is not None:
209
+ return construct_object_schema(typed.fields)
210
+
211
+ if typed.values is None:
212
+ return {"type": "string"}
213
+
214
+ return {"type": "string", "enum": list(typed.values)}
215
+
216
+
217
+ def construct_property(spec: Field, nullable: bool) -> JsonSchema:
218
+ typed = spec if isinstance(spec, TypedField) else TypedField("string", spec)
219
+ schema: JsonSchema = {
220
+ "type": [typed.type, "null"] if nullable else typed.type,
221
+ "description": typed.description,
222
+ }
223
+
224
+ if typed.type == "array":
225
+ return {**schema, "items": construct_items(typed)}
226
+
227
+ if typed.values is None:
228
+ return schema
229
+
230
+ choices: list[str | None] = [*typed.values]
231
+
232
+ return {**schema, "enum": [*choices, None] if nullable else choices}
233
+
234
+
235
+ def construct_object_schema(
236
+ required: Mapping[str, Field], optional: Mapping[str, Field] | None = None
237
+ ) -> JsonSchema:
238
+ """Builds a JSON Schema compatible with OpenAI's strict mode, where every field is required and optional ones are nullable."""
239
+ optional = optional or {}
240
+ properties = {
241
+ **{name: construct_property(spec, False) for name, spec in required.items()},
242
+ **{name: construct_property(spec, True) for name, spec in optional.items()},
243
+ }
244
+
245
+ return {
246
+ "type": "object",
247
+ "properties": properties,
248
+ "required": [*required, *optional],
249
+ "additionalProperties": False,
250
+ }
251
+
252
+
253
+ def read_string(arguments: ToolArguments, key: str) -> str:
254
+ value = arguments.get(key)
255
+ if not isinstance(value, str) or value == "":
256
+ raise AgentJamError(f'"{key}" must be a non-empty string')
257
+
258
+ return value
259
+
260
+
261
+ def read_optional_string(arguments: ToolArguments, key: str) -> str | None:
262
+ value = arguments.get(key)
263
+ if value is not None and not isinstance(value, str):
264
+ raise AgentJamError(f'"{key}" must be a string')
265
+
266
+ return value
267
+
268
+
269
+ def read_integer(arguments: ToolArguments, key: str) -> int:
270
+ value = arguments.get(key)
271
+ if (
272
+ isinstance(value, bool)
273
+ or not isinstance(value, int | float)
274
+ or not float(value).is_integer()
275
+ ):
276
+ raise AgentJamError(f'"{key}" must be a whole number')
277
+
278
+ return int(value)
279
+
280
+
281
+ def read_number(arguments: ToolArguments, key: str) -> float:
282
+ value = arguments.get(key)
283
+ if (
284
+ isinstance(value, bool)
285
+ or not isinstance(value, int | float)
286
+ or not math.isfinite(value)
287
+ ):
288
+ raise AgentJamError(f'"{key}" must be a number')
289
+
290
+ return value
291
+
292
+
293
+ def read_optional_number(arguments: ToolArguments, key: str) -> float | None:
294
+ return None if arguments.get(key) is None else read_number(arguments, key)
295
+
296
+
297
+ def read_optional_boolean(arguments: ToolArguments, key: str) -> bool | None:
298
+ value = arguments.get(key)
299
+ if value is not None and not isinstance(value, bool):
300
+ raise AgentJamError(f'"{key}" must be true or false')
301
+
302
+ return value
303
+
304
+
305
+ def read_list(arguments: ToolArguments, key: str) -> list[str]:
306
+ value = arguments.get(key)
307
+ if (
308
+ not isinstance(value, list)
309
+ or len(value) == 0
310
+ or not all(isinstance(item, str) and item != "" for item in value)
311
+ ):
312
+ raise AgentJamError(f'"{key}" must be a list of non-empty strings')
313
+
314
+ return value
315
+
316
+
317
+ def read_optional_list(arguments: ToolArguments, key: str) -> list[str] | None:
318
+ return None if arguments.get(key) is None else read_list(arguments, key)
319
+
320
+
321
+ def read_delegates(arguments: ToolArguments, key: str) -> list[Delegate]:
322
+ value = arguments.get(key)
323
+ if (
324
+ not isinstance(value, list)
325
+ or len(value) == 0
326
+ or not all(isinstance(item, dict) for item in value)
327
+ ):
328
+ raise AgentJamError(
329
+ f'"{key}" must be a list of objects, each naming an agent and a skill'
330
+ )
331
+
332
+ return [
333
+ Delegate(agent=read_string(item, "agent"), skill=read_string(item, "skill"))
334
+ for item in value
335
+ ]
336
+
337
+
338
+ def read_json(text: str) -> object:
339
+ try:
340
+ return json.loads(text)
341
+ except ValueError:
342
+ return None
343
+
344
+
345
+ def read_optional_object(arguments: ToolArguments, key: str) -> JsonObject | None:
346
+ value = arguments.get(key)
347
+ if value is None:
348
+ return None
349
+
350
+ parsed = read_json(value) if isinstance(value, str) else value
351
+ if isinstance(parsed, dict):
352
+ return parsed
353
+
354
+ raise AgentJamError(f'"{key}" must be a JSON object, or a string holding one')
355
+
356
+
357
+ def read_choice(value: str, key: str, choices: tuple[ChoiceT, ...]) -> ChoiceT:
358
+ for choice in choices:
359
+ if choice == value:
360
+ return choice
361
+
362
+ raise AgentJamError(f'"{key}" must be one of {", ".join(choices)}')
363
+
364
+
365
+ def summarize_artifact(received: TextArtifact | Attachment) -> JsonObject:
366
+ match received:
367
+ case TextArtifact():
368
+ return omit_none(
369
+ {
370
+ "id": received.id,
371
+ "type": "text",
372
+ "name": received.name,
373
+ "mimeType": received.mime_type,
374
+ "text": received.text,
375
+ }
376
+ )
377
+
378
+ case Attachment():
379
+ return {
380
+ "id": received.id,
381
+ "type": "file",
382
+ "name": received.file.name,
383
+ "mimeType": received.file.mime_type,
384
+ "size": received.file.size,
385
+ }
386
+
387
+ case _:
388
+ assert_never(received)
389
+
390
+
391
+ def construct_source(received: Artifact) -> ContentSource:
392
+ match received:
393
+ case TextArtifact():
394
+ return LabeledContent(
395
+ received.text, name=received.name, mime_type=received.mime_type
396
+ )
397
+
398
+ case Attachment():
399
+ return received.file
400
+
401
+ case _:
402
+ assert_never(received)
403
+
404
+
405
+ def describe_actions(task: OutgoingTask) -> JsonObject:
406
+ actions = [
407
+ omit_none(
408
+ {
409
+ "provider": action.provider,
410
+ "url": action.url,
411
+ "reason": action.reason or None,
412
+ "agent": action.origin.executor if action.origin else None,
413
+ }
414
+ )
415
+ for action in task.actions
416
+ ]
417
+
418
+ instruction = (
419
+ "The task can't go on until your human connects these accounts. The links already reach them through the agent that assigned you your task, so don't pass them on. Call wait_for_tasks with the taskId."
420
+ if current_task() is not None
421
+ else "The task can't go on until your human connects these accounts, each for the agent it names or else the one you delegated to, doing what its reason says. Show them the links, then call wait_for_tasks with the taskId."
422
+ )
423
+
424
+ return {
425
+ "taskId": task.id,
426
+ "status": "requires_action",
427
+ "actions": actions,
428
+ "instruction": instruction,
429
+ }
430
+
431
+
432
+ def describe_started(task: OutgoingTask) -> str:
433
+ return encode_json(
434
+ {
435
+ "taskId": task.id,
436
+ "status": "working",
437
+ "instruction": "The task is running. Call wait_for_tasks with the taskId for its result, or list_tasks to check on it.",
438
+ }
439
+ )
440
+
441
+
442
+ async def cancel_quietly(task: OutgoingTask, reason: str) -> None:
443
+ with contextlib.suppress(Exception):
444
+ await task.cancel(reason)
445
+
446
+
447
+ def describe_cancellation() -> str:
448
+ task = current_task()
449
+ reason = None if task is None else task.cancellation
450
+
451
+ return "The tool call was canceled" if reason is None else describe_error(reason)
452
+
453
+
454
+ class ArtifactShelf:
455
+ """Keeps the artifacts the tasks delegated as part of each task returned, for as long as that task lives, so it can forward them."""
456
+
457
+ def __init__(self) -> None:
458
+ self._received: WeakKeyDictionary[IncomingTask, dict[str, Artifact]] = (
459
+ WeakKeyDictionary()
460
+ )
461
+
462
+ def summarize_artifacts(
463
+ self, task_id: str, artifacts: list[Artifact]
464
+ ) -> list[JsonObject]:
465
+ """Summarizes a delegated task's artifacts for the model, keeping them for the current task."""
466
+ if (task := current_task()) is not None:
467
+ kept = self._received.setdefault(task, {})
468
+ kept.update(
469
+ {f"{task_id}/{received.id}": received for received in artifacts}
470
+ )
471
+
472
+ return [summarize_artifact(received) for received in artifacts]
473
+
474
+ def find_artifact(
475
+ self, task: IncomingTask, task_id: str, artifact_id: str
476
+ ) -> Artifact | None:
477
+ return self._received.get(task, {}).get(f"{task_id}/{artifact_id}")
478
+
479
+
480
+ class NetworkToolkit:
481
+ """Runs the network tools of one agent, tracking the tasks they delegated without waiting."""
482
+
483
+ def __init__(self, peer: Peer, settings: ToolSettings) -> None:
484
+ self._peer = peer
485
+ self._settings = settings
486
+ self._delegated: dict[str, OutgoingTask] = {}
487
+ self._shelf = ArtifactShelf()
488
+ self._shown: dict[str, set[str]] = {}
489
+
490
+ async def find_agents(self, arguments: ToolArguments) -> str:
491
+ cards = await self._peer.find(
492
+ skill=read_optional_string(arguments, "skill"),
493
+ query=read_optional_string(arguments, "query"),
494
+ )
495
+
496
+ return encode_json([card.to_wire() for card in cards])
497
+
498
+ async def prepare_delegates(self, arguments: ToolArguments) -> str:
499
+ delegates = read_delegates(arguments, "delegates")
500
+ task = current_task()
501
+ if task is None:
502
+ return "No task is in progress, so nothing was prepared."
503
+
504
+ await task.prepare(delegates)
505
+ agents = ", ".join(delegate.agent for delegate in delegates)
506
+
507
+ return f"Asked {agents} for the accounts they need. Once your human connects them, delegating to these agents won't ask again."
508
+
509
+ async def send_message(self, arguments: ToolArguments) -> ToolResult:
510
+ reply = await self._peer.send(
511
+ read_string(arguments, "agent"),
512
+ read_string(arguments, "text"),
513
+ conversation_id=read_optional_string(arguments, "conversationId"),
514
+ task_id=read_optional_string(arguments, "taskId"),
515
+ steer=read_optional_boolean(arguments, "steer") or False,
516
+ )
517
+
518
+ text = encode_json(
519
+ {
520
+ "reply": reply.text,
521
+ "conversationId": reply.conversation_id,
522
+ "attachments": [summarize_artifact(each) for each in reply.attachments],
523
+ }
524
+ )
525
+
526
+ return ToolResult(text=text, files=[each.file for each in reply.attachments])
527
+
528
+ async def delegate_task(self, arguments: ToolArguments) -> str:
529
+ wait = read_optional_boolean(arguments, "wait") is not False
530
+ group = read_optional_string(arguments, "watch")
531
+ is_watched = self._settings.watching and not wait
532
+ watch = group if group is not None else (True if is_watched else None)
533
+ task = await self._peer.propose(
534
+ read_string(arguments, "agent"),
535
+ read_string(arguments, "task"),
536
+ skill=read_optional_string(arguments, "skill"),
537
+ input=read_optional_object(arguments, "input"),
538
+ max_price_cents=read_optional_number(arguments, "maxPriceCents"),
539
+ follows=read_optional_string(arguments, "follows"),
540
+ watch=watch,
541
+ )
542
+
543
+ try:
544
+ if wait and not await self._await_links(task):
545
+ return await self._encode_result(task)
546
+ except asyncio.CancelledError:
547
+ self._cancel_delegated([task])
548
+ raise
549
+
550
+ self._delegated[task.id] = task
551
+
552
+ if not task.actions:
553
+ return describe_started(task)
554
+
555
+ return encode_json(self._show_actions(task))
556
+
557
+ async def wait_for_tasks(self, arguments: ToolArguments) -> str:
558
+ task_ids = read_list(arguments, "taskIds")
559
+ mode = read_optional_string(arguments, "mode")
560
+ chosen = "all" if mode is None else read_choice(mode, "mode", WAIT_MODES)
561
+ tasks = [self._find_delegated(task_id) for task_id in dict.fromkeys(task_ids)]
562
+ followed: dict[str, JsonObject] = {}
563
+
564
+ async def follow(task: OutgoingTask) -> None:
565
+ followed[task.id] = await self._follow_task(task)
566
+
567
+ following = [asyncio.create_task(follow(task)) for task in tasks]
568
+ settled = asyncio.ALL_COMPLETED if chosen == "all" else asyncio.FIRST_COMPLETED
569
+
570
+ try:
571
+ await asyncio.wait(following, return_when=settled)
572
+ except asyncio.CancelledError:
573
+ self._cancel_delegated([task for task in tasks if task.id not in followed])
574
+ raise
575
+ finally:
576
+ for pending in following:
577
+ pending.cancel()
578
+
579
+ for task_id, outcome in followed.items():
580
+ if outcome["status"] != "requires_action":
581
+ self._delegated.pop(task_id, None)
582
+ self._shown.pop(task_id, None)
583
+
584
+ outcomes = [
585
+ followed.get(task.id, {"taskId": task.id, "status": "working"})
586
+ for task in tasks
587
+ ]
588
+
589
+ return encode_json({"tasks": outcomes})
590
+
591
+ async def list_tasks(self, arguments: ToolArguments) -> str:
592
+ listed = read_optional_list(arguments, "statuses")
593
+ statuses = (
594
+ None
595
+ if listed is None
596
+ else [read_choice(status, "statuses", TASK_STATUSES) for status in listed]
597
+ )
598
+
599
+ page = await self._peer.list_tasks(
600
+ statuses=statuses,
601
+ agent=read_optional_string(arguments, "agent"),
602
+ watch=read_optional_string(arguments, "watch"),
603
+ unread=read_optional_boolean(arguments, "unread"),
604
+ cursor=read_optional_string(arguments, "cursor"),
605
+ )
606
+
607
+ return encode_json(page.to_wire())
608
+
609
+ async def recall_task(self, arguments: ToolArguments) -> str:
610
+ recap = await self._peer.recall_task(
611
+ TaskRef(
612
+ requester=read_string(arguments, "requester"),
613
+ task_id=read_string(arguments, "taskId"),
614
+ )
615
+ )
616
+
617
+ return encode_json(to_json_data(recap))
618
+
619
+ async def list_past_tasks(self, arguments: ToolArguments) -> str:
620
+ task = current_task()
621
+ if task is None:
622
+ return "No task is in progress, so it has no past tasks."
623
+
624
+ page = await task.list_history(cursor=read_optional_string(arguments, "cursor"))
625
+ tasks = [
626
+ {
627
+ "taskId": past.id,
628
+ **{key: value for key, value in past.to_wire().items() if key != "id"},
629
+ }
630
+ for past in page.tasks
631
+ ]
632
+
633
+ return encode_json(omit_none({"tasks": tasks, "next": page.next}))
634
+
635
+ async def publish_update(self, arguments: ToolArguments) -> str:
636
+ task = current_task()
637
+ if task is None:
638
+ return "No task is in progress, so the update was not sent."
639
+
640
+ await task.update(read_string(arguments, "text"))
641
+
642
+ return "Update sent."
643
+
644
+ async def deliver_file(self, arguments: ToolArguments) -> str:
645
+ task = current_task()
646
+ if task is None:
647
+ return "No task is in progress, so the file was not delivered."
648
+
649
+ name = read_string(arguments, "name")
650
+ content = read_string(arguments, "content")
651
+ mime_type = read_optional_string(arguments, "mimeType")
652
+ await task.deliver(
653
+ LabeledContent(content, name=name, mime_type=mime_type or None)
654
+ )
655
+
656
+ return f"Delivered {name}."
657
+
658
+ async def forward_artifact(self, arguments: ToolArguments) -> str:
659
+ task = current_task()
660
+ if task is None:
661
+ return "No task is in progress, so the artifact was not forwarded."
662
+
663
+ task_id = read_string(arguments, "taskId")
664
+ artifact_id = read_string(arguments, "artifactId")
665
+ received = self._shelf.find_artifact(task, task_id, artifact_id)
666
+ if received is None:
667
+ raise AgentJamError(
668
+ f'Task "{task_id}" returned no artifact "{artifact_id}" while you worked on the current task'
669
+ )
670
+
671
+ await task.deliver(construct_source(received))
672
+
673
+ return f'Forwarded artifact "{artifact_id}".'
674
+
675
+ async def rate_agent(self, arguments: ToolArguments) -> str:
676
+ review = await self._peer.rate(
677
+ read_string(arguments, "taskId"),
678
+ read_integer(arguments, "rating"),
679
+ read_optional_string(arguments, "text"),
680
+ )
681
+
682
+ return encode_json(review.to_wire())
683
+
684
+ async def dispute_task(self, arguments: ToolArguments) -> str:
685
+ dispute = await self._peer.dispute(
686
+ read_string(arguments, "taskId"), read_string(arguments, "reason")
687
+ )
688
+
689
+ return encode_json(dispute.to_wire())
690
+
691
+ async def list_reviews(self, arguments: ToolArguments) -> str:
692
+ page = await self._peer.reviews(
693
+ read_string(arguments, "agent"),
694
+ cursor=read_optional_string(arguments, "cursor"),
695
+ )
696
+
697
+ return encode_json(page.to_wire())
698
+
699
+ def _cancel_delegated(self, tasks: Sequence[OutgoingTask]) -> None:
700
+ reason = describe_cancellation()
701
+ for task in tasks:
702
+ self._delegated.pop(task.id, None)
703
+ self._shown.pop(task.id, None)
704
+ spawn(cancel_quietly(task, reason))
705
+
706
+ def _find_delegated(self, task_id: str) -> OutgoingTask:
707
+ task = self._delegated.get(task_id)
708
+ if task is None:
709
+ raise AgentJamError(
710
+ f'No task "{task_id}" was delegated without waiting or is waiting on your human'
711
+ )
712
+
713
+ return task
714
+
715
+ def _is_shown(self, task: OutgoingTask) -> bool:
716
+ shown = self._shown.get(task.id, set())
717
+
718
+ return all(action.url in shown for action in task.actions)
719
+
720
+ def _show_actions(self, task: OutgoingTask) -> JsonObject:
721
+ self._shown[task.id] = {action.url for action in task.actions}
722
+
723
+ return describe_actions(task)
724
+
725
+ def _has_new_links(self, task: OutgoingTask) -> bool:
726
+ return current_task() is None and not self._is_shown(task)
727
+
728
+ async def _await_links(self, task: OutgoingTask) -> bool:
729
+ """Returns False once the task ends, or True once its human must open links the model hasn't shown them.
730
+
731
+ The links of a task delegated as part of the current one already reach the human through its requester, so they never wake the model.
732
+ """
733
+ if self._has_new_links(task):
734
+ return True
735
+
736
+ with contextlib.suppress(Exception):
737
+ async for event in task.events():
738
+ if event.type == "actions" and self._has_new_links(task):
739
+ return True
740
+
741
+ return False
742
+
743
+ async def _follow_task(self, task: OutgoingTask) -> JsonObject:
744
+ if await self._await_links(task):
745
+ return self._show_actions(task)
746
+
747
+ return await self._settle_task(task)
748
+
749
+ async def _settle_task(self, task: OutgoingTask) -> JsonObject:
750
+ try:
751
+ artifacts = await task.result()
752
+ output = await task.get_output()
753
+ except TaskCanceledError as error:
754
+ return omit_none(
755
+ {
756
+ "taskId": task.id,
757
+ "status": "canceled",
758
+ "code": error.code,
759
+ "error": str(error),
760
+ }
761
+ )
762
+ except Exception as error:
763
+ return {
764
+ "taskId": task.id,
765
+ "status": "failed",
766
+ "error": describe_error(error),
767
+ }
768
+
769
+ return omit_none(
770
+ {
771
+ "taskId": task.id,
772
+ "status": "completed",
773
+ "output": output,
774
+ "artifacts": self._shelf.summarize_artifacts(task.id, artifacts),
775
+ }
776
+ )
777
+
778
+ async def _encode_result(self, task: OutgoingTask) -> str:
779
+ artifacts = await task.result()
780
+ output = await task.get_output()
781
+
782
+ return encode_json(
783
+ omit_none(
784
+ {
785
+ "taskId": task.id,
786
+ "output": output,
787
+ "artifacts": self._shelf.summarize_artifacts(task.id, artifacts),
788
+ }
789
+ )
790
+ )
791
+
792
+
793
+ def pick_tools(
794
+ tools: Sequence[NetworkTool], names: Sequence[ToolName]
795
+ ) -> list[NetworkTool]:
796
+ """Keeps the tools in `names`, in the order of `tools`.
797
+
798
+ Args:
799
+ tools: The tools to pick from.
800
+ names: The names of the tools to keep.
801
+ Returns:
802
+ The picked tools.
803
+ Raises:
804
+ AgentJamError: If a name in `names` isn't among `tools`.
805
+ """
806
+ available = {tool.name for tool in tools}
807
+ missing = next((name for name in names if name not in available), None)
808
+ if missing is not None:
809
+ raise AgentJamError(
810
+ f'The agent has no network tool named "{missing}". Check that network_tools in connect() enables it.'
811
+ )
812
+
813
+ picked = set(names)
814
+
815
+ return [tool for tool in tools if tool.name in picked]
816
+
817
+
818
+ def create_network_tools(peer: Peer, settings: ToolSettings) -> list[NetworkTool]:
819
+ """Builds the tools that let a model discover, message, and delegate to other agents.
820
+
821
+ Args:
822
+ peer: The agent the tools act through.
823
+ settings: How the agent handles delegated tasks.
824
+ Returns:
825
+ The network tools, in the order of `network_tool_names`.
826
+ """
827
+ toolkit = NetworkToolkit(peer, settings)
828
+ watch_description = (
829
+ "A watch group shared by related tasks, whose outcomes reach you together once all of them end"
830
+ if settings.watching
831
+ else "A watch group shared by related tasks, to list them together with list_tasks"
832
+ )
833
+
834
+ tools = [
835
+ NetworkTool(
836
+ name="find_agents",
837
+ description=f"Search the network for other agents. Filter by an exact skill name or free-text query, or omit both to list every agent. A skill's inputSchema is the JSON Schema its tasks' input must match, its outputSchema the JSON Schema of the output its tasks return, and its connections the accounts its agent needs your human to connect. {PREPARE_HINT} {IRREVERSIBLE_HINT}",
838
+ input_schema=construct_object_schema(
839
+ {},
840
+ {
841
+ "skill": "The exact name of a skill the agent must advertise",
842
+ "query": "Words to match against agent names, descriptions, and skills",
843
+ },
844
+ ),
845
+ run=toolkit.find_agents,
846
+ ),
847
+ NetworkTool(
848
+ name="prepare_delegates",
849
+ description="Ask the agents you'll delegate parts of the current task to for the accounts their skills need, so your human connects them all now rather than once each handoff starts. Call it once you've picked them, and only with agents you'll actually delegate to, since each may ask your human to connect an account. The links reach your human through the agent that assigned you the task.",
850
+ input_schema=construct_object_schema(
851
+ {
852
+ "delegates": TypedField(
853
+ "array",
854
+ "The agents you'll delegate to, each with the skill of theirs you'll call for",
855
+ fields={
856
+ "agent": "The agent's address, username/agent-name",
857
+ "skill": "The name of the agent's skill",
858
+ },
859
+ )
860
+ }
861
+ ),
862
+ run=toolkit.prepare_delegates,
863
+ ),
864
+ NetworkTool(
865
+ name="send_message",
866
+ description="Send a message to another agent and wait for its reply, which comes with a description of any files attached to it. Pass the conversationId from an earlier reply to continue that conversation, and a taskId to ask about a task you share with the agent, which shows it that task's request and results. To change a running task you delegated, also set steer to true: when the agent supports it the work in progress takes the change, and the reply says the message was passed to the running task. Leave steer unset for a question, such as about progress, so the agent answers it.",
867
+ input_schema=construct_object_schema(
868
+ {
869
+ "agent": "The address of the agent to message, username/agent-name",
870
+ "text": "The message to send",
871
+ },
872
+ {
873
+ "conversationId": "The conversationId of an earlier reply, to continue that thread",
874
+ "taskId": "The taskId of a task you delegated to the agent or it assigned you, which the message is about. Defaults to the current task when messaging the agent that assigned it",
875
+ "steer": TypedField(
876
+ "boolean",
877
+ "Whether the message changes the running task taskId names, which you delegated, rather than asking about it",
878
+ ),
879
+ },
880
+ ),
881
+ run=toolkit.send_message,
882
+ ),
883
+ NetworkTool(
884
+ name="delegate_task",
885
+ description=f'Delegate a task to another agent and wait for it to finish. Returns the taskId, the text it produced, and a description of any files, or links your human must open for it to go on. Set wait to false to start several tasks at once, then wait for them with wait_for_tasks. When the skill lists an inputSchema, also pass input matching it, since the task is refused without it. To run one of your own skills as a separate task, delegate to your own name, "{peer.name}". You can\'t delegate to an agent earlier in the chain of tasks that led to yours, such as the one that assigned you the current task. {FOLLOW_UP_HINT} {PREPARE_HINT} {IRREVERSIBLE_HINT}',
886
+ input_schema=construct_object_schema(
887
+ {
888
+ "agent": "The address of the agent to delegate to, username/agent-name",
889
+ "task": "A complete description of the task",
890
+ },
891
+ {
892
+ "skill": "The name of the agent's skill the task calls for",
893
+ "input": "The skill's structured input, as JSON text of an object matching the inputSchema find_agents lists for it",
894
+ "maxPriceCents": TypedField(
895
+ "number",
896
+ "The most you will pay if the skill is priced, in cents, such as 0.5 for half a cent. Omit it to pay up to the skill's listed price",
897
+ ),
898
+ "wait": TypedField(
899
+ "boolean",
900
+ "Whether to wait for the task to finish. Defaults to true",
901
+ ),
902
+ "watch": watch_description,
903
+ "follows": "The taskId of an ended task you delegated to the same agent, which this task follows up on, such as to revise its result",
904
+ },
905
+ ),
906
+ run=toolkit.delegate_task,
907
+ ),
908
+ NetworkTool(
909
+ name="wait_for_tasks",
910
+ description="Wait for tasks that delegate_task started without waiting, or left waiting on your human once they opened its links. Returns each task's result or why it failed or was canceled, or new links your human must open for an agent it delegated to, and leaves the ones still running as working.",
911
+ input_schema=construct_object_schema(
912
+ {
913
+ "taskIds": TypedField(
914
+ "array", "The taskIds that delegate_task returned"
915
+ )
916
+ },
917
+ {
918
+ "mode": TypedField(
919
+ "string",
920
+ "all to wait until every task ends, or any to wait until one does. Defaults to all",
921
+ values=WAIT_MODES,
922
+ )
923
+ },
924
+ ),
925
+ run=toolkit.wait_for_tasks,
926
+ ),
927
+ NetworkTool(
928
+ name="list_tasks",
929
+ description="List the tasks you delegated, newest first, with each one's agent, status, latest update and whether it has a result. Filter by status, agent or watch group, and pass the next cursor from a page to get the one after it.",
930
+ input_schema=construct_object_schema(
931
+ {},
932
+ {
933
+ "statuses": TypedField(
934
+ "array",
935
+ "Only tasks in one of these statuses",
936
+ values=TASK_STATUSES,
937
+ ),
938
+ "agent": "Only tasks delegated to this agent",
939
+ "watch": "Only tasks delegated with this watch group",
940
+ "unread": TypedField(
941
+ "boolean",
942
+ "true for only ended tasks whose outcome you haven't received",
943
+ ),
944
+ "cursor": "The next cursor of an earlier page, to continue it",
945
+ },
946
+ ),
947
+ run=toolkit.list_tasks,
948
+ ),
949
+ NetworkTool(
950
+ name="recall_task",
951
+ description="Recall what a task you worked on asked for and produced: its request and input, latest updates and results, and the conversation about it. Use it for an earlier task in a follow-up's chain, such as the one a recap's followUp names as previous, or for one list_past_tasks lists.",
952
+ input_schema=construct_object_schema(
953
+ {
954
+ "requester": "The address of the agent that assigned you the task",
955
+ "taskId": "The task's taskId",
956
+ }
957
+ ),
958
+ run=toolkit.recall_task,
959
+ ),
960
+ NetworkTool(
961
+ name="list_past_tasks",
962
+ description="List the earlier tasks you ran that the current task can look back on, newest first: for a scheduled run, its schedule's earlier runs; for a one-off, your earlier tasks of the same skill for the same human. Pass a task's requester and taskId to recall_task for what it produced, and the next cursor from a page to get the one after it.",
963
+ input_schema=construct_object_schema(
964
+ {}, {"cursor": "The next cursor of an earlier page, to continue it"}
965
+ ),
966
+ run=toolkit.list_past_tasks,
967
+ ),
968
+ NetworkTool(
969
+ name="publish_update",
970
+ description="Send a short progress update to the agent that assigned you the current task.",
971
+ input_schema=construct_object_schema({"text": "The progress update"}),
972
+ run=toolkit.publish_update,
973
+ ),
974
+ NetworkTool(
975
+ name="deliver_file",
976
+ description="Send a file to the agent that assigned you the current task, as one of the task's results. Each call delivers a separate file.",
977
+ input_schema=construct_object_schema(
978
+ {
979
+ "name": "The file name, including its extension",
980
+ "content": "The file's full text content",
981
+ },
982
+ {"mimeType": "The file's MIME type, such as text/csv"},
983
+ ),
984
+ run=toolkit.deliver_file,
985
+ ),
986
+ NetworkTool(
987
+ name="forward_artifact",
988
+ description="Deliver a file or text that a task you delegated returned to the agent that assigned you the current task, as one of the current task's results.",
989
+ input_schema=construct_object_schema(
990
+ {
991
+ "taskId": "The taskId of the delegated task that returned it",
992
+ "artifactId": "The artifact's id among that task's artifacts",
993
+ }
994
+ ),
995
+ run=toolkit.forward_artifact,
996
+ ),
997
+ NetworkTool(
998
+ name="rate_agent",
999
+ description="Rate the agent that completed a task you delegated, with an optional short review. Each task can be rated once, after it completed with a result.",
1000
+ input_schema=construct_object_schema(
1001
+ {
1002
+ "taskId": "The taskId that delegate_task returned",
1003
+ "rating": TypedField("integer", "From 1 (poor) to 5 (excellent)"),
1004
+ },
1005
+ {"text": "A short written review"},
1006
+ ),
1007
+ run=toolkit.rate_agent,
1008
+ ),
1009
+ NetworkTool(
1010
+ name="dispute_task",
1011
+ description="Dispute a task you delegated and paid for, asking for a refund to your human's credits. Only do this when your human asks for a refund, and ask them why first, since the AgentJam team reviews the reason. A task can be disputed once, within 7 days of its charge.",
1012
+ input_schema=construct_object_schema(
1013
+ {
1014
+ "taskId": "The taskId that delegate_task returned",
1015
+ "reason": "Why your human wants a refund, in their words, from 20 to 2000 characters",
1016
+ }
1017
+ ),
1018
+ run=toolkit.dispute_task,
1019
+ ),
1020
+ NetworkTool(
1021
+ name="list_reviews",
1022
+ description="List the reviews of an agent, newest first. Pass the next cursor from a page to get the one after it.",
1023
+ input_schema=construct_object_schema(
1024
+ {
1025
+ "agent": "The address of the agent whose reviews to list, username/agent-name"
1026
+ },
1027
+ {"cursor": "The next cursor of an earlier page, to continue it"},
1028
+ ),
1029
+ run=toolkit.list_reviews,
1030
+ ),
1031
+ ]
1032
+
1033
+ return [
1034
+ tool for tool in tools if settings.forwarding or tool.name != "forward_artifact"
1035
+ ]