@agentjam/sdk 0.0.0-stage → 0.2.0

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 (274) hide show
  1. package/README.md +181 -2
  2. package/dist/adapters/ai.d.ts +47 -0
  3. package/dist/adapters/ai.d.ts.map +1 -0
  4. package/dist/adapters/ai.js +168 -0
  5. package/dist/adapters/ai.js.map +1 -0
  6. package/dist/adapters/anthropic.d.ts +68 -0
  7. package/dist/adapters/anthropic.d.ts.map +1 -0
  8. package/dist/adapters/anthropic.js +193 -0
  9. package/dist/adapters/anthropic.js.map +1 -0
  10. package/dist/adapters/openai.d.ts +35 -0
  11. package/dist/adapters/openai.d.ts.map +1 -0
  12. package/dist/adapters/openai.js +80 -0
  13. package/dist/adapters/openai.js.map +1 -0
  14. package/dist/adapters/openaiAgents.d.ts +39 -0
  15. package/dist/adapters/openaiAgents.d.ts.map +1 -0
  16. package/dist/adapters/openaiAgents.js +152 -0
  17. package/dist/adapters/openaiAgents.js.map +1 -0
  18. package/dist/adapters/shared.d.ts +72 -0
  19. package/dist/adapters/shared.d.ts.map +1 -0
  20. package/dist/adapters/shared.js +174 -0
  21. package/dist/adapters/shared.js.map +1 -0
  22. package/dist/agent.d.ts +462 -0
  23. package/dist/agent.d.ts.map +1 -0
  24. package/dist/agent.js +1820 -0
  25. package/dist/agent.js.map +1 -0
  26. package/dist/artifacts.d.ts +79 -0
  27. package/dist/artifacts.d.ts.map +1 -0
  28. package/dist/artifacts.js +367 -0
  29. package/dist/artifacts.js.map +1 -0
  30. package/dist/attachments.d.ts +43 -0
  31. package/dist/attachments.d.ts.map +1 -0
  32. package/dist/attachments.js +69 -0
  33. package/dist/attachments.js.map +1 -0
  34. package/dist/connections.d.ts +109 -0
  35. package/dist/connections.d.ts.map +1 -0
  36. package/dist/connections.js +274 -0
  37. package/dist/connections.js.map +1 -0
  38. package/dist/content.d.ts +36 -0
  39. package/dist/content.d.ts.map +1 -0
  40. package/dist/content.js +21 -0
  41. package/dist/content.js.map +1 -0
  42. package/dist/cron.d.ts +31 -0
  43. package/dist/cron.d.ts.map +1 -0
  44. package/dist/cron.js +93 -0
  45. package/dist/cron.js.map +1 -0
  46. package/dist/errors.d.ts +227 -0
  47. package/dist/errors.d.ts.map +1 -0
  48. package/dist/errors.js +253 -0
  49. package/dist/errors.js.map +1 -0
  50. package/dist/events.d.ts +57 -0
  51. package/dist/events.d.ts.map +1 -0
  52. package/dist/events.js +24 -0
  53. package/dist/events.js.map +1 -0
  54. package/dist/idempotency.d.ts +21 -0
  55. package/dist/idempotency.d.ts.map +1 -0
  56. package/dist/idempotency.js +46 -0
  57. package/dist/idempotency.js.map +1 -0
  58. package/dist/index.d.ts +44 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +18 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/inputs.d.ts +22 -0
  63. package/dist/inputs.d.ts.map +1 -0
  64. package/dist/inputs.js +72 -0
  65. package/dist/inputs.js.map +1 -0
  66. package/dist/mpp.d.ts +76 -0
  67. package/dist/mpp.d.ts.map +1 -0
  68. package/dist/mpp.js +113 -0
  69. package/dist/mpp.js.map +1 -0
  70. package/dist/oauth.d.ts +3 -0
  71. package/dist/oauth.d.ts.map +1 -0
  72. package/dist/oauth.js +2 -0
  73. package/dist/oauth.js.map +1 -0
  74. package/dist/oauthCallbacks.d.ts +2 -0
  75. package/dist/oauthCallbacks.d.ts.map +1 -0
  76. package/dist/oauthCallbacks.js +58 -0
  77. package/dist/oauthCallbacks.js.map +1 -0
  78. package/dist/platforms/datadog.d.ts +10 -0
  79. package/dist/platforms/datadog.d.ts.map +1 -0
  80. package/dist/platforms/datadog.js +15 -0
  81. package/dist/platforms/datadog.js.map +1 -0
  82. package/dist/platforms/github.d.ts +181 -0
  83. package/dist/platforms/github.d.ts.map +1 -0
  84. package/dist/platforms/github.js +468 -0
  85. package/dist/platforms/github.js.map +1 -0
  86. package/dist/platforms/google.d.ts +19 -0
  87. package/dist/platforms/google.d.ts.map +1 -0
  88. package/dist/platforms/google.js +70 -0
  89. package/dist/platforms/google.js.map +1 -0
  90. package/dist/platforms/grafana.d.ts +10 -0
  91. package/dist/platforms/grafana.d.ts.map +1 -0
  92. package/dist/platforms/grafana.js +14 -0
  93. package/dist/platforms/grafana.js.map +1 -0
  94. package/dist/platforms/posthog.d.ts +10 -0
  95. package/dist/platforms/posthog.d.ts.map +1 -0
  96. package/dist/platforms/posthog.js +14 -0
  97. package/dist/platforms/posthog.js.map +1 -0
  98. package/dist/platforms/presets.d.ts +34 -0
  99. package/dist/platforms/presets.d.ts.map +1 -0
  100. package/dist/platforms/presets.js +36 -0
  101. package/dist/platforms/presets.js.map +1 -0
  102. package/dist/platforms/sentry.d.ts +79 -0
  103. package/dist/platforms/sentry.d.ts.map +1 -0
  104. package/dist/platforms/sentry.js +124 -0
  105. package/dist/platforms/sentry.js.map +1 -0
  106. package/dist/platforms/slack.d.ts +101 -0
  107. package/dist/platforms/slack.d.ts.map +1 -0
  108. package/dist/platforms/slack.js +309 -0
  109. package/dist/platforms/slack.js.map +1 -0
  110. package/dist/platforms/splunk.d.ts +10 -0
  111. package/dist/platforms/splunk.d.ts.map +1 -0
  112. package/dist/platforms/splunk.js +14 -0
  113. package/dist/platforms/splunk.js.map +1 -0
  114. package/dist/polling.d.ts +2 -0
  115. package/dist/polling.d.ts.map +1 -0
  116. package/dist/polling.js +66 -0
  117. package/dist/polling.js.map +1 -0
  118. package/dist/profile.d.ts +60 -0
  119. package/dist/profile.d.ts.map +1 -0
  120. package/dist/profile.js +119 -0
  121. package/dist/profile.js.map +1 -0
  122. package/dist/protocol.d.ts +474 -0
  123. package/dist/protocol.d.ts.map +1 -0
  124. package/dist/protocol.js +2 -0
  125. package/dist/protocol.js.map +1 -0
  126. package/dist/providers.d.ts +113 -0
  127. package/dist/providers.d.ts.map +1 -0
  128. package/dist/providers.js +98 -0
  129. package/dist/providers.js.map +1 -0
  130. package/dist/recaps.d.ts +10 -0
  131. package/dist/recaps.d.ts.map +1 -0
  132. package/dist/recaps.js +49 -0
  133. package/dist/recaps.js.map +1 -0
  134. package/dist/relay/chains.d.ts +62 -0
  135. package/dist/relay/chains.d.ts.map +1 -0
  136. package/dist/relay/chains.js +150 -0
  137. package/dist/relay/chains.js.map +1 -0
  138. package/dist/relay/credentials.d.ts +25 -0
  139. package/dist/relay/credentials.d.ts.map +1 -0
  140. package/dist/relay/credentials.js +234 -0
  141. package/dist/relay/credentials.js.map +1 -0
  142. package/dist/relay/endpoints.d.ts +13 -0
  143. package/dist/relay/endpoints.d.ts.map +1 -0
  144. package/dist/relay/endpoints.js +13 -0
  145. package/dist/relay/endpoints.js.map +1 -0
  146. package/dist/relay/frames.d.ts +193 -0
  147. package/dist/relay/frames.d.ts.map +1 -0
  148. package/dist/relay/frames.js +161 -0
  149. package/dist/relay/frames.js.map +1 -0
  150. package/dist/relay/grants.d.ts +158 -0
  151. package/dist/relay/grants.d.ts.map +1 -0
  152. package/dist/relay/grants.js +2 -0
  153. package/dist/relay/grants.js.map +1 -0
  154. package/dist/relay/guestStore.d.ts +37 -0
  155. package/dist/relay/guestStore.d.ts.map +1 -0
  156. package/dist/relay/guestStore.js +61 -0
  157. package/dist/relay/guestStore.js.map +1 -0
  158. package/dist/relay/guests.d.ts +7 -0
  159. package/dist/relay/guests.d.ts.map +1 -0
  160. package/dist/relay/guests.js +30 -0
  161. package/dist/relay/guests.js.map +1 -0
  162. package/dist/relay/memory.d.ts +60 -0
  163. package/dist/relay/memory.d.ts.map +1 -0
  164. package/dist/relay/memory.js +334 -0
  165. package/dist/relay/memory.js.map +1 -0
  166. package/dist/relay/payments.d.ts +43 -0
  167. package/dist/relay/payments.d.ts.map +1 -0
  168. package/dist/relay/payments.js +115 -0
  169. package/dist/relay/payments.js.map +1 -0
  170. package/dist/relay/profiles.d.ts +10 -0
  171. package/dist/relay/profiles.d.ts.map +1 -0
  172. package/dist/relay/profiles.js +43 -0
  173. package/dist/relay/profiles.js.map +1 -0
  174. package/dist/relay/relay.d.ts +133 -0
  175. package/dist/relay/relay.d.ts.map +1 -0
  176. package/dist/relay/relay.js +2 -0
  177. package/dist/relay/relay.js.map +1 -0
  178. package/dist/relay/remote.d.ts +39 -0
  179. package/dist/relay/remote.d.ts.map +1 -0
  180. package/dist/relay/remote.js +492 -0
  181. package/dist/relay/remote.js.map +1 -0
  182. package/dist/relay/revisions.d.ts +13 -0
  183. package/dist/relay/revisions.d.ts.map +1 -0
  184. package/dist/relay/revisions.js +34 -0
  185. package/dist/relay/revisions.js.map +1 -0
  186. package/dist/relay/schedules.d.ts +41 -0
  187. package/dist/relay/schedules.d.ts.map +1 -0
  188. package/dist/relay/schedules.js +217 -0
  189. package/dist/relay/schedules.js.map +1 -0
  190. package/dist/relay/secrets.d.ts +14 -0
  191. package/dist/relay/secrets.d.ts.map +1 -0
  192. package/dist/relay/secrets.js +30 -0
  193. package/dist/relay/secrets.js.map +1 -0
  194. package/dist/relay/sessions.d.ts +59 -0
  195. package/dist/relay/sessions.d.ts.map +1 -0
  196. package/dist/relay/sessions.js +282 -0
  197. package/dist/relay/sessions.js.map +1 -0
  198. package/dist/relay/uploads.d.ts +15 -0
  199. package/dist/relay/uploads.d.ts.map +1 -0
  200. package/dist/relay/uploads.js +55 -0
  201. package/dist/relay/uploads.js.map +1 -0
  202. package/dist/requests.d.ts +22 -0
  203. package/dist/requests.d.ts.map +1 -0
  204. package/dist/requests.js +64 -0
  205. package/dist/requests.js.map +1 -0
  206. package/dist/screening.d.ts +93 -0
  207. package/dist/screening.d.ts.map +1 -0
  208. package/dist/screening.js +176 -0
  209. package/dist/screening.js.map +1 -0
  210. package/dist/secrets.d.ts +38 -0
  211. package/dist/secrets.d.ts.map +1 -0
  212. package/dist/secrets.js +162 -0
  213. package/dist/secrets.js.map +1 -0
  214. package/dist/skills.d.ts +11 -0
  215. package/dist/skills.d.ts.map +1 -0
  216. package/dist/skills.js +55 -0
  217. package/dist/skills.js.map +1 -0
  218. package/dist/stripe.d.ts +10 -0
  219. package/dist/stripe.d.ts.map +1 -0
  220. package/dist/stripe.js +51 -0
  221. package/dist/stripe.js.map +1 -0
  222. package/dist/tasks/access.d.ts +35 -0
  223. package/dist/tasks/access.d.ts.map +1 -0
  224. package/dist/tasks/access.js +101 -0
  225. package/dist/tasks/access.js.map +1 -0
  226. package/dist/tasks/incoming.d.ts +333 -0
  227. package/dist/tasks/incoming.d.ts.map +1 -0
  228. package/dist/tasks/incoming.js +354 -0
  229. package/dist/tasks/incoming.js.map +1 -0
  230. package/dist/tasks/outgoing.d.ts +137 -0
  231. package/dist/tasks/outgoing.d.ts.map +1 -0
  232. package/dist/tasks/outgoing.js +233 -0
  233. package/dist/tasks/outgoing.js.map +1 -0
  234. package/dist/tasks/scheduled.d.ts +76 -0
  235. package/dist/tasks/scheduled.d.ts.map +1 -0
  236. package/dist/tasks/scheduled.js +110 -0
  237. package/dist/tasks/scheduled.js.map +1 -0
  238. package/dist/tasks/triggers.d.ts +47 -0
  239. package/dist/tasks/triggers.d.ts.map +1 -0
  240. package/dist/tasks/triggers.js +149 -0
  241. package/dist/tasks/triggers.js.map +1 -0
  242. package/dist/tasks/watches.d.ts +13 -0
  243. package/dist/tasks/watches.d.ts.map +1 -0
  244. package/dist/tasks/watches.js +54 -0
  245. package/dist/tasks/watches.js.map +1 -0
  246. package/dist/tools.d.ts +85 -0
  247. package/dist/tools.d.ts.map +1 -0
  248. package/dist/tools.js +627 -0
  249. package/dist/tools.js.map +1 -0
  250. package/dist/types.d.ts +926 -0
  251. package/dist/types.d.ts.map +1 -0
  252. package/dist/types.js +2 -0
  253. package/dist/types.js.map +1 -0
  254. package/dist/vaults/local.d.ts +54 -0
  255. package/dist/vaults/local.d.ts.map +1 -0
  256. package/dist/vaults/local.js +362 -0
  257. package/dist/vaults/local.js.map +1 -0
  258. package/dist/vaults/remote.d.ts +78 -0
  259. package/dist/vaults/remote.d.ts.map +1 -0
  260. package/dist/vaults/remote.js +295 -0
  261. package/dist/vaults/remote.js.map +1 -0
  262. package/dist/vaults/vault.d.ts +69 -0
  263. package/dist/vaults/vault.d.ts.map +1 -0
  264. package/dist/vaults/vault.js +19 -0
  265. package/dist/vaults/vault.js.map +1 -0
  266. package/dist/verdicts.d.ts +15 -0
  267. package/dist/verdicts.d.ts.map +1 -0
  268. package/dist/verdicts.js +17 -0
  269. package/dist/verdicts.js.map +1 -0
  270. package/dist/watermarks.d.ts +29 -0
  271. package/dist/watermarks.d.ts.map +1 -0
  272. package/dist/watermarks.js +11 -0
  273. package/dist/watermarks.js.map +1 -0
  274. package/package.json +160 -3
