-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcmd
More file actions
executable file
·417 lines (375 loc) · 13.1 KB
/
cmd
File metadata and controls
executable file
·417 lines (375 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
#!/usr/bin/env swift
import Foundation
#if os(Linux)
import Glibc
#else
import Darwin
#endif
func usage() {
print("""
Usage:
cmd list
cmd make <agent-name>
cmd <agent-id> <command...>
Global commands:
list -> list existing agents
make -> create agent working dir
Agent commands:
edit -> open agent working dir in $EDITOR
remove -> remove agent working dir (-y to confirm)
prompt -> run <tool> agent -m "<message>" (arg, tty prompt, or stdin)
start -> start gateway / daemon (depending on agent)
stop -> stop gateway / daemon (depending on agent)
Examples:
./cmd list
./cmd make 001-openclaw
./cmd 001 onboard
./cmd 001 prompt
./cmd 001 edit
./cmd 001 start
./cmd make 004-picoclaw
./cmd 004 onboard
./cmd 004 auth login --provider anthropic
./cmd 004 prompt "hello"
./cmd 004 stop
./cmd 007 make 007-zeroclaw
./cmd 007 onboard
./cmd 007 auth login --provider openai-codex
./cmd 007 onboard --channels-only
./cmd 007 status
""")
}
enum AgentTool: String, CaseIterable {
case openclaw
case picoclaw
case zeroclaw
}
enum GlobalCommand: String {
case make
case list
}
enum AgentCommand: String {
case edit
case prompt
case start
case stop
case remove
}
let rootURL = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
let agentsURL = rootURL.appendingPathComponent("agents", isDirectory: true)
let configURL = rootURL.appendingPathComponent("cfg")
var agentEntries: [URL] {
(try? FileManager.default.contentsOfDirectory(
at: agentsURL,
includingPropertiesForKeys: [.isDirectoryKey],
options: [.skipsHiddenFiles]
)) ?? []
}
func listAgents() -> Never {
let agents = agentEntries.compactMap { url -> String? in
let values = try? url.resourceValues(forKeys: [.isDirectoryKey])
guard values?.isDirectory == true else { return nil }
return url.lastPathComponent
}.sorted()
if agents.isEmpty {
print("no agents found")
} else {
for name in agents {
print(name)
}
}
exit(0)
}
enum ParsedCommand {
case globalMake(agentName: String)
case globalList
case agent(agentArg: String, command: String, extra: [String])
}
func parseArgs(_ args: [String]) -> ParsedCommand {
guard args.count >= 2 else {
usage()
exit(1)
}
switch args[1] {
case GlobalCommand.list.rawValue:
if args.count != 2 {
fputs("usage: cmd list\n", stderr)
exit(1)
}
return .globalList
case GlobalCommand.make.rawValue:
if args.count != 3 {
fputs("usage: cmd make <agent-name>\n", stderr)
exit(1)
}
return .globalMake(agentName: args[2])
default:
if args.count < 3 {
usage()
exit(1)
}
if args[2] == GlobalCommand.make.rawValue || args[2] == GlobalCommand.list.rawValue {
fputs("usage: cmd <agent-id> <command...>\n", stderr)
exit(1)
}
return .agent(agentArg: args[1], command: args[2], extra: Array(args.dropFirst(3)))
}
}
let parsed = parseArgs(CommandLine.arguments)
func resolveAgentName(_ agentArg: String, command: String) -> String {
if command == GlobalCommand.make.rawValue {
if AgentTool.allCases.contains(where: { agentArg.contains($0.rawValue) }) {
return agentArg
}
fputs("agent name must include kind, e.g. 007-openclaw (got: \(agentArg))\n", stderr)
exit(1)
}
let agentNames = agentEntries.compactMap { url -> String? in
let values = try? url.resourceValues(forKeys: [.isDirectoryKey])
guard values?.isDirectory == true else { return nil }
return url.lastPathComponent
}
if agentNames.contains(agentArg) {
return agentArg
}
let matches = agentNames.filter { name in
name.contains(agentArg) && AgentTool.allCases.contains { name.contains($0.rawValue) }
}
if matches.count == 1 {
return matches[0]
}
if matches.isEmpty {
fputs("unknown agent id: \(agentArg)\n", stderr)
} else {
let list = matches.sorted().joined(separator: ", ")
fputs("ambiguous agent id: \(agentArg) (matches: \(list))\n", stderr)
}
exit(1)
}
func portFor(agent: String) -> String? {
guard FileManager.default.fileExists(atPath: configURL.path) else { return nil }
guard let data = try? String(contentsOf: configURL, encoding: .utf8) else { return nil }
let key = "\(agent)_gateway"
var inPorts = false
for rawLine in data.split(separator: "\n", omittingEmptySubsequences: false) {
let line = String(rawLine)
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.isEmpty || trimmed.hasPrefix("#") { continue }
let isIndented = line.hasPrefix(" ") || line.hasPrefix("\t")
if !isIndented {
inPorts = (trimmed == "ports:" || trimmed == "ports")
continue
}
if !inPorts { continue }
if let eq = trimmed.firstIndex(of: "=") {
let k = trimmed[..<eq].trimmingCharacters(in: .whitespaces)
let v = trimmed[trimmed.index(after: eq)...].trimmingCharacters(in: .whitespaces)
if k == key { return String(v) }
} else if let colon = trimmed.firstIndex(of: ":") {
let k = trimmed[..<colon].trimmingCharacters(in: .whitespaces)
let v = trimmed[trimmed.index(after: colon)...].trimmingCharacters(in: .whitespaces)
if k == key { return String(v) }
}
}
return nil
}
func execInteractive(_ argv: [String]) -> Never {
var cArgs = argv.map { strdup($0) }
cArgs.append(nil)
guard let command = cArgs[0] else {
fputs("no command provided\n", stderr)
exit(1)
}
cArgs.withUnsafeMutableBufferPointer { argsBuffer in
guard let argv = argsBuffer.baseAddress else {
fputs("no argv provided\n", stderr)
exit(1)
}
execvp(command, argv)
}
perror("execvp")
exit(1)
}
func handleEdit(agentURL: URL) -> Never {
let env = ProcessInfo.processInfo.environment
if let editor = env["EDITOR"]?.trimmingCharacters(in: .whitespacesAndNewlines), !editor.isEmpty {
let editorArgs = editor.split(whereSeparator: { $0 == " " || $0 == "\t" }).map(String.init)
execInteractive(editorArgs + [agentURL.path])
}
fputs("$EDITOR is not set\n", stderr)
exit(1)
}
func handleMake(agent: String, agentURL: URL) -> Never {
if FileManager.default.fileExists(atPath: agentURL.path) {
fputs("agent already exists: \(agent)\n", stderr)
exit(1)
}
do {
try FileManager.default.createDirectory(at: agentURL, withIntermediateDirectories: true)
let gitkeepURL = agentURL.appendingPathComponent(".gitkeep")
_ = FileManager.default.createFile(atPath: gitkeepURL.path, contents: nil)
print("created working dir: \(agent)")
exit(0)
} catch {
fputs("failed to create working dir: \(error)\n", stderr)
exit(1)
}
}
func handleStart(agentTool: AgentTool, agentURL: URL, port: String?, extra: [String]) -> Never {
switch agentTool {
case .openclaw:
var args = ["openclaw", "gateway"]
if let port = port { args += ["--port", port] }
args += extra
setenv("OPENCLAW_HOME", agentURL.path, 1)
execInteractive(args)
case .picoclaw:
var args = ["picoclaw", "gateway"]
if let port = port { args += ["--port", port] }
args += extra
setenv("PICOCLAW_HOME", agentURL.path, 1)
execInteractive(args)
case .zeroclaw:
var args = ["zeroclaw", "--config-dir", agentURL.path, "daemon"]
if let port = port { args += ["--port", port] }
args += extra
execInteractive(args)
}
}
func handleStop(agentTool: AgentTool, agentURL: URL, extra: [String]) -> Never {
switch agentTool {
case .openclaw:
let args = ["openclaw", "gateway", "stop"] + extra
setenv("OPENCLAW_HOME", agentURL.path, 1)
execInteractive(args)
case .picoclaw:
let args = ["picoclaw", "gateway", "stop"] + extra
setenv("PICOCLAW_HOME", agentURL.path, 1)
execInteractive(args)
case .zeroclaw:
fputs("zeroclaw has no stop command yet\n", stderr)
exit(1)
}
}
func handleRemove(agent: String, agentURL: URL, extra: [String]) -> Never {
let confirmArgs: Set<String> = ["-y", "--yes"]
let unknownArgs = extra.filter { !confirmArgs.contains($0) }
if !unknownArgs.isEmpty {
fputs("usage: cmd <agent-id> remove [-y|--yes]\n", stderr)
exit(1)
}
let autoConfirm = extra.contains(where: { confirmArgs.contains($0) })
let isInteractive = isatty(fileno(stdin)) != 0
if !autoConfirm {
if !isInteractive {
fputs("non-interactive: pass -y or --yes to confirm removal\n", stderr)
exit(1)
}
fputs("Remove agent '\(agent)' at \(agentURL.path)? [y/N]: ", stderr)
let reply = readLine()?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? ""
if reply != "y" && reply != "yes" {
fputs("aborted\n", stderr)
exit(1)
}
}
do {
try FileManager.default.removeItem(at: agentURL)
print("removed working dir: \(agent)")
exit(0)
} catch {
fputs("failed to remove working dir: \(error)\n", stderr)
exit(1)
}
}
func promptMessage(extra: [String]) -> String? {
if let message = extra.last, !message.isEmpty {
return message
}
let isInteractive = isatty(fileno(stdin)) != 0
if isInteractive {
fputs("message: ", stderr)
let input = readLine()?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return input.isEmpty ? nil : input
}
let data = FileHandle.standardInput.readDataToEndOfFile()
guard !data.isEmpty else { return nil }
let input = String(data: data, encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return input.isEmpty ? nil : input
}
func handlePrompt(agentTool: AgentTool, agentURL: URL, extra: [String]) -> Never {
guard let message = promptMessage(extra: extra) else {
fputs("usage: cmd <agent-id> prompt [message]\n", stderr)
fputs("tip: omit [message] for interactive input or pipe from stdin\n", stderr)
exit(1)
}
switch agentTool {
case .openclaw:
let args = ["openclaw", "agent", "-m", message]
setenv("OPENCLAW_HOME", agentURL.path, 1)
execInteractive(args)
case .picoclaw:
let args = ["picoclaw", "agent", "-m", message]
setenv("PICOCLAW_HOME", agentURL.path, 1)
execInteractive(args)
case .zeroclaw:
let args = ["zeroclaw", "--config-dir", agentURL.path, "agent", "-m", message]
execInteractive(args)
}
}
func forwardCommand(agentTool: AgentTool, agentURL: URL, command: String, extra: [String]) -> Never {
switch agentTool {
case .openclaw:
let args = ["openclaw", command] + extra
setenv("OPENCLAW_HOME", agentURL.path, 1)
execInteractive(args)
case .picoclaw:
let args = ["picoclaw", command] + extra
setenv("PICOCLAW_HOME", agentURL.path, 1)
execInteractive(args)
case .zeroclaw:
let args = ["zeroclaw", "--config-dir", agentURL.path, command] + extra
execInteractive(args)
}
}
func requireAgentDir(agent: String, agentURL: URL) {
var isDir: ObjCBool = false
guard FileManager.default.fileExists(atPath: agentURL.path, isDirectory: &isDir), isDir.boolValue else {
fputs("unknown agent: \(agent)\n", stderr)
fputs("create it with: cmd make \(agent)\n", stderr)
exit(1)
}
}
switch parsed {
case .globalList:
listAgents()
case .globalMake(let agentName):
let agentURL = agentsURL.appendingPathComponent(agentName, isDirectory: true)
handleMake(agent: agentName, agentURL: agentURL)
case .agent(let agentArg, let command, let extra):
let agentName = resolveAgentName(agentArg, command: command)
let agentURL = agentsURL.appendingPathComponent(agentName, isDirectory: true)
let port = portFor(agent: agentName)
let kind = AgentTool.allCases.first { agentName.contains($0.rawValue) }
guard let agentTool = kind else {
fputs("unrecognized agent kind: \(agentName)\n", stderr)
exit(1)
}
requireAgentDir(agent: agentName, agentURL: agentURL)
if let agentCommand = AgentCommand(rawValue: command) {
switch agentCommand {
case .edit:
handleEdit(agentURL: agentURL)
case .prompt:
handlePrompt(agentTool: agentTool, agentURL: agentURL, extra: extra)
case .start:
handleStart(agentTool: agentTool, agentURL: agentURL, port: port, extra: extra)
case .stop:
handleStop(agentTool: agentTool, agentURL: agentURL, extra: extra)
case .remove:
handleRemove(agent: agentName, agentURL: agentURL, extra: extra)
}
} else {
forwardCommand(agentTool: agentTool, agentURL: agentURL, command: command, extra: extra)
}
}