@corbat-tech/coco 2.40.0 → 2.41.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/dist/adapters/index.d.ts +81 -3
- package/dist/adapters/index.js +179 -1
- package/dist/adapters/index.js.map +1 -1
- package/dist/{agent-runtime-Cd6pB640.d.ts → agent-runtime-BJeNjVuk.d.ts} +20 -2
- package/dist/{blueprints-Dmdaw6_I.d.ts → blueprints-Dw5-uWU9.d.ts} +28 -4
- package/dist/cli/index.js +474 -15
- package/dist/cli/index.js.map +1 -1
- package/dist/{workflow-engine-DleSoUhy.d.ts → context-BLPsKYxc.d.ts} +247 -129
- package/dist/{index-BD5_a3Q8.d.ts → index-DhUKtM2p.d.ts} +2 -2
- package/dist/index.d.ts +10 -10
- package/dist/index.js +1324 -128
- package/dist/index.js.map +1 -1
- package/dist/presets/index.d.ts +5 -5
- package/dist/presets/index.js +521 -17
- package/dist/presets/index.js.map +1 -1
- package/dist/{profiles-BA9dvyaF.d.ts → profiles-GRoVNorK.d.ts} +3 -3
- package/dist/{rag-D-Zo1oyo.d.ts → rag-B2oGudNb.d.ts} +68 -2
- package/dist/runtime/index.d.ts +278 -8
- package/dist/runtime/index.js +1113 -122
- package/dist/runtime/index.js.map +1 -1
- package/dist/tools/index.d.ts +4 -4
- package/dist/tools/index.js +1 -0
- package/dist/tools/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/runtime-tool-executor-L5i8QWzn.d.ts +0 -174
package/dist/adapters/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentRuntime } from '../agent-runtime-
|
|
2
|
-
import {
|
|
1
|
+
import { A as AgentRuntime } from '../agent-runtime-BJeNjVuk.js';
|
|
2
|
+
import { a as RuntimeTurnStreamEvent } from '../context-BLPsKYxc.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
|
|
5
5
|
interface ChannelInput {
|
|
@@ -38,6 +38,54 @@ interface WhatsAppAssistantAdapter {
|
|
|
38
38
|
surface: "whatsapp";
|
|
39
39
|
handleInbound(input: WhatsAppInboundMessage): Promise<ChannelOutput>;
|
|
40
40
|
}
|
|
41
|
+
interface ChannelSessionMapper {
|
|
42
|
+
getSessionId(input: {
|
|
43
|
+
tenantId: string;
|
|
44
|
+
channel: string;
|
|
45
|
+
senderId: string;
|
|
46
|
+
}): string | undefined;
|
|
47
|
+
setSessionId(input: {
|
|
48
|
+
tenantId: string;
|
|
49
|
+
channel: string;
|
|
50
|
+
senderId: string;
|
|
51
|
+
sessionId: string;
|
|
52
|
+
}): void;
|
|
53
|
+
}
|
|
54
|
+
interface WhatsAppCloudWebhookInput {
|
|
55
|
+
rawBody: string;
|
|
56
|
+
signature: string | undefined;
|
|
57
|
+
body?: unknown;
|
|
58
|
+
tenantId: string;
|
|
59
|
+
}
|
|
60
|
+
interface WhatsAppCloudMedia {
|
|
61
|
+
id: string;
|
|
62
|
+
type: "image" | "audio" | "video" | "document" | "sticker";
|
|
63
|
+
mimeType?: string;
|
|
64
|
+
caption?: string;
|
|
65
|
+
}
|
|
66
|
+
interface WhatsAppCloudMessage {
|
|
67
|
+
messageId: string;
|
|
68
|
+
from: string;
|
|
69
|
+
text: string;
|
|
70
|
+
profileName?: string;
|
|
71
|
+
media?: WhatsAppCloudMedia;
|
|
72
|
+
}
|
|
73
|
+
interface WhatsAppCloudAdapterOptions {
|
|
74
|
+
runtime: AgentRuntime;
|
|
75
|
+
appSecret: string;
|
|
76
|
+
tenantId: string;
|
|
77
|
+
sessionMapper?: ChannelSessionMapper;
|
|
78
|
+
maxMessagesPerMinutePerSender?: number;
|
|
79
|
+
optOutKeywords?: string[];
|
|
80
|
+
optInKeywords?: string[];
|
|
81
|
+
}
|
|
82
|
+
interface WhatsAppCloudWebhookResult {
|
|
83
|
+
accepted: boolean;
|
|
84
|
+
duplicate?: boolean;
|
|
85
|
+
optedOut?: boolean;
|
|
86
|
+
rateLimited?: boolean;
|
|
87
|
+
outputs: ChannelOutput[];
|
|
88
|
+
}
|
|
41
89
|
declare function createHttpAssistantAdapter(runtime: AgentRuntime): HttpAssistantAdapter;
|
|
42
90
|
declare function createStreamingHttpAssistantAdapter(runtime: AgentRuntime): StreamingHttpAssistantAdapter;
|
|
43
91
|
declare function createWebhookAssistantAdapter(runtime: AgentRuntime, options?: {
|
|
@@ -45,5 +93,35 @@ declare function createWebhookAssistantAdapter(runtime: AgentRuntime, options?:
|
|
|
45
93
|
surface?: ChannelAdapter["surface"];
|
|
46
94
|
}): ChannelAdapter;
|
|
47
95
|
declare function createWhatsAppAssistantAdapter(runtime: AgentRuntime): WhatsAppAssistantAdapter;
|
|
96
|
+
declare class InMemoryChannelSessionMapper implements ChannelSessionMapper {
|
|
97
|
+
private readonly sessions;
|
|
98
|
+
getSessionId(input: {
|
|
99
|
+
tenantId: string;
|
|
100
|
+
channel: string;
|
|
101
|
+
senderId: string;
|
|
102
|
+
}): string | undefined;
|
|
103
|
+
setSessionId(input: {
|
|
104
|
+
tenantId: string;
|
|
105
|
+
channel: string;
|
|
106
|
+
senderId: string;
|
|
107
|
+
sessionId: string;
|
|
108
|
+
}): void;
|
|
109
|
+
}
|
|
110
|
+
declare class WhatsAppCloudAdapter {
|
|
111
|
+
private readonly options;
|
|
112
|
+
private readonly mapper;
|
|
113
|
+
private readonly processedMessageIds;
|
|
114
|
+
private readonly optOutSenders;
|
|
115
|
+
private readonly senderTimestamps;
|
|
116
|
+
constructor(options: WhatsAppCloudAdapterOptions);
|
|
117
|
+
validateSignature(rawBody: string, signature: string | undefined): boolean;
|
|
118
|
+
handleWebhook(input: WhatsAppCloudWebhookInput): Promise<WhatsAppCloudWebhookResult>;
|
|
119
|
+
private getOrCreateSession;
|
|
120
|
+
private consumeRateLimit;
|
|
121
|
+
private isOptOut;
|
|
122
|
+
private isOptIn;
|
|
123
|
+
}
|
|
124
|
+
declare function createWhatsAppCloudAdapter(options: WhatsAppCloudAdapterOptions): WhatsAppCloudAdapter;
|
|
125
|
+
declare function createInMemoryChannelSessionMapper(): ChannelSessionMapper;
|
|
48
126
|
|
|
49
|
-
export { type ChannelAdapter, type ChannelInput, type ChannelOutput, type HttpAssistantAdapter, type StreamingHttpAssistantAdapter, type WhatsAppAssistantAdapter, type WhatsAppInboundMessage, createHttpAssistantAdapter, createStreamingHttpAssistantAdapter, createWebhookAssistantAdapter, createWhatsAppAssistantAdapter };
|
|
127
|
+
export { type ChannelAdapter, type ChannelInput, type ChannelOutput, type ChannelSessionMapper, type HttpAssistantAdapter, InMemoryChannelSessionMapper, type StreamingHttpAssistantAdapter, type WhatsAppAssistantAdapter, WhatsAppCloudAdapter, type WhatsAppCloudAdapterOptions, type WhatsAppCloudMedia, type WhatsAppCloudMessage, type WhatsAppCloudWebhookInput, type WhatsAppCloudWebhookResult, type WhatsAppInboundMessage, createHttpAssistantAdapter, createInMemoryChannelSessionMapper, createStreamingHttpAssistantAdapter, createWebhookAssistantAdapter, createWhatsAppAssistantAdapter, createWhatsAppCloudAdapter };
|
package/dist/adapters/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'crypto';
|
|
2
|
+
|
|
1
3
|
// src/adapters/index.ts
|
|
2
4
|
function createHttpAssistantAdapter(runtime) {
|
|
3
5
|
return {
|
|
@@ -60,7 +62,183 @@ function createWhatsAppAssistantAdapter(runtime) {
|
|
|
60
62
|
}
|
|
61
63
|
};
|
|
62
64
|
}
|
|
65
|
+
var InMemoryChannelSessionMapper = class {
|
|
66
|
+
sessions = /* @__PURE__ */ new Map();
|
|
67
|
+
getSessionId(input) {
|
|
68
|
+
return this.sessions.get(sessionKey(input));
|
|
69
|
+
}
|
|
70
|
+
setSessionId(input) {
|
|
71
|
+
this.sessions.set(sessionKey(input), input.sessionId);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
var WhatsAppCloudAdapter = class {
|
|
75
|
+
constructor(options) {
|
|
76
|
+
this.options = options;
|
|
77
|
+
this.mapper = options.sessionMapper ?? new InMemoryChannelSessionMapper();
|
|
78
|
+
}
|
|
79
|
+
options;
|
|
80
|
+
mapper;
|
|
81
|
+
processedMessageIds = /* @__PURE__ */ new Set();
|
|
82
|
+
optOutSenders = /* @__PURE__ */ new Set();
|
|
83
|
+
senderTimestamps = /* @__PURE__ */ new Map();
|
|
84
|
+
validateSignature(rawBody, signature) {
|
|
85
|
+
if (!signature?.startsWith("sha256=")) return false;
|
|
86
|
+
const expected = createHmac("sha256", this.options.appSecret).update(rawBody).digest("hex");
|
|
87
|
+
const actual = signature.slice("sha256=".length);
|
|
88
|
+
const expectedBuffer = Buffer.from(expected, "hex");
|
|
89
|
+
const actualBuffer = Buffer.from(actual, "hex");
|
|
90
|
+
return expectedBuffer.length === actualBuffer.length && timingSafeEqual(expectedBuffer, actualBuffer);
|
|
91
|
+
}
|
|
92
|
+
async handleWebhook(input) {
|
|
93
|
+
if (!this.validateSignature(input.rawBody, input.signature)) {
|
|
94
|
+
throw new Error("Invalid WhatsApp webhook signature.");
|
|
95
|
+
}
|
|
96
|
+
const messages = parseWhatsAppCloudMessages(input.body ?? JSON.parse(input.rawBody));
|
|
97
|
+
const outputs = [];
|
|
98
|
+
for (const message of messages) {
|
|
99
|
+
if (this.processedMessageIds.has(message.messageId)) {
|
|
100
|
+
return { accepted: true, duplicate: true, outputs };
|
|
101
|
+
}
|
|
102
|
+
this.processedMessageIds.add(message.messageId);
|
|
103
|
+
const senderKey = `${input.tenantId}:${message.from}`;
|
|
104
|
+
const normalizedText = message.text.trim();
|
|
105
|
+
if (this.isOptOut(normalizedText)) {
|
|
106
|
+
this.optOutSenders.add(senderKey);
|
|
107
|
+
return { accepted: true, optedOut: true, outputs };
|
|
108
|
+
}
|
|
109
|
+
if (this.isOptIn(normalizedText)) {
|
|
110
|
+
this.optOutSenders.delete(senderKey);
|
|
111
|
+
}
|
|
112
|
+
if (this.optOutSenders.has(senderKey)) {
|
|
113
|
+
return { accepted: true, optedOut: true, outputs };
|
|
114
|
+
}
|
|
115
|
+
if (!this.consumeRateLimit(senderKey)) {
|
|
116
|
+
return { accepted: true, rateLimited: true, outputs };
|
|
117
|
+
}
|
|
118
|
+
const sessionId = this.getOrCreateSession(input.tenantId, message);
|
|
119
|
+
const result = await this.options.runtime.runTurn({
|
|
120
|
+
sessionId,
|
|
121
|
+
content: normalizedText || mediaFallbackText(message.media),
|
|
122
|
+
metadata: {
|
|
123
|
+
surface: "whatsapp",
|
|
124
|
+
channel: "whatsapp-cloud",
|
|
125
|
+
tenantId: input.tenantId,
|
|
126
|
+
phoneNumber: message.from,
|
|
127
|
+
profileName: message.profileName,
|
|
128
|
+
messageId: message.messageId,
|
|
129
|
+
media: message.media
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
outputs.push({ sessionId, content: result.content, metadata: { model: result.model } });
|
|
133
|
+
}
|
|
134
|
+
return { accepted: true, outputs };
|
|
135
|
+
}
|
|
136
|
+
getOrCreateSession(tenantId, message) {
|
|
137
|
+
const existing = this.mapper.getSessionId({
|
|
138
|
+
tenantId,
|
|
139
|
+
channel: "whatsapp-cloud",
|
|
140
|
+
senderId: message.from
|
|
141
|
+
});
|
|
142
|
+
if (existing) return existing;
|
|
143
|
+
const session = this.options.runtime.createSession({
|
|
144
|
+
mode: "ask",
|
|
145
|
+
metadata: {
|
|
146
|
+
surface: "whatsapp",
|
|
147
|
+
channel: "whatsapp-cloud",
|
|
148
|
+
tenantId,
|
|
149
|
+
phoneNumber: message.from,
|
|
150
|
+
profileName: message.profileName
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
this.mapper.setSessionId({
|
|
154
|
+
tenantId,
|
|
155
|
+
channel: "whatsapp-cloud",
|
|
156
|
+
senderId: message.from,
|
|
157
|
+
sessionId: session.id
|
|
158
|
+
});
|
|
159
|
+
return session.id;
|
|
160
|
+
}
|
|
161
|
+
consumeRateLimit(senderKey) {
|
|
162
|
+
const limit = this.options.maxMessagesPerMinutePerSender;
|
|
163
|
+
if (!limit) return true;
|
|
164
|
+
const now = Date.now();
|
|
165
|
+
const recent = (this.senderTimestamps.get(senderKey) ?? []).filter(
|
|
166
|
+
(timestamp) => timestamp > now - 6e4
|
|
167
|
+
);
|
|
168
|
+
if (recent.length >= limit) {
|
|
169
|
+
this.senderTimestamps.set(senderKey, recent);
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
recent.push(now);
|
|
173
|
+
this.senderTimestamps.set(senderKey, recent);
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
isOptOut(text) {
|
|
177
|
+
const keywords = this.options.optOutKeywords ?? ["stop", "unsubscribe", "baja"];
|
|
178
|
+
return keywords.includes(text.toLowerCase());
|
|
179
|
+
}
|
|
180
|
+
isOptIn(text) {
|
|
181
|
+
const keywords = this.options.optInKeywords ?? ["start", "subscribe", "alta"];
|
|
182
|
+
return keywords.includes(text.toLowerCase());
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
function createWhatsAppCloudAdapter(options) {
|
|
186
|
+
return new WhatsAppCloudAdapter(options);
|
|
187
|
+
}
|
|
188
|
+
function createInMemoryChannelSessionMapper() {
|
|
189
|
+
return new InMemoryChannelSessionMapper();
|
|
190
|
+
}
|
|
191
|
+
function sessionKey(input) {
|
|
192
|
+
return `${input.tenantId}:${input.channel}:${input.senderId}`;
|
|
193
|
+
}
|
|
194
|
+
function parseWhatsAppCloudMessages(body) {
|
|
195
|
+
if (!body || typeof body !== "object") return [];
|
|
196
|
+
const entries = Array.isArray(body.entry) ? body.entry : [];
|
|
197
|
+
return entries.flatMap((entry) => {
|
|
198
|
+
const changes = Array.isArray(entry.changes) ? entry.changes : [];
|
|
199
|
+
return changes.flatMap((change) => {
|
|
200
|
+
const value = change.value;
|
|
201
|
+
const contacts = Array.isArray(value?.contacts) ? value.contacts : [];
|
|
202
|
+
const profileByWaId = new Map(
|
|
203
|
+
contacts.map((contact) => [
|
|
204
|
+
contact.wa_id,
|
|
205
|
+
contact.profile?.name
|
|
206
|
+
])
|
|
207
|
+
);
|
|
208
|
+
const messages = Array.isArray(value?.messages) ? value.messages : [];
|
|
209
|
+
return messages.map((message) => normalizeWhatsAppMessage(message, profileByWaId));
|
|
210
|
+
});
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
function normalizeWhatsAppMessage(message, profileByWaId) {
|
|
214
|
+
const record = message;
|
|
215
|
+
const from = String(record["from"] ?? "");
|
|
216
|
+
const type = String(record["type"] ?? "text");
|
|
217
|
+
const text = type === "text" ? String(record["text"]?.body ?? "") : "";
|
|
218
|
+
const media = normalizeMedia(record, type);
|
|
219
|
+
return {
|
|
220
|
+
messageId: String(record["id"] ?? ""),
|
|
221
|
+
from,
|
|
222
|
+
text: text || media?.caption || "",
|
|
223
|
+
profileName: profileByWaId.get(from),
|
|
224
|
+
media
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
function normalizeMedia(record, type) {
|
|
228
|
+
if (!["image", "audio", "video", "document", "sticker"].includes(type)) return void 0;
|
|
229
|
+
const mediaRecord = record[type];
|
|
230
|
+
if (!mediaRecord) return void 0;
|
|
231
|
+
return {
|
|
232
|
+
id: String(mediaRecord["id"] ?? ""),
|
|
233
|
+
type,
|
|
234
|
+
mimeType: typeof mediaRecord["mime_type"] === "string" ? mediaRecord["mime_type"] : void 0,
|
|
235
|
+
caption: typeof mediaRecord["caption"] === "string" ? mediaRecord["caption"] : void 0
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
function mediaFallbackText(media) {
|
|
239
|
+
return media ? `[${media.type}:${media.id}]` : "";
|
|
240
|
+
}
|
|
63
241
|
|
|
64
|
-
export { createHttpAssistantAdapter, createStreamingHttpAssistantAdapter, createWebhookAssistantAdapter, createWhatsAppAssistantAdapter };
|
|
242
|
+
export { InMemoryChannelSessionMapper, WhatsAppCloudAdapter, createHttpAssistantAdapter, createInMemoryChannelSessionMapper, createStreamingHttpAssistantAdapter, createWebhookAssistantAdapter, createWhatsAppAssistantAdapter, createWhatsAppCloudAdapter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EAAU,CAAA,CAAE,EAAA;AACtF,MAAA,OAAO,QAAQ,UAAA,CAAW;AAAA,QACxB,SAAA;AAAA,QACA,SAAS,KAAA,CAAM,OAAA;AAAA,QACf,UAAU,KAAA,CAAM;AAAA,OACjB,CAAA;AAAA,IACH;AAAA,GACF;AACF;AAEO,SAAS,6BAAA,CACd,OAAA,EACA,OAAA,GAAgE,EAAC,EACjD;AAChB,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,QAAQ,EAAA,IAAM,mBAAA;AAAA,IAClB,OAAA,EAAS,QAAQ,OAAA,IAAW,KAAA;AAAA,IAC5B,MAAM,OAAO,KAAA,EAAO;AAClB,MAAA,MAAM,OAAA,GAAU,2BAA2B,OAAO,CAAA;AAClD,MAAA,OAAO,OAAA,CAAQ,cAAc,KAAK,CAAA;AAAA,IACpC;AAAA,GACF;AACF;AAEO,SAAS,+BAA+B,OAAA,EAAiD;AAC9F,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,UAAA;AAAA,IACT,MAAM,cAAc,KAAA,EAAO;AACzB,MAAA,MAAM,OAAA,GAAU,2BAA2B,OAAO,CAAA;AAClD,MAAA,OAAO,QAAQ,aAAA,CAAc;AAAA,QAC3B,SAAS,KAAA,CAAM,IAAA;AAAA,QACf,QAAQ,KAAA,CAAM,IAAA;AAAA,QACd,QAAA,EAAU;AAAA,UACR,OAAA,EAAS,UAAA;AAAA,UACT,OAAA,EAAS,UAAA;AAAA,UACT,aAAa,KAAA,CAAM,IAAA;AAAA,UACnB,aAAa,KAAA,CAAM,WAAA;AAAA,UACnB,WAAW,KAAA,CAAM,SAAA;AAAA,UACjB,GAAG,KAAA,CAAM;AAAA;AACX,OACD,CAAA;AAAA,IACH;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import type { AgentRuntime } from \"../runtime/agent-runtime.js\";\nimport type { RuntimeTurnStreamEvent } from \"../runtime/types.js\";\n\nexport interface ChannelInput {\n sessionId?: string;\n content: string;\n userId?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface ChannelOutput {\n sessionId: string;\n content: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface ChannelAdapter {\n id: string;\n surface: \"web\" | \"whatsapp\" | \"slack\" | \"api\" | \"internal\";\n handle(input: ChannelInput): Promise<ChannelOutput>;\n}\n\nexport interface HttpAssistantAdapter {\n createSession(metadata?: Record<string, unknown>): { sessionId: string };\n handleMessage(input: ChannelInput): Promise<ChannelOutput>;\n}\n\nexport interface StreamingHttpAssistantAdapter extends HttpAssistantAdapter {\n streamMessage(input: ChannelInput): AsyncIterable<RuntimeTurnStreamEvent>;\n}\n\nexport interface WhatsAppInboundMessage {\n from: string;\n text: string;\n messageId?: string;\n profileName?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface WhatsAppAssistantAdapter {\n surface: \"whatsapp\";\n handleInbound(input: WhatsAppInboundMessage): Promise<ChannelOutput>;\n}\n\nexport function createHttpAssistantAdapter(runtime: AgentRuntime): HttpAssistantAdapter {\n return {\n createSession(metadata = {}) {\n const session = runtime.createSession({ mode: \"ask\", metadata });\n return { sessionId: session.id };\n },\n async handleMessage(input) {\n const sessionId =\n input.sessionId ?? runtime.createSession({ mode: \"ask\", metadata: input.metadata }).id;\n const result = await runtime.runTurn({\n sessionId,\n content: input.content,\n metadata: input.metadata,\n });\n return { sessionId, content: result.content, metadata: { model: result.model } };\n },\n };\n}\n\nexport function createStreamingHttpAssistantAdapter(\n runtime: AgentRuntime,\n): StreamingHttpAssistantAdapter {\n const base = createHttpAssistantAdapter(runtime);\n return {\n ...base,\n async *streamMessage(input) {\n const sessionId =\n input.sessionId ?? runtime.createSession({ mode: \"ask\", metadata: input.metadata }).id;\n yield* runtime.streamTurn({\n sessionId,\n content: input.content,\n metadata: input.metadata,\n });\n },\n };\n}\n\nexport function createWebhookAssistantAdapter(\n runtime: AgentRuntime,\n options: { id?: string; surface?: ChannelAdapter[\"surface\"] } = {},\n): ChannelAdapter {\n return {\n id: options.id ?? \"webhook-assistant\",\n surface: options.surface ?? \"api\",\n async handle(input) {\n const adapter = createHttpAssistantAdapter(runtime);\n return adapter.handleMessage(input);\n },\n };\n}\n\nexport function createWhatsAppAssistantAdapter(runtime: AgentRuntime): WhatsAppAssistantAdapter {\n return {\n surface: \"whatsapp\",\n async handleInbound(input) {\n const adapter = createHttpAssistantAdapter(runtime);\n return adapter.handleMessage({\n content: input.text,\n userId: input.from,\n metadata: {\n surface: \"whatsapp\",\n channel: \"whatsapp\",\n phoneNumber: input.from,\n profileName: input.profileName,\n messageId: input.messageId,\n ...input.metadata,\n },\n });\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/index.ts"],"names":[],"mappings":";;;AA+FO,SAAS,2BAA2B,OAAA,EAA6C;AACtF,EAAA,OAAO;AAAA,IACL,aAAA,CAAc,QAAA,GAAW,EAAC,EAAG;AAC3B,MAAA,MAAM,UAAU,OAAA,CAAQ,aAAA,CAAc,EAAE,IAAA,EAAM,KAAA,EAAO,UAAU,CAAA;AAC/D,MAAA,OAAO,EAAE,SAAA,EAAW,OAAA,CAAQ,EAAA,EAAG;AAAA,IACjC,CAAA;AAAA,IACA,MAAM,cAAc,KAAA,EAAO;AACzB,MAAA,MAAM,SAAA,GACJ,KAAA,CAAM,SAAA,IAAa,OAAA,CAAQ,aAAA,CAAc,EAAE,IAAA,EAAM,KAAA,EAAO,QAAA,EAAU,KAAA,CAAM,QAAA,EAAU,CAAA,CAAE,EAAA;AACtF,MAAA,MAAM,MAAA,GAAS,MAAM,OAAA,CAAQ,OAAA,CAAQ;AAAA,QACnC,SAAA;AAAA,QACA,SAAS,KAAA,CAAM,OAAA;AAAA,QACf,UAAU,KAAA,CAAM;AAAA,OACjB,CAAA;AACD,MAAA,OAAO,EAAE,SAAA,EAAW,OAAA,EAAS,MAAA,CAAO,OAAA,EAAS,UAAU,EAAE,KAAA,EAAO,MAAA,CAAO,KAAA,EAAM,EAAE;AAAA,IACjF;AAAA,GACF;AACF;AAEO,SAAS,oCACd,O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AAAA,IACA,IAAA,EAAM,IAAA,IAAQ,KAAA,EAAO,OAAA,IAAW,EAAA;AAAA,IAChC,WAAA,EAAa,aAAA,CAAc,GAAA,CAAI,IAAI,CAAA;AAAA,IACnC;AAAA,GACF;AACF;AAEA,SAAS,cAAA,CACP,QACA,IAAA,EACgC;AAChC,EAAA,IAAI,CAAC,CAAC,OAAA,EAAS,OAAA,EAAS,OAAA,EAAS,UAAA,EAAY,SAAS,CAAA,CAAE,QAAA,CAAS,IAAI,CAAA,EAAG,OAAO,MAAA;AAC/E,EAAA,MAAM,WAAA,GAAc,OAAO,IAAI,CAAA;AAC/B,EAAA,IAAI,CAAC,aAAa,OAAO,MAAA;AACzB,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,MAAA,CAAO,WAAA,CAAY,IAAI,KAAK,EAAE,CAAA;AAAA,IAClC,IAAA;AAAA,IACA,QAAA,EAAU,OAAO,WAAA,CAAY,WAAW,MAAM,QAAA,GAAW,WAAA,CAAY,WAAW,CAAA,GAAI,MAAA;AAAA,IACpF,OAAA,EAAS,OAAO,WAAA,CAAY,SAAS,MAAM,QAAA,GAAW,WAAA,CAAY,SAAS,CAAA,GAAI;AAAA,GACjF;AACF;AAEA,SAAS,kBAAkB,KAAA,EAA+C;AACxE,EAAA,OAAO,QAAQ,CAAA,CAAA,EAAI,KAAA,CAAM,IAAI,CAAA,CAAA,EAAI,KAAA,CAAM,EAAE,CAAA,CAAA,CAAA,GAAM,EAAA;AACjD","file":"index.js","sourcesContent":["import { createHmac, timingSafeEqual } from \"node:crypto\";\nimport type { AgentRuntime } from \"../runtime/agent-runtime.js\";\nimport type { RuntimeTurnStreamEvent } from \"../runtime/types.js\";\n\nexport interface ChannelInput {\n sessionId?: string;\n content: string;\n userId?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface ChannelOutput {\n sessionId: string;\n content: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface ChannelAdapter {\n id: string;\n surface: \"web\" | \"whatsapp\" | \"slack\" | \"api\" | \"internal\";\n handle(input: ChannelInput): Promise<ChannelOutput>;\n}\n\nexport interface HttpAssistantAdapter {\n createSession(metadata?: Record<string, unknown>): { sessionId: string };\n handleMessage(input: ChannelInput): Promise<ChannelOutput>;\n}\n\nexport interface StreamingHttpAssistantAdapter extends HttpAssistantAdapter {\n streamMessage(input: ChannelInput): AsyncIterable<RuntimeTurnStreamEvent>;\n}\n\nexport interface WhatsAppInboundMessage {\n from: string;\n text: string;\n messageId?: string;\n profileName?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface WhatsAppAssistantAdapter {\n surface: \"whatsapp\";\n handleInbound(input: WhatsAppInboundMessage): Promise<ChannelOutput>;\n}\n\nexport interface ChannelSessionMapper {\n getSessionId(input: { tenantId: string; channel: string; senderId: string }): string | undefined;\n setSessionId(input: {\n tenantId: string;\n channel: string;\n senderId: string;\n sessionId: string;\n }): void;\n}\n\nexport interface WhatsAppCloudWebhookInput {\n rawBody: string;\n signature: string | undefined;\n body?: unknown;\n tenantId: string;\n}\n\nexport interface WhatsAppCloudMedia {\n id: string;\n type: \"image\" | \"audio\" | \"video\" | \"document\" | \"sticker\";\n mimeType?: string;\n caption?: string;\n}\n\nexport interface WhatsAppCloudMessage {\n messageId: string;\n from: string;\n text: string;\n profileName?: string;\n media?: WhatsAppCloudMedia;\n}\n\nexport interface WhatsAppCloudAdapterOptions {\n runtime: AgentRuntime;\n appSecret: string;\n tenantId: string;\n sessionMapper?: ChannelSessionMapper;\n maxMessagesPerMinutePerSender?: number;\n optOutKeywords?: string[];\n optInKeywords?: string[];\n}\n\nexport interface WhatsAppCloudWebhookResult {\n accepted: boolean;\n duplicate?: boolean;\n optedOut?: boolean;\n rateLimited?: boolean;\n outputs: ChannelOutput[];\n}\n\nexport function createHttpAssistantAdapter(runtime: AgentRuntime): HttpAssistantAdapter {\n return {\n createSession(metadata = {}) {\n const session = runtime.createSession({ mode: \"ask\", metadata });\n return { sessionId: session.id };\n },\n async handleMessage(input) {\n const sessionId =\n input.sessionId ?? runtime.createSession({ mode: \"ask\", metadata: input.metadata }).id;\n const result = await runtime.runTurn({\n sessionId,\n content: input.content,\n metadata: input.metadata,\n });\n return { sessionId, content: result.content, metadata: { model: result.model } };\n },\n };\n}\n\nexport function createStreamingHttpAssistantAdapter(\n runtime: AgentRuntime,\n): StreamingHttpAssistantAdapter {\n const base = createHttpAssistantAdapter(runtime);\n return {\n ...base,\n async *streamMessage(input) {\n const sessionId =\n input.sessionId ?? runtime.createSession({ mode: \"ask\", metadata: input.metadata }).id;\n yield* runtime.streamTurn({\n sessionId,\n content: input.content,\n metadata: input.metadata,\n });\n },\n };\n}\n\nexport function createWebhookAssistantAdapter(\n runtime: AgentRuntime,\n options: { id?: string; surface?: ChannelAdapter[\"surface\"] } = {},\n): ChannelAdapter {\n return {\n id: options.id ?? \"webhook-assistant\",\n surface: options.surface ?? \"api\",\n async handle(input) {\n const adapter = createHttpAssistantAdapter(runtime);\n return adapter.handleMessage(input);\n },\n };\n}\n\nexport function createWhatsAppAssistantAdapter(runtime: AgentRuntime): WhatsAppAssistantAdapter {\n return {\n surface: \"whatsapp\",\n async handleInbound(input) {\n const adapter = createHttpAssistantAdapter(runtime);\n return adapter.handleMessage({\n content: input.text,\n userId: input.from,\n metadata: {\n surface: \"whatsapp\",\n channel: \"whatsapp\",\n phoneNumber: input.from,\n profileName: input.profileName,\n messageId: input.messageId,\n ...input.metadata,\n },\n });\n },\n };\n}\n\nexport class InMemoryChannelSessionMapper implements ChannelSessionMapper {\n private readonly sessions = new Map<string, string>();\n\n getSessionId(input: { tenantId: string; channel: string; senderId: string }): string | undefined {\n return this.sessions.get(sessionKey(input));\n }\n\n setSessionId(input: {\n tenantId: string;\n channel: string;\n senderId: string;\n sessionId: string;\n }): void {\n this.sessions.set(sessionKey(input), input.sessionId);\n }\n}\n\nexport class WhatsAppCloudAdapter {\n private readonly mapper: ChannelSessionMapper;\n private readonly processedMessageIds = new Set<string>();\n private readonly optOutSenders = new Set<string>();\n private readonly senderTimestamps = new Map<string, number[]>();\n\n constructor(private readonly options: WhatsAppCloudAdapterOptions) {\n this.mapper = options.sessionMapper ?? new InMemoryChannelSessionMapper();\n }\n\n validateSignature(rawBody: string, signature: string | undefined): boolean {\n if (!signature?.startsWith(\"sha256=\")) return false;\n const expected = createHmac(\"sha256\", this.options.appSecret).update(rawBody).digest(\"hex\");\n const actual = signature.slice(\"sha256=\".length);\n const expectedBuffer = Buffer.from(expected, \"hex\");\n const actualBuffer = Buffer.from(actual, \"hex\");\n return (\n expectedBuffer.length === actualBuffer.length && timingSafeEqual(expectedBuffer, actualBuffer)\n );\n }\n\n async handleWebhook(input: WhatsAppCloudWebhookInput): Promise<WhatsAppCloudWebhookResult> {\n if (!this.validateSignature(input.rawBody, input.signature)) {\n throw new Error(\"Invalid WhatsApp webhook signature.\");\n }\n const messages = parseWhatsAppCloudMessages(input.body ?? JSON.parse(input.rawBody));\n const outputs: ChannelOutput[] = [];\n\n for (const message of messages) {\n if (this.processedMessageIds.has(message.messageId)) {\n return { accepted: true, duplicate: true, outputs };\n }\n this.processedMessageIds.add(message.messageId);\n\n const senderKey = `${input.tenantId}:${message.from}`;\n const normalizedText = message.text.trim();\n if (this.isOptOut(normalizedText)) {\n this.optOutSenders.add(senderKey);\n return { accepted: true, optedOut: true, outputs };\n }\n if (this.isOptIn(normalizedText)) {\n this.optOutSenders.delete(senderKey);\n }\n if (this.optOutSenders.has(senderKey)) {\n return { accepted: true, optedOut: true, outputs };\n }\n if (!this.consumeRateLimit(senderKey)) {\n return { accepted: true, rateLimited: true, outputs };\n }\n\n const sessionId = this.getOrCreateSession(input.tenantId, message);\n const result = await this.options.runtime.runTurn({\n sessionId,\n content: normalizedText || mediaFallbackText(message.media),\n metadata: {\n surface: \"whatsapp\",\n channel: \"whatsapp-cloud\",\n tenantId: input.tenantId,\n phoneNumber: message.from,\n profileName: message.profileName,\n messageId: message.messageId,\n media: message.media,\n },\n });\n outputs.push({ sessionId, content: result.content, metadata: { model: result.model } });\n }\n\n return { accepted: true, outputs };\n }\n\n private getOrCreateSession(tenantId: string, message: WhatsAppCloudMessage): string {\n const existing = this.mapper.getSessionId({\n tenantId,\n channel: \"whatsapp-cloud\",\n senderId: message.from,\n });\n if (existing) return existing;\n const session = this.options.runtime.createSession({\n mode: \"ask\",\n metadata: {\n surface: \"whatsapp\",\n channel: \"whatsapp-cloud\",\n tenantId,\n phoneNumber: message.from,\n profileName: message.profileName,\n },\n });\n this.mapper.setSessionId({\n tenantId,\n channel: \"whatsapp-cloud\",\n senderId: message.from,\n sessionId: session.id,\n });\n return session.id;\n }\n\n private consumeRateLimit(senderKey: string): boolean {\n const limit = this.options.maxMessagesPerMinutePerSender;\n if (!limit) return true;\n const now = Date.now();\n const recent = (this.senderTimestamps.get(senderKey) ?? []).filter(\n (timestamp) => timestamp > now - 60_000,\n );\n if (recent.length >= limit) {\n this.senderTimestamps.set(senderKey, recent);\n return false;\n }\n recent.push(now);\n this.senderTimestamps.set(senderKey, recent);\n return true;\n }\n\n private isOptOut(text: string): boolean {\n const keywords = this.options.optOutKeywords ?? [\"stop\", \"unsubscribe\", \"baja\"];\n return keywords.includes(text.toLowerCase());\n }\n\n private isOptIn(text: string): boolean {\n const keywords = this.options.optInKeywords ?? [\"start\", \"subscribe\", \"alta\"];\n return keywords.includes(text.toLowerCase());\n }\n}\n\nexport function createWhatsAppCloudAdapter(\n options: WhatsAppCloudAdapterOptions,\n): WhatsAppCloudAdapter {\n return new WhatsAppCloudAdapter(options);\n}\n\nexport function createInMemoryChannelSessionMapper(): ChannelSessionMapper {\n return new InMemoryChannelSessionMapper();\n}\n\nfunction sessionKey(input: { tenantId: string; channel: string; senderId: string }): string {\n return `${input.tenantId}:${input.channel}:${input.senderId}`;\n}\n\nfunction parseWhatsAppCloudMessages(body: unknown): WhatsAppCloudMessage[] {\n if (!body || typeof body !== \"object\") return [];\n const entries = Array.isArray((body as { entry?: unknown[] }).entry)\n ? (body as { entry: unknown[] }).entry\n : [];\n return entries.flatMap((entry) => {\n const changes = Array.isArray((entry as { changes?: unknown[] }).changes)\n ? (entry as { changes: unknown[] }).changes\n : [];\n return changes.flatMap((change) => {\n const value = (change as { value?: { messages?: unknown[]; contacts?: unknown[] } }).value;\n const contacts = Array.isArray(value?.contacts) ? value.contacts : [];\n const profileByWaId = new Map(\n contacts.map((contact) => [\n (contact as { wa_id?: string }).wa_id,\n (contact as { profile?: { name?: string } }).profile?.name,\n ]),\n );\n const messages = Array.isArray(value?.messages) ? value.messages : [];\n return messages.map((message) => normalizeWhatsAppMessage(message, profileByWaId));\n });\n });\n}\n\nfunction normalizeWhatsAppMessage(\n message: unknown,\n profileByWaId: Map<string | undefined, string | undefined>,\n): WhatsAppCloudMessage {\n const record = message as Record<string, unknown>;\n const from = String(record[\"from\"] ?? \"\");\n const type = String(record[\"type\"] ?? \"text\");\n const text = type === \"text\" ? String((record[\"text\"] as { body?: unknown })?.body ?? \"\") : \"\";\n const media = normalizeMedia(record, type);\n return {\n messageId: String(record[\"id\"] ?? \"\"),\n from,\n text: text || media?.caption || \"\",\n profileName: profileByWaId.get(from),\n media,\n };\n}\n\nfunction normalizeMedia(\n record: Record<string, unknown>,\n type: string,\n): WhatsAppCloudMedia | undefined {\n if (![\"image\", \"audio\", \"video\", \"document\", \"sticker\"].includes(type)) return undefined;\n const mediaRecord = record[type] as Record<string, unknown> | undefined;\n if (!mediaRecord) return undefined;\n return {\n id: String(mediaRecord[\"id\"] ?? \"\"),\n type: type as WhatsAppCloudMedia[\"type\"],\n mimeType: typeof mediaRecord[\"mime_type\"] === \"string\" ? mediaRecord[\"mime_type\"] : undefined,\n caption: typeof mediaRecord[\"caption\"] === \"string\" ? mediaRecord[\"caption\"] : undefined,\n };\n}\n\nfunction mediaFallbackText(media: WhatsAppCloudMedia | undefined): string {\n return media ? `[${media.type}:${media.id}]` : \"\";\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { h as ProviderCatalogEntry, P as ProviderType, M as ModelCatalogEntry, i as ProviderRuntimeCapability, b as ProviderConfig, L as LLMProvider, j as ProviderProbeResult, T as ToolRegistry, k as RuntimeSessionStore, W as WorkflowEngine, l as PermissionPolicy, E as EventLog, c as RuntimeTurnRunner, A as AgentRuntimeOptions, m as AgentRuntimeSnapshot, n as RuntimeSessionCreateOptions, e as RuntimeSession, o as createRetentionCutoffs, f as RuntimeTurnInput, g as RuntimeTurnResult, a as RuntimeTurnStreamEvent, p as RuntimeToolExecutionInput, q as RuntimeToolExecutionResult, r as RuntimeMode } from './context-BLPsKYxc.js';
|
|
2
2
|
|
|
3
3
|
/** Catalog-backed provider/model registry used by runtime consumers. */
|
|
4
4
|
declare class ProviderRegistry {
|
|
@@ -14,6 +14,16 @@ declare class ProviderRegistry {
|
|
|
14
14
|
}
|
|
15
15
|
declare function createProviderRegistry(): ProviderRegistry;
|
|
16
16
|
|
|
17
|
+
interface RuntimeRetentionCleanupOptions {
|
|
18
|
+
dryRun?: boolean;
|
|
19
|
+
now?: Date;
|
|
20
|
+
}
|
|
21
|
+
interface RuntimeRetentionCleanupResult {
|
|
22
|
+
dryRun: boolean;
|
|
23
|
+
cutoffs: ReturnType<typeof createRetentionCutoffs>;
|
|
24
|
+
expiredSessionIds: string[];
|
|
25
|
+
deletedSessionIds: string[];
|
|
26
|
+
}
|
|
17
27
|
/**
|
|
18
28
|
* Reusable runtime facade for wiring providers, tools, permissions, sessions,
|
|
19
29
|
* and observability. It does not own the CLI loop; CLI/headless are adapters on
|
|
@@ -34,6 +44,9 @@ declare class AgentRuntime {
|
|
|
34
44
|
private provider?;
|
|
35
45
|
private readonly runtimeContext?;
|
|
36
46
|
private readonly runtimePolicy?;
|
|
47
|
+
private readonly runtimeHostMode;
|
|
48
|
+
private readonly requestTimestampsBySubject;
|
|
49
|
+
private activeRuns;
|
|
37
50
|
constructor(options: AgentRuntimeOptions);
|
|
38
51
|
initialize(): Promise<void>;
|
|
39
52
|
getModel(): string;
|
|
@@ -43,11 +56,16 @@ declare class AgentRuntime {
|
|
|
43
56
|
createSession(options?: RuntimeSessionCreateOptions): RuntimeSession;
|
|
44
57
|
getSession(sessionId: string): RuntimeSession | undefined;
|
|
45
58
|
listSessions(): RuntimeSession[];
|
|
59
|
+
cleanupRetention(options?: RuntimeRetentionCleanupOptions): RuntimeRetentionCleanupResult;
|
|
46
60
|
runTurn(input: RuntimeTurnInput): Promise<RuntimeTurnResult>;
|
|
47
61
|
streamTurn(input: RuntimeTurnInput): AsyncIterable<RuntimeTurnStreamEvent>;
|
|
48
62
|
executeTool(input: RuntimeToolExecutionInput): Promise<RuntimeToolExecutionResult>;
|
|
49
63
|
assertToolAllowed(mode: RuntimeMode, toolName: string, input?: Record<string, unknown>): boolean;
|
|
64
|
+
private beginRuntimeRequest;
|
|
65
|
+
private assertWithinRateLimit;
|
|
66
|
+
private assertWithinConcurrencyLimit;
|
|
67
|
+
private estimateTurnCost;
|
|
50
68
|
}
|
|
51
69
|
declare function createAgentRuntime(options: AgentRuntimeOptions): Promise<AgentRuntime>;
|
|
52
70
|
|
|
53
|
-
export { AgentRuntime as A, ProviderRegistry as P,
|
|
71
|
+
export { AgentRuntime as A, ProviderRegistry as P, type RuntimeRetentionCleanupOptions as R, type RuntimeRetentionCleanupResult as a, createProviderRegistry as b, createAgentRuntime as c };
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { A as AgentRuntime } from './agent-runtime-
|
|
1
|
+
import { P as ProviderType, b as ProviderConfig, L as LLMProvider, T as ToolRegistry, E as EventLog, c as RuntimeTurnRunner, R as RuntimeRequestContext, d as RuntimePolicy, e as RuntimeSession, f as RuntimeTurnInput, g as RuntimeTurnResult } from './context-BLPsKYxc.js';
|
|
2
|
+
import { A as AgentRuntime } from './agent-runtime-BJeNjVuk.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
|
|
5
5
|
type GuardrailSeverity = "info" | "warning" | "blocked";
|
|
6
|
-
type GuardrailStage = "input" | "output" | "tool";
|
|
6
|
+
type GuardrailStage = "input" | "retrieved-document" | "tool-input" | "tool-output" | "final-output" | "output" | "tool";
|
|
7
|
+
type GuardrailAction = "allow" | "warn" | "block";
|
|
7
8
|
interface GuardrailFinding {
|
|
8
9
|
id: string;
|
|
9
10
|
stage: GuardrailStage;
|
|
@@ -29,7 +30,29 @@ interface GuardrailConfig {
|
|
|
29
30
|
maxOutputChars?: number;
|
|
30
31
|
secretRedaction?: SecretRedactionConfig;
|
|
31
32
|
promptInjectionDetection?: boolean;
|
|
33
|
+
promptInjectionAction?: GuardrailAction;
|
|
32
34
|
topicBoundary?: TopicBoundaryConfig;
|
|
35
|
+
policyProvider?: PolicyAsCodeProvider;
|
|
36
|
+
}
|
|
37
|
+
interface PolicyAsCodeProvider {
|
|
38
|
+
evaluate(input: {
|
|
39
|
+
stage: GuardrailStage;
|
|
40
|
+
content: string;
|
|
41
|
+
findings: GuardrailFinding[];
|
|
42
|
+
}): Promise<GuardrailFinding[]> | GuardrailFinding[];
|
|
43
|
+
}
|
|
44
|
+
interface GuardrailPipelineStep {
|
|
45
|
+
stage: GuardrailStage;
|
|
46
|
+
content: string;
|
|
47
|
+
config?: GuardrailConfig;
|
|
48
|
+
}
|
|
49
|
+
interface GuardrailPipelineResult {
|
|
50
|
+
allowed: boolean;
|
|
51
|
+
outputs: Array<{
|
|
52
|
+
stage: GuardrailStage;
|
|
53
|
+
content: string;
|
|
54
|
+
}>;
|
|
55
|
+
findings: GuardrailFinding[];
|
|
33
56
|
}
|
|
34
57
|
declare const defaultPublicGuardrails: GuardrailConfig;
|
|
35
58
|
declare function redactSecrets(content: string, config?: SecretRedactionConfig): {
|
|
@@ -37,6 +60,7 @@ declare function redactSecrets(content: string, config?: SecretRedactionConfig):
|
|
|
37
60
|
findings: GuardrailFinding[];
|
|
38
61
|
};
|
|
39
62
|
declare function runGuardrails(stage: GuardrailStage, content: string, config?: GuardrailConfig): GuardrailResult;
|
|
63
|
+
declare function runGuardrailPipeline(steps: GuardrailPipelineStep[], config?: GuardrailConfig): Promise<GuardrailPipelineResult>;
|
|
40
64
|
declare function validateStructuredOutput(output: unknown, schema: z.ZodTypeAny | undefined): GuardrailFinding[];
|
|
41
65
|
|
|
42
66
|
type AgentDeploymentSurface = "cli" | "web" | "whatsapp" | "slack" | "api" | "internal";
|
|
@@ -98,4 +122,4 @@ declare function createSafeToolRegistry(allowedTools: string[], source?: ToolReg
|
|
|
98
122
|
declare function createAgentFromBlueprint(blueprint: AgentBlueprint, options: AgentRuntimeFactoryOptions): Promise<BlueprintAgent>;
|
|
99
123
|
declare function createBaseBlueprint(input: Omit<AgentBlueprint, "guardrails" | "memory" | "approval" | "observability"> & Partial<Pick<AgentBlueprint, "guardrails" | "memory" | "approval" | "observability">>): AgentBlueprint;
|
|
100
124
|
|
|
101
|
-
export { type
|
|
125
|
+
export { type AgentPreset as A, type BlueprintAgent as B, type GuardrailAction as G, type MemoryConfig as M, type ObservabilityConfig as O, type PolicyAsCodeProvider as P, type SecretRedactionConfig as S, type TopicBoundaryConfig as T, type AgentActionMode as a, type AgentBlueprint as b, type AgentDeploymentSurface as c, type AgentMaturity as d, type AgentRuntimeFactoryOptions as e, type ApprovalPolicy as f, type GuardrailConfig as g, type GuardrailFinding as h, type GuardrailPipelineResult as i, type GuardrailPipelineStep as j, type GuardrailResult as k, type GuardrailSeverity as l, type GuardrailStage as m, createAgentFromBlueprint as n, createBaseBlueprint as o, createSafeToolRegistry as p, defaultPublicGuardrails as q, mapActionModeToRuntimeMode as r, redactSecrets as s, runGuardrailPipeline as t, runGuardrails as u, validateStructuredOutput as v };
|