@agent-native/core 0.72.3 → 0.72.4
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/corpus/README.md +1 -1
- package/corpus/core/CHANGELOG.md +10 -0
- package/corpus/core/package.json +6 -6
- package/corpus/core/src/a2a/client.ts +7 -3
- package/corpus/core/src/client/api-path.ts +28 -0
- package/corpus/core/src/client/embed-auth.ts +26 -0
- package/corpus/core/src/client/mcp-app-host.ts +6 -0
- package/corpus/core/src/client/mcp-apps/McpAppRenderer.tsx +227 -33
- package/corpus/core/src/client/resources/use-mcp-servers.ts +1 -0
- package/corpus/core/src/client/settings/DemoModeSection.tsx +3 -1
- package/corpus/core/src/demo/fetch-interceptor.ts +1 -1
- package/corpus/core/src/embedding/agent.ts +6 -1
- package/corpus/core/src/embedding/bridge.ts +34 -1
- package/corpus/core/src/mcp/build-server.ts +38 -10
- package/corpus/core/src/mcp/embed-app.ts +120 -45
- package/corpus/core/src/mcp/index.ts +5 -0
- package/corpus/core/src/mcp/org-directory.ts +70 -11
- package/corpus/core/src/mcp/server.ts +14 -0
- package/corpus/core/src/mcp-client/config.ts +12 -0
- package/corpus/core/src/mcp-client/index.ts +2 -0
- package/corpus/core/src/mcp-client/manager.ts +268 -9
- package/corpus/core/src/mcp-client/remote-store.ts +154 -0
- package/corpus/core/src/mcp-client/routes.ts +2 -0
- package/corpus/core/src/server/agent-chat-plugin.ts +8 -0
- package/corpus/core/src/server/index.ts +1 -0
- package/corpus/core/src/shared/mcp-embed-headers.ts +44 -3
- package/corpus/core/src/vite/client.ts +53 -0
- package/corpus/templates/assets/.agents/skills/a2a-assets/SKILL.md +17 -10
- package/corpus/templates/assets/.agents/skills/asset-generation/SKILL.md +15 -6
- package/corpus/templates/assets/AGENTS.md +7 -5
- package/corpus/templates/assets/actions/generate-asset.ts +161 -0
- package/corpus/templates/assets/actions/list-assets.ts +4 -2
- package/corpus/templates/assets/actions/open-asset-picker.ts +84 -3
- package/corpus/templates/assets/app/routes/library.tsx +243 -40
- package/corpus/templates/clips/desktop/src-tauri/src/native_speech.rs +9 -0
- package/corpus/templates/design/AGENTS.md +10 -5
- package/corpus/templates/design/actions/connect-assets-mcp.ts +131 -0
- package/corpus/templates/design/actions/insert-asset.ts +219 -0
- package/corpus/templates/design/actions/view-screen.ts +3 -1
- package/corpus/templates/design/app/components/editor/PromptDialog.tsx +1 -1
- package/corpus/templates/design/app/pages/DesignEditor.tsx +53 -0
- package/corpus/templates/design/server/plugins/agent-chat.ts +5 -1
- package/corpus/templates/design/server/plugins/assets-mcp.ts +60 -0
- package/dist/a2a/client.d.ts +1 -0
- package/dist/a2a/client.d.ts.map +1 -1
- package/dist/a2a/client.js +5 -3
- package/dist/a2a/client.js.map +1 -1
- package/dist/client/api-path.d.ts.map +1 -1
- package/dist/client/api-path.js +27 -0
- package/dist/client/api-path.js.map +1 -1
- package/dist/client/embed-auth.d.ts.map +1 -1
- package/dist/client/embed-auth.js +27 -0
- package/dist/client/embed-auth.js.map +1 -1
- package/dist/client/mcp-app-host.d.ts.map +1 -1
- package/dist/client/mcp-app-host.js +5 -0
- package/dist/client/mcp-app-host.js.map +1 -1
- package/dist/client/mcp-apps/McpAppRenderer.d.ts +1 -0
- package/dist/client/mcp-apps/McpAppRenderer.d.ts.map +1 -1
- package/dist/client/mcp-apps/McpAppRenderer.js +179 -33
- package/dist/client/mcp-apps/McpAppRenderer.js.map +1 -1
- package/dist/client/resources/use-mcp-servers.d.ts +1 -0
- package/dist/client/resources/use-mcp-servers.d.ts.map +1 -1
- package/dist/client/resources/use-mcp-servers.js.map +1 -1
- package/dist/client/settings/DemoModeSection.d.ts.map +1 -1
- package/dist/client/settings/DemoModeSection.js +3 -1
- package/dist/client/settings/DemoModeSection.js.map +1 -1
- package/dist/demo/fetch-interceptor.js +1 -1
- package/dist/demo/fetch-interceptor.js.map +1 -1
- package/dist/embedding/agent.d.ts +1 -1
- package/dist/embedding/agent.d.ts.map +1 -1
- package/dist/embedding/agent.js +1 -1
- package/dist/embedding/agent.js.map +1 -1
- package/dist/embedding/bridge.d.ts.map +1 -1
- package/dist/embedding/bridge.js +27 -1
- package/dist/embedding/bridge.js.map +1 -1
- package/dist/extensions/schema.d.ts +2 -2
- package/dist/mcp/build-server.d.ts +2 -0
- package/dist/mcp/build-server.d.ts.map +1 -1
- package/dist/mcp/build-server.js +32 -9
- package/dist/mcp/build-server.js.map +1 -1
- package/dist/mcp/embed-app.d.ts.map +1 -1
- package/dist/mcp/embed-app.js +120 -45
- package/dist/mcp/embed-app.js.map +1 -1
- package/dist/mcp/index.d.ts +1 -0
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/index.js +1 -0
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/org-directory.d.ts +1 -0
- package/dist/mcp/org-directory.d.ts.map +1 -1
- package/dist/mcp/org-directory.js +59 -11
- package/dist/mcp/org-directory.js.map +1 -1
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +9 -0
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp-client/config.d.ts +12 -0
- package/dist/mcp-client/config.d.ts.map +1 -1
- package/dist/mcp-client/config.js.map +1 -1
- package/dist/mcp-client/index.d.ts +1 -1
- package/dist/mcp-client/index.d.ts.map +1 -1
- package/dist/mcp-client/index.js +1 -1
- package/dist/mcp-client/index.js.map +1 -1
- package/dist/mcp-client/manager.d.ts +2 -0
- package/dist/mcp-client/manager.d.ts.map +1 -1
- package/dist/mcp-client/manager.js +201 -9
- package/dist/mcp-client/manager.js.map +1 -1
- package/dist/mcp-client/remote-store.d.ts +27 -0
- package/dist/mcp-client/remote-store.d.ts.map +1 -1
- package/dist/mcp-client/remote-store.js +105 -0
- package/dist/mcp-client/remote-store.js.map +1 -1
- package/dist/mcp-client/routes.d.ts +1 -0
- package/dist/mcp-client/routes.d.ts.map +1 -1
- package/dist/mcp-client/routes.js +1 -0
- package/dist/mcp-client/routes.js.map +1 -1
- package/dist/provider-api/actions/github-repo-files.d.ts +2 -2
- package/dist/provider-api/actions/query-staged-dataset.d.ts +3 -3
- package/dist/provider-api/corpus-jobs.d.ts +8 -8
- package/dist/server/agent-chat-plugin.d.ts +2 -0
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +8 -0
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/index.js.map +1 -1
- package/dist/shared/mcp-embed-headers.d.ts +3 -1
- package/dist/shared/mcp-embed-headers.d.ts.map +1 -1
- package/dist/shared/mcp-embed-headers.js +40 -3
- package/dist/shared/mcp-embed-headers.js.map +1 -1
- package/dist/sharing/actions/list-resource-shares.d.ts +1 -1
- package/dist/sharing/actions/set-resource-visibility.d.ts +2 -2
- package/dist/sharing/actions/share-resource.d.ts +1 -1
- package/dist/sharing/schema.d.ts +1 -1
- package/dist/vite/client.d.ts.map +1 -1
- package/dist/vite/client.js +44 -0
- package/dist/vite/client.js.map +1 -1
- package/package.json +6 -6
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { defineAction } from "@agent-native/core";
|
|
2
|
+
import { readAppStateForCurrentTab } from "@agent-native/core/application-state";
|
|
3
|
+
import {
|
|
4
|
+
hasCollabState,
|
|
5
|
+
getText,
|
|
6
|
+
applyText,
|
|
7
|
+
seedFromText,
|
|
8
|
+
} from "@agent-native/core/collab";
|
|
9
|
+
import { accessFilter, assertAccess } from "@agent-native/core/sharing";
|
|
10
|
+
import { and, eq } from "drizzle-orm";
|
|
11
|
+
import { z } from "zod";
|
|
12
|
+
import { getDb, schema } from "../server/db/index.js";
|
|
13
|
+
|
|
14
|
+
const schemaInput = z.object({
|
|
15
|
+
assetUrl: z
|
|
16
|
+
.string()
|
|
17
|
+
.url()
|
|
18
|
+
.refine((value) => {
|
|
19
|
+
try {
|
|
20
|
+
const protocol = new URL(value).protocol;
|
|
21
|
+
return protocol === "http:" || protocol === "https:";
|
|
22
|
+
} catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}, "Asset URL must use http or https.")
|
|
26
|
+
.describe("Chosen asset image/video URL."),
|
|
27
|
+
assetId: z.string().optional().describe("Chosen Assets asset id."),
|
|
28
|
+
title: z.string().optional().describe("Human-readable asset title."),
|
|
29
|
+
altText: z.string().optional().describe("Alt text for an image asset."),
|
|
30
|
+
mediaType: z.enum(["image", "video"]).default("image"),
|
|
31
|
+
designId: z
|
|
32
|
+
.string()
|
|
33
|
+
.optional()
|
|
34
|
+
.describe("Design id. Defaults to the current editor navigation state."),
|
|
35
|
+
fileId: z
|
|
36
|
+
.string()
|
|
37
|
+
.optional()
|
|
38
|
+
.describe("Design file id. Defaults to the active editor file."),
|
|
39
|
+
ownerId: z
|
|
40
|
+
.string()
|
|
41
|
+
.optional()
|
|
42
|
+
.describe("Design editor selection owner token from current screen state."),
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
function stringFromState(state: unknown, key: string): string | undefined {
|
|
46
|
+
if (!state || typeof state !== "object") return undefined;
|
|
47
|
+
const value = (state as Record<string, unknown>)[key];
|
|
48
|
+
return typeof value === "string" && value ? value : undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function escapeHtml(value: string): string {
|
|
52
|
+
return value
|
|
53
|
+
.replace(/&/g, "&")
|
|
54
|
+
.replace(/</g, "<")
|
|
55
|
+
.replace(/>/g, ">")
|
|
56
|
+
.replace(/"/g, """);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function insertBeforeClosingTag(
|
|
60
|
+
html: string,
|
|
61
|
+
closingTag: "main" | "body",
|
|
62
|
+
snippet: string,
|
|
63
|
+
): string | null {
|
|
64
|
+
const pattern = new RegExp(`</${closingTag}>`, "i");
|
|
65
|
+
if (!pattern.test(html)) return null;
|
|
66
|
+
return html.replace(pattern, `${snippet}\n</${closingTag}>`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function appendAssetMarkup(
|
|
70
|
+
html: string,
|
|
71
|
+
args: z.infer<typeof schemaInput>,
|
|
72
|
+
): string {
|
|
73
|
+
const label = args.title?.trim() || args.altText?.trim() || "Generated asset";
|
|
74
|
+
const escapedUrl = escapeHtml(args.assetUrl);
|
|
75
|
+
const escapedLabel = escapeHtml(label);
|
|
76
|
+
const assetIdAttr = args.assetId
|
|
77
|
+
? ` data-asset-id="${escapeHtml(args.assetId)}"`
|
|
78
|
+
: "";
|
|
79
|
+
const media =
|
|
80
|
+
args.mediaType === "video"
|
|
81
|
+
? `<video src="${escapedUrl}" controls class="w-full rounded-xl object-cover"></video>`
|
|
82
|
+
: `<img src="${escapedUrl}" alt="${escapeHtml(args.altText?.trim() || label)}" class="w-full rounded-xl object-cover" />`;
|
|
83
|
+
const snippet = `
|
|
84
|
+
<section class="mx-auto my-8 max-w-5xl px-4" data-agent-native-asset${assetIdAttr}>
|
|
85
|
+
<figure class="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
|
|
86
|
+
${media}
|
|
87
|
+
<figcaption class="px-4 py-3 text-sm text-slate-600">${escapedLabel}</figcaption>
|
|
88
|
+
</figure>
|
|
89
|
+
</section>`;
|
|
90
|
+
|
|
91
|
+
return (
|
|
92
|
+
insertBeforeClosingTag(html, "main", snippet) ??
|
|
93
|
+
insertBeforeClosingTag(html, "body", snippet) ??
|
|
94
|
+
`${html}\n${snippet}`
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function resolveTarget(args: z.infer<typeof schemaInput>) {
|
|
99
|
+
const [navigation, selection] = await Promise.all([
|
|
100
|
+
readAppStateForCurrentTab("navigation").catch(() => null),
|
|
101
|
+
readAppStateForCurrentTab("design-selection").catch(() => null),
|
|
102
|
+
]);
|
|
103
|
+
const navigationDesignId = stringFromState(navigation, "designId");
|
|
104
|
+
const selectionDesignId = stringFromState(selection, "designId");
|
|
105
|
+
const selectionOwnerId = stringFromState(selection, "ownerId");
|
|
106
|
+
const selectionMatchesOwner =
|
|
107
|
+
Boolean(args.ownerId) && selectionOwnerId === args.ownerId;
|
|
108
|
+
// Prefer the owner-matched selection over generic navigation so a tab-scoped
|
|
109
|
+
// picker handoff lands in the design that produced it.
|
|
110
|
+
const designId =
|
|
111
|
+
args.designId ??
|
|
112
|
+
(selectionMatchesOwner ? selectionDesignId : undefined) ??
|
|
113
|
+
navigationDesignId;
|
|
114
|
+
const canUseSelection =
|
|
115
|
+
selectionMatchesOwner &&
|
|
116
|
+
Boolean(designId) &&
|
|
117
|
+
selectionDesignId === designId;
|
|
118
|
+
const navigationActiveFileId =
|
|
119
|
+
designId && navigationDesignId === designId
|
|
120
|
+
? stringFromState(navigation, "activeFileId")
|
|
121
|
+
: undefined;
|
|
122
|
+
return {
|
|
123
|
+
designId,
|
|
124
|
+
fileId:
|
|
125
|
+
args.fileId ??
|
|
126
|
+
(canUseSelection
|
|
127
|
+
? stringFromState(selection, "activeFileId")
|
|
128
|
+
: undefined) ??
|
|
129
|
+
navigationActiveFileId,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function isHtmlFile(file: {
|
|
134
|
+
fileType: string | null;
|
|
135
|
+
filename: string | null;
|
|
136
|
+
}): boolean {
|
|
137
|
+
return file.fileType === "html" || file.filename?.endsWith(".html") === true;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export default defineAction({
|
|
141
|
+
description:
|
|
142
|
+
"Insert a chosen Assets image or video URL into a Design file. Use this after the Assets picker returns chooseAsset/chooseImage context; pass designId/fileId directly when known, or pass ownerId from view-screen.designSelection when targeting the current editor selection.",
|
|
143
|
+
schema: schemaInput,
|
|
144
|
+
publicAgent: { expose: true, readOnly: false, requiresAuth: true },
|
|
145
|
+
run: async (args) => {
|
|
146
|
+
const target = await resolveTarget(args);
|
|
147
|
+
if (!target.designId) {
|
|
148
|
+
throw new Error(
|
|
149
|
+
"No active design found. Open a design or pass designId.",
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const db = getDb();
|
|
154
|
+
const files = await db
|
|
155
|
+
.select({
|
|
156
|
+
id: schema.designFiles.id,
|
|
157
|
+
designId: schema.designFiles.designId,
|
|
158
|
+
filename: schema.designFiles.filename,
|
|
159
|
+
fileType: schema.designFiles.fileType,
|
|
160
|
+
content: schema.designFiles.content,
|
|
161
|
+
})
|
|
162
|
+
.from(schema.designFiles)
|
|
163
|
+
.innerJoin(
|
|
164
|
+
schema.designs,
|
|
165
|
+
eq(schema.designFiles.designId, schema.designs.id),
|
|
166
|
+
)
|
|
167
|
+
.where(
|
|
168
|
+
and(
|
|
169
|
+
eq(schema.designFiles.designId, target.designId),
|
|
170
|
+
accessFilter(schema.designs, schema.designShares),
|
|
171
|
+
),
|
|
172
|
+
);
|
|
173
|
+
const requestedFile = files.find(
|
|
174
|
+
(candidate) => candidate.id === target.fileId,
|
|
175
|
+
);
|
|
176
|
+
const file =
|
|
177
|
+
requestedFile && isHtmlFile(requestedFile)
|
|
178
|
+
? requestedFile
|
|
179
|
+
: (files.find(isHtmlFile) ?? null);
|
|
180
|
+
if (!file) throw new Error("No editable HTML design file found.");
|
|
181
|
+
await assertAccess("design", file.designId, "editor");
|
|
182
|
+
|
|
183
|
+
let base = file.content ?? "";
|
|
184
|
+
try {
|
|
185
|
+
if (await hasCollabState(file.id)) {
|
|
186
|
+
const live = await getText(file.id, "content");
|
|
187
|
+
if (typeof live === "string") base = live;
|
|
188
|
+
}
|
|
189
|
+
} catch {
|
|
190
|
+
// Collab read is best-effort; fall back to stored content.
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const content = appendAssetMarkup(base, args);
|
|
194
|
+
const now = new Date().toISOString();
|
|
195
|
+
await db
|
|
196
|
+
.update(schema.designFiles)
|
|
197
|
+
.set({ content, updatedAt: now })
|
|
198
|
+
.where(eq(schema.designFiles.id, file.id));
|
|
199
|
+
await db
|
|
200
|
+
.update(schema.designs)
|
|
201
|
+
.set({ updatedAt: now })
|
|
202
|
+
.where(eq(schema.designs.id, file.designId));
|
|
203
|
+
|
|
204
|
+
if (await hasCollabState(file.id)) {
|
|
205
|
+
await applyText(file.id, content, "content", "agent");
|
|
206
|
+
} else {
|
|
207
|
+
await seedFromText(file.id, content);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return {
|
|
211
|
+
designId: file.designId,
|
|
212
|
+
fileId: file.id,
|
|
213
|
+
filename: file.filename,
|
|
214
|
+
inserted: true,
|
|
215
|
+
assetId: args.assetId ?? null,
|
|
216
|
+
assetUrl: args.assetUrl,
|
|
217
|
+
};
|
|
218
|
+
},
|
|
219
|
+
});
|
|
@@ -20,9 +20,10 @@ export default defineAction({
|
|
|
20
20
|
schema: z.object({}),
|
|
21
21
|
http: false,
|
|
22
22
|
run: async () => {
|
|
23
|
-
const [navigation, designVariants] = await Promise.all([
|
|
23
|
+
const [navigation, designVariants, designSelection] = await Promise.all([
|
|
24
24
|
readAppStateForCurrentTab("navigation"),
|
|
25
25
|
readAppState("design-variants"),
|
|
26
|
+
readAppStateForCurrentTab("design-selection"),
|
|
26
27
|
]);
|
|
27
28
|
const designId =
|
|
28
29
|
navigation &&
|
|
@@ -37,6 +38,7 @@ export default defineAction({
|
|
|
37
38
|
|
|
38
39
|
const screen: Record<string, unknown> = {};
|
|
39
40
|
if (navigation) screen.navigation = navigation;
|
|
41
|
+
if (designSelection) screen.designSelection = designSelection;
|
|
40
42
|
if (showQuestions) {
|
|
41
43
|
screen.pendingQuestions = showQuestions;
|
|
42
44
|
screen.note =
|
|
@@ -398,7 +398,7 @@ export default function PromptPopover({
|
|
|
398
398
|
return;
|
|
399
399
|
}
|
|
400
400
|
|
|
401
|
-
if (name !== "chooseImage") return;
|
|
401
|
+
if (name !== "chooseImage" && name !== "chooseAsset") return;
|
|
402
402
|
const url = pickedAssetImageSource(payload);
|
|
403
403
|
if (!url) {
|
|
404
404
|
toast.error("Assets did not return an image URL.");
|
|
@@ -43,6 +43,9 @@ import {
|
|
|
43
43
|
ShareButton,
|
|
44
44
|
isEmbedAuthActive,
|
|
45
45
|
sendToAgentChat,
|
|
46
|
+
getBrowserTabId,
|
|
47
|
+
readClientAppState,
|
|
48
|
+
setClientAppState,
|
|
46
49
|
useReconciledState,
|
|
47
50
|
usePresence,
|
|
48
51
|
useFollowUser,
|
|
@@ -113,6 +116,16 @@ import { cn } from "@/lib/utils";
|
|
|
113
116
|
import { toast } from "sonner";
|
|
114
117
|
|
|
115
118
|
const TAB_ID = generateTabId();
|
|
119
|
+
|
|
120
|
+
// Selection is tab-scoped (like navigation) so a second editor tab cannot
|
|
121
|
+
// overwrite this tab's selection context. The global key is mirrored as a
|
|
122
|
+
// fallback for CLI/external agents that do not send a browser tab id.
|
|
123
|
+
function designSelectionStateKeys(): string[] {
|
|
124
|
+
const tabId = getBrowserTabId();
|
|
125
|
+
return tabId
|
|
126
|
+
? [`design-selection:${tabId}`, "design-selection"]
|
|
127
|
+
: ["design-selection"];
|
|
128
|
+
}
|
|
116
129
|
// Stable symbol used as the Yjs transaction origin for all local user edits.
|
|
117
130
|
// The UndoManager tracks only this origin so remote peers' and the agent's
|
|
118
131
|
// edits are never undone by this user's Cmd+Z.
|
|
@@ -317,6 +330,8 @@ export default function DesignEditor() {
|
|
|
317
330
|
const [canUndo, setCanUndo] = useState(false);
|
|
318
331
|
const [canRedo, setCanRedo] = useState(false);
|
|
319
332
|
const undoManagerRef = useRef<Y.UndoManager | null>(null);
|
|
333
|
+
const persistedSelectionStateRef = useRef<string | null>(null);
|
|
334
|
+
const designSelectionOwnerIdRef = useRef(`${TAB_ID}:${generateTabId()}`);
|
|
320
335
|
const [tweakSaveActive, setTweakSaveActive] = useState(false);
|
|
321
336
|
// Shared visual-editor modes (overlays the iframe). drawMode toggles the
|
|
322
337
|
// pencil overlay, pinMode lets the user drop comment pins. They're
|
|
@@ -340,6 +355,26 @@ export default function DesignEditor() {
|
|
|
340
355
|
const [promptDesignSystemId, setPromptDesignSystemId] = useState<
|
|
341
356
|
string | null | undefined
|
|
342
357
|
>(undefined);
|
|
358
|
+
|
|
359
|
+
useEffect(() => {
|
|
360
|
+
return () => {
|
|
361
|
+
void (async () => {
|
|
362
|
+
const keys = designSelectionStateKeys();
|
|
363
|
+
const current = await readClientAppState(keys[0]).catch(() => null);
|
|
364
|
+
const ownerId =
|
|
365
|
+
current && typeof current === "object"
|
|
366
|
+
? (current as { ownerId?: unknown }).ownerId
|
|
367
|
+
: undefined;
|
|
368
|
+
if (ownerId !== designSelectionOwnerIdRef.current) return;
|
|
369
|
+
persistedSelectionStateRef.current = null;
|
|
370
|
+
for (const key of designSelectionStateKeys()) {
|
|
371
|
+
await setClientAppState(key, null, {
|
|
372
|
+
keepalive: true,
|
|
373
|
+
}).catch(() => {});
|
|
374
|
+
}
|
|
375
|
+
})();
|
|
376
|
+
};
|
|
377
|
+
}, []);
|
|
343
378
|
// When generation stalls we keep the original prompt + files around so the
|
|
344
379
|
// user can retry with one click instead of re-typing. Cleared as soon as the
|
|
345
380
|
// user kicks off a new run (retry or fresh prompt).
|
|
@@ -1414,6 +1449,24 @@ export default function DesignEditor() {
|
|
|
1414
1449
|
mode,
|
|
1415
1450
|
};
|
|
1416
1451
|
(window as any).__designSelection = selection;
|
|
1452
|
+
const persistedSelection = {
|
|
1453
|
+
designId: selection.designId,
|
|
1454
|
+
designTitle: selection.designTitle,
|
|
1455
|
+
activeFileId: selection.activeFileId,
|
|
1456
|
+
activeFilename: selection.activeFilename,
|
|
1457
|
+
selectedElement: selection.selectedElement,
|
|
1458
|
+
mode: selection.mode,
|
|
1459
|
+
ownerId: designSelectionOwnerIdRef.current,
|
|
1460
|
+
};
|
|
1461
|
+
const persistedKey = JSON.stringify(persistedSelection);
|
|
1462
|
+
if (persistedSelectionStateRef.current !== persistedKey) {
|
|
1463
|
+
persistedSelectionStateRef.current = persistedKey;
|
|
1464
|
+
for (const key of designSelectionStateKeys()) {
|
|
1465
|
+
setClientAppState(key, persistedSelection, {
|
|
1466
|
+
keepalive: true,
|
|
1467
|
+
}).catch(() => {});
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1417
1470
|
const el = document.documentElement;
|
|
1418
1471
|
el.dataset.designId = id;
|
|
1419
1472
|
if (activeFile?.id) el.dataset.fileId = activeFile.id;
|
|
@@ -14,6 +14,8 @@ const INITIAL_TOOL_NAMES = [
|
|
|
14
14
|
"edit-design",
|
|
15
15
|
"generate-design",
|
|
16
16
|
"present-design-variants",
|
|
17
|
+
"insert-asset",
|
|
18
|
+
"connect-assets-mcp",
|
|
17
19
|
"apply-tweaks",
|
|
18
20
|
"update-design",
|
|
19
21
|
"list-files",
|
|
@@ -38,5 +40,7 @@ export default createAgentChatPlugin({
|
|
|
38
40
|
|
|
39
41
|
Provider-specific Design actions are shortcuts, not limits. If a first-class action cannot express the exact GitHub endpoint, repository tree query, code search, issue or pull request query, request body, pagination mode, payload shape, metadata field, or API version needed, call provider-api-catalog and provider-api-docs as needed, then call provider-api-request against the real GitHub API. Use the raw provider API escape hatch instead of weakening the answer or claiming Design cannot do something the underlying GitHub API can do.
|
|
40
42
|
|
|
41
|
-
Design's GitHub provider API uses the saved GITHUB_TOKEN secret when present. Never ask the user to paste tokens into chat. For large GitHub search results or repository scans, pass stageAs and pagination options to provider-api-request, then use query-staged-dataset to count, filter, group, or project the staged rows
|
|
43
|
+
Design's GitHub provider API uses the saved GITHUB_TOKEN secret when present. Never ask the user to paste tokens into chat. For large GitHub search results or repository scans, pass stageAs and pagination options to provider-api-request, then use query-staged-dataset to count, filter, group, or project the staged rows.
|
|
44
|
+
|
|
45
|
+
For raster image generation, use available first-party Assets MCP tools such as generate-asset instead of placeholders or generic stock-image descriptions. When the Assets picker returns selectedAsset/chooseAsset/chooseImage context while a design is open, call insert-asset with the chosen asset URL/id, then refine placement with normal Design edit tools if needed. Preserve Assets assetId, runId, and URLs verbatim.`,
|
|
42
46
|
});
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { defineNitroPlugin } from "@agent-native/core/server";
|
|
2
|
+
import { registerOnboardingStep } from "@agent-native/core/onboarding";
|
|
3
|
+
import {
|
|
4
|
+
isFirstPartyRemoteEndpointTrusted,
|
|
5
|
+
listRemoteServers,
|
|
6
|
+
} from "@agent-native/core/mcp-client";
|
|
7
|
+
import { fetchOrgApps } from "@agent-native/core/mcp";
|
|
8
|
+
|
|
9
|
+
const SERVER_NAME = "assets";
|
|
10
|
+
|
|
11
|
+
async function hasAssetsServer(orgId: string) {
|
|
12
|
+
const apps = await fetchOrgApps({ selfId: "design" });
|
|
13
|
+
const assets = apps.find((app) => app.id === "assets");
|
|
14
|
+
if (!assets?.url) return false;
|
|
15
|
+
const currentUrl = `${assets.url.replace(/\/+$/, "")}/_agent-native/mcp`;
|
|
16
|
+
const servers = await listRemoteServers("org", orgId);
|
|
17
|
+
for (const server of servers) {
|
|
18
|
+
if (server.name !== SERVER_NAME || server.firstParty !== true) continue;
|
|
19
|
+
if (server.url.replace(/\/+$/, "") !== currentUrl) continue;
|
|
20
|
+
const trust = await isFirstPartyRemoteEndpointTrusted(
|
|
21
|
+
orgId,
|
|
22
|
+
"assets",
|
|
23
|
+
server.url,
|
|
24
|
+
);
|
|
25
|
+
if (trust.ok) return true;
|
|
26
|
+
}
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function ensureAssetsServer(ctx?: {
|
|
31
|
+
userEmail?: string;
|
|
32
|
+
orgId?: string | null;
|
|
33
|
+
}) {
|
|
34
|
+
if (!ctx?.userEmail || !ctx.orgId) return false;
|
|
35
|
+
return hasAssetsServer(ctx.orgId);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export default defineNitroPlugin(() => {
|
|
39
|
+
registerOnboardingStep({
|
|
40
|
+
id: "assets-mcp",
|
|
41
|
+
order: 70,
|
|
42
|
+
title: "Connect Assets",
|
|
43
|
+
description:
|
|
44
|
+
"Enable first-party Assets MCP tools so Design can generate and insert on-brand media.",
|
|
45
|
+
required: false,
|
|
46
|
+
methods: [
|
|
47
|
+
{
|
|
48
|
+
id: "agent",
|
|
49
|
+
kind: "agent-task",
|
|
50
|
+
label: "Connect Assets",
|
|
51
|
+
primary: true,
|
|
52
|
+
payload: {
|
|
53
|
+
prompt:
|
|
54
|
+
"Call connect-assets-mcp to connect the first-party Assets MCP server for this Design organization, then verify generate-asset is visible.",
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
],
|
|
58
|
+
isComplete: ensureAssetsServer,
|
|
59
|
+
});
|
|
60
|
+
});
|
package/dist/a2a/client.d.ts
CHANGED
|
@@ -18,6 +18,7 @@ export declare class A2ATaskTimeoutError extends Error {
|
|
|
18
18
|
export declare function signA2AToken(email: string, orgDomain?: string, orgSecret?: string, options?: {
|
|
19
19
|
expiresIn?: string | number;
|
|
20
20
|
preferGlobalSecret?: boolean;
|
|
21
|
+
audience?: string | string[];
|
|
21
22
|
/**
|
|
22
23
|
* Extra JWT claims to merge alongside `sub` / `org_domain`. Used by the
|
|
23
24
|
* MCP connect flow to add a revocable `jti` and a `scope: "mcp-connect"`
|
package/dist/a2a/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/a2a/client.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,SAAS,EAGT,OAAO,EACP,IAAI,EACL,MAAM,YAAY,CAAC;AAEpB,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC;IACxB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;gBAEf,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM;CAW9D;AAED;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAChC,KAAK,EAAE,MAAM,EACb,SAAS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AAE,OAAO,CAAC,CAAA;KAAE,GAChE,cAAc,CAAC,IAAI,CAAC;YA6DT,wBAAwB;YAyBxB,QAAQ;CAuBvB;AA2DD;;;;;;GAMG;AACH,wBAAsB,SAAS,CAC7B,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE;IACL,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,8DAA8D;IAC9D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,yEAAyE;IACzE,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,GACA,OAAO,CAAC,MAAM,CAAC,CAsEjB"}
|
package/dist/a2a/client.js
CHANGED
|
@@ -35,7 +35,7 @@ export async function signA2AToken(email, orgDomain, orgSecret, options) {
|
|
|
35
35
|
const appUrl = process.env.APP_URL ||
|
|
36
36
|
process.env.BETTER_AUTH_URL ||
|
|
37
37
|
"http://localhost:3000";
|
|
38
|
-
|
|
38
|
+
const jwt = new jose.SignJWT({
|
|
39
39
|
...(options?.extraClaims ?? {}),
|
|
40
40
|
// `sub` / `org_domain` are spread AFTER extraClaims so a caller-supplied
|
|
41
41
|
// map can never override the verified identity claims.
|
|
@@ -45,8 +45,10 @@ export async function signA2AToken(email, orgDomain, orgSecret, options) {
|
|
|
45
45
|
.setProtectedHeader({ alg: "HS256" })
|
|
46
46
|
.setIssuer(appUrl)
|
|
47
47
|
.setIssuedAt()
|
|
48
|
-
.setExpirationTime(options?.expiresIn ?? "15m")
|
|
49
|
-
|
|
48
|
+
.setExpirationTime(options?.expiresIn ?? "15m");
|
|
49
|
+
if (options?.audience)
|
|
50
|
+
jwt.setAudience(options.audience);
|
|
51
|
+
return jwt.sign(new TextEncoder().encode(secret));
|
|
50
52
|
}
|
|
51
53
|
export class A2AClient {
|
|
52
54
|
baseUrl;
|
package/dist/a2a/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/a2a/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAS5D,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IACnC,MAAM,CAAS;IACf,QAAQ,CAAO;IACf,SAAS,CAAS;IAClB,SAAS,CAAS;IAE3B,YAAY,MAAc,EAAE,QAAc,EAAE,SAAiB;QAC3D,MAAM,SAAS,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC;QACxC,KAAK,CACH,YAAY,MAAM,4BAA4B,SAAS,mBAAmB,SAAS,GAAG,CACvF,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;QAClC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;CACF;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,KAAa,EACb,SAAkB,EAClB,SAAkB,EAClB,OAUC;IAED,MAAM,MAAM,GAAG,OAAO,EAAE,kBAAkB;QACxC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,IAAI,SAAS;QACrC,CAAC,CAAC,SAAS,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;IACxC,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CACb,yEAAyE;YACvE,wFAAwF,CAC3F,CAAC;IACJ,CAAC;IAED,MAAM,MAAM,G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AO,CAAC;IAC5C,IAAI,eAAe,EAAE,CAAC;QACpB,MAAM,SAAS,GAAG,eAAe,CAAC,KAAK;aACpC,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;aACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QACtB,OAAO,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;IAED,OAAO,EAAE,CAAC;AACZ,CAAC;AAED,SAAS,8BAA8B,CAAC,IAAU;IAChD,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,QAAQ,EAAE,+BAA+B,EAAE,CAAC;QACpE,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,OAAO,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AACjD,CAAC;AAED,SAAS,kBAAkB,CAAC,OAAgB;IAC1C,OAAO,OAAO,CAAC,KAAK;SACjB,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;SACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;SAClB,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC","sourcesContent":["import * as jose from \"jose\";\nimport { ssrfSafeFetch } from \"../extensions/url-safety.js\";\nimport type {\n AgentCard,\n JsonRpcRequest,\n JsonRpcResponse,\n Message,\n Task,\n} from \"./types.js\";\n\nexport class A2ATaskTimeoutError extends Error {\n readonly taskId: string;\n readonly lastTask: Task;\n readonly lastState: string;\n readonly timeoutMs: number;\n\n constructor(taskId: string, lastTask: Task, timeoutMs: number) {\n const lastState = lastTask.status.state;\n super(\n `A2A task ${taskId} did not complete within ${timeoutMs}ms (last state: ${lastState})`,\n );\n this.name = \"A2ATaskTimeoutError\";\n this.taskId = taskId;\n this.lastTask = lastTask;\n this.lastState = lastState;\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * Sign a JWT for A2A cross-app identity verification.\n *\n * Uses an org-level secret by default for direct org-secret workflows. Callers\n * that are doing ordinary hosted cross-app delegation can set\n * `preferGlobalSecret` so deployments with a shared A2A_SECRET don't depend on\n * every app database having an identical org row. The token contains the\n * caller's email as `sub`, so the receiving app can verify who's calling.\n */\nexport async function signA2AToken(\n email: string,\n orgDomain?: string,\n orgSecret?: string,\n options?: {\n expiresIn?: string | number;\n preferGlobalSecret?: boolean;\n /**\n * Extra JWT claims to merge alongside `sub` / `org_domain`. Used by the\n * MCP connect flow to add a revocable `jti` and a `scope: \"mcp-connect\"`\n * marker. Reserved claims (`sub`, `org_domain`) cannot be overridden —\n * they are spread last so a caller can never spoof identity via this map.\n */\n extraClaims?: Record<string, unknown>;\n },\n): Promise<string> {\n const secret = options?.preferGlobalSecret\n ? process.env.A2A_SECRET || orgSecret\n : orgSecret || process.env.A2A_SECRET;\n if (!secret) {\n throw new Error(\n \"No A2A secret available. Set an org-level A2A secret in Team settings, \" +\n \"or set A2A_SECRET as an environment variable on all apps that need to verify identity.\",\n );\n }\n\n const appUrl =\n process.env.APP_URL ||\n process.env.BETTER_AUTH_URL ||\n \"http://localhost:3000\";\n\n return new jose.SignJWT({\n ...(options?.extraClaims ?? {}),\n // `sub` / `org_domain` are spread AFTER extraClaims so a caller-supplied\n // map can never override the verified identity claims.\n sub: email,\n ...(orgDomain ? { org_domain: orgDomain } : {}),\n })\n .setProtectedHeader({ alg: \"HS256\" })\n .setIssuer(appUrl)\n .setIssuedAt()\n .setExpirationTime(options?.expiresIn ?? \"15m\")\n .sign(new TextEncoder().encode(secret));\n}\n\nexport class A2AClient {\n private baseUrl: string;\n private apiKey?: string;\n private endpointCandidates: string[] = [];\n private endpointResolved = false;\n private requestTimeoutMs?: number;\n\n constructor(\n baseUrl: string,\n apiKey?: string,\n options?: { requestTimeoutMs?: number },\n ) {\n const normalized = baseUrl.replace(/\\/$/, \"\");\n const explicitEndpoint = splitExplicitA2AEndpoint(normalized);\n this.baseUrl = explicitEndpoint?.baseUrl ?? normalized;\n if (explicitEndpoint) {\n this.endpointCandidates = [explicitEndpoint.endpointUrl];\n this.endpointResolved = true;\n }\n this.apiKey = apiKey;\n this.requestTimeoutMs = options?.requestTimeoutMs;\n }\n\n /**\n * Detect which A2A path the target agent uses.\n * Agent-native apps use /_agent-native/a2a, external agents may use /a2a.\n */\n async resolveEndpoint(): Promise<void> {\n await this.ensureEndpointCandidates();\n if (this.endpointCandidates.length <= 1) return;\n\n for (const endpoint of this.endpointCandidates) {\n try {\n const res = await ssrfSafeFetch(\n endpoint,\n { method: \"OPTIONS\" },\n { maxRedirects: 3 },\n );\n if (res.status !== 404 && res.status !== 405) {\n this.endpointCandidates = [endpoint];\n return;\n }\n if (res.status === 405) {\n this.endpointCandidates = [endpoint];\n return;\n }\n } catch {\n // Try the next candidate.\n }\n }\n }\n\n private headers(): Record<string, string> {\n const h: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (this.apiKey) {\n h[\"Authorization\"] = `Bearer ${this.apiKey}`;\n }\n return h;\n }\n\n private async rpc(\n method: string,\n params: Record<string, unknown>,\n ): Promise<JsonRpcResponse> {\n const body: JsonRpcRequest = {\n jsonrpc: \"2.0\",\n id: Date.now(),\n method,\n params,\n };\n\n await this.ensureEndpointCandidates();\n let lastError: Error | null = null;\n\n for (const url of this.endpointCandidates) {\n console.log(`[A2A Client] POST ${url} method=${method}`);\n const startTime = Date.now();\n const res = await this.postJson(url, body);\n console.log(\n `[A2A Client] Response: ${res.status} in ${Date.now() - startTime}ms`,\n );\n\n if (res.ok) {\n this.endpointCandidates = [url];\n return res.json() as Promise<JsonRpcResponse>;\n }\n\n const text = await res.text();\n lastError = new Error(`A2A request failed (${res.status}): ${text}`);\n if (!shouldTryNextEndpoint(res.status)) {\n throw lastError;\n }\n }\n\n throw lastError ?? new Error(\"No A2A endpoint candidates available\");\n }\n\n async getAgentCard(): Promise<AgentCard> {\n const res = await ssrfSafeFetch(\n `${this.baseUrl}/.well-known/agent-card.json`,\n {},\n { maxRedirects: 3 },\n );\n if (!res.ok) {\n throw new Error(`Failed to fetch agent card (${res.status})`);\n }\n return res.json() as Promise<AgentCard>;\n }\n\n async send(\n message: Message,\n opts?: {\n contextId?: string;\n metadata?: Record<string, unknown>;\n /**\n * If true, ask the server to return the task immediately in `working`\n * state and process the handler in the background. The caller should\n * then poll `getTask(taskId)` until `completed` / `failed` / `canceled`.\n *\n * Use this when you expect the handler may exceed a synchronous\n * serverless request budget.\n */\n async?: boolean;\n },\n ): Promise<Task> {\n const response = await this.rpc(\"message/send\", {\n message,\n contextId: opts?.contextId,\n metadata: opts?.metadata,\n ...(opts?.async ? { async: true } : {}),\n });\n\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n\n return response.result as Task;\n }\n\n /**\n * Poll for a task by id. Used in async mode after `send({ async: true })`.\n */\n async getTask(taskId: string): Promise<Task> {\n const response = await this.rpc(\"tasks/get\", { id: taskId });\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n return response.result as Task;\n }\n\n /**\n * Send a message in async mode and poll until the task reaches a terminal\n * state. This is the recommended path on serverless hosts with short\n * function timeouts (Netlify, Vercel) where a synchronous LLM-driven A2A\n * call can exceed the gateway limit.\n *\n * Each individual fetch returns quickly; long-running work happens on the\n * receiving side and is checked via `tasks/get`.\n */\n async sendAndWait(\n message: Message,\n opts?: {\n contextId?: string;\n metadata?: Record<string, unknown>;\n /** Total time to wait for completion. Default 5 min. */\n timeoutMs?: number;\n /** Poll interval. Default 2s. */\n pollIntervalMs?: number;\n /** Called with each polled task — useful for surfacing progress. */\n onUpdate?: (task: Task) => void;\n },\n ): Promise<Task> {\n const submitted = await this.send(message, {\n contextId: opts?.contextId,\n metadata: opts?.metadata,\n async: true,\n });\n\n const terminalStates = new Set([\"completed\", \"failed\", \"canceled\"]);\n if (terminalStates.has(submitted.status.state)) return submitted;\n\n const timeoutMs = opts?.timeoutMs ?? 5 * 60_000;\n const pollMs = opts?.pollIntervalMs ?? 2_000;\n const deadline = Date.now() + timeoutMs;\n\n let current = submitted;\n while (Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, pollMs));\n try {\n current = await this.getTask(submitted.id);\n opts?.onUpdate?.(current);\n } catch {\n // Transient fetch failure — keep polling until the deadline.\n continue;\n }\n if (terminalStates.has(current.status.state)) return current;\n }\n throw new A2ATaskTimeoutError(submitted.id, current, timeoutMs);\n }\n\n async *stream(\n message: Message,\n opts?: { contextId?: string; metadata?: Record<string, unknown> },\n ): AsyncGenerator<Task> {\n const body: JsonRpcRequest = {\n jsonrpc: \"2.0\",\n id: Date.now(),\n method: \"message/stream\",\n params: {\n message,\n contextId: opts?.contextId,\n metadata: opts?.metadata,\n },\n };\n\n await this.ensureEndpointCandidates();\n let res: Response | null = null;\n let lastError: Error | null = null;\n for (const candidate of this.endpointCandidates) {\n res = await this.postJson(candidate, body);\n if (res.ok) {\n this.endpointCandidates = [candidate];\n break;\n }\n const text = await res.text();\n lastError = new Error(`A2A stream failed (${res.status}): ${text}`);\n if (!shouldTryNextEndpoint(res.status)) throw lastError;\n }\n if (!res?.ok) {\n throw lastError ?? new Error(\"No A2A endpoint candidates available\");\n }\n\n const reader = res.body?.getReader();\n if (!reader) throw new Error(\"No response body\");\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const json = line.slice(6).trim();\n if (!json) continue;\n\n const response: JsonRpcResponse = JSON.parse(json);\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n if (response.result) {\n yield response.result as Task;\n }\n }\n }\n }\n\n private async ensureEndpointCandidates(): Promise<void> {\n if (this.endpointResolved) return;\n this.endpointResolved = true;\n\n const candidates: string[] = [];\n addDefaultEndpointCandidates(candidates, this.baseUrl);\n\n try {\n const card = await this.getAgentCard();\n const cardUrl = normalizeUrl(card.url, this.baseUrl);\n if (cardUrl) {\n const explicitEndpoint = splitExplicitA2AEndpoint(cardUrl);\n if (explicitEndpoint) {\n candidates.unshift(explicitEndpoint.endpointUrl);\n } else {\n addDefaultEndpointCandidates(candidates, cardUrl);\n }\n }\n } catch {\n // Agent cards are discovery hints. Fall back to conventional endpoints.\n }\n\n this.endpointCandidates = unique(candidates);\n }\n\n private async postJson(url: string, body: JsonRpcRequest): Promise<Response> {\n const controller = this.requestTimeoutMs\n ? new AbortController()\n : undefined;\n const timer =\n controller && this.requestTimeoutMs\n ? setTimeout(() => controller.abort(), this.requestTimeoutMs)\n : undefined;\n try {\n return await ssrfSafeFetch(\n url,\n {\n method: \"POST\",\n headers: this.headers(),\n body: JSON.stringify(body),\n signal: controller?.signal,\n },\n { maxRedirects: 3 },\n );\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n}\n\nfunction splitExplicitA2AEndpoint(\n url: string,\n): { baseUrl: string; endpointUrl: string } | null {\n try {\n const parsed = new URL(url);\n const pathname = parsed.pathname.replace(/\\/$/, \"\");\n if (pathname.endsWith(\"/_agent-native/a2a\")) {\n parsed.pathname = pathname.slice(0, -\"/_agent-native/a2a\".length) || \"/\";\n parsed.search = \"\";\n parsed.hash = \"\";\n return {\n baseUrl: parsed.toString().replace(/\\/$/, \"\"),\n endpointUrl: url,\n };\n }\n if (pathname.endsWith(\"/a2a\")) {\n parsed.pathname = pathname.slice(0, -\"/a2a\".length) || \"/\";\n parsed.search = \"\";\n parsed.hash = \"\";\n return {\n baseUrl: parsed.toString().replace(/\\/$/, \"\"),\n endpointUrl: url,\n };\n }\n } catch {\n // Relative or invalid URLs are handled by the caller's normal fetch path.\n }\n return null;\n}\n\nfunction addDefaultEndpointCandidates(candidates: string[], baseUrl: string) {\n const base = baseUrl.replace(/\\/$/, \"\");\n candidates.push(`${base}/_agent-native/a2a`, `${base}/a2a`);\n}\n\nfunction normalizeUrl(\n value: string | undefined,\n baseUrl: string,\n): string | null {\n if (!value) return null;\n try {\n return new URL(value, `${baseUrl.replace(/\\/$/, \"\")}/`)\n .toString()\n .replace(/\\/$/, \"\");\n } catch {\n return null;\n }\n}\n\nfunction shouldTryNextEndpoint(status: number): boolean {\n return status === 404 || status === 405;\n}\n\nfunction unique(values: string[]): string[] {\n return Array.from(new Set(values));\n}\n\n/**\n * One-shot convenience function: send a text message and get a text response.\n *\n * When A2A_SECRET is set and userEmail is provided, outbound calls are signed\n * with a JWT so the receiving app can cryptographically verify the caller's\n * identity (instead of blindly trusting metadata).\n */\nexport async function callAgent(\n url: string,\n text: string,\n opts?: {\n apiKey?: string;\n contextId?: string;\n userEmail?: string;\n orgDomain?: string;\n orgSecret?: string;\n /**\n * Use async/poll instead of a single blocking POST. Recommended for\n * cross-app calls that may exceed a synchronous serverless request budget.\n * Defaults to true so callers get safe behavior out of the box.\n */\n async?: boolean;\n /** Total time to wait for the polled task (default 5 min). */\n timeoutMs?: number;\n /** Poll interval for async calls. Primarily useful for tests/retries. */\n pollIntervalMs?: number;\n },\n): Promise<string> {\n let apiKey = opts?.apiKey;\n\n // Auto-sign with JWT when an A2A secret (org or global) is available and we have a user email\n if (\n !apiKey &&\n opts?.userEmail &&\n (opts?.orgSecret || process.env.A2A_SECRET)\n ) {\n try {\n apiKey = await signA2AToken(\n opts.userEmail,\n opts.orgDomain,\n opts.orgSecret,\n { preferGlobalSecret: !opts.orgSecret },\n );\n } catch {\n // Fall back to unsigned call\n }\n }\n\n const client = new A2AClient(url, apiKey);\n const metadata: Record<string, unknown> = {};\n if (opts?.userEmail) metadata.userEmail = opts.userEmail;\n if (opts?.orgDomain) metadata.orgDomain = opts.orgDomain;\n\n // Default to async + poll. The receiving A2A server's `_process-task` route\n // runs the handler in a fresh function execution (cross-platform queue\n // pattern), so async mode now works on every host instead of relying on\n // detached promises that get killed on Netlify/Vercel. Callers that\n // explicitly want a single-shot blocking POST can pass `async: false`.\n const useAsync = opts?.async ?? true;\n const message: Message = {\n role: \"user\",\n parts: [{ type: \"text\", text }],\n };\n\n let task: Task;\n if (useAsync) {\n try {\n task = await client.sendAndWait(message, {\n contextId: opts?.contextId,\n metadata,\n timeoutMs: opts?.timeoutMs,\n pollIntervalMs: opts?.pollIntervalMs,\n });\n } catch (err) {\n if (err instanceof A2ATaskTimeoutError) {\n const recoverableText = extractRecoverableArtifactText(err.lastTask);\n if (recoverableText) return recoverableText;\n }\n throw err;\n }\n } else {\n task = await client.send(message, {\n contextId: opts?.contextId,\n metadata,\n });\n }\n\n // Extract text from the response\n const responseMessage = task.status.message;\n if (responseMessage) {\n const textParts = responseMessage.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text);\n return textParts.join(\"\\n\");\n }\n\n return \"\";\n}\n\nfunction extractRecoverableArtifactText(task: Task): string {\n if (!task.status.message?.metadata?.agentNativeRecoverableArtifacts) {\n return \"\";\n }\n return extractMessageText(task.status.message);\n}\n\nfunction extractMessageText(message: Message): string {\n return message.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\\n\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/a2a/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAS5D,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IACnC,MAAM,CAAS;IACf,QAAQ,CAAO;IACf,SAAS,CAAS;IAClB,SAAS,CAAS;IAE3B,YAAY,MAAc,EAAE,QAAc,EAAE,SAAiB;QAC3D,MAAM,SAAS,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC;QACxC,KAAK,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I,CAAC,MAAM,CAAC,OAAO,EAAE,QAAQ,EAAE,+BAA+B,EAAE,CAAC;QACpE,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,OAAO,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AACjD,CAAC;AAED,SAAS,kBAAkB,CAAC,OAAgB;IAC1C,OAAO,OAAO,CAAC,KAAK;SACjB,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;SACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;SAClB,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC","sourcesContent":["import * as jose from \"jose\";\nimport { ssrfSafeFetch } from \"../extensions/url-safety.js\";\nimport type {\n AgentCard,\n JsonRpcRequest,\n JsonRpcResponse,\n Message,\n Task,\n} from \"./types.js\";\n\nexport class A2ATaskTimeoutError extends Error {\n readonly taskId: string;\n readonly lastTask: Task;\n readonly lastState: string;\n readonly timeoutMs: number;\n\n constructor(taskId: string, lastTask: Task, timeoutMs: number) {\n const lastState = lastTask.status.state;\n super(\n `A2A task ${taskId} did not complete within ${timeoutMs}ms (last state: ${lastState})`,\n );\n this.name = \"A2ATaskTimeoutError\";\n this.taskId = taskId;\n this.lastTask = lastTask;\n this.lastState = lastState;\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * Sign a JWT for A2A cross-app identity verification.\n *\n * Uses an org-level secret by default for direct org-secret workflows. Callers\n * that are doing ordinary hosted cross-app delegation can set\n * `preferGlobalSecret` so deployments with a shared A2A_SECRET don't depend on\n * every app database having an identical org row. The token contains the\n * caller's email as `sub`, so the receiving app can verify who's calling.\n */\nexport async function signA2AToken(\n email: string,\n orgDomain?: string,\n orgSecret?: string,\n options?: {\n expiresIn?: string | number;\n preferGlobalSecret?: boolean;\n audience?: string | string[];\n /**\n * Extra JWT claims to merge alongside `sub` / `org_domain`. Used by the\n * MCP connect flow to add a revocable `jti` and a `scope: \"mcp-connect\"`\n * marker. Reserved claims (`sub`, `org_domain`) cannot be overridden —\n * they are spread last so a caller can never spoof identity via this map.\n */\n extraClaims?: Record<string, unknown>;\n },\n): Promise<string> {\n const secret = options?.preferGlobalSecret\n ? process.env.A2A_SECRET || orgSecret\n : orgSecret || process.env.A2A_SECRET;\n if (!secret) {\n throw new Error(\n \"No A2A secret available. Set an org-level A2A secret in Team settings, \" +\n \"or set A2A_SECRET as an environment variable on all apps that need to verify identity.\",\n );\n }\n\n const appUrl =\n process.env.APP_URL ||\n process.env.BETTER_AUTH_URL ||\n \"http://localhost:3000\";\n\n const jwt = new jose.SignJWT({\n ...(options?.extraClaims ?? {}),\n // `sub` / `org_domain` are spread AFTER extraClaims so a caller-supplied\n // map can never override the verified identity claims.\n sub: email,\n ...(orgDomain ? { org_domain: orgDomain } : {}),\n })\n .setProtectedHeader({ alg: \"HS256\" })\n .setIssuer(appUrl)\n .setIssuedAt()\n .setExpirationTime(options?.expiresIn ?? \"15m\");\n\n if (options?.audience) jwt.setAudience(options.audience);\n\n return jwt.sign(new TextEncoder().encode(secret));\n}\n\nexport class A2AClient {\n private baseUrl: string;\n private apiKey?: string;\n private endpointCandidates: string[] = [];\n private endpointResolved = false;\n private requestTimeoutMs?: number;\n\n constructor(\n baseUrl: string,\n apiKey?: string,\n options?: { requestTimeoutMs?: number },\n ) {\n const normalized = baseUrl.replace(/\\/$/, \"\");\n const explicitEndpoint = splitExplicitA2AEndpoint(normalized);\n this.baseUrl = explicitEndpoint?.baseUrl ?? normalized;\n if (explicitEndpoint) {\n this.endpointCandidates = [explicitEndpoint.endpointUrl];\n this.endpointResolved = true;\n }\n this.apiKey = apiKey;\n this.requestTimeoutMs = options?.requestTimeoutMs;\n }\n\n /**\n * Detect which A2A path the target agent uses.\n * Agent-native apps use /_agent-native/a2a, external agents may use /a2a.\n */\n async resolveEndpoint(): Promise<void> {\n await this.ensureEndpointCandidates();\n if (this.endpointCandidates.length <= 1) return;\n\n for (const endpoint of this.endpointCandidates) {\n try {\n const res = await ssrfSafeFetch(\n endpoint,\n { method: \"OPTIONS\" },\n { maxRedirects: 3 },\n );\n if (res.status !== 404 && res.status !== 405) {\n this.endpointCandidates = [endpoint];\n return;\n }\n if (res.status === 405) {\n this.endpointCandidates = [endpoint];\n return;\n }\n } catch {\n // Try the next candidate.\n }\n }\n }\n\n private headers(): Record<string, string> {\n const h: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (this.apiKey) {\n h[\"Authorization\"] = `Bearer ${this.apiKey}`;\n }\n return h;\n }\n\n private async rpc(\n method: string,\n params: Record<string, unknown>,\n ): Promise<JsonRpcResponse> {\n const body: JsonRpcRequest = {\n jsonrpc: \"2.0\",\n id: Date.now(),\n method,\n params,\n };\n\n await this.ensureEndpointCandidates();\n let lastError: Error | null = null;\n\n for (const url of this.endpointCandidates) {\n console.log(`[A2A Client] POST ${url} method=${method}`);\n const startTime = Date.now();\n const res = await this.postJson(url, body);\n console.log(\n `[A2A Client] Response: ${res.status} in ${Date.now() - startTime}ms`,\n );\n\n if (res.ok) {\n this.endpointCandidates = [url];\n return res.json() as Promise<JsonRpcResponse>;\n }\n\n const text = await res.text();\n lastError = new Error(`A2A request failed (${res.status}): ${text}`);\n if (!shouldTryNextEndpoint(res.status)) {\n throw lastError;\n }\n }\n\n throw lastError ?? new Error(\"No A2A endpoint candidates available\");\n }\n\n async getAgentCard(): Promise<AgentCard> {\n const res = await ssrfSafeFetch(\n `${this.baseUrl}/.well-known/agent-card.json`,\n {},\n { maxRedirects: 3 },\n );\n if (!res.ok) {\n throw new Error(`Failed to fetch agent card (${res.status})`);\n }\n return res.json() as Promise<AgentCard>;\n }\n\n async send(\n message: Message,\n opts?: {\n contextId?: string;\n metadata?: Record<string, unknown>;\n /**\n * If true, ask the server to return the task immediately in `working`\n * state and process the handler in the background. The caller should\n * then poll `getTask(taskId)` until `completed` / `failed` / `canceled`.\n *\n * Use this when you expect the handler may exceed a synchronous\n * serverless request budget.\n */\n async?: boolean;\n },\n ): Promise<Task> {\n const response = await this.rpc(\"message/send\", {\n message,\n contextId: opts?.contextId,\n metadata: opts?.metadata,\n ...(opts?.async ? { async: true } : {}),\n });\n\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n\n return response.result as Task;\n }\n\n /**\n * Poll for a task by id. Used in async mode after `send({ async: true })`.\n */\n async getTask(taskId: string): Promise<Task> {\n const response = await this.rpc(\"tasks/get\", { id: taskId });\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n return response.result as Task;\n }\n\n /**\n * Send a message in async mode and poll until the task reaches a terminal\n * state. This is the recommended path on serverless hosts with short\n * function timeouts (Netlify, Vercel) where a synchronous LLM-driven A2A\n * call can exceed the gateway limit.\n *\n * Each individual fetch returns quickly; long-running work happens on the\n * receiving side and is checked via `tasks/get`.\n */\n async sendAndWait(\n message: Message,\n opts?: {\n contextId?: string;\n metadata?: Record<string, unknown>;\n /** Total time to wait for completion. Default 5 min. */\n timeoutMs?: number;\n /** Poll interval. Default 2s. */\n pollIntervalMs?: number;\n /** Called with each polled task — useful for surfacing progress. */\n onUpdate?: (task: Task) => void;\n },\n ): Promise<Task> {\n const submitted = await this.send(message, {\n contextId: opts?.contextId,\n metadata: opts?.metadata,\n async: true,\n });\n\n const terminalStates = new Set([\"completed\", \"failed\", \"canceled\"]);\n if (terminalStates.has(submitted.status.state)) return submitted;\n\n const timeoutMs = opts?.timeoutMs ?? 5 * 60_000;\n const pollMs = opts?.pollIntervalMs ?? 2_000;\n const deadline = Date.now() + timeoutMs;\n\n let current = submitted;\n while (Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, pollMs));\n try {\n current = await this.getTask(submitted.id);\n opts?.onUpdate?.(current);\n } catch {\n // Transient fetch failure — keep polling until the deadline.\n continue;\n }\n if (terminalStates.has(current.status.state)) return current;\n }\n throw new A2ATaskTimeoutError(submitted.id, current, timeoutMs);\n }\n\n async *stream(\n message: Message,\n opts?: { contextId?: string; metadata?: Record<string, unknown> },\n ): AsyncGenerator<Task> {\n const body: JsonRpcRequest = {\n jsonrpc: \"2.0\",\n id: Date.now(),\n method: \"message/stream\",\n params: {\n message,\n contextId: opts?.contextId,\n metadata: opts?.metadata,\n },\n };\n\n await this.ensureEndpointCandidates();\n let res: Response | null = null;\n let lastError: Error | null = null;\n for (const candidate of this.endpointCandidates) {\n res = await this.postJson(candidate, body);\n if (res.ok) {\n this.endpointCandidates = [candidate];\n break;\n }\n const text = await res.text();\n lastError = new Error(`A2A stream failed (${res.status}): ${text}`);\n if (!shouldTryNextEndpoint(res.status)) throw lastError;\n }\n if (!res?.ok) {\n throw lastError ?? new Error(\"No A2A endpoint candidates available\");\n }\n\n const reader = res.body?.getReader();\n if (!reader) throw new Error(\"No response body\");\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const json = line.slice(6).trim();\n if (!json) continue;\n\n const response: JsonRpcResponse = JSON.parse(json);\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n if (response.result) {\n yield response.result as Task;\n }\n }\n }\n }\n\n private async ensureEndpointCandidates(): Promise<void> {\n if (this.endpointResolved) return;\n this.endpointResolved = true;\n\n const candidates: string[] = [];\n addDefaultEndpointCandidates(candidates, this.baseUrl);\n\n try {\n const card = await this.getAgentCard();\n const cardUrl = normalizeUrl(card.url, this.baseUrl);\n if (cardUrl) {\n const explicitEndpoint = splitExplicitA2AEndpoint(cardUrl);\n if (explicitEndpoint) {\n candidates.unshift(explicitEndpoint.endpointUrl);\n } else {\n addDefaultEndpointCandidates(candidates, cardUrl);\n }\n }\n } catch {\n // Agent cards are discovery hints. Fall back to conventional endpoints.\n }\n\n this.endpointCandidates = unique(candidates);\n }\n\n private async postJson(url: string, body: JsonRpcRequest): Promise<Response> {\n const controller = this.requestTimeoutMs\n ? new AbortController()\n : undefined;\n const timer =\n controller && this.requestTimeoutMs\n ? setTimeout(() => controller.abort(), this.requestTimeoutMs)\n : undefined;\n try {\n return await ssrfSafeFetch(\n url,\n {\n method: \"POST\",\n headers: this.headers(),\n body: JSON.stringify(body),\n signal: controller?.signal,\n },\n { maxRedirects: 3 },\n );\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n}\n\nfunction splitExplicitA2AEndpoint(\n url: string,\n): { baseUrl: string; endpointUrl: string } | null {\n try {\n const parsed = new URL(url);\n const pathname = parsed.pathname.replace(/\\/$/, \"\");\n if (pathname.endsWith(\"/_agent-native/a2a\")) {\n parsed.pathname = pathname.slice(0, -\"/_agent-native/a2a\".length) || \"/\";\n parsed.search = \"\";\n parsed.hash = \"\";\n return {\n baseUrl: parsed.toString().replace(/\\/$/, \"\"),\n endpointUrl: url,\n };\n }\n if (pathname.endsWith(\"/a2a\")) {\n parsed.pathname = pathname.slice(0, -\"/a2a\".length) || \"/\";\n parsed.search = \"\";\n parsed.hash = \"\";\n return {\n baseUrl: parsed.toString().replace(/\\/$/, \"\"),\n endpointUrl: url,\n };\n }\n } catch {\n // Relative or invalid URLs are handled by the caller's normal fetch path.\n }\n return null;\n}\n\nfunction addDefaultEndpointCandidates(candidates: string[], baseUrl: string) {\n const base = baseUrl.replace(/\\/$/, \"\");\n candidates.push(`${base}/_agent-native/a2a`, `${base}/a2a`);\n}\n\nfunction normalizeUrl(\n value: string | undefined,\n baseUrl: string,\n): string | null {\n if (!value) return null;\n try {\n return new URL(value, `${baseUrl.replace(/\\/$/, \"\")}/`)\n .toString()\n .replace(/\\/$/, \"\");\n } catch {\n return null;\n }\n}\n\nfunction shouldTryNextEndpoint(status: number): boolean {\n return status === 404 || status === 405;\n}\n\nfunction unique(values: string[]): string[] {\n return Array.from(new Set(values));\n}\n\n/**\n * One-shot convenience function: send a text message and get a text response.\n *\n * When A2A_SECRET is set and userEmail is provided, outbound calls are signed\n * with a JWT so the receiving app can cryptographically verify the caller's\n * identity (instead of blindly trusting metadata).\n */\nexport async function callAgent(\n url: string,\n text: string,\n opts?: {\n apiKey?: string;\n contextId?: string;\n userEmail?: string;\n orgDomain?: string;\n orgSecret?: string;\n /**\n * Use async/poll instead of a single blocking POST. Recommended for\n * cross-app calls that may exceed a synchronous serverless request budget.\n * Defaults to true so callers get safe behavior out of the box.\n */\n async?: boolean;\n /** Total time to wait for the polled task (default 5 min). */\n timeoutMs?: number;\n /** Poll interval for async calls. Primarily useful for tests/retries. */\n pollIntervalMs?: number;\n },\n): Promise<string> {\n let apiKey = opts?.apiKey;\n\n // Auto-sign with JWT when an A2A secret (org or global) is available and we have a user email\n if (\n !apiKey &&\n opts?.userEmail &&\n (opts?.orgSecret || process.env.A2A_SECRET)\n ) {\n try {\n apiKey = await signA2AToken(\n opts.userEmail,\n opts.orgDomain,\n opts.orgSecret,\n { preferGlobalSecret: !opts.orgSecret },\n );\n } catch {\n // Fall back to unsigned call\n }\n }\n\n const client = new A2AClient(url, apiKey);\n const metadata: Record<string, unknown> = {};\n if (opts?.userEmail) metadata.userEmail = opts.userEmail;\n if (opts?.orgDomain) metadata.orgDomain = opts.orgDomain;\n\n // Default to async + poll. The receiving A2A server's `_process-task` route\n // runs the handler in a fresh function execution (cross-platform queue\n // pattern), so async mode now works on every host instead of relying on\n // detached promises that get killed on Netlify/Vercel. Callers that\n // explicitly want a single-shot blocking POST can pass `async: false`.\n const useAsync = opts?.async ?? true;\n const message: Message = {\n role: \"user\",\n parts: [{ type: \"text\", text }],\n };\n\n let task: Task;\n if (useAsync) {\n try {\n task = await client.sendAndWait(message, {\n contextId: opts?.contextId,\n metadata,\n timeoutMs: opts?.timeoutMs,\n pollIntervalMs: opts?.pollIntervalMs,\n });\n } catch (err) {\n if (err instanceof A2ATaskTimeoutError) {\n const recoverableText = extractRecoverableArtifactText(err.lastTask);\n if (recoverableText) return recoverableText;\n }\n throw err;\n }\n } else {\n task = await client.send(message, {\n contextId: opts?.contextId,\n metadata,\n });\n }\n\n // Extract text from the response\n const responseMessage = task.status.message;\n if (responseMessage) {\n const textParts = responseMessage.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text);\n return textParts.join(\"\\n\");\n }\n\n return \"\";\n}\n\nfunction extractRecoverableArtifactText(task: Task): string {\n if (!task.status.message?.metadata?.agentNativeRecoverableArtifacts) {\n return \"\";\n }\n return extractMessageText(task.status.message);\n}\n\nfunction extractMessageText(message: Message): string {\n return message.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\\n\");\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-path.d.ts","sourceRoot":"","sources":["../../src/client/api-path.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"api-path.d.ts","sourceRoot":"","sources":["../../src/client/api-path.ts"],"names":[],"mappings":"AAuFA,wBAAgB,WAAW,IAAI,MAAM,CAepC;AAED,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAM5C;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAM/C;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGpD"}
|
package/dist/client/api-path.js
CHANGED
|
@@ -46,8 +46,35 @@ function workspacePathBasePath() {
|
|
|
46
46
|
return "";
|
|
47
47
|
return normalizeBasePath(segment);
|
|
48
48
|
}
|
|
49
|
+
function externalEmbedTargetBasePath() {
|
|
50
|
+
if (typeof window === "undefined")
|
|
51
|
+
return "";
|
|
52
|
+
const target = window.__AGENT_NATIVE_EXTERNAL_EMBED?.target;
|
|
53
|
+
if (typeof target !== "string" || !target.startsWith("/"))
|
|
54
|
+
return "";
|
|
55
|
+
try {
|
|
56
|
+
const url = new URL(target, "http://agent-native.invalid");
|
|
57
|
+
const markerIndex = url.pathname.indexOf(FRAMEWORK_ROUTE_PREFIX);
|
|
58
|
+
if (markerIndex > 0) {
|
|
59
|
+
return normalizeBasePath(url.pathname.slice(0, markerIndex));
|
|
60
|
+
}
|
|
61
|
+
if (isWorkspaceRuntime()) {
|
|
62
|
+
const segment = url.pathname.split("/").find(Boolean);
|
|
63
|
+
if (segment && segment !== "_agent-native" && segment !== "api") {
|
|
64
|
+
return normalizeBasePath(segment);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return "";
|
|
70
|
+
}
|
|
71
|
+
return "";
|
|
72
|
+
}
|
|
49
73
|
export function appBasePath() {
|
|
50
74
|
ensureEmbedAuthFetchInterceptor();
|
|
75
|
+
const externalEmbed = externalEmbedTargetBasePath();
|
|
76
|
+
if (externalEmbed)
|
|
77
|
+
return externalEmbed;
|
|
51
78
|
const configured = configuredBasePath();
|
|
52
79
|
const derived = pathDerivedBasePath();
|
|
53
80
|
if (!configured)
|