@arnilo/prism-hosts 0.13.1 → 0.14.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/CHANGELOG.md +2 -0
- package/a2a/README.md +195 -0
- package/a2a/src/card.ts +208 -0
- package/a2a/src/codec.ts +523 -0
- package/a2a/src/connect.ts +415 -0
- package/a2a/src/errors.ts +87 -0
- package/a2a/src/index.ts +40 -0
- package/a2a/src/limits.ts +43 -0
- package/a2a/src/pending.ts +28 -0
- package/a2a/src/proxy.ts +526 -0
- package/a2a/src/serve.ts +886 -0
- package/acp/README.md +3 -1
- package/acp/src/limits.ts +3 -16
- package/acp/src/mapper.ts +26 -5
- package/acp/src/serve.ts +6 -5
- package/ag-ui/README.md +2 -1
- package/ag-ui/src/a2ui.ts +8 -31
- package/ag-ui/src/ag-ui-mapper.ts +27 -1
- package/ag-ui/src/encrypted-value.ts +3 -3
- package/ag-ui/src/handler.ts +4 -4
- package/ag-ui/src/index.ts +0 -33
- package/ag-ui/src/limits.ts +5 -88
- package/ag-ui/src/projectors.ts +8 -6
- package/ag-ui/src/renderer/bind.ts +2 -1
- package/channels/README.md +61 -5
- package/channels/src/discord-gateway.ts +354 -0
- package/channels/src/discord.ts +873 -0
- package/channels/src/index.ts +4 -2
- package/channels/src/limits.ts +3 -19
- package/channels/src/pairing.ts +1 -2
- package/channels/src/runtime-turn.ts +10 -2
- package/channels/src/signal.ts +11 -19
- package/channels/src/slack.ts +854 -0
- package/channels/src/telegram.ts +22 -44
- package/channels/src/types.ts +5 -2
- package/devtools/README.md +1 -1
- package/driver-process/src/driver.ts +3 -1
- package/driver-process/src/testing.ts +1 -1
- package/driver-process/src/turn.ts +5 -1
- package/evals/README.md +11 -7
- package/evals/src/calibration.ts +5 -13
- package/evals/src/compare-experiments.ts +1 -2
- package/evals/src/comparison.ts +7 -25
- package/evals/src/curate.ts +3 -9
- package/evals/src/dataset.ts +0 -2
- package/evals/src/index.ts +3 -20
- package/evals/src/injection.ts +33 -6
- package/evals/src/judge.ts +9 -13
- package/evals/src/limits.ts +0 -17
- package/evals/src/rubric-judge.ts +5 -10
- package/evals/src/scenario-runner.ts +8 -4
- package/evals/src/scenarios.ts +5 -5
- package/evals/src/score.ts +3 -5
- package/evals/src/stats.ts +0 -2
- package/evals/src/threshold.ts +3 -3
- package/evals/src/toolless-session.ts +7 -3
- package/evals/src/trace.ts +8 -14
- package/evals/src/trajectory.ts +45 -11
- package/evals/src/types.ts +2 -2
- package/evals/src/user-simulator.ts +1 -7
- package/evals/src/util.ts +3 -9
- package/headless/README.md +20 -1
- package/headless/src/authority.ts +14 -1
- package/headless/src/errors.ts +3 -1
- package/headless/src/index.ts +10 -1
- package/headless/src/limits.ts +2 -2
- package/headless/src/pending.ts +4 -3
- package/headless/src/recover.ts +126 -0
- package/headless/src/resume.ts +1 -1
- package/host-builder/data/api.json +1271 -1360
- package/host-builder/data/errors.json +199 -185
- package/host-builder/data/examples/a2a-client.ts +125 -0
- package/host-builder/data/examples/a2a-server.ts +133 -0
- package/host-builder/data/examples/autonomous-coding-loop.ts +1 -1
- package/host-builder/data/examples/build-workflow.ts +2 -2
- package/host-builder/data/examples/caveman-ponytail.ts +1 -1
- package/host-builder/data/examples/channel-discord.ts +176 -0
- package/host-builder/data/examples/channel-slack.ts +146 -0
- package/host-builder/data/examples/continue-after-failure.ts +80 -0
- package/host-builder/data/examples/custom-adapter.ts +1 -1
- package/host-builder/data/examples/decision-models.ts +1 -1
- package/host-builder/data/examples/define-package.ts +1 -1
- package/host-builder/data/examples/delegate.ts +74 -9
- package/host-builder/data/examples/durable-loops-and-approvals.ts +11 -10
- package/host-builder/data/examples/governance-deny.ts +1 -1
- package/host-builder/data/examples/guardrail-content.ts +126 -0
- package/host-builder/data/examples/headless-host.ts +1 -1
- package/host-builder/data/examples/long-running-job.ts +129 -0
- package/host-builder/data/examples/long-term-memory.ts +1 -1
- package/host-builder/data/examples/mcp-oauth.ts +197 -0
- package/host-builder/data/examples/mcp-trust.ts +1 -1
- package/host-builder/data/examples/memory-and-wiki.ts +2 -2
- package/host-builder/data/examples/memory-system.ts +19 -9
- package/host-builder/data/examples/model-router-aggregate-budgets.ts +1 -1
- package/host-builder/data/examples/parallel-tools.ts +70 -0
- package/host-builder/data/examples/remote-agent.ts +1 -1
- package/host-builder/data/examples/serve-tools.ts +1 -1
- package/host-builder/data/examples/session-memory.ts +18 -16
- package/host-builder/data/examples/side-call.ts +1 -1
- package/host-builder/data/examples/sqlite-resume.ts +1 -1
- package/host-builder/data/examples/structured-output.ts +57 -0
- package/host-builder/data/examples.json +14 -4
- package/host-builder/skills/prism-host-builder/SKILL.md +1 -1
- package/host-builder/skills/prism-host-builder/references/choosing.md +14 -10
- package/host-builder/skills/prism-host-builder/references/pitfalls.md +5 -3
- package/host-builder/skills/prism-host-builder/references/recipes.md +5 -5
- package/host-builder/skills/prism-host-builder/references/verification.md +1 -1
- package/host-builder/src/check/runner.ts +2 -3
- package/host-builder/src/server.ts +2 -2
- package/mcp-server/README.md +3 -3
- package/mcp-server/src/bounds.ts +3 -3
- package/mcp-server/src/serve-tools.ts +2 -9
- package/mcp-server/src/serve.ts +2 -4
- package/mcp-server/src/server.ts +10 -20
- package/package.json +12 -6
- package/remote/README.md +7 -4
- package/remote/src/channel.ts +6 -2
- package/remote/src/connect.ts +9 -3
- package/remote/src/errors.ts +3 -1
- package/remote/src/limits.ts +3 -13
- package/remote/src/mirror.ts +2 -1
- package/remote/src/pending.ts +4 -3
- package/remote/src/protocol.ts +3 -0
- package/remote/src/serve.ts +43 -5
- package/remote/src/session-proxy.ts +28 -5
- package/remote/src/testing.ts +3 -1
- package/remote/src/wire.ts +74 -14
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type AgentEvent,
|
|
3
|
+
askEveryTool,
|
|
4
|
+
createAgent,
|
|
5
|
+
createMemorySessionStore,
|
|
6
|
+
type JsonObject,
|
|
7
|
+
providerDone,
|
|
8
|
+
providerTextDelta,
|
|
9
|
+
toolCallContent,
|
|
10
|
+
} from "@arnilo/prism";
|
|
11
|
+
import { providerPackage } from "@arnilo/prism/provider-kit";
|
|
12
|
+
import { connectA2A, serveA2A } from "@arnilo/prism-hosts/a2a";
|
|
13
|
+
|
|
14
|
+
// Bun-only demo (the examples tsconfig is Node-typed): the one Bun global this file uses.
|
|
15
|
+
declare const Bun: {
|
|
16
|
+
serve(options: { hostname: string; port: number; fetch: (request: Request) => Response | Promise<Response> }): {
|
|
17
|
+
readonly port: number;
|
|
18
|
+
stop(closeActiveConnections?: boolean): void;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Calls a remote A2A 1.0 agent as a local `Agent`, offline: an approval-gated peer is served with `serveA2A`
|
|
24
|
+
* on a loopback port (Bun-only, `Bun.serve`), and `connectA2A` reads its Agent Card and returns a proxy.
|
|
25
|
+
* The peer's `TASK_STATE_INPUT_REQUIRED` becomes a suspended run, and `session.resume` answers it.
|
|
26
|
+
* In a real host the peer is another framework's agent at an `https:` URL, and `allowLoopback` stays off.
|
|
27
|
+
*/
|
|
28
|
+
export async function demo() {
|
|
29
|
+
const executed: string[] = [];
|
|
30
|
+
let turn = 0;
|
|
31
|
+
const peerAgent = await createAgent({
|
|
32
|
+
id: "a2a-publisher",
|
|
33
|
+
model: { provider: "mock", model: "mock" },
|
|
34
|
+
slots: { store: createMemorySessionStore() },
|
|
35
|
+
packages: [
|
|
36
|
+
providerPackage("demo-provider", [
|
|
37
|
+
{
|
|
38
|
+
id: "mock",
|
|
39
|
+
async *generate() {
|
|
40
|
+
turn += 1;
|
|
41
|
+
if (turn === 1) {
|
|
42
|
+
yield { type: "tool_call" as const, call: toolCallContent("call-1", "publish_draft", { title: "Release notes" }) };
|
|
43
|
+
yield providerDone();
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
yield providerTextDelta(turn === 2 ? "Published." : "Here is a summary.");
|
|
47
|
+
yield providerDone();
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
]),
|
|
51
|
+
],
|
|
52
|
+
hooks: askEveryTool(),
|
|
53
|
+
tools: {
|
|
54
|
+
add: [
|
|
55
|
+
{
|
|
56
|
+
name: "publish_draft",
|
|
57
|
+
parameters: { type: "object" },
|
|
58
|
+
execute: (args: JsonObject, context: { toolCallId: string }) => {
|
|
59
|
+
executed.push(`${context.toolCallId}:${JSON.stringify(args)}`);
|
|
60
|
+
return { toolCallId: context.toolCallId, name: "publish_draft", value: "published" };
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
],
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// The peer. Its `authorize` checks the Bearer token the client sends.
|
|
68
|
+
process.env.DEMO_A2A_TOKEN = "demo-peer-token";
|
|
69
|
+
let handle: ReturnType<typeof serveA2A> | undefined;
|
|
70
|
+
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: (request) => (handle as ReturnType<typeof serveA2A>)(request) });
|
|
71
|
+
const base = `http://127.0.0.1:${server.port}`;
|
|
72
|
+
handle = serveA2A(peerAgent, {
|
|
73
|
+
card: {
|
|
74
|
+
name: "Publisher",
|
|
75
|
+
description: "Publishes drafts after a human approves.",
|
|
76
|
+
version: "1.0.0",
|
|
77
|
+
supportedInterfaces: [{ url: `${base}/a2a`, protocolBinding: "JSONRPC", protocolVersion: "1.0" }],
|
|
78
|
+
defaultInputModes: ["text/plain"],
|
|
79
|
+
defaultOutputModes: ["text/plain"],
|
|
80
|
+
skills: [{ id: "publish", name: "Publish", description: "Publishes a draft.", tags: ["publishing"] }],
|
|
81
|
+
},
|
|
82
|
+
authorize: ({ request }) =>
|
|
83
|
+
request.headers.get("authorization") === "Bearer demo-peer-token"
|
|
84
|
+
? { principal: { kind: "agent", id: "demo-client" }, ownership: { tenantId: "demo" } }
|
|
85
|
+
: false,
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
// The client: the token is a ref, never a literal.
|
|
89
|
+
const publisher = await connectA2A({ url: base, token: "env:DEMO_A2A_TOKEN" }, { allowLoopback: true });
|
|
90
|
+
const session = await publisher.session();
|
|
91
|
+
|
|
92
|
+
// 1. The run stops at the peer's approval: a suspended result with the pending decision.
|
|
93
|
+
const first = await session.run("Publish the release notes");
|
|
94
|
+
const pending = first.pending ?? [];
|
|
95
|
+
|
|
96
|
+
// 2. Answer it; the peer continues the same task.
|
|
97
|
+
const resumed: AgentEvent[] = [];
|
|
98
|
+
for await (const event of session.resume(
|
|
99
|
+
pending.map((decision) => ({ approvalId: decision.approvalId, outcome: "allow_once" as const })),
|
|
100
|
+
)) {
|
|
101
|
+
resumed.push(event);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// 3. A streamed second task in the same context.
|
|
105
|
+
const streamed: AgentEvent[] = [];
|
|
106
|
+
for await (const event of session.stream("Summarize")) streamed.push(event);
|
|
107
|
+
|
|
108
|
+
await publisher.dispose();
|
|
109
|
+
await handle.close();
|
|
110
|
+
server.stop(true);
|
|
111
|
+
return {
|
|
112
|
+
firstStatus: first.status,
|
|
113
|
+
pendingTool: pending[0]?.scope.toolName,
|
|
114
|
+
resumedFinal: resumed.at(-1)?.type,
|
|
115
|
+
streamedText: (await session.messages())
|
|
116
|
+
.at(-1)
|
|
117
|
+
?.content.map((block) => (block.type === "text" ? block.text : ""))
|
|
118
|
+
.join(""),
|
|
119
|
+
origin: streamed[0]?.origin?.kind,
|
|
120
|
+
executedBy: streamed[0]?.origin?.executedBy,
|
|
121
|
+
executedCalls: executed.length,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo()));
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import {
|
|
2
|
+
askEveryTool,
|
|
3
|
+
createAgent,
|
|
4
|
+
createMemorySessionStore,
|
|
5
|
+
type JsonObject,
|
|
6
|
+
providerDone,
|
|
7
|
+
providerTextDelta,
|
|
8
|
+
toolCallContent,
|
|
9
|
+
} from "@arnilo/prism";
|
|
10
|
+
import { providerPackage } from "@arnilo/prism/provider-kit";
|
|
11
|
+
import { PRISM_DECISIONS_EXTENSION, serveA2A } from "@arnilo/prism-hosts/a2a";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Serves one approval-gated agent to A2A 1.0 peers, offline: the peer reads the Agent Card, sends a
|
|
15
|
+
* message, gets `TASK_STATE_INPUT_REQUIRED`, answers with a decision, and streams a second task.
|
|
16
|
+
* In a real host, pass the handler to `Bun.serve({ fetch: handle })`.
|
|
17
|
+
*/
|
|
18
|
+
export async function demo() {
|
|
19
|
+
const executed: string[] = [];
|
|
20
|
+
let turn = 0;
|
|
21
|
+
const agent = await createAgent({
|
|
22
|
+
id: "a2a-publisher",
|
|
23
|
+
model: { provider: "mock", model: "mock" },
|
|
24
|
+
slots: { store: createMemorySessionStore() },
|
|
25
|
+
packages: [
|
|
26
|
+
providerPackage("demo-provider", [
|
|
27
|
+
{
|
|
28
|
+
id: "mock",
|
|
29
|
+
async *generate() {
|
|
30
|
+
turn += 1;
|
|
31
|
+
if (turn === 1) {
|
|
32
|
+
yield { type: "tool_call" as const, call: toolCallContent("call-1", "publish_draft", { title: "Release notes" }) };
|
|
33
|
+
yield providerDone();
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
yield providerTextDelta(turn === 2 ? "Published." : "Here is a summary.");
|
|
37
|
+
yield providerDone();
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
]),
|
|
41
|
+
],
|
|
42
|
+
hooks: askEveryTool(),
|
|
43
|
+
tools: {
|
|
44
|
+
add: [
|
|
45
|
+
{
|
|
46
|
+
name: "publish_draft",
|
|
47
|
+
parameters: { type: "object" },
|
|
48
|
+
execute: (args: JsonObject, context: { toolCallId: string }) => {
|
|
49
|
+
executed.push(`${context.toolCallId}:${JSON.stringify(args)}`);
|
|
50
|
+
return { toolCallId: context.toolCallId, name: "publish_draft", value: "published" };
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
],
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const endpoint = "https://agents.example.test/a2a";
|
|
58
|
+
const handle = serveA2A(agent, {
|
|
59
|
+
card: {
|
|
60
|
+
name: "Publisher",
|
|
61
|
+
description: "Publishes drafts after a human approves.",
|
|
62
|
+
version: "1.0.0",
|
|
63
|
+
supportedInterfaces: [{ url: endpoint, protocolBinding: "JSONRPC", protocolVersion: "1.0" }],
|
|
64
|
+
defaultInputModes: ["text/plain"],
|
|
65
|
+
defaultOutputModes: ["text/plain"],
|
|
66
|
+
skills: [{ id: "publish", name: "Publish", description: "Publishes a draft.", tags: ["publishing"] }],
|
|
67
|
+
securitySchemes: { bearer: { httpAuthSecurityScheme: { scheme: "Bearer" } } },
|
|
68
|
+
},
|
|
69
|
+
// A real host verifies a token here. Without `authorize`, every call is refused.
|
|
70
|
+
authorize: ({ request }) =>
|
|
71
|
+
request.headers.get("authorization") === "Bearer demo-peer"
|
|
72
|
+
? { principal: { kind: "agent", id: "demo-peer" }, ownership: { tenantId: "demo" } }
|
|
73
|
+
: false,
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
let id = 0;
|
|
77
|
+
const call = (method: string, params: unknown) =>
|
|
78
|
+
handle(
|
|
79
|
+
new Request(endpoint, {
|
|
80
|
+
method: "POST",
|
|
81
|
+
headers: { "content-type": "application/json", "a2a-version": "1.0", authorization: "Bearer demo-peer" },
|
|
82
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params }),
|
|
83
|
+
}),
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
const card = await (await handle(new Request("https://agents.example.test/.well-known/agent-card.json"))).json();
|
|
87
|
+
|
|
88
|
+
// 1. A blocking send: the run asks to call a tool, so the task stops at INPUT_REQUIRED.
|
|
89
|
+
const first = (await (
|
|
90
|
+
await call("SendMessage", { message: { messageId: "m-1", role: "ROLE_USER", parts: [{ text: "Publish the release notes" }] } })
|
|
91
|
+
).json()) as {
|
|
92
|
+
result: { task: { id: string; contextId: string; status: { state: string; message: { parts: { data: { approvalId: string } }[] } } } };
|
|
93
|
+
};
|
|
94
|
+
const task = first.result.task;
|
|
95
|
+
const approvalId = task.status.message.parts[0]?.data.approvalId;
|
|
96
|
+
|
|
97
|
+
// 2. The peer answers with one decision through the Prism decisions extension.
|
|
98
|
+
const resumed = (await (
|
|
99
|
+
await call("SendMessage", {
|
|
100
|
+
message: {
|
|
101
|
+
messageId: "m-2",
|
|
102
|
+
role: "ROLE_USER",
|
|
103
|
+
taskId: task.id,
|
|
104
|
+
extensions: [PRISM_DECISIONS_EXTENSION],
|
|
105
|
+
parts: [{ data: { decisions: [{ approvalId, outcome: "allow_once" }] } }],
|
|
106
|
+
},
|
|
107
|
+
})
|
|
108
|
+
).json()) as { result: { task: { status: { state: string }; artifacts: { parts: { text: string }[] }[] } } };
|
|
109
|
+
|
|
110
|
+
// 3. A streaming send in the same context.
|
|
111
|
+
const stream = await (
|
|
112
|
+
await call("SendStreamingMessage", {
|
|
113
|
+
message: { messageId: "m-3", role: "ROLE_USER", contextId: task.contextId, parts: [{ text: "Summarize" }] },
|
|
114
|
+
})
|
|
115
|
+
).text();
|
|
116
|
+
const frames = stream
|
|
117
|
+
.split("\n\n")
|
|
118
|
+
.filter((chunk) => chunk.startsWith("data: "))
|
|
119
|
+
.map((chunk) => JSON.parse(chunk.slice(6)).result);
|
|
120
|
+
|
|
121
|
+
await handle.close();
|
|
122
|
+
return {
|
|
123
|
+
cardStreaming: card.capabilities.streaming,
|
|
124
|
+
firstState: task.status.state,
|
|
125
|
+
resumedState: resumed.result.task.status.state,
|
|
126
|
+
resumedText: resumed.result.task.artifacts.at(-1)?.parts[0]?.text,
|
|
127
|
+
streamedFrames: frames.length,
|
|
128
|
+
streamedFinalState: frames.at(-1)?.statusUpdate?.status.state,
|
|
129
|
+
executedCalls: executed,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo()));
|
|
@@ -155,7 +155,7 @@ async function buildRuntime(store: SessionStore) {
|
|
|
155
155
|
// This demo records session events only; WM and rehearsal need no work here.
|
|
156
156
|
wm: false,
|
|
157
157
|
rehearsal: false,
|
|
158
|
-
context: {
|
|
158
|
+
context: { compactAfterRun: { maxTokens: 999_999 } },
|
|
159
159
|
worker: { maxTurns: 1 },
|
|
160
160
|
}),
|
|
161
161
|
],
|
|
@@ -84,7 +84,7 @@ export async function demo(): Promise<Record<string, unknown>> {
|
|
|
84
84
|
const shared = definePackage({
|
|
85
85
|
name: "@example/build-shared",
|
|
86
86
|
version: "1.0.0",
|
|
87
|
-
requires: { api:
|
|
87
|
+
requires: { api: 2 },
|
|
88
88
|
setup: (prism) => prism.services.provide("workspace", workspace),
|
|
89
89
|
});
|
|
90
90
|
const store = () => sqliteStore({ path: dbPath });
|
|
@@ -153,7 +153,7 @@ export async function demo(): Promise<Record<string, unknown>> {
|
|
|
153
153
|
definePackage({
|
|
154
154
|
name: "@example/build-command",
|
|
155
155
|
version: "1.0.0",
|
|
156
|
-
requires: { api:
|
|
156
|
+
requires: { api: 2 },
|
|
157
157
|
setup: (prism) =>
|
|
158
158
|
prism.commands.register(
|
|
159
159
|
workflowCommand(prism, "build", () => build, {
|
|
@@ -57,7 +57,7 @@ function personaPackage(options: PersonaOptions) {
|
|
|
57
57
|
return definePackage({
|
|
58
58
|
name: `@example/${options.name}`,
|
|
59
59
|
version: "1.0.0",
|
|
60
|
-
requires: { api:
|
|
60
|
+
requires: { api: 2 },
|
|
61
61
|
async setup(prism) {
|
|
62
62
|
const entries = await options.store.list(sessionId);
|
|
63
63
|
for (const entry of entries) {
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import {
|
|
2
|
+
askEveryTool,
|
|
3
|
+
createAgent,
|
|
4
|
+
createMemorySessionStore,
|
|
5
|
+
type JsonObject,
|
|
6
|
+
providerDone,
|
|
7
|
+
providerTextDelta,
|
|
8
|
+
toolCallContent,
|
|
9
|
+
} from "@arnilo/prism";
|
|
10
|
+
import { providerPackage } from "@arnilo/prism/provider-kit";
|
|
11
|
+
import { connectDiscord, type DiscordSocket } from "@arnilo/prism-hosts/channels/discord";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Binds one approval-gated agent to a Discord bot, offline: a scripted Gateway socket and a scripted
|
|
15
|
+
* `fetch` stand in for Discord. The client identifies and becomes ready, a guild mention runs a turn
|
|
16
|
+
* that asks for approval, another user's click is refused, and the bound user's click resumes the run.
|
|
17
|
+
* In a real host, `await discord.start()` opens the Gateway through the global `WebSocket`.
|
|
18
|
+
*/
|
|
19
|
+
export async function demo() {
|
|
20
|
+
process.env.DEMO_DISCORD_BOT_TOKEN ??= "demo-discord-bot-token";
|
|
21
|
+
const executed: string[] = [];
|
|
22
|
+
let turn = 0;
|
|
23
|
+
const agent = await createAgent({
|
|
24
|
+
id: "discord-publisher",
|
|
25
|
+
model: { provider: "mock", model: "mock" },
|
|
26
|
+
slots: { store: createMemorySessionStore() },
|
|
27
|
+
hooks: askEveryTool(),
|
|
28
|
+
packages: [
|
|
29
|
+
providerPackage("demo-provider", [
|
|
30
|
+
{
|
|
31
|
+
id: "mock",
|
|
32
|
+
async *generate() {
|
|
33
|
+
turn += 1;
|
|
34
|
+
if (turn === 1) {
|
|
35
|
+
yield { type: "tool_call" as const, call: toolCallContent("call-1", "publish_draft", { title: "Release notes" }) };
|
|
36
|
+
yield providerDone();
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
yield providerTextDelta("Published the release notes.");
|
|
40
|
+
yield providerDone();
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
]),
|
|
44
|
+
],
|
|
45
|
+
tools: {
|
|
46
|
+
add: [
|
|
47
|
+
{
|
|
48
|
+
name: "publish_draft",
|
|
49
|
+
parameters: { type: "object" },
|
|
50
|
+
execute: (args: JsonObject, context: { toolCallId: string }) => {
|
|
51
|
+
executed.push(JSON.stringify(args));
|
|
52
|
+
return { toolCallId: context.toolCallId, name: "publish_draft", value: "published" };
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
],
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
// Scripted REST API: the Gateway URL, message creation, and interaction callbacks.
|
|
60
|
+
const posted: Array<{ path: string; body: Record<string, unknown> }> = [];
|
|
61
|
+
let nextId = 9000;
|
|
62
|
+
const fetch = (async (input: unknown, init?: RequestInit) => {
|
|
63
|
+
const path = new URL(String(input)).pathname.replace("/api/v10", "");
|
|
64
|
+
if (path === "/gateway/bot") return Response.json({ url: "wss://gateway.discord.example" });
|
|
65
|
+
posted.push({ path, body: JSON.parse(String(init?.body ?? "{}")) as Record<string, unknown> });
|
|
66
|
+
if (path.startsWith("/interactions/")) return new Response(null, { status: 204 });
|
|
67
|
+
nextId += 1;
|
|
68
|
+
return Response.json({ id: String(nextId) });
|
|
69
|
+
}) as typeof globalThis.fetch;
|
|
70
|
+
|
|
71
|
+
// Scripted Gateway: Hello on connect, READY after Identify.
|
|
72
|
+
const sent: Array<{ op: number; d: unknown }> = [];
|
|
73
|
+
let gateway: { emit(frame: unknown): void } | undefined;
|
|
74
|
+
const webSocket = (_url: string): DiscordSocket => {
|
|
75
|
+
const listeners = new Map<string, Array<(event: { data?: unknown; code?: number }) => void>>();
|
|
76
|
+
const emit = (frame: unknown) => {
|
|
77
|
+
for (const listener of listeners.get("message") ?? []) listener({ data: JSON.stringify(frame) });
|
|
78
|
+
};
|
|
79
|
+
gateway = { emit };
|
|
80
|
+
queueMicrotask(() => emit({ op: 10, d: { heartbeat_interval: 41_250 } }));
|
|
81
|
+
return {
|
|
82
|
+
addEventListener: (type, listener) => listeners.set(type, [...(listeners.get(type) ?? []), listener]),
|
|
83
|
+
send(data) {
|
|
84
|
+
const frame = JSON.parse(data) as { op: number; d: unknown };
|
|
85
|
+
sent.push(frame);
|
|
86
|
+
if (frame.op === 2)
|
|
87
|
+
queueMicrotask(() =>
|
|
88
|
+
emit({
|
|
89
|
+
op: 0,
|
|
90
|
+
t: "READY",
|
|
91
|
+
s: 1,
|
|
92
|
+
d: { session_id: "demo-session", resume_gateway_url: "wss://resume.discord.example", user: { id: "999" } },
|
|
93
|
+
}),
|
|
94
|
+
);
|
|
95
|
+
},
|
|
96
|
+
close: (code) => {
|
|
97
|
+
for (const listener of listeners.get("close") ?? []) listener({ code: code ?? 1000 });
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const discord = await connectDiscord(agent, {
|
|
103
|
+
token: "env:DEMO_DISCORD_BOT_TOKEN",
|
|
104
|
+
applicationId: "999",
|
|
105
|
+
// Deny by default: only these two server members may talk to the agent.
|
|
106
|
+
authorize: (input) =>
|
|
107
|
+
["1", "2"].includes(input.externalActorId) && {
|
|
108
|
+
identity: {
|
|
109
|
+
tenantId: "acme",
|
|
110
|
+
userId: input.externalActorId,
|
|
111
|
+
principal: { kind: "user", id: input.externalActorId },
|
|
112
|
+
scopes: ["chat"],
|
|
113
|
+
issuedAt: new Date(0).toISOString(),
|
|
114
|
+
verified: true,
|
|
115
|
+
},
|
|
116
|
+
grantRevision: "1",
|
|
117
|
+
},
|
|
118
|
+
fetch,
|
|
119
|
+
webSocket,
|
|
120
|
+
});
|
|
121
|
+
await discord.start();
|
|
122
|
+
const identify = sent.find((frame) => frame.op === 2)?.d as { intents?: number } | undefined;
|
|
123
|
+
|
|
124
|
+
gateway?.emit({
|
|
125
|
+
op: 0,
|
|
126
|
+
t: "MESSAGE_CREATE",
|
|
127
|
+
s: 2,
|
|
128
|
+
d: {
|
|
129
|
+
id: "5001",
|
|
130
|
+
type: 0,
|
|
131
|
+
guild_id: "100",
|
|
132
|
+
channel_id: "200",
|
|
133
|
+
author: { id: "1" },
|
|
134
|
+
content: "<@999> publish the release notes",
|
|
135
|
+
mentions: [{ id: "999" }],
|
|
136
|
+
},
|
|
137
|
+
});
|
|
138
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
139
|
+
await discord.drain();
|
|
140
|
+
const prompt = posted.find((call) => call.path === "/channels/200/messages");
|
|
141
|
+
const rows = prompt?.body.components as Array<{ components: Array<{ label: string; custom_id: string }> }> | undefined;
|
|
142
|
+
const allow = rows?.flatMap((row) => row.components).find((button) => button.label === "Allow once");
|
|
143
|
+
const click = (id: string, user: string) => ({
|
|
144
|
+
op: 0,
|
|
145
|
+
t: "INTERACTION_CREATE",
|
|
146
|
+
d: {
|
|
147
|
+
id,
|
|
148
|
+
type: 3,
|
|
149
|
+
token: `demo-interaction-${id}`,
|
|
150
|
+
guild_id: "100",
|
|
151
|
+
channel_id: "200",
|
|
152
|
+
member: { user: { id: user } },
|
|
153
|
+
data: { component_type: 2, custom_id: allow?.custom_id },
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
gateway?.emit(click("6001", "2"));
|
|
157
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
158
|
+
await discord.drain();
|
|
159
|
+
const foreignClickRuns = executed.length;
|
|
160
|
+
gateway?.emit(click("6002", "1"));
|
|
161
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
162
|
+
await discord.drain();
|
|
163
|
+
await discord.close();
|
|
164
|
+
|
|
165
|
+
const replies = posted.filter((call) => call.path === "/channels/200/messages");
|
|
166
|
+
return {
|
|
167
|
+
identified: identify?.intents === ((1 << 9) | (1 << 12) | (1 << 15)),
|
|
168
|
+
approvalPrompt: prompt?.body.content,
|
|
169
|
+
foreignClickRuns,
|
|
170
|
+
acknowledgements: posted.filter((call) => call.path.startsWith("/interactions/")).length,
|
|
171
|
+
finalReply: replies.at(-1)?.body.content,
|
|
172
|
+
toolRuns: executed.length,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo()));
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { createHmac } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
askEveryTool,
|
|
4
|
+
createAgent,
|
|
5
|
+
createMemorySessionStore,
|
|
6
|
+
type JsonObject,
|
|
7
|
+
providerDone,
|
|
8
|
+
providerTextDelta,
|
|
9
|
+
toolCallContent,
|
|
10
|
+
} from "@arnilo/prism";
|
|
11
|
+
import { providerPackage } from "@arnilo/prism/provider-kit";
|
|
12
|
+
import { connectSlack } from "@arnilo/prism-hosts/channels/slack";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Binds one approval-gated agent to a Slack app over the Events API, offline: a scripted `fetch`
|
|
16
|
+
* stands in for the Web API and requests are signed with a demo signing secret. A mention runs a
|
|
17
|
+
* turn that asks for approval; the Allow button resumes it in the same thread. In a real host,
|
|
18
|
+
* mount `slack.handle` with `Bun.serve({ fetch: (request) => slack.handle(request) })`.
|
|
19
|
+
*/
|
|
20
|
+
export async function demo() {
|
|
21
|
+
process.env.DEMO_SLACK_BOT_TOKEN ??= "demo-slack-bot-token";
|
|
22
|
+
process.env.DEMO_SLACK_SIGNING_SECRET ??= "demo-signing-secret";
|
|
23
|
+
const signingSecret = process.env.DEMO_SLACK_SIGNING_SECRET;
|
|
24
|
+
const executed: string[] = [];
|
|
25
|
+
let turn = 0;
|
|
26
|
+
const agent = await createAgent({
|
|
27
|
+
id: "slack-publisher",
|
|
28
|
+
model: { provider: "mock", model: "mock" },
|
|
29
|
+
slots: { store: createMemorySessionStore() },
|
|
30
|
+
hooks: askEveryTool(),
|
|
31
|
+
packages: [
|
|
32
|
+
providerPackage("demo-provider", [
|
|
33
|
+
{
|
|
34
|
+
id: "mock",
|
|
35
|
+
async *generate() {
|
|
36
|
+
turn += 1;
|
|
37
|
+
if (turn === 1) {
|
|
38
|
+
yield { type: "tool_call" as const, call: toolCallContent("call-1", "publish_draft", { title: "Release notes" }) };
|
|
39
|
+
yield providerDone();
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
yield providerTextDelta("Published the release notes.");
|
|
43
|
+
yield providerDone();
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
]),
|
|
47
|
+
],
|
|
48
|
+
tools: {
|
|
49
|
+
add: [
|
|
50
|
+
{
|
|
51
|
+
name: "publish_draft",
|
|
52
|
+
parameters: { type: "object" },
|
|
53
|
+
execute: (args: JsonObject, context: { toolCallId: string }) => {
|
|
54
|
+
executed.push(JSON.stringify(args));
|
|
55
|
+
return { toolCallId: context.toolCallId, name: "publish_draft", value: "published" };
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
],
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// Scripted Slack Web API: every chat.postMessage succeeds and is recorded.
|
|
63
|
+
const posted: Array<Record<string, unknown>> = [];
|
|
64
|
+
const fetch = (async (_input: unknown, init?: RequestInit) => {
|
|
65
|
+
const body = JSON.parse(String(init?.body)) as Record<string, unknown>;
|
|
66
|
+
posted.push(body);
|
|
67
|
+
return Response.json({ ok: true, channel: body.channel, ts: `1700000000.00${posted.length}` });
|
|
68
|
+
}) as typeof globalThis.fetch;
|
|
69
|
+
|
|
70
|
+
const slack = await connectSlack(agent, {
|
|
71
|
+
token: "env:DEMO_SLACK_BOT_TOKEN",
|
|
72
|
+
signingSecret: "env:DEMO_SLACK_SIGNING_SECRET",
|
|
73
|
+
// Deny by default: only this workspace member may talk to the agent.
|
|
74
|
+
authorize: (input) =>
|
|
75
|
+
input.externalActorId === "T1:U1" && {
|
|
76
|
+
identity: {
|
|
77
|
+
tenantId: "acme",
|
|
78
|
+
userId: "U1",
|
|
79
|
+
principal: { kind: "user", id: "U1" },
|
|
80
|
+
scopes: ["chat"],
|
|
81
|
+
issuedAt: new Date(0).toISOString(),
|
|
82
|
+
verified: true,
|
|
83
|
+
},
|
|
84
|
+
grantRevision: "1",
|
|
85
|
+
},
|
|
86
|
+
fetch,
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
function signed(payload: unknown, form = false): Request {
|
|
90
|
+
const json = JSON.stringify(payload);
|
|
91
|
+
const body = form ? `payload=${encodeURIComponent(json)}` : json;
|
|
92
|
+
const timestamp = String(Math.floor(Date.now() / 1000));
|
|
93
|
+
const signature = `v0=${createHmac("sha256", signingSecret).update(`v0:${timestamp}:${body}`).digest("hex")}`;
|
|
94
|
+
return new Request("https://bot.example.test/slack/events", {
|
|
95
|
+
method: "POST",
|
|
96
|
+
headers: {
|
|
97
|
+
"content-type": form ? "application/x-www-form-urlencoded" : "application/json",
|
|
98
|
+
"x-slack-request-timestamp": timestamp,
|
|
99
|
+
"x-slack-signature": signature,
|
|
100
|
+
},
|
|
101
|
+
body,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const thread = "1700000000.000100";
|
|
106
|
+
const mention = {
|
|
107
|
+
type: "event_callback",
|
|
108
|
+
team_id: "T1",
|
|
109
|
+
event_id: "Ev1",
|
|
110
|
+
event: { type: "app_mention", user: "U1", channel: "C1", ts: thread, text: "<@UBOT> publish the release notes" },
|
|
111
|
+
};
|
|
112
|
+
const mentionStatus = ((await slack.handle(signed(mention))) as Response).status;
|
|
113
|
+
await slack.drain();
|
|
114
|
+
const prompt = posted[0];
|
|
115
|
+
const blocks = prompt?.blocks as Array<{ type: string; elements?: Array<{ text: { text: string }; value: string }> }>;
|
|
116
|
+
const allow = blocks.find((block) => block.type === "actions")?.elements?.find((button) => button.text.text === "Allow once");
|
|
117
|
+
const click = {
|
|
118
|
+
type: "block_actions",
|
|
119
|
+
team: { id: "T1" },
|
|
120
|
+
user: { id: "U1", team_id: "T1" },
|
|
121
|
+
channel: { id: "C1" },
|
|
122
|
+
container: { type: "message", message_ts: String(prompt?.ts ?? "1700000000.001"), channel_id: "C1", thread_ts: thread },
|
|
123
|
+
message: { ts: "1700000000.001", thread_ts: thread },
|
|
124
|
+
actions: [{ action_id: "prism_0", type: "button", value: allow?.value, action_ts: "1700000001.000001" }],
|
|
125
|
+
};
|
|
126
|
+
const unsignedStatus = (
|
|
127
|
+
(await slack.handle(
|
|
128
|
+
new Request("https://bot.example.test/slack/events", { method: "POST", body: JSON.stringify(mention) }),
|
|
129
|
+
)) as Response
|
|
130
|
+
).status;
|
|
131
|
+
const clickStatus = ((await slack.handle(signed(click, true))) as Response).status;
|
|
132
|
+
await slack.drain();
|
|
133
|
+
await slack.close();
|
|
134
|
+
|
|
135
|
+
return {
|
|
136
|
+
mentionStatus,
|
|
137
|
+
unsignedStatus,
|
|
138
|
+
clickStatus,
|
|
139
|
+
approvalPrompt: prompt?.text,
|
|
140
|
+
replyInThread: posted.at(-1)?.thread_ts === thread,
|
|
141
|
+
finalReply: posted.at(-1)?.text,
|
|
142
|
+
toolRuns: executed.length,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo()));
|