-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathspec-mode-new-session.ts
More file actions
94 lines (84 loc) · 2.67 KB
/
Copy pathspec-mode-new-session.ts
File metadata and controls
94 lines (84 loc) · 2.67 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
/**
* Spec mode: approve and hand off implementation to a new session.
*
* Demonstrates starting a session in spec (planning) mode and answering
* the ExitSpecMode confirmation with `ProceedNewSessionHigh`, which
* implements the plan in a fresh session.
*
* Usage:
* npx tsx examples/spec-mode-new-session.ts
*
* Requirements: droid CLI installed and logged in. FACTORY_API_KEY is
* optional; stored CLI credentials are used when it is unset.
*/
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { join } from 'node:path';
import {
DroidInteractionMode,
ReasoningEffort,
ToolConfirmationOutcome,
ToolConfirmationType,
createSession,
} from '@factory/droid-sdk';
const tempDir = await mkdtemp(join(process.cwd(), '.droid-sdk-spec-'));
const outputPath = join(tempDir, 'hello.txt');
async function waitForFile(path: string, timeoutMs = 120_000): Promise<string> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
return await readFile(path, 'utf8');
} catch (error) {
if (
!(error instanceof Error) ||
!('code' in error) ||
error.code !== 'ENOENT'
) {
throw error;
}
await new Promise<void>((resolve) => setTimeout(resolve, 500));
}
}
throw new Error(`Timed out waiting for ${path}`);
}
try {
const session = await createSession({
apiKey: process.env.FACTORY_API_KEY!,
cwd: process.cwd(),
interactionMode: DroidInteractionMode.Spec,
specModeReasoningEffort: ReasoningEffort.High,
permissionHandler(params) {
const canExitSpec = params.toolUses.some(
(item) => item.details.type === ToolConfirmationType.ExitSpecMode
);
const onlyCreatesFile = params.toolUses.every(
(item) =>
item.details.type === ToolConfirmationType.Create &&
item.details.filePath === outputPath
);
if (canExitSpec) {
return ToolConfirmationOutcome.ProceedNewSessionHigh;
}
return onlyCreatesFile
? ToolConfirmationOutcome.ProceedOnce
: ToolConfirmationOutcome.Cancel;
},
});
try {
for await (const _msg of session.stream(
`Plan then create ${outputPath} containing "Hello from Droid".`
)) {
// Consume the stream until the handoff implementation finishes.
}
console.log(await waitForFile(outputPath));
} catch (error) {
console.error(
`Expected ${outputPath} to exist after the turn, but it was not ` +
`created: ${error instanceof Error ? error.message : String(error)}`
);
process.exitCode = 1;
} finally {
await session.close();
}
} finally {
await rm(tempDir, { recursive: true, force: true });
}