-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathsetup.ts
More file actions
452 lines (381 loc) · 13.1 KB
/
setup.ts
File metadata and controls
452 lines (381 loc) · 13.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
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
#!/usr/bin/env bun
/**
* PAI Pulse Worker — Provisioning Script
*
* Sets up a new PAI Worker from scratch.
* Reads DA_IDENTITY.md for worker identity.
* Generates PULSE.toml, .env, and installs launchd service.
*
* Usage: bun run setup.ts
* Goal: under 30 minutes from bare machine to working worker.
*/
import { join, resolve } from "path"
import { existsSync, mkdirSync } from "fs"
const HOME = process.env.HOME ?? "~"
const PAI_DIR = join(HOME, ".claude", "PAI")
const PULSE_DIR = join(PAI_DIR, "PULSE")
// ── Helpers ──
function prompt(question: string): Promise<string> {
process.stdout.write(`\n ${question} `)
return new Promise((resolve) => {
const buf: Buffer[] = []
process.stdin.resume()
process.stdin.once("data", (data) => {
process.stdin.pause()
resolve(data.toString().trim())
})
})
}
function heading(text: string): void {
console.log(`\n${"─".repeat(50)}`)
console.log(` ${text}`)
console.log(`${"─".repeat(50)}`)
}
function ok(text: string): void {
console.log(` [ok] ${text}`)
}
function warn(text: string): void {
console.log(` [!!] ${text}`)
}
// ── Step 1: Read Identity ──
async function readIdentity(): Promise<{ name: string; description: string }> {
heading("Step 1: Worker Identity")
const identityPath = join(PAI_DIR, "USER", "DA_IDENTITY.md")
if (existsSync(identityPath)) {
const content = await Bun.file(identityPath).text()
const nameMatch = content.match(/\*\*Name:\*\*\s*(.+)/i) ?? content.match(/^-\s*\*\*Name:\*\*\s*(.+)/mi)
const roleMatch = content.match(/\*\*Role:\*\*\s*(.+)/i)
const name = nameMatch?.[1]?.trim() ?? ""
const description = roleMatch?.[1]?.trim() ?? ""
if (name) {
ok(`Found identity: ${name}`)
if (description) ok(`Role: ${description}`)
return { name: name.toLowerCase(), description }
}
}
const name = await prompt("Worker name (e.g., devi, echo, cipher):")
const description = await prompt("Worker description (e.g., research specialist):")
return { name: name.toLowerCase(), description }
}
// ── Step 2: GitHub App Setup ──
async function setupGitHubApp(workerName: string): Promise<{
appId: string
installationId: string
privateKeyPath: string
repos: string[]
}> {
heading("Step 2: GitHub App")
console.log(`
Create a GitHub App for this worker:
1. Go to: https://github.com/settings/apps/new
2. App name: pai-worker-${workerName}
3. Homepage URL: https://github.com/danielmiessler
4. Uncheck Webhook (Active)
5. Permissions:
- Issues: Read & Write
- Contents: Read & Write
- Pull requests: Read & Write
- Metadata: Read-only
6. Where can this app be installed? → Only on this account
7. Create GitHub App
8. Note the App ID
9. Generate a private key (downloads .pem file)
10. Install the app on your repos
`)
const appId = await prompt("GitHub App ID:")
const privateKeyPath = await prompt("Path to private key (.pem file):")
const resolvedKey = resolve(privateKeyPath.replace(/^~/, HOME))
if (!existsSync(resolvedKey)) {
warn(`Private key not found at: ${resolvedKey}`)
warn("You can set this up later in PULSE.toml")
} else {
ok(`Private key found: ${resolvedKey}`)
}
// Get installation ID
console.log(`
Find your installation ID:
1. Go to: https://github.com/settings/installations
2. Click "Configure" on pai-worker-${workerName}
3. The URL ends with /installations/XXXXX — that number is the ID
`)
const installationId = await prompt("Installation ID:")
const reposInput = await prompt("Repos to monitor (comma-separated, e.g., your-org/your-repo):")
const repos = reposInput.split(",").map((r) => r.trim()).filter(Boolean)
ok(`GitHub App configured: ${appId}`)
return { appId, installationId, privateKeyPath: resolvedKey, repos }
}
// ── Step 3: Telegram Setup ──
async function setupTelegram(workerName: string): Promise<{ botToken: string; chatId: string }> {
heading("Step 3: Telegram Bot")
console.log(`
Create a Telegram bot for ${workerName}:
1. Message @BotFather on Telegram
2. Send: /newbot
3. Name: ${workerName} PAI Worker
4. Username: pai_${workerName}_bot
5. Copy the bot token
`)
const botToken = await prompt("Bot token (or press Enter to skip):")
if (!botToken) {
warn("Telegram skipped — can configure later in .env")
return { botToken: "", chatId: "" }
}
const chatId = await prompt("Your Telegram chat ID:")
ok("Telegram configured")
return { botToken, chatId }
}
// ── Step 4: Generate Config Files ──
async function generateConfigs(opts: {
name: string
description: string
appId: string
installationId: string
privateKeyPath: string
repos: string[]
botToken: string
chatId: string
specialization: string[]
}): Promise<void> {
heading("Step 4: Generating Config Files")
// PULSE.toml
const reposToml = opts.repos.map((r) => `"${r}"`).join(", ")
const specToml = opts.specialization.map((s) => `"${s}"`).join(", ")
const pulseToml = `# PAI Pulse — ${opts.name} Worker Configuration
#
# type = "script" → runs command, $0 cost
# type = "claude" → spawns claude --print, costs tokens
# output = voice | telegram | ntfy | email | log
# Sentinels: NO_ACTION, NO_URGENT, NO_EVENTS → suppress dispatch
[worker]
name = "${opts.name}"
github_app_id = "${opts.appId}"
github_app_private_key = "${opts.privateKeyPath}"
github_installation_id = "${opts.installationId}"
repos = [${reposToml}]
specialization = [${specToml}]
max_concurrent = 1
[[job]]
name = "github-work"
schedule = "*/2 * * * *"
type = "script"
command = "bun run checks/github-work.ts"
output = "log"
enabled = true
[[job]]
name = "healthcheck"
schedule = "*/5 * * * *"
type = "script"
command = "bun run checks/health.ts"
output = "telegram"
enabled = true
[[job]]
name = "morning-report"
schedule = "0 7 * * *"
type = "claude"
prompt = "You are ${opts.name}, a PAI Worker (${opts.description}). Summarize your completed work from the last 24 hours. Check recent git log and closed issues. Be concise."
model = "sonnet"
output = "telegram"
enabled = true
`
await Bun.write(join(PULSE_DIR, "PULSE.toml"), pulseToml)
ok("PULSE.toml written")
// .env
const envLines = [
`# PAI Worker: ${opts.name}`,
`# Generated by setup.ts on ${new Date().toISOString()}`,
``,
`# GitHub App`,
`GITHUB_APP_ID=${opts.appId}`,
`GITHUB_APP_PRIVATE_KEY_PATH=${opts.privateKeyPath}`,
`GITHUB_INSTALLATION_ID=${opts.installationId}`,
``,
`# Telegram`,
opts.botToken ? `TELEGRAM_BOT_TOKEN=${opts.botToken}` : `# TELEGRAM_BOT_TOKEN=`,
opts.chatId ? `TELEGRAM_PRINCIPAL_CHAT_ID=${opts.chatId}` : `# TELEGRAM_PRINCIPAL_CHAT_ID=`,
``,
`# Anthropic`,
`# ANTHROPIC_API_KEY=sk-ant-...`,
``,
]
const envPath = join(HOME, ".claude", ".env")
if (existsSync(envPath)) {
warn(`.env already exists — appending worker config`)
const existing = await Bun.file(envPath).text()
await Bun.write(envPath, existing + "\n" + envLines.join("\n"))
} else {
await Bun.write(envPath, envLines.join("\n"))
}
ok(".env written")
}
// ── Step 5: Local HTTPS Setup (hosts file + mkcert) ──
async function setupLocalHTTPS(): Promise<void> {
heading("Step 5: Local HTTPS (mkcert)")
// Check if 'pai' hostname is in /etc/hosts
const hostsContent = await Bun.file("/etc/hosts").text()
const hasPaiHost = /^\s*127\.0\.0\.1\s+.*\bpai\b/m.test(hostsContent)
if (!hasPaiHost) {
console.log(`
The 'pai' hostname needs to be added to /etc/hosts.
This requires sudo. The following line will be appended:
127.0.0.1\tpai
`)
const confirm = await prompt("Add 'pai' to /etc/hosts? (y/n):")
if (confirm.toLowerCase() === "y") {
const proc = Bun.spawn(["sudo", "bash", "-c", `echo '127.0.0.1\tpai' >> /etc/hosts`], {
stdout: "inherit",
stderr: "inherit",
stdin: "inherit",
})
const code = await proc.exited
if (code === 0) {
ok("Added 'pai' to /etc/hosts")
} else {
warn("Failed to update /etc/hosts — add manually: 127.0.0.1 pai")
}
} else {
warn("Skipped — add manually: echo '127.0.0.1 pai' | sudo tee -a /etc/hosts")
}
} else {
ok("'pai' hostname already in /etc/hosts")
}
// Check for mkcert
const whichProc = Bun.spawn(["which", "mkcert"], { stdout: "pipe", stderr: "pipe" })
const whichCode = await whichProc.exited
if (whichCode !== 0) {
console.log(`
mkcert is needed for local HTTPS. Installing via Homebrew...
`)
const brewProc = Bun.spawn(["brew", "install", "mkcert"], {
stdout: "inherit",
stderr: "inherit",
})
const brewCode = await brewProc.exited
if (brewCode !== 0) {
warn("Failed to install mkcert — install manually: brew install mkcert")
warn("Then run: mkcert -install && cd Pulse/certs && mkcert pai localhost 127.0.0.1")
return
}
}
ok("mkcert available")
// Install local CA into system trust store
console.log("\n Installing local CA into system trust store...")
const caProc = Bun.spawn(["mkcert", "-install"], {
stdout: "inherit",
stderr: "inherit",
})
await caProc.exited
ok("Local CA installed in system trust store")
// Generate certs
const certsDir = join(PULSE_DIR, "certs")
const certPath = join(certsDir, "pai+2.pem")
if (existsSync(certPath)) {
ok("TLS certificates already exist")
} else {
mkdirSync(certsDir, { recursive: true })
const certProc = Bun.spawn(["mkcert", "pai", "localhost", "127.0.0.1"], {
cwd: certsDir,
stdout: "inherit",
stderr: "inherit",
})
const certCode = await certProc.exited
if (certCode === 0) {
ok("TLS certificates generated for: pai, localhost, 127.0.0.1")
ok(`Cert: ${join(certsDir, "pai+2.pem")}`)
ok(`Key: ${join(certsDir, "pai+2-key.pem")}`)
ok("Expires in 2 years — regenerate with: cd Pulse/certs && mkcert pai localhost 127.0.0.1")
} else {
warn("Failed to generate certificates")
}
}
}
// ── Step 6: Install launchd Service ──
async function installService(): Promise<void> {
heading("Step 6: Installing launchd Service")
// Create directories
for (const dir of ["state", "logs"]) {
const path = join(PULSE_DIR, dir)
if (!existsSync(path)) mkdirSync(path, { recursive: true })
}
const plistSrc = join(PULSE_DIR, "com.pai.pulse.plist")
const plistDst = join(HOME, "Library", "LaunchAgents", "com.pai.pulse.plist")
if (!existsSync(plistSrc)) {
warn("com.pai.pulse.plist not found — create it manually")
return
}
// Copy and load plist
const proc = Bun.spawn(["bash", "-c", `cp "${plistSrc}" "${plistDst}" && launchctl load "${plistDst}" 2>/dev/null`], {
stdout: "pipe",
stderr: "pipe",
})
await proc.exited
ok("launchd service installed")
}
// ── Step 7: Health Check ──
async function healthCheck(): Promise<void> {
heading("Step 7: Health Check")
// Wait for Pulse to start
await Bun.sleep(3_000)
const pidPath = join(PULSE_DIR, "state", "pulse.pid")
if (existsSync(pidPath)) {
const pid = (await Bun.file(pidPath).text()).trim()
const proc = Bun.spawn(["ps", "-p", pid], { stdout: "pipe", stderr: "pipe" })
const code = await proc.exited
if (code === 0) {
ok(`Pulse running (PID ${pid})`)
} else {
warn(`Pulse PID ${pid} not running — check logs/pulse-stderr.log`)
}
} else {
warn("No PID file — Pulse may not have started")
}
// Check hook server
try {
const resp = await fetch("http://localhost:31337/healthz", { signal: AbortSignal.timeout(3_000) })
if (resp.ok) {
const data = (await resp.json()) as { status: string; jobs: unknown[] }
ok(`Hook server responding — ${(data.jobs as unknown[])?.length ?? 0} jobs loaded`)
}
} catch {
warn("Hook server not responding on port 31337")
}
}
// ── Main ──
async function main() {
console.log(`
${"═".repeat(50)}
PAI Pulse Worker Setup
Goal: Working AI employee in under 30 minutes
${"═".repeat(50)}`)
const startTime = Date.now()
const identity = await readIdentity()
const specInput = await prompt("Specialization labels (comma-separated, e.g., research,content — or Enter for none):")
const specialization = specInput ? specInput.split(",").map((s) => s.trim()).filter(Boolean) : []
const github = await setupGitHubApp(identity.name)
const telegram = await setupTelegram(identity.name)
await generateConfigs({
...identity,
...github,
...telegram,
specialization,
})
await setupLocalHTTPS()
await installService()
await healthCheck()
const elapsed = Math.round((Date.now() - startTime) / 1000)
console.log(`
${"═".repeat(50)}
Setup Complete!
Worker: ${identity.name}
Time: ${Math.floor(elapsed / 60)}m ${elapsed % 60}s
Next steps:
- Verify ANTHROPIC_API_KEY is set in ${join(HOME, ".claude", ".env")}
- Create a test issue with label "status:ready" in one of your repos
- Watch: tail -f ${join(PULSE_DIR, "logs", "pulse-stdout.log")}
- Status: ${join(PULSE_DIR, "manage.sh")} status
${"═".repeat(50)}
`)
}
main().catch((err) => {
console.error(`Setup failed: ${err}`)
process.exit(1)
})