forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.ts
More file actions
186 lines (169 loc) · 5.57 KB
/
Copy paththread.ts
File metadata and controls
186 lines (169 loc) · 5.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import type { PlatformAdapter, ReplyTarget } from "./platform-adapter.js";
import type { ActionRegistry } from "./action-registry.js";
import type {
Renderable,
MessageRef,
PlatformUser,
ThreadMessage,
Thread as ThreadInterface,
} from "@copilotkit/bot-ui";
import { runAgentLoop } from "./run-loop.js";
import { toAgentToolDescriptors } from "./tools.js";
import type {
BotTool,
BotToolContext,
ContextEntry,
AgentToolDescriptor,
} from "./tools.js";
import type { AbstractAgent } from "@ag-ui/client";
export interface ThreadDeps {
adapter: PlatformAdapter;
replyTarget: ReplyTarget;
conversationKey: string;
registry: ActionRegistry;
agentFactory: (threadId: string) => AbstractAgent;
tools: Map<string, BotTool>;
toolDescriptors: AgentToolDescriptor[];
context: ContextEntry[];
registerWaiter: (
conversationKey: string,
resolve: (value: unknown) => void,
) => void;
interruptHandlers: Map<
string,
(args: { payload: unknown; thread: Thread }) => void | Promise<void>
>;
}
/** A concrete conversation thread: posts UI, runs the agent loop, and resolves HITL waiters. */
export class Thread implements ThreadInterface {
readonly platform: string;
constructor(private deps: ThreadDeps) {
this.platform = deps.adapter.platform;
}
private async bindForPost(ui: Renderable) {
return this.deps.registry.bindRenderable(ui, this.deps.conversationKey);
}
async post(ui: Renderable): Promise<MessageRef> {
return this.deps.adapter.post(
this.deps.replyTarget,
await this.bindForPost(ui),
);
}
async update(ref: MessageRef, ui: Renderable): Promise<MessageRef> {
await this.deps.adapter.update(ref, await this.bindForPost(ui));
return ref;
}
async delete(ref: MessageRef): Promise<void> {
await this.deps.adapter.delete(ref);
}
async stream(src: string | AsyncIterable<string>): Promise<MessageRef> {
const iter =
typeof src === "string"
? (async function* () {
yield src;
})()
: src;
return this.deps.adapter.stream(this.deps.replyTarget, iter);
}
async postFile(args: {
bytes: Uint8Array;
filename: string;
title?: string;
altText?: string;
}): Promise<{ ok: boolean; fileId?: string; error?: string }> {
const adapter = this.deps.adapter;
if (!adapter.postFile) {
return {
ok: false,
error: `${this.platform} does not support file upload`,
};
}
return adapter.postFile(this.deps.replyTarget, args);
}
/** Read the conversation's messages (returns `[]` when the adapter can't read history). */
async getMessages(): Promise<ThreadMessage[]> {
return (await this.deps.adapter.getMessages?.(this.deps.replyTarget)) ?? [];
}
/** Resolve a platform user by free-form query (returns `undefined` when unsupported). */
async lookupUser(query: string): Promise<PlatformUser | undefined> {
return this.deps.adapter.lookupUser?.({ query });
}
/** Post a picker and wait until an interaction in this conversation resolves it. */
async awaitChoice<T = unknown>(ui: Renderable): Promise<T> {
const p = new Promise<T>((resolve) =>
this.deps.registerWaiter(
this.deps.conversationKey,
resolve as (value: unknown) => void,
),
);
await this.post(ui);
return p;
}
async runAgent(input?: {
context?: ContextEntry[];
tools?: BotTool[];
/**
* A user message to inject before running. Needed when the input isn't
* already in the conversation history the adapter reconstructs — e.g. a
* slash command, whose args are never posted to the channel.
*/
prompt?: string;
}): Promise<MessageRef | undefined> {
return this.run(undefined, input);
}
async resume(value: unknown): Promise<MessageRef | undefined> {
return this.run({ resume: value });
}
private async run(
initialResume?: { resume: unknown },
extra?: { context?: ContextEntry[]; tools?: BotTool[]; prompt?: string },
): Promise<MessageRef | undefined> {
const session = await this.deps.adapter.conversationStore.getOrCreate(
this.deps.conversationKey,
this.deps.replyTarget,
this.deps.agentFactory,
);
// Inject an explicit user message when the input isn't in the adapter's
// reconstructed history (e.g. a slash command's args).
if (extra?.prompt) {
session.agent.addMessage({
id: globalThis.crypto.randomUUID(),
role: "user",
content: extra.prompt,
});
}
const renderer = this.deps.adapter.createRunRenderer(this.deps.replyTarget);
// Merge per-run context/tools (this run only) on top of the bot-level deps.
const extraTools = extra?.tools ?? [];
let tools = this.deps.tools;
let toolDescriptors = this.deps.toolDescriptors;
if (extraTools.length > 0) {
tools = new Map(this.deps.tools);
for (const t of extraTools) tools.set(t.name, t);
toolDescriptors = [
...this.deps.toolDescriptors,
...toAgentToolDescriptors(extraTools),
];
}
const context = extra?.context?.length
? [...this.deps.context, ...extra.context]
: this.deps.context;
await runAgentLoop({
agent: session.agent,
renderer,
tools,
toolDescriptors,
context,
makeToolCtx: (): BotToolContext => ({
thread: this,
platform: this.platform,
}),
handleInterrupt: async (interrupt) => {
const h = this.deps.interruptHandlers.get(interrupt.eventName);
if (h) await h({ payload: interrupt.value, thread: this });
},
initialResume,
});
return undefined;
}
}