@agentjam/sdk 0.8.0 → 0.10.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 (178) hide show
  1. package/README.md +3 -2
  2. package/dist/agent.d.ts +52 -16
  3. package/dist/agent.d.ts.map +1 -1
  4. package/dist/agent.js +211 -70
  5. package/dist/agent.js.map +1 -1
  6. package/dist/anyOf.d.ts +2 -0
  7. package/dist/anyOf.d.ts.map +1 -1
  8. package/dist/anyOf.js +3 -0
  9. package/dist/anyOf.js.map +1 -1
  10. package/dist/artifacts.d.ts +8 -9
  11. package/dist/artifacts.d.ts.map +1 -1
  12. package/dist/artifacts.js +40 -76
  13. package/dist/artifacts.js.map +1 -1
  14. package/dist/attachments.d.ts +30 -5
  15. package/dist/attachments.d.ts.map +1 -1
  16. package/dist/attachments.js +53 -8
  17. package/dist/attachments.js.map +1 -1
  18. package/dist/connections.d.ts +3 -1
  19. package/dist/connections.d.ts.map +1 -1
  20. package/dist/connections.js +1 -0
  21. package/dist/connections.js.map +1 -1
  22. package/dist/content.d.ts +3 -9
  23. package/dist/content.d.ts.map +1 -1
  24. package/dist/content.js +0 -9
  25. package/dist/content.js.map +1 -1
  26. package/dist/definitions.d.ts +20 -0
  27. package/dist/definitions.d.ts.map +1 -0
  28. package/dist/definitions.js +28 -0
  29. package/dist/definitions.js.map +1 -0
  30. package/dist/errors.d.ts +24 -0
  31. package/dist/errors.d.ts.map +1 -1
  32. package/dist/errors.js +28 -0
  33. package/dist/errors.js.map +1 -1
  34. package/dist/files.d.ts +16 -4
  35. package/dist/files.d.ts.map +1 -1
  36. package/dist/files.js +26 -11
  37. package/dist/files.js.map +1 -1
  38. package/dist/index.d.ts +6 -4
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +3 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/inputs.d.ts +14 -0
  43. package/dist/inputs.d.ts.map +1 -1
  44. package/dist/inputs.js +59 -12
  45. package/dist/inputs.js.map +1 -1
  46. package/dist/managedWebhooks.d.ts.map +1 -1
  47. package/dist/managedWebhooks.js +2 -0
  48. package/dist/managedWebhooks.js.map +1 -1
  49. package/dist/platforms/datadog.d.ts +2 -2
  50. package/dist/platforms/datadog.d.ts.map +1 -1
  51. package/dist/platforms/discord.d.ts +59 -54
  52. package/dist/platforms/discord.d.ts.map +1 -1
  53. package/dist/platforms/discord.js +4 -0
  54. package/dist/platforms/discord.js.map +1 -1
  55. package/dist/platforms/discordEvents.d.ts.map +1 -1
  56. package/dist/platforms/discordEvents.js +2 -0
  57. package/dist/platforms/discordEvents.js.map +1 -1
  58. package/dist/platforms/discordInteractions.d.ts.map +1 -1
  59. package/dist/platforms/discordInteractions.js +2 -0
  60. package/dist/platforms/discordInteractions.js.map +1 -1
  61. package/dist/platforms/github.d.ts +37 -34
  62. package/dist/platforms/github.d.ts.map +1 -1
  63. package/dist/platforms/github.js +4 -0
  64. package/dist/platforms/github.js.map +1 -1
  65. package/dist/platforms/githubEvents.d.ts.map +1 -1
  66. package/dist/platforms/githubEvents.js +2 -0
  67. package/dist/platforms/githubEvents.js.map +1 -1
  68. package/dist/platforms/grafana.d.ts +2 -2
  69. package/dist/platforms/grafana.d.ts.map +1 -1
  70. package/dist/platforms/microsoft.d.ts +6 -3
  71. package/dist/platforms/microsoft.d.ts.map +1 -1
  72. package/dist/platforms/microsoft.js +4 -0
  73. package/dist/platforms/microsoft.js.map +1 -1
  74. package/dist/platforms/pagerduty.d.ts +2 -2
  75. package/dist/platforms/pagerduty.d.ts.map +1 -1
  76. package/dist/platforms/sentry.d.ts +8 -7
  77. package/dist/platforms/sentry.d.ts.map +1 -1
  78. package/dist/platforms/sentry.js +2 -0
  79. package/dist/platforms/sentry.js.map +1 -1
  80. package/dist/platforms/sentryEvents.d.ts.map +1 -1
  81. package/dist/platforms/sentryEvents.js +2 -0
  82. package/dist/platforms/sentryEvents.js.map +1 -1
  83. package/dist/platforms/slack.d.ts +54 -54
  84. package/dist/platforms/slack.d.ts.map +1 -1
  85. package/dist/platforms/slackEvents.d.ts.map +1 -1
  86. package/dist/platforms/slackEvents.js +2 -0
  87. package/dist/platforms/slackEvents.js.map +1 -1
  88. package/dist/platforms/slackInteractions.d.ts.map +1 -1
  89. package/dist/platforms/slackInteractions.js +2 -0
  90. package/dist/platforms/slackInteractions.js.map +1 -1
  91. package/dist/principals.d.ts +9 -0
  92. package/dist/principals.d.ts.map +1 -0
  93. package/dist/principals.js +9 -0
  94. package/dist/principals.js.map +1 -0
  95. package/dist/profile.d.ts +7 -7
  96. package/dist/profile.d.ts.map +1 -1
  97. package/dist/profile.js +11 -7
  98. package/dist/profile.js.map +1 -1
  99. package/dist/protocol.d.ts +19 -7
  100. package/dist/protocol.d.ts.map +1 -1
  101. package/dist/recaps.d.ts +12 -2
  102. package/dist/recaps.d.ts.map +1 -1
  103. package/dist/recaps.js +12 -1
  104. package/dist/recaps.js.map +1 -1
  105. package/dist/relay/chains.d.ts +6 -1
  106. package/dist/relay/chains.d.ts.map +1 -1
  107. package/dist/relay/chains.js +16 -1
  108. package/dist/relay/chains.js.map +1 -1
  109. package/dist/relay/frames.d.ts +3 -2
  110. package/dist/relay/frames.d.ts.map +1 -1
  111. package/dist/relay/frames.js +8 -2
  112. package/dist/relay/frames.js.map +1 -1
  113. package/dist/relay/history.d.ts +45 -0
  114. package/dist/relay/history.d.ts.map +1 -0
  115. package/dist/relay/history.js +235 -0
  116. package/dist/relay/history.js.map +1 -0
  117. package/dist/relay/memory.d.ts +34 -10
  118. package/dist/relay/memory.d.ts.map +1 -1
  119. package/dist/relay/memory.js +180 -36
  120. package/dist/relay/memory.js.map +1 -1
  121. package/dist/relay/relay.d.ts +2 -0
  122. package/dist/relay/relay.d.ts.map +1 -1
  123. package/dist/relay/remote.d.ts +1 -1
  124. package/dist/relay/remote.d.ts.map +1 -1
  125. package/dist/relay/remote.js +4 -2
  126. package/dist/relay/remote.js.map +1 -1
  127. package/dist/relay/resumes.d.ts +40 -0
  128. package/dist/relay/resumes.d.ts.map +1 -0
  129. package/dist/relay/resumes.js +75 -0
  130. package/dist/relay/resumes.js.map +1 -0
  131. package/dist/relay/schedules.d.ts.map +1 -1
  132. package/dist/relay/schedules.js +3 -2
  133. package/dist/relay/schedules.js.map +1 -1
  134. package/dist/relay/sessions.d.ts +14 -4
  135. package/dist/relay/sessions.d.ts.map +1 -1
  136. package/dist/relay/sessions.js +30 -8
  137. package/dist/relay/sessions.js.map +1 -1
  138. package/dist/relay/subscriptions.d.ts.map +1 -1
  139. package/dist/relay/subscriptions.js +2 -1
  140. package/dist/relay/subscriptions.js.map +1 -1
  141. package/dist/secrets.js +1 -0
  142. package/dist/secrets.js.map +1 -1
  143. package/dist/skillChecks.d.ts +58 -0
  144. package/dist/skillChecks.d.ts.map +1 -0
  145. package/dist/skillChecks.js +173 -0
  146. package/dist/skillChecks.js.map +1 -0
  147. package/dist/subscriptions.d.ts +4 -2
  148. package/dist/subscriptions.d.ts.map +1 -1
  149. package/dist/subscriptions.js +20 -7
  150. package/dist/subscriptions.js.map +1 -1
  151. package/dist/tasks/incoming.d.ts +78 -34
  152. package/dist/tasks/incoming.d.ts.map +1 -1
  153. package/dist/tasks/incoming.js +75 -32
  154. package/dist/tasks/incoming.js.map +1 -1
  155. package/dist/tasks/triggers.d.ts +2 -2
  156. package/dist/tasks/triggers.d.ts.map +1 -1
  157. package/dist/tasks/triggers.js +11 -1
  158. package/dist/tasks/triggers.js.map +1 -1
  159. package/dist/tools/network.js +1 -1
  160. package/dist/tools/network.js.map +1 -1
  161. package/dist/tools/shared.d.ts +3 -3
  162. package/dist/types.d.ts +219 -63
  163. package/dist/types.d.ts.map +1 -1
  164. package/dist/vaults/local.d.ts +1 -0
  165. package/dist/vaults/local.d.ts.map +1 -1
  166. package/dist/vaults/local.js +13 -0
  167. package/dist/vaults/local.js.map +1 -1
  168. package/dist/vaults/remote.d.ts +2 -0
  169. package/dist/vaults/remote.d.ts.map +1 -1
  170. package/dist/vaults/remote.js +2 -0
  171. package/dist/vaults/remote.js.map +1 -1
  172. package/dist/vaults/vault.d.ts.map +1 -1
  173. package/dist/vaults/vault.js.map +1 -1
  174. package/dist/verdicts.d.ts +4 -2
  175. package/dist/verdicts.d.ts.map +1 -1
  176. package/dist/verdicts.js +4 -2
  177. package/dist/verdicts.js.map +1 -1
  178. package/package.json +1 -1
