-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpermission-handler.ts
More file actions
74 lines (63 loc) · 1.84 KB
/
permission-handler.ts
File metadata and controls
74 lines (63 loc) · 1.84 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
/**
* Permission handler example.
*
* Demonstrates using `query()` with a custom `permissionHandler` that
* logs tool confirmation details and returns `ToolConfirmationOutcome.ProceedOnce`
* to approve each tool execution individually.
*
* Usage:
* npx tsx examples/permission-handler.ts
*/
import {
query,
ToolConfirmationOutcome,
type RequestPermissionRequestParams,
} from '../src/index.js';
function permissionHandler(
params: RequestPermissionRequestParams
): ToolConfirmationOutcome {
for (const item of params.toolUses) {
console.log(`\n[Permission] Tool: ${item.toolUse.name}`);
console.log(` Type: ${item.confirmationType}`);
console.log(` Input: ${JSON.stringify(item.toolUse.input, null, 2)}`);
}
console.log(` → Approving with ProceedOnce\n`);
return ToolConfirmationOutcome.ProceedOnce;
}
async function main(): Promise<void> {
const prompt =
process.argv[2] ??
"Create a file called hello.txt with the text 'Hello, World!'";
console.log(`Sending prompt: "${prompt}"\n`);
const stream = query({
prompt,
cwd: process.cwd(),
permissionHandler,
});
for await (const msg of stream) {
switch (msg.type) {
case 'assistant_text_delta':
process.stdout.write(msg.text);
break;
case 'tool_use':
console.log(`\n[Tool Use] ${msg.toolName}`);
break;
case 'tool_result':
console.log(`[Tool Result] ${msg.isError ? 'Error' : 'Success'}`);
break;
case 'turn_complete':
console.log('\n\n--- Turn complete ---');
if (msg.tokenUsage) {
console.log(
`Tokens — input: ${msg.tokenUsage.inputTokens}, ` +
`output: ${msg.tokenUsage.outputTokens}`
);
}
break;
}
}
}
main().catch((err: unknown) => {
console.error('Error:', err);
process.exit(1);
});