@segmentstream/ontology 0.161.0 → 0.163.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -0
- package/dist/agent-draft.d.ts +21 -0
- package/dist/agent-draft.js +57 -1
- package/dist/deployment.d.ts +13 -1
- package/dist/deployment.js +8 -0
- package/dist/index.d.ts +6 -5
- package/dist/index.js +7 -6
- package/dist/manifest.js +1 -0
- package/dist/runtime/agent-web.js +42 -3
- package/dist/runtime/agents.js +6 -1
- package/dist/service/agent/authentication.js +9 -2
- package/dist/service/agent/eval-tokens.d.ts +25 -0
- package/dist/service/agent/eval-tokens.js +130 -0
- package/dist/service/agent/protocol.d.ts +20 -5
- package/dist/service/agent/protocol.js +25 -3
- package/dist/service/agent/server.d.ts +11 -0
- package/dist/service/agent/server.js +114 -5
- package/dist/service/agent/web-tokens.d.ts +13 -2
- package/dist/service/agent/web-tokens.js +20 -5
- package/dist/service/authentication.js +3 -2
- package/dist/service/chat/archive.d.ts +15 -1
- package/dist/service/chat/draft-files.d.ts +56 -0
- package/dist/service/chat/draft-files.js +137 -0
- package/dist/service/chat/idempotency.d.ts +6 -1
- package/dist/service/chat/idempotency.js +7 -1
- package/dist/service/chat/providers/custom.js +12 -2
- package/dist/service/chat/providers/email.d.ts +2 -1
- package/dist/service/chat/providers/email.js +48 -4
- package/dist/service/chat/providers/provider.d.ts +49 -1
- package/dist/service/chat/providers/provider.js +18 -1
- package/dist/service/chat/review-delivery.d.ts +2 -0
- package/dist/service/chat/review-delivery.js +73 -4
- package/dist/service/chat/store-delivery.js +13 -0
- package/dist/service/config.js +8 -2
- package/dist/service/runtime-contract.d.ts +33 -0
- package/dist/service/runtime-identity.d.ts +17 -1
- package/dist/service/runtime-identity.js +15 -2
- package/dist/service/service.js +64 -11
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { randomInt } from "node:crypto";
|
|
2
2
|
import { Schema } from "effect";
|
|
3
|
-
import { AGENT_DRAFT_PARTICIPANTS_LIMIT } from "../../agent-draft.js";
|
|
3
|
+
import { AGENT_DRAFT_FILES_LIMIT, AGENT_DRAFT_PARTICIPANTS_LIMIT } from "../../agent-draft.js";
|
|
4
4
|
import { ChatChannelName } from "../../chat-channel.js";
|
|
5
5
|
import { EMAIL_RECIPIENTS_LIMIT } from "../../email.js";
|
|
6
6
|
import { EMAIL_PATTERN } from "../../property.js";
|
|
@@ -186,6 +186,12 @@ export const ChatHandoffRequest = Schema.Struct({
|
|
|
186
186
|
* `POST /api/ontology/agent/drafts`: a reply the agent kept for a member to review, for the member
|
|
187
187
|
* it answers. `key` names the reply, so a report repeated after a failure finds its draft.
|
|
188
188
|
*/
|
|
189
|
+
/** A record file a held reply carries, by its entity, record and file property. */
|
|
190
|
+
const HeldFile = Schema.Struct({
|
|
191
|
+
entity: Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9_]{0,63}$/)),
|
|
192
|
+
id: Schema.String.check(Schema.isUUID()),
|
|
193
|
+
property: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9_]{0,63}$/))),
|
|
194
|
+
});
|
|
189
195
|
export const ReviewRequest = Schema.Struct({
|
|
190
196
|
key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512)).annotate({
|
|
191
197
|
description: "The agent's key for the reply: its session and content part.",
|
|
@@ -223,9 +229,15 @@ export const ReviewRequest = Schema.Struct({
|
|
|
223
229
|
session_id: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512)).annotate({
|
|
224
230
|
description: "The agent's session that wrote the reply.",
|
|
225
231
|
}),
|
|
226
|
-
text: Schema.String.check(Schema.
|
|
227
|
-
description: "The reply as the agent wrote it, in Markdown.",
|
|
232
|
+
text: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(20_000))).annotate({
|
|
233
|
+
description: "The reply as the agent wrote it, in Markdown; empty or absent only for a reply of files.",
|
|
228
234
|
}),
|
|
235
|
+
files: Schema.optionalKey(Schema.Array(HeldFile)
|
|
236
|
+
.check(Schema.isMinLength(1), Schema.isMaxLength(AGENT_DRAFT_FILES_LIMIT))
|
|
237
|
+
.annotate({
|
|
238
|
+
description: "Record files the reply carries, in order, which the person may read: approval sends " +
|
|
239
|
+
"the revision each holds now.",
|
|
240
|
+
})),
|
|
229
241
|
mode: Schema.Literals(["always", "whenUnsure"]).annotate({
|
|
230
242
|
description: "Why the reply was held: every reply is reviewed, or the model was unsure.",
|
|
231
243
|
}),
|
|
@@ -236,6 +248,16 @@ export const ReviewRequest = Schema.Struct({
|
|
|
236
248
|
description: "The agent's turn that wrote the reply.",
|
|
237
249
|
})),
|
|
238
250
|
});
|
|
251
|
+
/**
|
|
252
|
+
* `POST /api/ontology/agent/drafts/files`: whether a reply on a channel may carry these files, read
|
|
253
|
+
* as the member it is for, checked as holding it would check them, without holding anything.
|
|
254
|
+
*/
|
|
255
|
+
export const DraftFilesRequest = Schema.Struct({
|
|
256
|
+
provider: Provider,
|
|
257
|
+
channel: Schema.optionalKey(ChatChannelName),
|
|
258
|
+
member_id: Schema.String,
|
|
259
|
+
files: Schema.Array(HeldFile).check(Schema.isMinLength(1), Schema.isMaxLength(AGENT_DRAFT_FILES_LIMIT)),
|
|
260
|
+
});
|
|
239
261
|
/**
|
|
240
262
|
* `POST /api/ontology/agent/drafts/revision`: what became of a redraft a member asked for: the new
|
|
241
263
|
* draft, or, without `text`, that the agent could not write one.
|
|
@@ -8,6 +8,8 @@ import { type RuntimeTokenVerifier } from "../runtime-identity.js";
|
|
|
8
8
|
import { type AgentToolsOf } from "./protocol.js";
|
|
9
9
|
import { type VisitorWebsites } from "./web-tokens.js";
|
|
10
10
|
import type { BotCheckVerifier } from "./bot-check.js";
|
|
11
|
+
import type { DeploymentObservation } from "../../deployment.js";
|
|
12
|
+
import { type OntologyManifest } from "../../manifest.js";
|
|
11
13
|
import { GUEST_LINK_PATH, type EmailCodes } from "./guest-sign-up.js";
|
|
12
14
|
import type { ResolvedGuest } from "../../sign-in.js";
|
|
13
15
|
/** The agent's endpoints, under the ontology service's path. */
|
|
@@ -15,6 +17,8 @@ export declare const AGENT_PATH = "/api/ontology/agent";
|
|
|
15
17
|
/** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
|
|
16
18
|
export declare const AGENT_TOKENS_PATH = "/api/ontology/agent/tokens";
|
|
17
19
|
export declare const AGENT_TOKEN_INTROSPECTION_PATH = "/api/ontology/agent/tokens/introspect";
|
|
20
|
+
/** Where the platform issues an eval session's agent token, in a preview that runs the agent. */
|
|
21
|
+
export declare const AGENT_EVAL_TOKENS_PATH = "/api/ontology/agent/eval-tokens";
|
|
18
22
|
/** Where a browser on a declared website signs its visitor up on `web`. */
|
|
19
23
|
export declare const AGENT_VISITORS_PATH = "/api/ontology/agent/visitors";
|
|
20
24
|
/** A website's guests' own routes: becoming a user, and the runtime's report of their spend. */
|
|
@@ -52,6 +56,13 @@ export interface AgentServerOptions {
|
|
|
52
56
|
readonly cronSecret?: Redacted.Redacted<string> | undefined;
|
|
53
57
|
/** How many days the chats' messages are kept, as the ontology declares it. */
|
|
54
58
|
readonly chatRetentionDays?: number;
|
|
59
|
+
/**
|
|
60
|
+
* The preview deployment, in a preview that runs the agent: the platform issues eval sessions
|
|
61
|
+
* there, and introspection answers for their `agent-eval` tokens. Never set in production.
|
|
62
|
+
*/
|
|
63
|
+
readonly evalTokens?: DeploymentObservation;
|
|
64
|
+
/** The ontology, whose record files a held reply carries and whose channels send them. */
|
|
65
|
+
readonly manifest?: OntologyManifest;
|
|
55
66
|
}
|
|
56
67
|
/**
|
|
57
68
|
* The routes that pair channel accounts with members for the app's own agent, and record the group
|
|
@@ -13,10 +13,12 @@ import { secretHash } from "../oauth/protocol.js";
|
|
|
13
13
|
import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
|
|
14
14
|
import { OntologyBackend } from "../runtime-contract.js";
|
|
15
15
|
import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
|
|
16
|
-
import { ChatHandoffRequest, ChatSeenRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
|
|
16
|
+
import { ChatHandoffRequest, ChatSeenRequest, DraftFilesRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
|
|
17
17
|
import { AGENT_TOKEN_LIMIT, BOT_CHECK_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
|
|
18
|
+
import { issueEvalToken } from "./eval-tokens.js";
|
|
18
19
|
import { CHAT_MESSAGE_PATHS, changeChatMessage, purgeChatMessages, readChatMessages, recordChatMessage, } from "./chat-message-routes.js";
|
|
19
20
|
import { CHAT_RETENTION_DAYS } from "../../manifest.js";
|
|
21
|
+
import { snapshotDraftFiles } from "../chat/draft-files.js";
|
|
20
22
|
import { GUEST_LINK_PATH, guestRoutesPreflight, guestSignUpRoutes, recordGuestUsage, } from "./guest-sign-up.js";
|
|
21
23
|
import { identityToken } from "../operations.js";
|
|
22
24
|
/** The agent's endpoints, under the ontology service's path. */
|
|
@@ -32,6 +34,8 @@ const REVIEWS_PATH = `${AGENT_PATH}/reviews`;
|
|
|
32
34
|
/** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
|
|
33
35
|
export const AGENT_TOKENS_PATH = `${AGENT_PATH}/tokens`;
|
|
34
36
|
export const AGENT_TOKEN_INTROSPECTION_PATH = `${AGENT_TOKENS_PATH}/introspect`;
|
|
37
|
+
/** Where the platform issues an eval session's agent token, in a preview that runs the agent. */
|
|
38
|
+
export const AGENT_EVAL_TOKENS_PATH = `${AGENT_PATH}/eval-tokens`;
|
|
35
39
|
/** Where a browser on a declared website signs its visitor up on `web`. */
|
|
36
40
|
export const AGENT_VISITORS_PATH = `${AGENT_PATH}/visitors`;
|
|
37
41
|
/** A website's guests' own routes: becoming a user, and the runtime's report of their spend. */
|
|
@@ -353,7 +357,7 @@ function seeChat(store) {
|
|
|
353
357
|
* pending `agent_draft` for the member it answers, once per key; 404 when that member is not an
|
|
354
358
|
* active member, so the reply is neither sent nor kept.
|
|
355
359
|
*/
|
|
356
|
-
function holdReply(store) {
|
|
360
|
+
function holdReply(store, backend, manifest) {
|
|
357
361
|
return (request) => Effect.gen(function* () {
|
|
358
362
|
const requestId = yield* RequestId;
|
|
359
363
|
const decoded = Schema.decodeUnknownResult(ReviewRequest)(yield* jsonBody(request), {
|
|
@@ -387,6 +391,51 @@ function holdReply(store) {
|
|
|
387
391
|
{ path: [body.to === undefined ? "cc" : "to"], message: "Only a reply to mail has it." },
|
|
388
392
|
]);
|
|
389
393
|
}
|
|
394
|
+
const text = body.text ?? "";
|
|
395
|
+
// A reply is its text, its files, or both.
|
|
396
|
+
if (text.trim() === "" && body.files === undefined) {
|
|
397
|
+
return invalidBody(requestId, [
|
|
398
|
+
{ path: ["text"], message: "A reply without files has text." },
|
|
399
|
+
]);
|
|
400
|
+
}
|
|
401
|
+
const channel = body.channel ?? body.provider;
|
|
402
|
+
let files;
|
|
403
|
+
// A report repeated after a lost answer finds the draft its key holds, whatever became of
|
|
404
|
+
// its files since: only a new draft reads them.
|
|
405
|
+
const [existing] = body.files === undefined
|
|
406
|
+
? []
|
|
407
|
+
: (yield* backend
|
|
408
|
+
.find({ entity: "agent_draft", query: { where: { key: body.key }, limit: 1 } })
|
|
409
|
+
.pipe(Effect.orDie)).items;
|
|
410
|
+
if (existing !== undefined) {
|
|
411
|
+
return json({ id: String(existing.id), status: String(existing.status), created: false });
|
|
412
|
+
}
|
|
413
|
+
// Each file as the person may read it now, and as the channel sends it.
|
|
414
|
+
if (body.files !== undefined) {
|
|
415
|
+
const member = yield* store.member(body.member_id);
|
|
416
|
+
if (member === undefined) {
|
|
417
|
+
return toServerResponse(notFound(requestId, "The reply is for no active member."));
|
|
418
|
+
}
|
|
419
|
+
if (manifest === undefined) {
|
|
420
|
+
return HttpServerResponse.jsonUnsafe({ error: "files_unsupported", request_id: requestId }, { status: 422, headers: NO_STORE });
|
|
421
|
+
}
|
|
422
|
+
const snapshot = yield* snapshotDraftFiles({
|
|
423
|
+
manifest,
|
|
424
|
+
backend,
|
|
425
|
+
principal: member.principal,
|
|
426
|
+
channel,
|
|
427
|
+
files: body.files,
|
|
428
|
+
});
|
|
429
|
+
if ("refusal" in snapshot) {
|
|
430
|
+
yield* Effect.logInfo("ontology.agent.reply_files_refused").pipe(Effect.annotateLogs({ requestId, channel, refusal: snapshot.refusal }));
|
|
431
|
+
return HttpServerResponse.jsonUnsafe({
|
|
432
|
+
error: snapshot.refusal,
|
|
433
|
+
...(snapshot.index === undefined ? {} : { index: snapshot.index }),
|
|
434
|
+
request_id: requestId,
|
|
435
|
+
}, { status: 422, headers: NO_STORE });
|
|
436
|
+
}
|
|
437
|
+
files = snapshot.files;
|
|
438
|
+
}
|
|
390
439
|
const review = yield* store.holdReply({
|
|
391
440
|
key: body.key,
|
|
392
441
|
provider: body.provider,
|
|
@@ -402,7 +451,8 @@ function holdReply(store) {
|
|
|
402
451
|
replyTo: body.reply_to,
|
|
403
452
|
memberId: body.member_id,
|
|
404
453
|
sessionId: body.session_id,
|
|
405
|
-
text
|
|
454
|
+
text,
|
|
455
|
+
...(files === undefined ? {} : { files }),
|
|
406
456
|
mode: body.mode,
|
|
407
457
|
confidence: body.confidence,
|
|
408
458
|
...(body.turn_id === undefined ? {} : { turnId: body.turn_id }),
|
|
@@ -421,6 +471,57 @@ function holdReply(store) {
|
|
|
421
471
|
return json({ id: review.id, status: review.status, created: review.created });
|
|
422
472
|
});
|
|
423
473
|
}
|
|
474
|
+
/**
|
|
475
|
+
* `POST /api/ontology/agent/drafts/files` (runtime): the files a reply would carry, read as the
|
|
476
|
+
* member it is for and checked against its channel as holding the reply checks them, without
|
|
477
|
+
* holding anything: the agent asks before it promises a file in a reviewed chat. An ontology
|
|
478
|
+
* without draft files answers 404, which the agent takes as no files in reviewed chats.
|
|
479
|
+
*/
|
|
480
|
+
function checkDraftFiles(store, backend, manifest) {
|
|
481
|
+
return (request) => Effect.gen(function* () {
|
|
482
|
+
const requestId = yield* RequestId;
|
|
483
|
+
const decoded = Schema.decodeUnknownResult(DraftFilesRequest)(yield* jsonBody(request), {
|
|
484
|
+
errors: "all",
|
|
485
|
+
onExcessProperty: "error",
|
|
486
|
+
});
|
|
487
|
+
if (Result.isFailure(decoded)) {
|
|
488
|
+
return invalidBody(requestId, schemaIssues(decoded.failure));
|
|
489
|
+
}
|
|
490
|
+
const body = decoded.success;
|
|
491
|
+
const member = yield* store.member(body.member_id);
|
|
492
|
+
if (member === undefined) {
|
|
493
|
+
return toServerResponse(notFound(requestId, "The reply is for no active member."));
|
|
494
|
+
}
|
|
495
|
+
const snapshot = manifest === undefined
|
|
496
|
+
? { refusal: "files_unsupported" }
|
|
497
|
+
: yield* snapshotDraftFiles({
|
|
498
|
+
manifest,
|
|
499
|
+
backend,
|
|
500
|
+
principal: member.principal,
|
|
501
|
+
channel: body.channel ?? body.provider,
|
|
502
|
+
files: body.files,
|
|
503
|
+
});
|
|
504
|
+
return "refusal" in snapshot
|
|
505
|
+
? HttpServerResponse.jsonUnsafe({
|
|
506
|
+
error: snapshot.refusal,
|
|
507
|
+
...("index" in snapshot && snapshot.index !== undefined
|
|
508
|
+
? { index: snapshot.index }
|
|
509
|
+
: {}),
|
|
510
|
+
request_id: requestId,
|
|
511
|
+
}, { status: 422, headers: NO_STORE })
|
|
512
|
+
: HttpServerResponse.jsonUnsafe({
|
|
513
|
+
files: snapshot.files.map((file) => ({
|
|
514
|
+
entity: file.entity,
|
|
515
|
+
id: file.id,
|
|
516
|
+
property: file.property,
|
|
517
|
+
revision_id: file.revisionId,
|
|
518
|
+
filename: file.filename,
|
|
519
|
+
content_type: file.contentType,
|
|
520
|
+
size: file.size,
|
|
521
|
+
})),
|
|
522
|
+
}, { headers: NO_STORE });
|
|
523
|
+
});
|
|
524
|
+
}
|
|
424
525
|
/**
|
|
425
526
|
* `POST /api/ontology/agent/drafts/revision` (runtime): the agent redrafted a reply a member sent
|
|
426
527
|
* back, or could not. The new draft becomes a pending draft for the same person and chat that
|
|
@@ -624,14 +725,22 @@ export function agentLayer(options) {
|
|
|
624
725
|
yield* router.add("POST", `${AGENT_PATH}${CHAT_MESSAGE_PATHS.purge}`, purge);
|
|
625
726
|
}
|
|
626
727
|
for (const path of [DRAFTS_PATH, REVIEWS_PATH]) {
|
|
627
|
-
yield* router.add("POST", path, asRuntime(holdReply(store)));
|
|
728
|
+
yield* router.add("POST", path, asRuntime(holdReply(store, backend, options.manifest)));
|
|
628
729
|
yield* router.add("POST", `${path}/session`, asRuntime(sessionReviews(store)));
|
|
629
730
|
yield* router.add("POST", `${path}/revision`, asRuntime(revision(store)));
|
|
630
731
|
}
|
|
732
|
+
yield* router.add("POST", `${DRAFTS_PATH}/files`, asRuntime(checkDraftFiles(store, backend, options.manifest)));
|
|
631
733
|
yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
|
|
632
734
|
if (store.web !== undefined && backend.oauth !== undefined) {
|
|
633
735
|
yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
|
|
634
|
-
yield* router.add("POST", AGENT_TOKEN_INTROSPECTION_PATH, asRuntime(introspectAgentToken(store, store.web, backend.oauth, options.agentTools, options.guest)));
|
|
736
|
+
yield* router.add("POST", AGENT_TOKEN_INTROSPECTION_PATH, asRuntime(introspectAgentToken(store, store.web, backend.oauth, options.agentTools, options.guest, options.evalTokens !== undefined)));
|
|
737
|
+
if (options.evalTokens !== undefined) {
|
|
738
|
+
yield* router.add("POST", AGENT_EVAL_TOKENS_PATH, issueEvalToken({
|
|
739
|
+
deployment: options.evalTokens,
|
|
740
|
+
verifyToken: options.verifyToken,
|
|
741
|
+
web: store.web,
|
|
742
|
+
}));
|
|
743
|
+
}
|
|
635
744
|
const websites = options.visitorWebsites ?? { guests: [], signUp: [] };
|
|
636
745
|
const botCheck = options.guest?.botCheck === undefined || options.botCheckVerifier === undefined
|
|
637
746
|
? undefined
|
|
@@ -15,6 +15,14 @@ import { type AgentToolsOf } from "./protocol.js";
|
|
|
15
15
|
* stands for, and names the token's grant whenever it then acts for the member.
|
|
16
16
|
*/
|
|
17
17
|
export declare const AGENT_WEB_CLIENT_ID = "agent-web";
|
|
18
|
+
/**
|
|
19
|
+
* The first-party client of the grants with which a builder's evals reach the agent of an app
|
|
20
|
+
* preview, as a test member that exists only in the preview's branch: `POST
|
|
21
|
+
* /api/ontology/agent/eval-tokens` issues them, for the platform only. Its tokens are agent tokens
|
|
22
|
+
* like `agent-web`'s, which introspection marks `eval: true`. Outside a preview that runs the agent
|
|
23
|
+
* the client is refused outright, and a production ontology holds none of its grants.
|
|
24
|
+
*/
|
|
25
|
+
export declare const AGENT_EVAL_CLIENT_ID = "agent-eval";
|
|
18
26
|
/** The resource agent tokens are issued for: the agent's routes on the origin the member used. */
|
|
19
27
|
export declare function agentResource(origin: string): string;
|
|
20
28
|
/** Tokens one member may request per minute; the browser keeps one until it is about to expire. */
|
|
@@ -34,9 +42,12 @@ export declare function issueAgentToken(store: AgentStore, web: AgentWebStore, l
|
|
|
34
42
|
* member is starting a turn: someone `signUp` created has it counted against the agent's limits,
|
|
35
43
|
* and the answer names the limit it exceeds as `limited`. A guest's token is answered
|
|
36
44
|
* `{ active, guest_id, roles, grant_id, chat, agent_tools }`, without a member, and each of their
|
|
37
|
-
* turns counts against the agent's guest limits.
|
|
45
|
+
* turns counts against the agent's guest limits. In a preview that runs the agent, an `agent-eval`
|
|
46
|
+
* token is answered as a member's, with `eval: true`, and its turns count against no limit.
|
|
38
47
|
*/
|
|
39
|
-
export declare function introspectAgentToken(store: AgentStore, web: AgentWebStore, oauth: OAuthStore, agentTools: AgentToolsOf, guests?: Pick<ResolvedGuest, "confirmations"
|
|
48
|
+
export declare function introspectAgentToken(store: AgentStore, web: AgentWebStore, oauth: OAuthStore, agentTools: AgentToolsOf, guests?: Pick<ResolvedGuest, "confirmations">,
|
|
49
|
+
/** Whether `agent-eval` tokens count: only in a preview that runs the agent. */
|
|
50
|
+
evalGrants?: boolean): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
|
|
40
51
|
/** The headers that let a website on `origin` read an answer to its visitor's browser. */
|
|
41
52
|
export declare function websiteHeaders(origin: string): Record<string, string>;
|
|
42
53
|
/** The declared website a browser's request comes from, when it comes from one. */
|
|
@@ -18,6 +18,14 @@ import { AgentLimitsRequest } from "./protocol.js";
|
|
|
18
18
|
* stands for, and names the token's grant whenever it then acts for the member.
|
|
19
19
|
*/
|
|
20
20
|
export const AGENT_WEB_CLIENT_ID = "agent-web";
|
|
21
|
+
/**
|
|
22
|
+
* The first-party client of the grants with which a builder's evals reach the agent of an app
|
|
23
|
+
* preview, as a test member that exists only in the preview's branch: `POST
|
|
24
|
+
* /api/ontology/agent/eval-tokens` issues them, for the platform only. Its tokens are agent tokens
|
|
25
|
+
* like `agent-web`'s, which introspection marks `eval: true`. Outside a preview that runs the agent
|
|
26
|
+
* the client is refused outright, and a production ontology holds none of its grants.
|
|
27
|
+
*/
|
|
28
|
+
export const AGENT_EVAL_CLIENT_ID = "agent-eval";
|
|
21
29
|
/** The resource agent tokens are issued for: the agent's routes on the origin the member used. */
|
|
22
30
|
export function agentResource(origin) {
|
|
23
31
|
return new URL(`${BASE_PATH}/agent`, origin).href;
|
|
@@ -90,9 +98,12 @@ function originOf(value, request) {
|
|
|
90
98
|
* member is starting a turn: someone `signUp` created has it counted against the agent's limits,
|
|
91
99
|
* and the answer names the limit it exceeds as `limited`. A guest's token is answered
|
|
92
100
|
* `{ active, guest_id, roles, grant_id, chat, agent_tools }`, without a member, and each of their
|
|
93
|
-
* turns counts against the agent's guest limits.
|
|
101
|
+
* turns counts against the agent's guest limits. In a preview that runs the agent, an `agent-eval`
|
|
102
|
+
* token is answered as a member's, with `eval: true`, and its turns count against no limit.
|
|
94
103
|
*/
|
|
95
|
-
export function introspectAgentToken(store, web, oauth, agentTools, guests
|
|
104
|
+
export function introspectAgentToken(store, web, oauth, agentTools, guests,
|
|
105
|
+
/** Whether `agent-eval` tokens count: only in a preview that runs the agent. */
|
|
106
|
+
evalGrants = false) {
|
|
96
107
|
return (request) => Effect.gen(function* () {
|
|
97
108
|
const requestId = yield* RequestId;
|
|
98
109
|
const body = yield* Effect.map(Effect.orDie(request.text), (text) => {
|
|
@@ -150,14 +161,17 @@ export function introspectAgentToken(store, web, oauth, agentTools, guests) {
|
|
|
150
161
|
...limitedAs(limited),
|
|
151
162
|
});
|
|
152
163
|
}
|
|
153
|
-
const
|
|
154
|
-
|
|
164
|
+
const client = authenticated?.caller.kind === "oauth" ? authenticated.caller.client.id : undefined;
|
|
165
|
+
const evaluating = evalGrants && client === AGENT_EVAL_CLIENT_ID;
|
|
166
|
+
const member = authenticated !== undefined && (client === AGENT_WEB_CLIENT_ID || evaluating)
|
|
155
167
|
? yield* store.member(authenticated.principal.id)
|
|
156
168
|
: undefined;
|
|
157
169
|
if (authenticated === undefined || member === undefined) {
|
|
158
170
|
return json({ active: false });
|
|
159
171
|
}
|
|
160
|
-
|
|
172
|
+
// An eval's turns spend the workspace's budget as any turn does, but count against no
|
|
173
|
+
// member's limits: the test member exists only in the preview.
|
|
174
|
+
const limited = decoded.success.turn === true && !evaluating
|
|
161
175
|
? yield* web.countTurn(member.principal.id, limits)
|
|
162
176
|
: undefined;
|
|
163
177
|
return json({
|
|
@@ -168,6 +182,7 @@ export function introspectAgentToken(store, web, oauth, agentTools, guests) {
|
|
|
168
182
|
agent_tools: agentTools(member.principal),
|
|
169
183
|
grant_id: authenticated.grantId,
|
|
170
184
|
chat: personalChat(member.principal.id),
|
|
185
|
+
...(evaluating ? { eval: true } : {}),
|
|
171
186
|
...limitedAs(limited),
|
|
172
187
|
});
|
|
173
188
|
});
|
|
@@ -4,7 +4,7 @@ import { HttpApiMiddleware, HttpApiSecurity, OpenApi } from "effect/unstable/htt
|
|
|
4
4
|
import { createRemoteJWKSet, decodeJwt, decodeProtectedHeader, errors, jwtVerify, } from "jose";
|
|
5
5
|
import { channelIdentityProvider, WORKSPACE_CHANNEL_KIND, workspaceChannelOf, } from "../chat-channel.js";
|
|
6
6
|
import { CHANNEL_COOKIE_PATTERN } from "../channel-session.js";
|
|
7
|
-
import { requireDeploymentCapability } from "../deployment.js";
|
|
7
|
+
import { previewRunsAgent, requireDeploymentCapability, } from "../deployment.js";
|
|
8
8
|
import { API_KEY_PREFIX } from "../runtime/principals.js";
|
|
9
9
|
import { FEDERATION_TOKEN_PREFIX, federationDigest } from "../runtime/federation.js";
|
|
10
10
|
import { browserRevisionAdmitted, browserRevisionObservation, browserSessionAdmission, federationStatus, } from "./federation-status.js";
|
|
@@ -620,7 +620,8 @@ export function authenticate(credential, verifyToken, options = {}) {
|
|
|
620
620
|
((token.startsWith(FEDERATION_TOKEN_PREFIX) && !verifyToken.browserMethods) ||
|
|
621
621
|
token.startsWith(ACCESS_TOKEN_PREFIX) ||
|
|
622
622
|
token.startsWith(API_KEY_PREFIX) ||
|
|
623
|
-
|
|
623
|
+
// Only a preview that runs the agent admits its runtime.
|
|
624
|
+
(options.runtime !== undefined && !previewRunsAgent(verifyToken.deployment)))) {
|
|
624
625
|
return { status: "rejected" };
|
|
625
626
|
}
|
|
626
627
|
if (token === "") {
|
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import { Effect, Schema } from "effect";
|
|
2
2
|
import type { OntologyEnvironment } from "../config.js";
|
|
3
3
|
import type { ChatRequester } from "./attribution.js";
|
|
4
|
+
/** A file of a delivered message, as the chat's history shows it: its name, type and size. */
|
|
5
|
+
export interface DeliveryAttachment {
|
|
6
|
+
readonly id: string;
|
|
7
|
+
readonly kind: "file";
|
|
8
|
+
readonly filename: string;
|
|
9
|
+
readonly contentType: string;
|
|
10
|
+
readonly size: number;
|
|
11
|
+
}
|
|
4
12
|
export interface DeliveryEvent {
|
|
5
13
|
readonly eventId: string;
|
|
6
14
|
readonly operationId: string;
|
|
@@ -27,7 +35,13 @@ export interface DeliveryEvent {
|
|
|
27
35
|
readonly toolName: null;
|
|
28
36
|
readonly argsSummary: string | null;
|
|
29
37
|
readonly status: "requested" | "sent" | "uncertain" | "failed";
|
|
30
|
-
|
|
38
|
+
/** The files the message carries, as its history shows them: none but an approved draft's. */
|
|
39
|
+
readonly attachments: ReadonlyArray<DeliveryAttachment>;
|
|
40
|
+
/**
|
|
41
|
+
* The record files the message carries, each `[entity, id, property, revisionId]` in order,
|
|
42
|
+
* which bind the delivery: absent for a message of text alone, so its binding stays.
|
|
43
|
+
*/
|
|
44
|
+
readonly files?: ReadonlyArray<readonly [string, string, string, string]>;
|
|
31
45
|
readonly requestedBy: ChatRequester;
|
|
32
46
|
readonly url: string | null;
|
|
33
47
|
readonly at: string;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { AgentDraftFile } from "../../agent-draft.js";
|
|
3
|
+
import type { OntologyManifest } from "../../manifest.js";
|
|
4
|
+
import type { Principal } from "../../runtime.js";
|
|
5
|
+
import type { OntologyBackend } from "../runtime-contract.js";
|
|
6
|
+
import type { ChatFilesRefusal, ChatProvider, ChatSendFile } from "./providers/provider.js";
|
|
7
|
+
/**
|
|
8
|
+
* Record files a draft carries with its reply (`agent_draft.files`). The agent names them when it
|
|
9
|
+
* holds the reply; the ontology reads each as the person the reply is for and keeps the revision
|
|
10
|
+
* it read, which approval sends again only after reading it as that person once more. Nothing of a
|
|
11
|
+
* file's bytes is kept with the draft: the record keeps them, as long as it keeps that revision.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Why `provider` cannot send these files in one reply, checked before anything is reserved or
|
|
15
|
+
* sent: `files_unsupported` for a provider that sends none, `too_many_files` past its count,
|
|
16
|
+
* `file_too_large` past its bytes together, else what its own check says.
|
|
17
|
+
*/
|
|
18
|
+
export declare function refuseChatFiles(provider: ChatProvider, files: ReadonlyArray<{
|
|
19
|
+
readonly contentType: string;
|
|
20
|
+
readonly size: number;
|
|
21
|
+
}>): ChatFilesRefusal | undefined;
|
|
22
|
+
/** A file a reply names, by its record and file property. */
|
|
23
|
+
export interface DraftFileReference {
|
|
24
|
+
readonly entity: string;
|
|
25
|
+
readonly id: string;
|
|
26
|
+
readonly property?: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The files a reply on `channel` names, read as `principal`, the person it is for: each record's
|
|
30
|
+
* revision of the file now, with its name, type and size. A file the person may not read, or that
|
|
31
|
+
* is gone, refuses them all as `file_unavailable` with its index; files the channel cannot send
|
|
32
|
+
* as its refusal.
|
|
33
|
+
*/
|
|
34
|
+
export declare function snapshotDraftFiles(input: {
|
|
35
|
+
readonly manifest: OntologyManifest;
|
|
36
|
+
readonly backend: OntologyBackend["Service"];
|
|
37
|
+
readonly principal: Principal;
|
|
38
|
+
readonly channel: string;
|
|
39
|
+
readonly files: ReadonlyArray<DraftFileReference>;
|
|
40
|
+
}): Effect.Effect<{
|
|
41
|
+
readonly files: ReadonlyArray<AgentDraftFile>;
|
|
42
|
+
} | {
|
|
43
|
+
readonly refusal: ChatFilesRefusal;
|
|
44
|
+
readonly index?: number;
|
|
45
|
+
}>;
|
|
46
|
+
/**
|
|
47
|
+
* The bytes of a draft's files for its delivery, each read as `person`, the member the reply is
|
|
48
|
+
* for, at the revision the draft holds; undefined when any of them is gone, no longer retained, or
|
|
49
|
+
* no longer theirs to read, or reads other than the revision held.
|
|
50
|
+
*/
|
|
51
|
+
export declare function readDraftFiles(input: {
|
|
52
|
+
readonly backend: OntologyBackend["Service"];
|
|
53
|
+
readonly person: string | null;
|
|
54
|
+
readonly files: ReadonlyArray<AgentDraftFile>;
|
|
55
|
+
readonly fetch: typeof fetch;
|
|
56
|
+
}): Effect.Effect<ReadonlyArray<ChatSendFile> | undefined>;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { resolveFileRecord } from "../../runtime/files.js";
|
|
3
|
+
import { describeChatError } from "./diagnostics.js";
|
|
4
|
+
import { channelProvider } from "./providers/index.js";
|
|
5
|
+
/**
|
|
6
|
+
* Record files a draft carries with its reply (`agent_draft.files`). The agent names them when it
|
|
7
|
+
* holds the reply; the ontology reads each as the person the reply is for and keeps the revision
|
|
8
|
+
* it read, which approval sends again only after reading it as that person once more. Nothing of a
|
|
9
|
+
* file's bytes is kept with the draft: the record keeps them, as long as it keeps that revision.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Why `provider` cannot send these files in one reply, checked before anything is reserved or
|
|
13
|
+
* sent: `files_unsupported` for a provider that sends none, `too_many_files` past its count,
|
|
14
|
+
* `file_too_large` past its bytes together, else what its own check says.
|
|
15
|
+
*/
|
|
16
|
+
export function refuseChatFiles(provider, files) {
|
|
17
|
+
if (files.length === 0) {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
if (provider.files === undefined) {
|
|
21
|
+
return "files_unsupported";
|
|
22
|
+
}
|
|
23
|
+
if (files.length > provider.files.count) {
|
|
24
|
+
return "too_many_files";
|
|
25
|
+
}
|
|
26
|
+
if (files.reduce((total, file) => total + file.size, 0) > provider.files.bytes) {
|
|
27
|
+
return "file_too_large";
|
|
28
|
+
}
|
|
29
|
+
return provider.refuseFiles?.(files);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The files a reply on `channel` names, read as `principal`, the person it is for: each record's
|
|
33
|
+
* revision of the file now, with its name, type and size. A file the person may not read, or that
|
|
34
|
+
* is gone, refuses them all as `file_unavailable` with its index; files the channel cannot send
|
|
35
|
+
* as its refusal.
|
|
36
|
+
*/
|
|
37
|
+
export function snapshotDraftFiles(input) {
|
|
38
|
+
return Effect.gen(function* () {
|
|
39
|
+
const { backend, principal } = input;
|
|
40
|
+
const blobs = backend.blobs;
|
|
41
|
+
const files = [];
|
|
42
|
+
if (blobs === undefined) {
|
|
43
|
+
return { refusal: "file_unavailable", index: 0 };
|
|
44
|
+
}
|
|
45
|
+
for (const [index, reference] of input.files.entries()) {
|
|
46
|
+
const file = yield* resolveFileRecord({
|
|
47
|
+
manifest: input.manifest,
|
|
48
|
+
reads: backend,
|
|
49
|
+
principal,
|
|
50
|
+
reference,
|
|
51
|
+
}).pipe(
|
|
52
|
+
// The revision read, granted to the person: a scoped read they may not make refuses it.
|
|
53
|
+
Effect.tap((resolved) => blobs.download(resolved.entity, resolved.id, resolved.property, { revisionId: resolved.file.id }, principal)), Effect.map((resolved) => ({
|
|
54
|
+
entity: resolved.entity,
|
|
55
|
+
id: resolved.id.toLowerCase(),
|
|
56
|
+
property: resolved.property,
|
|
57
|
+
revisionId: resolved.file.id,
|
|
58
|
+
filename: resolved.file.filename,
|
|
59
|
+
contentType: resolved.file.contentType,
|
|
60
|
+
size: resolved.file.size,
|
|
61
|
+
})),
|
|
62
|
+
// A refusal or a missing record; a defect of the store still fails the request. The
|
|
63
|
+
// original reason stays in the operator log.
|
|
64
|
+
Effect.catch((cause) => Effect.logWarning("ontology.agent_draft.file_unavailable").pipe(Effect.annotateLogs({
|
|
65
|
+
phase: "hold",
|
|
66
|
+
index,
|
|
67
|
+
error: describeChatError(cause, (text) => text),
|
|
68
|
+
}), Effect.as(undefined))));
|
|
69
|
+
if (file === undefined) {
|
|
70
|
+
return { refusal: "file_unavailable", index };
|
|
71
|
+
}
|
|
72
|
+
files.push(file);
|
|
73
|
+
}
|
|
74
|
+
const provider = channelProvider(input.manifest.chat, input.channel);
|
|
75
|
+
const refusal = provider === undefined ? "files_unsupported" : refuseChatFiles(provider, files);
|
|
76
|
+
return refusal === undefined ? { files } : { refusal };
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The bytes of a draft's files for its delivery, each read as `person`, the member the reply is
|
|
81
|
+
* for, at the revision the draft holds; undefined when any of them is gone, no longer retained, or
|
|
82
|
+
* no longer theirs to read, or reads other than the revision held.
|
|
83
|
+
*/
|
|
84
|
+
export function readDraftFiles(input) {
|
|
85
|
+
return Effect.gen(function* () {
|
|
86
|
+
if (input.files.length === 0) {
|
|
87
|
+
return [];
|
|
88
|
+
}
|
|
89
|
+
const { blobs, agents } = input.backend;
|
|
90
|
+
const member = input.person === null || agents === undefined
|
|
91
|
+
? undefined
|
|
92
|
+
: yield* agents.member(input.person);
|
|
93
|
+
if (blobs === undefined || member === undefined) {
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
const read = [];
|
|
97
|
+
for (const file of input.files) {
|
|
98
|
+
const bytes = yield* blobs
|
|
99
|
+
.download(file.entity, file.id, file.property, { revisionId: file.revisionId }, member.principal)
|
|
100
|
+
.pipe(Effect.flatMap((grant) => Effect.tryPromise(async () => {
|
|
101
|
+
const response = await input.fetch(grant.url, {
|
|
102
|
+
method: grant.method,
|
|
103
|
+
headers: grant.headers,
|
|
104
|
+
});
|
|
105
|
+
if (!response.ok) {
|
|
106
|
+
await response.body?.cancel();
|
|
107
|
+
throw new Error(`Storage answered the file's read with status ${response.status}.`);
|
|
108
|
+
}
|
|
109
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
110
|
+
}).pipe(
|
|
111
|
+
// The grant's link is a credential: no diagnostic shows it.
|
|
112
|
+
Effect.mapError((cause) => ({ cause, secret: grant.url })))), Effect.catch((failure) => Effect.logWarning("ontology.agent_draft.file_unavailable").pipe(Effect.annotateLogs({
|
|
113
|
+
phase: "approve",
|
|
114
|
+
entity: file.entity,
|
|
115
|
+
id: file.id,
|
|
116
|
+
revisionId: file.revisionId,
|
|
117
|
+
error: typeof failure === "object" && failure !== null && "secret" in failure
|
|
118
|
+
? describeChatError(failure.cause, (text) => text.split(failure.secret).join("[redacted]"))
|
|
119
|
+
: describeChatError(failure, (text) => text),
|
|
120
|
+
}), Effect.as(undefined))));
|
|
121
|
+
if (bytes === undefined || bytes.byteLength !== file.size) {
|
|
122
|
+
if (bytes !== undefined) {
|
|
123
|
+
yield* Effect.logWarning("ontology.agent_draft.file_unavailable").pipe(Effect.annotateLogs({
|
|
124
|
+
phase: "approve",
|
|
125
|
+
entity: file.entity,
|
|
126
|
+
id: file.id,
|
|
127
|
+
revisionId: file.revisionId,
|
|
128
|
+
error: `The revision read has ${bytes.byteLength} bytes, not the ${file.size} held.`,
|
|
129
|
+
}));
|
|
130
|
+
}
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
read.push({ filename: file.filename, contentType: file.contentType, bytes });
|
|
134
|
+
}
|
|
135
|
+
return read;
|
|
136
|
+
});
|
|
137
|
+
}
|
|
@@ -46,5 +46,10 @@ buttons?: ChatButtonRows,
|
|
|
46
46
|
recipients?: {
|
|
47
47
|
readonly to: ReadonlyArray<string>;
|
|
48
48
|
readonly cc: ReadonlyArray<string>;
|
|
49
|
-
}
|
|
49
|
+
},
|
|
50
|
+
/**
|
|
51
|
+
* The record files a message carries, each `[entity, id, property, revisionId]` in order, bound
|
|
52
|
+
* when given so a key of text alone keeps its binding.
|
|
53
|
+
*/
|
|
54
|
+
files?: ReadonlyArray<readonly [string, string, string, string]>): string;
|
|
50
55
|
export {};
|
|
@@ -27,7 +27,12 @@ buttons,
|
|
|
27
27
|
* Whom a reply to mail goes to beside its destination, bound when given so a key that names no
|
|
28
28
|
* one else keeps its binding.
|
|
29
29
|
*/
|
|
30
|
-
recipients
|
|
30
|
+
recipients,
|
|
31
|
+
/**
|
|
32
|
+
* The record files a message carries, each `[entity, id, property, revisionId]` in order, bound
|
|
33
|
+
* when given so a key of text alone keeps its binding.
|
|
34
|
+
*/
|
|
35
|
+
files) {
|
|
31
36
|
const sorted = (values) => Object.entries(values).sort(([one], [other]) => (one < other ? -1 : one > other ? 1 : 0));
|
|
32
37
|
const media = template?.header?.media;
|
|
33
38
|
return digest(JSON.stringify([
|
|
@@ -40,6 +45,7 @@ recipients) {
|
|
|
40
45
|
preview.text,
|
|
41
46
|
...(buttons === undefined ? [] : [{ buttons }]),
|
|
42
47
|
...(recipients === undefined ? [] : [{ to: recipients.to, cc: recipients.cc }]),
|
|
48
|
+
...(files === undefined || files.length === 0 ? [] : [{ files }]),
|
|
43
49
|
]
|
|
44
50
|
: [
|
|
45
51
|
{
|