package/dist/agent.js CHANGED
@@ -1,19 +1,22 @@
1
1
  import { isAnyOfConnection, leavesOf } from "./anyOf.js";
2
2
  import { ArtifactAssembler } from "./artifacts.js";
3
- import { assertAttachmentTotal, constructUpload, receiveAttachments, } from "./attachments.js";
3
+ import { assertAttachmentTotal, constructAttachmentEntry, ForwardedFile, receiveAttachments, } from "./attachments.js";
4
4
  import { bindGrantVault, Readiness, receiveRevocation, unbindGrantVault, } from "./connections.js";
5
5
  import { DEFAULT_TIME_ZONE } from "./cron.js";
6
- import { AgentJamError, AgentNotFoundError, describeError, FollowUpFailedError, TaskFailedError, TaskRejectedError, TriggerFailedError, } from "./errors.js";
6
+ import { AgentDeclinedError, AgentJamError, AgentNotFoundError, describeError, FollowUpFailedError, MessagesNotAcceptedError, TaskFailedError, TaskRejectedError, TriggerFailedError, } from "./errors.js";
7
7
  import { defaultMaxBufferedBytes, FileReceiver } from "./files.js";
8
8
  import { IdempotencyCache } from "./idempotency.js";
9
- import { isStoredSchema, parseValue } from "./inputs.js";
9
+ import { isInputSchema, isStoredSchema, parseTriggerValue, parseValue, } from "./inputs.js";
10
10
  import { receiveOAuthCallback } from "./oauthCallbacks.js";
