-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
1006 lines (888 loc) · 36.7 KB
/
Copy pathcli.ts
File metadata and controls
1006 lines (888 loc) · 36.7 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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env tsx
/**
* cli.ts — CLI entrypoint for supertinker
*
* Usage:
* tsx cli.ts run --prompt "Build a REST API"
* tsx cli.ts run --workflow meta --prompt "Build a REST API"
* tsx cli.ts resume --run <runId> --choice <label> --workflow <name|path>
* tsx cli.ts status --run <runId>
* tsx cli.ts list
* tsx cli.ts plugins list [--installed]
* tsx cli.ts plugins install [<name>...] [--global|--local]
* tsx cli.ts plugins uninstall <name>... --global|--local
* tsx cli.ts plugins update
*/
import { existsSync, mkdirSync, readFileSync, copyFileSync, unlinkSync, writeFileSync, readdirSync, statSync } from "fs"
import { spawnSync, execSync } from "child_process"
import { join, resolve } from "path"
import { homedir } from "os"
import { run, resume, buildCatalog, buildNodeCatalog, loadStorage, loadHooks } from "./supertinker.js"
import type { Context, ProviderOverrides, StorageAdapter } from "./supertinker.js"
import { renderDashboard } from "./dashboard.js"
import type { TranscriptMapper } from "./display-protocol.js"
// ─── TMUX AUTO-LAUNCH
function shellQuote(a: string): string {
return `'${a.replace(/'/g, `'\\''`)}'`
}
async function discoverRunId(storage: StorageAdapter, sinceMs: number, timeoutMs = 4000): Promise<string | null> {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
const runs = await storage.listRuns({ sinceMs })
if (runs.length > 0) {
runs.sort((a, b) => b.mtimeMs - a.mtimeMs)
return runs[0].runId
}
await new Promise(r => setTimeout(r, 50))
}
return null
}
async function ensureTmux(): Promise<boolean> {
if (!!process.env.TMUX) return true
const storage = await loadStorage()
const sess = `supertinker-${Date.now()}`
const cmd = process.argv.map(shellQuote).join(" ")
const startedAt = Date.now()
// Create an empty session first so the shell persists after the command exits;
// otherwise the session dies the moment the workflow pauses/finishes and the
// user can no longer attach to inspect what happened.
const create = spawnSync("tmux", ["new-session", "-d", "-s", sess], { stdio: "ignore" })
if (create.error || create.status !== 0) {
console.log("(tmux not available — running without panes)")
return true
}
const send = spawnSync("tmux", ["send-keys", "-t", sess, cmd, "Enter"], { stdio: "ignore" })
if (send.error || send.status !== 0) {
spawnSync("tmux", ["kill-session", "-t", sess], { stdio: "ignore" })
console.log("(tmux not available — running without panes)")
return true
}
const runId = await discoverRunId(storage, startedAt)
console.log(`supertinker running in tmux session: ${sess}`)
console.log(` attach: tmux attach -t ${sess}`)
console.log(` kill: tmux kill-session -t ${sess}`)
if (runId) {
console.log(` runId: ${runId}`)
console.log(` logs: tail -f ${storage.runDir(runId)}/orchestrator.log`)
console.log(` status: ${process.argv[0]} ${process.argv[1]} status --run ${runId}`)
} else {
console.log(` (run not yet detected — check the tmux session)`)
}
return false
}
// ─── PLUGIN TYPES
interface PluginManifest {
name: string
type: "hook" | "provider" | "workflow" | "storage" | "command" | "node"
description: string
files: string[]
version: string
}
interface InstalledEntry {
name: string
type: string
version: string
installedAt: string
}
interface InstalledJson {
plugins: InstalledEntry[]
}
export interface CommandPlugin {
name: string
description: string
usage?: string
handler: (args: string[], get: (flag: string) => string | undefined) => Promise<void>
}
const PLUGIN_TYPES = ["hook", "provider", "workflow", "storage", "command", "node"] as const
const TYPE_TO_DIR: Record<string, string> = {
hook: "hooks", provider: "providers", workflow: "workflows", storage: "storage", command: "commands", node: "nodes",
}
const USER_HOME = join(homedir(), ".supertinker")
const CACHE_DIR = join(USER_HOME, "cache", "supertinker")
const REPO_URL = "https://github.com/AndurilCode/supertinker.git"
function discoverPlugins(pluginsRoot: string): PluginManifest[] {
const manifests: PluginManifest[] = []
for (const type of PLUGIN_TYPES) {
const typeDir = join(pluginsRoot, TYPE_TO_DIR[type])
if (!existsSync(typeDir)) continue
for (const entry of readdirSync(typeDir)) {
const manifestPath = join(typeDir, entry, "manifest.json")
if (!existsSync(manifestPath)) continue
try {
const m = JSON.parse(readFileSync(manifestPath, "utf8")) as PluginManifest
manifests.push(m)
} catch {}
}
}
return manifests
}
function loadInstalled(targetDir: string): InstalledJson {
const p = join(targetDir, "installed.json")
if (!existsSync(p)) return { plugins: [] }
try { return JSON.parse(readFileSync(p, "utf8")) } catch { return { plugins: [] } }
}
function saveInstalled(targetDir: string, data: InstalledJson): void {
writeFileSync(join(targetDir, "installed.json"), JSON.stringify(data, null, 2))
}
function copyPluginFile(src: string, dest: string, cacheRoot: string): void {
if (src.endsWith(".ts")) {
// Rewrite type imports to point at supertinker.ts in the resolved cache root
// (either the npm-installed package dir or ~/.supertinker/cache/supertinker/).
// These are type-only imports (erased at runtime) — just for IDE type-checking.
const supertinkerPath = join(cacheRoot, "supertinker.js")
let content = readFileSync(src, "utf8")
content = content.replace(
/from\s+["'][^"']*supertinker(?:\.js)?["']/g,
`from "${supertinkerPath}"`,
)
writeFileSync(dest, content)
} else {
copyFileSync(src, dest)
}
}
// The package's own plugins/ dir — works when installed via npm/npx
const PKG_DIR = resolve(join(new URL(import.meta.url).pathname, ".."))
function ensureCache(): string {
// 1. Check package-local plugins (npm install / npx)
if (existsSync(join(PKG_DIR, "plugins"))) return PKG_DIR
// 2. Check existing cache
if (existsSync(join(CACHE_DIR, "plugins"))) return CACHE_DIR
if (existsSync(CACHE_DIR)) return CACHE_DIR
// 3. Clone
console.log("Cloning supertinker plugin repository...")
try {
mkdirSync(join(USER_HOME, "cache"), { recursive: true })
execSync(`git clone "${REPO_URL}" "${CACHE_DIR}"`, { stdio: "inherit" })
return CACHE_DIR
} catch (err) {
console.error("Failed to clone plugin repository. Check your network connection.")
console.error(` Repo URL: ${REPO_URL}`)
console.error(` Cache dir: ${CACHE_DIR}`)
process.exit(1)
}
}
// ─── PLUGINS LIST
function pluginsList(onlyInstalled: boolean): void {
const cacheRoot = ensureCache()
const available = discoverPlugins(join(cacheRoot, "plugins"))
const globalInstalled = loadInstalled(USER_HOME)
const localInstalled = loadInstalled(join(process.cwd(), ".supertinker"))
const installedMap = new Map<string, string>()
for (const p of globalInstalled.plugins) installedMap.set(p.name, "global")
for (const p of localInstalled.plugins) installedMap.set(p.name, "local")
const grouped = new Map<string, PluginManifest[]>()
for (const type of PLUGIN_TYPES) grouped.set(type, [])
for (const m of available) grouped.get(m.type)!.push(m)
const typeLabels: Record<string, string> = {
hook: "Hooks", provider: "Providers", workflow: "Workflows", storage: "Storage", command: "Commands", node: "Node Types",
}
for (const type of PLUGIN_TYPES) {
const plugins = grouped.get(type)!
if (plugins.length === 0) continue
console.log(`\n${typeLabels[type]}:`)
for (const p of plugins) {
const scope = installedMap.get(p.name)
if (onlyInstalled && !scope) continue
const marker = scope ? "\u25cf" : "\u25cb"
const tag = scope ? ` [${scope}]` : ""
console.log(` ${marker} ${p.name.padEnd(20)} ${p.description}${tag}`)
}
}
console.log()
}
// ─── ANSI INTERACTIVE PICKER
interface PickerItem {
name: string
description: string
type: string
selected: boolean
isHeader: boolean
}
function ansiPicker(available: PluginManifest[], alreadyInstalled: Set<string>): Promise<string[]> {
return new Promise((resolve) => {
const typeLabels: Record<string, string> = {
hook: "Hooks", provider: "Providers", workflow: "Workflows", storage: "Storage",
}
const items: PickerItem[] = []
for (const type of PLUGIN_TYPES) {
const plugins = available.filter(p => p.type === type)
if (plugins.length === 0) continue
items.push({ name: typeLabels[type], description: "", type, selected: false, isHeader: true })
for (const p of plugins) {
items.push({ name: p.name, description: p.description, type: p.type, selected: false, isHeader: false })
}
}
let cursor = items.findIndex(i => !i.isHeader)
if (cursor < 0) { resolve([]); return }
const stdin = process.stdin
const wasRaw = stdin.isRaw
stdin.setRawMode(true)
stdin.resume()
stdin.setEncoding("utf8")
function render(): void {
process.stdout.write("\x1b[H\x1b[J")
process.stdout.write("Select plugins to install (\u2191\u2193 navigate, space toggle, enter confirm):\n\n")
for (let i = 0; i < items.length; i++) {
const item = items[i]
if (item.isHeader) {
process.stdout.write(` \x1b[1m${item.name}\x1b[0m\n`)
continue
}
const isCursor = i === cursor
const installed = alreadyInstalled.has(item.name)
const check = installed ? "\x1b[90m[installed]\x1b[0m" : item.selected ? "[x]" : "[ ]"
const prefix = isCursor ? "\x1b[36m> \x1b[0m" : " "
const nameStr = item.name.padEnd(20)
process.stdout.write(`${prefix}${check} ${nameStr} ${item.description}\n`)
}
process.stdout.write("\n")
}
function onKey(key: string): void {
if (key === "\x1b[A") {
do { cursor = (cursor - 1 + items.length) % items.length } while (items[cursor].isHeader)
} else if (key === "\x1b[B") {
do { cursor = (cursor + 1) % items.length } while (items[cursor].isHeader)
} else if (key === " ") {
const item = items[cursor]
if (!item.isHeader && !alreadyInstalled.has(item.name)) item.selected = !item.selected
} else if (key === "\r" || key === "\n") {
stdin.setRawMode(wasRaw ?? false)
stdin.removeListener("data", onKey)
stdin.pause()
process.stdout.write("\x1b[H\x1b[J")
resolve(items.filter(i => i.selected && !i.isHeader).map(i => i.name))
return
} else if (key === "\x03") {
stdin.setRawMode(wasRaw ?? false)
stdin.removeListener("data", onKey)
stdin.pause()
process.stdout.write("\x1b[H\x1b[J")
process.exit(0)
}
render()
}
render()
stdin.on("data", onKey)
})
}
function ansiScopePicker(): Promise<"global" | "local"> {
return new Promise((resolve) => {
const options = [
{ label: `Global (${USER_HOME}/)`, value: "global" as const },
{ label: `Local (.supertinker/)`, value: "local" as const },
]
let cursor = 0
const stdin = process.stdin
const wasRaw = stdin.isRaw
stdin.setRawMode(true)
stdin.resume()
stdin.setEncoding("utf8")
function render(): void {
process.stdout.write("\x1b[H\x1b[J")
process.stdout.write("Install to:\n\n")
for (let i = 0; i < options.length; i++) {
const prefix = i === cursor ? "\x1b[36m> \x1b[0m" : " "
process.stdout.write(`${prefix}${options[i].label}\n`)
}
}
function onKey(key: string): void {
if (key === "\x1b[A") cursor = (cursor - 1 + options.length) % options.length
else if (key === "\x1b[B") cursor = (cursor + 1) % options.length
else if (key === "\r" || key === "\n") {
stdin.setRawMode(wasRaw ?? false)
stdin.removeListener("data", onKey)
stdin.pause()
process.stdout.write("\x1b[H\x1b[J")
resolve(options[cursor].value)
return
} else if (key === "\x03") {
stdin.setRawMode(wasRaw ?? false)
stdin.removeListener("data", onKey)
stdin.pause()
process.stdout.write("\x1b[H\x1b[J")
process.exit(0)
}
render()
}
render()
stdin.on("data", onKey)
})
}
// ─── PLUGINS INSTALL
async function installPlugins(names: string[], scope: "global" | "local"): Promise<void> {
const cacheRoot = ensureCache()
const available = discoverPlugins(join(cacheRoot, "plugins"))
const targetDir = scope === "global" ? USER_HOME : join(process.cwd(), ".supertinker")
const installed = loadInstalled(targetDir)
const installedNames = new Set(installed.plugins.map(p => p.name))
let toInstall: string[]
if (names.length > 0) {
toInstall = names
} else {
toInstall = await ansiPicker(available, installedNames)
}
if (toInstall.length === 0) {
console.log("No plugins selected.")
return
}
let count = 0
for (const name of toInstall) {
if (installedNames.has(name)) {
console.log(` skip: ${name} (already installed)`)
continue
}
const manifest = available.find(m => m.name === name)
if (!manifest) {
console.error(` error: plugin "${name}" not found`)
continue
}
const sourceDir = join(cacheRoot, "plugins", TYPE_TO_DIR[manifest.type], name)
const destDir = join(targetDir, TYPE_TO_DIR[manifest.type])
mkdirSync(destDir, { recursive: true })
for (const file of manifest.files) {
copyPluginFile(join(sourceDir, file), join(destDir, file), cacheRoot)
}
installed.plugins.push({
name: manifest.name,
type: manifest.type,
version: manifest.version,
installedAt: new Date().toISOString(),
})
console.log(` installed: ${name} (${manifest.type}) \u2192 ${scope}`)
count++
}
saveInstalled(targetDir, installed)
console.log(`\n${count} plugin(s) installed.`)
}
// ─── PLUGINS UNINSTALL
function uninstallPlugins(names: string[], scope: "global" | "local"): void {
const targetDir = scope === "global" ? USER_HOME : join(process.cwd(), ".supertinker")
const installed = loadInstalled(targetDir)
let count = 0
for (const name of names) {
const idx = installed.plugins.findIndex(p => p.name === name)
if (idx < 0) {
console.error(` skip: ${name} (not installed in ${scope})`)
continue
}
const entry = installed.plugins[idx]
const dir = join(targetDir, TYPE_TO_DIR[entry.type])
const cacheRoot = ensureCache()
const manifestPath = join(cacheRoot, "plugins", TYPE_TO_DIR[entry.type], name, "manifest.json")
if (existsSync(manifestPath)) {
const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as PluginManifest
for (const file of manifest.files) {
const filePath = join(dir, file)
if (existsSync(filePath)) unlinkSync(filePath)
}
}
installed.plugins.splice(idx, 1)
console.log(` uninstalled: ${name} (${entry.type}) from ${scope}`)
count++
}
saveInstalled(targetDir, installed)
console.log(`\n${count} plugin(s) uninstalled.`)
}
// ─── PLUGINS UPDATE
function pluginsUpdate(): void {
if (!existsSync(CACHE_DIR)) {
console.error("Plugin cache not found. Run `supertinker plugins list` first to initialize.")
process.exit(1)
}
console.log("Pulling latest plugins...")
try {
execSync("git pull", { cwd: CACHE_DIR, stdio: "inherit" })
} catch {
console.error("Failed to pull. Check your network connection.")
process.exit(1)
}
const available = discoverPlugins(join(CACHE_DIR, "plugins"))
const availableMap = new Map(available.map(m => [m.name, m]))
let updated = 0
const globalInstalled = loadInstalled(USER_HOME)
for (const entry of globalInstalled.plugins) {
const manifest = availableMap.get(entry.name)
if (!manifest) continue
const sourceDir = join(CACHE_DIR, "plugins", TYPE_TO_DIR[manifest.type], manifest.name)
const destDir = join(USER_HOME, TYPE_TO_DIR[manifest.type])
mkdirSync(destDir, { recursive: true })
for (const file of manifest.files) {
copyPluginFile(join(sourceDir, file), join(destDir, file), CACHE_DIR)
}
const changed = entry.version !== manifest.version
if (changed) {
console.log(` updated: ${entry.name} (${entry.version} \u2192 ${manifest.version}) [global]`)
entry.version = manifest.version
updated++
} else {
console.log(` current: ${entry.name} (${entry.version}) [global]`)
}
}
saveInstalled(USER_HOME, globalInstalled)
const localDir = join(process.cwd(), ".supertinker")
const localInstalled = loadInstalled(localDir)
for (const entry of localInstalled.plugins) {
const manifest = availableMap.get(entry.name)
if (!manifest) continue
const sourceDir = join(CACHE_DIR, "plugins", TYPE_TO_DIR[manifest.type], manifest.name)
const destDir = join(localDir, TYPE_TO_DIR[manifest.type])
mkdirSync(destDir, { recursive: true })
for (const file of manifest.files) {
copyPluginFile(join(sourceDir, file), join(destDir, file), CACHE_DIR)
}
const changed = entry.version !== manifest.version
if (changed) {
console.log(` updated: ${entry.name} (${entry.version} \u2192 ${manifest.version}) [local]`)
entry.version = manifest.version
updated++
} else {
console.log(` current: ${entry.name} (${entry.version}) [local]`)
}
}
saveInstalled(localDir, localInstalled)
console.log(`\n${updated} plugin(s) updated.`)
}
// ─── COMMAND PLUGIN LOADER
async function loadCommandPlugin(name: string): Promise<CommandPlugin | null> {
const BUILTIN_DIR = resolve(join(new URL(import.meta.url).pathname, ".."))
const USER_DIR = join(homedir(), ".supertinker")
const PROJECT_DIR = join(process.cwd(), ".supertinker")
const SEARCH_DIRS = [PROJECT_DIR, USER_DIR, BUILTIN_DIR]
for (const base of SEARCH_DIRS) {
for (const ext of ["ts", "js"]) {
const p = join(base, "commands", `${name}.${ext}`)
if (existsSync(p)) {
try {
const mod = await import(p)
const cmd = mod.command ?? mod.default?.command
if (cmd && typeof cmd.handler === "function" && cmd.name) return cmd as CommandPlugin
} catch {}
}
}
}
return null
}
async function discoverCommandPlugins(): Promise<Array<{ name: string; description: string; usage?: string }>> {
const BUILTIN_DIR = resolve(join(new URL(import.meta.url).pathname, ".."))
const USER_DIR = join(homedir(), ".supertinker")
const PROJECT_DIR = join(process.cwd(), ".supertinker")
const SEARCH_DIRS = [PROJECT_DIR, USER_DIR, BUILTIN_DIR]
const seen = new Set<string>()
const results: Array<{ name: string; description: string; usage?: string }> = []
for (const base of SEARCH_DIRS) {
const dir = join(base, "commands")
if (!existsSync(dir)) continue
let files: string[]
try { files = readdirSync(dir).filter((f: string) => f.endsWith(".ts") || f.endsWith(".js")) } catch { continue }
for (const file of files) {
const name = file.replace(/\.(ts|js)$/, "")
if (seen.has(name)) continue
try {
const mod = await import(join(dir, file))
const cmd = mod.command ?? mod.default?.command
if (cmd && typeof cmd.handler === "function" && cmd.name) {
seen.add(name)
results.push({ name: cmd.name, description: cmd.description ?? "", usage: cmd.usage })
}
} catch {}
}
}
return results
}
// ─── MAPPER LOADER
async function loadMapperForProvider(provider: string): Promise<TranscriptMapper | null> {
const BUILTIN_DIR = resolve(join(new URL(import.meta.url).pathname, ".."))
const USER_DIR = join(homedir(), ".supertinker")
const PROJECT_DIR = join(process.cwd(), ".supertinker")
const SEARCH_DIRS = [PROJECT_DIR, USER_DIR, BUILTIN_DIR]
for (const base of SEARCH_DIRS) {
for (const ext of ["ts", "js"]) {
const p = join(base, "providers", `${provider}.${ext}`)
if (existsSync(p)) {
try {
const mod = await import(p)
const mapper = mod.mapTranscript ?? mod.default?.mapTranscript
if (typeof mapper === "function") return mapper
} catch {}
}
}
}
return null
}
// ─── BUILT-IN COMMANDS (exposed through the same CommandPlugin contract as
// external command plugins, but bundled with the CLI so they are always
// available without installation).
const runCmd: CommandPlugin = {
name: "run",
description: "run a workflow",
usage: "run [--workflow <name|path>] --prompt <text> [--quiet] (default: meta)",
async handler(args, get) {
const workflowRef = get("--workflow") ?? "meta"
const prompt = get("--prompt")
const provider = get("--provider")
const model = get("--model")
const quiet = args.includes("--quiet")
const overrides: ProviderOverrides = { ...(provider && { provider }), ...(model && { model }) }
const storage = await loadStorage()
const workflowPath = await storage.resolveWorkflow(workflowRef) ?? resolve(workflowRef)
const { workflow } = await import(workflowPath)
const initialContext: Context = {
catalog: await buildCatalog(storage),
nodeCatalog: await buildNodeCatalog(),
cwd: process.cwd(),
// Exact re-invocation command (node/bun binary + entry file) so agents
// can call back into supertinker without guessing how it was launched
// (npx, bun-from-skill, global symlink, or repo-local tsx).
launcher: `${process.argv[0]} ${process.argv[1]}`,
}
if (prompt) initialContext.task = prompt
if (quiet) {
await run({ workflow, initialContext, overrides })
// Force exit — hooks and other plugins may hold the event loop alive
// (e.g. detached child processes, lingering timers). Once the workflow
// has reached a terminal/paused state there is no more CLI work to do.
process.exit(0)
}
// Dashboard mode: suppress stdout writes and prevent child processes
// (claude CLI) from writing to /dev/tty, which breaks Ink's rendering.
process.stdout.write = (() => true) as any
const prefix = workflow.id
const sinceMs = Date.now()
const discoverRunDir = (): Promise<string> => new Promise((res) => {
const interval = setInterval(async () => {
const runs = await storage.listRuns({ sinceMs })
const match = runs.find(r => r.runId.startsWith(prefix))
if (match) {
clearInterval(interval)
res(storage.runDir(match.runId))
}
}, 100)
})
const runDirPromise = discoverRunDir()
const workflowPromise = run({ workflow, initialContext, overrides })
const resolvedRunDir = await runDirPromise
renderDashboard({
runDir: resolvedRunDir,
runWorkflow: () => workflowPromise,
loadMapper: loadMapperForProvider,
})
},
}
const resumeCmd: CommandPlugin = {
name: "resume",
description: "resume a paused run",
usage: "resume --run <runId> --choice <label> --workflow <name|path> [--quiet]",
async handler(args, get) {
const runId = get("--run"), choice = get("--choice"), workflowRef = get("--workflow")
const provider = get("--provider"), model = get("--model")
const quiet = args.includes("--quiet")
const overrides: ProviderOverrides = { ...(provider && { provider }), ...(model && { model }) }
if (!runId || !choice || !workflowRef) { console.error("Usage: supertinker resume --run <id> --choice <label> --workflow <name|path>"); process.exit(1) }
const storage = await loadStorage()
const { workflow } = await import(await storage.resolveWorkflow(workflowRef) ?? resolve(workflowRef))
const runDir = storage.runDir(runId)
// Refresh runtime-computed context keys on every external resume so the
// agent sees the current plugin registry (not a snapshot from run start),
// and scrub transient retry-feedback keys so a budget-exhausted pause
// never leaks the prior turn's "previous attempt" text into a new user
// turn. A persistent director, for example, needs `catalog` to reflect
// workflows it created mid-run.
if (await storage.pauseExists(runDir)) {
const paused = await storage.loadPause(runDir)
paused.context.catalog = await buildCatalog(storage)
paused.context.nodeCatalog = await buildNodeCatalog()
paused.context.cwd = process.cwd()
paused.context.launcher = `${process.argv[0]} ${process.argv[1]}`
for (const k of Object.keys(paused.context)) {
if (k.startsWith("_retry_feedback:")) delete paused.context[k]
}
await storage.savePause(runDir, paused)
}
if (quiet) {
await resume({ workflow, runId, choice, overrides })
process.exit(0)
}
process.stdout.write = (() => true) as any
renderDashboard({
runDir: runDir,
runWorkflow: () => resume({ workflow, runId, choice, overrides }),
loadMapper: loadMapperForProvider,
})
},
}
const statusCmd: CommandPlugin = {
name: "status",
description: "inspect a run's state and context",
usage: "status --run <runId>",
async handler(args, get) {
const runId = get("--run")
if (!runId) { console.error("Usage: supertinker status --run <runId>"); process.exit(1) }
const storage = await loadStorage()
const runDir = storage.runDir(runId)
if (!existsSync(runDir)) { console.error(`Run directory not found: ${runDir}`); process.exit(1) }
// ── Discover sub-workflows
const subDirs: Array<{ name: string; dir: string }> = []
try {
for (const entry of readdirSync(runDir)) {
if (entry.startsWith("sub-")) {
const subDir = join(runDir, entry)
if (existsSync(subDir) && statSync(subDir).isDirectory()) {
subDirs.push({ name: entry.replace(/^sub-/, ""), dir: subDir })
}
}
}
} catch {}
// ── Parse events for timeline
type EvtSummary = { ts: string; event: string; nodeId?: string; extra: string; isSub: boolean; subName?: string }
function parseEventsFile(filePath: string, isSub: boolean, subName?: string): EvtSummary[] {
if (!existsSync(filePath)) return []
const summaries: EvtSummary[] = []
for (const line of readFileSync(filePath, "utf8").trim().split("\n")) {
if (!line) continue
try {
const e = JSON.parse(line)
const ts = (e.ts as string)?.slice(11, 19) ?? ""
const evt = e.event as string
const nodeId = e.nodeId as string | undefined
let extra = ""
if (evt === "PostAgent") {
const dur = Math.round((e.duration_ms as number ?? 0) / 1000)
extra = `choice=${e.choice} ${dur}s`
}
if (evt === "GuardrailFail") extra = e.reason as string ?? ""
if (evt === "Paused") extra = e.reason as string ?? ""
if (evt === "RunEnd") extra = `terminal=${e.terminal}`
if (evt === "SubworkflowStart") extra = `→ ${e.innerWorkflowId} (${e.innerNodeCount} nodes)`
if (evt === "SubworkflowEnd") extra = `keys=[${(e.innerContextKeys as string[])?.join(", ") ?? ""}]`
summaries.push({ ts, event: evt, nodeId, extra, isSub, subName })
} catch {}
}
return summaries
}
const outerEvents = parseEventsFile(join(runDir, "events.ndjson"), false)
const subEventsByName = new Map<string, EvtSummary[]>()
for (const sub of subDirs) {
subEventsByName.set(sub.name, parseEventsFile(join(sub.dir, "events.ndjson"), true, sub.name))
}
// ── Determine overall status
const hasPause = await storage.pauseExists(runDir)
const subPauses: Array<{ name: string; nodeId: string; reason: string }> = []
for (const sub of subDirs) {
if (await storage.pauseExists(sub.dir)) {
try {
const p = await storage.loadPause(sub.dir)
subPauses.push({ name: sub.name, nodeId: p.nodeId, reason: p.reason ?? "" })
} catch {}
}
}
const outerTerminal = outerEvents.find(e => e.event === "RunEnd")?.extra ?? ""
let overallStatus = hasPause ? "PAUSED" : outerTerminal.includes("done") ? "completed" : outerTerminal.includes("failed") ? "FAILED" : "running"
if (overallStatus === "completed" && subPauses.length > 0) {
overallStatus = "completed (sub-workflow paused)"
}
// ── Print header
console.log(`\n Run: ${runId}`)
console.log(` Dir: ${runDir}`)
console.log(` Status: ${overallStatus}\n`)
// ── Outer pause
if (hasPause) {
const paused = await storage.loadPause(runDir)
console.log(` Paused at: ${paused.nodeId}`)
if (paused.reason) console.log(` Reason: ${paused.reason}`)
if (paused.iterationCounts) {
const counts = Object.entries(paused.iterationCounts).filter(([, v]) => v > 0)
if (counts.length > 0) console.log(` Iterations: ${counts.map(([k, v]) => `${k}=${v}`).join(", ")}`)
}
console.log()
}
// ── Sub-workflow pauses
for (const sp of subPauses) {
console.log(` ⚠ Sub-workflow "${sp.name}" paused at node "${sp.nodeId}"`)
if (sp.reason) console.log(` Reason: ${sp.reason}`)
console.log()
}
// ── Timeline (interleaved outer + sub events)
console.log(` Timeline:`)
// Print outer events, inserting sub-workflow events at SubworkflowStart/End boundaries
const printedSubs = new Set<string>()
for (const evt of outerEvents) {
const node = evt.nodeId ? ` ${evt.nodeId}` : ""
const extra = evt.extra ? ` ${evt.extra}` : ""
console.log(` ${evt.ts} ${evt.event}${node}${extra}`)
// After SubworkflowStart, print that sub-workflow's events indented
if (evt.event === "SubworkflowStart") {
const innerName = evt.extra.match(/→ (\S+)/)?.[1]
if (innerName && subEventsByName.has(innerName) && !printedSubs.has(innerName)) {
printedSubs.add(innerName)
const subEvts = subEventsByName.get(innerName)!
for (const se of subEvts) {
const sNode = se.nodeId ? ` ${se.nodeId}` : ""
const sExtra = se.extra ? ` ${se.extra}` : ""
console.log(` ${se.ts} ${se.event}${sNode}${sExtra}`)
}
}
}
}
// Print any sub-workflows not anchored to a SubworkflowStart
for (const [name, evts] of subEventsByName) {
if (printedSubs.has(name)) continue
console.log(` ── sub: ${name}`)
for (const se of evts) {
const sNode = se.nodeId ? ` ${se.nodeId}` : ""
const sExtra = se.extra ? ` ${se.extra}` : ""
console.log(` ${se.ts} ${se.event}${sNode}${sExtra}`)
}
}
console.log()
// ── Context
let hasContext = false
try { await storage.loadContext(runDir); hasContext = true } catch {}
if (hasContext) {
const ctx = await storage.loadContext(runDir)
const keys = Object.keys(ctx)
console.log(` Context keys (${keys.length}):`)
for (const key of keys) {
const val = ctx[key]
const preview = val.length > 120 ? val.slice(0, 120) + "..." : val
console.log(` [${key}] (${val.length} chars) ${preview.replace(/\n/g, " ")}`)
}
console.log()
}
// ── Log (outer)
const logPath = join(runDir, "orchestrator.log")
if (existsSync(logPath)) {
const lines = readFileSync(logPath, "utf8").trim().split("\n")
const tail = lines.slice(-10)
console.log(` Log (last ${tail.length} of ${lines.length} lines):`)
for (const line of tail) console.log(` ${line}`)
console.log()
}
// ── Sub-workflow logs
for (const sub of subDirs) {
const subLog = join(sub.dir, "orchestrator.log")
if (!existsSync(subLog)) continue
const lines = readFileSync(subLog, "utf8").trim().split("\n")
const tail = lines.slice(-10)
console.log(` Sub-workflow "${sub.name}" log (last ${tail.length} of ${lines.length} lines):`)
for (const line of tail) console.log(` ${line}`)
console.log()
}
},
}
const listCmd: CommandPlugin = {
name: "list",
description: "show available workflows (or hooks with --hooks)",
usage: "list [--hooks]",
async handler(args) {
if (args.includes("--hooks")) {
const storage = await loadStorage()
const tmpDir = await storage.createRun("hook-list")
const hooks = await loadHooks(tmpDir)
const entries: string[] = []
const seen = new Set<string>()
for (const [, hookList] of hooks) {
for (const h of hookList) {
if (seen.has(h.name)) continue
seen.add(h.name)
entries.push(`- ${h.name}: ${h.description ?? "(no description)"} events: [${h.events.join(", ")}] parallel: ${h.parallel} priority: ${h.priority}`)
}
}
console.log(entries.length === 0 ? "No hooks found." : `Hooks (${entries.length}):\n${entries.join("\n")}`)
return
}
const storage = await loadStorage()
console.log(await buildCatalog(storage))
},
}
const pluginsCmd: CommandPlugin = {
name: "plugins",
description: "manage plugins (hooks, providers, workflows, storage, commands)",
usage: `plugins <list|install|uninstall|update>
list [--installed] show available/installed plugins
install [<name>...] [--global|--local] install plugins
uninstall <name>... --global|--local remove plugins
update pull latest + re-copy installed`,
async handler(args) {
const sub = args[0]
if (sub === "list") {
pluginsList(args.includes("--installed"))
return
}
if (sub === "install") {
const names = args.slice(1).filter(a => !a.startsWith("--"))
let scope: "global" | "local" | undefined
if (args.includes("--global")) scope = "global"
if (args.includes("--local")) scope = "local"
if (!scope) scope = await ansiScopePicker()
await installPlugins(names, scope)
return
}
if (sub === "uninstall") {
const names = args.slice(1).filter(a => !a.startsWith("--"))
if (names.length === 0) { console.error("Usage: supertinker plugins uninstall <name> [<name>...] --global|--local"); process.exit(1) }
let scope: "global" | "local" | undefined
if (args.includes("--global")) scope = "global"
if (args.includes("--local")) scope = "local"
if (!scope) { console.error("Specify --global or --local"); process.exit(1) }
uninstallPlugins(names, scope)
return
}
if (sub === "update") {
pluginsUpdate()
return
}
console.log("Usage: supertinker plugins <list|install|uninstall|update>")
},
}
const BUILTIN_COMMANDS: CommandPlugin[] = [runCmd, resumeCmd, statusCmd, listCmd, pluginsCmd]
function renderCommandEntry(c: { name: string; description: string; usage?: string }): string {
const head = ` ${c.name.padEnd(10)}${c.description}`
if (!c.usage) return head
const usageLines = c.usage.split("\n").map(l => ` ${l}`).join("\n")
return `${head}\n Usage:\n${usageLines}`
}
// ─── CLI
async function cli(): Promise<void> {
const argv = process.argv.slice(2)
const cmd = argv[0]
const get = (flag: string) => { const i = argv.indexOf(flag); return i >= 0 ? argv[i + 1] : undefined }
// Built-in commands share the CommandPlugin contract with external plugins.
const builtin = BUILTIN_COMMANDS.find(c => c.name === cmd)
if (builtin) {
await builtin.handler(argv.slice(1), get)
return
}
// Fall through to installed command plugins.
if (cmd && cmd !== "--help" && cmd !== "-h") {
const loaded = await loadCommandPlugin(cmd)
if (loaded) {
await loaded.handler(argv.slice(1), get)
return
}
}
// Help / no command: render built-ins and installed command plugins
// through the same renderer so they read identically.
const pluginCmds = await discoverCommandPlugins()
const builtinSection = BUILTIN_COMMANDS.map(renderCommandEntry).join("\n")
const pluginSection = pluginCmds.length > 0
? "\n\nInstalled command plugins:\n" + pluginCmds.map(renderCommandEntry).join("\n")
: ""
console.log(`supertinker — minimal agent orchestrator
Built-in commands:
${builtinSection}${pluginSection}
Examples:
tsx cli.ts run --prompt "Build a REST API"
tsx cli.ts plugins list
tsx cli.ts plugins install logger fork-worktree --global
tsx cli.ts plugins uninstall logger --global
tsx cli.ts plugins update`)
}
// ─── ENTRYPOINT
const cmd = process.argv[2]
const isQuiet = process.argv.includes("--quiet")
const isDashboard = false // TODO: re-enable when dashboard is stable — was: (cmd === "run" || cmd === "resume") && !isQuiet