-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathtypes.ts
More file actions
1682 lines (1496 loc) · 47.5 KB
/
types.ts
File metadata and controls
1682 lines (1496 loc) · 47.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
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
/**
* Type definitions for the Copilot SDK
*/
// Import and re-export generated session event types
import type { SessionFsHandler } from "./generated/rpc.js";
import type { SessionEvent as GeneratedSessionEvent } from "./generated/session-events.js";
import type { CopilotSession } from "./session.js";
export type SessionEvent = GeneratedSessionEvent;
export type { SessionFsHandler } from "./generated/rpc.js";
/**
* Options for creating a CopilotClient
*/
/**
* W3C Trace Context headers used for distributed trace propagation.
*/
export interface TraceContext {
traceparent?: string;
tracestate?: string;
}
/**
* Callback that returns the current W3C Trace Context.
* Wire this up to your OpenTelemetry (or other tracing) SDK to enable
* distributed trace propagation between your app and the Copilot CLI.
*/
export type TraceContextProvider = () => TraceContext | Promise<TraceContext>;
/**
* Configuration for OpenTelemetry instrumentation.
*
* When provided via {@link CopilotClientOptions.telemetry}, the SDK sets
* the corresponding environment variables on the spawned CLI process so
* that the CLI's built-in OTel exporter is configured automatically.
*/
export interface TelemetryConfig {
/** OTLP HTTP endpoint URL for trace/metric export. Sets OTEL_EXPORTER_OTLP_ENDPOINT. */
otlpEndpoint?: string;
/** File path for JSON-lines trace output. Sets COPILOT_OTEL_FILE_EXPORTER_PATH. */
filePath?: string;
/** Exporter backend type: "otlp-http" or "file". Sets COPILOT_OTEL_EXPORTER_TYPE. */
exporterType?: string;
/** Instrumentation scope name. Sets COPILOT_OTEL_SOURCE_NAME. */
sourceName?: string;
/** Whether to capture message content (prompts, responses). Sets OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT. */
captureContent?: boolean;
}
export interface CopilotClientOptions {
/**
* Path to the CLI executable or JavaScript entry point.
* If not specified, uses the bundled CLI from the @github/copilot package.
*/
cliPath?: string;
/**
* Extra arguments to pass to the CLI executable (inserted before SDK-managed args)
*/
cliArgs?: string[];
/**
* Working directory for the CLI process
* If not set, inherits the current process's working directory
*/
cwd?: string;
/**
* Port for the CLI server (TCP mode only)
* @default 0 (random available port)
*/
port?: number;
/**
* Use stdio transport instead of TCP
* When true, communicates with CLI via stdin/stdout pipes
* @default true
*/
useStdio?: boolean;
/**
* When true, indicates the SDK is running as a child process of the Copilot CLI server, and should
* use its own stdio for communicating with the existing parent process. Can only be used in combination
* with useStdio: true.
*/
isChildProcess?: boolean;
/**
* URL of an existing Copilot CLI server to connect to over TCP
* When provided, the client will not spawn a CLI process
* Format: "host:port" or "http://host:port" or just "port" (defaults to localhost)
* Examples: "localhost:8080", "http://127.0.0.1:9000", "8080"
* Mutually exclusive with cliPath, useStdio
*/
cliUrl?: string;
/**
* Log level for the CLI server
*/
logLevel?: "none" | "error" | "warning" | "info" | "debug" | "all";
/**
* Auto-start the CLI server on first use
* @default true
*/
autoStart?: boolean;
/**
* @deprecated This option has no effect and will be removed in a future release.
*/
autoRestart?: boolean;
/**
* Environment variables to pass to the CLI process. If not set, inherits process.env.
*/
env?: Record<string, string | undefined>;
/**
* GitHub token to use for authentication.
* When provided, the token is passed to the CLI server via environment variable.
* This takes priority over other authentication methods.
*/
githubToken?: string;
/**
* Whether to use the logged-in user for authentication.
* When true, the CLI server will attempt to use stored OAuth tokens or gh CLI auth.
* When false, only explicit tokens (githubToken or environment variables) are used.
* @default true (but defaults to false when githubToken is provided)
*/
useLoggedInUser?: boolean;
/**
* Custom handler for listing available models.
* When provided, client.listModels() calls this handler instead of
* querying the CLI server. Useful in BYOK mode to return models
* available from your custom provider.
*/
onListModels?: () => Promise<ModelInfo[]> | ModelInfo[];
/**
* OpenTelemetry configuration for the CLI process.
* When provided, the corresponding OTel environment variables are set
* on the spawned CLI server.
*/
telemetry?: TelemetryConfig;
/**
* Advanced: callback that returns the current W3C Trace Context for distributed
* trace propagation. Most users do not need this — the {@link telemetry} config
* alone is sufficient to collect traces from the CLI.
*
* This callback is only useful when your application creates its own
* OpenTelemetry spans and you want them to appear in the **same** distributed
* trace as the CLI's spans. The SDK calls this before `session.create`,
* `session.resume`, and `session.send` RPCs to inject `traceparent`/`tracestate`
* into the request.
*
* @example
* ```typescript
* import { propagation, context } from "@opentelemetry/api";
*
* const client = new CopilotClient({
* onGetTraceContext: () => {
* const carrier: Record<string, string> = {};
* propagation.inject(context.active(), carrier);
* return carrier;
* },
* });
* ```
*/
onGetTraceContext?: TraceContextProvider;
/**
* Custom session filesystem provider.
* When provided, the client registers as the session filesystem provider
* on connection, routing all session-scoped file I/O through these callbacks
* instead of the server's default local filesystem storage.
*/
sessionFs?: SessionFsConfig;
}
/**
* Configuration for creating a session
*/
export type ToolResultType = "success" | "failure" | "rejected" | "denied" | "timeout";
export type ToolBinaryResult = {
data: string;
mimeType: string;
type: string;
description?: string;
};
export type ToolResultObject = {
textResultForLlm: string;
binaryResultsForLlm?: ToolBinaryResult[];
resultType: ToolResultType;
error?: string;
sessionLog?: string;
toolTelemetry?: Record<string, unknown>;
};
export type ToolResult = string | ToolResultObject;
// ============================================================================
// MCP CallToolResult support
// ============================================================================
/**
* Content block types within an MCP CallToolResult.
*/
type McpCallToolResultTextContent = {
type: "text";
text: string;
};
type McpCallToolResultImageContent = {
type: "image";
data: string;
mimeType: string;
};
type McpCallToolResultResourceContent = {
type: "resource";
resource: {
uri: string;
mimeType?: string;
text?: string;
blob?: string;
};
};
type McpCallToolResultContent =
| McpCallToolResultTextContent
| McpCallToolResultImageContent
| McpCallToolResultResourceContent;
/**
* MCP-compatible CallToolResult type. Can be passed to
* {@link convertMcpCallToolResult} to produce a {@link ToolResultObject}.
*/
type McpCallToolResult = {
content: McpCallToolResultContent[];
isError?: boolean;
};
/**
* Converts an MCP CallToolResult into the SDK's ToolResultObject format.
*/
export function convertMcpCallToolResult(callResult: McpCallToolResult): ToolResultObject {
const textParts: string[] = [];
const binaryResults: ToolBinaryResult[] = [];
for (const block of callResult.content) {
switch (block.type) {
case "text":
// Guard against malformed input where text field is missing at runtime
if (typeof block.text === "string") {
textParts.push(block.text);
}
break;
case "image":
if (
typeof block.data === "string" &&
block.data &&
typeof block.mimeType === "string"
) {
binaryResults.push({
data: block.data,
mimeType: block.mimeType,
type: "image",
});
}
break;
case "resource": {
// Use optional chaining: resource field may be absent in malformed input
if (block.resource?.text) {
textParts.push(block.resource.text);
}
if (block.resource?.blob) {
binaryResults.push({
data: block.resource.blob,
mimeType: block.resource.mimeType ?? "application/octet-stream",
type: "resource",
description: block.resource.uri,
});
}
break;
}
}
}
return {
textResultForLlm: textParts.join("\n"),
resultType: callResult.isError ? "failure" : "success",
...(binaryResults.length > 0 ? { binaryResultsForLlm: binaryResults } : {}),
};
}
export interface ToolInvocation {
sessionId: string;
toolCallId: string;
toolName: string;
arguments: unknown;
/** W3C Trace Context traceparent from the CLI's execute_tool span. */
traceparent?: string;
/** W3C Trace Context tracestate from the CLI's execute_tool span. */
tracestate?: string;
}
export type ToolHandler<TArgs = unknown> = (
args: TArgs,
invocation: ToolInvocation
) => Promise<unknown> | unknown;
/**
* Zod-like schema interface for type inference.
* Any object with `toJSONSchema()` method is treated as a Zod schema.
*/
export interface ZodSchema<T = unknown> {
_output: T;
toJSONSchema(): Record<string, unknown>;
}
/**
* Tool definition. Parameters can be either:
* - A Zod schema (provides type inference for handler)
* - A raw JSON schema object
* - Omitted (no parameters)
*/
export interface Tool<TArgs = unknown> {
name: string;
description?: string;
parameters?: ZodSchema<TArgs> | Record<string, unknown>;
handler: ToolHandler<TArgs>;
/**
* When true, explicitly indicates this tool is intended to override a built-in tool
* of the same name. If not set and the name clashes with a built-in tool, the runtime
* will return an error.
*/
overridesBuiltInTool?: boolean;
/**
* When true, the tool can execute without a permission prompt.
*/
skipPermission?: boolean;
}
/**
* Helper to define a tool with Zod schema and get type inference for the handler.
* Without this helper, TypeScript cannot infer handler argument types from Zod schemas.
*/
export function defineTool<T = unknown>(
name: string,
config: {
description?: string;
parameters?: ZodSchema<T> | Record<string, unknown>;
handler: ToolHandler<T>;
overridesBuiltInTool?: boolean;
skipPermission?: boolean;
}
): Tool<T> {
return { name, ...config };
}
// ============================================================================
// Commands
// ============================================================================
/**
* Context passed to a command handler when a command is executed.
*/
export interface CommandContext {
/** Session ID where the command was invoked */
sessionId: string;
/** The full command text (e.g. "/deploy production") */
command: string;
/** Command name without leading / */
commandName: string;
/** Raw argument string after the command name */
args: string;
}
/**
* Handler invoked when a registered command is executed by a user.
*/
export type CommandHandler = (context: CommandContext) => Promise<void> | void;
/**
* Definition of a slash command registered with the session.
* When the CLI is running with a TUI, registered commands appear as
* `/commandName` for the user to invoke.
*/
export interface CommandDefinition {
/** Command name (without leading /). */
name: string;
/** Human-readable description shown in command completion UI. */
description?: string;
/** Handler invoked when the command is executed. */
handler: CommandHandler;
}
// ============================================================================
// UI Elicitation
// ============================================================================
/**
* Capabilities reported by the CLI host for this session.
*/
export interface SessionCapabilities {
ui?: {
/** Whether the host supports interactive elicitation dialogs. */
elicitation?: boolean;
};
}
/**
* A single field in an elicitation schema — matches the MCP SDK's
* `PrimitiveSchemaDefinition` union.
*/
export type ElicitationSchemaField =
| {
type: "string";
title?: string;
description?: string;
enum: string[];
enumNames?: string[];
default?: string;
}
| {
type: "string";
title?: string;
description?: string;
oneOf: { const: string; title: string }[];
default?: string;
}
| {
type: "array";
title?: string;
description?: string;
minItems?: number;
maxItems?: number;
items: { type: "string"; enum: string[] };
default?: string[];
}
| {
type: "array";
title?: string;
description?: string;
minItems?: number;
maxItems?: number;
items: { anyOf: { const: string; title: string }[] };
default?: string[];
}
| {
type: "boolean";
title?: string;
description?: string;
default?: boolean;
}
| {
type: "string";
title?: string;
description?: string;
minLength?: number;
maxLength?: number;
format?: "email" | "uri" | "date" | "date-time";
default?: string;
}
| {
type: "number" | "integer";
title?: string;
description?: string;
minimum?: number;
maximum?: number;
default?: number;
};
/**
* Schema describing the form fields for an elicitation request.
*/
export interface ElicitationSchema {
type: "object";
properties: Record<string, ElicitationSchemaField>;
required?: string[];
}
/**
* Primitive field value in an elicitation result.
* Matches MCP SDK's `ElicitResult.content` value type.
*/
export type ElicitationFieldValue = string | number | boolean | string[];
/**
* Result returned from an elicitation request.
*/
export interface ElicitationResult {
/** User action: "accept" (submitted), "decline" (rejected), or "cancel" (dismissed). */
action: "accept" | "decline" | "cancel";
/** Form values submitted by the user (present when action is "accept"). */
content?: Record<string, ElicitationFieldValue>;
}
/**
* Parameters for a raw elicitation request.
*/
export interface ElicitationParams {
/** Message describing what information is needed from the user. */
message: string;
/** JSON Schema describing the form fields to present. */
requestedSchema: ElicitationSchema;
}
/**
* Context for an elicitation handler invocation, combining the request data
* with session context. Mirrors the single-argument pattern of {@link CommandContext}.
*/
export interface ElicitationContext {
/** Identifier of the session that triggered the elicitation request. */
sessionId: string;
/** Message describing what information is needed from the user. */
message: string;
/** JSON Schema describing the form fields to present. */
requestedSchema?: ElicitationSchema;
/** Elicitation mode: "form" for structured input, "url" for browser redirect. */
mode?: "form" | "url";
/** The source that initiated the request (e.g. MCP server name). */
elicitationSource?: string;
/** URL to open in the user's browser (url mode only). */
url?: string;
}
/**
* Handler invoked when the server dispatches an elicitation request to this client.
* Return an {@link ElicitationResult} with the user's response.
*/
export type ElicitationHandler = (
context: ElicitationContext
) => Promise<ElicitationResult> | ElicitationResult;
/**
* Options for the `input()` convenience method.
*/
export interface InputOptions {
/** Title label for the input field. */
title?: string;
/** Descriptive text shown below the field. */
description?: string;
/** Minimum character length. */
minLength?: number;
/** Maximum character length. */
maxLength?: number;
/** Semantic format hint. */
format?: "email" | "uri" | "date" | "date-time";
/** Default value pre-populated in the field. */
default?: string;
}
/**
* The `session.ui` API object providing interactive UI methods.
* Only usable when the CLI host supports elicitation.
*/
export interface SessionUiApi {
/**
* Shows a generic elicitation dialog with a custom schema.
* @throws Error if the host does not support elicitation.
*/
elicitation(params: ElicitationParams): Promise<ElicitationResult>;
/**
* Shows a confirmation dialog and returns the user's boolean answer.
* Returns `false` if the user declines or cancels.
* @throws Error if the host does not support elicitation.
*/
confirm(message: string): Promise<boolean>;
/**
* Shows a selection dialog with the given options.
* Returns the selected value, or `null` if the user declines/cancels.
* @throws Error if the host does not support elicitation.
*/
select(message: string, options: string[]): Promise<string | null>;
/**
* Shows a text input dialog.
* Returns the entered text, or `null` if the user declines/cancels.
* @throws Error if the host does not support elicitation.
*/
input(message: string, options?: InputOptions): Promise<string | null>;
}
export interface ToolCallRequestPayload {
sessionId: string;
toolCallId: string;
toolName: string;
arguments: unknown;
}
export interface ToolCallResponsePayload {
result: ToolResult;
}
/**
* Known system prompt section identifiers for the "customize" mode.
* Each section corresponds to a distinct part of the system prompt.
*/
export type SystemPromptSection =
| "identity"
| "tone"
| "tool_efficiency"
| "environment_context"
| "code_change_rules"
| "guidelines"
| "safety"
| "tool_instructions"
| "custom_instructions"
| "last_instructions";
/** Section metadata for documentation and tooling. */
export const SYSTEM_PROMPT_SECTIONS: Record<SystemPromptSection, { description: string }> = {
identity: { description: "Agent identity preamble and mode statement" },
tone: { description: "Response style, conciseness rules, output formatting preferences" },
tool_efficiency: { description: "Tool usage patterns, parallel calling, batching guidelines" },
environment_context: { description: "CWD, OS, git root, directory listing, available tools" },
code_change_rules: { description: "Coding rules, linting/testing, ecosystem tools, style" },
guidelines: { description: "Tips, behavioral best practices, behavioral guidelines" },
safety: { description: "Environment limitations, prohibited actions, security policies" },
tool_instructions: { description: "Per-tool usage instructions" },
custom_instructions: { description: "Repository and organization custom instructions" },
last_instructions: {
description:
"End-of-prompt instructions: parallel tool calling, persistence, task completion",
},
};
/**
* Transform callback for a single section: receives current content, returns new content.
*/
export type SectionTransformFn = (currentContent: string) => string | Promise<string>;
/**
* Override action: a string literal for static overrides, or a callback for transforms.
*
* - `"replace"`: Replace section content entirely
* - `"remove"`: Remove the section
* - `"append"`: Append to existing section content
* - `"prepend"`: Prepend to existing section content
* - `function`: Transform callback — receives current section content, returns new content
*/
export type SectionOverrideAction =
| "replace"
| "remove"
| "append"
| "prepend"
| SectionTransformFn;
/**
* Override operation for a single system prompt section.
*/
export interface SectionOverride {
/**
* The operation to perform on this section.
* Can be a string action or a transform callback function.
*/
action: SectionOverrideAction;
/**
* Content for the override. Optional for all actions.
* - For replace, omitting content replaces with an empty string.
* - For append/prepend, content is added before/after the existing section.
* - Ignored for the remove action.
*/
content?: string;
}
/**
* Append mode: Use CLI foundation with optional appended content (default).
*/
export interface SystemMessageAppendConfig {
mode?: "append";
/**
* Additional instructions appended after SDK-managed sections.
*/
content?: string;
}
/**
* Replace mode: Use caller-provided system message entirely.
* Removes all SDK guardrails including security restrictions.
*/
export interface SystemMessageReplaceConfig {
mode: "replace";
/**
* Complete system message content.
* Replaces the entire SDK-managed system message.
*/
content: string;
}
/**
* Customize mode: Override individual sections of the system prompt.
* Keeps the SDK-managed prompt structure while allowing targeted modifications.
*/
export interface SystemMessageCustomizeConfig {
mode: "customize";
/**
* Override specific sections of the system prompt by section ID.
* Unknown section IDs gracefully fall back: content-bearing overrides are appended
* to additional instructions, and "remove" on unknown sections is a silent no-op.
*/
sections?: Partial<Record<SystemPromptSection, SectionOverride>>;
/**
* Additional content appended after all sections.
* Equivalent to append mode's content field — provided for convenience.
*/
content?: string;
}
/**
* System message configuration for session creation.
* - Append mode (default): SDK foundation + optional custom content
* - Replace mode: Full control, caller provides entire system message
* - Customize mode: Section-level overrides with graceful fallback
*/
export type SystemMessageConfig =
| SystemMessageAppendConfig
| SystemMessageReplaceConfig
| SystemMessageCustomizeConfig;
/**
* Permission request types from the server
*/
export interface PermissionRequest {
kind: "shell" | "write" | "mcp" | "read" | "url" | "custom-tool";
toolCallId?: string;
[key: string]: unknown;
}
import type { SessionPermissionsHandlePendingPermissionRequestParams } from "./generated/rpc.js";
export type PermissionRequestResult =
| SessionPermissionsHandlePendingPermissionRequestParams["result"]
| { kind: "no-result" };
export type PermissionHandler = (
request: PermissionRequest,
invocation: { sessionId: string }
) => Promise<PermissionRequestResult> | PermissionRequestResult;
export const approveAll: PermissionHandler = () => ({ kind: "approved" });
export const defaultJoinSessionPermissionHandler: PermissionHandler =
(): PermissionRequestResult => ({
kind: "no-result",
});
// ============================================================================
// User Input Request Types
// ============================================================================
/**
* Request for user input from the agent (enables ask_user tool)
*/
export interface UserInputRequest {
/**
* The question to ask the user
*/
question: string;
/**
* Optional choices for multiple choice questions
*/
choices?: string[];
/**
* Whether to allow freeform text input in addition to choices
* @default true
*/
allowFreeform?: boolean;
}
/**
* Response to a user input request
*/
export interface UserInputResponse {
/**
* The user's answer
*/
answer: string;
/**
* Whether the answer was freeform (not from choices)
*/
wasFreeform: boolean;
}
/**
* Handler for user input requests from the agent
*/
export type UserInputHandler = (
request: UserInputRequest,
invocation: { sessionId: string }
) => Promise<UserInputResponse> | UserInputResponse;
// ============================================================================
// Hook Types
// ============================================================================
/**
* Base interface for all hook inputs
*/
export interface BaseHookInput {
timestamp: number;
cwd: string;
}
/**
* Input for pre-tool-use hook
*/
export interface PreToolUseHookInput extends BaseHookInput {
toolName: string;
toolArgs: unknown;
}
/**
* Output for pre-tool-use hook
*/
export interface PreToolUseHookOutput {
permissionDecision?: "allow" | "deny" | "ask";
permissionDecisionReason?: string;
modifiedArgs?: unknown;
additionalContext?: string;
suppressOutput?: boolean;
}
/**
* Handler for pre-tool-use hook
*/
export type PreToolUseHandler = (
input: PreToolUseHookInput,
invocation: { sessionId: string }
) => Promise<PreToolUseHookOutput | void> | PreToolUseHookOutput | void;
/**
* Input for post-tool-use hook
*/
export interface PostToolUseHookInput extends BaseHookInput {
toolName: string;
toolArgs: unknown;
toolResult: ToolResultObject;
}
/**
* Output for post-tool-use hook
*/
export interface PostToolUseHookOutput {
modifiedResult?: ToolResultObject;
additionalContext?: string;
suppressOutput?: boolean;
}
/**
* Handler for post-tool-use hook
*/
export type PostToolUseHandler = (
input: PostToolUseHookInput,
invocation: { sessionId: string }
) => Promise<PostToolUseHookOutput | void> | PostToolUseHookOutput | void;
/**
* Input for user-prompt-submitted hook
*/
export interface UserPromptSubmittedHookInput extends BaseHookInput {
prompt: string;
}
/**
* Output for user-prompt-submitted hook
*/
export interface UserPromptSubmittedHookOutput {
modifiedPrompt?: string;
additionalContext?: string;
suppressOutput?: boolean;
}
/**
* Handler for user-prompt-submitted hook
*/
export type UserPromptSubmittedHandler = (
input: UserPromptSubmittedHookInput,
invocation: { sessionId: string }
) => Promise<UserPromptSubmittedHookOutput | void> | UserPromptSubmittedHookOutput | void;
/**
* Input for session-start hook
*/
export interface SessionStartHookInput extends BaseHookInput {
source: "startup" | "resume" | "new";
initialPrompt?: string;
}
/**
* Output for session-start hook
*/
export interface SessionStartHookOutput {
additionalContext?: string;
modifiedConfig?: Record<string, unknown>;
}
/**
* Handler for session-start hook
*/
export type SessionStartHandler = (
input: SessionStartHookInput,
invocation: { sessionId: string }
) => Promise<SessionStartHookOutput | void> | SessionStartHookOutput | void;
/**
* Input for session-end hook
*/
export interface SessionEndHookInput extends BaseHookInput {
reason: "complete" | "error" | "abort" | "timeout" | "user_exit";
finalMessage?: string;
error?: string;
}
/**
* Output for session-end hook
*/
export interface SessionEndHookOutput {
suppressOutput?: boolean;
cleanupActions?: string[];
sessionSummary?: string;
}
/**
* Handler for session-end hook
*/
export type SessionEndHandler = (
input: SessionEndHookInput,
invocation: { sessionId: string }
) => Promise<SessionEndHookOutput | void> | SessionEndHookOutput | void;
/**
* Input for error-occurred hook
*/
export interface ErrorOccurredHookInput extends BaseHookInput {
error: string;
errorContext: "model_call" | "tool_execution" | "system" | "user_input";
recoverable: boolean;
}
/**
* Output for error-occurred hook
*/
export interface ErrorOccurredHookOutput {
suppressOutput?: boolean;
errorHandling?: "retry" | "skip" | "abort";
retryCount?: number;
userNotification?: string;
}
/**
* Handler for error-occurred hook
*/
export type ErrorOccurredHandler = (
input: ErrorOccurredHookInput,
invocation: { sessionId: string }
) => Promise<ErrorOccurredHookOutput | void> | ErrorOccurredHookOutput | void;
/**
* Configuration for session hooks
*/
export interface SessionHooks {
/**
* Called before a tool is executed
*/
onPreToolUse?: PreToolUseHandler;
/**
* Called after a tool is executed
*/
onPostToolUse?: PostToolUseHandler;
/**
* Called when the user submits a prompt
*/
onUserPromptSubmitted?: UserPromptSubmittedHandler;
/**
* Called when a session starts
*/