@vellumai/assistant 0.10.8-dev.202607110310.3d0fcac → 0.10.8-dev.202607110654.dcd3b7b
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/openapi.yaml +21 -0
- package/package.json +1 -1
- package/src/__tests__/app-asset-bytes.test.ts +72 -0
- package/src/apps/app-store.ts +15 -0
- package/src/channels/types.ts +4 -0
- package/src/config/bundled-skills/app-builder/SKILL.md +23 -0
- package/src/config/bundled-skills/app-builder/references/CUSTOM_ROUTES.md +30 -0
- package/src/daemon/__tests__/route-conversation-post.test.ts +158 -0
- package/src/daemon/route-conversation-post.ts +158 -0
- package/src/runtime/routes/__tests__/user-route-dispatcher.test.ts +3 -0
- package/src/runtime/routes/app-routes.ts +98 -6
- package/src/runtime/routes/user-route-dispatcher.ts +27 -0
- package/src/runtime/routes/user-routes.ts +4 -0
package/openapi.yaml
CHANGED
|
@@ -617,6 +617,27 @@ paths:
|
|
|
617
617
|
required:
|
|
618
618
|
- apps
|
|
619
619
|
additionalProperties: false
|
|
620
|
+
/v1/apps/{appId}/asset/{path}:
|
|
621
|
+
get:
|
|
622
|
+
operationId: apps_by_appId_asset_by_path_get
|
|
623
|
+
summary: Serve app asset
|
|
624
|
+
description: Serve a bundled binary asset (image, audio, video, font) from anywhere in an app's directory.
|
|
625
|
+
tags:
|
|
626
|
+
- apps
|
|
627
|
+
parameters:
|
|
628
|
+
- name: appId
|
|
629
|
+
in: path
|
|
630
|
+
required: true
|
|
631
|
+
schema:
|
|
632
|
+
type: string
|
|
633
|
+
- name: path
|
|
634
|
+
in: path
|
|
635
|
+
required: true
|
|
636
|
+
schema:
|
|
637
|
+
type: string
|
|
638
|
+
responses:
|
|
639
|
+
"200":
|
|
640
|
+
description: Successful response
|
|
620
641
|
/v1/apps/{appId}/dist/{filename}:
|
|
621
642
|
get:
|
|
622
643
|
operationId: apps_by_appId_dist_by_filename_get
|
package/package.json
CHANGED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guard tests for `readAppFileBytes` — the byte-reading helper behind the app
|
|
3
|
+
* asset endpoint (`GET /v1/apps/:appId/asset/:path*`, served to sandboxed apps
|
|
4
|
+
* via `window.vellum.asset`).
|
|
5
|
+
*
|
|
6
|
+
* - Bytes round-trip intact (the point of the helper: utf-8 decoding would
|
|
7
|
+
* corrupt binary media).
|
|
8
|
+
* - Path validation still rejects traversal, absolute paths, and the
|
|
9
|
+
* protected `records/` directory.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { tmpdir } from "node:os";
|
|
14
|
+
import { dirname, join } from "node:path";
|
|
15
|
+
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
createApp,
|
|
19
|
+
getAppDirPath,
|
|
20
|
+
readAppFileBytes,
|
|
21
|
+
} from "../apps/app-store.js";
|
|
22
|
+
|
|
23
|
+
let testDir: string;
|
|
24
|
+
|
|
25
|
+
beforeEach(() => {
|
|
26
|
+
testDir = join(
|
|
27
|
+
tmpdir(),
|
|
28
|
+
`vellum-app-asset-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
29
|
+
);
|
|
30
|
+
process.env.VELLUM_WORKSPACE_DIR = testDir;
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
afterEach(() => {
|
|
34
|
+
rmSync(testDir, { recursive: true, force: true });
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
function makeApp(): string {
|
|
38
|
+
return createApp({
|
|
39
|
+
name: "Asset Test",
|
|
40
|
+
schemaJson: "{}",
|
|
41
|
+
htmlDefinition: "<h1>hi</h1>",
|
|
42
|
+
}).id;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
describe("readAppFileBytes", () => {
|
|
46
|
+
test("reads binary bytes without utf-8 corruption", () => {
|
|
47
|
+
const appId = makeApp();
|
|
48
|
+
// Includes 0xFF/0x80 — bytes that are not valid utf-8 and would be
|
|
49
|
+
// mangled by a text read.
|
|
50
|
+
const bytes = Buffer.from([0x00, 0x01, 0xff, 0xfe, 0x80, 0x7f, 0x42]);
|
|
51
|
+
const abs = join(getAppDirPath(appId), "assets", "clip.bin");
|
|
52
|
+
mkdirSync(dirname(abs), { recursive: true });
|
|
53
|
+
writeFileSync(abs, bytes);
|
|
54
|
+
|
|
55
|
+
const read = readAppFileBytes(appId, "assets/clip.bin");
|
|
56
|
+
expect(Buffer.compare(read, bytes)).toBe(0);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("rejects traversal, absolute paths, and the records/ directory", () => {
|
|
60
|
+
const appId = makeApp();
|
|
61
|
+
expect(() => readAppFileBytes(appId, "../../etc/passwd")).toThrow();
|
|
62
|
+
expect(() => readAppFileBytes(appId, "/etc/passwd")).toThrow();
|
|
63
|
+
expect(() => readAppFileBytes(appId, "records/secret.json")).toThrow();
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("throws for a missing file", () => {
|
|
67
|
+
const appId = makeApp();
|
|
68
|
+
expect(() => readAppFileBytes(appId, "assets/nope.png")).toThrow(
|
|
69
|
+
/not found/i,
|
|
70
|
+
);
|
|
71
|
+
});
|
|
72
|
+
});
|
package/src/apps/app-store.ts
CHANGED
|
@@ -865,6 +865,21 @@ export function readAppFile(appId: string, path: string): string {
|
|
|
865
865
|
return readFileSync(resolved, "utf-8");
|
|
866
866
|
}
|
|
867
867
|
|
|
868
|
+
/**
|
|
869
|
+
* Read a file from the app directory as raw bytes.
|
|
870
|
+
* Path is validated to prevent traversal. Use for binary assets (images,
|
|
871
|
+
* audio, video, fonts) where {@link readAppFile}'s utf-8 decoding corrupts
|
|
872
|
+
* the data.
|
|
873
|
+
*/
|
|
874
|
+
export function readAppFileBytes(appId: string, path: string): Buffer {
|
|
875
|
+
validateId(appId);
|
|
876
|
+
const resolved = validateFilePath(appId, path);
|
|
877
|
+
if (!existsSync(resolved)) {
|
|
878
|
+
throw new Error(`File not found: ${path}`);
|
|
879
|
+
}
|
|
880
|
+
return readFileSync(resolved);
|
|
881
|
+
}
|
|
882
|
+
|
|
868
883
|
/**
|
|
869
884
|
* Write a file to the app directory.
|
|
870
885
|
* Auto-creates intermediate directories. Path is validated to prevent traversal.
|
package/src/channels/types.ts
CHANGED
|
@@ -150,6 +150,10 @@ export const INTERFACE_IDS = [
|
|
|
150
150
|
"email",
|
|
151
151
|
"chrome-extension",
|
|
152
152
|
"a2a",
|
|
153
|
+
// Turns injected by workspace custom routes (webhook receivers, cron jobs,
|
|
154
|
+
// device/service callbacks). Non-interactive — permission prompts route
|
|
155
|
+
// through the guardian system, not an interactive client — and non-host-proxy.
|
|
156
|
+
"route",
|
|
153
157
|
] as const;
|
|
154
158
|
|
|
155
159
|
export type InterfaceId = (typeof INTERFACE_IDS)[number];
|
|
@@ -270,6 +270,29 @@ useEffect(() => {
|
|
|
270
270
|
}, []);
|
|
271
271
|
```
|
|
272
272
|
|
|
273
|
+
**Bundled media — `window.vellum.asset(path)`.** For binary assets too big to inline (images, audio, short video, custom fonts), bundle the file under the app directory with `file_write` and load it at runtime via `window.vellum.asset("assets/intro.mp4")`, which resolves to a `blob:` URL the sandbox can use directly. Don't reach for giant base64 data-URIs.
|
|
274
|
+
|
|
275
|
+
```tsx
|
|
276
|
+
const [src, setSrc] = useState("");
|
|
277
|
+
useEffect(() => {
|
|
278
|
+
window.vellum.asset("assets/intro.mp4").then(setSrc).catch(() => notifyError("Couldn't load media"));
|
|
279
|
+
}, []);
|
|
280
|
+
return src ? <video src={src} controls /> : null;
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
Paths are validated server-side (no traversal, no `records/`); the file is served only from this app's own directory.
|
|
284
|
+
|
|
285
|
+
**Live updates — `window.vellum.subscribe({ tags }, cb)`.** Instead of polling on a timer, subscribe to your own invalidation tags and refresh when the data actually changes. After a route mutates data it publishes a `sync_changed` event (`context.assistantEventHub.publish({ …, message: { type: "sync_changed", tags: ["my-app:items"] } })`); the app subscribes to that tag and re-fetches when it fires. Returns an unsubscribe function — call it on cleanup. Only your own custom tags are delivered (host namespaces like `conversation:`/`assistant:` are never forwarded), and the payload is just the changed tags — re-fetch through `window.vellum.fetch` for the data.
|
|
286
|
+
|
|
287
|
+
```tsx
|
|
288
|
+
useEffect(() => {
|
|
289
|
+
const off = window.vellum.subscribe({ tags: ["my-app:items"] }, () => {
|
|
290
|
+
void loadItems(); // re-fetch on change — no polling
|
|
291
|
+
});
|
|
292
|
+
return off;
|
|
293
|
+
}, []);
|
|
294
|
+
```
|
|
295
|
+
|
|
273
296
|
**Writing a route handler.** Routes are `.ts`/`.js` files in `{workspaceDir}/routes/`, served at `/v1/x/<filename>` (`routes/items.ts` → `/v1/x/items`; `routes/bar/index.ts` → `/v1/x/bar`). Write them with `file_write` **before** `app_refresh`. Each exports named functions per HTTP method (`GET`/`POST`/`PUT`/`PATCH`/`DELETE`), receiving the Web `Request` and an optional `context`. Full Node API access (`fs`, `path`, `crypto`), 30s timeout, hot-reloaded on change. No `[id].ts` dynamic segments — use query params.
|
|
274
297
|
|
|
275
298
|
```typescript
|
|
@@ -84,6 +84,7 @@ Every handler receives a frozen `context` object as its second argument. This pr
|
|
|
84
84
|
export async function POST(request: Request, context): Promise<Response> {
|
|
85
85
|
// context.assistantEventHub — publish events to connected SSE clients
|
|
86
86
|
// context.assistantId — the daemon's logical assistant ID ("self")
|
|
87
|
+
// context.conversations — post messages into conversations as real turns
|
|
87
88
|
}
|
|
88
89
|
```
|
|
89
90
|
|
|
@@ -108,6 +109,35 @@ export async function POST(request: Request, context): Promise<Response> {
|
|
|
108
109
|
}
|
|
109
110
|
```
|
|
110
111
|
|
|
112
|
+
### Posting into a conversation
|
|
113
|
+
|
|
114
|
+
Use `context.conversations.postMessage` to surface an inbound event as a real assistant turn — the way a webhook receiver, a scheduled job, or a device callback turns "your deploy finished" or "payment received" into a message the assistant actually responds to (not just a client-side event).
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
// routes/deploy-webhook.ts — an external CI system POSTs here when a build finishes
|
|
118
|
+
export async function POST(request: Request, context): Promise<Response> {
|
|
119
|
+
const { conversationId, status } = await request.json();
|
|
120
|
+
try {
|
|
121
|
+
await context.conversations.postMessage(
|
|
122
|
+
conversationId,
|
|
123
|
+
`Your deploy finished: ${status}.`,
|
|
124
|
+
);
|
|
125
|
+
return Response.json({ ok: true });
|
|
126
|
+
} catch (err) {
|
|
127
|
+
// err.code is "not_found" | "rate_limited" | "invalid"
|
|
128
|
+
const code = (err as { code?: string }).code;
|
|
129
|
+
const httpStatus =
|
|
130
|
+
code === "not_found" ? 404 : code === "rate_limited" ? 429 : 400;
|
|
131
|
+
return Response.json(
|
|
132
|
+
{ ok: false, error: String(err) },
|
|
133
|
+
{ status: httpStatus },
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
The posted turn is attributed to a dedicated `route` interface — it can never impersonate a human surface — and runs under the target conversation's existing trust context, so a route cannot elevate privilege by posting. Unknown conversation ids are rejected (a route never silently creates a conversation), and posts are rate-limited per conversation to backstop runaway route→assistant→route loops.
|
|
140
|
+
|
|
111
141
|
The context object is **immutable** — attempting to reassign its properties will throw in strict mode (ESM). This prevents user route handlers from accidentally corrupting shared state.
|
|
112
142
|
|
|
113
143
|
Legacy handlers that only accept `(request)` continue to work — the context is passed positionally but ignored if the handler doesn't declare the parameter.
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guard tests for {@link postRouteConversationMessage} — the helper that lets a
|
|
3
|
+
* workspace custom route inject a message into a conversation as a real turn.
|
|
4
|
+
*
|
|
5
|
+
* The security-relevant invariants are asserted here without a DB by stubbing
|
|
6
|
+
* the two dependencies the helper touches: `processMessageInBackground` (the
|
|
7
|
+
* turn sink — spied to inspect attribution) and `getConversation` (existence).
|
|
8
|
+
*
|
|
9
|
+
* - Attribution is unspoofable: posts are always stamped with the dedicated
|
|
10
|
+
* `route` interface, never a human surface, and the helper exposes no way
|
|
11
|
+
* to override it.
|
|
12
|
+
* - No privilege escalation: the helper never passes a trust or auth context.
|
|
13
|
+
* - Unknown conversations are rejected (never silently created).
|
|
14
|
+
* - A per-conversation rate limit backstops runaway loops.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { beforeEach, describe, expect, mock, test } from "bun:test";
|
|
18
|
+
|
|
19
|
+
interface ProcessCall {
|
|
20
|
+
conversationId: string;
|
|
21
|
+
content: string;
|
|
22
|
+
options: Record<string, unknown> | undefined;
|
|
23
|
+
}
|
|
24
|
+
const processCalls: ProcessCall[] = [];
|
|
25
|
+
let conversationExists = true;
|
|
26
|
+
|
|
27
|
+
const realProcess = await import("../process-message.js");
|
|
28
|
+
mock.module("../process-message.js", () => ({
|
|
29
|
+
...realProcess,
|
|
30
|
+
processMessageInBackground: async (
|
|
31
|
+
conversationId: string,
|
|
32
|
+
content: string,
|
|
33
|
+
options?: Record<string, unknown>,
|
|
34
|
+
) => {
|
|
35
|
+
processCalls.push({ conversationId, content, options });
|
|
36
|
+
return { messageId: `msg-${processCalls.length}` };
|
|
37
|
+
},
|
|
38
|
+
}));
|
|
39
|
+
|
|
40
|
+
const realCrud = await import("../../persistence/conversation-crud.js");
|
|
41
|
+
mock.module("../../persistence/conversation-crud.js", () => ({
|
|
42
|
+
...realCrud,
|
|
43
|
+
getConversation: (id: string) =>
|
|
44
|
+
conversationExists ? ({ id } as unknown) : null,
|
|
45
|
+
}));
|
|
46
|
+
|
|
47
|
+
// Controls for the active-conversation (busy/queue) path.
|
|
48
|
+
let conversationBusy = false;
|
|
49
|
+
let enqueueResult: { queued: boolean; requestId: string; rejected?: boolean } =
|
|
50
|
+
{
|
|
51
|
+
queued: true,
|
|
52
|
+
requestId: "queued-req",
|
|
53
|
+
};
|
|
54
|
+
const enqueueCalls: Array<{
|
|
55
|
+
content: string;
|
|
56
|
+
metadata: Record<string, unknown> | undefined;
|
|
57
|
+
}> = [];
|
|
58
|
+
|
|
59
|
+
const realStore = await import("../conversation-store.js");
|
|
60
|
+
mock.module("../conversation-store.js", () => ({
|
|
61
|
+
...realStore,
|
|
62
|
+
getOrCreateConversation: async (_id: string) => ({
|
|
63
|
+
isProcessing: () => conversationBusy,
|
|
64
|
+
enqueueMessage: (opts: {
|
|
65
|
+
content: string;
|
|
66
|
+
metadata?: Record<string, unknown>;
|
|
67
|
+
}) => {
|
|
68
|
+
enqueueCalls.push({ content: opts.content, metadata: opts.metadata });
|
|
69
|
+
return enqueueResult;
|
|
70
|
+
},
|
|
71
|
+
}),
|
|
72
|
+
}));
|
|
73
|
+
|
|
74
|
+
const { postRouteConversationMessage } =
|
|
75
|
+
await import("../route-conversation-post.js");
|
|
76
|
+
|
|
77
|
+
const HUMAN_INTERFACES = ["web", "macos", "ios", "cli"];
|
|
78
|
+
|
|
79
|
+
describe("postRouteConversationMessage", () => {
|
|
80
|
+
beforeEach(() => {
|
|
81
|
+
processCalls.length = 0;
|
|
82
|
+
conversationExists = true;
|
|
83
|
+
conversationBusy = false;
|
|
84
|
+
enqueueCalls.length = 0;
|
|
85
|
+
enqueueResult = { queued: true, requestId: "queued-req" };
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test("posts the turn attributed to the route interface, never a human one", async () => {
|
|
89
|
+
const res = await postRouteConversationMessage(
|
|
90
|
+
"conv-attr",
|
|
91
|
+
"deploy finished",
|
|
92
|
+
);
|
|
93
|
+
expect(res.messageId).toBeTruthy();
|
|
94
|
+
expect(processCalls).toHaveLength(1);
|
|
95
|
+
expect(processCalls[0]!.conversationId).toBe("conv-attr");
|
|
96
|
+
expect(processCalls[0]!.content).toBe("deploy finished");
|
|
97
|
+
expect(processCalls[0]!.options?.sourceInterface).toBe("route");
|
|
98
|
+
expect(HUMAN_INTERFACES).not.toContain(
|
|
99
|
+
processCalls[0]!.options?.sourceInterface,
|
|
100
|
+
);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test("never passes a trust or auth context (no privilege escalation)", async () => {
|
|
104
|
+
await postRouteConversationMessage("conv-trust", "hi");
|
|
105
|
+
expect(processCalls[0]!.options).not.toHaveProperty("trustContext");
|
|
106
|
+
expect(processCalls[0]!.options).not.toHaveProperty("authContext");
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test("rejects an unknown conversation without creating one", async () => {
|
|
110
|
+
conversationExists = false;
|
|
111
|
+
await expect(
|
|
112
|
+
postRouteConversationMessage("does-not-exist", "hi"),
|
|
113
|
+
).rejects.toMatchObject({ code: "not_found" });
|
|
114
|
+
expect(processCalls).toHaveLength(0);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test("rejects empty text", async () => {
|
|
118
|
+
await expect(
|
|
119
|
+
postRouteConversationMessage("conv-empty", " "),
|
|
120
|
+
).rejects.toMatchObject({ code: "invalid" });
|
|
121
|
+
expect(processCalls).toHaveLength(0);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test("rate-limits per conversation to backstop runaway loops", async () => {
|
|
125
|
+
const convId = "conv-rate-limit";
|
|
126
|
+
for (let i = 0; i < 5; i++) {
|
|
127
|
+
await postRouteConversationMessage(convId, `m${i}`);
|
|
128
|
+
}
|
|
129
|
+
await expect(
|
|
130
|
+
postRouteConversationMessage(convId, "overflow"),
|
|
131
|
+
).rejects.toMatchObject({ code: "rate_limited" });
|
|
132
|
+
expect(processCalls).toHaveLength(5);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test("queues (does not drop) when the conversation is mid-turn", async () => {
|
|
136
|
+
conversationBusy = true;
|
|
137
|
+
const res = await postRouteConversationMessage("conv-busy", "event fired");
|
|
138
|
+
// Queued, not processed immediately, and never dropped.
|
|
139
|
+
expect(res.messageId).toBeTruthy();
|
|
140
|
+
expect(enqueueCalls).toHaveLength(1);
|
|
141
|
+
expect(processCalls).toHaveLength(0);
|
|
142
|
+
// Queued turn keeps the route attribution via metadata.
|
|
143
|
+
expect(enqueueCalls[0]!.metadata?.userMessageInterface).toBe("route");
|
|
144
|
+
expect(enqueueCalls[0]!.metadata?.assistantMessageInterface).toBe("route");
|
|
145
|
+
expect(HUMAN_INTERFACES).not.toContain(
|
|
146
|
+
enqueueCalls[0]!.metadata?.userMessageInterface,
|
|
147
|
+
);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test("surfaces a rate_limited error when the turn queue is full", async () => {
|
|
151
|
+
conversationBusy = true;
|
|
152
|
+
enqueueResult = { queued: false, requestId: "x", rejected: true };
|
|
153
|
+
await expect(
|
|
154
|
+
postRouteConversationMessage("conv-busy", "event"),
|
|
155
|
+
).rejects.toMatchObject({ code: "rate_limited" });
|
|
156
|
+
expect(processCalls).toHaveLength(0);
|
|
157
|
+
});
|
|
158
|
+
});
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Post a message into a conversation from a workspace custom route.
|
|
3
|
+
*
|
|
4
|
+
* Lets integration routes (webhook receivers, cron-triggered handlers,
|
|
5
|
+
* device/service callbacks) surface an inbound event as a real assistant turn
|
|
6
|
+
* — "your deploy finished", "payment received" — instead of only publishing a
|
|
7
|
+
* client-side event via the event hub.
|
|
8
|
+
*
|
|
9
|
+
* Security posture (asserted by route-conversation-post.test.ts):
|
|
10
|
+
* - Attribution is unspoofable: every posted turn is stamped with the
|
|
11
|
+
* dedicated `route` interface. The caller cannot supply an interface, so a
|
|
12
|
+
* route can never impersonate a human surface (web / macos / cli / …).
|
|
13
|
+
* - No privilege escalation: the turn runs under the target conversation's
|
|
14
|
+
* existing trust context. This helper never passes a trust or auth context,
|
|
15
|
+
* so a route cannot grant itself guardian trust by posting a turn.
|
|
16
|
+
* - Loop backstop: a per-conversation rate limit bounds runaway
|
|
17
|
+
* route → assistant → route cycles.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { v7 as uuidv7 } from "uuid";
|
|
21
|
+
|
|
22
|
+
import type { InterfaceId } from "../channels/types.js";
|
|
23
|
+
import { getConversation } from "../persistence/conversation-crud.js";
|
|
24
|
+
import { getLogger } from "../util/logger.js";
|
|
25
|
+
import { getOrCreateConversation } from "./conversation-store.js";
|
|
26
|
+
import { processMessageInBackground } from "./process-message.js";
|
|
27
|
+
|
|
28
|
+
const log = getLogger("route-conversation-post");
|
|
29
|
+
|
|
30
|
+
/** Attribution interface for turns injected by workspace custom routes. */
|
|
31
|
+
const ROUTE_SOURCE_INTERFACE: InterfaceId = "route";
|
|
32
|
+
|
|
33
|
+
/** Loop backstop: max route-originated posts per conversation per window. */
|
|
34
|
+
const RATE_LIMIT_MAX = 5;
|
|
35
|
+
const RATE_LIMIT_WINDOW_MS = 60_000;
|
|
36
|
+
const recentPostTimestamps = new Map<string, number[]>();
|
|
37
|
+
|
|
38
|
+
export type RouteMessageErrorCode = "not_found" | "rate_limited" | "invalid";
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Typed failure surfaced by {@link postRouteConversationMessage}. A route
|
|
42
|
+
* handler can catch it and map `code` to an HTTP status, or let it propagate
|
|
43
|
+
* (the dispatcher renders it as a 500).
|
|
44
|
+
*/
|
|
45
|
+
export class RouteMessageError extends Error {
|
|
46
|
+
readonly code: RouteMessageErrorCode;
|
|
47
|
+
constructor(message: string, code: RouteMessageErrorCode) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.name = "RouteMessageError";
|
|
50
|
+
this.code = code;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function enforceRateLimit(conversationId: string): void {
|
|
55
|
+
const now = Date.now();
|
|
56
|
+
const cutoff = now - RATE_LIMIT_WINDOW_MS;
|
|
57
|
+
const recent = (recentPostTimestamps.get(conversationId) ?? []).filter(
|
|
58
|
+
(t) => t > cutoff,
|
|
59
|
+
);
|
|
60
|
+
if (recent.length >= RATE_LIMIT_MAX) {
|
|
61
|
+
throw new RouteMessageError(
|
|
62
|
+
`Route message rate limit exceeded for this conversation ` +
|
|
63
|
+
`(max ${RATE_LIMIT_MAX} per ${RATE_LIMIT_WINDOW_MS / 1000}s). ` +
|
|
64
|
+
`This backstops runaway route→assistant→route loops.`,
|
|
65
|
+
"rate_limited",
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
recent.push(now);
|
|
69
|
+
recentPostTimestamps.set(conversationId, recent);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Post `text` into an existing conversation as a real user turn attributed to
|
|
74
|
+
* the `route` interface, returning the persisted message id. The agent turn
|
|
75
|
+
* runs fire-and-forget (matching the conversation launcher), so this resolves
|
|
76
|
+
* as soon as the message is persisted and the loop is kicked off.
|
|
77
|
+
*
|
|
78
|
+
* @throws {@link RouteMessageError} with code `invalid` (missing id / empty
|
|
79
|
+
* text), `not_found` (unknown conversation — never silently creates one), or
|
|
80
|
+
* `rate_limited`.
|
|
81
|
+
*/
|
|
82
|
+
export async function postRouteConversationMessage(
|
|
83
|
+
conversationId: string,
|
|
84
|
+
text: string,
|
|
85
|
+
): Promise<{ messageId: string }> {
|
|
86
|
+
if (typeof conversationId !== "string" || conversationId.trim() === "") {
|
|
87
|
+
throw new RouteMessageError("conversationId is required", "invalid");
|
|
88
|
+
}
|
|
89
|
+
if (typeof text !== "string" || text.trim() === "") {
|
|
90
|
+
throw new RouteMessageError(
|
|
91
|
+
"message text must be a non-empty string",
|
|
92
|
+
"invalid",
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Reject unknown conversations explicitly. processMessageInBackground would
|
|
97
|
+
// otherwise create one via getOrCreateActiveConversation, letting a route
|
|
98
|
+
// spawn empty conversations from arbitrary ids.
|
|
99
|
+
if (!getConversation(conversationId)) {
|
|
100
|
+
throw new RouteMessageError(
|
|
101
|
+
`conversation not found: ${conversationId}`,
|
|
102
|
+
"not_found",
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
enforceRateLimit(conversationId);
|
|
107
|
+
|
|
108
|
+
// Attribution is fixed here — never taken from the caller — so a route cannot
|
|
109
|
+
// post as a human interface. Trust and auth contexts are intentionally
|
|
110
|
+
// omitted: the turn inherits the conversation's existing trust context and a
|
|
111
|
+
// route cannot elevate privilege by posting.
|
|
112
|
+
|
|
113
|
+
// Honor the standard send contract: queue when the conversation is mid-turn
|
|
114
|
+
// rather than dropping the event. A bursty integration (webhook, cron) that
|
|
115
|
+
// fires during an active turn would otherwise hit CONVERSATION_BUSY_MESSAGE
|
|
116
|
+
// and be lost. The queued turn carries the same `route` attribution via
|
|
117
|
+
// metadata so its drain is stamped correctly.
|
|
118
|
+
const conversation = await getOrCreateConversation(conversationId);
|
|
119
|
+
if (conversation.isProcessing()) {
|
|
120
|
+
const requestId = uuidv7();
|
|
121
|
+
const result = conversation.enqueueMessage({
|
|
122
|
+
content: text,
|
|
123
|
+
requestId,
|
|
124
|
+
metadata: {
|
|
125
|
+
userMessageChannel: "vellum",
|
|
126
|
+
assistantMessageChannel: "vellum",
|
|
127
|
+
userMessageInterface: ROUTE_SOURCE_INTERFACE,
|
|
128
|
+
assistantMessageInterface: ROUTE_SOURCE_INTERFACE,
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
if (result.rejected) {
|
|
132
|
+
throw new RouteMessageError(
|
|
133
|
+
"conversation queue is full; retry shortly",
|
|
134
|
+
"rate_limited",
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
if (result.queued) {
|
|
138
|
+
log.info(
|
|
139
|
+
{ conversationId, requestId },
|
|
140
|
+
"Route message queued behind an active turn",
|
|
141
|
+
);
|
|
142
|
+
return { messageId: requestId };
|
|
143
|
+
}
|
|
144
|
+
// The turn finished between the check and the enqueue — fall through and
|
|
145
|
+
// process immediately.
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const { messageId } = await processMessageInBackground(conversationId, text, {
|
|
149
|
+
sourceChannel: "vellum",
|
|
150
|
+
sourceInterface: ROUTE_SOURCE_INTERFACE,
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
log.info(
|
|
154
|
+
{ conversationId, messageId },
|
|
155
|
+
"Route posted a message into a conversation",
|
|
156
|
+
);
|
|
157
|
+
return { messageId };
|
|
158
|
+
}
|
|
@@ -19,6 +19,9 @@ function makeContext(overrides?: Partial<UserRouteContext>): UserRouteContext {
|
|
|
19
19
|
return {
|
|
20
20
|
assistantEventHub: new AssistantEventHub(),
|
|
21
21
|
assistantId: "test-assistant",
|
|
22
|
+
conversations: {
|
|
23
|
+
postMessage: async () => ({ messageId: "test-msg" }),
|
|
24
|
+
},
|
|
22
25
|
...overrides,
|
|
23
26
|
};
|
|
24
27
|
}
|
|
@@ -8,7 +8,12 @@ import { extname, join } from "node:path";
|
|
|
8
8
|
import JSZip from "jszip";
|
|
9
9
|
import { z } from "zod";
|
|
10
10
|
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
getApp,
|
|
13
|
+
getAppDirPath,
|
|
14
|
+
isMultifileApp,
|
|
15
|
+
readAppFileBytes,
|
|
16
|
+
} from "../../apps/app-store.js";
|
|
12
17
|
import {
|
|
13
18
|
createSharedAppLink,
|
|
14
19
|
deleteSharedAppLinkByToken,
|
|
@@ -165,8 +170,8 @@ function serveMultifileApp(appId: string, appName: string): string {
|
|
|
165
170
|
return html;
|
|
166
171
|
}
|
|
167
172
|
|
|
168
|
-
/** Content-Type map for static dist/ assets. */
|
|
169
|
-
const
|
|
173
|
+
/** Content-Type map for static app files (dist/ assets and bundled media). */
|
|
174
|
+
const STATIC_CONTENT_TYPES: Record<string, string> = {
|
|
170
175
|
".js": "application/javascript",
|
|
171
176
|
".css": "text/css",
|
|
172
177
|
".html": "text/html",
|
|
@@ -175,10 +180,32 @@ const DIST_CONTENT_TYPES: Record<string, string> = {
|
|
|
175
180
|
".png": "image/png",
|
|
176
181
|
".jpg": "image/jpeg",
|
|
177
182
|
".jpeg": "image/jpeg",
|
|
183
|
+
".gif": "image/gif",
|
|
184
|
+
".webp": "image/webp",
|
|
185
|
+
".avif": "image/avif",
|
|
186
|
+
".ico": "image/x-icon",
|
|
187
|
+
".mp4": "video/mp4",
|
|
188
|
+
".webm": "video/webm",
|
|
189
|
+
".ogv": "video/ogg",
|
|
190
|
+
".mov": "video/quicktime",
|
|
191
|
+
".mp3": "audio/mpeg",
|
|
192
|
+
".wav": "audio/wav",
|
|
193
|
+
".m4a": "audio/mp4",
|
|
194
|
+
".aac": "audio/aac",
|
|
195
|
+
".oga": "audio/ogg",
|
|
178
196
|
".woff2": "font/woff2",
|
|
179
197
|
".woff": "font/woff",
|
|
198
|
+
".ttf": "font/ttf",
|
|
199
|
+
".otf": "font/otf",
|
|
180
200
|
};
|
|
181
201
|
|
|
202
|
+
function contentTypeForPath(filePath: string): string {
|
|
203
|
+
return (
|
|
204
|
+
STATIC_CONTENT_TYPES[extname(filePath).toLowerCase()] ??
|
|
205
|
+
"application/octet-stream"
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
|
|
182
209
|
/**
|
|
183
210
|
* Serve a static file from an app's dist/ directory.
|
|
184
211
|
* Validates the filename to prevent path traversal.
|
|
@@ -217,6 +244,55 @@ function handleServeDistFile({ pathParams }: RouteHandlerArgs): Uint8Array {
|
|
|
217
244
|
return new Uint8Array(readFileSync(filePath));
|
|
218
245
|
}
|
|
219
246
|
|
|
247
|
+
/** 25 MB — generous cap for a single bundled app asset. */
|
|
248
|
+
const MAX_APP_ASSET_BYTES = 25 * 1024 * 1024;
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Serve a bundled file from anywhere in an app's directory (e.g.
|
|
252
|
+
* `assets/intro.mp4`), for binary media an app can't practically inline as a
|
|
253
|
+
* data-URI. `readAppFileBytes` runs the app-store path validation
|
|
254
|
+
* (rejects `..`, absolute paths, symlink escapes, and the protected
|
|
255
|
+
* `records/` directory), so authors bundle assets under the app dir and load
|
|
256
|
+
* them via `window.vellum.asset(path)`.
|
|
257
|
+
*/
|
|
258
|
+
function handleServeAppAsset({ pathParams }: RouteHandlerArgs): Uint8Array {
|
|
259
|
+
const appId = pathParams?.appId as string;
|
|
260
|
+
const assetPath = pathParams?.path as string;
|
|
261
|
+
|
|
262
|
+
if (
|
|
263
|
+
!appId ||
|
|
264
|
+
appId.includes("..") ||
|
|
265
|
+
appId.includes("/") ||
|
|
266
|
+
appId.includes("\\") ||
|
|
267
|
+
appId !== appId.trim()
|
|
268
|
+
) {
|
|
269
|
+
throw new BadRequestError("Invalid appId");
|
|
270
|
+
}
|
|
271
|
+
if (!assetPath || assetPath.trim() === "") {
|
|
272
|
+
throw new BadRequestError("Invalid asset path");
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
let bytes: Buffer;
|
|
276
|
+
try {
|
|
277
|
+
bytes = readAppFileBytes(appId, assetPath);
|
|
278
|
+
} catch (err) {
|
|
279
|
+
const message = err instanceof Error ? err.message : "";
|
|
280
|
+
if (message.includes("not found")) {
|
|
281
|
+
throw new NotFoundError("Asset not found");
|
|
282
|
+
}
|
|
283
|
+
// validateFilePath throws on traversal / absolute / records-dir access.
|
|
284
|
+
throw new BadRequestError("Invalid asset path");
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
if (bytes.byteLength > MAX_APP_ASSET_BYTES) {
|
|
288
|
+
throw new BadRequestError(
|
|
289
|
+
`Asset too large (limit: ${MAX_APP_ASSET_BYTES} bytes)`,
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return new Uint8Array(bytes);
|
|
294
|
+
}
|
|
295
|
+
|
|
220
296
|
/** 50 MB — generous cap for zip app bundles. */
|
|
221
297
|
const MAX_SHARE_BODY_BYTES = 50 * 1024 * 1024;
|
|
222
298
|
|
|
@@ -342,13 +418,29 @@ export const ROUTES: RouteDefinition[] = [
|
|
|
342
418
|
description: "Serve a static asset from an app's compiled dist/ directory.",
|
|
343
419
|
tags: ["apps"],
|
|
344
420
|
responseHeaders: ({ pathParams }) => ({
|
|
345
|
-
"Content-Type":
|
|
346
|
-
DIST_CONTENT_TYPES[extname(pathParams?.filename ?? "").toLowerCase()] ??
|
|
347
|
-
"application/octet-stream",
|
|
421
|
+
"Content-Type": contentTypeForPath(pathParams?.filename ?? ""),
|
|
348
422
|
"Cache-Control": "no-cache",
|
|
349
423
|
}),
|
|
350
424
|
handler: handleServeDistFile,
|
|
351
425
|
},
|
|
426
|
+
{
|
|
427
|
+
operationId: "apps_asset",
|
|
428
|
+
endpoint: "apps/:appId/asset/:path*",
|
|
429
|
+
method: "GET",
|
|
430
|
+
policy: {
|
|
431
|
+
requiredScopes: ["settings.read"],
|
|
432
|
+
allowedPrincipalTypes: ACTOR_PRINCIPALS,
|
|
433
|
+
},
|
|
434
|
+
summary: "Serve app asset",
|
|
435
|
+
description:
|
|
436
|
+
"Serve a bundled binary asset (image, audio, video, font) from anywhere in an app's directory.",
|
|
437
|
+
tags: ["apps"],
|
|
438
|
+
responseHeaders: ({ pathParams }) => ({
|
|
439
|
+
"Content-Type": contentTypeForPath(pathParams?.path ?? ""),
|
|
440
|
+
"Cache-Control": "no-cache",
|
|
441
|
+
}),
|
|
442
|
+
handler: handleServeAppAsset,
|
|
443
|
+
},
|
|
352
444
|
{
|
|
353
445
|
operationId: "apps_share",
|
|
354
446
|
endpoint: "apps/share",
|
|
@@ -44,6 +44,33 @@ export interface UserRouteContext {
|
|
|
44
44
|
readonly assistantEventHub: AssistantEventHub;
|
|
45
45
|
/** The logical assistant ID used by the daemon (typically "self"). */
|
|
46
46
|
readonly assistantId: string;
|
|
47
|
+
/** Conversation operations available to route handlers (e.g. posting integration events as turns). */
|
|
48
|
+
readonly conversations: RouteConversationsApi;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Conversation operations exposed to route handlers. Lets integration routes
|
|
53
|
+
* (webhook receivers, cron jobs, device/service callbacks) surface an inbound
|
|
54
|
+
* event as a real assistant turn rather than only a client-side event.
|
|
55
|
+
*/
|
|
56
|
+
export interface RouteConversationsApi {
|
|
57
|
+
/**
|
|
58
|
+
* Post a message into an existing conversation as a real assistant turn.
|
|
59
|
+
*
|
|
60
|
+
* The turn is attributed to a dedicated integration interface (never a human
|
|
61
|
+
* surface) and runs under the conversation's existing trust context — a
|
|
62
|
+
* route cannot impersonate a user or elevate privilege by posting. Unknown
|
|
63
|
+
* conversation ids are rejected (a route never silently creates one), and
|
|
64
|
+
* posts are rate-limited per conversation to backstop runaway loops.
|
|
65
|
+
*
|
|
66
|
+
* Rejects with a `RouteMessageError` carrying `code`
|
|
67
|
+
* (`"not_found" | "rate_limited" | "invalid"`) — catch it to map to an HTTP
|
|
68
|
+
* status, or let it surface as a 500.
|
|
69
|
+
*/
|
|
70
|
+
postMessage(
|
|
71
|
+
conversationId: string,
|
|
72
|
+
text: string,
|
|
73
|
+
): Promise<{ messageId: string }>;
|
|
47
74
|
}
|
|
48
75
|
|
|
49
76
|
// ---------------------------------------------------------------------------
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
* over both HTTP and IPC.
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
+
import { postRouteConversationMessage } from "../../daemon/route-conversation-post.js";
|
|
15
16
|
import { assistantEventHub } from "../assistant-event-hub.js";
|
|
16
17
|
import { DAEMON_INTERNAL_ASSISTANT_ID } from "../assistant-scope.js";
|
|
17
18
|
import { ACTOR_PRINCIPALS } from "../auth/route-policy.js";
|
|
@@ -23,6 +24,9 @@ const dispatcher = new UserRouteDispatcher({
|
|
|
23
24
|
context: {
|
|
24
25
|
assistantEventHub,
|
|
25
26
|
assistantId: DAEMON_INTERNAL_ASSISTANT_ID,
|
|
27
|
+
conversations: {
|
|
28
|
+
postMessage: postRouteConversationMessage,
|
|
29
|
+
},
|
|
26
30
|
},
|
|
27
31
|
});
|
|
28
32
|
|