-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcommand-service.ts
237 lines (213 loc) · 7.95 KB
/
command-service.ts
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import { getOwner, setOwner } from '@ember/owner';
import Service, { service } from '@ember/service';
import { isTesting } from '@embroider/macros';
import { task, timeout, all } from 'ember-concurrency';
import { IEvent } from 'matrix-js-sdk';
import { TrackedSet } from 'tracked-built-ins';
import { v4 as uuidv4 } from 'uuid';
import {
Command,
type PatchData,
CommandContext,
CommandContextStamp,
ResolvedCodeRef,
isResolvedCodeRef,
getClass,
} from '@cardstack/runtime-common';
import type MatrixService from '@cardstack/host/services/matrix-service';
import type OperatorModeStateService from '@cardstack/host/services/operator-mode-state-service';
import type Realm from '@cardstack/host/services/realm';
import type { CardDef } from 'https://cardstack.com/base/card-api';
import { SearchCardsByTypeAndTitleCommand } from '../commands/search-cards';
import MessageCommand from '../lib/matrix-classes/message-command';
import { shortenUuid } from '../utils/uuid';
import CardService from './card-service';
import RealmServerService from './realm-server';
import type LoaderService from './loader-service';
const DELAY_FOR_APPLYING_UI = isTesting() ? 50 : 500;
type GenericCommand = Command<
typeof CardDef | undefined,
typeof CardDef | undefined
>;
export default class CommandService extends Service {
@service private declare operatorModeStateService: OperatorModeStateService;
@service private declare matrixService: MatrixService;
@service private declare cardService: CardService;
@service private declare loaderService: LoaderService;
@service private declare realm: Realm;
@service private declare realmServer: RealmServerService;
currentlyExecutingCommandEventIds = new TrackedSet<string>();
private commands: Map<
string,
{
command: GenericCommand;
autoExecute: boolean;
}
> = new Map();
public registerCommand(command: GenericCommand, autoExecute: boolean) {
let name = `${command.name}_${shortenUuid(uuidv4())}`;
this.commands.set(name, { command, autoExecute });
return name;
}
public async executeCommandEventIfNeeded(event: Partial<IEvent>) {
let eventId = event.event_id;
if (event.content?.['m.relates_to']?.rel_type === 'm.replace') {
eventId = event.content?.['m.relates_to']!.event_id;
}
if (!eventId) {
throw new Error(
'No event id found for command event, this should not happen',
);
}
// examine the tool_call and see if it's a command that we know how to run
let toolCall = event?.content?.data?.toolCall;
if (!toolCall) {
return;
}
// TODO: check whether this toolCall was already executed and exit if so
let { name } = toolCall;
let { command, autoExecute } = this.commands.get(name) ?? {};
if (!command || !autoExecute) {
return;
}
this.currentlyExecutingCommandEventIds.add(eventId);
try {
// Get the input type and validate/construct the payload
let InputType = await command.getInputType();
// Construct a new instance of the input type with the
// The input is undefined if the command has no input type
let typedInput;
if (InputType) {
typedInput = new InputType({
...toolCall.arguments.attributes,
...toolCall.arguments.relationships,
});
} else {
typedInput = undefined;
}
let resultCard = await command.execute(typedInput as any);
await this.matrixService.sendCommandResultEvent(
event.room_id!,
eventId,
resultCard,
);
} finally {
this.currentlyExecutingCommandEventIds.delete(eventId);
}
}
get commandContext(): CommandContext {
let result = {
[CommandContextStamp]: true,
};
setOwner(result, getOwner(this)!);
return result;
}
//TODO: Convert to non-EC async method after fixing CS-6987
run = task(async (command: MessageCommand) => {
let { payload, eventId } = command;
let resultCard: CardDef | undefined;
try {
this.matrixService.failedCommandState.delete(eventId);
this.currentlyExecutingCommandEventIds.add(eventId);
// lookup command
let { command: commandToRun } = this.commands.get(command.name) ?? {};
// If we don't find it in the one-offs, start searching for
// one in the skills we can construct
if (!commandToRun) {
// here we can get the coderef from the messagecommand
let commandCodeRef = await command.getCommandCodeRef();
if (commandCodeRef) {
let CommandConstructor = (await getClass(
commandCodeRef,
this.loaderService.loader,
)) as { new (context: CommandContext): Command<any, any> };
commandToRun = new CommandConstructor(this.commandContext);
}
}
if (commandToRun) {
// Get the input type and validate/construct the payload
let InputType = await commandToRun.getInputType();
// Construct a new instance of the input type with the payload
// The input is undefined if the command has no input type
let typedInput;
if (InputType) {
typedInput = new InputType({
...payload.attributes,
...payload.relationships,
});
} else {
typedInput = undefined;
}
[resultCard] = await all([
await commandToRun.execute(typedInput as any),
await timeout(DELAY_FOR_APPLYING_UI), // leave a beat for the "applying" state of the UI to be shown
]);
} else if (command.name === 'patchCard') {
if (!hasPatchData(payload)) {
throw new Error(
"Patch command can't run because it doesn't have all the fields in arguments returned by open ai",
);
}
await this.operatorModeStateService.patchCard.perform(
payload?.attributes?.cardId,
{
attributes: payload?.attributes?.patch?.attributes,
relationships: payload?.attributes?.patch?.relationships,
},
);
} else if (command.name === 'searchCardsByTypeAndTitle') {
if (!hasSearchData(payload)) {
throw new Error(
"Search command can't run because it doesn't have all the arguments returned by open ai",
);
}
let command = new SearchCardsByTypeAndTitleCommand(this.commandContext);
resultCard = await command.execute({
title: payload.attributes.title,
cardType: payload.attributes.cardType,
type: payload.attributes.type,
});
} else {
// Unrecognized command. This can happen if a programmatically-provided command is no longer available due to a browser refresh.
throw new Error(
`Unrecognized command: ${command.name}. This command may have been associated with a previous browser session.`,
);
}
await this.matrixService.sendCommandResultEvent(
command.message.roomId,
eventId,
resultCard,
);
} catch (e) {
let error =
typeof e === 'string'
? new Error(e)
: e instanceof Error
? e
: new Error('Command failed.');
console.warn(error);
await timeout(DELAY_FOR_APPLYING_UI); // leave a beat for the "applying" state of the UI to be shown
this.matrixService.failedCommandState.set(eventId, error);
} finally {
this.currentlyExecutingCommandEventIds.delete(eventId);
}
});
}
type PatchPayload = { attributes: { cardId: string; patch: PatchData } };
type SearchPayload = {
attributes: { cardType?: string; title?: string; type?: ResolvedCodeRef };
};
function hasPatchData(payload: any): payload is PatchPayload {
return (
payload.attributes?.cardId &&
(payload.attributes?.patch?.attributes ||
payload.attributes?.patch?.relationships)
);
}
function hasSearchData(payload: any): payload is SearchPayload {
return (
isResolvedCodeRef(payload.attributes?.type) ||
payload.attributes?.title ||
payload.attributes?.cardType
);
}