@agentjam/sdk 0.9.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 (151) hide show
  1. package/README.md +2 -1
  2. package/dist/agent.d.ts +49 -15
  3. package/dist/agent.d.ts.map +1 -1
  4. package/dist/agent.js +185 -68
  5. package/dist/agent.js.map +1 -1
  6. package/dist/artifacts.d.ts +8 -9
  7. package/dist/artifacts.d.ts.map +1 -1
  8. package/dist/artifacts.js +40 -76
  9. package/dist/artifacts.js.map +1 -1
  10. package/dist/attachments.d.ts +30 -5
  11. package/dist/attachments.d.ts.map +1 -1
  12. package/dist/attachments.js +53 -8
  13. package/dist/attachments.js.map +1 -1
  14. package/dist/content.d.ts +3 -9
  15. package/dist/content.d.ts.map +1 -1
  16. package/dist/content.js +0 -9
  17. package/dist/content.js.map +1 -1
  18. package/dist/definitions.d.ts +20 -0
  19. package/dist/definitions.d.ts.map +1 -0
  20. package/dist/definitions.js +28 -0
  21. package/dist/definitions.js.map +1 -0
  22. package/dist/errors.d.ts +24 -0
  23. package/dist/errors.d.ts.map +1 -1
  24. package/dist/errors.js +28 -0
  25. package/dist/errors.js.map +1 -1
  26. package/dist/files.d.ts +16 -4
  27. package/dist/files.d.ts.map +1 -1
  28. package/dist/files.js +26 -11
  29. package/dist/files.js.map +1 -1
  30. package/dist/index.d.ts +6 -4
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +3 -1
  33. package/dist/index.js.map +1 -1
  34. package/dist/inputs.d.ts +14 -0
  35. package/dist/inputs.d.ts.map +1 -1
  36. package/dist/inputs.js +59 -12
  37. package/dist/inputs.js.map +1 -1
  38. package/dist/managedWebhooks.d.ts.map +1 -1
  39. package/dist/managedWebhooks.js +2 -0
  40. package/dist/managedWebhooks.js.map +1 -1
  41. package/dist/platforms/datadog.d.ts +2 -2
  42. package/dist/platforms/datadog.d.ts.map +1 -1
  43. package/dist/platforms/discord.d.ts +59 -54
  44. package/dist/platforms/discord.d.ts.map +1 -1
  45. package/dist/platforms/discord.js +4 -0
  46. package/dist/platforms/discord.js.map +1 -1
  47. package/dist/platforms/discordEvents.d.ts.map +1 -1
  48. package/dist/platforms/discordEvents.js +2 -0
  49. package/dist/platforms/discordEvents.js.map +1 -1
  50. package/dist/platforms/discordInteractions.d.ts.map +1 -1
  51. package/dist/platforms/discordInteractions.js +2 -0
  52. package/dist/platforms/discordInteractions.js.map +1 -1
  53. package/dist/platforms/github.d.ts +37 -34
  54. package/dist/platforms/github.d.ts.map +1 -1
  55. package/dist/platforms/github.js +4 -0
  56. package/dist/platforms/github.js.map +1 -1
  57. package/dist/platforms/githubEvents.d.ts.map +1 -1
  58. package/dist/platforms/githubEvents.js +2 -0
  59. package/dist/platforms/githubEvents.js.map +1 -1
  60. package/dist/platforms/grafana.d.ts +2 -2
  61. package/dist/platforms/grafana.d.ts.map +1 -1
  62. package/dist/platforms/microsoft.d.ts +6 -3
  63. package/dist/platforms/microsoft.d.ts.map +1 -1
  64. package/dist/platforms/microsoft.js +4 -0
  65. package/dist/platforms/microsoft.js.map +1 -1
  66. package/dist/platforms/pagerduty.d.ts +2 -2
  67. package/dist/platforms/pagerduty.d.ts.map +1 -1
  68. package/dist/platforms/sentry.d.ts +8 -7
  69. package/dist/platforms/sentry.d.ts.map +1 -1
  70. package/dist/platforms/sentry.js +2 -0
  71. package/dist/platforms/sentry.js.map +1 -1
  72. package/dist/platforms/sentryEvents.d.ts.map +1 -1
  73. package/dist/platforms/sentryEvents.js +2 -0
  74. package/dist/platforms/sentryEvents.js.map +1 -1
  75. package/dist/platforms/slack.d.ts +54 -54
  76. package/dist/platforms/slack.d.ts.map +1 -1
  77. package/dist/platforms/slackEvents.d.ts.map +1 -1
  78. package/dist/platforms/slackEvents.js +2 -0
  79. package/dist/platforms/slackEvents.js.map +1 -1
  80. package/dist/platforms/slackInteractions.d.ts.map +1 -1
  81. package/dist/platforms/slackInteractions.js +2 -0
  82. package/dist/platforms/slackInteractions.js.map +1 -1
  83. package/dist/principals.d.ts +9 -0
  84. package/dist/principals.d.ts.map +1 -0
  85. package/dist/principals.js +9 -0
  86. package/dist/principals.js.map +1 -0
  87. package/dist/profile.d.ts +5 -5
  88. package/dist/profile.d.ts.map +1 -1
  89. package/dist/profile.js +9 -5
  90. package/dist/profile.js.map +1 -1
  91. package/dist/protocol.d.ts +14 -5
  92. package/dist/protocol.d.ts.map +1 -1
  93. package/dist/recaps.d.ts +12 -2
  94. package/dist/recaps.d.ts.map +1 -1
  95. package/dist/recaps.js +12 -1
  96. package/dist/recaps.js.map +1 -1
  97. package/dist/relay/chains.d.ts +6 -1
  98. package/dist/relay/chains.d.ts.map +1 -1
  99. package/dist/relay/chains.js +16 -1
  100. package/dist/relay/chains.js.map +1 -1
  101. package/dist/relay/frames.d.ts +3 -2
  102. package/dist/relay/frames.d.ts.map +1 -1
  103. package/dist/relay/frames.js +8 -2
  104. package/dist/relay/frames.js.map +1 -1
  105. package/dist/relay/history.d.ts +45 -0
  106. package/dist/relay/history.d.ts.map +1 -0
  107. package/dist/relay/history.js +235 -0
  108. package/dist/relay/history.js.map +1 -0
  109. package/dist/relay/memory.d.ts +34 -10
  110. package/dist/relay/memory.d.ts.map +1 -1
  111. package/dist/relay/memory.js +180 -36
  112. package/dist/relay/memory.js.map +1 -1
  113. package/dist/relay/relay.d.ts +2 -0
  114. package/dist/relay/relay.d.ts.map +1 -1
  115. package/dist/relay/remote.d.ts +1 -1
  116. package/dist/relay/remote.d.ts.map +1 -1
  117. package/dist/relay/remote.js +4 -2
  118. package/dist/relay/remote.js.map +1 -1
  119. package/dist/relay/resumes.d.ts +40 -0
  120. package/dist/relay/resumes.d.ts.map +1 -0
  121. package/dist/relay/resumes.js +75 -0
  122. package/dist/relay/resumes.js.map +1 -0
  123. package/dist/relay/schedules.d.ts.map +1 -1
  124. package/dist/relay/schedules.js +3 -2
  125. package/dist/relay/schedules.js.map +1 -1
  126. package/dist/relay/sessions.d.ts +14 -4
  127. package/dist/relay/sessions.d.ts.map +1 -1
  128. package/dist/relay/sessions.js +30 -8
  129. package/dist/relay/sessions.js.map +1 -1
  130. package/dist/skillChecks.d.ts +58 -0
  131. package/dist/skillChecks.d.ts.map +1 -0
  132. package/dist/skillChecks.js +173 -0
  133. package/dist/skillChecks.js.map +1 -0
  134. package/dist/tasks/incoming.d.ts +78 -34
  135. package/dist/tasks/incoming.d.ts.map +1 -1
  136. package/dist/tasks/incoming.js +75 -32
  137. package/dist/tasks/incoming.js.map +1 -1
  138. package/dist/tasks/triggers.d.ts +2 -2
  139. package/dist/tasks/triggers.d.ts.map +1 -1
  140. package/dist/tasks/triggers.js +11 -1
  141. package/dist/tasks/triggers.js.map +1 -1
  142. package/dist/tools/network.js +1 -1
  143. package/dist/tools/network.js.map +1 -1
  144. package/dist/tools/shared.d.ts +3 -3
  145. package/dist/types.d.ts +215 -60
  146. package/dist/types.d.ts.map +1 -1
  147. package/dist/verdicts.d.ts +4 -2
  148. package/dist/verdicts.d.ts.map +1 -1
  149. package/dist/verdicts.js +4 -2
  150. package/dist/verdicts.js.map +1 -1
  151. package/package.json +1 -1