11
- import { recapFromWire } from "./recaps.js";
11
+ import { resolveChainPrincipal } from "./principals.js";
12
+ import { listRecappedFiles, recapFromWire } from "./recaps.js";
12
13
  import { ReassignedError } from "./relay/frames.js";
13
14
  import { AgentJamRelay } from "./relay/remote.js";
14
15
  import { PendingRequests } from "./requests.js";
15
16
  import { screenProposal } from "./screening.js";
16
17
  import { constructSecretSource, isSecretConnection, isSecretSource, } from "./secrets.js";
18
+ import { describeMissingSkill, findProposalProblem, listVisibleSkills, } from "./skillChecks.js";
19
+ import { constructSubscriptionId } from "./subscriptions.js";
17
20
  import { AccessWaits } from "./tasks/access.js";
18
21
  import { currentTask, TaskExecution } from "./tasks/incoming.js";
19
22
  import { TaskHandle } from "./tasks/outgoing.js";
@@ -39,6 +42,7 @@ const noTasks = "This relay doesn't keep tasks";
39
42
  const noSchedules = "This relay doesn't keep schedules";
40
43
  const steered = "Passed your message to the running task, which reads it before its next step.";
41
44
  const noUploads = "This relay doesn't take attachments";
45
+ const noFileArtifacts = "This relay doesn't store files, so tasks can't deliver them";
42
46
  const maxAttachments = 10;
43
47
  const untaskedAttachments = "Only a message about a task, or a reply to one, can carry attachments";
44
48
  const untaskedSteer = "Only a message about a task can steer it";