package/dist/agent.js ADDED
@@ -0,0 +1,1820 @@
1
+ import { constructFile, receiveAttachments } from "./attachments.js";
2
+ import { bindGrantVault, Readiness, receiveRevocation, unbindGrantVault, } from "./connections.js";
3
+ import { DEFAULT_TIME_ZONE } from "./cron.js";
4
+ import { AgentJamError, AgentNotFoundError, describeError, FollowUpFailedError, TaskFailedError, TaskRejectedError, TriggerFailedError, } from "./errors.js";
5
+ import { IdempotencyCache } from "./idempotency.js";
6
+ import { isStoredSchema, parseValue } from "./inputs.js";
7
+ import { receiveOAuthCallback } from "./oauthCallbacks.js";
8
+ import { recapFromWire } from "./recaps.js";
9
+ import { ReassignedError } from "./relay/frames.js";
10
+ import { AgentJamRelay } from "./relay/remote.js";
11
+ import { PendingRequests } from "./requests.js";
12
+ import { screenProposal } from "./screening.js";
13
+ import { constructSecretSource, isSecretConnection, isSecretSource, } from "./secrets.js";
14
+ import { AccessWaits } from "./tasks/access.js";
15
+ import { currentTask, TaskExecution } from "./tasks/incoming.js";
16
+ import { TaskHandle } from "./tasks/outgoing.js";
17
+ import { ScheduleHandle } from "./tasks/scheduled.js";
18
+ import { TriggerRunner } from "./tasks/triggers.js";
19
+ import { TaskWatches } from "./tasks/watches.js";
20
+ import { createNetworkTools, pickTools } from "./tools.js";
21
+ import { lostGrant, requestersOf } from "./vaults/vault.js";
22
+ import { accept, reject } from "./verdicts.js";
23
+ const defaultTimeout = 30_000;
24
+ const allForwarded = {
25
+ updates: true,
26
+ questions: true,
27
+ files: true,
28
+ };
29
+ const dedupeWindow = 10 * 60_000;
30
+ const noReviews = "This relay doesn't support reviews";
31
+ const noDisputes = "This relay doesn't support disputes";
32
+ const noTaskList = "This relay doesn't list tasks";
33
+ const noRecall = "This relay doesn't recall tasks";
34
+ const noHistory = "This relay doesn't keep task history";
35
+ const steered = "Passed your message to the running task, which reads it before its next step.";
36
+ const noUploads = "This relay doesn't take attachments";
37
+ const maxAttachments = 10;
38
+ const untaskedAttachments = "Only a message about a task, or a reply to one, can carry attachments";
39
+ const untaskedSteer = "Only a message about a task can steer it";
40
+ const maxTaskPage = 100;
41
+ const openStatuses = ["proposed", "requires_action", "working"];
42
+ const unfollowed = (reason) => new AgentJamError(`${reason}. The task keeps running, and collect() reattaches it after reconnecting`);
43
+ const noWatchHandler = "Pass onWatchResolved to connect() to watch delegated tasks";
44
+ const key = (peer, id) => `${peer}/${id}`;
45
+ const toMessage = ({ id, from, to, conversationId, text, }) => ({
46
+ id,
47
+ from,
48
+ to,
49
+ conversationId,
50
+ text,
51
+ });
52
+ const warnGuest = (name, claimUrl) => {
53
+ console.warn(`"${name}" is a guest agent, which runs only free tasks until its human claims it at ${claimUrl}`);
54
+ };
55
+ export const warnPayouts = (name, payoutsUrl) => {
56
+ console.warn(`"${name}" takes only free tasks until your human sets up payouts at ${payoutsUrl}`);
57
+ };
58
+ const logRun = async (run) => {
59
+ try {
60
+ const artifacts = await run.result();
61
+ console.info(`Run ${run.id} of schedule ${run.scheduleId} with ${run.to} completed with ${artifacts.length} artifacts`);
62
+ }
63
+ catch (error) {
64
+ console.warn(`Run ${run.id} of schedule ${run.scheduleId} with ${run.to} failed: ${describeError(error)}`);
65
+ }
66
+ };
67
+ const logFollowUp = async (task) => {
68
+ try {
69
+ const artifacts = await task.result();
70
+ console.info(`Follow-up ${task.id} with ${task.to} completed with ${artifacts.length} artifacts`);
71
+ }
72
+ catch (error) {
73
+ console.warn(`Follow-up ${task.id} with ${task.to} failed: ${describeError(error)}`);
74
+ }
75
+ };
76
+ const isRun = (task) => task.scheduleId !== undefined;
77
+ const isSchedule = ({ cron, trigger }) => cron !== undefined || trigger !== undefined;
78
+ const eventOf = ({ eventId, summary = "", eventData, }) => eventId === undefined
79
+ ? undefined
80
+ : { id: eventId, summary, ...(eventData && { data: eventData }) };
81
+ const watchOf = ({ scheduleId, from, principal, text, skill, trigger, config, input, expiresAt, }) => ({
82
+ id: scheduleId,
83
+ from,
84
+ ...(principal === undefined ? {} : { principal }),
85
+ text,
86
+ skill,
87
+ trigger,
88
+ config,
89
+ ...(input === undefined ? {} : { input }),
90
+ ...(expiresAt === undefined ? {} : { expiresAt: new Date(expiresAt) }),
91
+ });
92
+ const toProposal = ({ from, principal, text, skill, input, cron, trigger, budget, expiresAt, follows, previous, }, attachments) => ({
93
+ from,
94
+ ...(principal === undefined ? {} : { principal }),
95
+ text,
96
+ ...(skill === undefined ? {} : { skill }),
97
+ ...(input === undefined ? {} : { input }),
98
+ ...(cron === undefined
99
+ ? {}
100
+ : { cron: { ...cron, timeZone: cron.timeZone ?? DEFAULT_TIME_ZONE } }),
101
+ ...(trigger === undefined ? {} : { trigger }),
102
+ ...(budget === undefined ? {} : { budget }),
103
+ ...(expiresAt === undefined ? {} : { expiresAt: new Date(expiresAt) }),
104
+ attachments,
105
+ ...(follows === undefined ? {} : { follows }),
106
+ ...(previous === undefined ? {} : { previous: recapFromWire(previous) }),
107
+ });
108
+ const warnRevoking = (name, { from, skill }, sources) => {
109
+ const providers = Array.from(sources)
110
+ .filter((source) => source.revokeOnEnd && !isSecretSource(source))
111
+ .map(({ provider }) => provider);
112
+ if (providers.length === 0)
113
+ return;
114
+ console.warn(`"${name}" prepares the "${skill}" skill for ${from}, but its ${providers.join(" and ")} connection revokes each grant once nothing uses it, so the work it prepares for asks the human to connect again. Turn off revokeOnEnd to keep the grant for it`);
115
+ };
116
+ const describeAction = ({ provider, url, origin, reason }) => {
117
+ const account = origin
118
+ ? `their ${provider} account for ${origin.executor}`
119
+ : `their ${provider} account`;
120
+ return reason ? `${account} (${reason}) at ${url}` : `${account} at ${url}`;
121
+ };
122
+ const warnActions = ({ peer, proposalId, actions }) => {
123
+ const links = actions.map(describeAction).join(" and ");
124
+ const blocked = actions.some(({ origin, reason }) => origin ?? reason)
125
+ ? "can't go on with"
126
+ : "can't start";
127
+ console.warn(`${peer} ${blocked} ${proposalId} until your human connects ${links}`);
128
+ };
129
+ const actionsOf = (verdict) => verdict.type === "task.require" ? verdict.actions : [];
130
+ const ownProvidersOf = (verdict) => actionsOf(verdict)
131
+ .filter(({ origin }) => origin === undefined)
132
+ .map(({ provider }) => provider);
133
+ const awaitPreparations = (preparations) => Promise.allSettled(preparations.map((preparation) => preparation.result()));
134
+ const isAccepting = ({ type }) => type === "task.accept" || type === "task.require";
135
+ const ignoreReassigned = (error) => {
136
+ if (!(error instanceof ReassignedError))
137
+ throw error;
138
+ };
139
+ const unexpected = (reply) => new AgentJamError(`${reply.from} sent an unexpected ${reply.type}`);
140
+ const constructQuestionOptions = (task, { signal, timeoutMs = Infinity, ...options }) => ({
141
+ ...options,
142
+ signal: signal ? AbortSignal.any([signal, task.signal]) : task.signal,
143
+ timeoutMs,
144
+ });
145
+ const assertGrantVault = (connection, name) => {
146
+ if (!connection.credentials?.oauth) {
147
+ throw new AgentJamError(`The relay ${name} connects to holds no OAuth grants, so pass a store to each of its OAuth connections`);
148
+ }
149
+ };
150
+ const isSource = (connection) => "authorize" in connection && typeof connection.authorize === "function";
151
+ const actionKindOf = (source) => isSecretSource(source) ? "credential_form" : "oauth";
152
+ const sourcesOf = ({ name, connections = [] }, bindSecret) => new Map(connections.map((connection) => {
153
+ if (isSecretConnection(connection)) {
154
+ return [connection.provider, bindSecret(connection)];
155
+ }
156
+ if (!isSource(connection)) {
157
+ throw new AgentJamError(`The ${connection.provider} connection of the "${name}" skill must come from oauthConnection(), secretConnection() or another CredentialSource`);
158
+ }
159
+ return [connection.provider, connection];
160
+ }));
161
+ const missingFrom = (card, part) => new AgentJamError(`"${card.name}" has no ${part} on the relay, so this process can't handle it. Add it with update() or on the dashboard, or leave it out of the skills you pass to connect()`);
162
+ const staleSchema = (card, skill, field) => new AgentJamError(`The ${field} schema of the "${skill}" skill differs from the one "${card.name}" has on the relay, which validates its tasks' ${field}. Push it with update() or on the dashboard, or leave ${field} out of the skills you pass to connect()`);
163
+ const assertStored = (card, handlers) => {
164
+ for (const handler of handlers) {
165
+ const { name, triggers = {}, connections = [], input, output } = handler;
166
+ const stored = card.skills.find((skill) => skill.name === name);
167
+ if (!stored)
168
+ throw missingFrom(card, `skill named "${name}"`);
169
+ if (input && !isStoredSchema(name, "input", input, stored.inputSchema)) {
170
+ throw staleSchema(card, name, "input");
171
+ }
172
+ if (output &&
173
+ !isStoredSchema(name, "output", output, stored.outputSchema)) {
174
+ throw staleSchema(card, name, "output");
175
+ }
176
+ const trigger = Object.keys(triggers).find((handled) => !stored.triggers?.some((known) => known.name === handled));
177
+ if (trigger) {
178
+ throw missingFrom(card, `"${trigger}" trigger on its "${name}" skill`);
179
+ }
180
+ const connection = connections.find(({ provider }) => !stored.connections?.some((known) => known.provider === provider));
181
+ if (connection) {
182
+ throw missingFrom(card, `${connection.provider} connection on its "${name}" skill`);
183
+ }
184
+ }
185
+ };
186
+ const assertDistinct = (tools, toolNames) => {
187
+ const collision = tools.find((tool) => toolNames.includes(tool.name));
188
+ if (!collision)
189
+ return;
190
+ throw new AgentJamError(`Your agent already has a tool named "${collision.name}", which is also a network tool. Rename it, or leave it out of networkTools in connect().`);
191
+ };
192
+ /** @internal The network an identity lives on. */
193
+ export const networkOf = ({ apiKey, network, payments, }) => network ?? new AgentJamRelay({ apiKey, payments });
194
+ /** An agent connected to the network. Create one with `connect()`. */
195
+ export class Agent {
196
+ /** SDK-neutral network tools, which adapters convert and merge into your agent's own tools. */
197
+ tools;
198
+ // Invariant: `link` is set before open() resolves or any envelope is dispatched.
199
+ link;
200
+ connected = Promise.withResolvers();
201
+ handlers;
202
+ screen;
203
+ timeoutMs;
204
+ forward;
205
+ onError;
206
+ onRun;
207
+ onFollowUp;
208
+ onActionRequired;
209
+ connection;
210
+ requestedName;
211
+ sources;
212
+ vaulted;
213
+ inputs;
214
+ delegates;
215
+ unwatch;
216
+ readiness = new Readiness();
217
+ accessWaits = new AccessWaits();
218
+ requests = new PendingRequests();
219
+ replies = new IdempotencyCache(dedupeWindow);
220
+ verdicts = new IdempotencyCache(dedupeWindow);
221
+ incoming = new Map();
222
+ drains = new Set();
223
+ outgoing = new Map();
224
+ schedules = new Map();
225
+ scheduling = new Set();
226
+ performed = new IdempotencyCache(dedupeWindow);
227
+ triggers;
228
+ watches = new TaskWatches((outcomes) => this.resolveWatch(outcomes));
229
+ constructor({ name, apiKey, network, payments, skills = [], networkTools = true, timeoutMs = defaultTimeout, instanceId, forward = {}, onError = console.error, onRun = logRun, onFollowUp = logFollowUp, onActionRequired = warnActions, toolNames = [], screen, ...handlers }, shown = {}) {
230
+ this.requestedName = name;
231
+ const bindSecret = (connection) => constructSecretSource(connection, () => this.credentialChannel(connection.provider));
232
+ this.sources = new Map(skills.map((skill) => [skill.name, sourcesOf(skill, bindSecret)]));
233
+ this.vaulted = new Set(this.allSources().filter((source) => bindGrantVault(source, name, {
234
+ channel: () => this.oauthChannel(source.provider),
235
+ announce: async ({ principal, reason, holders }) => this.announce({
236
+ type: "revoked",
237
+ provider: source.provider,
238
+ principal,
239
+ requesters: requestersOf(holders),
240
+ reason,
241
+ }),
242
+ })));
243
+ this.inputs = new Map(skills.flatMap((skill) => skill.input ? [[skill.name, skill.input]] : []));
244
+ this.delegates = new Map(skills.flatMap((skill) => skill.delegates ? [[skill.name, skill.delegates]] : []));
245
+ this.forward = { ...allForwarded, ...forward };
246
+ const tools = createNetworkTools(this, {
247
+ watching: handlers.onWatchResolved !== undefined,
248
+ forwarding: this.forward.files,
249
+ });
250
+ this.tools =
251
+ networkTools === true ? tools : pickTools(tools, networkTools || []);
252
+ assertDistinct(this.tools, toolNames);
253
+ this.handlers = handlers;
254
+ this.screen = screen;
255
+ this.timeoutMs = timeoutMs;
256
+ this.onError = onError;
257
+ this.onRun = onRun;
258
+ this.onFollowUp = onFollowUp;
259
+ this.onActionRequired = onActionRequired;
260
+ this.unwatch = this.allSources().map((source) => source.watch((event) => {
261
+ // WARNING: every instance hears the network's notice of a revoked grant, so only the revoking one tells requesters.
262
+ if (event.type === "revoked" && this.vaulted.has(source))
263
+ return;
264
+ this.announce(event).catch(this.onError);
265
+ }));
266
+ this.triggers = new TriggerRunner(skills, {
267
+ post: (to, body) => this.postTo(to)(body),
268
+ accessOf: ({ skill, from, id }) => this.accessOf(skill, { requester: from, id }),
269
+ onError,
270
+ });
271
+ this.connection = networkOf({ apiKey, network, payments })
272
+ .connect(name, (envelope) => this.receive(envelope), {
273
+ onSessionReplaced: () => {
274
+ this.rejoin();
275
+ void this.restartTriggers(this.connection);
276
+ },
277
+ onError: (error) => this.orphan(error),
278
+ }, { instanceId })
279
+ .then(async (connection) => {
280
+ try {
281
+ assertStored(connection.card, skills);
282
+ if (this.vaulted.size > 0)
283
+ assertGrantVault(connection, name);
284
+ }
285
+ catch (error) {
286
+ await connection.close();
287
+ throw error;
288
+ }
289
+ this.link = connection;
290
+ const { claimUrl, payoutsUrl } = connection;
291
+ if (claimUrl && claimUrl !== shown.claimUrl)
292
+ warnGuest(name, claimUrl);
293
+ if (payoutsUrl && payoutsUrl !== shown.payoutsUrl) {
294
+ warnPayouts(name, payoutsUrl);
295
+ }
296
+ // WARNING: triggers must start before envelopes dispatch, so a schedule.end can stop what they start.
297
+ await this.restartTriggers(Promise.resolve(connection));
298
+ this.connected.resolve();
299
+ return connection;
300
+ });
301
+ }
302
+ /** @internal Use `connect()` instead. `shown` holds the links the caller already printed. */
303
+ static async open(options, shown) {
304
+ const agent = new Agent(options, shown);
305
+ try {
306
+ await agent.connection;
307
+ }
308
+ catch (error) {
309
+ agent.stopWatching();
310
+ throw error;
311
+ }
312
+ return agent;
313
+ }
314
+ /** The agent's address on the network, `username/agent-name`, as the relay connected it. */
315
+ get name() {
316
+ return this.link?.name ?? this.requestedName;
317
+ }
318
+ /** The profile other agents see when discovering this one, as the relay stores it. */
319
+ get card() {
320
+ if (!this.link)
321
+ throw new AgentJamError(`${this.name} isn't connected yet`);
322
+ return this.link.card;
323
+ }
324
+ /**
325
+ * The single-use link where this agent's human claims it while it's an unclaimed guest, after which
326
+ * it can run paid tasks. The relay sends a current one on every connect, and none once it's claimed.
327
+ */
328
+ get claimUrl() {
329
+ return this.link?.claimUrl;
330
+ }
331
+ /**
332
+ * The link where this agent's human sets up payouts while its paid skills wait for them. Until
333
+ * then it takes only free tasks, and the relay sends none once payouts are ready.
334
+ */
335
+ get payoutsUrl() {
336
+ return this.link?.payoutsUrl;
337
+ }
338
+ /**
339
+ * Discovers other connected agents, optionally filtered by skill or free text.
340
+ *
341
+ * @param query Filters to match agents against. Defaults to matching every agent.
342
+ * @returns The cards of matching agents, excluding this one.
343
+ */
344
+ async find(query = {}) {
345
+ const connection = await this.connection;
346
+ const cards = await connection.find(query);
347
+ return cards.filter((card) => card.name !== this.name);
348
+ }
349
+ /**
350
+ * Sends a message to another agent and resolves with its reply. Inside `onTask`, a message to the
351
+ * task's requester is about that task, so it reaches the session that proposed it and waits for the
352
+ * reply until the task ends, since a human may need to answer.
353
+ *
354
+ * @param to The recipient's address, `username/agent-name`.
355
+ * @param text The message to send.
356
+ * @param options The conversation to continue, the task the message is about and the files to attach, plus per-call request overrides.
357
+ * @returns The recipient's reply, with its files downloaded.
358
+ * @throws {AgentJamError} If the message attaches files or steers without being about a task, or an attachment couldn't upload.
359
+ * @throws {AgentNotFoundError} If no agent at `to` is connected.
360
+ * @throws {TimeoutError} If no reply arrives within the timeout, which a question to the requester of a task this agent runs only has when `options` sets one.
361
+ */
362
+ async send(to, text, { conversationId = crypto.randomUUID(), idempotencyKey = crypto.randomUUID(), taskId = this.findCurrentTask(to)?.id, attachments, steer, ...options } = {}) {
363
+ if (taskId === undefined && attachments?.length) {
364
+ throw new AgentJamError(untaskedAttachments);
365
+ }
366
+ if (taskId === undefined && steer)
367
+ throw new AgentJamError(untaskedSteer);
368
+ const refs = await this.uploadAttachments(attachments, options.signal);
369
+ const draft = {
370
+ type: "message",
371
+ id: idempotencyKey,
372
+ to,
373
+ conversationId,
374
+ ...(taskId === undefined ? {} : { taskId }),
375
+ text,
376
+ ...(refs === undefined ? {} : { attachments: refs }),
377
+ ...(steer ? { steer: true } : {}),
378
+ };
379
+ const asked = this.findIncomingTask(to, taskId);
380
+ const requestOptions = asked
381
+ ? constructQuestionOptions(asked, options)
382
+ : options;
383
+ const { files, ...reply } = await this.request(draft, requestOptions, (response) => {
384
+ if (response.type !== "reply")
385
+ throw unexpected(response);
386
+ return {
387
+ id: response.id,
388
+ from: to,
389
+ to: this.name,
390
+ conversationId,
391
+ text: response.text,
392
+ files: response.attachments,
393
+ };
394
+ });
395
+ return { ...reply, attachments: await receiveAttachments(files) };
396
+ }
397
+ /**
398
+ * Proposes a task to another agent and resolves once it accepts. Aborting `signal` withdraws
399
+ * the proposal, or cancels the task if it was already accepted. With `watch`, the task's outcome
400
+ * also reaches `onWatchResolved`, even if the agent declines it.
401
+ *
402
+ * @param to The address of the agent to delegate to, `username/agent-name`.
403
+ * @param text A description of the task.
404
+ * @param options The skill the task calls for and its input, the most it may cost, how to watch it, the earlier task it follows up on and the files to attach, plus per-call request overrides.
405
+ * @returns A handle for following the task's events and awaiting its result.
406
+ * @throws {AgentJamError} If `watch` is set but the agent connected without `onWatchResolved`, an attachment couldn't upload, or `follows` names a task that isn't an ended one this agent delegated to `to`.
407
+ * @throws {TaskRejectedError} If the agent declines the task.
408
+ * @throws {PaymentRequiredError} If the skill is priced and the task couldn't be paid for.
409
+ * @throws {SkillRequiredError} If the agent charges for its skills and `skill` doesn't name one.
410
+ * @throws {InvalidInputError} If `input` doesn't match the skill's input schema, or is missing for a skill with one.
411
+ * @throws {AgentNotFoundError} If no agent at `to` is connected.
412
+ * @throws {TimeoutError} If no response arrives within the timeout.
413
+ */
414
+ async propose(to, text, { skill, input, maxPriceCents, watch, attachments, follows, idempotencyKey = crypto.randomUUID(), ...options } = {}) {
415
+ const watched = watch !== undefined && watch !== false;
416
+ if (watched && !this.handlers.onWatchResolved) {
417
+ throw new AgentJamError(noWatchHandler);
418
+ }
419
+ const refs = await this.uploadAttachments(attachments, options.signal);
420
+ const parent = this.findParent();
421
+ const draft = {
422
+ type: "task.propose",
423
+ id: idempotencyKey,
424
+ to,
425
+ text,
426
+ ...(skill === undefined ? {} : { skill }),
427
+ ...(input === undefined ? {} : { input }),
428
+ ...(maxPriceCents === undefined ? {} : { maxPriceCents }),
429
+ ...(watch === undefined ? {} : { watch }),
430
+ ...(refs === undefined ? {} : { attachments: refs }),
431
+ ...(parent === undefined ? {} : { parent }),
432
+ ...(follows === undefined ? {} : { follows }),
433
+ };
434
+ const proposal = this.request(draft, options, (response) => {
435
+ if (response.type === "task.reject") {
436
+ throw new TaskRejectedError(to, response.reason);
437
+ }
438
+ if (response.type !== "task.accept" && response.type !== "task.require") {
439
+ throw unexpected(response);
440
+ }
441
+ if (!parent)
442
+ this.require(to, response);
443
+ return this.track(to, response, { signal: options.signal, parent });
444
+ });
445
+ if (watched)
446
+ this.watches.watch(to, idempotencyKey, proposal, watch);
447
+ return proposal;
448
+ }
449
+ /**
450
+ * Proposes a recurring task to another agent and resolves once it accepts. The relay then starts
451
+ * a run on each match of its `cron`, or each time the executor's `trigger` fires, and keeps runs
452
+ * going while this agent is offline.
453
+ *
454
+ * @param to The address of the agent to delegate to, `username/agent-name`.
455
+ * @param text A description of the task each run performs.
456
+ * @param options Its cron or trigger, its skill and input, the most each run may cost, its budget, when it expires and the files every run receives, plus per-call request overrides.
457
+ * @returns A handle for following the schedule's runs and ending it.
458
+ * @throws {AgentJamError} If an attachment couldn't upload.
459
+ * @throws {TaskRejectedError} If the agent declines the schedule.
460
+ * @throws {PaymentRequiredError} If the skill is priced and the schedule couldn't be paid for.
461
+ * @throws {SkillRequiredError} If the agent charges for its skills and `skill` doesn't name one.
462
+ * @throws {InvalidInputError} If `input` doesn't match the skill's input schema, or is missing for a skill with one.
463
+ * @throws {AgentNotFoundError} If no agent at `to` is connected.
464
+ * @throws {TimeoutError} If no response arrives within the timeout.
465
+ */
466
+ async schedule(to, text, { cron, trigger, budget, skill, input, maxPriceCents, expiresAt, attachments, then, idempotencyKey = crypto.randomUUID(), ...options }) {
467
+ const refs = await this.uploadAttachments(attachments, options.signal);
468
+ const parent = this.findParent();
469
+ const draft = {
470
+ type: "task.propose",
471
+ id: idempotencyKey,
472
+ to,
473
+ text,
474
+ ...(cron === undefined ? {} : { cron }),
475
+ ...(trigger === undefined ? {} : { trigger }),
476
+ ...(budget === undefined ? {} : { budget }),
477
+ ...(skill === undefined ? {} : { skill }),
478
+ ...(input === undefined ? {} : { input }),
479
+ ...(maxPriceCents === undefined ? {} : { maxPriceCents }),
480
+ ...(expiresAt === undefined
481
+ ? {}
482
+ : { expiresAt: expiresAt.toISOString() }),
483
+ ...(refs === undefined ? {} : { attachments: refs }),
484
+ ...(parent === undefined ? {} : { parent }),
485
+ ...(then === undefined ? {} : { then }),
486
+ };
487
+ const id = key(to, idempotencyKey);
488
+ this.scheduling.add(id);
489
+ return this.request(draft, options, (response) => {
490
+ if (response.type === "task.reject") {
491
+ this.scheduling.delete(id);
492
+ throw new TaskRejectedError(to, response.reason);
493
+ }
494
+ if (response.type !== "task.accept" && response.type !== "task.require") {
495
+ throw unexpected(response);
496
+ }
497
+ this.scheduling.delete(id);
498
+ if (!parent)
499
+ this.require(to, response);
500
+ return this.follow(to, idempotencyKey, actionsOf(response), parent);
501
+ });
502
+ }
503
+ /**
504
+ * Rates the agent that performed a task this agent delegated. A task can be rated once, after it
505
+ * completed with at least one artifact.
506
+ *
507
+ * @param taskId The `id` of the delegated task.
508
+ * @param rating A whole number from 1 (poor) to 5 (excellent).
509
+ * @param text An optional written review of up to 500 characters.
510
+ * @returns The saved review.
511
+ * @throws {AgentJamError} If the task can't be rated, this agent already rated it, or the relay has no reviews.
512
+ */
513
+ async rate(taskId, rating, text) {
514
+ const connection = await this.connection;
515
+ if (!connection.rate)
516
+ throw new AgentJamError(noReviews);
517
+ return connection.rate({
518
+ taskId,
519
+ rating,
520
+ ...(text === undefined ? {} : { text }),
521
+ });
522
+ }
523
+ /**
524
+ * Asks for a refund of a task this agent delegated, which the AgentJam team reviews. A task can be
525
+ * disputed once, while its charge is held for 7 days, and an approved dispute refunds your credits.
526
+ *
527
+ * @param taskId The `id` of the delegated task.
528
+ * @param reason Why you want a refund, in 20 to 2000 characters.
529
+ * @returns The open dispute.
530
+ * @throws {AgentJamError} If the task is free, its hold ended, it's already disputed, or the relay has no disputes.
531
+ */
532
+ async dispute(taskId, reason) {
533
+ const connection = await this.connection;
534
+ if (!connection.dispute)
535
+ throw new AgentJamError(noDisputes);
536
+ return connection.dispute(taskId, reason);
537
+ }
538
+ /**
539
+ * Lists the reviews other agents left for an agent, newest first.
540
+ *
541
+ * @param name The name of the reviewed agent.
542
+ * @param query The page size, and the `next` cursor of an earlier page to continue from.
543
+ * @returns A page of reviews, with `next` set when older ones remain.
544
+ * @throws {AgentJamError} If no agent with that name exists, or the relay has no reviews.
545
+ */
546
+ async reviews(name, query = {}) {
547
+ const connection = await this.connection;
548
+ if (!connection.reviews)
549
+ throw new AgentJamError(noReviews);
550
+ return connection.reviews(name, query);
551
+ }
552
+ /**
553
+ * Lists the tasks this agent delegated, newest first, such as the ones still running or one watch
554
+ * group's. Runs of schedules are left out.
555
+ *
556
+ * @param query Filters to match tasks against, plus the page size and the `next` cursor of an earlier page.
557
+ * @returns A page of task summaries, with `next` set when older ones remain.
558
+ * @throws {AgentJamError} If the relay doesn't list tasks, or refuses the query.
559
+ */
560
+ async listTasks(query = {}) {
561
+ const connection = await this.connection;
562
+ if (!connection.tasks)
563
+ throw new AgentJamError(noTaskList);
564
+ return connection.tasks(query);
565
+ }
566
+ /**
567
+ * Recaps a task this agent executed, such as an earlier one in a follow-up's chain, with fresh links to its files.
568
+ *
569
+ * @param task The task's requester and id, such as `{ requester: task.from, taskId: task.previous.followUp.previous }`.
570
+ * @returns What the task asked for and produced.
571
+ * @throws {AgentJamError} If the relay doesn't keep tasks, or this agent didn't execute the task.
572
+ */
573
+ async recallTask(task) {
574
+ const connection = await this.connection;
575
+ if (!connection.recall)
576
+ throw new AgentJamError(noRecall);
577
+ return recapFromWire(await connection.recall(task));
578
+ }
579
+ /**
580
+ * Buys AgentJam credits for this agent's owner, paying over MPP with its `payments`. Cards buy at
581
+ * least $5 at a time, and stablecoin any amount from 1 cent.
582
+ *
583
+ * @param amountCents How many cents of credits to buy.
584
+ * @returns The credit account with the credits added.
585
+ * @throws {AgentJamError} If the agent connected without `payments`.
586
+ * @throws {PaymentRequiredError} If the payment fails, such as `below_card_minimum` for a card top-up under $5, or `unclaimed` for a guest.
587
+ */
588
+ async topUp(amountCents) {
589
+ const connection = await this.connection;
590
+ if (!connection.topUp) {
591
+ throw new AgentJamError("Pass payments to connect() to buy credits");
592
+ }
593
+ return connection.topUp(amountCents);
594
+ }
595
+ /**
596
+ * Reloads this agent's owner's credits whenever they fall below `thresholdCents`, charging a recurring
597
+ * token from the `recurringToken` in its `payments` that allows up to `limitCents` each period. The owner can switch reloads back to their saved card in the dashboard.
598
+ *
599
+ * @param settings When and how much to reload, and the token's limit and period.
600
+ * @returns The credit account, reloading from the new token.
601
+ * @throws {AgentJamError} If the agent connected without `payments`, or its `payments` have no `recurringToken`.
602
+ * @throws {PaymentRequiredError} If the gateway refuses the token or the settings, or `unclaimed` for a guest.
603
+ */
604
+ async setAutoReload(settings) {
605
+ const connection = await this.connection;
606
+ if (!connection.setAutoReload) {
607
+ throw new AgentJamError("Pass payments to connect() to set up auto-reload");
608
+ }
609
+ return connection.setAutoReload(settings);
610
+ }
611
+ /**
612
+ * Reattaches the tasks this agent delegated from earlier sessions, such as before a restart, that are
613
+ * still running or ended without it receiving their outcome. Each handle replays what its executor sent.
614
+ *
615
+ * @returns A handle for each reattached task, leaving out the ones this session already follows. A
616
+ * handle the relay won't reattach rejects with its refusal.
617
+ * @throws {AgentJamError} If the relay doesn't list tasks.
618
+ */
619
+ async collect() {
620
+ const summaries = [
621
+ ...(await this.listEvery({ statuses: openStatuses })),
622
+ ...(await this.listEvery({ unread: true })),
623
+ ];
624
+ const tracked = summaries
625
+ .filter(({ agent, id }) => !this.outgoing.has(key(agent, id)))
626
+ .map(({ agent, id }) => this.track(agent, { replyTo: id }));
627
+ const tasks = [...new Set(tracked)];
628
+ await Promise.all(tasks.map((task) => this.reattach(task)));
629
+ return tasks;
630
+ }
631
+ /**
632
+ * Starts a run of each active schedule this agent executes whose trigger subscribed it to one of the event's
633
+ * keys, once per schedule and event `id`. Any session can dispatch, such as the one receiving a webhook.
634
+ *
635
+ * @param event The event, with the keys it's filed under and the `data` each run receives.
636
+ * @returns Resolves once the relay has the event, whether or not any schedule subscribed to it.
637
+ * @throws {DispatchFailedError} If the relay stayed unreachable for over an hour, so the event was dropped.
638
+ */
639
+ async dispatch({ eventKeys, id, summary, data, }) {
640
+ await this.post({
641
+ type: "trigger.dispatch",
642
+ id: crypto.randomUUID(),
643
+ eventKeys,
644
+ eventId: id,
645
+ summary,
646
+ ...(data && { data }),
647
+ });
648
+ }
649
+ /**
650
+ * Answers a provider's webhook request through `source`, dispatching each event it carries and ending every
651
+ * grant of each account it reports revoked. Failures go to `onError`, so the provider still gets its answer.
652
+ *
653
+ * @param source Reads and verifies the provider's requests, such as `slackEvents()`.
654
+ * @param request The webhook request, as a web `Request` or its headers and raw body.
655
+ * @returns The answer to send the provider.
656
+ */
657
+ async receiveEvents(source, request) {
658
+ const { response, events } = await source.receive(request);
659
+ await Promise.all(events.map((event) => this.receiveEvent(event).catch(this.onError)));
660
+ return response;
661
+ }
662
+ /**
663
+ * Answers the request a provider redirects the human to once they consent, finishing the authorization with the
664
+ * connection among this agent's skills that started it. Serve it at the `redirectUri` of the agent's OAuth
665
+ * connections, which can share one.
666
+ *
667
+ * @param request The callback request, as a web `Request` or its URL, absolute or relative to the `redirectUri`.
668
+ * @returns A page telling the human their account connected, or why it didn't with a 400 status.
669
+ * @throws {Error} If the token request failed for a reason other than the provider's refusal, such as the network.
670
+ */
671
+ async receiveOAuth(request) {
672
+ return receiveOAuthCallback(this.allSources(), request);
673
+ }
674
+ /**
675
+ * Lists the tasks and schedules holding a grant of `connection`, so work outside a task, such as a mailbox
676
+ * listener started with the agent, can reach each human's account.
677
+ *
678
+ * @param connection An OAuth connection without a store that one of the agent's skills declares.
679
+ * @returns The tasks and schedules holding a grant, with the human each acts for.
680
+ * @throws {AgentJamError} If no skill declares the connection, or it keeps its grants in a store.
681
+ */
682
+ async grants(connection) {
683
+ const source = this.findSource(connection.provider);
684
+ if (!source.listGrants) {
685
+ throw new AgentJamError(`The ${connection.provider} connection can't list its grants`);
686
+ }
687
+ return source.listGrants();
688
+ }
689
+ /**
690
+ * Returns a current access token of `connection` for a task or schedule outside its handler, such as one that
691
+ * `grants()` listed, refreshing it first if it expired.
692
+ *
693
+ * @param connection A connection one of the agent's skills declares.
694
+ * @param grant The task or schedule whose grant to use.
695
+ * @param name The token to return, for providers that issue several. Defaults to the provider's default token.
696
+ * @returns The access token.
697
+ * @throws {ConnectionRevokedError} If the human revoked access, or the grant ended.
698
+ */
699
+ async credentials(connection, grant, name) {
700
+ return this.findSource(connection.provider).token(grant, name);
701
+ }
702
+ /**
703
+ * Returns the account `connection` connects for a task or schedule outside its handler, such as one that
704
+ * `grants()` listed, so a mailbox listener can log in as the human's address.
705
+ *
706
+ * @param connection A connection one of the agent's skills declares.
707
+ * @param grant The task or schedule whose grant to read.
708
+ * @returns The account, or undefined if the connection doesn't know it.
709
+ * @throws {ConnectionRevokedError} If the human revoked access, or the grant ended.
710
+ */
711
+ async account(connection, grant) {
712
+ return this.findSource(connection.provider).account?.(grant);
713
+ }
714
+ /**
715
+ * Stops the relay sending this session new tasks, runs and events, then waits for its incoming tasks to finish. The
716
+ * session keeps its tasks, questions and delegated tasks meanwhile, so call `close()` afterwards to leave, which moves
717
+ * any resumable task still running to another session.
718
+ *
719
+ * @param options How long to wait for incoming tasks.
720
+ * @returns Resolves once every incoming task finished or `deadlineMs` passed.
721
+ */
722
+ async drain({ deadlineMs }) {
723
+ await this.post({ type: "session.drain", id: crypto.randomUUID() });
724
+ if (this.incoming.size === 0)
725
+ return;
726
+ const { promise, resolve } = Promise.withResolvers();
727
+ const timer = setTimeout(resolve, deadlineMs);
728
+ this.drains.add(resolve);
729
+ await promise;
730
+ clearTimeout(timer);
731
+ this.drains.delete(resolve);
732
+ }
733
+ /**
734
+ * Disconnects from the relay, failing incoming tasks and stopping triggers. Tasks of resumable skills move to another
735
+ * session of this agent instead. Outgoing tasks keep running and their handles reject, so `collect()` from a later
736
+ * session reattaches them. Runs of this agent's schedules keep going too, and wait for it to reconnect.
737
+ *
738
+ * @returns Resolves once the agent has left the network.
739
+ */
740
+ async close() {
741
+ const reason = `${this.name} disconnected`;
742
+ this.stopWatching();
743
+ this.requests.failAll(new AgentJamError(reason));
744
+ for (const task of this.listDelegated())
745
+ task.fail(unfollowed(reason));
746
+ await Promise.allSettled([
747
+ this.triggers.stopAll("closing"),
748
+ ...Array.from(this.incoming.values(), (task) => task.resumable
749
+ ? task.abandon(new AgentJamError(reason))
750
+ : task.fail(new AgentJamError(reason))),
751
+ ]);
752
+ const connection = await this.connection;
753
+ await connection.close();
754
+ }
755
+ async receive(envelope) {
756
+ await this.connected.promise;
757
+ await this.handleEnvelope(envelope).catch(this.onError);
758
+ }
759
+ async handleEnvelope(envelope) {
760
+ switch (envelope.type) {
761
+ case "message":
762
+ return this.reply(envelope);
763
+ case "reply":
764
+ this.requests.settle(envelope);
765
+ return;
766
+ case "error":
767
+ case "task.reject":
768
+ if (this.requests.settle(envelope))
769
+ return;
770
+ return this.refuse(envelope);
771
+ case "task.accept":
772
+ case "task.require": {
773
+ if (this.requests.settle(envelope))
774
+ return;
775
+ const task = this.outgoing.get(key(envelope.from, envelope.replyTo));
776
+ if (task)
777
+ return task.restart(envelope.id, actionsOf(envelope));
778
+ return this.withdraw(envelope.from, envelope.replyTo);
779
+ }
780
+ case "task.propose":
781
+ if (envelope.resumed)
782
+ return this.resume(envelope);
783
+ return this.consider(envelope).catch(ignoreReassigned);
784
+ case "task.update":
785
+ case "task.artifact":
786
+ case "task.commit":
787
+ case "task.complete":
788
+ case "task.fail":
789
+ return this.progress(envelope);
790
+ case "task.cancel":
791
+ this.incoming
792
+ .get(key(envelope.from, envelope.taskId))
793
+ ?.cancel(envelope.reason, envelope.code);
794
+ return;
795
+ case "task.budget":
796
+ this.incoming
797
+ .get(key(envelope.from, envelope.taskId))
798
+ ?.setHeldCents(envelope.heldCents);
799
+ return;
800
+ case "task.actions":
801
+ return this.inherit(envelope);
802
+ case "disconnect":
803
+ return this.abandon(envelope.from, envelope.abandoned);
804
+ case "schedule.end":
805
+ return this.closeSchedule(envelope);
806
+ case "schedule.start":
807
+ return this.triggers.activate(watchOf(envelope));
808
+ case "schedule.handover":
809
+ await this.triggers.stop(envelope.from, envelope.scheduleId, "handover");
810
+ return;
811
+ case "trigger.failed":
812
+ return this.onError(new TriggerFailedError(envelope.from, envelope.scheduleId, envelope.eventId, envelope.error));
813
+ case "task.recur":
814
+ if (envelope.from !== this.name)
815
+ return this.perform(envelope);
816
+ this.notice(envelope.to, envelope);
817
+ return;
818
+ case "schedule.followup":
819
+ return this.followUp(envelope);
820
+ case "connection.ready": {
821
+ const { from, proposalId, provider, origin } = envelope;
822
+ const id = key(from, proposalId);
823
+ this.outgoing.get(id)?.complete(provider);
824
+ this.schedules.get(id)?.complete(provider, origin);
825
+ return;
826
+ }
827
+ case "connection.required":
828
+ return this.requireAccess(envelope);
829
+ case "connection.stored": {
830
+ const { from, proposalId, principal, provider } = envelope;
831
+ const grant = { requester: from, id: proposalId, principal };
832
+ return this.announce({ type: "ready", provider, grant });
833
+ }
834
+ case "connection.revoked":
835
+ return this.handleRevocation(envelope);
836
+ default: {
837
+ const unknown = envelope;
838
+ throw new AgentJamError(`Received an unknown envelope: ${JSON.stringify(unknown)}`);
839
+ }
840
+ }
841
+ }
842
+ async reply(envelope) {
843
+ const request = key(envelope.from, envelope.id);
844
+ const { response, repeated } = this.replies.remember(request, () => this.answer(envelope));
845
+ try {
846
+ await this.post(await response);
847
+ }
848
+ finally {
849
+ if (!repeated)
850
+ this.replies.release(request);
851
+ }
852
+ }
853
+ async answer(envelope) {
854
+ const response = {
855
+ id: crypto.randomUUID(),
856
+ to: envelope.from,
857
+ replyTo: envelope.id,
858
+ };
859
+ try {
860
+ const output = await this.computeReply(envelope);
861
+ const { text, attachments } = typeof output === "string" ? { text: output } : output;
862
+ if (envelope.taskId === undefined && attachments?.length) {
863
+ throw new AgentJamError(untaskedAttachments);
864
+ }
865
+ const refs = await this.uploadAttachments(attachments, undefined);
866
+ return {
867
+ ...response,
868
+ type: "reply",
869
+ text,
870
+ ...(refs === undefined ? {} : { attachments: refs }),
871
+ };
872
+ }
873
+ catch (error) {
874
+ return { ...response, type: "error", error: describeError(error) };
875
+ }
876
+ }
877
+ async computeReply(envelope) {
878
+ const attachments = await receiveAttachments(envelope.attachments);
879
+ const asked = this.findAsked(envelope);
880
+ if (asked) {
881
+ const reply = await asked.send(`${envelope.from}: ${envelope.text}`, {
882
+ attachments: attachments.map(({ file }) => file),
883
+ });
884
+ return {
885
+ text: reply.text,
886
+ attachments: reply.attachments.map(({ file }) => file),
887
+ };
888
+ }
889
+ const { history, taskId, task, steer } = envelope;
890
+ const message = {
891
+ ...toMessage(envelope),
892
+ history,
893
+ ...(taskId === undefined ? {} : { taskId }),
894
+ ...(task === undefined ? {} : { task: recapFromWire(task) }),
895
+ ...(steer === undefined ? {} : { steer }),
896
+ attachments,
897
+ };
898
+ if (steer && this.findSteered(envelope)?.queueMessage(message)) {
899
+ return steered;
900
+ }
901
+ if (!this.handlers.onMessage) {
902
+ throw new AgentJamError(`${this.name} does not accept messages`);
903
+ }
904
+ return this.handlers.onMessage(message, this);
905
+ }
906
+ /** Finds the running task a requester's message about it may steer. */
907
+ findSteered({ from, taskId }) {
908
+ return taskId === undefined
909
+ ? undefined
910
+ : this.incoming.get(key(from, taskId));
911
+ }
912
+ /** Finds the task to pass a question about a delegated task up to: the one it was delegated as part of. */
913
+ findAsked({ from, taskId }) {
914
+ if (!this.forward.questions || taskId === undefined)
915
+ return undefined;
916
+ return this.findAbove(this.outgoing.get(key(from, taskId)));
917
+ }
918
+ findAbove(task) {
919
+ const parent = task?.parent;
920
+ if (parent?.kind !== "task")
921
+ return undefined;
922
+ return this.incoming.get(key(parent.requester, parent.id));
923
+ }
924
+ async consider(proposal) {
925
+ const request = key(proposal.from, proposal.id);
926
+ const { response, repeated } = this.verdicts.remember(request, () => this.judge(proposal));
927
+ const { verdict, attachments, parsedInput, preparations = [], } = await response;
928
+ const { from, text, skill, input } = proposal;
929
+ const id = key(from, proposal.id);
930
+ if (repeated) {
931
+ await this.post(verdict);
932
+ return this.incoming.get(id)?.settled;
933
+ }
934
+ const grant = { requester: from, id: proposal.id };
935
+ if (!isAccepting(verdict) || isSchedule(proposal)) {
936
+ this.verdicts.release(request);
937
+ return this.post(verdict).catch((error) => {
938
+ this.release(grant, this.sourcesFor(skill).values());
939
+ throw error;
940
+ });
941
+ }
942
+ const task = new TaskExecution({
943
+ id: proposal.id,
944
+ from,
945
+ principal: proposal.principal,
946
+ text,
947
+ skill,
948
+ input,
949
+ parsedInput,
950
+ attachments,
951
+ previous: proposal.previous && recapFromWire(proposal.previous),
952
+ price: proposal.prepare ? undefined : this.priceOf(skill, from),
953
+ card: proposal.prepare ? undefined : this.findSkillCard(skill),
954
+ isSelf: from === this.name,
955
+ heldCents: proposal.heldCents,
956
+ resumable: !proposal.prepare && this.isResumable(skill),
957
+ ...this.accessOf(skill, grant),
958
+ }, {
959
+ post: this.postTo(from),
960
+ send: this.sendAbout(from, proposal.id),
961
+ upload: this.uploadArtifact,
962
+ prepare: this.prepareFor({
963
+ kind: "task",
964
+ requester: from,
965
+ id: proposal.id,
966
+ }),
967
+ listHistory: this.listHistoryOf({
968
+ requester: from,
969
+ taskId: proposal.id,
970
+ }),
971
+ requireAccess: this.requireAccessFor(skill, { ...grant, principal: proposal.principal ?? from }, proposal.id),
972
+ });
973
+ const cleanup = () => {
974
+ this.verdicts.forget(request, response);
975
+ this.readiness.forget(grant);
976
+ this.releaseExecution(id, task, grant);
977
+ };
978
+ this.incoming.set(id, task);
979
+ this.readiness.expect(grant, ownProvidersOf(verdict));
980
+ try {
981
+ await this.post(verdict);
982
+ }
983
+ catch (error) {
984
+ cleanup();
985
+ throw error;
986
+ }
987
+ void this.execute(task, cleanup, async (incoming) => {
988
+ await this.readiness.wait(grant, incoming.signal);
989
+ if (!proposal.prepare)
990
+ return this.handlers.onTask?.(incoming, this);
991
+ // WARNING: the relay cancels a task's children once it ends, so a preparation outlives the ones below it.
992
+ await awaitPreparations(preparations);
993
+ });
994
+ return task.settled;
995
+ }
996
+ async judge(proposal) {
997
+ const response = {
998
+ id: crypto.randomUUID(),
999
+ to: proposal.from,
1000
+ replyTo: proposal.id,
1001
+ };
1002
+ try {
1003
+ const parsedInput = proposal.prepare
1004
+ ? undefined
1005
+ : await this.parseSkillInput(proposal.skill, proposal.input);
1006
+ if (parsedInput && "problem" in parsedInput) {
1007
+ return {
1008
+ verdict: {
1009
+ ...response,
1010
+ type: "task.reject",
1011
+ reason: parsedInput.problem,
1012
+ },
1013
+ attachments: [],
1014
+ };
1015
+ }
1016
+ const attachments = await receiveAttachments(proposal.attachments);
1017
+ const { verdict, preparations } = await this.constructVerdict(proposal, attachments);
1018
+ return {
1019
+ verdict: { ...response, ...verdict },
1020
+ attachments,
1021
+ parsedInput,
1022
+ preparations,
1023
+ };
1024
+ }
1025
+ catch (error) {
1026
+ return {
1027
+ verdict: { ...response, type: "error", error: describeError(error) },
1028
+ attachments: [],
1029
+ };
1030
+ }
1031
+ }
1032
+ async constructVerdict(proposal, attachments) {
1033
+ const { id, from, principal, skill } = proposal;
1034
+ const incoming = toProposal(proposal, attachments);
1035
+ const verdict = proposal.prepare ? accept() : await this.decide(incoming);
1036
+ if (!verdict.accepted) {
1037
+ const rejection = {
1038
+ type: "task.reject",
1039
+ reason: verdict.reason,
1040
+ };
1041
+ return { verdict: rejection, preparations: [] };
1042
+ }
1043
+ if (proposal.prepare) {
1044
+ warnRevoking(this.name, proposal, this.sourcesFor(skill).values());
1045
+ }
1046
+ // WARNING: a proposal without a principal leaves each requester with its own grants.
1047
+ const grant = { requester: from, id, principal: principal ?? from };
1048
+ const [own, prepared] = await Promise.all([
1049
+ this.actionsFor(skill, grant),
1050
+ this.prepareDelegates(proposal, incoming),
1051
+ ]);
1052
+ const copies = prepared.flatMap((preparation) => preparation.actions);
1053
+ const actions = [...own, ...copies];
1054
+ const preparations = prepared.map(({ task }) => task);
1055
+ const accepted = actions.length > 0
1056
+ ? { type: "task.require", actions }
1057
+ : { type: "task.accept" };
1058
+ return { verdict: accepted, preparations };
1059
+ }
1060
+ /** Asks each agent the proposal's skill delegates to for the actions it needs ahead of the proposal's work. */
1061
+ async prepareDelegates(proposal, incoming) {
1062
+ const { from, id } = proposal;
1063
+ const delegates = await this.pickDelegates(proposal, incoming);
1064
+ const kind = isSchedule(proposal) ? "schedule" : "task";
1065
+ return this.prepareEach(delegates, { kind, requester: from, id });
1066
+ }
1067
+ /** Lists the delegates of the proposal's skill, leaving out picked ones while another agent only prepares it. */
1068
+ async pickDelegates(proposal, incoming) {
1069
+ const { skill, prepare, then } = proposal;
1070
+ const delegates = skill === undefined ? [] : this.delegates.get(skill);
1071
+ const followUp = then ? [{ agent: then.to, skill: then.skill }] : [];
1072
+ if (typeof delegates !== "function") {
1073
+ return [...(delegates ?? []), ...followUp];
1074
+ }
1075
+ return prepare ? [] : [...(await delegates(incoming, this)), ...followUp];
1076
+ }
1077
+ prepareFor(parent) {
1078
+ return async (delegates) => {
1079
+ await this.prepareEach(delegates, parent);
1080
+ };
1081
+ }
1082
+ /** Sends each delegate a preparation under `parent`, reporting the ones that can't prepare to `onError`. */
1083
+ async prepareEach(delegates, parent) {
1084
+ const prepared = await Promise.all(delegates.map((delegate) => this.prepare(delegate, parent).catch((error) => {
1085
+ this.onError(error);
1086
+ return [];
1087
+ })));
1088
+ return prepared.flat();
1089
+ }
1090
+ prepare({ agent, skill }, parent) {
1091
+ const id = crypto.randomUUID();
1092
+ const origin = { requester: this.name, taskId: id, executor: agent };
1093
+ const draft = {
1094
+ type: "task.propose",
1095
+ id,
1096
+ to: agent,
1097
+ text: `Connect the accounts the "${skill}" skill needs ahead of the work on ${parent.id}`,
1098
+ skill,
1099
+ prepare: true,
1100
+ parent,
1101
+ };
1102
+ return this.request(draft, {}, (response) => {
1103
+ if (response.type === "task.reject") {
1104
+ throw new TaskRejectedError(agent, response.reason);
1105
+ }
1106
+ if (response.type !== "task.accept" && response.type !== "task.require") {
1107
+ throw unexpected(response);
1108
+ }
1109
+ const actions = actionsOf(response).map((action) => ({
1110
+ ...action,
1111
+ origin: action.origin ?? origin,
1112
+ }));
1113
+ return { task: this.track(agent, response, { parent }), actions };
1114
+ });
1115
+ }
1116
+ /**
1117
+ * Runs the checks proposals get without an `onProposal`: rejecting every proposal without an `onTask`, and ones
1118
+ * that name a skill the agent doesn't advertise or a trigger its skill doesn't declare. Call it from `onProposal` to keep them.
1119
+ *
1120
+ * @param proposal The proposal to check.
1121
+ * @returns Whether the proposal passes the checks.
1122
+ */
1123
+ checkProposal(proposal) {
1124
+ const { skill, trigger } = proposal;
1125
+ if (!this.handlers.onTask) {
1126
+ return reject(`${this.name} does not accept tasks`);
1127
+ }
1128
+ if (skill !== undefined &&
1129
+ !this.card.skills.some(({ name }) => name === skill)) {
1130
+ return reject(`${this.name} has no skill named "${skill}"`);
1131
+ }
1132
+ if (trigger && !this.triggers.offers(skill, trigger.name)) {
1133
+ return reject(`${this.name} has no trigger named "${trigger.name}" for this skill`);
1134
+ }
1135
+ return accept();
1136
+ }
1137
+ /** @internal The agents and skills a skill hands work off to, leaving out ones a function picks per proposal. */
1138
+ listDelegates(skill) {
1139
+ const delegates = skill === undefined ? [] : this.delegates.get(skill);
1140
+ return Array.isArray(delegates) ? delegates : [];
1141
+ }
1142
+ /** @internal Reports an error that can't reach another agent to `onError`. */
1143
+ reportError(error) {
1144
+ this.onError(error);
1145
+ }
1146
+ async decide(proposal) {
1147
+ const verdict = this.handlers.onProposal
1148
+ ? await this.handlers.onProposal(proposal, this)
1149
+ : this.checkProposal(proposal);
1150
+ if (!verdict.accepted || !this.screen || proposal.from === this.name) {
1151
+ return verdict;
1152
+ }
1153
+ return screenProposal(proposal, this, this.screen);
1154
+ }
1155
+ async parseSkillInput(skill, input) {
1156
+ if (skill === undefined)
1157
+ return undefined;
1158
+ const schema = this.inputs.get(skill);
1159
+ return schema && parseValue(skill, "input", schema, input);
1160
+ }
1161
+ priceOf(skill, requester) {
1162
+ if (requester === this.name)
1163
+ return undefined;
1164
+ return this.findSkillCard(skill)?.price;
1165
+ }
1166
+ findSkillCard(skill) {
1167
+ return this.card.skills.find(({ name }) => name === skill);
1168
+ }
1169
+ async restartTriggers(connection) {
1170
+ if (!this.triggers.declared)
1171
+ return;
1172
+ await this.triggers.sync(async () => (await connection).triggers?.());
1173
+ }
1174
+ perform(recur) {
1175
+ const { from, principal, scheduleId, run, taskId, text, skill, input } = recur;
1176
+ const id = key(from, taskId);
1177
+ const { response } = this.performed.remember(id, async () => {
1178
+ const { attachments, parsedInput, failure } = await this.receiveTask(recur);
1179
+ const task = new TaskExecution({
1180
+ id: taskId,
1181
+ from,
1182
+ principal,
1183
+ text,
1184
+ skill,
1185
+ input,
1186
+ parsedInput,
1187
+ attachments,
1188
+ scheduleId,
1189
+ run,
1190
+ event: eventOf(recur),
1191
+ price: this.priceOf(skill, from),
1192
+ card: this.findSkillCard(skill),
1193
+ isSelf: from === this.name,
1194
+ heldCents: recur.heldCents,
1195
+ ...this.accessOf(skill, { requester: from, id: scheduleId }),
1196
+ }, {
1197
+ post: this.postTo(from),
1198
+ send: this.sendAbout(from, taskId),
1199
+ upload: this.uploadArtifact,
1200
+ prepare: this.prepareFor({
1201
+ kind: "task",
1202
+ requester: from,
1203
+ id: taskId,
1204
+ }),
1205
+ listHistory: this.listHistoryOf({ requester: from, taskId }),
1206
+ requireAccess: this.requireAccessFor(skill, { requester: from, id: scheduleId, principal: principal ?? from }, taskId),
1207
+ });
1208
+ const cleanup = () => {
1209
+ this.forgetIncoming(id);
1210
+ this.performed.release(id);
1211
+ };
1212
+ this.incoming.set(id, task);
1213
+ await this.execute(task, cleanup, async (incoming) => {
1214
+ if (failure)
1215
+ throw failure.error;
1216
+ return this.handlers.onTask?.(incoming, this);
1217
+ });
1218
+ });
1219
+ return response;
1220
+ }
1221
+ /**
1222
+ * Runs a task of a resumable skill that the relay moved here from a departed session of this agent, following the
1223
+ * tasks it delegated there so their events aren't refused as unknown. A repeat of an attempt already running is ignored.
1224
+ */
1225
+ async resume(proposal) {
1226
+ const { from, id: taskId, principal, text, skill, input } = proposal;
1227
+ const { attempt = 2, children = [] } = proposal;
1228
+ const id = key(from, taskId);
1229
+ const grant = { requester: from, id: taskId };
1230
+ const { attachments, parsedInput, failure } = await this.receiveTask(proposal);
1231
+ const running = this.incoming.get(id);
1232
+ if (running && running.attempt >= attempt)
1233
+ return;
1234
+ running?.abandon(new ReassignedError(`Task "${taskId}" resumed as attempt ${attempt}`));
1235
+ const parent = { kind: "task", requester: from, id: taskId };
1236
+ for (const child of children) {
1237
+ void this.reattach(this.track(child.to, { replyTo: child.id }, { parent }));
1238
+ }
1239
+ const task = new TaskExecution({
1240
+ id: taskId,
1241
+ from,
1242
+ principal,
1243
+ text,
1244
+ skill,
1245
+ input,
1246
+ parsedInput,
1247
+ attachments,
1248
+ attempt,
1249
+ price: this.priceOf(skill, from),
1250
+ card: this.findSkillCard(skill),
1251
+ isSelf: from === this.name,
1252
+ heldCents: proposal.heldCents,
1253
+ resumable: true,
1254
+ ...this.accessOf(skill, grant),
1255
+ }, {
1256
+ post: this.postTo(from),
1257
+ send: this.sendAbout(from, taskId),
1258
+ upload: this.uploadArtifact,
1259
+ prepare: this.prepareFor(parent),
1260
+ listHistory: this.listHistoryOf({ requester: from, taskId }),
1261
+ requireAccess: this.requireAccessFor(skill, { ...grant, principal: principal ?? from }, taskId),
1262
+ });
1263
+ const cleanup = () => this.releaseExecution(id, task, grant);
1264
+ this.incoming.set(id, task);
1265
+ await this.execute(task, cleanup, async (incoming) => {
1266
+ if (failure)
1267
+ throw failure.error;
1268
+ return this.handlers.onTask?.(incoming, this);
1269
+ });
1270
+ }
1271
+ /** Downloads a task's attachments and parses its input, keeping the first failure for the task's run to throw. */
1272
+ async receiveTask({ skill, input, attachments, }) {
1273
+ const received = await receiveAttachments(attachments).then((files) => ({ attachments: files, failure: undefined }), (error) => ({ attachments: [], failure: { error } }));
1274
+ const parsed = await this.parseSkillInput(skill, input).catch((error) => ({ problem: describeError(error) }));
1275
+ if (parsed && "problem" in parsed) {
1276
+ const error = new AgentJamError(parsed.problem);
1277
+ return {
1278
+ ...received,
1279
+ parsedInput: undefined,
1280
+ failure: received.failure ?? { error },
1281
+ };
1282
+ }
1283
+ return { ...received, parsedInput: parsed };
1284
+ }
1285
+ /** Forgets a finished task and releases its connections, unless a resumed attempt replaced it meanwhile. */
1286
+ releaseExecution(id, task, grant) {
1287
+ if (this.incoming.get(id) !== task)
1288
+ return;
1289
+ this.forgetIncoming(id);
1290
+ this.release(grant, this.sourcesFor(task.skill).values());
1291
+ }
1292
+ forgetIncoming(id) {
1293
+ this.incoming.delete(id);
1294
+ if (this.incoming.size > 0)
1295
+ return;
1296
+ for (const resolve of this.drains)
1297
+ resolve();
1298
+ }
1299
+ isResumable(skill) {
1300
+ return this.findSkillCard(skill)?.resumable === true;
1301
+ }
1302
+ async execute(task, cleanup, work) {
1303
+ try {
1304
+ await task.perform(work);
1305
+ }
1306
+ catch (error) {
1307
+ if (!(error instanceof ReassignedError))
1308
+ this.onError(error);
1309
+ }
1310
+ finally {
1311
+ cleanup();
1312
+ }
1313
+ }
1314
+ allSources() {
1315
+ const sources = [...this.sources.values()].flatMap((skill) => [
1316
+ ...skill.values(),
1317
+ ]);
1318
+ return [...new Set(sources)];
1319
+ }
1320
+ sourcesFor(skill) {
1321
+ return ((skill === undefined ? undefined : this.sources.get(skill)) ??
1322
+ new Map());
1323
+ }
1324
+ async actionsFor(skill, grant) {
1325
+ const links = await Promise.all(Array.from(this.sourcesFor(skill).values(), async (source) => ({
1326
+ kind: actionKindOf(source),
1327
+ provider: source.provider,
1328
+ url: await source.authorize(grant),
1329
+ })));
1330
+ return links.flatMap(({ kind, provider, url }) => url === undefined ? [] : [{ kind, provider, url }]);
1331
+ }
1332
+ findSource(provider) {
1333
+ const source = this.allSources().find((declared) => declared.provider === provider);
1334
+ if (!source) {
1335
+ throw new AgentJamError(`${this.name} declares no ${provider} connection on any skill`);
1336
+ }
1337
+ return source;
1338
+ }
1339
+ sourceOf(skill, provider) {
1340
+ const source = this.sourcesFor(skill).get(provider);
1341
+ if (!source) {
1342
+ throw new AgentJamError(`The "${skill}" skill declares no ${provider} connection`);
1343
+ }
1344
+ return source;
1345
+ }
1346
+ accessOf(skill, holder) {
1347
+ const secretOf = ({ provider }) => {
1348
+ const source = this.sourceOf(skill, provider);
1349
+ if (!isSecretSource(source)) {
1350
+ throw new AgentJamError(`The ${provider} connection of the "${skill}" skill isn't a secret connection, so get its token with credentials()`);
1351
+ }
1352
+ return source;
1353
+ };
1354
+ return {
1355
+ credentials: async ({ provider }, name) => this.sourceOf(skill, provider).token(holder, name),
1356
+ account: async ({ provider }) => this.sourceOf(skill, provider).account?.(holder),
1357
+ connectionFetch: (connection) => {
1358
+ const source = secretOf(connection);
1359
+ return (input, init) => source.fetch(holder, input, init);
1360
+ },
1361
+ connectionConfig: async (connection) => secretOf(connection).config(holder),
1362
+ };
1363
+ }
1364
+ /**
1365
+ * Builds how the running task `proposalId` asks its human for access it lacks: it requires the action, then
1366
+ * re-runs `verify` with backoff, sooner once the connection is ready, and requires it again if a ready
1367
+ * connection still doesn't verify.
1368
+ */
1369
+ requireAccessFor(skill, grant, proposalId) {
1370
+ return async ({ provider }, { reason, verify, url }, signal) => {
1371
+ const source = this.sourceOf(skill, provider);
1372
+ const post = this.postTo(grant.requester);
1373
+ const require = async () => post({
1374
+ type: "connection.required",
1375
+ proposalId,
1376
+ provider,
1377
+ url: url ?? (await this.constructAccessUrl(source, grant)),
1378
+ reason,
1379
+ });
1380
+ const wait = { provider, holder: grant, proposalId };
1381
+ await require();
1382
+ await this.accessWaits.poll(wait, signal, async (woken) => {
1383
+ const announced = woken && grant.id === proposalId;
1384
+ if (await verify()) {
1385
+ if (!announced) {
1386
+ await post({ type: "connection.ready", proposalId, provider });
1387
+ }
1388
+ return true;
1389
+ }
1390
+ if (woken)
1391
+ await require();
1392
+ return false;
1393
+ });
1394
+ };
1395
+ }
1396
+ async constructAccessUrl(source, grant) {
1397
+ if (!source.constructAccessUrl) {
1398
+ throw new AgentJamError(`The ${source.provider} connection can't link to its access settings, so requireAccess() needs a url`);
1399
+ }
1400
+ return source.constructAccessUrl(grant);
1401
+ }
1402
+ oauthChannel(provider) {
1403
+ const channel = this.link?.credentials?.oauth;
1404
+ if (!channel) {
1405
+ throw new AgentJamError(`The relay "${this.name}" connects to holds no OAuth grants, so its ${provider} connection needs a store`);
1406
+ }
1407
+ return channel;
1408
+ }
1409
+ /**
1410
+ * Tells the connection's watchers about a grant the network revoked, which only its notice lists the holders of. The
1411
+ * relay ends the work that held it, so long-lived listeners, such as a mailbox, are all that's left to close.
1412
+ */
1413
+ handleRevocation({ provider, principal, reason = lostGrant, holders, }) {
1414
+ if (!holders)
1415
+ return;
1416
+ for (const source of this.allSources()) {
1417
+ if (source.provider === provider) {
1418
+ receiveRevocation(source, { principal, reason, holders });
1419
+ }
1420
+ }
1421
+ }
1422
+ credentialChannel(provider) {
1423
+ const channel = this.link?.credentials;
1424
+ if (!channel) {
1425
+ throw new AgentJamError(`The relay "${this.name}" connects to holds no credentials, so its ${provider} secret connection can't reach one`);
1426
+ }
1427
+ return channel;
1428
+ }
1429
+ async announce(event) {
1430
+ switch (event.type) {
1431
+ case "ready": {
1432
+ const { provider, grant } = event;
1433
+ this.readiness.settle(provider, grant);
1434
+ await this.postTo(grant.requester)({
1435
+ type: "connection.ready",
1436
+ proposalId: grant.id,
1437
+ provider,
1438
+ });
1439
+ this.accessWaits.wake(provider, grant);
1440
+ return;
1441
+ }
1442
+ case "required": {
1443
+ const { provider, grant, url, reason } = event;
1444
+ const waiting = this.accessWaits.listWaiting(provider, grant);
1445
+ const proposalIds = waiting.length > 0 ? waiting : [grant.id];
1446
+ await Promise.all(proposalIds.map(async (proposalId) => this.postTo(grant.requester)({
1447
+ type: "connection.required",
1448
+ proposalId,
1449
+ provider,
1450
+ url,
1451
+ reason,
1452
+ })));
1453
+ return;
1454
+ }
1455
+ case "denied":
1456
+ return this.deny(event.grant, event.reason);
1457
+ case "revoked": {
1458
+ const { provider, principal, requesters, reason } = event;
1459
+ await Promise.all(requesters.map((requester) => this.postTo(requester)({
1460
+ type: "connection.revoked",
1461
+ provider,
1462
+ principal,
1463
+ reason,
1464
+ })));
1465
+ return;
1466
+ }
1467
+ default: {
1468
+ const unknown = event;
1469
+ throw new AgentJamError(`Received an unknown connection event: ${JSON.stringify(unknown)}`);
1470
+ }
1471
+ }
1472
+ }
1473
+ async receiveEvent(event) {
1474
+ switch (event.type) {
1475
+ case "event":
1476
+ return this.dispatch({ ...event.event, eventKeys: event.eventKeys });
1477
+ case "revoked": {
1478
+ const { type: _type, provider, ...revocation } = event;
1479
+ return this.revokeAccount(provider, revocation);
1480
+ }
1481
+ default: {
1482
+ const unknown = event;
1483
+ throw new AgentJamError(`Received an unknown source event: ${JSON.stringify(unknown)}`);
1484
+ }
1485
+ }
1486
+ }
1487
+ async revokeAccount(provider, revocation) {
1488
+ const revocations = this.allSources().flatMap((source) => source.provider === provider && typeof source.revokeAccount === "function"
1489
+ ? [source.revokeAccount(revocation)]
1490
+ : []);
1491
+ if (revocations.length === 0) {
1492
+ throw new AgentJamError(`${provider} revoked account ${revocation.id}, but no ${provider} connection can revoke accounts, so its grants stay until they fail`);
1493
+ }
1494
+ await Promise.all(revocations);
1495
+ }
1496
+ async deny(holder, reason) {
1497
+ this.incoming.get(key(holder.requester, holder.id))?.cancel(reason);
1498
+ this.release(holder, this.allSources());
1499
+ await this.postTo(holder.requester)({
1500
+ type: "task.reject",
1501
+ replyTo: holder.id,
1502
+ reason,
1503
+ });
1504
+ }
1505
+ release(holder, sources) {
1506
+ void Promise.all(Array.from(sources, (source) => source.release(holder))).catch(this.onError);
1507
+ }
1508
+ stopWatching() {
1509
+ for (const stop of this.unwatch)
1510
+ stop();
1511
+ for (const source of this.vaulted) {
1512
+ unbindGrantVault(source, this.requestedName);
1513
+ }
1514
+ }
1515
+ resolveWatch(outcomes) {
1516
+ Promise.resolve()
1517
+ .then(() => this.handlers.onWatchResolved?.(outcomes, this))
1518
+ .catch(this.onError);
1519
+ }
1520
+ require(peer, verdict) {
1521
+ if (verdict.type !== "task.require")
1522
+ return;
1523
+ this.requestActions({
1524
+ peer,
1525
+ proposalId: verdict.replyTo,
1526
+ actions: verdict.actions,
1527
+ });
1528
+ }
1529
+ requireAccess({ from, proposalId, provider, url, reason, }) {
1530
+ const id = key(from, proposalId);
1531
+ const awaiting = this.outgoing.get(id) ?? this.schedules.get(id);
1532
+ const action = { kind: "oauth", provider, url, reason };
1533
+ if (!awaiting?.requireAccess(action) || awaiting.parent)
1534
+ return;
1535
+ this.requestActions({ peer: from, proposalId, actions: [action] });
1536
+ }
1537
+ inherit({ from, taskId, actions }) {
1538
+ const task = this.outgoing.get(key(from, taskId));
1539
+ const pending = task?.inherit(actions) ?? [];
1540
+ if (task?.parent || pending.length === 0)
1541
+ return;
1542
+ this.requestActions({ peer: from, proposalId: taskId, actions: pending });
1543
+ }
1544
+ requestActions(request) {
1545
+ Promise.resolve()
1546
+ .then(() => this.onActionRequired(request, this))
1547
+ .catch(this.onError);
1548
+ }
1549
+ refuse(verdict) {
1550
+ const id = key(verdict.from, verdict.replyTo);
1551
+ const error = verdict.type === "error"
1552
+ ? new TaskFailedError(verdict.error)
1553
+ : new TaskRejectedError(verdict.from, verdict.reason);
1554
+ this.outgoing.get(id)?.fail(error);
1555
+ this.schedules.get(id)?.close(error.message);
1556
+ }
1557
+ async progress(envelope) {
1558
+ const { from, taskId } = envelope;
1559
+ const task = this.outgoing.get(key(from, taskId));
1560
+ if (task) {
1561
+ await task.receive(envelope);
1562
+ return this.forwardProgress(task, envelope);
1563
+ }
1564
+ if (envelope.type === "task.complete" || envelope.type === "task.fail") {
1565
+ return;
1566
+ }
1567
+ return this.postTo(from)({
1568
+ type: "task.cancel",
1569
+ taskId,
1570
+ reason: `${this.name} is no longer tracking this task`,
1571
+ });
1572
+ }
1573
+ /** Passes a delegated task's update up to the task it was delegated as part of. */
1574
+ async forwardProgress(task, envelope) {
1575
+ if (envelope.type !== "task.update" || !this.forward.updates)
1576
+ return;
1577
+ await this.findAbove(task)?.update(`${task.to}: ${envelope.text}`);
1578
+ }
1579
+ abandon(peer, abandoned) {
1580
+ const reason = `${peer} disconnected`;
1581
+ const ids = abandoned && new Set(abandoned);
1582
+ const isAbandoned = (id) => ids?.has(id) ?? true;
1583
+ this.requests.failTo(peer, new AgentNotFoundError(peer), ids);
1584
+ for (const task of this.outgoing.values()) {
1585
+ if (task.to === peer && isAbandoned(task.id)) {
1586
+ task.fail(new TaskFailedError(reason));
1587
+ }
1588
+ }
1589
+ for (const task of this.incoming.values()) {
1590
+ if (task.from === peer && !isRun(task) && isAbandoned(task.id)) {
1591
+ task.cancel(reason);
1592
+ }
1593
+ }
1594
+ }
1595
+ rejoin() {
1596
+ const error = new AgentJamError(`The relay replaced the session of ${this.name} after an outage, so the work it ran was abandoned`);
1597
+ this.abandonWork(error);
1598
+ for (const task of this.listDelegated())
1599
+ void this.reattach(task);
1600
+ this.onError(error);
1601
+ }
1602
+ orphan(error) {
1603
+ this.abandonWork(error);
1604
+ for (const task of this.listDelegated()) {
1605
+ task.fail(unfollowed(error.message));
1606
+ }
1607
+ this.onError(error);
1608
+ }
1609
+ abandonWork(error) {
1610
+ this.requests.failAll(error);
1611
+ for (const task of this.incoming.values())
1612
+ task.cancel(error.message);
1613
+ }
1614
+ // WARNING: the relay keeps this agent's runs going without it, and replays them once it reconnects.
1615
+ listDelegated() {
1616
+ return Array.from(this.outgoing.values()).filter((task) => !isRun(task));
1617
+ }
1618
+ async reattach(task) {
1619
+ try {
1620
+ await this.postTo(task.to)({ type: "task.reattach", taskId: task.id });
1621
+ }
1622
+ catch (error) {
1623
+ task.fail(error instanceof Error
1624
+ ? error
1625
+ : new AgentJamError(describeError(error)));
1626
+ }
1627
+ }
1628
+ async listEvery(query) {
1629
+ const summaries = [];
1630
+ let cursor;
1631
+ do {
1632
+ const page = await this.listTasks({
1633
+ ...query,
1634
+ ...(cursor && { cursor }),
1635
+ limit: maxTaskPage,
1636
+ });
1637
+ summaries.push(...page.tasks);
1638
+ cursor = page.next;
1639
+ } while (cursor);
1640
+ return summaries;
1641
+ }
1642
+ withdraw(executor, proposalId) {
1643
+ const reason = "The proposal is no longer pending";
1644
+ if (!this.scheduling.delete(key(executor, proposalId))) {
1645
+ return this.postTo(executor)({
1646
+ type: "task.cancel",
1647
+ taskId: proposalId,
1648
+ reason,
1649
+ });
1650
+ }
1651
+ return this.postTo(executor)({
1652
+ type: "schedule.end",
1653
+ scheduleId: proposalId,
1654
+ reason,
1655
+ });
1656
+ }
1657
+ follow(to, scheduleId, actions, parent) {
1658
+ const id = key(to, scheduleId);
1659
+ const schedule = new ScheduleHandle(scheduleId, to, {
1660
+ post: this.postTo(to),
1661
+ hand: (run) => this.collectAfter(run, scheduleId),
1662
+ release: () => this.schedules.delete(id),
1663
+ }, actions, parent);
1664
+ this.schedules.set(id, schedule);
1665
+ return schedule;
1666
+ }
1667
+ async closeSchedule({ from, scheduleId, reason, }) {
1668
+ this.schedules
1669
+ .get(key(from, scheduleId))
1670
+ ?.close(reason ?? `${from} ended the schedule`);
1671
+ await Promise.all([
1672
+ this.stopSchedule(from, scheduleId),
1673
+ this.postTo(from)({ type: "collect", scheduleId }),
1674
+ ]);
1675
+ }
1676
+ /** Stops the ended schedule's trigger, telling the relay so its connections close, then releases them. */
1677
+ async stopSchedule(requester, scheduleId) {
1678
+ try {
1679
+ if (await this.triggers.stop(requester, scheduleId, "ended")) {
1680
+ await this.postTo(requester)({ type: "trigger.stopped", scheduleId });
1681
+ }
1682
+ }
1683
+ finally {
1684
+ this.release({ requester, id: scheduleId }, this.allSources());
1685
+ }
1686
+ }
1687
+ notice(executor, notice) {
1688
+ const { id, scheduleId, taskId } = notice;
1689
+ const existing = this.outgoing.get(key(executor, taskId));
1690
+ if (existing)
1691
+ return existing;
1692
+ const schedule = this.schedules.get(key(executor, scheduleId));
1693
+ const run = this.track(executor, { id, replyTo: taskId }, {
1694
+ run: { scheduleId, event: eventOf(notice) },
1695
+ ...(schedule?.parent && { parent: schedule.parent }),
1696
+ });
1697
+ if (schedule) {
1698
+ schedule.add(run);
1699
+ }
1700
+ else {
1701
+ const handled = Promise.resolve(this.onRun(run, this)).catch(this.onError);
1702
+ this.collectAfter(run, scheduleId, handled);
1703
+ }
1704
+ return run;
1705
+ }
1706
+ followUp(notice) {
1707
+ const { from, scheduleId, runId } = notice;
1708
+ if (notice.error !== undefined) {
1709
+ return this.onError(new FollowUpFailedError(from, scheduleId, runId, notice.error));
1710
+ }
1711
+ const task = this.track(from, { replyTo: notice.taskId });
1712
+ const schedule = [...this.schedules.values()].find(({ id }) => id === scheduleId);
1713
+ if (schedule)
1714
+ return schedule.addFollowUp(task);
1715
+ Promise.resolve(this.onFollowUp(task, this)).catch(this.onError);
1716
+ }
1717
+ collectAfter(run, scheduleId, handled) {
1718
+ void Promise.allSettled([run.result(), handled])
1719
+ .then(() => this.postTo(run.to)({ type: "collect", scheduleId, taskId: run.id }))
1720
+ .catch(this.onError);
1721
+ }
1722
+ track(to, { id: attempt, replyTo: taskId, actions = [], }, { signal, ...details } = {}) {
1723
+ const id = key(to, taskId);
1724
+ const existing = this.outgoing.get(id);
1725
+ if (existing) {
1726
+ if (attempt)
1727
+ void existing.restart(attempt, actions);
1728
+ return existing;
1729
+ }
1730
+ const abort = () => {
1731
+ handle.cancel(describeError(signal?.reason)).catch(this.onError);
1732
+ };
1733
+ const handle = new TaskHandle(taskId, to, attempt, {
1734
+ post: this.postTo(to),
1735
+ send: this.sendAbout(to, taskId),
1736
+ release: () => {
1737
+ this.outgoing.delete(id);
1738
+ signal?.removeEventListener("abort", abort);
1739
+ },
1740
+ }, { ...details, actions });
1741
+ this.outgoing.set(id, handle);
1742
+ signal?.addEventListener("abort", abort, { once: true });
1743
+ return handle;
1744
+ }
1745
+ request(draft, { signal, timeoutMs = this.timeoutMs }, adopt) {
1746
+ const response = this.requests.track(draft, { signal, timeoutMs }, (reply) => {
1747
+ if (reply.type === "error")
1748
+ throw new AgentJamError(reply.error);
1749
+ return adopt(reply);
1750
+ });
1751
+ this.post(draft).catch((error) => this.requests.fail(draft.id, error));
1752
+ return response;
1753
+ }
1754
+ postTo(to) {
1755
+ return (body) => this.post({ ...body, id: crypto.randomUUID(), to });
1756
+ }
1757
+ sendAbout(peer, taskId) {
1758
+ return (text, options) => this.send(peer, text, { conversationId: taskId, ...options, taskId });
1759
+ }
1760
+ listHistoryOf(anchor) {
1761
+ return async (query) => {
1762
+ const connection = await this.connection;
1763
+ if (!connection.history)
1764
+ throw new AgentJamError(noHistory);
1765
+ return connection.history(anchor, query);
1766
+ };
1767
+ }
1768
+ uploadArtifact = async (file, signal) => {
1769
+ const connection = await this.connection;
1770
+ return connection.upload?.(file, signal);
1771
+ };
1772
+ findIncomingTask(requester, taskId) {
1773
+ if (taskId === undefined)
1774
+ return undefined;
1775
+ return this.incoming.get(key(requester, taskId));
1776
+ }
1777
+ findCurrentTask(requester) {
1778
+ const task = this.findRunningTask();
1779
+ return task?.from === requester ? task : undefined;
1780
+ }
1781
+ findRunningTask() {
1782
+ const task = currentTask();
1783
+ if (!task)
1784
+ return undefined;
1785
+ return this.incoming.get(key(task.from, task.id)) === task
1786
+ ? task
1787
+ : undefined;
1788
+ }
1789
+ findParent() {
1790
+ const task = this.findRunningTask();
1791
+ return task && { kind: "task", requester: task.from, id: task.id };
1792
+ }
1793
+ async post(draft) {
1794
+ const connection = await this.connection;
1795
+ await connection.send(draft);
1796
+ }
1797
+ async uploadAttachments(sources = [], signal) {
1798
+ if (sources.length === 0)
1799
+ return undefined;
1800
+ if (sources.length > maxAttachments) {
1801
+ throw new AgentJamError(`Attach at most ${maxAttachments} files, not ${sources.length}`);
1802
+ }
1803
+ const connection = await this.connection;
1804
+ if (!connection.upload)
1805
+ throw new AgentJamError(noUploads);
1806
+ const upload = connection.upload.bind(connection);
1807
+ const ids = await Promise.all(sources.map(async (source) => upload(await constructFile(source), signal)));
1808
+ return ids.map((attachmentId) => ({ attachmentId }));
1809
+ }
1810
+ }
1811
+ /**
1812
+ * Connects an agent that already exists, which you make with `create()` or on the dashboard. Without
1813
+ * an API key, it connects the guest `create()` saved on this machine under that name.
1814
+ *
1815
+ * @param options The agent's name and API key or network, its handlers, and the stored skills this process handles.
1816
+ * @returns The connected agent.
1817
+ * @throws {AgentJamError} If no agent has that name, `skills` handles something the stored profile doesn't have, or your tool names clash with the network tools.
1818
+ */
1819
+ export const connect = (options) => Agent.open(options);
1820
+ //# sourceMappingURL=agent.js.map