package/dist/agent.js CHANGED
@@ -1,19 +1,21 @@
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";
17
19
  import { constructSubscriptionId } from "./subscriptions.js";
18
20
  import { AccessWaits } from "./tasks/access.js";
19
21
  import { currentTask, TaskExecution } from "./tasks/incoming.js";
@@ -40,6 +42,7 @@ const noTasks = "This relay doesn't keep tasks";
40
42
  const noSchedules = "This relay doesn't keep schedules";
41
43
  const steered = "Passed your message to the running task, which reads it before its next step.";
42
44
  const noUploads = "This relay doesn't take attachments";
45
+ const noFileArtifacts = "This relay doesn't store files, so tasks can't deliver them";
43
46
  const maxAttachments = 10;
44
47
  const untaskedAttachments = "Only a message about a task, or a reply to one, can carry attachments";
45
48
  const untaskedSteer = "Only a message about a task can steer it";
@@ -87,7 +90,7 @@ const eventOf = ({ eventId, summary = "", eventData, }) => eventId === undefined
87
90
  const watchOf = ({ scheduleId, from, principal, text, skill, trigger, config, input, expiresAt, }) => ({
88
91
  id: scheduleId,
89
92
  from,
90
- ...(principal === undefined ? {} : { principal }),
93
+ principal: resolveChainPrincipal(principal, from),
91
94
  text,
92
95
  skill,
93
96
  trigger,
@@ -96,16 +99,21 @@ const watchOf = ({ scheduleId, from, principal, text, skill, trigger, config, in
96
99
  ...(expiresAt === undefined ? {} : { expiresAt: new Date(expiresAt) }),
97
100
  });
98
101
  const constructOrigin = (requester, taskId) => taskId === undefined ? undefined : { requester, taskId };
99
- 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) => ({
100
103
  from,
101
- ...(principal === undefined ? {} : { principal }),
104
+ principal: resolveChainPrincipal(principal, from),
102
105
  text,
103
106
  ...(skill === undefined ? {} : { skill }),
104
- ...(input === undefined ? {} : { input }),
107
+ input: parsed.input ? parsed.input.value : input,
105
108
  ...(cron === undefined
106
109
  ? {}
107
110
  : { cron: { ...cron, timeZone: cron.timeZone ?? DEFAULT_TIME_ZONE } }),
108
- ...(trigger === undefined ? {} : { trigger }),
111
+ ...(trigger && {
112
+ trigger: {
113
+ name: trigger.name,
114
+ config: parsed.config ? parsed.config.value : trigger.config,
115
+ },
116
+ }),
109
117
  ...(budget === undefined ? {} : { budget }),
110
118
  ...(expiresAt === undefined ? {} : { expiresAt: new Date(expiresAt) }),
111
119
  attachments,
@@ -146,6 +154,11 @@ const ignoreReassigned = (error) => {
146
154
  if (!(error instanceof ReassignedError))
147
155
  throw error;
148
156
  };
157
+ const rejectDeclined = (error) => {
158
+ if (!(error instanceof AgentDeclinedError))
159
+ throw error;
160
+ return reject(error.reason);
161
+ };
149
162
  const unexpected = (reply) => new AgentJamError(`${reply.from} sent an unexpected ${reply.type}`);
150
163
  const constructQuestionOptions = (task, { signal, timeoutMs = Infinity, ...options }) => ({
151
164
  ...options,
@@ -224,6 +237,8 @@ export class Agent {
224
237
  link;
225
238
  connected = Promise.withResolvers();
226
239
  handlers;
240
+ context;
241
+ skills;
227
242
  screen;
228
243
  timeoutMs;
229
244
  files;
@@ -236,8 +251,6 @@ export class Agent {
236
251
  requestedName;
237
252
  sources;
238
253
  vaulted;
239
- inputs;
240
- delegates;
241
254
  unwatch;
242
255
  readiness = new Readiness();
243
256
  accessWaits = new AccessWaits();
@@ -252,7 +265,7 @@ export class Agent {
252
265
  performed = new IdempotencyCache(dedupeWindow);
253
266
  triggers;
254
267
  watches = new TaskWatches((outcomes) => this.resolveWatch(outcomes));
255
- 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 = {}) {
256
269
  this.requestedName = name;
257
270
  const bindSecret = (connection) => constructSecretSource(connection, () => this.credentialChannel(connection.provider));
258
271
  this.sources = new Map(skills.map((skill) => [skill.name, sourcesOf(skill, bindSecret)]));
@@ -272,8 +285,8 @@ export class Agent {
272
285
  }));
273
286
  return bound.includes(true);
274
287
  }));
275
- this.inputs = new Map(skills.flatMap((skill) => skill.input ? [[skill.name, skill.input]] : []));
276
- 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 };
277
290
  this.forward = { ...allForwarded, ...forward };
278
291
  const tools = createNetworkTools(this, {
279
292
  watching: handlers.onWatchResolved !== undefined,
@@ -308,7 +321,7 @@ export class Agent {
308
321
  void this.restartTriggers(this.connection);
309
322
  },
310
323
  onError: (error) => this.orphan(error),
311
- }, { instanceId })
324
+ }, { instanceId, messages: handlers.onMessage !== undefined })
312
325
  .then(async (connection) => {
313
326
  try {
314
327
  assertStored(connection.card, skills);
@@ -390,6 +403,7 @@ export class Agent {
390
403
  * @returns The recipient's reply, with its files downloaded.
391
404
  * @throws {AgentJamError} If the message attaches files or steers without being about a task, or an attachment couldn't upload.
392
405
  * @throws {AgentNotFoundError} If no agent at `to` is connected.
406
+ * @throws {MessagesNotAcceptedError} If the recipient connected without `onMessage`.
393
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.
394
408
  */
395
409
  async send(to, text, { conversationId = crypto.randomUUID(), idempotencyKey = crypto.randomUUID(), taskId = this.findCurrentTask(to)?.id, attachments, steer, ...options } = {}) {
@@ -893,7 +907,7 @@ export class Agent {
893
907
  await Promise.allSettled([
894
908
  this.triggers.stopAll("closing"),
895
909
  ...Array.from(this.incoming.values(), (task) => task.resumable
896
- ? task.abandon(new AgentJamError(reason))
910
+ ? task.handOver(new AgentJamError(reason))
897
911
  : task.fail(new AgentJamError(reason))),
898
912
  ]);
899
913
  const connection = await this.connection;
@@ -1043,10 +1057,16 @@ export class Agent {
1043
1057
  if (steer && this.findSteered(envelope)?.queueMessage(message)) {
1044
1058
  return steered;
1045
1059
  }
1046
- if (!this.handlers.onMessage) {
1047
- 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;
1048
1069
  }
1049
- return this.handlers.onMessage(message, this);
1050
1070
  }
1051
1071
  /** Finds the running task a requester's message about it may steer. */
1052
1072
  findSteered({ from, taskId }) {
@@ -1111,6 +1131,7 @@ export class Agent {
1111
1131
  requester: from,
1112
1132
  id: proposal.id,
1113
1133
  }),
1134
+ recall: (ref) => this.recallTask(ref),
1114
1135
  listHistory: this.listHistoryOf({
1115
1136
  requester: from,
1116
1137
  taskId: proposal.id,
@@ -1131,13 +1152,18 @@ export class Agent {
1131
1152
  cleanup();
1132
1153
  throw error;
1133
1154
  }
1134
- void this.execute(task, cleanup, async (incoming) => {
1135
- await this.readiness.wait(grant, incoming.signal);
1136
- if (!proposal.prepare)
1137
- return this.handlers.onTask?.(incoming, this);
1138
- // WARNING: the relay cancels a task's children once it ends, so a preparation outlives the ones below it.
1139
- await awaitPreparations(preparations);
1140
- });
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
+ }
1141
1167
  return task.settled;
1142
1168
  }
1143
1169
  async judge(proposal) {
@@ -1147,24 +1173,27 @@ export class Agent {
1147
1173
  replyTo: proposal.id,
1148
1174
  };
1149
1175
  try {
1150
- const parsedInput = proposal.prepare
1151
- ? undefined
1152
- : 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
+ });
1153
1186
  if (parsedInput && "problem" in parsedInput) {
1154
- return {
1155
- verdict: {
1156
- ...response,
1157
- type: "task.reject",
1158
- reason: parsedInput.problem,
1159
- },
1160
- attachments: [],
1161
- };
1187
+ return refuse(parsedInput.problem);
1188
+ }
1189
+ if (parsedConfig && "problem" in parsedConfig) {
1190
+ return refuse(parsedConfig.problem);
1162
1191
  }
1163
1192
  const attachments = receiveAttachments(proposal.attachments, this.files, {
1164
1193
  requester: proposal.from,
1165
1194
  taskId: proposal.id,
1166
1195
  });
1167
- const { verdict, preparations } = await this.constructVerdict(proposal, attachments);
1196
+ const { verdict, preparations } = await this.constructVerdict(proposal, attachments, { input: parsedInput, config: parsedConfig });
1168
1197
  return {
1169
1198
  verdict: { ...response, ...verdict },
1170
1199
  attachments,
@@ -1179,9 +1208,9 @@ export class Agent {
1179
1208
  };
1180
1209
  }
1181
1210
  }
1182
- async constructVerdict(proposal, attachments) {
1211
+ async constructVerdict(proposal, attachments, parsed) {
1183
1212
  const { id, from, principal, skill } = proposal;
1184
- const incoming = toProposal(proposal, attachments, this.files);
1213
+ const incoming = toProposal(proposal, attachments, this.files, parsed);
1185
1214
  const verdict = proposal.prepare ? accept() : await this.decide(incoming);
1186
1215
  if (!verdict.accepted) {
1187
1216
  const rejection = {
@@ -1217,12 +1246,16 @@ export class Agent {
1217
1246
  /** Lists the delegates of the proposal's skill, leaving out picked ones while another agent only prepares it. */
1218
1247
  async pickDelegates(proposal, incoming) {
1219
1248
  const { skill, prepare, then } = proposal;
1220
- const delegates = skill === undefined ? [] : this.delegates.get(skill);
1249
+ const delegates = this.findSkill(skill)?.delegates;
1221
1250
  const followUp = then ? [{ agent: then.to, skill: then.skill }] : [];
1222
1251
  if (typeof delegates !== "function") {
1223
1252
  return [...(delegates ?? []), ...followUp];
1224
1253
  }
1225
- 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];
1226
1259
  }
1227
1260
  prepareFor(parent) {
1228
1261
  return async (delegates) => {
@@ -1264,20 +1297,31 @@ export class Agent {
1264
1297
  });
1265
1298
  }
1266
1299
  /**
1267
- * Runs the checks a proposal must pass before it reaches `onProposal`. It rejects every proposal without an `onTask`,
1268
- * and ones that name a skill the agent doesn't advertise or a trigger its skill doesn't declare.
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`.
1269
1303
  *
1270
1304
  * @param proposal The proposal to check.
1271
1305
  * @returns Whether the proposal passes the checks.
1272
1306
  */
1273
1307
  checkProposal(proposal) {
1274
1308
  const { skill, trigger } = proposal;
1275
- if (!this.handlers.onTask) {
1276
- return reject(`${this.name} does not accept tasks`);
1277
- }
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);
1278
1321
  if (skill !== undefined &&
1279
- !this.card.skills.some(({ name }) => name === skill)) {
1280
- 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`);
1281
1325
  }
1282
1326
  if (trigger && !this.triggers.offers(skill, trigger.name)) {
1283
1327
  return reject(`${this.name} has no trigger named "${trigger.name}" for this skill`);
@@ -1286,7 +1330,7 @@ export class Agent {
1286
1330
  }
1287
1331
  /** @internal The agents and skills a skill hands work off to, leaving out ones a function picks per proposal. */
1288
1332
  listDelegates(skill) {
1289
- const delegates = skill === undefined ? [] : this.delegates.get(skill);
1333
+ const delegates = this.findSkill(skill)?.delegates;
1290
1334
  return Array.isArray(delegates) ? delegates : [];
1291
1335
  }
1292
1336
  /** @internal Reports an error that can't reach another agent to `onError`. */
@@ -1297,19 +1341,31 @@ export class Agent {
1297
1341
  const checked = this.checkProposal(proposal);
1298
1342
  if (!checked.accepted)
1299
1343
  return checked;
1300
- const verdict = this.handlers.onProposal
1301
- ? await this.handlers.onProposal(proposal, this)
1302
- : checked;
1344
+ const verdict = await this.consultHandlers(proposal, checked).catch(rejectDeclined);
1303
1345
  if (!verdict.accepted || !this.screen || proposal.from === this.name) {
1304
1346
  return verdict;
1305
1347
  }
1306
1348
  return screenProposal(proposal, this, this.screen);
1307
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
+ }
1308
1364
  async parseSkillInput(skill, input) {
1309
- if (skill === undefined)
1365
+ const schema = this.findSkill(skill)?.input;
1366
+ if (skill === undefined || !schema)
1310
1367
  return undefined;
1311
- const schema = this.inputs.get(skill);
1312
- return schema && parseValue(skill, "input", schema, input);
1368
+ return parseValue(skill, "input", schema, input);
1313
1369
  }
1314
1370
  priceOf(skill, requester) {
1315
1371
  if (requester === this.name)
@@ -1338,6 +1394,7 @@ export class Agent {
1338
1394
  const id = key(from, taskId);
1339
1395
  const { response } = this.performed.remember(id, async () => {
1340
1396
  const { attachments, parsedInput, failure } = await this.receiveTask(recur, { requester: from, taskId });
1397
+ const received = await this.readFiredEvent(recur);
1341
1398
  const task = new TaskExecution({
1342
1399
  id: taskId,
1343
1400
  from,
@@ -1349,7 +1406,7 @@ export class Agent {
1349
1406
  attachments,
1350
1407
  scheduleId,
1351
1408
  run,
1352
- event: eventOf(recur),
1409
+ event: received.event,
1353
1410
  price: this.priceOf(skill, from),
1354
1411
  card: this.findSkillCard(skill),
1355
1412
  isSelf: from === this.name,
@@ -1364,6 +1421,7 @@ export class Agent {
1364
1421
  requester: from,
1365
1422
  id: taskId,
1366
1423
  }),
1424
+ recall: (ref) => this.recallTask(ref),
1367
1425
  listHistory: this.listHistoryOf({ requester: from, taskId }),
1368
1426
  requireAccess: this.requireAccessFor(skill, { requester: from, id: scheduleId, principal: principal ?? from }, taskId),
1369
1427
  });
@@ -1372,14 +1430,39 @@ export class Agent {
1372
1430
  this.performed.release(id);
1373
1431
  };
1374
1432
  this.incoming.set(id, task);
1375
- await this.execute(task, cleanup, async (incoming) => {
1376
- if (failure)
1377
- throw failure.error;
1378
- 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;
1379
1437
  });
1380
1438
  });
1381
1439
  return response;
1382
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
+ }
1383
1466
  /**
1384
1467
  * Runs a task of a resumable skill that the relay moved here from a departed session of this agent, following the
1385
1468
  * tasks it delegated there so their events aren't refused as unknown. A repeat of an attempt already running is ignored.
@@ -1424,15 +1507,15 @@ export class Agent {
1424
1507
  send: this.sendAbout(from, taskId),
1425
1508
  upload: this.uploadArtifact,
1426
1509
  prepare: this.prepareFor(parent),
1510
+ recall: (ref) => this.recallTask(ref),
1427
1511
  listHistory: this.listHistoryOf({ requester: from, taskId }),
1428
1512
  requireAccess: this.requireAccessFor(skill, { ...grant, principal: principal ?? from }, taskId),
1429
1513
  });
1430
1514
  const cleanup = () => this.releaseExecution(id, task, grant);
1431
1515
  this.incoming.set(id, task);
1432
- await this.execute(task, cleanup, async (incoming) => {
1516
+ await this.executeSkill(task, cleanup, () => {
1433
1517
  if (failure)
1434
1518
  throw failure.error;
1435
- return this.handlers.onTask?.(incoming, this);
1436
1519
  });
1437
1520
  }
1438
1521
  /** Receives a task's attachments and parses its input, keeping the first failure for the task's run to throw. */
@@ -1487,6 +1570,35 @@ export class Agent {
1487
1570
  cleanup();
1488
1571
  }
1489
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
+ }
1490
1602
  allSources() {
1491
1603
  const sources = [...this.sources.values()].flatMap((skill) => [
1492
1604
  ...skill.values(),
@@ -2012,7 +2124,9 @@ export class Agent {
2012
2124
  }
2013
2125
  uploadArtifact = async (source, signal) => {
2014
2126
  const connection = await this.connection;
2015
- return connection.upload?.(source, signal);
2127
+ if (!connection.upload)
2128
+ throw new AgentJamError(noFileArtifacts);
2129
+ return connection.upload(source, signal);
2016
2130
  };
2017
2131
  findIncomingTask(requester, taskId) {
2018
2132
  if (taskId === undefined)
@@ -2048,11 +2162,14 @@ export class Agent {
2048
2162
  const connection = await this.connection;
2049
2163
  if (!connection.upload)
2050
2164
  throw new AgentJamError(noUploads);
2051
- const uploads = await Promise.all(sources.map(constructUpload));
2052
- assertAttachmentTotal(uploads);
2165
+ const entries = await Promise.all(sources.map(constructAttachmentEntry));
2166
+ assertAttachmentTotal(entries);
2053
2167
  const upload = connection.upload.bind(connection);
2054
- const ids = await Promise.all(uploads.map((source) => upload(source, signal)));
2055
- 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
+ }));
2056
2173
  }
2057
2174
  }
2058
2175
  /**