-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathagent.ts
More file actions
98 lines (84 loc) · 2.5 KB
/
Copy pathagent.ts
File metadata and controls
98 lines (84 loc) · 2.5 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
import {
DestroyRef,
Injectable,
inject,
signal,
computed,
Signal,
} from "@angular/core";
import { CopilotKit } from "./copilotkit";
import type { AbstractAgent } from "@ag-ui/client";
import type { Message } from "@ag-ui/client";
import { DEFAULT_AGENT_ID } from "@copilotkitnext/shared";
export class AgentStore {
readonly #subscription?: {
unsubscribe: () => void;
};
readonly #isRunning = signal<boolean>(false);
readonly #messages = signal<Message[]>([]);
readonly #state = signal<any>(undefined);
readonly agent: AbstractAgent;
readonly isRunning = this.#isRunning.asReadonly();
readonly messages = this.#messages.asReadonly();
readonly state = this.#state.asReadonly();
constructor(abstractAgent: AbstractAgent, destroyRef: DestroyRef) {
this.agent = abstractAgent;
this.#subscription = abstractAgent.subscribe({
onMessagesChanged: () => {
this.#messages.set(abstractAgent.messages);
},
onStateChanged: () => {
this.#state.set(abstractAgent.state);
},
onRunInitialized: () => {
this.#isRunning.set(true);
},
onRunFinalized: () => {
this.#isRunning.set(false);
},
onRunFailed: () => {
this.#isRunning.set(false);
},
});
destroyRef.onDestroy(() => {
this.teardown();
});
}
teardown(): void {
if (this.#subscription) {
this.#subscription.unsubscribe();
}
}
}
@Injectable({ providedIn: "root" })
export class CopilotkitAgentFactory {
readonly #copilotkit = inject(CopilotKit);
createAgentStoreSignal(
agentId: Signal<string | undefined>,
destroyRef: DestroyRef
): Signal<AgentStore | undefined> {
let lastAgentStore: AgentStore | undefined;
return computed(() => {
this.#copilotkit.agents();
if (lastAgentStore) {
lastAgentStore.teardown();
lastAgentStore = undefined;
}
const abstractAgent = this.#copilotkit.getAgent(
agentId() || DEFAULT_AGENT_ID
);
if (!abstractAgent) return undefined;
lastAgentStore = new AgentStore(abstractAgent, destroyRef);
return lastAgentStore;
});
}
}
export function injectAgentStore(
agentId: string | Signal<string | undefined>
): Signal<AgentStore | undefined> {
const agentFactory = inject(CopilotkitAgentFactory);
const destroyRef = inject(DestroyRef);
const agentIdSignal =
typeof agentId === "function" ? agentId : computed(() => agentId);
return agentFactory.createAgentStoreSignal(agentIdSignal, destroyRef);
}