@asterism-app/builtin-api 0.26.2 → 0.27.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.
package/docs/agents.md CHANGED
@@ -14,6 +14,8 @@ Sender attribution explains where input came from independently of the Agent tha
14
14
 
15
15
  Keep the body useful as ordinary readable text. For example, a pull-request notification can state the repository, change, author, and URL. The integration understands those facts and should explain them; the receiving Agent's instructions supply its responsibilities. A domain event does not need a private machine payload disguised as a message.
16
16
 
17
+ A resource event can separate the two audiences. Leading YAML frontmatter carries metadata of any shape for the receiving Agent, such as the event kind and the identifiers its tools accept; the Markdown after it is the message people read in the conversation, which hides the frontmatter. Put each fact where its reader needs it rather than repeating identifiers in prose or squeezing the readable summary into metadata. A body may be empty when the following parts already form the message, as when a chat event is followed by the received messages themselves.
18
+
17
19
  Use retained attachments when the message must preserve submitted bytes. Use file references when the message should carry an address for later consumption. Forwarding an address does not mean its content has been read or captured.
18
20
 
19
21
  ## Choose admission and scheduling intentionally
@@ -1,5 +1,6 @@
1
1
  import { nanoid } from "nanoid";
2
- import { SubmitAgentInput, CancelAgent, type AgentMessageSender, type SubmitAgentInputData, type AgentInputPart } from "@asterism-app/builtin-api/contracts";
2
+ import { SubmitAgentInput, CancelAgent, resourceEventText, type AgentMessageSender, type SubmitAgentInputData, type AgentInputPart } from "@asterism-app/builtin-api/contracts";
3
+ import type { JsonObject } from "@asterism-app/sdk/contracts";
3
4
  import { PluginApiError, type ObjectReader, type PluginContext, type ResourceRef, type ResourceActionOptions } from "@asterism-app/sdk/runtime";
4
5
 
5
6
  /** Construct once and retain the complete input for any retry. Delivery mode is independent of source. */
@@ -13,12 +14,15 @@ export function agentMessage(sender: Extract<AgentMessageSender, { kind: "agent"
13
14
  return { submissionId: nanoid(16), mode, parts, sender };
14
15
  }
15
16
 
16
- /** Resource callbacks format facts as readable text and capture the source name when constructing the input. */
17
- export function resourceEvent(source: ObjectReader, text: string, mode: SubmitAgentInputData["mode"]): SubmitAgentInputData {
17
+ /**
18
+ * Resource callbacks format facts as readable Markdown, add identifiers as frontmatter metadata, and capture the source name.
19
+ * For example: resourceEvent(source, { event: "pull_request.opened", number: 128 }, "Ada opened **Fix login** in web", "follow").
20
+ */
21
+ export function resourceEvent(source: ObjectReader, metadata: JsonObject, body: string, mode: SubmitAgentInputData["mode"]): SubmitAgentInputData {
18
22
  const resource = source.snapshot();
19
23
  if (!resource) throw new PluginApiError("not_found", "The event source is unavailable.");
20
24
  return {
21
- submissionId: nanoid(16), mode, parts: [{ kind: "text", text }],
25
+ submissionId: nanoid(16), mode, parts: [{ kind: "text", text: resourceEventText(metadata, body) }],
22
26
  sender: { kind: "event", resource: { ...source.ref }, name: resource.title },
23
27
  };
24
28
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asterism-app/builtin-api",
3
- "version": "0.26.2",
3
+ "version": "0.27.0",
4
4
  "description": "Public domain contracts and extensions for Asterism built-in features",
5
5
  "license": "MIT",
6
6
  "author": "Chien Zhang",
package/src/input.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { modelInputPartSchema, fileReferencePartSchema } from "@asterism-app/sdk/contracts";
2
+ import { modelInputPartSchema, fileReferencePartSchema, type Json, type JsonObject } from "@asterism-app/sdk/contracts";
3
3
 
4
4
  export const agentInputPartSchema = z.union([modelInputPartSchema, fileReferencePartSchema]);
5
5
  export type AgentInputPart = z.infer<typeof agentInputPartSchema>;
@@ -10,6 +10,39 @@ export function inputFileName(part: Exclude<AgentInputPart, { kind: "text" }>):
10
10
  export const agentInputPartsSchema = z.array(agentInputPartSchema).min(1).max(128)
11
11
  .refine(parts => parts.some(part => part.kind !== "text" || part.text.trim().length > 0), "A message requires text or a file.")
12
12
  .refine(parts => parts.flatMap(part => part.kind === "text" ? [part.text] : []).join("\n").length <= 100_000, "The message text exceeds the size limit.");
13
+ /** Strings that YAML reads back as the same string without quotes; anything else is written as JSON, which YAML also accepts. */
14
+ const plainScalar = /^[A-Za-z_][\w./@-]*$/u;
15
+ const reservedScalar = /^(?:true|false|null|yes|no|on|off|y|n)$/iu;
16
+ const frontmatterKey = /^[A-Za-z_][\w.-]*$/u;
17
+ function scalar(value: Json): string {
18
+ return typeof value === "string" && plainScalar.test(value) && !reservedScalar.test(value) ? value : JSON.stringify(value);
19
+ }
20
+ /**
21
+ * Resource event text: YAML frontmatter with structured metadata for the receiving Agent, then the Markdown body people read.
22
+ * Each metadata value occupies one line, so no metadata line can close the block. Omitted metadata produces the body alone.
23
+ */
24
+ export function resourceEventText(metadata: JsonObject, body: string): string {
25
+ const entries = Object.entries(metadata).filter(([, value]) => value !== undefined);
26
+ if (!entries.length) return body;
27
+ for (const [key] of entries) if (!frontmatterKey.test(key)) throw new Error(`Invalid event metadata key: ${key}`);
28
+ return ["---", ...entries.map(([key, value]) => `${key}: ${scalar(value)}`), "---", "", body].join("\n");
29
+ }
30
+ /** Separates leading frontmatter from the body; text without a complete leading block is all body. */
31
+ export function splitResourceEventText(text: string): { metadata: string | null; body: string } {
32
+ if (!text.startsWith("---\n")) return { metadata: null, body: text };
33
+ const end = text.indexOf("\n---", 3);
34
+ if (end < 0 || (text.length > end + 4 && text[end + 4] !== "\n")) return { metadata: null, body: text };
35
+ return { metadata: text.slice(4, end), body: text.slice(end + 5).replace(/^\n/u, "") };
36
+ }
37
+ /** Parts shown to people: an event's leading frontmatter is model-facing metadata and is omitted from display. */
38
+ export function displayInputParts(message: { sender: { kind: string }; parts: readonly AgentInputPart[] }): readonly AgentInputPart[] {
39
+ if (message.sender.kind !== "event") return message.parts;
40
+ return message.parts.flatMap((part, index) => {
41
+ if (index !== 0 || part.kind !== "text") return [part];
42
+ const { body } = splitResourceEventText(part.text);
43
+ return body.trim() ? [{ ...part, text: body }] : [];
44
+ });
45
+ }
13
46
  export function inputSummary(parts: readonly AgentInputPart[]): string {
14
47
  return parts.flatMap(part => part.kind === "text" ? [part.text] : []).join("\n").trim()
15
48
  || parts.flatMap(part => part.kind === "text" ? [] : [inputFileName(part)]).join(", ");