@@ -86,7 +90,7 @@ const eventOf = ({ eventId, summary = "", eventData, }) => eventId === undefined
86
90
  const watchOf = ({ scheduleId, from, principal, text, skill, trigger, config, input, expiresAt, }) => ({
87
91
  id: scheduleId,
88
92
  from,
89
- ...(principal === undefined ? {} : { principal }),
93
+ principal: resolveChainPrincipal(principal, from),
90
94
  text,
91
95
  skill,
92
96
  trigger,
@@ -95,16 +99,21 @@ const watchOf = ({ scheduleId, from, principal, text, skill, trigger, config, in
95
99
  ...(expiresAt === undefined ? {} : { expiresAt: new Date(expiresAt) }),
96
100
  });
97
101
  const constructOrigin = (requester, taskId) => taskId === undefined ? undefined : { requester, taskId };
98
- const toProposal = ({ from, principal, text, skill, input, cron, trigger, budget, expiresAt, follows, previous, subscribe, }, attachments, files) => ({
102
+ const toProposal = ({ from, principal, text, skill, input, cron, trigger, budget, expiresAt, follows, previous, subscribe, }, attachments, files, parsed) => ({
99
103
  from,
100
- ...(principal === undefined ? {} : { principal }),
104
+ principal: resolveChainPrincipal(principal, from),
101
105
  text,
102
106
  ...(skill === undefined ? {} : { skill }),
103
- ...(input === undefined ? {} : { input }),
107
+ input: parsed.input ? parsed.input.value : input,
104
108
  ...(cron === undefined
105
109
  ? {}
106
110
  : { cron: { ...cron, timeZone: cron.timeZone ?? DEFAULT_TIME_ZONE } }),
107
- ...(trigger === undefined ? {} : { trigger }),
111
+ ...(trigger && {
112
+ trigger: {
113
+ name: trigger.name,
114
+ config: parsed.config ? parsed.config.value : trigger.config,
115
+ },
116
+ }),
108
117
  ...(budget === undefined ? {} : { budget }),
109
118
  ...(expiresAt === undefined ? {} : { expiresAt: new Date(expiresAt) }),
110
119
  attachments,
@@ -145,6 +154,11 @@ const ignoreReassigned = (error) => {
145
154
  if (!(error instanceof ReassignedError))
146
155
  throw error;
147
156
  };
157
+ const rejectDeclined = (error) => {
158
+ if (!(error instanceof AgentDeclinedError))
159
+ throw error;
160
+ return reject(error.reason);
161
+ };
148
162
  const unexpected = (reply) => new AgentJamError(`${reply.from} sent an unexpected ${reply.type}`);
149
163
  const constructQuestionOptions = (task, { signal, timeoutMs = Infinity, ...options }) => ({
150
164
  ...options,
@@ -223,6 +237,8 @@ export class Agent {
223
237
  link;
224
238
  connected = Promise.withResolvers();
225
239
  handlers;
240
+ context;
241
+ skills;
226
242
  screen;
227
243
  timeoutMs;
228
244
  files;
@@ -235,8 +251,6 @@ export class Agent {
235
251
  requestedName;
236
252
  sources;
237
253
  vaulted;
238
- inputs;
239
- delegates;
240
254
  unwatch;
241
255
  readiness = new Readiness();
242
256
  accessWaits = new AccessWaits();
@@ -251,7 +265,7 @@ export class Agent {
251
265
  performed = new IdempotencyCache(dedupeWindow);
252
266
  triggers;
253
267
  watches = new TaskWatches((outcomes) => this.resolveWatch(outcomes));
254
- constructor({ name, apiKey, network, payments, skills = [], networkTools = true, timeoutMs = defaultTimeout, instanceId, forward = {}, onError = console.error, onRun = logRun, onFollowUp = logFollowUp, onActionRequired = warnActions, toolNames = [], screen, maxBufferedBytes = defaultMaxBufferedBytes, ...handlers }, shown = {}) {
268
+ constructor({ name, apiKey, network, payments, skills = [], networkTools = true, timeoutMs = defaultTimeout, instanceId, forward = {}, onError = console.error, onRun = logRun, onFollowUp = logFollowUp, onActionRequired = warnActions, toolNames = [], screen, maxBufferedBytes = defaultMaxBufferedBytes, context, ...handlers }, shown = {}) {
255
269
  this.requestedName = name;
256
270
  const bindSecret = (connection) => constructSecretSource(connection, () => this.credentialChannel(connection.provider));
257
271
  this.sources = new Map(skills.map((skill) => [skill.name, sourcesOf(skill, bindSecret)]));
@@ -271,8 +285,8 @@ export class Agent {
271
285
  }));
272
286
  return bound.includes(true);
273
287
  }));
274
- this.inputs = new Map(skills.flatMap((skill) => skill.input ? [[skill.name, skill.input]] : []));
275
- this.delegates = new Map(skills.flatMap((skill) => skill.delegates ? [[skill.name, skill.delegates]] : []));
288
+ this.skills = new Map(skills.map((skill) => [skill.name, skill]));
289
+ this.context = { ...context, agent: this };
276
290
  this.forward = { ...allForwarded, ...forward };
277
291
  const tools = createNetworkTools(this, {
278
292
  watching: handlers.onWatchResolved !== undefined,
@@ -307,7 +321,7 @@ export class Agent {
307
321
  void this.restartTriggers(this.connection);
308
322
  },
309
323
  onError: (error) => this.orphan(error),
310
- }, { instanceId })
324
+ }, { instanceId, messages: handlers.onMessage !== undefined })
311
325
  .then(async (connection) => {
312
326
  try {
313
327
  assertStored(connection.card, skills);
@@ -389,6 +403,7 @@ export class Agent {
389
403
  * @returns The recipient's reply, with its files downloaded.
390
404
  * @throws {AgentJamError} If the message attaches files or steers without being about a task, or an attachment couldn't upload.
391
405
  * @throws {AgentNotFoundError} If no agent at `to` is connected.
406
+ * @throws {MessagesNotAcceptedError} If the recipient connected without `onMessage`.
392
407
  * @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.
393
408
  */
394
409
  async send(to, text, { conversationId = crypto.randomUUID(), idempotencyKey = crypto.randomUUID(), taskId = this.findCurrentTask(to)?.id, attachments, steer, ...options } = {}) {
@@ -892,7 +907,7 @@ export class Agent {
892
907
  await Promise.allSettled([
893
908
  this.triggers.stopAll("closing"),
894
909
  ...Array.from(this.incoming.values(), (task) => task.resumable
895
- ? task.abandon(new AgentJamError(reason))
910
+ ? task.handOver(new AgentJamError(reason))
896
911
  : task.fail(new AgentJamError(reason))),
897
912
  ]);
898
913
  const connection = await this.connection;
@@ -1042,10 +1057,16 @@ export class Agent {
1042
1057
  if (steer && this.findSteered(envelope)?.queueMessage(message)) {
1043
1058
  return steered;
1044
1059
  }
1045
- if (!this.handlers.onMessage) {
1046
- throw new AgentJamError(`${this.name} does not accept messages`);
1060
+ if (!this.handlers.onMessage)
1061
+ throw new MessagesNotAcceptedError(this.name);
1062
+ try {
1063
+ return await this.handlers.onMessage(message, this);
1064
+ }
1065
+ catch (error) {
1066
+ if (error instanceof AgentDeclinedError)
1067
+ return error.reason;
1068
+ throw error;
1047
1069
  }
1048
- return this.handlers.onMessage(message, this);
1049
1070
  }
1050
1071
  /** Finds the running task a requester's message about it may steer. */
1051
1072
  findSteered({ from, taskId }) {
@@ -1102,7 +1123,7 @@ export class Agent {
1102
1123
  isOptedOut: proposal.subscribe === false,
1103
1124
  ...this.accessOf(skill, grant),
1104
1125
  }, {
1105
- post: this.postTo(from),
1126
+ post: this.postForTask(skill, grant),
1106
1127
  send: this.sendAbout(from, proposal.id),
1107
1128
  upload: this.uploadArtifact,
1108
1129
  prepare: this.prepareFor({
@@ -1110,6 +1131,7 @@ export class Agent {
1110
1131
  requester: from,
1111
1132
  id: proposal.id,
1112
1133
  }),
1134
+ recall: (ref) => this.recallTask(ref),
1113
1135
  listHistory: this.listHistoryOf({
1114
1136
  requester: from,
1115
1137
  taskId: proposal.id,
@@ -1130,13 +1152,18 @@ export class Agent {
1130
1152
  cleanup();
1131
1153
  throw error;
1132
1154
  }
1133
- void this.execute(task, cleanup, async (incoming) => {
1134
- await this.readiness.wait(grant, incoming.signal);
1135
- if (!proposal.prepare)
1136
- return this.handlers.onTask?.(incoming, this);
1137
- // WARNING: the relay cancels a task's children once it ends, so a preparation outlives the ones below it.
1138
- await awaitPreparations(preparations);
1139
- });
1155
+ if (proposal.prepare) {
1156
+ void this.execute(task, cleanup, async (incoming) => {
1157
+ await this.readiness.wait(grant, incoming.signal);
1158
+ // WARNING: the relay cancels a task's children once it ends, so a preparation outlives the ones below it.
1159
+ await awaitPreparations(preparations);
1160
+ });
1161
+ }
1162
+ else {
1163
+ void this.executeSkill(task, cleanup, async (incoming) => {
1164
+ await this.readiness.wait(grant, incoming.signal);
1165
+ });
1166
+ }
1140
1167
  return task.settled;
1141
1168
  }
1142
1169
  async judge(proposal) {
@@ -1146,24 +1173,27 @@ export class Agent {
1146
1173
  replyTo: proposal.id,
1147
1174
  };
1148
1175
  try {
1149
- const parsedInput = proposal.prepare
1150
- ? undefined
1151
- : await this.parseSkillInput(proposal.skill, proposal.input);
1176
+ const [parsedInput, parsedConfig] = proposal.prepare
1177
+ ? []
1178
+ : await Promise.all([
1179
+ this.parseSkillInput(proposal.skill, proposal.input),
1180
+ this.parseTriggerConfig(proposal),
1181
+ ]);
1182
+ const refuse = (reason) => ({
1183
+ verdict: { ...response, type: "task.reject", reason },
1184
+ attachments: [],
1185
+ });
1152
1186
  if (parsedInput && "problem" in parsedInput) {
1153
- return {
1154
- verdict: {
1155
- ...response,
1156
- type: "task.reject",
1157
- reason: parsedInput.problem,
1158
- },
1159
- attachments: [],
1160
- };
1187
+ return refuse(parsedInput.problem);
1188
+ }
1189
+ if (parsedConfig && "problem" in parsedConfig) {
1190
+ return refuse(parsedConfig.problem);
1161
1191
  }
1162
1192
  const attachments = receiveAttachments(proposal.attachments, this.files, {
1163
1193
  requester: proposal.from,
1164
1194
  taskId: proposal.id,
1165
1195
  });
1166
- const { verdict, preparations } = await this.constructVerdict(proposal, attachments);
1196
+ const { verdict, preparations } = await this.constructVerdict(proposal, attachments, { input: parsedInput, config: parsedConfig });
1167
1197
  return {
1168
1198
  verdict: { ...response, ...verdict },
1169
1199
  attachments,
@@ -1178,9 +1208,9 @@ export class Agent {
1178
1208
  };
1179
1209
  }
1180
1210
  }
1181
- async constructVerdict(proposal, attachments) {
1211
+ async constructVerdict(proposal, attachments, parsed) {
1182
1212
  const { id, from, principal, skill } = proposal;
1183
- const incoming = toProposal(proposal, attachments, this.files);
1213
+ const incoming = toProposal(proposal, attachments, this.files, parsed);
1184
1214
  const verdict = proposal.prepare ? accept() : await this.decide(incoming);
1185
1215
  if (!verdict.accepted) {
1186
1216
  const rejection = {
@@ -1216,12 +1246,16 @@ export class Agent {
1216
1246
  /** Lists the delegates of the proposal's skill, leaving out picked ones while another agent only prepares it. */
1217
1247
  async pickDelegates(proposal, incoming) {
1218
1248
  const { skill, prepare, then } = proposal;
1219
- const delegates = skill === undefined ? [] : this.delegates.get(skill);
1249
+ const delegates = this.findSkill(skill)?.delegates;
1220
1250
  const followUp = then ? [{ agent: then.to, skill: then.skill }] : [];
1221
1251
  if (typeof delegates !== "function") {
1222
1252
  return [...(delegates ?? []), ...followUp];
1223
1253
  }
1224
- return prepare ? [] : [...(await delegates(incoming, this)), ...followUp];
1254
+ if (prepare)
1255
+ return [];
1256
+ // WARNING: `incoming` carries the input this skill's own schema parsed, which is the type its picker takes.
1257
+ const picked = await delegates(incoming, this);
1258
+ return [...picked, ...followUp];
1225
1259
  }
1226
1260
  prepareFor(parent) {
1227
1261
  return async (delegates) => {
@@ -1263,20 +1297,31 @@ export class Agent {
1263
1297
  });
1264
1298
  }
1265
1299
  /**
1266
- * Runs the checks proposals get without an `onProposal`: rejecting every proposal without an `onTask`, and ones
1267
- * that name a skill the agent doesn't advertise or a trigger its skill doesn't declare. Call it from `onProposal` to keep them.
1300
+ * Runs the checks a proposal must pass before it reaches `onProposal`. It rejects proposals that name a skill the
1301
+ * agent doesn't advertise or a trigger its skill doesn't declare, ones the skill's `runsAs` rules out, and ones that
1302
+ * name no skill or a skill this process has no `perform` for while the agent has no `onTask`.
1268
1303
  *
1269
1304
  * @param proposal The proposal to check.
1270
1305
  * @returns Whether the proposal passes the checks.
1271
1306
  */
1272
1307
  checkProposal(proposal) {
1273
1308
  const { skill, trigger } = proposal;
1274
- if (!this.handlers.onTask) {
1275
- return reject(`${this.name} does not accept tasks`);
1276
- }
1309
+ const skills = listVisibleSkills(this.card, proposal.from);
1310
+ if (skill === undefined && !this.handlers.onTask) {
1311
+ return reject(skills.length > 0
1312
+ ? describeMissingSkill(this.name, skills)
1313
+ : `"${this.name}" does not accept tasks`);
1314
+ }
1315
+ const problem = findProposalProblem(this.card, proposal, {
1316
+ attached: proposal.attachments,
1317
+ previous: listRecappedFiles(proposal.previous),
1318
+ });
1319
+ if (problem)
1320
+ return reject(problem);
1277
1321
  if (skill !== undefined &&
1278
- !this.card.skills.some(({ name }) => name === skill)) {
1279
- return reject(`${this.name} has no skill named "${skill}"`);
1322
+ !this.findSkill(skill)?.perform &&
1323
+ !this.handlers.onTask) {
1324
+ return reject(`"${this.name}" does not run the "${skill}" skill`);
1280
1325
  }
1281
1326
  if (trigger && !this.triggers.offers(skill, trigger.name)) {
1282
1327
  return reject(`${this.name} has no trigger named "${trigger.name}" for this skill`);
@@ -1285,7 +1330,7 @@ export class Agent {
1285
1330
  }
1286
1331
  /** @internal The agents and skills a skill hands work off to, leaving out ones a function picks per proposal. */
1287
1332
  listDelegates(skill) {
1288
- const delegates = skill === undefined ? [] : this.delegates.get(skill);
1333
+ const delegates = this.findSkill(skill)?.delegates;
1289
1334
  return Array.isArray(delegates) ? delegates : [];
1290
1335
  }
1291
1336
  /** @internal Reports an error that can't reach another agent to `onError`. */
@@ -1293,19 +1338,34 @@ export class Agent {
1293
1338
  this.onError(error);
1294
1339
  }
1295
1340
  async decide(proposal) {
1296
- const verdict = this.handlers.onProposal
1297
- ? await this.handlers.onProposal(proposal, this)
1298
- : this.checkProposal(proposal);
1341
+ const checked = this.checkProposal(proposal);
1342
+ if (!checked.accepted)
1343
+ return checked;
1344
+ const verdict = await this.consultHandlers(proposal, checked).catch(rejectDeclined);
1299
1345
  if (!verdict.accepted || !this.screen || proposal.from === this.name) {
1300
1346
  return verdict;
1301
1347
  }
1302
1348
  return screenProposal(proposal, this, this.screen);
1303
1349
  }
1350
+ /** Asks `onProposal`, then the skill's `consider`, about a proposal `checkProposal()` accepted. */
1351
+ async consultHandlers(proposal, checked) {
1352
+ const gated = await this.handlers.onProposal?.(proposal, this.context);
1353
+ if (gated && !gated.accepted)
1354
+ return gated;
1355
+ const skill = this.findSkill(proposal.skill);
1356
+ return skill?.consider ? skill.consider(proposal, this.context) : checked;
1357
+ }
1358
+ async parseTriggerConfig({ skill, trigger }) {
1359
+ const schema = trigger && this.findSkill(skill)?.triggers?.[trigger.name]?.config;
1360
+ if (!trigger || !schema || !isInputSchema(schema))
1361
+ return undefined;
1362
+ return parseTriggerValue(trigger.name, "config", schema, trigger.config);
1363
+ }
1304
1364
  async parseSkillInput(skill, input) {
1305
- if (skill === undefined)
1365
+ const schema = this.findSkill(skill)?.input;
1366
+ if (skill === undefined || !schema)
1306
1367
  return undefined;
1307
- const schema = this.inputs.get(skill);
1308
- return schema && parseValue(skill, "input", schema, input);
1368
+ return parseValue(skill, "input", schema, input);
1309
1369
  }
1310
1370
  priceOf(skill, requester) {
1311
1371
  if (requester === this.name)
@@ -1334,6 +1394,7 @@ export class Agent {
1334
1394
  const id = key(from, taskId);
1335
1395
  const { response } = this.performed.remember(id, async () => {
1336
1396
  const { attachments, parsedInput, failure } = await this.receiveTask(recur, { requester: from, taskId });
1397
+ const received = await this.readFiredEvent(recur);
1337
1398
  const task = new TaskExecution({
1338
1399
  id: taskId,
1339
1400
  from,
@@ -1345,7 +1406,7 @@ export class Agent {
1345
1406
  attachments,
1346
1407
  scheduleId,
1347
1408
  run,
1348
- event: eventOf(recur),
1409
+ event: received.event,
1349
1410
  price: this.priceOf(skill, from),
1350
1411
  card: this.findSkillCard(skill),
1351
1412
  isSelf: from === this.name,
@@ -1360,6 +1421,7 @@ export class Agent {
1360
1421
  requester: from,
1361
1422
  id: taskId,
1362
1423
  }),
1424
+ recall: (ref) => this.recallTask(ref),
1363
1425
  listHistory: this.listHistoryOf({ requester: from, taskId }),
1364
1426
  requireAccess: this.requireAccessFor(skill, { requester: from, id: scheduleId, principal: principal ?? from }, taskId),
1365
1427
  });
@@ -1368,14 +1430,39 @@ export class Agent {
1368
1430
  this.performed.release(id);
1369
1431
  };
1370
1432
  this.incoming.set(id, task);
1371
- await this.execute(task, cleanup, async (incoming) => {
1372
- if (failure)
1373
- throw failure.error;
1374
- return this.handlers.onTask?.(incoming, this);
1433
+ await this.executeSkill(task, cleanup, () => {
1434
+ const problem = failure ?? received.failure;
1435
+ if (problem)
1436
+ throw problem.error;
1375
1437
  });
1376
1438
  });
1377
1439
  return response;
1378
1440
  }
1441
+ /** Names the trigger whose event started a run, and parses the event's data with that trigger's `event` schema. */
1442
+ async readFiredEvent(recur) {
1443
+ const event = eventOf(recur);
1444
+ if (!event)
1445
+ return { event: undefined };
1446
+ const name = recur.event?.trigger ?? this.findOnlyTrigger(recur.skill);
1447
+ if (!name)
1448
+ return { event };
1449
+ const named = { ...event, name };
1450
+ const schema = this.findSkill(recur.skill)?.triggers?.[name]?.event;
1451
+ if (!schema)
1452
+ return { event: named };
1453
+ const parsed = await parseTriggerValue(name, "event", schema, event.data).catch((error) => ({ problem: describeError(error) }));
1454
+ if ("problem" in parsed) {
1455
+ return {
1456
+ event: named,
1457
+ failure: { error: new AgentJamError(parsed.problem) },
1458
+ };
1459
+ }
1460
+ return { event: { ...named, data: parsed.value } };
1461
+ }
1462
+ findOnlyTrigger(skill) {
1463
+ const triggers = this.findSkillCard(skill)?.triggers ?? [];
1464
+ return triggers.length === 1 ? triggers[0]?.name : undefined;
1465
+ }
1379
1466
  /**
1380
1467
  * Runs a task of a resumable skill that the relay moved here from a departed session of this agent, following the
1381
1468
  * tasks it delegated there so their events aren't refused as unknown. A repeat of an attempt already running is ignored.
@@ -1416,19 +1503,19 @@ export class Agent {
1416
1503
  isOptedOut: proposal.subscribe === false,
1417
1504
  ...this.accessOf(skill, grant),
1418
1505
  }, {
1419
- post: this.postTo(from),
1506
+ post: this.postForTask(skill, grant),
1420
1507
  send: this.sendAbout(from, taskId),
1421
1508
  upload: this.uploadArtifact,
1422
1509
  prepare: this.prepareFor(parent),
1510
+ recall: (ref) => this.recallTask(ref),
1423
1511
  listHistory: this.listHistoryOf({ requester: from, taskId }),
1424
1512
  requireAccess: this.requireAccessFor(skill, { ...grant, principal: principal ?? from }, taskId),
1425
1513
  });
1426
1514
  const cleanup = () => this.releaseExecution(id, task, grant);
1427
1515
  this.incoming.set(id, task);
1428
- await this.execute(task, cleanup, async (incoming) => {
1516
+ await this.executeSkill(task, cleanup, () => {
1429
1517
  if (failure)
1430
1518
  throw failure.error;
1431
- return this.handlers.onTask?.(incoming, this);
1432
1519
  });
1433
1520
  }
1434
1521
  /** Receives a task's attachments and parses its input, keeping the first failure for the task's run to throw. */
@@ -1483,6 +1570,35 @@ export class Agent {
1483
1570
  cleanup();
1484
1571
  }
1485
1572
  }
1573
+ /** Runs a task with its skill's `perform`, or `onTask` without one, between the task lifecycle hooks, once `prepare` resolves. */
1574
+ async executeSkill(task, cleanup, prepare) {
1575
+ let started = false;
1576
+ await this.execute(task, cleanup, async (incoming) => {
1577
+ await prepare(incoming);
1578
+ started = true;
1579
+ await this.handlers.onTaskStarted?.(incoming, this.context);
1580
+ return this.runTask(incoming);
1581
+ });
1582
+ if (started)
1583
+ await this.endTask(task);
1584
+ }
1585
+ runTask(task) {
1586
+ const skill = this.findSkill(task.skill);
1587
+ return skill?.perform
1588
+ ? skill.perform(task, this.context)
1589
+ : this.handlers.onTask?.(task, this);
1590
+ }
1591
+ findSkill(name) {
1592
+ return name === undefined ? undefined : this.skills.get(name);
1593
+ }
1594
+ async endTask(task) {
1595
+ try {
1596
+ await this.handlers.onTaskEnded?.(task, this.context, task.ending);
1597
+ }
1598
+ catch (error) {
1599
+ this.onError(error);
1600
+ }
1601
+ }
1486
1602
  allSources() {
1487
1603
  const sources = [...this.sources.values()].flatMap((skill) => [
1488
1604
  ...skill.values(),
@@ -1975,6 +2091,26 @@ export class Agent {
1975
2091
  postTo(to) {
1976
2092
  return (body) => this.post({ ...body, id: crypto.randomUUID(), to });
1977
2093
  }
2094
+ /** Posts for a one-off task, handing its accounts over to the subscription its completion starts before sending it. */
2095
+ postForTask(skill, task) {
2096
+ const post = this.postTo(task.requester);
2097
+ return async (body) => {
2098
+ const isSubscribing = body.type === "task.complete" && body.subscription !== undefined;
2099
+ if (!isSubscribing)
2100
+ return post(body);
2101
+ const { requester, id } = task;
2102
+ const subscription = { requester, id: constructSubscriptionId(id) };
2103
+ const sources = [...this.sourcesFor(skill).values()];
2104
+ try {
2105
+ await Promise.all(sources.map(async (source) => source.handOver?.(task, subscription)));
2106
+ await post(body);
2107
+ }
2108
+ catch (error) {
2109
+ this.release(subscription, sources);
2110
+ throw error;
2111
+ }
2112
+ };
2113
+ }
1978
2114
  sendAbout(peer, taskId) {
1979
2115
  return (text, options) => this.send(peer, text, { conversationId: taskId, ...options, taskId });
1980
2116
  }
@@ -1988,7 +2124,9 @@ export class Agent {
1988
2124
  }
1989
2125
  uploadArtifact = async (source, signal) => {
1990
2126
  const connection = await this.connection;
1991
- return connection.upload?.(source, signal);
2127
+ if (!connection.upload)
2128
+ throw new AgentJamError(noFileArtifacts);
2129
+ return connection.upload(source, signal);
1992
2130
  };
1993
2131
  findIncomingTask(requester, taskId) {
1994
2132
  if (taskId === undefined)
@@ -2024,11 +2162,14 @@ export class Agent {
2024
2162
  const connection = await this.connection;
2025
2163
  if (!connection.upload)
2026
2164
  throw new AgentJamError(noUploads);
2027
- const uploads = await Promise.all(sources.map(constructUpload));
2028
- assertAttachmentTotal(uploads);
2165
+ const entries = await Promise.all(sources.map(constructAttachmentEntry));
2166
+ assertAttachmentTotal(entries);
2029
2167
  const upload = connection.upload.bind(connection);
2030
- const ids = await Promise.all(uploads.map((source) => upload(source, signal)));
2031
- return ids.map((attachmentId) => ({ attachmentId }));
2168
+ return Promise.all(entries.map(async (entry) => {
2169
+ if (entry instanceof ForwardedFile)
2170
+ return entry.ref;
2171
+ return { attachmentId: await upload(entry, signal) };
2172
+ }));
2032
2173
  }
2033
2174
  }
2034
2175
  /**