Repository navigation
Expand file tree
/
Copy pathbuilder.ts
More file actions
895 lines (851 loc) · 29.3 KB
/
Copy pathbuilder.ts
File metadata and controls
895 lines (851 loc) · 29.3 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
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
import type {AdminAuthentication} from './types';
import type {AdminAuthenticationDef} from './types';
import type {AgentDefinition} from './types';
import type {AgentTool} from './types';
import type {AgentToolsDef} from './types';
import type {AllowedAuthentication} from './types';
import type {AllowedAuthenticationDef} from './types';
import type {Authentication} from './types';
import {AuthenticationType} from './types';
import type {BasicPackDefinition} from './types';
import {ConnectionRequirement} from './api_types';
import type {DeepReadonly} from './type_utils';
import type {DefaultTriggerDefinition} from './types';
import {DefaultTriggerKind} from './types';
import type {DistributiveOmit} from './type_utils';
import type {DynamicSyncTableOptions} from './api';
import type {EventTriggerDefinition} from './types';
import {EventTriggerType} from './types';
import type {Format} from './types';
import type {Formula} from './api';
import type {FormulaDefinitionOptions} from './api';
import type {MCPServer} from './types';
import type {MailEventTriggerDefinition} from './types';
import type {NotetakerEventTriggerDefinition} from './types';
import type {ObjectSchema} from './schema';
import type {ObjectSchemaDefinition} from './schema';
import type {PackVersionDefinition} from './types';
import type {ParamDefs} from './api_types';
import type {PartialSkillDef} from './types';
import type {ScheduleTriggerDefinition} from './types';
import type {Schema} from './schema';
import type {Skill} from './types';
import type {SkillEntrypoints} from './types';
import type {SlackEventTriggerDefinition} from './types';
import type {SuggestedPrompt} from './types';
import type {SyncExecutionContext} from './api_types';
import type {SyncPassthroughData} from './api';
import type {SyncTable} from './api';
import type {SyncTableOptions} from './api';
import type {SystemAuthentication} from './types';
import type {SystemAuthenticationDef} from './types';
import {ToolType} from './types';
import type {UserAuthenticationDef} from './api_types';
import type {ValueType} from './schema';
import type {WhileWritingTriggerDefinition} from './types';
import {deepCopy} from './helpers/object_utils';
import {deepFreeze} from './helpers/object_utils';
import {isDynamicSyncTable} from './api';
import {makeDynamicSyncTable} from './api';
import {makeFormula} from './api';
import {makeSyncTable} from './api';
import {maybeRewriteConnectionForFormula} from './api';
import {maybeRewriteConnectionForNamedPropertyOptions} from './api';
import {setEndpointDefHelper} from './helpers/migration';
import {validateRRuleString} from './testing/rrule_validation';
import {wrapMetadataFunction} from './api';
/**
* Creates a new skeleton pack definition that can be added to.
*
* @example
* ```
* export const pack = newPack();
* pack.addFormula({resultType: ValueType.String, name: 'MyFormula', ...});
* pack.addSyncTable('MyTable', ...);
* pack.setUserAuthentication({type: AuthenticationType.HeaderBearerToken});
* ```
*/
export function newPack(
definition?: Partial<Omit<PackVersionDefinition, 'agent' | 'defaultTriggers'>>,
): PackDefinitionBuilder {
return new PackDefinitionBuilder(definition);
}
/**
* Creates a new skeleton agent definition that can be added to.
*
* @example
* ```
* export const pack = newAgent();
* pack.setInstructions('You help a team run async standups. Keep replies short.');
* ```
*
* @internal
* @hidden
*/
export function newAgent(): AgentDefinitionBuilder {
return new AgentDefinitionBuilder();
}
/**
* Fields and methods shared by {@link PackDefinitionBuilder} and {@link AgentDefinitionBuilder}.
*
* @internal
* @hidden
*/
export class BaseDefinitionBuilder {
/**
* See {@link PackVersionDefinition.version}.
*/
version?: string;
/**
* Sets the semantic version of this pack version, e.g. `'1.2.3'`.
*
* This is optional, and you only need to provide a version if you are manually doing
* semantic versioning, or using the CLI. If using the web editor, you can omit this
* and the web editor will automatically provide an appropriate semantic version
* each time you build a version.
*
* @example
* ```
* pack.setVersion('1.2.3');
* ```
*/
setVersion(version: string): this {
this.version = version;
return this;
}
}
/**
* A class that assists in constructing a pack definition. Use {@link newPack} to create one.
*/
export class PackDefinitionBuilder extends BaseDefinitionBuilder implements BasicPackDefinition {
/**
* See {@link PackVersionDefinition.formulas}.
*/
formulas: Formula[];
/**
* See {@link PackVersionDefinition.formats}.
*/
formats: Format[];
/**
* See {@link PackVersionDefinition.syncTables}.
*/
syncTables: SyncTable[];
/**
* See {@link PackVersionDefinition.skills}.
*/
skills: Skill[];
/**
* See {@link PackVersionDefinition.skillEntrypoints}.
* @deprecated No longer used, now that agents are connectors.
*/
skillEntrypoints?: SkillEntrypoints;
/**
* See {@link PackVersionDefinition.chatSkill}.
* @hidden
* @deprecated No longer used, now that agents are connectors.
*/
chatSkill?: PartialSkillDef;
/**
* See {@link PackVersionDefinition.benchInitializationSkill}.
* @hidden
* @deprecated No longer used, now that agents are connectors.
*/
benchInitializationSkill?: PartialSkillDef;
/**
* See {@link PackVersionDefinition.suggestedPrompts}.
* @hidden
* @deprecated No longer used, now that agents are connectors.
*/
suggestedPrompts: SuggestedPrompt[];
/**
* See {@link PackVersionDefinition.networkDomains}.
*/
networkDomains: string[];
/**
* See {@link PackVersionDefinition.mcpServers}.
* @hidden
*/
mcpServers: MCPServer[];
/**
* See {@link PackVersionDefinition.defaultAuthentication}.
*/
defaultAuthentication?: Authentication;
/**
* See {@link PackVersionDefinition.systemConnectionAuthentication}.
*/
systemConnectionAuthentication?: SystemAuthentication;
/**
* See {@link PackVersionDefinition.adminAuthentications}.
* @hidden
*/
adminAuthentications?: AdminAuthentication[];
/** @deprecated */
formulaNamespace?: string;
private _defaultConnectionRequirement: ConnectionRequirement | undefined;
/**
* Constructs a {@link PackDefinitionBuilder}. However, `sdk.newPack()` should be used instead
* rather than constructing a builder directly.
*/
constructor(definition?: Partial<Omit<PackVersionDefinition, 'agent' | 'defaultTriggers'>>) {
super();
const {
formulas,
formats,
syncTables,
skills,
chatSkill,
benchInitializationSkill,
networkDomains,
defaultAuthentication,
systemConnectionAuthentication,
version,
formulaNamespace,
skillEntrypoints,
suggestedPrompts,
mcpServers,
} = definition || {};
this.formulas = formulas || [];
this.formats = formats || [];
this.syncTables = syncTables || [];
this.skills = skills || [];
this.skillEntrypoints = skillEntrypoints;
this.chatSkill = chatSkill;
this.benchInitializationSkill = benchInitializationSkill;
this.suggestedPrompts = suggestedPrompts || [];
this.networkDomains = networkDomains || [];
this.mcpServers = mcpServers || [];
this.defaultAuthentication = defaultAuthentication;
this.systemConnectionAuthentication = systemConnectionAuthentication;
this.version = version;
this.formulaNamespace = formulaNamespace || 'Deprecated';
}
/**
* Adds a formula definition to this pack.
*
* In the web editor, the `/Formula` shortcut will insert a snippet of a skeleton formula.
*
* @example
* ```
* pack.addFormula({
* resultType: ValueType.String,
* name: 'MyFormula',
* description: 'My description.',
* parameters: [
* makeParameter({
* type: ParameterType.String,
* name: 'myParam',
* description: 'My param description.',
* }),
* ],
* execute: async ([param]) => {
* return `Hello ${param}`;
* },
* });
* ```
*/
addFormula<ParamDefsT extends ParamDefs, ResultT extends ValueType, SchemaT extends Schema>(
definition: {resultType: ResultT} & FormulaDefinitionOptions<ParamDefsT, ResultT, SchemaT>,
): this {
const formula = makeFormula<ParamDefsT, ResultT, SchemaT>({
...definition,
connectionRequirement: definition.connectionRequirement || this._defaultConnectionRequirement,
});
this.formulas.push(formula as any); // WTF
return this;
}
/**
* Adds a sync table definition to this pack.
*
* In the web editor, the `/SyncTable` shortcut will insert a snippet of a skeleton sync table.
*
* @example
* ```
* pack.addSyncTable({
* name: 'MySyncTable',
* identityName: 'EntityName',
* schema: sdk.makeObjectSchema({
* ...
* }),
* formula: {
* ...
* },
* });
* ```
*/
addSyncTable<
K extends string,
L extends string,
ParamDefsT extends ParamDefs,
SchemaT extends ObjectSchema<K, L>,
ContextT extends SyncExecutionContext<any, any>,
PermissionsContextT extends SyncPassthroughData,
>(definition: SyncTableOptions<K, L, ParamDefsT, SchemaT, ContextT, PermissionsContextT>): this {
const connectionRequirementToUse = definition.connectionRequirement || this._defaultConnectionRequirement;
const syncTable = makeSyncTable({
...definition,
connectionRequirement: connectionRequirementToUse,
});
this.syncTables.push(syncTable);
return this;
}
/**
* Adds a dynamic sync table definition to this pack.
*
* In the web editor, the `/DynamicSyncTable` shortcut will insert a snippet of a skeleton sync table.
*
* @example
* ```
* pack.addDynamicSyncTable({
* name: "MySyncTable",
* getName: async funciton (context) => {
* const response = await context.fetcher.fetch({method: "GET", url: context.sync.dynamicUrl});
* return response.body.name;
* },
* getName: async function (context) => {
* const response = await context.fetcher.fetch({method: "GET", url: context.sync.dynamicUrl});
* return response.body.browserLink;
* },
* ...
* });
* ```
*/
addDynamicSyncTable<
K extends string,
L extends string,
ParamDefsT extends ParamDefs,
SchemaT extends ObjectSchemaDefinition<K, L>,
ContextT extends SyncExecutionContext<any, any>,
PermissionsContextT extends SyncPassthroughData,
>(definition: DynamicSyncTableOptions<K, L, ParamDefsT, SchemaT, ContextT, PermissionsContextT>): this {
const dynamicSyncTable = makeDynamicSyncTable({
...definition,
connectionRequirement: definition.connectionRequirement || this._defaultConnectionRequirement,
});
this.syncTables.push(dynamicSyncTable);
return this;
}
/**
* Adds a column format definition to this pack.
*
* In the web editor, the `/ColumnFormat` shortcut will insert a snippet of a skeleton format.
*
* @example
* ```
* pack.addColumnFormat({
* name: 'MyColumn',
* formulaName: 'MyFormula',
* });
* ```
*
* Only supported in Superhuman Docs.
*/
addColumnFormat(format: Format): this {
this.formats.push(format);
return this;
}
/**
* Adds a skill definition to this pack.
*
* In the web editor, the `/Skill` shortcut will insert a snippet of a skeleton skill.
*
* @example
* ```
* pack.addSkill({
* name: "MySkill",
* displayName: "My Display Name",
* description: "My description.",
* prompt: `My prompt.`,
* tools: [
* { type: sdk.ToolType.Pack },
* ],
* });
* ```
*/
addSkill(skill: Skill): this {
this.skills.push(skill);
return this;
}
/**
* Adds an MCP server to this pack.
*
* @example
* ```
* pack.addMCPServer({name: 'MyMCPServer', endpointUrl: 'https://my-mcp-server.com'});
* ```
*
* Only supported in Superhuman Go.
*/
addMCPServer(server: MCPServer): this {
this.mcpServers.push(server);
return this;
}
/**
* Sets the chat skill for agent.
*
* The chat skill controls the behavior when users chat with the agent.
* It defines the prompts, available tools, and optionally the model to use.
*
* All fields are optional — omitted fields use defaults at runtime. When `tools` is omitted,
* the agent automatically gets:
*
* - {@link ToolType.Pack} — the pack's own formulas
* - {@link ToolType.Knowledge} — search over the pack's sync table data (when sync tables exist)
*
* Specifying `tools` replaces these defaults entirely.
*
* @example
* ```ts
* // Override just the prompt — default tools are preserved
* pack.setChatSkill({
* prompt: "End every reply with 'Moo!'",
* });
*
* // Override tools — replaces the defaults
* pack.setChatSkill({
* tools: [
* { type: sdk.ToolType.Pack },
* { type: sdk.ToolType.ContactResolution },
* ],
* });
* ```
*
* @deprecated No longer used, now that agents are connectors.
*/
setChatSkill(skill: PartialSkillDef): this {
this.chatSkill = skill;
return this;
}
/**
* Sets the skill used when the agent is first opened in the agent bench.
* All fields are optional - omitted fields will use defaults at runtime.
*
* @example
* ```ts
* pack.setBenchInitializationSkill({
* prompt: `
* Say hello to the user, referencing the time of day and a friendly nickname.
* For example: 10AM, Kramer => "Good morning K-man!"
* `,
* tools: [],
* });
* ```
*
* @deprecated No longer used, now that agents are connectors.
*/
setBenchInitializationSkill(skill: PartialSkillDef): this {
this.benchInitializationSkill = skill;
return this;
}
/**
* Maps entrypoints to skills in the Pack.
*
* @example
* ```
* pack.setSkillEntrypoints({
* defaultChat: { skillName: "MySkill" },
* });
* ```
*
* @deprecated No longer used, now that agents are connectors.
*/
setSkillEntrypoints(entrypoints: SkillEntrypoints): this {
this.skillEntrypoints = entrypoints;
return this;
}
/**
* Adds a suggested prompt that appears as a button when the agent is opened in chat.
*
* @example
* ```
* pack.addSuggestedPrompt({
* name: "TicketStatus",
* displayName: "Check ticket status",
* prompt: `
* Show me the status of all open support tickets.
* `,
* });
* ```
*
* @deprecated No longer used, now that agents are connectors.
*/
addSuggestedPrompt(prompt: SuggestedPrompt): this {
this.suggestedPrompts.push(prompt);
return this;
}
private _wrapAuthenticationFunctions(authentication: AllowedAuthenticationDef): AllowedAuthentication {
const {
getConnectionName: getConnectionNameDef,
getConnectionUserId: getConnectionUserIdDef,
postSetup: postSetupDef,
...rest
} = authentication;
const getConnectionName = wrapMetadataFunction(getConnectionNameDef);
const getConnectionUserId = wrapMetadataFunction(getConnectionUserIdDef);
const postSetup = postSetupDef?.map(step => {
const getOptions = wrapMetadataFunction(setEndpointDefHelper(step).getOptions);
const getOptionsFormula = wrapMetadataFunction(step.getOptionsFormula);
return {...step, getOptions, getOptionsFormula};
});
return {...rest, getConnectionName, getConnectionUserId, postSetup} as AllowedAuthentication;
}
/**
* Sets this pack to use authentication for individual users, using the
* authentication method is the given definition.
*
* Each user will need to register an account in order to use this pack.
*
* In the web editor, the `/UserAuthentication` shortcut will insert a snippet of a skeleton
* authentication definition.
*
* By default, this will set a default connection (account) requirement, making a user account
* required to invoke all formulas in this pack unless you specify differently on a particular
* formula. To change the default, you can pass a `defaultConnectionRequirement` option into
* this method.
*
* @example
* ```
* pack.setUserAuthentication({
* type: AuthenticationType.HeaderBearerToken,
* });
* ```
*/
setUserAuthentication(authDef: UserAuthenticationDef): this {
const {defaultConnectionRequirement = ConnectionRequirement.Required, ...authentication} = authDef;
if (authentication.type === AuthenticationType.None || authentication.type === AuthenticationType.Various) {
this.defaultAuthentication = authentication;
} else {
this.defaultAuthentication = this._wrapAuthenticationFunctions(authentication);
}
if (authentication.type !== AuthenticationType.None) {
this._setDefaultConnectionRequirement(defaultConnectionRequirement);
}
return this;
}
/**
* Sets this pack to use authentication provided by you as the maker of this pack.
*
* You will need to register credentials to use with this pack. When users use the
* pack, their requests will be authenticated with those system credentials, they need
* not register their own account.
*
* In the web editor, the `/SystemAuthentication` shortcut will insert a snippet of a skeleton
* authentication definition.
*
* @example
* ```
* pack.setSystemAuthentication({
* type: AuthenticationType.HeaderBearerToken,
* });
* ```
*/
setSystemAuthentication(systemAuthentication: SystemAuthenticationDef): this {
// TODO(patrick): Remove this cast
this.systemConnectionAuthentication = this._wrapAuthenticationFunctions(
systemAuthentication,
) as SystemAuthentication;
return this;
}
/**
* TODO(patrick): Unhide this
* @hidden
*/
addAdminAuthentication(adminAuth: AdminAuthenticationDef): this {
if (!this.adminAuthentications) {
this.adminAuthentications = [];
}
this.adminAuthentications.push({
...adminAuth,
authentication: this._wrapAuthenticationFunctions(adminAuth.authentication),
});
return this;
}
/**
* Adds the domain that this pack makes HTTP requests to.
* For example, if your pack makes HTTP requests to "api.example.com",
* use "example.com" as your network domain.
*
* If your pack make HTTP requests, it must declare a network domain,
* for security purposes. The platform enforces that your pack cannot make requests to
* any undeclared domains.
*
* You are allowed one network domain per pack by default. If your pack needs
* to connect to multiple domains, contact Superhuman for approval.
*
* @example
* ```
* pack.addNetworkDomain('example.com');
* ```
*/
addNetworkDomain(...domain: string[]): this {
this.networkDomains.push(...domain);
return this;
}
private _setDefaultConnectionRequirement(connectionRequirement: ConnectionRequirement): this {
this._defaultConnectionRequirement = connectionRequirement;
// Rewrite any formulas or sync tables that were already defined, in case the maker sets the default
// after the fact.
this.formulas = this.formulas.map(formula => {
return formula.connectionRequirement ? formula : maybeRewriteConnectionForFormula(formula, connectionRequirement);
});
this.syncTables = this.syncTables.map(syncTable => {
if (syncTable.getter.connectionRequirement) {
return syncTable;
} else if (isDynamicSyncTable(syncTable)) {
return {
...syncTable,
getter: maybeRewriteConnectionForFormula(syncTable.getter, connectionRequirement),
// These 4 are metadata formulas, so they use ConnectionRequirement.Required
// by default if you don't specify a connection requirement (a legacy behavior
// that is confusing and perhaps undesirable now that we have better builders).
// We don't know if the maker set Required explicitly or if was just the default,
// so we don't know if we should overwrite the connection requirement. For lack
// of a better option, we'll override it here regardless. This ensure that these
// dynamic sync table metadata formulas have the same connetion requirement as the
// sync table itself, which seems desirable basically 100% of the time and should
// always work, but it does give rise to confusing behavior that calling
// setDefaultConnectionRequirement() can wipe away an explicit connection
// requirement override set on one of these 4 metadata formulas.
getName: maybeRewriteConnectionForFormula(syncTable.getName, connectionRequirement),
getDisplayUrl: maybeRewriteConnectionForFormula(syncTable.getDisplayUrl, connectionRequirement),
getSchema: maybeRewriteConnectionForFormula(syncTable.getSchema, connectionRequirement),
listDynamicUrls: maybeRewriteConnectionForFormula(syncTable.listDynamicUrls, connectionRequirement),
searchDynamicUrls: maybeRewriteConnectionForFormula(syncTable.searchDynamicUrls, connectionRequirement),
namedPropertyOptions: maybeRewriteConnectionForNamedPropertyOptions(
syncTable.namedPropertyOptions,
connectionRequirement,
),
};
} else {
return {
...syncTable,
getter: maybeRewriteConnectionForFormula(syncTable.getter, connectionRequirement),
getSchema: maybeRewriteConnectionForFormula(syncTable.getSchema, connectionRequirement),
namedPropertyOptions: maybeRewriteConnectionForNamedPropertyOptions(
syncTable.namedPropertyOptions,
connectionRequirement,
),
};
}
});
return this;
}
}
// Copies before freezing so the caller's own arrays (connector formulas, trigger filters) stay theirs.
function frozenCopy<T extends {}>(value: T): T {
return deepFreeze(deepCopy(value)) as T;
}
interface AgentBuilderState {
agent: Partial<AgentDefinition>;
defaultTriggers?: DefaultTriggerDefinition[];
suggestedPrompts?: SuggestedPrompt[];
}
// Off the instance: an own property leaks into the metadata, and `#private` breaks pre-ES2015 .d.ts consumers.
const agentBuilderStates = new WeakMap<AgentDefinitionBuilder, AgentBuilderState>();
function stateOf(builder: AgentDefinitionBuilder): AgentBuilderState {
return agentBuilderStates.get(builder)!;
}
/**
* A class that assists in constructing an agent definition. Use {@link newAgent} to create one.
*
* @internal
* @hidden
*/
export class AgentDefinitionBuilder extends BaseDefinitionBuilder {
/**
* See {@link PackVersionDefinition.agent}. Set via {@link setInstructions} and {@link setTools}.
*/
declare readonly agent: DeepReadonly<Partial<AgentDefinition>>;
/**
* See {@link PackVersionDefinition.defaultTriggers}. Set via {@link setDefaultWhileWritingTrigger},
* {@link addDefaultMailEventTrigger}, {@link addDefaultSlackEventTrigger},
* {@link addDefaultNotetakerEventTrigger}, and {@link setDefaultScheduleTrigger}.
*/
declare readonly defaultTriggers?: DeepReadonly<DefaultTriggerDefinition[]>;
/**
* See {@link PackVersionDefinition.suggestedPrompts}. Set via {@link addSuggestedPrompt}.
*/
declare readonly suggestedPrompts?: DeepReadonly<SuggestedPrompt[]>;
constructor() {
super();
const state: AgentBuilderState = {agent: frozenCopy({tools: []})};
agentBuilderStates.set(this, state);
// Own and enumerable, unlike a class getter, so compilePackMetadata's object rest still copies them.
Object.defineProperty(this, 'agent', {enumerable: true, get: () => state.agent});
Object.defineProperty(this, 'defaultTriggers', {enumerable: true, get: () => state.defaultTriggers});
Object.defineProperty(this, 'suggestedPrompts', {enumerable: true, get: () => state.suggestedPrompts});
}
/**
* Sets this agent's instructions.
*
* @example
* ```
* pack.setInstructions('You help a team run async standups. Keep replies short.');
* ```
*/
setInstructions(instructions: string): this {
const state = stateOf(this);
state.agent = frozenCopy({...state.agent, instructions});
return this;
}
/**
* Sets the tools this agent can use. Anything left out is off.
*
* @example
* ```
* pack.setTools({docs: true, mail: true, webSearch: {allowedDomains: ['docs.example.com']}});
* pack.setTools({connectors: [{packId: 1234, formulas: [{formulaName: 'CreateTask'}]}]});
* ```
*/
setTools({docs, mail, webSearch, connectors}: AgentToolsDef): this {
const tools: AgentTool[] = [];
if (webSearch) {
const allowedDomains = typeof webSearch === 'object' ? webSearch.allowedDomains : undefined;
tools.push({type: ToolType.WebSearch, ...(allowedDomains ? {allowedDomains} : {})});
}
if (docs) {
tools.push({type: ToolType.CodaDocsAndTables});
}
if (mail) {
tools.push({type: ToolType.MailAndCalendar});
}
for (const connector of connectors || []) {
tools.push({
type: ToolType.Pack,
packId: connector.packId,
...(connector.formulas ? {formulas: connector.formulas} : {}),
});
}
const state = stateOf(this);
state.agent = frozenCopy({...state.agent, tools});
return this;
}
/**
* Adds a starter prompt that shows as a button when someone opens this agent in chat. An agent can have up to 3.
*
* @example
* ```
* pack.addSuggestedPrompt({
* name: 'ticketStatus',
* displayName: 'Check ticket status',
* prompt: 'Show me the status of all open support tickets',
* });
* ```
*/
addSuggestedPrompt(prompt: SuggestedPrompt): this {
const state = stateOf(this);
state.suggestedPrompts = frozenCopy<SuggestedPrompt[]>([...(state.suggestedPrompts ?? []), prompt]);
return this;
}
/**
* Sets the while-writing trigger this agent runs on.
*
* @example
* ```
* pack.setDefaultWhileWritingTrigger({
* condition: 'Offer a citation when the user asserts a statistic',
* surfaces: [sdk.ContextualTriggerSurface.Docs, sdk.ContextualTriggerSurface.Email],
* });
* ```
*/
setDefaultWhileWritingTrigger(contextualTrigger: Omit<WhileWritingTriggerDefinition, 'kind'>): this {
const state = stateOf(this);
const otherTriggers = (state.defaultTriggers ?? []).filter(
trigger => trigger.kind !== DefaultTriggerKind.WhileWriting,
);
state.defaultTriggers = frozenCopy<DefaultTriggerDefinition[]>([
...otherTriggers,
{kind: DefaultTriggerKind.WhileWriting, ...contextualTrigger},
]);
return this;
}
/**
* Adds a mail event trigger this agent runs on.
*
* @example
* ```
* pack.addDefaultMailEventTrigger({
* mailEventType: sdk.MailEventType.MessageReceived,
* filters: {
* conditions: [
* {
* field: sdk.MailFilterField.From,
* operator: sdk.FilterOperator.TextContains,
* value: '@customers.example.com',
* },
* ],
* },
* });
* ```
*/
addDefaultMailEventTrigger(trigger: DistributiveOmit<MailEventTriggerDefinition, 'kind' | 'type'>): this {
return this._addDefaultEventTrigger({type: EventTriggerType.Mail, ...trigger});
}
/**
* Adds a Slack event trigger this agent runs on. The workspace and channels are bound at install.
*
* @example
* ```
* pack.addDefaultSlackEventTrigger({
* eventType: sdk.SlackEventType.MessageKeyword,
* keywords: ['deploy', 'rollback'],
* });
* ```
*/
addDefaultSlackEventTrigger(trigger: DistributiveOmit<SlackEventTriggerDefinition, 'kind' | 'type'>): this {
return this._addDefaultEventTrigger({type: EventTriggerType.Slack, ...trigger});
}
/**
* Adds a notetaker event trigger this agent runs on.
*
* @example
* ```
* pack.addDefaultNotetakerEventTrigger({
* eventType: sdk.NotetakerEventType.MeetingSummaryCompleted,
* filters: {
* conditions: [
* {
* field: sdk.NotetakerFilterField.DurationMinutes,
* operator: sdk.FilterOperator.NumberAtLeast,
* value: '30',
* },
* ],
* },
* });
* ```
*/
addDefaultNotetakerEventTrigger(trigger: DistributiveOmit<NotetakerEventTriggerDefinition, 'kind' | 'type'>): this {
return this._addDefaultEventTrigger({type: EventTriggerType.Notetaker, ...trigger});
}
private _addDefaultEventTrigger(eventTrigger: DistributiveOmit<EventTriggerDefinition, 'kind'>): this {
const state = stateOf(this);
state.defaultTriggers = frozenCopy<DefaultTriggerDefinition[]>([
...(state.defaultTriggers ?? []),
{kind: DefaultTriggerKind.Event, ...eventTrigger},
]);
return this;
}
/**
* Sets the schedule this agent runs on. Throws on a recurrence the runtime cannot fire, including
* one with no DTSTART to anchor it.
*
* @example
* ```
* pack.setDefaultScheduleTrigger({
* rruleString: 'DTSTART:20260101T090000\nRRULE:FREQ=WEEKLY;BYDAY=MO',
* });
* ```
*/
setDefaultScheduleTrigger(scheduleTrigger: Omit<ScheduleTriggerDefinition, 'kind'>): this {
const message = validateRRuleString(scheduleTrigger.rruleString);
if (message) {
throw new Error(message);
}
const state = stateOf(this);
const otherTriggers = (state.defaultTriggers ?? []).filter(trigger => trigger.kind !== DefaultTriggerKind.Schedule);
state.defaultTriggers = frozenCopy<DefaultTriggerDefinition[]>([
...otherTriggers,
{kind: DefaultTriggerKind.Schedule, ...scheduleTrigger},
]);
return this;
}
}