@asterism-app/builtin-api 0.20.1 → 0.22.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 +70 -15
- package/examples/agent-input.ts +26 -15
- package/examples/agent-observation.ts +45 -0
- package/package.json +1 -1
- package/src/agent-events.ts +30 -0
- package/src/agent.ts +3 -3
- package/src/configuration.ts +24 -10
- package/src/contracts.ts +1 -0
- package/src/input.ts +14 -7
- package/src/messaging.ts +19 -8
- package/src/records.ts +3 -2
- package/src/search.ts +1 -1
- package/src/text.ts +15 -10
- package/src/tools.ts +23 -2
package/docs/agents.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Extend built-in agents
|
|
2
2
|
|
|
3
|
-
The built-in public API lets plugins
|
|
3
|
+
The built-in public API lets plugins submit messages to existing Agents and extend their preparation and presentation. The contributing plugin owns its integration and business state. Builtin owns input admission, conversation history, and Agent execution.
|
|
4
4
|
|
|
5
5
|
## Declare the dependency
|
|
6
6
|
|
|
@@ -8,40 +8,95 @@ Declare `@asterism-app/builtin-api` and `@asterism-app/sdk` in `peerDependencies
|
|
|
8
8
|
|
|
9
9
|
Examples are TypeScript and TSX fragments for a plugin's backend or renderer. They use public packages; install additional libraries imported by the chosen example, such as Nano ID for submission identities, in the plugin project. A plugin still supplies its manifest and composition entry points.
|
|
10
10
|
|
|
11
|
-
##
|
|
11
|
+
## Messages and their sources
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
An Agent input is a message with ordered text, stored-file, or file-reference parts and a structured sender. All messages use the same submission action, history record, queue, and body renderer. The sender has three variants:
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
| Source | Meaning | Attribution |
|
|
16
|
+
| --- | --- | --- |
|
|
17
|
+
| `user` | Input from the user | No additional sender fields; this is the default when sender is omitted |
|
|
18
|
+
| `agent` | Communication from another Agent | Communication resource reference and Agent name, with optional Mesh channel addressing |
|
|
19
|
+
| `event` | Facts reported by a resource | Emitting resource reference and its name when the message is constructed |
|
|
16
20
|
|
|
17
|
-
|
|
21
|
+
Plugins supply sender attribution from their integration context. An Agent's Send tool obtains it from the bound caller. The saved input record belongs to the receiving Agent; its sender identifies the origin independently. Attribution itself grants no access to the source resource or reply route.
|
|
18
22
|
|
|
19
|
-
|
|
23
|
+
Keep the body useful as ordinary readable text. A resource reporting a pull request can include its repository, number, title, author, commit, and URL. The Agent's configured instructions supply its responsibilities. Event type names and domain facts belong in the body; no separate event payload schema or renderer is required.
|
|
24
|
+
|
|
25
|
+
Builtin preserves the submitted body and sender in history. Model projection wraps Agent and event messages in escaped source envelopes. The UI renders the original body with source identification: Agent messages use the Agent name, while event messages use the resource name, event icon, and blue surface. Names remain those recorded with the message even if the source is later renamed or removed.
|
|
26
|
+
|
|
27
|
+
## Submit and schedule messages
|
|
28
|
+
|
|
29
|
+
Obtain the target session executor from the plugin context and invoke `SubmitAgentInput` with the Agent resource reference. Each submission includes a 16-character Nano ID, parts, a delivery mode, and its sender. External callbacks can invoke the same action without a model tool call. Use a resource's attachment lifetime for an object-owned connection and pass its signal into ongoing submissions.
|
|
30
|
+
|
|
31
|
+
An idle Agent records accepted input and starts execution. When the Agent is running, accepted input enters its persistent drafts collection. Delivery mode is independent of sender:
|
|
32
|
+
|
|
33
|
+
| Mode | Delivery while running |
|
|
34
|
+
| --- | --- |
|
|
35
|
+
| `steer` | At the next request boundary, after the current response and tool batch |
|
|
36
|
+
| `follow` | At a turn boundary, together with other pending inputs eligible for the next turn |
|
|
37
|
+
|
|
38
|
+
For example, a new independent review can use `follow`, while updated facts for the current task can use `steer`. A turn may consume a batch of messages; submission does not promise a separate turn for each message. Successful submission means acceptance, not completion of the Agent's response.
|
|
39
|
+
|
|
40
|
+
Construct the complete input once and retain it for retries, including the submission ID, sender name, mode, and body. An already accepted submission ID is ignored rather than accepted again. A new message needs a new ID.
|
|
41
|
+
|
|
42
|
+
Stored-file parts (`kind: "file"`) supply immutable content to the model and require the appropriate content reader when forwarded through an action. File-reference parts (`kind: "file-reference"`) carry a `FileRef` in `ref`, with optional `filename` and `mediaType`. They pass through actions, events, drafts, and history as ordinary JSON. Model projection presents their addresses as text; receiving or resending one does not read its bytes or require a content reader.
|
|
43
|
+
|
|
44
|
+
Cancellation of a submission is separate from cancellation of the Agent's independent execution, which has its own public action. Stopping an Agent preserves pending drafts. Restoring drafts on application startup does not automatically send them.
|
|
45
|
+
|
|
46
|
+
## Creation and input
|
|
47
|
+
|
|
48
|
+
Agent creation and message submission are independent operations. Creating an Agent establishes an empty resource with its configuration; it does not require a message or start execution. Plugins can create the resource and submit ordinary input later.
|
|
49
|
+
|
|
50
|
+
The builtin Home entry combines session creation, Agent creation, and acceptance of a user message in one transaction. It prepares the input before committing the new session, so rejected input leaves no empty session behind. The message uses the ordinary input contract, preparers, and acceptance notification. There is no separate first-message event or plugin lifecycle stage.
|
|
51
|
+
|
|
52
|
+
Creation-related work belongs to resource creation or observation of the resulting creation fact, independently of incoming messages. In a session observer's `committed` callback, use the SDK's `ResourceCreated.decodeAll(records)` and select known entries whose `data.type` equals `Agent.kind`. The associated Agent ID is `data.id`; the host-created record's source is null. A creation observer sees the committed state; Home's creation and input may already be present together. Observation is not a blocking initialization hook. Resource-presence notifications and attachment lifetimes describe entry into the current resource set, including reconstruction, rather than only new creation.
|
|
53
|
+
|
|
54
|
+
## Resolve recipients
|
|
55
|
+
|
|
56
|
+
The publishing plugin selects recipients and submits messages explicitly. A bridge resource can read a fresh session snapshot for resources directly linked to itself, select Agent references, and invoke their input action. Each link makes a resource available to its receiver; the reverse relationship is independent. Reading a link does not expose another plugin's private state.
|
|
57
|
+
|
|
58
|
+
The SDK event bus delivers typed transient notifications to subscribers. Publishing there does not submit an Agent message. A callback can translate a notification into a readable event message and submit it to selected Agents. This translation belongs to the integration that understands the notification.
|
|
20
59
|
|
|
21
60
|
## Implement communication resources
|
|
22
61
|
|
|
23
|
-
Use the public Send, Peek, GetProfile, and SetProfile tool declarations when a resource provides those operations. Each resource implementation owns its addressing schema and resolves targets within its authorized scope. A shared tool name does not grant direct access to the addressed
|
|
62
|
+
Use the public Send, Peek, GetProfile, and SetProfile tool declarations when a resource provides those operations. Each resource implementation owns its addressing schema and resolves targets within its authorized scope. A shared tool name does not grant direct access to the addressed Agent or its linked resources.
|
|
24
63
|
|
|
25
|
-
|
|
64
|
+
Send accepts ordered `parts` containing text and file references. Each file-reference part carries a `FileRef` in `ref`; its optional `filename` specifies the name used for delivery. Agent and Mesh implementations forward these parts into Agent input without resolving the references. A consuming implementation can stream a referenced file through `plugin.files.open(ref, { signal })`. The original source resource remains in the reference across sessions and intermediate senders. The consuming operation determines how to use the bytes; support for references is explicit in each operation's contract.
|
|
26
65
|
|
|
27
|
-
|
|
66
|
+
For cross-session messaging, obtain the target session executor and submit through the same Agent input action. The public Agent service supplies an Agent's configured type and investigates its saved records without exposing private Agent state. Investigation captures a fixed record snapshot and does not start a turn on the target. Forward cancellation and investigation progress to the caller.
|
|
28
67
|
|
|
29
|
-
Communication resources own their member directory and task descriptions. Resolve
|
|
68
|
+
Mesh messages retain their internal sender attribution in history. Model projection uses the channel name, Agent name, and numeric disambiguator; a sender not exposed to the channel is marked as not visible. Communication resources own their member directory and task descriptions. Resolve targets against the request's captured access scope. Read current task descriptions when handling an operation; identity resolution and mutable profile text have separate lifetimes.
|
|
30
69
|
|
|
31
70
|
## Prepare incoming input
|
|
32
71
|
|
|
33
|
-
An external preparer can inspect, replace, or reject
|
|
72
|
+
An external preparer can inspect, replace, or reject any of the three message sources using the original built-in action contract. Its replacement supplies raw action input that will be parsed again. Preparation applies to idle input, queued steering and follow-ups, and Home's initial input. It runs before acceptance, including on retries, so it is not an acceptance notification. Preparation has read capabilities and does not commit session mutations.
|
|
73
|
+
|
|
74
|
+
Keep a preparer's scope tied to its business purpose. It does not replace the Agent implementation or acquire a private Agent executor.
|
|
75
|
+
|
|
76
|
+
## Observe input and turn boundaries
|
|
77
|
+
|
|
78
|
+
Input preparation, acceptance, and delivery are separate observation points. Use a preparer to modify or reject a submission. Subscribe to `AgentInputAccepted` to react after a new input commits. Its payload contains the final prepared `input`, including `submissionId`, and `queued`, which reports whether it entered drafts instead of being delivered immediately. Rejected inputs and retries of accepted submissions produce no new acceptance event. Home publishes acceptance after its complete session-creation transaction succeeds.
|
|
79
|
+
|
|
80
|
+
Saving a held draft or changing an existing draft's mode is a draft-state operation, not a new input submission. These operations do not emit acceptance events; record observers still see the draft if it is delivered.
|
|
81
|
+
|
|
82
|
+
Observe `AgentInputMessage` through `SessionObserver.committed` to see actual delivery to conversation history. Queued messages produce this record when consumed; idle inputs produce it during acceptance. Steering records do not start a new turn. These records and acceptance events use separate delivery mechanisms; an idle input's record is committed before its acceptance event is published. Acceptance does not guarantee that a queued message will reach a model request: pending drafts remain editable and can be discarded.
|
|
83
|
+
|
|
84
|
+
Subscribe to `AgentTurnEnded` for execution boundaries. Every ending carries `reason` and `settled`. A normal turn followed by another queued batch reports `settled: false`; the last turn reports `settled: true` after the loop stops consuming. Failure and cancellation are reported with their own reasons rather than as successful completion. Steering joins the current turn and does not produce an ending by itself.
|
|
85
|
+
|
|
86
|
+
The event's `inputId` identifies the turn-opening input record, and `position.nodeId` identifies its ending history position before any next-turn inputs. `inputId` can be null when execution has no recorded turn input. By the time a handler runs, the live session may contain later records; use these identities to locate the reported work instead of assuming the current tip is that ending. A stopped turn can be resumed explicitly and emit another ending for the same input. The event does not seal history or promise that the Agent will remain idle.
|
|
87
|
+
|
|
88
|
+
Both events are transient occurrence notifications on `plugin.ipc.events`, with the receiving Agent as their resource source. Subscribe for all Agents or filter by session and resource identity, and bind subscriptions to the plugin lifetime. A plugin does not need its own resource to subscribe. Handlers run asynchronously and do not participate in input admission or turn scheduling. `settled` describes the consuming loop, while host task cleanup may still be tracked independently. Events are not replayed after restart.
|
|
34
89
|
|
|
35
|
-
|
|
90
|
+
`SessionObserver.completed` concerns finalized operation records; it is not a turn-end callback. Resource status events describe coarse workbench status. Use the Agent's domain notifications when input identity, turn position, or the distinction between turn end and loop end matters.
|
|
36
91
|
|
|
37
92
|
## Prepare model requests
|
|
38
93
|
|
|
39
94
|
The host collects skill packages and instruction blocks with their registering plugin's provenance. Builtin selects its effective skills and builds structured instruction blocks for each request. User skills override plugin skills, which override builtin skills.
|
|
40
95
|
|
|
41
|
-
Declare an Agent preparer to filter skills or remove, change, and append instruction blocks. Preparers run synchronously in plugin initialization order. Each request captures the catalog and preparer set before awaiting linked context, then uses the prepared result for its prompt
|
|
96
|
+
Declare an Agent preparer to filter skills or remove, change, and append instruction blocks. Preparers run synchronously in plugin initialization order. Each request captures the catalog and preparer set before awaiting linked context, then uses the prepared result for its prompt. `skill_read` resolves names independently through the current flattened catalog. Removing a skill from the prompt does not restrict reading it; a catalog refresh affects later reads and model requests.
|
|
42
97
|
|
|
43
98
|
## Extend presentation
|
|
44
99
|
|
|
45
|
-
Register
|
|
100
|
+
Register Agent UI extensions during frontend preparation and bind registration to its cancellation signal. Extensions can present controls, supplemental content, overlays, or modal interaction using the built-in presentation components. Message sources already share the built-in body renderer and source presentation.
|
|
46
101
|
|
|
47
|
-
The plugin supplies business state for the associated
|
|
102
|
+
The plugin supplies business state for the associated Agent and callbacks for user actions. A component becoming invisible does not complete or cancel waiting backend work. Remounting should reread current state, and each submission entry owns its pending and error state.
|
package/examples/agent-input.ts
CHANGED
|
@@ -1,24 +1,35 @@
|
|
|
1
1
|
import { nanoid } from "nanoid";
|
|
2
|
-
import { SubmitAgentInput, CancelAgent, type AgentMessageSender } from "@asterism-app/builtin-api/contracts";
|
|
3
|
-
import type
|
|
4
|
-
import type { PluginContext, ResourceRef, ResourceActionOptions } from "@asterism-app/sdk/runtime";
|
|
2
|
+
import { SubmitAgentInput, CancelAgent, type AgentMessageSender, type SubmitAgentInputData, type AgentInputPart } from "@asterism-app/builtin-api/contracts";
|
|
3
|
+
import { PluginApiError, type ObjectReader, type PluginContext, type ResourceRef, type ResourceActionOptions } from "@asterism-app/sdk/runtime";
|
|
5
4
|
|
|
6
|
-
/**
|
|
7
|
-
export
|
|
8
|
-
|
|
9
|
-
submissionId: nanoid(16), mode: "steer", parts,
|
|
10
|
-
}, options);
|
|
5
|
+
/** Construct once and retain the complete input for any retry. Delivery mode is independent of source. */
|
|
6
|
+
export function userMessage(parts: AgentInputPart[], mode: SubmitAgentInputData["mode"]): SubmitAgentInputData {
|
|
7
|
+
return { submissionId: nanoid(16), mode, parts, sender: { kind: "user" } };
|
|
11
8
|
}
|
|
12
9
|
|
|
13
|
-
/** Relay adapters
|
|
14
|
-
export
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
submissionId: nanoid(16), mode: "steer", sender, parts,
|
|
18
|
-
}, options);
|
|
10
|
+
/** Relay adapters supply the communication resource and the Agent's name on that resource. */
|
|
11
|
+
export function agentMessage(sender: Extract<AgentMessageSender, { kind: "agent" }>,
|
|
12
|
+
parts: AgentInputPart[], mode: SubmitAgentInputData["mode"]): SubmitAgentInputData {
|
|
13
|
+
return { submissionId: nanoid(16), mode, parts, sender };
|
|
19
14
|
}
|
|
20
15
|
|
|
21
|
-
/**
|
|
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 {
|
|
18
|
+
const resource = source.snapshot();
|
|
19
|
+
if (!resource) throw new PluginApiError("not_found", "The event source is unavailable.");
|
|
20
|
+
return {
|
|
21
|
+
submissionId: nanoid(16), mode, parts: [{ kind: "text", text }],
|
|
22
|
+
sender: { kind: "event", resource: { ...source.ref }, name: resource.title },
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** All three sources use this action. Resolution confirms acceptance; the Agent executes independently. */
|
|
27
|
+
export async function submitMessage(plugin: PluginContext, agent: ResourceRef, input: SubmitAgentInputData,
|
|
28
|
+
options?: ResourceActionOptions) {
|
|
29
|
+
await plugin.session(agent.sessionId).invoke(SubmitAgentInput, agent, input, options);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Cancelling submission and cancelling the Agent's independent execution are separate operations. */
|
|
22
33
|
export async function stopAgent(plugin: PluginContext, agent: ResourceRef) {
|
|
23
34
|
await plugin.session(agent.sessionId).invoke(CancelAgent, agent, {});
|
|
24
35
|
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Agent, AgentInputAccepted, AgentInputMessage, AgentTurnEnded } from "@asterism-app/builtin-api/contracts";
|
|
2
|
+
import { pluginNamespace, ResourceCreated } from "@asterism-app/sdk/contracts";
|
|
3
|
+
import { defineModule, definePlugin } from "@asterism-app/sdk/runtime";
|
|
4
|
+
|
|
5
|
+
/** A plugin can observe Agents without declaring a resource of its own. */
|
|
6
|
+
export default definePlugin({
|
|
7
|
+
namespace: pluginNamespace("example.agent-observation"),
|
|
8
|
+
modules: [defineModule(plugin => {
|
|
9
|
+
const options = { source: { resourceKind: Agent.kind }, signal: plugin.lifetime.signal };
|
|
10
|
+
plugin.ipc.events.subscribe(AgentInputAccepted, options, ({ source, data }) => {
|
|
11
|
+
// The payload is the final prepared input, accepted once for this submission identity.
|
|
12
|
+
plugin.log.info(`Agent ${source!.resource!.id} accepted ${data.input.submissionId}; queued=${data.queued}.`);
|
|
13
|
+
});
|
|
14
|
+
plugin.ipc.events.subscribe(AgentTurnEnded, options, ({ source, data }) => {
|
|
15
|
+
plugin.log.info(`Agent ${source!.resource!.id} ended turn ${data.inputId}: ${data.reason}; settled=${data.settled}.`);
|
|
16
|
+
if (data.settled) {
|
|
17
|
+
// position identifies this ending even if another execution has started by the time this callback runs.
|
|
18
|
+
plugin.log.info(`Execution ended at history position ${data.position.nodeId}.`);
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
return {
|
|
22
|
+
observers: [{
|
|
23
|
+
id: "agent-records",
|
|
24
|
+
committed({ records }) {
|
|
25
|
+
for (const created of ResourceCreated.decodeAll(records)) {
|
|
26
|
+
if (created.status === "unknown") {
|
|
27
|
+
plugin.log.error(`Cannot decode resource creation record ${created.record.id}.`);
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (created.data.type === Agent.kind)
|
|
31
|
+
plugin.log.info(`Agent ${created.data.id} was created as ${created.data.title}.`);
|
|
32
|
+
}
|
|
33
|
+
for (const message of AgentInputMessage.decodeAll(records)) {
|
|
34
|
+
if (message.status === "unknown") {
|
|
35
|
+
plugin.log.error(`Cannot decode Agent input record ${message.record.id}.`);
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
// This record is now part of model context. Steering is delivered with startsTurn=false.
|
|
39
|
+
plugin.log.info(`Agent ${message.record.source!.resource!.id} received ${message.data.sender.kind} input ${message.record.id}; startsTurn=${message.data.startsTurn}.`);
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
}],
|
|
43
|
+
};
|
|
44
|
+
})],
|
|
45
|
+
});
|
package/package.json
CHANGED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { defineEvent } from "@asterism-app/sdk/contracts";
|
|
3
|
+
import { builtin } from "./identity.ts";
|
|
4
|
+
import { SubmitAgentInput } from "./agent.ts";
|
|
5
|
+
|
|
6
|
+
/** Published by the receiving Agent after a new submission commits, including queued inputs. */
|
|
7
|
+
export const AgentInputAccepted = defineEvent(builtin.name("agent.input-accepted"), {
|
|
8
|
+
schema: z.strictObject({
|
|
9
|
+
input: SubmitAgentInput.schema,
|
|
10
|
+
queued: z.boolean(),
|
|
11
|
+
}),
|
|
12
|
+
source: "resource",
|
|
13
|
+
semantics: { kind: "occurrence" },
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
/** An execution boundary, not an immutable seal: explicit continuation can resume an interrupted turn. */
|
|
17
|
+
export const AgentTurnEnded = defineEvent(builtin.name("agent.turn-ended"), {
|
|
18
|
+
schema: z.strictObject({
|
|
19
|
+
/** The turn-opening input record, or null when execution has no recorded turn input. */
|
|
20
|
+
inputId: z.string().min(1).nullable(),
|
|
21
|
+
/** Last history position before any following turn's inputs were delivered. */
|
|
22
|
+
position: z.strictObject({ nodeId: z.string().min(1).nullable() }),
|
|
23
|
+
reason: z.enum(["completed", "failed", "cancelled", "limited"]),
|
|
24
|
+
/** This execution loop stopped consuming inputs; later submissions can start another loop. */
|
|
25
|
+
settled: z.boolean(),
|
|
26
|
+
}),
|
|
27
|
+
source: "resource",
|
|
28
|
+
semantics: { kind: "occurrence" },
|
|
29
|
+
});
|
|
30
|
+
export type AgentTurnEndReason = z.infer<typeof AgentTurnEnded.schema>["reason"];
|
package/src/agent.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { defineCreation, defineAction, defineCall } from "@asterism-app/sdk/contracts";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { builtin } from "./identity.ts";
|
|
4
|
-
import {
|
|
4
|
+
import { agentInputPartsSchema } from "./input.ts";
|
|
5
5
|
import { agentSelectionSchema } from "./configuration.ts";
|
|
6
6
|
import { agentMessageSenderSchema } from "./messaging.ts";
|
|
7
7
|
|
|
@@ -14,7 +14,7 @@ export const agentInputModeSchema = z.enum(["steer", "follow"]);
|
|
|
14
14
|
/** Submissions and drafts share a 16-character Nano ID identity. */
|
|
15
15
|
export const submissionIdSchema = z.string().regex(/^[A-Za-z0-9_-]{16}$/u);
|
|
16
16
|
export const StartAgentSession = defineCall(builtin.name("session.start"), {
|
|
17
|
-
scope: "plugin", input: z.strictObject({ submissionId: submissionIdSchema, selection: agentSelectionSchema, parts:
|
|
17
|
+
scope: "plugin", input: z.strictObject({ submissionId: submissionIdSchema, selection: agentSelectionSchema, parts: agentInputPartsSchema }),
|
|
18
18
|
output: z.strictObject({ sessionId: z.string().min(1) }),
|
|
19
19
|
});
|
|
20
20
|
/** title is optional; when omitted, the creation entry point generates a random display name. */
|
|
@@ -27,7 +27,7 @@ export const CreateAgent = defineCreation(Agent, { id: builtin.name("agent.creat
|
|
|
27
27
|
export const SubmitAgentInput = defineAction(Agent, {
|
|
28
28
|
id: builtin.name("agent.submit"),
|
|
29
29
|
schema: z.strictObject({
|
|
30
|
-
submissionId: submissionIdSchema, parts:
|
|
30
|
+
submissionId: submissionIdSchema, parts: agentInputPartsSchema, mode: agentInputModeSchema,
|
|
31
31
|
sender: agentMessageSenderSchema.default({ kind: "user" }),
|
|
32
32
|
}),
|
|
33
33
|
});
|
package/src/configuration.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { modelExpressionSchema, thinkingSchema } from "@asterism-app/sdk/contracts";
|
|
3
|
-
const id = z.string().min(1).max(160);
|
|
4
3
|
/** Configurations use readable slugs for identification by both users and models. */
|
|
5
4
|
export const configurationIdSchema = z.string().trim().min(1).max(160).regex(/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/u, "Use lowercase letters, digits, hyphens or underscores.");
|
|
6
5
|
export const modelRoleInputSchema = z.strictObject({
|
|
@@ -10,23 +9,38 @@ export const modelRoleSchema = modelRoleInputSchema.extend({ id: configurationId
|
|
|
10
9
|
export const modelRoleOverridesSchema = modelRoleInputSchema.partial();
|
|
11
10
|
export type ModelRole = z.infer<typeof modelRoleSchema>;
|
|
12
11
|
export type ModelRoleOverrides = z.infer<typeof modelRoleOverridesSchema>;
|
|
13
|
-
|
|
12
|
+
/** Execution limits applied to subagent runs; workbench Agents have no budget. */
|
|
13
|
+
export const agentBudgetSchema = z.strictObject({
|
|
14
|
+
maxRequests: z.number().int().positive(),
|
|
15
|
+
maxDurationSeconds: z.number().int().positive().max(2147483),
|
|
16
|
+
});
|
|
17
|
+
export type AgentBudget = z.infer<typeof agentBudgetSchema>;
|
|
18
|
+
const subagentConfigurationSchema = z.strictObject({
|
|
19
|
+
instructions: z.string().max(100_000),
|
|
20
|
+
budget: agentBudgetSchema,
|
|
21
|
+
});
|
|
22
|
+
const resourceTypesSchema = z.array(z.string().trim().min(1).max(160)).max(200).nullable();
|
|
14
23
|
const agentFieldsSchema = z.strictObject({
|
|
15
24
|
enabled: z.boolean(), description: z.string().max(20_000), systemPrompt: z.string().max(100_000),
|
|
16
|
-
modelRole: configurationIdSchema.nullable(),
|
|
17
|
-
|
|
18
|
-
|
|
25
|
+
modelRole: configurationIdSchema.nullable(), examples: z.array(z.string().max(4_000)).max(50),
|
|
26
|
+
subagent: subagentConfigurationSchema,
|
|
27
|
+
resources: resourceTypesSchema,
|
|
28
|
+
excludeResources: resourceTypesSchema,
|
|
29
|
+
delegates: z.array(configurationIdSchema).max(200).nullable(),
|
|
19
30
|
});
|
|
20
|
-
export const agentInputSchema = agentFieldsSchema.refine(value => value.
|
|
31
|
+
export const agentInputSchema = agentFieldsSchema.refine(value => value.resources === null || value.excludeResources === null,
|
|
32
|
+
"Resource allowlist and denylist are mutually exclusive.");
|
|
21
33
|
export const agentSchema = agentInputSchema.safeExtend({ id: configurationIdSchema, builtin: z.boolean() });
|
|
22
|
-
// Blank text removes the override on save; false, null, and empty lists retain their respective business meanings.
|
|
23
|
-
export const agentOverridesSchema = agentFieldsSchema.
|
|
24
|
-
.
|
|
34
|
+
// Blank text removes the override on save; false, null, and empty lists retain their respective business meanings. Subagent fields override individually.
|
|
35
|
+
export const agentOverridesSchema = agentFieldsSchema.extend({
|
|
36
|
+
subagent: subagentConfigurationSchema.extend({ budget: agentBudgetSchema.partial() }).partial(),
|
|
37
|
+
}).partial().refine(value => value.resources == null || value.excludeResources == null,
|
|
38
|
+
"Resource allowlist and denylist are mutually exclusive.");
|
|
25
39
|
|
|
26
40
|
export type AgentConfiguration = z.infer<typeof agentSchema>;
|
|
27
41
|
export type AgentOverrides = z.infer<typeof agentOverridesSchema>;
|
|
28
42
|
export const agentSelectionSchema = z.strictObject({
|
|
29
|
-
agent: configurationIdSchema.describe("ID of the configuration supplying this Agent's instructions and
|
|
43
|
+
agent: configurationIdSchema.describe("ID of the configuration supplying this Agent's instructions and model role."),
|
|
30
44
|
model: modelExpressionSchema.nullable().describe("Model for this Agent as provider/model. Null uses the model resolved from its configuration."),
|
|
31
45
|
thinking: thinkingSchema.nullable().describe("Thinking level for this Agent. Null uses the default resolved from its configuration."),
|
|
32
46
|
}).describe("The Agent's base configuration and per-instance model settings.");
|
package/src/contracts.ts
CHANGED
package/src/input.ts
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { modelInputPartSchema, fileReferencePartSchema } from "@asterism-app/sdk/contracts";
|
|
2
3
|
|
|
3
|
-
|
|
4
|
-
export
|
|
5
|
-
|
|
6
|
-
.
|
|
7
|
-
|
|
8
|
-
|
|
4
|
+
export const agentInputPartSchema = z.union([modelInputPartSchema, fileReferencePartSchema]);
|
|
5
|
+
export type AgentInputPart = z.infer<typeof agentInputPartSchema>;
|
|
6
|
+
export function inputFileName(part: Exclude<AgentInputPart, { kind: "text" }>): string {
|
|
7
|
+
return part.filename ?? (part.kind === "file" ? part.mediaType : part.mediaType ?? part.ref.source.id);
|
|
8
|
+
}
|
|
9
|
+
/** Shared body limits for one Agent input message, independent of its sender or delivery mode. */
|
|
10
|
+
export const agentInputPartsSchema = z.array(agentInputPartSchema).min(1).max(128)
|
|
11
|
+
.refine(parts => parts.some(part => part.kind !== "text" || part.text.trim().length > 0), "A message requires text or a file.")
|
|
12
|
+
.refine(parts => parts.flatMap(part => part.kind === "text" ? [part.text] : []).join("\n").length <= 100_000, "The message text exceeds the size limit.");
|
|
13
|
+
export function inputSummary(parts: readonly AgentInputPart[]): string {
|
|
14
|
+
return parts.flatMap(part => part.kind === "text" ? [part.text] : []).join("\n").trim()
|
|
15
|
+
|| parts.flatMap(part => part.kind === "text" ? [] : [inputFileName(part)]).join(", ");
|
|
9
16
|
}
|
package/src/messaging.ts
CHANGED
|
@@ -1,35 +1,46 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { defineTool } from "@asterism-app/sdk/contracts";
|
|
2
|
+
import { defineTool, fileReferencePartSchema } from "@asterism-app/sdk/contracts";
|
|
3
3
|
import { builtin } from "./identity.ts";
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
const messageResourceSchema = z.strictObject({ sessionId: z.string().min(1), id: z.string().min(1), kind: z.string().min(1) });
|
|
6
|
+
|
|
7
|
+
/** Agent and event messages retain the source resource and sender name captured with the input; plugins format event facts as message text. */
|
|
6
8
|
export const agentMessageSenderSchema = z.discriminatedUnion("kind", [
|
|
7
9
|
z.strictObject({ kind: z.literal("user") }),
|
|
8
10
|
z.strictObject({
|
|
9
11
|
kind: z.literal("agent"),
|
|
10
|
-
resource:
|
|
12
|
+
resource: messageResourceSchema,
|
|
11
13
|
name: z.string().min(1),
|
|
12
14
|
mesh: z.strictObject({
|
|
13
15
|
channel: z.string().min(1),
|
|
14
16
|
id: z.number().int().nonnegative().nullable(),
|
|
15
17
|
}).optional().describe("Mesh channel name and sender's numeric name disambiguator. Null means the sender is not exposed to the channel."),
|
|
16
18
|
}),
|
|
19
|
+
z.strictObject({
|
|
20
|
+
kind: z.literal("event"),
|
|
21
|
+
resource: messageResourceSchema,
|
|
22
|
+
name: z.string().min(1),
|
|
23
|
+
}),
|
|
17
24
|
]);
|
|
18
25
|
export type AgentMessageSender = z.infer<typeof agentMessageSenderSchema>;
|
|
19
26
|
|
|
20
27
|
/** The host matches resource types; target is declared by each resource implementation. */
|
|
21
28
|
export const Send = defineTool({
|
|
22
29
|
id: builtin.name("tool.send"), name: "send",
|
|
23
|
-
description: "Send
|
|
30
|
+
description: "Send text and file references through a linked resource.",
|
|
24
31
|
guidelines: [
|
|
25
32
|
"resource_id selects the messaging resource. Its target schema describes recipient selection.",
|
|
26
33
|
"The runtime supplies the sender's resource address and Agent name.",
|
|
27
|
-
"
|
|
28
|
-
"
|
|
34
|
+
"A file-reference part carries a FileRef in its ref field. The optional filename specifies the name used for delivery.",
|
|
35
|
+
"Referenced content is resolved by the consuming implementation.",
|
|
29
36
|
],
|
|
30
37
|
argsSchema: z.strictObject({
|
|
31
|
-
|
|
32
|
-
.
|
|
38
|
+
parts: z.array(z.union([
|
|
39
|
+
z.strictObject({ kind: z.literal("text"), text: z.string() }),
|
|
40
|
+
fileReferencePartSchema,
|
|
41
|
+
])).min(1).max(128)
|
|
42
|
+
.refine(parts => parts.some(part => part.kind !== "text" || part.text.trim().length > 0), "A message requires text or a file reference.")
|
|
43
|
+
.describe("Ordered text and file references. References identify content provided by their original source resources."),
|
|
33
44
|
}).describe("The message to send."),
|
|
34
45
|
});
|
|
35
46
|
|
package/src/records.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { defineRecord, modelBlockSchema, modelCompletionSchema
|
|
2
|
+
import { defineRecord, modelBlockSchema, modelCompletionSchema } from "@asterism-app/sdk/contracts";
|
|
3
3
|
import { builtin } from "./identity.ts";
|
|
4
4
|
import { agentMessageSenderSchema } from "./messaging.ts";
|
|
5
|
+
import { agentInputPartSchema } from "./input.ts";
|
|
5
6
|
|
|
6
7
|
/** The record source of an input message is the receiving agent; the communication sender is represented independently by sender. */
|
|
7
8
|
export const AgentInputMessage = defineRecord(builtin.name("agent.input-message"), {
|
|
8
|
-
schema: z.object({ parts:
|
|
9
|
+
schema: z.object({ parts: z.array(agentInputPartSchema).min(1), startsTurn: z.boolean(), sender: agentMessageSenderSchema }),
|
|
9
10
|
});
|
|
10
11
|
export const Execution = defineRecord(builtin.name("agent.execution"), {
|
|
11
12
|
schema: z.strictObject({ type: z.literal("block"), block: modelBlockSchema }),
|
package/src/search.ts
CHANGED
|
@@ -33,7 +33,7 @@ export const Grep = defineTool({
|
|
|
33
33
|
...globGuidelines,
|
|
34
34
|
],
|
|
35
35
|
argsSchema: z.strictObject({
|
|
36
|
-
pattern: pattern.describe("
|
|
36
|
+
pattern: pattern.describe("Pattern in ripgrep's default Rust regex syntax, without / delimiters. Matching is line-oriented; lookaround and pattern backreferences are unsupported. When literal is true, this is literal text."),
|
|
37
37
|
literal: z.boolean().optional().describe("Interpret pattern as literal text; defaults to false."),
|
|
38
38
|
ignoreCase: z.boolean().optional().describe("Use case-insensitive matching; defaults to false."),
|
|
39
39
|
word: z.boolean().optional().describe("Match only at word boundaries; defaults to false."),
|
package/src/text.ts
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
|
|
3
3
|
export const lineAnchorSchema = z.strictObject({
|
|
4
|
-
line: z.number().int().positive().describe("1-based line number copied from an anchored read
|
|
5
|
-
hash: z.string().regex(/^[0-9A-HJKMNP-TV-Z]{4}$/).describe("The exact four-character content hash after # in an anchored read
|
|
4
|
+
line: z.number().int().positive().describe("1-based line number copied from an anchored read, grep, edit, or replace result."),
|
|
5
|
+
hash: z.string().regex(/^[0-9A-HJKMNP-TV-Z]{4}$/).describe("The exact four-character content hash after # in an anchored read, grep, edit, or replace result."),
|
|
6
6
|
}).describe("A LINE#HASH reference to the current content at one line.");
|
|
7
7
|
const body = z.array(z.string().regex(/^[^\r\n]*$/).describe("One content line without a line terminator; an empty string represents a blank line."))
|
|
8
8
|
.min(1).describe("New text lines to insert or use as replacement content.");
|
|
9
9
|
const anchor = lineAnchorSchema.describe("The first affected line, or the preserved line next to an insertion.");
|
|
10
|
-
const end = lineAnchorSchema.optional().describe("Inclusive last line for replace/delete.
|
|
10
|
+
const end = lineAnchorSchema.optional().describe("Inclusive last line for replace/delete. Required for a multi-line range; omission selects only the anchor line. Validation checks the cited endpoints.");
|
|
11
11
|
export const editOperationSchema = z.discriminatedUnion("op", [
|
|
12
|
-
z.strictObject({ op: z.literal("replace"), anchor, end, body }),
|
|
13
|
-
z.strictObject({ op: z.literal("delete"), anchor, end }),
|
|
14
|
-
z.strictObject({ op: z.literal("insert_after"), anchor, body }),
|
|
15
|
-
z.strictObject({ op: z.literal("insert_before"), anchor, body }),
|
|
16
|
-
z.strictObject({ op: z.literal("append"), body }),
|
|
17
|
-
z.strictObject({ op: z.literal("prepend"), body }),
|
|
12
|
+
z.strictObject({ op: z.literal("replace").describe("Replace the selected lines with body."), anchor, end, body }),
|
|
13
|
+
z.strictObject({ op: z.literal("delete").describe("Delete the selected lines."), anchor, end }),
|
|
14
|
+
z.strictObject({ op: z.literal("insert_after").describe("Insert body after the preserved anchor line. body contains only new lines."), anchor, body }),
|
|
15
|
+
z.strictObject({ op: z.literal("insert_before").describe("Insert body before the preserved anchor line. body contains only new lines."), anchor, body }),
|
|
16
|
+
z.strictObject({ op: z.literal("append").describe("Append body to the target's text."), body }),
|
|
17
|
+
z.strictObject({ op: z.literal("prepend").describe("Prepend body to the target's text."), body }),
|
|
18
18
|
]).describe("Replace/delete an inclusive anchored range, insert beside a preserved anchor, or append/prepend without anchors.");
|
|
19
19
|
|
|
20
20
|
export const textRowSchema = z.strictObject({
|
|
@@ -40,8 +40,13 @@ export const textChangeSchema = z.strictObject({
|
|
|
40
40
|
diff: z.string().describe("The actual unified diff, preserving final-newline and CRLF differences."),
|
|
41
41
|
added: z.number().int().nonnegative().describe("Number of added lines in the actual diff."),
|
|
42
42
|
removed: z.number().int().nonnegative().describe("Number of removed lines in the actual diff."),
|
|
43
|
-
anchors: z.array(textRowSchema).describe("Fresh anchors for lines produced by edit, including a line shifted into a deletion gap. Always empty for write."),
|
|
43
|
+
anchors: z.array(textRowSchema).describe("Fresh anchors for lines produced by edit or replace, including a line shifted into a deletion gap. Always empty for write."),
|
|
44
44
|
anchorsTruncated: z.boolean().describe("True when the fresh anchors cover a subset of the changed lines."),
|
|
45
45
|
}).describe("The committed content change with an actual diff and bounded fresh edit anchors. write returns an empty anchors array.");
|
|
46
46
|
export type TextRead = z.infer<typeof textReadSchema>;
|
|
47
47
|
export type TextChange = z.infer<typeof textChangeSchema>;
|
|
48
|
+
|
|
49
|
+
export const textReplaceSchema = textChangeSchema.extend({
|
|
50
|
+
matches: z.number().int().nonnegative().describe("Number of matched occurrences, including matches whose replacement leaves content unchanged."),
|
|
51
|
+
}).describe("Match count, actual content diff, and bounded fresh anchors for the resulting changed lines.");
|
|
52
|
+
export type TextReplace = z.infer<typeof textReplaceSchema>;
|
package/src/tools.ts
CHANGED
|
@@ -38,7 +38,7 @@ export const Edit = defineTool({
|
|
|
38
38
|
description: "Apply a batch of line-anchored text edits to an existing target, and return the actual diff and fresh anchors.",
|
|
39
39
|
guidelines: [
|
|
40
40
|
"target selects existing editable text according to the resource implementation's schema. args.edits contains the operations.",
|
|
41
|
-
"Anchors contain a line number and its content hash, as returned by read or
|
|
41
|
+
"Anchors contain a line number and its content hash, as returned by read, grep, edit, or replace.",
|
|
42
42
|
"replace/delete affect the inclusive anchor..end range. An omitted end selects one line. Validation checks the cited endpoints.",
|
|
43
43
|
"insert_before/insert_after preserve the anchor line. body contains the new lines.",
|
|
44
44
|
"append/prepend take body. Each body item is one text line; an empty string represents a blank line.",
|
|
@@ -53,8 +53,9 @@ export const Edit = defineTool({
|
|
|
53
53
|
export const Write = defineTool({
|
|
54
54
|
id: builtin.name("tool.write"),
|
|
55
55
|
name: "write",
|
|
56
|
-
description: "Write
|
|
56
|
+
description: "Write complete text to a target.",
|
|
57
57
|
guidelines: [
|
|
58
|
+
"Use write only for new targets or complete rewrites.",
|
|
58
59
|
"args.content is the complete desired text, including line endings and final newline.",
|
|
59
60
|
"target selects the destination according to the resource implementation's schema, which states whether missing targets are created.",
|
|
60
61
|
"An existing target is overwritten. Success returns a brief confirmation and change statistics.",
|
|
@@ -64,6 +65,26 @@ export const Write = defineTool({
|
|
|
64
65
|
}).describe("Full replacement text. The implementation specifies its content size limit."),
|
|
65
66
|
});
|
|
66
67
|
|
|
68
|
+
export const Replace = defineTool({
|
|
69
|
+
id: builtin.name("tool.replace"),
|
|
70
|
+
name: "replace",
|
|
71
|
+
description: "Replace all occurrences of text or a regular expression in an existing target.",
|
|
72
|
+
guidelines: [
|
|
73
|
+
"target selects existing editable text. Matching covers the entire content, including line breaks, and does not verify edit anchors.",
|
|
74
|
+
"Literal mode matches find as text and inserts replace verbatim. Regex mode uses JavaScript regular expressions and replacement syntax.",
|
|
75
|
+
"All non-overlapping matches are replaced. flags applies in both modes; global matching is always enabled.",
|
|
76
|
+
"No matches returns an error without changing the target. Matches that produce identical content succeed without writing.",
|
|
77
|
+
"The result includes the match count, actual diff, and fresh anchors for changed lines. These anchors can be used by edit.",
|
|
78
|
+
],
|
|
79
|
+
argsSchema: z.strictObject({
|
|
80
|
+
find: z.string().min(1).describe("Non-empty text to find, or a JavaScript regular expression source when regex is true."),
|
|
81
|
+
replace: z.string().describe("Replacement text; empty text deletes matches. Regex mode supports $$, $&, $1 through $99, $<name>, $` and $'. Literal mode preserves these sequences."),
|
|
82
|
+
regex: z.boolean().optional().describe("Interpret find as a JavaScript (ECMAScript) regular expression source, without / delimiters. Supports lookaround, pattern backreferences, and named capture groups. Matching covers the entire target; flags controls matching options. Defaults to false (literal text)."),
|
|
83
|
+
flags: z.string().regex(/^[gimsuv]*$/).optional().describe("Matching flags: i ignores case, m gives line anchors, s lets dot match line breaks, and u or v enables Unicode matching. g is implicit. Defaults to no additional flags."),
|
|
84
|
+
}).describe("Search pattern, replacement text, and optional matching mode and flags."),
|
|
85
|
+
});
|
|
86
|
+
export type ReplaceArgs = z.infer<typeof Replace.argsSchema>;
|
|
87
|
+
|
|
67
88
|
export const See = defineTool({
|
|
68
89
|
id: builtin.name("tool.see"),
|
|
69
90
|
name: "see",
|