@tangle-network/agent-app 0.60.12 → 0.60.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-surfaces/cli.js +1 -1
- package/dist/agent-surfaces/index.d.ts +5 -2
- package/dist/agent-surfaces/index.js +1 -1
- package/dist/chat-routes/index.js +3 -2
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/{chunk-3G7IOCSV.js → chunk-HGKDZQ52.js} +14 -19
- package/dist/chunk-HGKDZQ52.js.map +1 -0
- package/dist/chunk-XB4KZVUV.js +151 -0
- package/dist/chunk-XB4KZVUV.js.map +1 -0
- package/dist/{chunk-FNRUXPXE.js → chunk-XPTYP3FP.js} +2 -2
- package/dist/chunk-YG66IHDU.js +80 -0
- package/dist/chunk-YG66IHDU.js.map +1 -0
- package/dist/{chunk-53K4S3K6.js → chunk-YXYQ6MJL.js} +1 -78
- package/dist/chunk-YXYQ6MJL.js.map +1 -0
- package/dist/operator/chat-adapter.d.ts +98 -0
- package/dist/operator/index.d.ts +2 -0
- package/dist/operator/index.js +307 -7
- package/dist/operator/index.js.map +1 -1
- package/dist/operator/platform-agent-keys.d.ts +47 -0
- package/dist/platform/agent-keys.d.ts +63 -0
- package/dist/platform/index.d.ts +1 -0
- package/dist/platform/index.js +12 -2
- package/dist/platform/index.js.map +1 -1
- package/dist/public-consultation/index.d.ts +2 -2
- package/dist/public-consultation/index.js +3 -2
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/stream/index.js +6 -4
- package/package.json +3 -3
- package/dist/chunk-3G7IOCSV.js.map +0 -1
- package/dist/chunk-53K4S3K6.js.map +0 -1
- package/dist/chunk-MLDKEEFQ.js +0 -48
- package/dist/chunk-MLDKEEFQ.js.map +0 -1
- /package/dist/{chunk-FNRUXPXE.js.map → chunk-XPTYP3FP.js.map} +0 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { OperatorApproval, OperatorAssetRef, OperatorFile, OperatorFileEntry, OperatorJournalEntry, OperatorRole, OperatorScorecard } from './contract';
|
|
2
|
+
import { type OperatorAdapter, type OperatorContext } from './server';
|
|
3
|
+
/** The message fields the adapter reads; agent-app's chat-store rows satisfy it. */
|
|
4
|
+
export interface ChatOperatorMessage {
|
|
5
|
+
id: string;
|
|
6
|
+
role: 'user' | 'assistant' | 'system' | 'tool';
|
|
7
|
+
content: string;
|
|
8
|
+
parts: ReadonlyArray<Record<string, unknown>> | null;
|
|
9
|
+
createdAt: Date | string | number;
|
|
10
|
+
model?: string | null;
|
|
11
|
+
servedModel?: string | null;
|
|
12
|
+
costUsd?: number | null;
|
|
13
|
+
}
|
|
14
|
+
export interface ChatOperatorThread {
|
|
15
|
+
id: string;
|
|
16
|
+
workspaceId: string;
|
|
17
|
+
title: string;
|
|
18
|
+
updatedAt?: Date | string | number | null;
|
|
19
|
+
}
|
|
20
|
+
export interface ChatOperatorWorkspace {
|
|
21
|
+
id: string;
|
|
22
|
+
name: string;
|
|
23
|
+
role?: OperatorRole;
|
|
24
|
+
createdAt?: Date | string | number | null;
|
|
25
|
+
}
|
|
26
|
+
export interface ChatOperatorAdapterOptions<Identity> {
|
|
27
|
+
/** The app's public origin, the base of every browser link. */
|
|
28
|
+
origin: string;
|
|
29
|
+
/** Browser path of a conversation; defaults to `/app/<workspace>/chat/<thread>`. */
|
|
30
|
+
threadPath?(workspaceId: string, threadId: string): string;
|
|
31
|
+
/** Browser path of a workspace; defaults to `/app/<workspace>`. */
|
|
32
|
+
workspacePath?(workspaceId: string): string;
|
|
33
|
+
workspaces: {
|
|
34
|
+
/** Apply the app's roles: `read` needs viewer access, `run` the role that may start agent work. */
|
|
35
|
+
authorize(ctx: OperatorContext<Identity>, workspaceId: string, access: 'read' | 'run'): Promise<ChatOperatorWorkspace | null>;
|
|
36
|
+
list(ctx: OperatorContext<Identity>): Promise<ChatOperatorWorkspace[]>;
|
|
37
|
+
create?(ctx: OperatorContext<Identity>, input: {
|
|
38
|
+
name: string;
|
|
39
|
+
}): Promise<ChatOperatorWorkspace>;
|
|
40
|
+
};
|
|
41
|
+
threads: {
|
|
42
|
+
get(threadId: string): Promise<ChatOperatorThread | null>;
|
|
43
|
+
/** Insert a thread with this id; agent-app's chat store accepts a caller-assigned id. */
|
|
44
|
+
create(input: {
|
|
45
|
+
id: string;
|
|
46
|
+
workspaceId: string;
|
|
47
|
+
title: string;
|
|
48
|
+
}): Promise<ChatOperatorThread>;
|
|
49
|
+
/** Oldest first. */
|
|
50
|
+
listMessages(threadId: string): Promise<ChatOperatorMessage[]>;
|
|
51
|
+
list?(ctx: OperatorContext<Identity>, workspaceId: string, query: {
|
|
52
|
+
cursor?: string;
|
|
53
|
+
limit: number;
|
|
54
|
+
}): Promise<{
|
|
55
|
+
threads: ChatOperatorThread[];
|
|
56
|
+
nextCursor: string | null;
|
|
57
|
+
}>;
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Run one turn through the app's own chat route as this caller. The adapter
|
|
61
|
+
* reads the response to its end, so the turn is driven exactly as a browser
|
|
62
|
+
* holding its stream drives it, and the start request returns once it settles.
|
|
63
|
+
*/
|
|
64
|
+
runTurn(ctx: OperatorContext<Identity>, input: {
|
|
65
|
+
workspaceId: string;
|
|
66
|
+
threadId: string;
|
|
67
|
+
turnId: string;
|
|
68
|
+
content: string;
|
|
69
|
+
model?: string;
|
|
70
|
+
}): Promise<Response>;
|
|
71
|
+
/** Turn ids still running on a thread, or null when the app cannot tell. */
|
|
72
|
+
runningTurns?(ctx: OperatorContext<Identity>, workspaceId: string, threadId: string): Promise<string[] | null>;
|
|
73
|
+
/** Decisions open in the workspace, or on one conversation when `threadId` is set. */
|
|
74
|
+
approvals?(ctx: OperatorContext<Identity>, workspaceId: string, threadId?: string): Promise<OperatorApproval[]>;
|
|
75
|
+
files?: {
|
|
76
|
+
list(ctx: OperatorContext<Identity>, workspaceId: string, prefix: string): Promise<OperatorFileEntry[]>;
|
|
77
|
+
read(ctx: OperatorContext<Identity>, workspaceId: string, path: string): Promise<OperatorFile | null>;
|
|
78
|
+
};
|
|
79
|
+
journal?(ctx: OperatorContext<Identity>, workspaceId: string, days: number): Promise<OperatorJournalEntry[]>;
|
|
80
|
+
assets?: {
|
|
81
|
+
/** Assets a reply references; defaults to none. */
|
|
82
|
+
refs?(message: ChatOperatorMessage, workspaceId: string): OperatorAssetRef[];
|
|
83
|
+
read?(ctx: OperatorContext<Identity>, workspaceId: string, assetId: string): Promise<Response | null>;
|
|
84
|
+
};
|
|
85
|
+
scorecard?(ctx: OperatorContext<Identity>, workspaceId: string, days: number): Promise<OperatorScorecard>;
|
|
86
|
+
/** A reply's failure; defaults to a `turn-failure` notice or an `error` part. */
|
|
87
|
+
failureOf?(message: ChatOperatorMessage): {
|
|
88
|
+
code?: string;
|
|
89
|
+
message: string;
|
|
90
|
+
} | null;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* The operator adapter for an app built on agent-app's chat stack: threads and
|
|
94
|
+
* messages from its chat store, turns through its own chat route. The app
|
|
95
|
+
* supplies its workspace roles and, optionally, files, journal, approvals,
|
|
96
|
+
* assets, and a scorecard.
|
|
97
|
+
*/
|
|
98
|
+
export declare function createChatOperatorAdapter<Identity>(options: ChatOperatorAdapterOptions<Identity>): OperatorAdapter<Identity>;
|
package/dist/operator/index.d.ts
CHANGED
package/dist/operator/index.js
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import {
|
|
2
|
+
PLATFORM_KEY_PREFIX,
|
|
3
|
+
agentOperatorScopes,
|
|
2
4
|
createApiKeyRequestAuth
|
|
3
|
-
} from "../chunk-
|
|
5
|
+
} from "../chunk-XB4KZVUV.js";
|
|
4
6
|
import {
|
|
5
7
|
createApiKeyFetch
|
|
6
8
|
} from "../chunk-RN4WPTBH.js";
|
|
9
|
+
import {
|
|
10
|
+
messageHasTurnId
|
|
11
|
+
} from "../chunk-YG66IHDU.js";
|
|
7
12
|
|
|
8
13
|
// src/operator/contract.ts
|
|
9
14
|
var OPERATOR_API_VERSION = "v1";
|
|
@@ -146,13 +151,13 @@ function relativePath(value, name, { allowEmpty }) {
|
|
|
146
151
|
async function readJsonBody(request) {
|
|
147
152
|
const declared = Number(request.headers.get("content-length") ?? "0");
|
|
148
153
|
if (declared > MAX_BODY_BYTES) throw new OperatorError("operator.body_too_large", 413, "Request body is too large");
|
|
149
|
-
const
|
|
150
|
-
if (new TextEncoder().encode(
|
|
154
|
+
const text2 = await request.text();
|
|
155
|
+
if (new TextEncoder().encode(text2).byteLength > MAX_BODY_BYTES) {
|
|
151
156
|
throw new OperatorError("operator.body_too_large", 413, "Request body is too large");
|
|
152
157
|
}
|
|
153
158
|
let parsed;
|
|
154
159
|
try {
|
|
155
|
-
parsed = JSON.parse(
|
|
160
|
+
parsed = JSON.parse(text2);
|
|
156
161
|
} catch {
|
|
157
162
|
throw new OperatorError("operator.invalid_json", 400, "Body must be a JSON object");
|
|
158
163
|
}
|
|
@@ -433,8 +438,8 @@ function createOperatorClient(options) {
|
|
|
433
438
|
const query = (params) => {
|
|
434
439
|
const search = new URLSearchParams();
|
|
435
440
|
for (const [name, value] of Object.entries(params)) if (value !== void 0 && value !== "") search.set(name, String(value));
|
|
436
|
-
const
|
|
437
|
-
return
|
|
441
|
+
const text2 = search.toString();
|
|
442
|
+
return text2 ? `?${text2}` : "";
|
|
438
443
|
};
|
|
439
444
|
const client = {
|
|
440
445
|
describe: () => call("", (body) => body),
|
|
@@ -514,6 +519,299 @@ function createOperatorClient(options) {
|
|
|
514
519
|
};
|
|
515
520
|
return client;
|
|
516
521
|
}
|
|
522
|
+
|
|
523
|
+
// src/operator/chat-adapter.ts
|
|
524
|
+
var iso = (value) => {
|
|
525
|
+
if (value === null || value === void 0) return void 0;
|
|
526
|
+
const date = value instanceof Date ? value : new Date(typeof value === "number" && value < 1e12 ? value * 1e3 : value);
|
|
527
|
+
return Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
|
|
528
|
+
};
|
|
529
|
+
var text = (value) => typeof value === "string" && value.trim() ? value : null;
|
|
530
|
+
function defaultFailure(message) {
|
|
531
|
+
for (const part of message.parts ?? []) {
|
|
532
|
+
const notice = part.type === "notice" && (part.noticeKind === "turn-failure" || part.kind === "turn-failure");
|
|
533
|
+
if (!notice && part.type !== "error") continue;
|
|
534
|
+
const detail = text(part.message) ?? text(part.text) ?? text(part.error) ?? "The turn failed";
|
|
535
|
+
return { ...typeof part.code === "string" ? { code: part.code } : {}, message: detail };
|
|
536
|
+
}
|
|
537
|
+
return null;
|
|
538
|
+
}
|
|
539
|
+
function fileChanges(message) {
|
|
540
|
+
const files = [];
|
|
541
|
+
for (const part of message.parts ?? []) {
|
|
542
|
+
if (part.type !== "session-artifact" || typeof part.path !== "string") continue;
|
|
543
|
+
const action = part.action === "created" || part.action === "updated" || part.action === "deleted" ? part.action : "changed";
|
|
544
|
+
if (!files.some((file) => file.path === part.path)) files.push({ path: part.path, action });
|
|
545
|
+
}
|
|
546
|
+
return files;
|
|
547
|
+
}
|
|
548
|
+
function turnIdOf(message) {
|
|
549
|
+
for (const part of message.parts ?? []) {
|
|
550
|
+
if (typeof part.turnId === "string" && part.turnId) return part.turnId;
|
|
551
|
+
}
|
|
552
|
+
return null;
|
|
553
|
+
}
|
|
554
|
+
async function sha256Hex(value) {
|
|
555
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
|
|
556
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
557
|
+
}
|
|
558
|
+
async function drain(response, signal) {
|
|
559
|
+
if (!response.body) return;
|
|
560
|
+
const reader = response.body.getReader();
|
|
561
|
+
const stop = () => {
|
|
562
|
+
void reader.cancel().catch(() => {
|
|
563
|
+
});
|
|
564
|
+
};
|
|
565
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
566
|
+
try {
|
|
567
|
+
while (!(await reader.read()).done) {
|
|
568
|
+
}
|
|
569
|
+
} finally {
|
|
570
|
+
signal.removeEventListener("abort", stop);
|
|
571
|
+
reader.releaseLock();
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
function createChatOperatorAdapter(options) {
|
|
575
|
+
const origin = options.origin.replace(/\/$/, "");
|
|
576
|
+
const threadUrl = (workspaceId, threadId) => origin + (options.threadPath?.(workspaceId, threadId) ?? `/app/${workspaceId}/chat/${threadId}`);
|
|
577
|
+
const workspaceView = (workspace) => ({
|
|
578
|
+
id: workspace.id,
|
|
579
|
+
name: workspace.name,
|
|
580
|
+
...workspace.role ? { role: workspace.role } : {},
|
|
581
|
+
url: origin + (options.workspacePath?.(workspace.id) ?? `/app/${workspace.id}`),
|
|
582
|
+
...iso(workspace.createdAt) ? { createdAt: iso(workspace.createdAt) } : {}
|
|
583
|
+
});
|
|
584
|
+
const threadView = (thread) => ({
|
|
585
|
+
id: thread.id,
|
|
586
|
+
title: thread.title,
|
|
587
|
+
url: threadUrl(thread.workspaceId, thread.id),
|
|
588
|
+
...iso(thread.updatedAt) ? { updatedAt: iso(thread.updatedAt) } : {}
|
|
589
|
+
});
|
|
590
|
+
async function threadIn(workspaceId, threadId) {
|
|
591
|
+
const thread = await options.threads.get(threadId);
|
|
592
|
+
return thread && thread.workspaceId === workspaceId ? thread : null;
|
|
593
|
+
}
|
|
594
|
+
async function turnOf(ctx, workspaceId, threadId, turnId) {
|
|
595
|
+
const messages = await options.threads.listMessages(threadId);
|
|
596
|
+
const userIndex = messages.findIndex((message) => message.role === "user" && messageHasTurnId(message, turnId));
|
|
597
|
+
if (userIndex < 0) return null;
|
|
598
|
+
const later = messages.slice(userIndex + 1);
|
|
599
|
+
const nextUser = later.findIndex((message) => message.role === "user");
|
|
600
|
+
const window = nextUser < 0 ? later : later.slice(0, nextUser);
|
|
601
|
+
const assistant = [...window].reverse().find((message) => message.role === "assistant") ?? null;
|
|
602
|
+
const latest = nextUser < 0;
|
|
603
|
+
const running = latest && options.runningTurns ? await options.runningTurns(ctx, workspaceId, threadId) : [];
|
|
604
|
+
const turn = {
|
|
605
|
+
workspaceId,
|
|
606
|
+
threadId,
|
|
607
|
+
turnId,
|
|
608
|
+
state: "unknown",
|
|
609
|
+
url: threadUrl(workspaceId, threadId),
|
|
610
|
+
reply: null,
|
|
611
|
+
failure: null,
|
|
612
|
+
assets: [],
|
|
613
|
+
files: [],
|
|
614
|
+
approvals: []
|
|
615
|
+
};
|
|
616
|
+
let state = running === null ? "unknown" : running.length > 0 ? "working" : "unknown";
|
|
617
|
+
if (assistant) {
|
|
618
|
+
turn.files = fileChanges(assistant);
|
|
619
|
+
turn.assets = options.assets?.refs?.(assistant, workspaceId) ?? [];
|
|
620
|
+
const model = assistant.servedModel ?? assistant.model;
|
|
621
|
+
if (model) turn.model = model;
|
|
622
|
+
if (typeof assistant.costUsd === "number") turn.costUsd = assistant.costUsd;
|
|
623
|
+
if (state !== "working") {
|
|
624
|
+
const failure2 = (options.failureOf ?? defaultFailure)(assistant);
|
|
625
|
+
if (failure2) {
|
|
626
|
+
state = "failed";
|
|
627
|
+
turn.failure = failure2;
|
|
628
|
+
} else if (assistant.content.trim()) {
|
|
629
|
+
state = "succeeded";
|
|
630
|
+
turn.reply = { content: assistant.content, mediaType: "text/markdown" };
|
|
631
|
+
}
|
|
632
|
+
const completedAt = iso(assistant.createdAt);
|
|
633
|
+
if (completedAt && (state === "succeeded" || state === "failed")) turn.completedAt = completedAt;
|
|
634
|
+
}
|
|
635
|
+
} else if (state !== "working" && !latest) {
|
|
636
|
+
state = "failed";
|
|
637
|
+
turn.failure = { message: "The turn ended without a reply" };
|
|
638
|
+
}
|
|
639
|
+
turn.state = state;
|
|
640
|
+
if (state !== "succeeded" && state !== "failed" && options.approvals) {
|
|
641
|
+
turn.approvals = await options.approvals(ctx, workspaceId, threadId);
|
|
642
|
+
}
|
|
643
|
+
return turn;
|
|
644
|
+
}
|
|
645
|
+
async function ensureThread(ctx, workspaceId, input) {
|
|
646
|
+
const id = (await sha256Hex(`operator-thread\0${ctx.key.keyId}\0${workspaceId}\0${input.turnId}`)).slice(0, 32);
|
|
647
|
+
const existing = await options.threads.get(id);
|
|
648
|
+
if (existing) {
|
|
649
|
+
if (existing.workspaceId !== workspaceId) throw new OperatorError("operator.turn_identity_conflict", 409, "This turn id belongs to another conversation");
|
|
650
|
+
return id;
|
|
651
|
+
}
|
|
652
|
+
const title = (input.title ?? input.content.split("\n").find((line) => line.trim()) ?? "New conversation").trim().slice(0, 80);
|
|
653
|
+
try {
|
|
654
|
+
await options.threads.create({ id, workspaceId, title });
|
|
655
|
+
} catch (error) {
|
|
656
|
+
if (!await threadIn(workspaceId, id)) throw error;
|
|
657
|
+
}
|
|
658
|
+
return id;
|
|
659
|
+
}
|
|
660
|
+
const adapter = {
|
|
661
|
+
async authorizeWorkspace(ctx, workspaceId, access) {
|
|
662
|
+
const workspace = await options.workspaces.authorize(ctx, workspaceId, access);
|
|
663
|
+
return workspace ? workspaceView(workspace) : null;
|
|
664
|
+
},
|
|
665
|
+
async listWorkspaces(ctx) {
|
|
666
|
+
return (await options.workspaces.list(ctx)).map(workspaceView);
|
|
667
|
+
},
|
|
668
|
+
async startTurn(ctx, workspace, input) {
|
|
669
|
+
let threadId = input.threadId;
|
|
670
|
+
if (threadId === void 0) {
|
|
671
|
+
threadId = await ensureThread(ctx, workspace.id, input);
|
|
672
|
+
} else if (!await threadIn(workspace.id, threadId)) {
|
|
673
|
+
throw new OperatorError("operator.thread_not_found", 404, "Thread not found");
|
|
674
|
+
}
|
|
675
|
+
const existing = await turnOf(ctx, workspace.id, threadId, input.turnId);
|
|
676
|
+
if (existing) return existing;
|
|
677
|
+
const response = await options.runTurn(ctx, {
|
|
678
|
+
workspaceId: workspace.id,
|
|
679
|
+
threadId,
|
|
680
|
+
turnId: input.turnId,
|
|
681
|
+
content: input.content,
|
|
682
|
+
...input.model === void 0 ? {} : { model: input.model }
|
|
683
|
+
});
|
|
684
|
+
if (!response.ok) {
|
|
685
|
+
const body = await response.json().catch(() => ({}));
|
|
686
|
+
throw new OperatorError(
|
|
687
|
+
typeof body.code === "string" ? body.code : `operator.chat_${response.status}`,
|
|
688
|
+
response.status,
|
|
689
|
+
typeof body.error === "string" ? body.error : "The app refused the turn",
|
|
690
|
+
response.status === 429 || response.status >= 500
|
|
691
|
+
);
|
|
692
|
+
}
|
|
693
|
+
await drain(response, ctx.request.signal);
|
|
694
|
+
return await turnOf(ctx, workspace.id, threadId, input.turnId) ?? {
|
|
695
|
+
workspaceId: workspace.id,
|
|
696
|
+
threadId,
|
|
697
|
+
turnId: input.turnId,
|
|
698
|
+
state: "unknown",
|
|
699
|
+
url: threadUrl(workspace.id, threadId),
|
|
700
|
+
reply: null,
|
|
701
|
+
failure: null,
|
|
702
|
+
assets: [],
|
|
703
|
+
files: [],
|
|
704
|
+
approvals: []
|
|
705
|
+
};
|
|
706
|
+
},
|
|
707
|
+
async getTurn(ctx, workspace, target) {
|
|
708
|
+
if (!await threadIn(workspace.id, target.threadId)) return null;
|
|
709
|
+
return turnOf(ctx, workspace.id, target.threadId, target.turnId);
|
|
710
|
+
},
|
|
711
|
+
async getThread(ctx, workspace, threadId) {
|
|
712
|
+
const thread = await threadIn(workspace.id, threadId);
|
|
713
|
+
if (!thread) return null;
|
|
714
|
+
const messages = await options.threads.listMessages(threadId);
|
|
715
|
+
const lastUser = [...messages].reverse().find((message) => message.role === "user");
|
|
716
|
+
const turnId = lastUser ? turnIdOf(lastUser) : null;
|
|
717
|
+
return { thread: threadView(thread), latestTurn: turnId ? await turnOf(ctx, workspace.id, threadId, turnId) : null };
|
|
718
|
+
},
|
|
719
|
+
listApprovals: (ctx, workspace) => options.approvals ? options.approvals(ctx, workspace.id) : Promise.resolve([])
|
|
720
|
+
};
|
|
721
|
+
if (options.workspaces.create) {
|
|
722
|
+
const create = options.workspaces.create;
|
|
723
|
+
adapter.createWorkspace = async (ctx, input) => workspaceView(await create(ctx, input));
|
|
724
|
+
}
|
|
725
|
+
if (options.threads.list) {
|
|
726
|
+
const list = options.threads.list;
|
|
727
|
+
adapter.listThreads = async (ctx, workspace, query) => {
|
|
728
|
+
const page = await list(ctx, workspace.id, query);
|
|
729
|
+
return { threads: page.threads.map(threadView), nextCursor: page.nextCursor };
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
if (options.files) {
|
|
733
|
+
const files = options.files;
|
|
734
|
+
adapter.listFiles = (ctx, workspace, query) => files.list(ctx, workspace.id, query.prefix);
|
|
735
|
+
adapter.readFile = (ctx, workspace, path) => files.read(ctx, workspace.id, path);
|
|
736
|
+
}
|
|
737
|
+
if (options.journal) {
|
|
738
|
+
const journal = options.journal;
|
|
739
|
+
adapter.listJournal = (ctx, workspace, query) => journal(ctx, workspace.id, query.days);
|
|
740
|
+
}
|
|
741
|
+
if (options.assets?.read) {
|
|
742
|
+
const read = options.assets.read;
|
|
743
|
+
adapter.readAsset = (ctx, workspace, assetId) => read(ctx, workspace.id, assetId);
|
|
744
|
+
}
|
|
745
|
+
if (options.scorecard) {
|
|
746
|
+
const scorecard = options.scorecard;
|
|
747
|
+
adapter.getScorecard = (ctx, workspace, query) => scorecard(ctx, workspace.id, query.days);
|
|
748
|
+
}
|
|
749
|
+
return adapter;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
// src/operator/platform-agent-keys.ts
|
|
753
|
+
var OPERATOR_ACTIONS = ["read", "write", "run"];
|
|
754
|
+
function refused(status, code, error) {
|
|
755
|
+
return Response.json({ error, code }, { status, headers: { "cache-control": "private, no-store" } });
|
|
756
|
+
}
|
|
757
|
+
function isPlatformAgentKey(key) {
|
|
758
|
+
return key.source === "platform-agent";
|
|
759
|
+
}
|
|
760
|
+
function withPlatformAgentKeys(appKeys, access) {
|
|
761
|
+
async function provisionOwner(verified, rawKey) {
|
|
762
|
+
const resolution = await access.accounts.resolveAccount({ email: verified.email, platformUserId: verified.platformUserId });
|
|
763
|
+
if (resolution.kind === "reject") {
|
|
764
|
+
throw refused(403, "agent_key.account_conflict", `The key owner's Tangle identity conflicts with an account in this app (${resolution.reason}).`);
|
|
765
|
+
}
|
|
766
|
+
if (resolution.kind === "existing" && resolution.matchedBy === "platform-id") return resolution.userId;
|
|
767
|
+
const { userId } = await access.accounts.upsertUserByEmail({
|
|
768
|
+
email: verified.email,
|
|
769
|
+
name: verified.name,
|
|
770
|
+
tangleUserId: verified.platformUserId,
|
|
771
|
+
resolution
|
|
772
|
+
});
|
|
773
|
+
await access.accounts.saveTangleLink({
|
|
774
|
+
userId,
|
|
775
|
+
sessionToken: "",
|
|
776
|
+
tangleUserId: verified.platformUserId,
|
|
777
|
+
email: verified.email,
|
|
778
|
+
name: verified.name,
|
|
779
|
+
apiKey: rawKey,
|
|
780
|
+
planTier: null
|
|
781
|
+
});
|
|
782
|
+
return userId;
|
|
783
|
+
}
|
|
784
|
+
return {
|
|
785
|
+
async verify(authorization) {
|
|
786
|
+
const raw = /^Bearer +(\S+)$/i.exec(authorization)?.[1];
|
|
787
|
+
if (!raw?.startsWith(PLATFORM_KEY_PREFIX)) return appKeys.verify(authorization);
|
|
788
|
+
const verified = await access.verifier.verify(raw);
|
|
789
|
+
if (!verified.ok) throw refused(verified.status, verified.code, verified.message);
|
|
790
|
+
const scopes = agentOperatorScopes(verified.scopes, access.product, OPERATOR_ACTIONS);
|
|
791
|
+
if (scopes.length === 0) {
|
|
792
|
+
throw refused(403, "agent_key.product_not_granted", "The key's owner did not approve it for this app.");
|
|
793
|
+
}
|
|
794
|
+
const ownerId = await provisionOwner(verified, raw);
|
|
795
|
+
return {
|
|
796
|
+
keyId: verified.keyId,
|
|
797
|
+
ownerId,
|
|
798
|
+
scopes,
|
|
799
|
+
// The operator API requires a finite expiry. This one bounds the
|
|
800
|
+
// request being authorized; the next request asks Platform again once
|
|
801
|
+
// the verifier's short cache lapses.
|
|
802
|
+
expiresAt: Math.max(verified.validUntil, Date.now() + 3e4),
|
|
803
|
+
source: "platform-agent"
|
|
804
|
+
};
|
|
805
|
+
},
|
|
806
|
+
async resolveIdentity(key) {
|
|
807
|
+
return isPlatformAgentKey(key) ? access.loadIdentity(key.ownerId) : appKeys.resolveIdentity(key);
|
|
808
|
+
},
|
|
809
|
+
async claimRequest(key, requestId) {
|
|
810
|
+
if (!isPlatformAgentKey(key)) return appKeys.claimRequest(key, requestId);
|
|
811
|
+
return access.claimRequest ? access.claimRequest(key.keyId, requestId) : { allowed: true };
|
|
812
|
+
}
|
|
813
|
+
};
|
|
814
|
+
}
|
|
517
815
|
export {
|
|
518
816
|
OPERATOR_ACCESS,
|
|
519
817
|
OPERATOR_API_BASE_PATH,
|
|
@@ -524,10 +822,12 @@ export {
|
|
|
524
822
|
OPERATOR_SETTLED_STATES,
|
|
525
823
|
OPERATOR_WORKSPACE_SCOPE_PREFIX,
|
|
526
824
|
OperatorError,
|
|
825
|
+
createChatOperatorAdapter,
|
|
527
826
|
createOperatorApi,
|
|
528
827
|
createOperatorClient,
|
|
529
828
|
matchOperatorRoute,
|
|
530
829
|
operatorKeyWorkspaces,
|
|
531
|
-
operatorWorkspaceScope
|
|
830
|
+
operatorWorkspaceScope,
|
|
831
|
+
withPlatformAgentKeys
|
|
532
832
|
};
|
|
533
833
|
//# sourceMappingURL=index.js.map
|