Repository navigation
Expand file tree
/
Copy pathpermission-handler.ts
More file actions
85 lines (76 loc) · 2.76 KB
/
Copy pathpermission-handler.ts
File metadata and controls
85 lines (76 loc) · 2.76 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
/**
* Permission handler example.
*
* Turns autonomy off so that every tool call asks for permission, then
* approves only the calls that create the expected file and cancels the rest.
*
* Usage:
* npx tsx examples/node/permission-handler.ts
*/
import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
AutonomyLevel,
ToolConfirmationOutcome,
ToolConfirmationType,
run,
} from '@factory/droid-sdk/node';
// Resolve symlinks (for example /var -> /private/var on macOS) so the path in
// the prompt is the same path that the permission request reports.
const tempDir = await realpath(
await mkdtemp(join(tmpdir(), 'droid-sdk-permission-'))
);
const outputPath = join(tempDir, 'hello.txt');
try {
let handledPermission = false;
const result = await run(
`Create ${outputPath} with the text "Hello, World!"`,
{
cwd: tempDir,
autonomyLevel: AutonomyLevel.Off,
permissionHandler({ toolUses, options }) {
handledPermission = true;
// A Script request batches several tool calls; approve it only when
// every call in the batch is allowed.
const confirmations = toolUses.flatMap((item) =>
item.details.type === ToolConfirmationType.Script
? item.details.calls.map((call) => call.confirmation)
: [item.details]
);
// Depending on the model, Droid creates files with Create or ApplyPatch.
const onlyCreatesExpectedFile =
confirmations.length > 0 &&
confirmations.every(
(details) =>
(details.type === ToolConfirmationType.Create &&
details.filePath === outputPath) ||
(details.type === ToolConfirmationType.ApplyPatch &&
details.files !== undefined &&
details.files.length > 0 &&
details.files.every(
(file) =>
file.filePath === outputPath &&
file.operation === 'create' &&
file.moveTo === undefined
))
);
const desired = onlyCreatesExpectedFile
? ToolConfirmationOutcome.ProceedOnce
: ToolConfirmationOutcome.Cancel;
const offered = options.find((option) => option.value === desired);
if (!offered) throw new Error(`Outcome not offered: ${desired}`);
return desired;
},
}
);
if (!result.success) {
throw new Error(result.error?.message ?? 'The turn was interrupted.');
}
if (!handledPermission) {
throw new Error('The turn finished without requesting permission.');
}
console.log(await readFile(outputPath, 'utf8'));
} finally {
await rm(tempDir, { recursive: true, force: true });
}