-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathsession-event-types.test.ts
More file actions
420 lines (388 loc) · 16.1 KB
/
Copy pathsession-event-types.test.ts
File metadata and controls
420 lines (388 loc) · 16.1 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
/**
* Regression test for #1156: dedicated session event data/payload types are
* importable from the package entry point (`@github/copilot-sdk` /
* `src/index.js`).
*
* Before this fix, only the aggregate `SessionEvent` discriminated union was
* re-exported. The constituent `*Event` wrapper interfaces and their `*Data`
* payload types lived in `generated/session-events.ts` and could only be
* reached via a deep import (`@github/copilot-sdk/dist/generated/...`).
*
* Most of this file exercises the *type* surface — if these type-only imports
* compile, the public API exposes the types. The runtime assertions below only
* validate representative object shapes for those annotations; they do not
* prove that type-only exports exist at runtime.
*/
import { describe, expect, it } from "vitest";
import { approveAll } from "../src/index.js";
import { WORKFLOW_AGENT_OPTION_KEYS } from "../src/workflow.js";
import type { WorkflowAgentOptions as WireWorkflowAgentOptions } from "../src/generated/rpc.js";
import type {
// The aggregate union; must still resolve via the package root.
SessionEvent,
AutoTier,
AutoTierSwitchFailedData,
AutoTierSwitchFailedEvent,
AutoTierSwitchFailureReason,
CapiSessionOptions,
PermissionRequest,
PermissionRequestedData,
PermissionRequestedEvent,
PermissionResponseCapability,
ManagedSettingsResolvedData,
ManagedSettingsResolvedEvent,
ManagedSettingsResolvedSource,
// *Data payload types from the v0.3.0 generated session-event schema.
AssistantMessageData,
AssistantMessageDeltaData,
AssistantReasoningData,
AssistantTurnStartData,
ErrorData,
IdleData,
ResumeData,
StartData,
ToolExecutionCompleteData,
ToolExecutionPartialData,
ToolExecutionProgressData,
ToolExecutionStartData,
UserMessageData,
// *Event wrapper interfaces.
AssistantMessageEvent,
ErrorEvent,
IdleEvent,
ResumeEvent,
StartEvent,
ToolExecutionCompleteEvent,
ToolExecutionStartEvent,
UserMessageEvent,
// A sample of supporting auxiliary aliases/unions referenced by the
// *Data shapes — these must also be reachable so that consumers can
// narrow or annotate intermediate values.
UserMessageAgentMode,
Attachment,
WorkingDirectoryContextHostType,
WorkflowContext,
WorkflowDefinition,
WorkflowAgentOptions,
WorkflowRunResult,
JsonValue,
} from "../src/index.js";
/**
* Type-only helper: forces the compiler to resolve the supplied type
* parameter. If the type is not exported from `../src/index.js`, the file
* fails to type-check and the test never runs. There is no runtime body —
* the helper exists purely to make "is this type importable?" assertions
* compile-time checked.
*/
function assertImportable<_T>(): void {
/* no-op; compile-time check only */
}
/**
* Compile-time mutual-assignability check: passes only when `A` and `B`
* are structurally equivalent. Used below to pin the package-root
* `AssistantMessageEvent` (which is explicitly re-exported from
* `./session.js` and therefore shadows the generated `AssistantMessageEvent`
* arriving via `export type *`) to the corresponding arm of the generated
* `SessionEvent` union. If a future schema regen ever caused these two
* shapes to drift, this assertion would fail to type-check and `npm run
* typecheck` would surface it before the public API silently changed.
*/
type _AssertEqual<A, B> =
(<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
type _AssistantMessageEventStaysAlignedWithSessionEventUnion = _AssertEqual<
AssistantMessageEvent,
Extract<SessionEvent, { type: "assistant.message" }>
>;
const _assistantMessageEventAlignmentCheck: _AssistantMessageEventStaysAlignedWithSessionEventUnion = true;
type _DefaultWorkflowArgsAreJsonValue = _AssertEqual<WorkflowContext["args"], JsonValue>;
const _defaultWorkflowArgsCheck: _DefaultWorkflowArgsAreJsonValue = true;
type _DefaultWorkflowResultIsJsonValueOrVoid = _AssertEqual<
Awaited<ReturnType<WorkflowDefinition["run"]>>,
JsonValue | void
>;
const _defaultWorkflowResultCheck: _DefaultWorkflowResultIsJsonValueOrVoid = true;
type _WorkflowRunResultIsJsonValueOrUndefined = _AssertEqual<
WorkflowRunResult["result"],
JsonValue | undefined
>;
const _workflowRunResultCheck: _WorkflowRunResultIsJsonValueOrUndefined = true;
type _WorkflowAgentOptionKeysMatchPublicInterface = _AssertEqual<
(typeof WORKFLOW_AGENT_OPTION_KEYS)[number],
keyof WorkflowAgentOptions
>;
const _workflowAgentOptionKeysCheck: _WorkflowAgentOptionKeysMatchPublicInterface = true;
type _PublicWorkflowAgentOptionsMatchWire = _AssertEqual<
keyof WorkflowAgentOptions,
keyof WireWorkflowAgentOptions
>;
const _publicWorkflowAgentOptionsCheck: _PublicWorkflowAgentOptionsMatchWire = true;
// @ts-expect-error Workflow arguments must be representable on the JSON wire.
type _WorkflowArgsRejectUndefined = WorkflowContext<undefined>;
// @ts-expect-error Workflow results must be JSON values or top-level void.
type _WorkflowResultRejectsFunction = WorkflowDefinition<JsonValue, () => void>;
type _PermissionRequestedEventStaysAlignedWithSessionEventUnion = _AssertEqual<
PermissionRequestedEvent,
Extract<SessionEvent, { type: "permission.requested" }>
>;
const _permissionRequestedEventAlignmentCheck: _PermissionRequestedEventStaysAlignedWithSessionEventUnion = true;
describe("Session event type exports (#1156)", () => {
it.each(["efficiency", "balance", "intelligence", "fast", undefined] satisfies (
| AutoTier
| undefined
)[])("exposes Auto tier %s on start and resume data", (autoTier) => {
const start: StartData = {
copilotVersion: "1.0.82-1",
producer: "copilot-agent",
sessionId: "session-1",
startTime: "2026-08-28T00:00:00Z",
version: 1,
autoTier,
};
const resume: ResumeData = {
eventCount: 1,
resumeTime: "2026-08-28T00:01:00Z",
autoTier,
};
const capi: CapiSessionOptions = { autoTier: start.autoTier };
expect(capi.autoTier).toBe(autoTier);
expect(resume.autoTier).toBe(autoTier);
if (autoTier === undefined) {
expect(JSON.parse(JSON.stringify(start))).not.toHaveProperty("autoTier");
expect(JSON.parse(JSON.stringify(resume))).not.toHaveProperty("autoTier");
}
});
it.each([
"policy_rejected",
"request_failed",
"setup_failed",
"unsupported",
] satisfies AutoTierSwitchFailureReason[])(
"exposes the Auto tier switch failure event with reason %s",
(reason) => {
const data: AutoTierSwitchFailedData = {
reason,
requestedAutoTier: "fast",
effectiveAutoTier: "balance",
};
const event: AutoTierSwitchFailedEvent = {
type: "session.auto_tier_switch_failed",
id: "event-1",
parentId: null,
timestamp: "2026-09-02T00:00:00Z",
ephemeral: true,
data,
};
// The failure event must be reachable through the aggregate union so
// consumers can narrow on it in a single event handler.
const asSessionEvent: SessionEvent = event;
expect(asSessionEvent.type).toBe("session.auto_tier_switch_failed");
expect(data.reason).toBe(reason);
expect(data.requestedAutoTier).toBe("fast");
}
);
it("allows a null requested Auto tier when returning to default routing fails", () => {
const data: AutoTierSwitchFailedData = {
reason: "unsupported",
requestedAutoTier: null,
};
expect(data.requestedAutoTier).toBeNull();
expect(data.effectiveAutoTier).toBeUndefined();
});
it("exposes the headline ToolExecutionStartData type with a usable shape", () => {
// This is the specific type called out in issue #1156. The annotation
// is the compile-time API-surface check; these assertions only validate
// the representative runtime object shape a consumer would use.
const data: ToolExecutionStartData = {
toolCallId: "call-1",
toolName: "shell",
arguments: { command: "ls" },
mcpServerName: "filesystem",
mcpToolName: "list_dir",
turnId: "turn-1",
};
expect(data.toolName).toBe("shell");
expect(data.toolCallId).toBe("call-1");
expect(data.arguments).toEqual({ command: "ls" });
expect(data.mcpServerName).toBe("filesystem");
expect(data.mcpToolName).toBe("list_dir");
expect(data.turnId).toBe("turn-1");
});
it("exposes explicit user approval metadata for managed Domain requests", () => {
const request: PermissionRequest = {
kind: "url",
url: "https://api.example.com/data",
intention: "Fetch domain data",
managedApprovalRequired: true,
};
expect(request.managedApprovalRequired).toBe(true);
});
it("exposes managed approval metadata through permission event types", () => {
const data: PermissionRequestedData = {
permissionRequest: {
kind: "url",
url: "https://api.example.com/data",
intention: "Fetch domain data",
managedApprovalRequired: true,
},
requestId: "permission-1",
};
const event: SessionEvent = {
id: "evt-permission-1",
parentId: null,
timestamp: "2026-01-01T00:00:00.000Z",
type: "permission.requested",
data,
};
if (event.type !== "permission.requested") {
throw new Error("expected permission.requested narrowing");
}
const permissionEvent: PermissionRequestedEvent = event;
expect(permissionEvent.data.permissionRequest.managedApprovalRequired).toBe(true);
});
it("exposes managed settings client and mixed provenance", () => {
const sources: ManagedSettingsResolvedSource[] = [
"server",
"device",
"client",
"mixed",
"none",
];
expect(sources).toEqual(["server", "device", "client", "mixed", "none"]);
const clientData: ManagedSettingsResolvedData = {
bypassPermissionsDisabled: true,
clientManaged: true,
deviceManaged: false,
failClosed: false,
managedKeys: ["permissions"],
serverManaged: false,
source: "client",
};
const clientEvent: ManagedSettingsResolvedEvent = {
ephemeral: true,
id: "evt-managed-1",
parentId: null,
timestamp: "2026-01-01T00:00:00.000Z",
type: "session.managed_settings_resolved",
data: clientData,
};
expect(clientEvent.data.source).toBe("client");
expect(clientEvent.data.clientManaged).toBe(true);
const { clientManaged: _, ...withoutClientManaged } = clientData;
const mixedData: ManagedSettingsResolvedData = {
...withoutClientManaged,
source: "mixed",
};
expect(mixedData.source).toBe("mixed");
expect("clientManaged" in mixedData).toBe(false);
});
it("rejects approveAll in managed settings sessions", () => {
expect(() =>
approveAll(
{
kind: "url",
url: "https://api.example.com/data",
intention: "Fetch ordinary data",
},
{ sessionId: "session-1", managedSettingsEnabled: true }
)
).toThrow("approveAll cannot be used when managed settings are enabled");
expect(() =>
approveAll(
{
kind: "url",
url: "https://api.example.com/data",
intention: "Fetch managed data",
managedApprovalRequired: true,
},
{ sessionId: "session-1", managedSettingsEnabled: true }
)
).toThrow("approveAll cannot be used when managed settings are enabled");
});
it("leaves managed requests pending when managed settings are disabled", () => {
expect(
approveAll(
{
kind: "url",
url: "https://api.example.com/data",
intention: "Fetch managed data",
managedApprovalRequired: true,
},
{ sessionId: "session-1", managedSettingsEnabled: false }
)
).toEqual({ kind: "no-result" });
});
it("wraps ToolExecutionStartData inside the exported ToolExecutionStartEvent", () => {
const event: ToolExecutionStartEvent = {
id: "evt-1",
parentId: null,
timestamp: "2026-01-01T00:00:00.000Z",
type: "tool.execution_start",
data: {
toolCallId: "call-1",
toolName: "shell",
},
};
expect(event.type).toBe("tool.execution_start");
expect(event.data.toolName).toBe("shell");
expect(event.parentId).toBeNull();
});
it("narrows the aggregate SessionEvent union to a dedicated *Data type", () => {
const evt: SessionEvent = {
id: "evt-2",
parentId: null,
timestamp: "2026-01-01T00:00:01.000Z",
type: "tool.execution_start",
data: {
toolCallId: "call-2",
toolName: "shell",
},
};
if (evt.type !== "tool.execution_start") {
throw new Error("expected tool.execution_start narrowing");
}
// After narrowing, `evt.data` must satisfy `ToolExecutionStartData`.
// Annotating the local with the dedicated *Data type proves the
// re-export is wired up correctly.
const data: ToolExecutionStartData = evt.data;
expect(data.toolCallId).toBe("call-2");
expect(data.toolName).toBe("shell");
});
it("re-exports the full set of *Data and *Event types named in v0.3.0", () => {
// Compile-time checks: if any of these fail to resolve, the file
// will not type-check and the test will not be executed.
assertImportable<AssistantMessageData>();
assertImportable<AssistantMessageDeltaData>();
assertImportable<AssistantReasoningData>();
assertImportable<AssistantTurnStartData>();
assertImportable<ErrorData>();
assertImportable<IdleData>();
assertImportable<ResumeData>();
assertImportable<StartData>();
assertImportable<ToolExecutionCompleteData>();
assertImportable<ToolExecutionPartialData>();
assertImportable<ToolExecutionProgressData>();
assertImportable<ToolExecutionStartData>();
assertImportable<UserMessageData>();
assertImportable<PermissionRequestedData>();
assertImportable<PermissionResponseCapability>();
assertImportable<ManagedSettingsResolvedData>();
assertImportable<AssistantMessageEvent>();
assertImportable<ErrorEvent>();
assertImportable<IdleEvent>();
assertImportable<ResumeEvent>();
assertImportable<StartEvent>();
assertImportable<ToolExecutionCompleteEvent>();
assertImportable<ToolExecutionStartEvent>();
assertImportable<UserMessageEvent>();
assertImportable<PermissionRequestedEvent>();
assertImportable<ManagedSettingsResolvedEvent>();
assertImportable<ManagedSettingsResolvedSource>();
// Supporting auxiliary types referenced by the *Data shapes — these
// must round-trip through the package root too, otherwise consumers
// annotating intermediate values would still need a deep import.
assertImportable<UserMessageAgentMode>();
assertImportable<Attachment>();
assertImportable<WorkingDirectoryContextHostType>();
expect(true).toBe(true);
});
});