agentlanes-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agentlanes/__init__.py +10 -0
- agentlanes/__main__.py +3 -0
- agentlanes/claims.py +215 -0
- agentlanes/cli.py +323 -0
- agentlanes/core.py +184 -0
- agentlanes/hook.py +166 -0
- agentlanes/jobs.py +126 -0
- agentlanes/landlock.py +257 -0
- agentlanes/onboard.py +364 -0
- agentlanes/procs.py +255 -0
- agentlanes/run.py +201 -0
- agentlanes/slots.py +253 -0
- agentlanes_cli-0.1.0.dist-info/METADATA +323 -0
- agentlanes_cli-0.1.0.dist-info/RECORD +18 -0
- agentlanes_cli-0.1.0.dist-info/WHEEL +5 -0
- agentlanes_cli-0.1.0.dist-info/entry_points.txt +2 -0
- agentlanes_cli-0.1.0.dist-info/licenses/LICENSE +202 -0
- agentlanes_cli-0.1.0.dist-info/top_level.txt +1 -0
agentlanes/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Coordination primitives for several AI coding agents sharing one machine.
|
|
2
|
+
|
|
3
|
+
Rename the whole tool by changing NAME (and the two lines marked in pyproject.toml):
|
|
4
|
+
the CLI prog name, environment-variable prefix, state directory and project marker all derive from it.
|
|
5
|
+
"""
|
|
6
|
+
NAME = 'agentlanes'
|
|
7
|
+
__version__ = '0.1.0'
|
|
8
|
+
|
|
9
|
+
ENV = NAME.upper() # AGENTLANES_STATE_DIR, AGENTLANES_AGENT, ...
|
|
10
|
+
PROJECT_MARKER = '.' + NAME # a directory named .agentlanes makes a per-project state dir
|
agentlanes/__main__.py
ADDED
agentlanes/claims.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Claims: named work leases with optional path guards.
|
|
2
|
+
|
|
3
|
+
A claim says "agent X is working on TOPIC (and these paths) until T". With --pid it is a lease: it disappears
|
|
4
|
+
as soon as that process exits, so a crashed agent never blocks the others. Overlapping path claims are refused
|
|
5
|
+
unless --share is given. State: <state>/claims.json, guarded by flock; every change goes to the event log.
|
|
6
|
+
"""
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
from . import core, procs
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def claims_file():
|
|
15
|
+
return core.path('claims.json')
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def norm(p):
|
|
19
|
+
return os.path.realpath(os.path.expanduser(p.strip())).rstrip('/') or '/'
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def overlaps(a, b):
|
|
23
|
+
return a == b or a.startswith(b.rstrip('/') + '/') or b.startswith(a.rstrip('/') + '/')
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _dead(c):
|
|
27
|
+
return bool(c.get('pid')) and not procs.same_process(c['pid'], c.get('pstart'))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _split(d):
|
|
31
|
+
now = time.time()
|
|
32
|
+
live, dropped = {}, {}
|
|
33
|
+
for k, c in d.items():
|
|
34
|
+
if not isinstance(c, dict):
|
|
35
|
+
continue
|
|
36
|
+
if c.get('until', 0) <= now:
|
|
37
|
+
dropped[k] = (c, 'expire')
|
|
38
|
+
elif _dead(c):
|
|
39
|
+
dropped[k] = (c, 'reap')
|
|
40
|
+
else:
|
|
41
|
+
live[k] = c
|
|
42
|
+
return live, dropped
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Store:
|
|
46
|
+
"""with Store() as s: s.claims is the live dict; changes are saved and events emitted on exit."""
|
|
47
|
+
|
|
48
|
+
def __enter__(self):
|
|
49
|
+
self.file = claims_file()
|
|
50
|
+
self._lock = core.locked(self.file)
|
|
51
|
+
self._lock.__enter__()
|
|
52
|
+
raw = core.load_json(self.file, {})
|
|
53
|
+
self.claims, self.dropped = _split(raw if isinstance(raw, dict) else {})
|
|
54
|
+
self.changed = bool(self.dropped)
|
|
55
|
+
self.events = [('claim.' + why, dict(by=c.get('by'), topic=k, msg=c.get('desc', '')[:120], pid=c.get('pid')))
|
|
56
|
+
for k, (c, why) in self.dropped.items()]
|
|
57
|
+
return self
|
|
58
|
+
|
|
59
|
+
def __exit__(self, *exc):
|
|
60
|
+
try:
|
|
61
|
+
if self.changed and exc[0] is None:
|
|
62
|
+
core.save_json(self.file, self.claims)
|
|
63
|
+
finally:
|
|
64
|
+
self._lock.__exit__(*exc)
|
|
65
|
+
for kind, kw in self.events:
|
|
66
|
+
core.emit(kind, **kw)
|
|
67
|
+
return False
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def snapshot():
|
|
71
|
+
"""Live claims without taking the lock for long (read-only helpers: status, hook, agents)."""
|
|
72
|
+
with Store() as s:
|
|
73
|
+
return dict(s.claims)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def holders_of(path, claims=None):
|
|
77
|
+
p = norm(path)
|
|
78
|
+
claims = snapshot() if claims is None else claims
|
|
79
|
+
return [(k, c, q) for k, c in claims.items() for q in c.get('paths', []) if overlaps(p, q)]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def resolve_pid(spec):
|
|
83
|
+
"""'self' -> enclosing agent pid; number -> that pid. Returns (pid, error)."""
|
|
84
|
+
if spec == 'self':
|
|
85
|
+
pid, _ = procs.agent_self()
|
|
86
|
+
if not pid:
|
|
87
|
+
return None, ('--pid self: no coding-agent process found above this shell; pass --pid PID '
|
|
88
|
+
'or set %s_AGENT_PID' % core.ENV)
|
|
89
|
+
return pid, None
|
|
90
|
+
try:
|
|
91
|
+
pid = int(spec)
|
|
92
|
+
except ValueError:
|
|
93
|
+
return None, 'bad --pid: %s' % spec
|
|
94
|
+
if not procs.pid_alive(pid):
|
|
95
|
+
return None, 'no such process: %s' % spec
|
|
96
|
+
return pid, None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def add(topic, by, desc='', ttl_min=120, pid=None, paths=(), share=False, renew=False, out=print):
|
|
100
|
+
"""Returns exit code: 0 claimed, 1 held/conflict, 2 usage error."""
|
|
101
|
+
lease_pid = None
|
|
102
|
+
if pid:
|
|
103
|
+
lease_pid, err = resolve_pid(pid)
|
|
104
|
+
if err:
|
|
105
|
+
out(err)
|
|
106
|
+
return 2
|
|
107
|
+
with Store() as s:
|
|
108
|
+
cur = s.claims.get(topic)
|
|
109
|
+
if cur and cur['by'] != by:
|
|
110
|
+
out('HELD by %s since %s: %s' % (cur['by'], core.hm(cur['since']), cur.get('desc', '')))
|
|
111
|
+
s.events.append(('claim.conflict', dict(by=by, topic=topic, holder=cur['by'])))
|
|
112
|
+
return 1
|
|
113
|
+
if renew and not cur:
|
|
114
|
+
out('not held by you')
|
|
115
|
+
return 1
|
|
116
|
+
paths = [norm(p) for p in paths if p.strip()] or (cur or {}).get('paths', [])
|
|
117
|
+
if paths and not share:
|
|
118
|
+
for k, c in s.claims.items():
|
|
119
|
+
if k == topic or c.get('by') == by:
|
|
120
|
+
continue
|
|
121
|
+
for p in paths:
|
|
122
|
+
for q in c.get('paths', []):
|
|
123
|
+
if overlaps(p, q):
|
|
124
|
+
out('PATH HELD by %s (%s, since %s): %s -- use --share to work there anyway'
|
|
125
|
+
% (c['by'], k, core.hm(c['since']), q))
|
|
126
|
+
s.events.append(('claim.conflict', dict(by=by, topic=topic, holder=c['by'],
|
|
127
|
+
holder_topic=k, path=q)))
|
|
128
|
+
return 1
|
|
129
|
+
now = time.time()
|
|
130
|
+
n = dict(cur or {})
|
|
131
|
+
n.update(by=by, desc=desc or (cur or {}).get('desc', ''), since=(cur or {}).get('since', now),
|
|
132
|
+
until=now + ttl_min * 60)
|
|
133
|
+
if paths:
|
|
134
|
+
n['paths'] = paths
|
|
135
|
+
if lease_pid:
|
|
136
|
+
n['pid'], n['pstart'] = lease_pid, procs.start_token(lease_pid)
|
|
137
|
+
apid, kind = procs.agent_self()
|
|
138
|
+
if apid:
|
|
139
|
+
n['apid'], n['agent'] = apid, kind
|
|
140
|
+
sid = core.env('SESSION')
|
|
141
|
+
if sid:
|
|
142
|
+
n['sid'] = sid
|
|
143
|
+
s.claims[topic] = n
|
|
144
|
+
s.changed = True
|
|
145
|
+
s.events.append(('claim.renew' if cur else 'claim.add',
|
|
146
|
+
dict(by=by, topic=topic, msg=n['desc'][:120], ttl=ttl_min, pid=n.get('pid'),
|
|
147
|
+
paths=','.join(paths) or None)))
|
|
148
|
+
out('claimed %s' % topic)
|
|
149
|
+
return 0
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def release(topic, by=None, out=print):
|
|
153
|
+
with Store() as s:
|
|
154
|
+
c = s.claims.get(topic)
|
|
155
|
+
if c and (not by or c['by'] == by):
|
|
156
|
+
del s.claims[topic]
|
|
157
|
+
s.changed = True
|
|
158
|
+
s.events.append(('claim.done', dict(by=c['by'], topic=topic, held_s=int(time.time() - c['since']))))
|
|
159
|
+
out('released %s' % topic)
|
|
160
|
+
return 0
|
|
161
|
+
out('not held by you' if c else 'not held')
|
|
162
|
+
return 1
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def fmt(k, c):
|
|
166
|
+
extra = ''
|
|
167
|
+
if c.get('paths'):
|
|
168
|
+
extra += ' [paths: %s]' % ', '.join(c['paths'])
|
|
169
|
+
if c.get('pid'):
|
|
170
|
+
extra += ' [lease pid %s]' % c['pid']
|
|
171
|
+
return '%s -- %s since %s, %s left: %s%s' % (k, c['by'], core.hm(c['since']), core.dur(c['until'] - time.time()),
|
|
172
|
+
c.get('desc', ''), extra)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def cmd_list(as_json=False, out=print):
|
|
176
|
+
with Store() as s:
|
|
177
|
+
d = dict(s.claims)
|
|
178
|
+
if as_json:
|
|
179
|
+
out(json.dumps(d, ensure_ascii=False, indent=1))
|
|
180
|
+
elif not d:
|
|
181
|
+
out('no active claims')
|
|
182
|
+
else:
|
|
183
|
+
for k, c in sorted(d.items(), key=lambda x: x[1]['since']):
|
|
184
|
+
out(fmt(k, c))
|
|
185
|
+
return 0
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def cmd_check(topic, out=print):
|
|
189
|
+
c = snapshot().get(topic)
|
|
190
|
+
if c:
|
|
191
|
+
out('HELD by %s: %s' % (c['by'], c.get('desc', '')))
|
|
192
|
+
return 1
|
|
193
|
+
out('free')
|
|
194
|
+
return 0
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def cmd_who(paths, out=print):
|
|
198
|
+
d = snapshot()
|
|
199
|
+
rc = 0
|
|
200
|
+
for p in paths:
|
|
201
|
+
hits = holders_of(p, d)
|
|
202
|
+
for k, c, q in hits:
|
|
203
|
+
out('HELD by %s (%s, since %s): %s -- %s' % (c['by'], k, core.hm(c['since']), q, c.get('desc', '')))
|
|
204
|
+
if hits:
|
|
205
|
+
rc = 1
|
|
206
|
+
else:
|
|
207
|
+
out('free: %s' % norm(p))
|
|
208
|
+
return rc
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def cmd_reap(out=print):
|
|
212
|
+
with Store() as s:
|
|
213
|
+
n = sum(1 for _, why in s.dropped.values() if why == 'reap')
|
|
214
|
+
out('reaped %d dead lease(s), expired %d' % (n, len(s.dropped) - n))
|
|
215
|
+
return 0
|
agentlanes/cli.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"""Command-line interface. Exit codes: 0 ok, 1 held/conflict/not found, 2 usage, 75 slot timeout, 124 wait timeout."""
|
|
2
|
+
import argparse
|
|
3
|
+
import collections
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from . import NAME, __version__, claims, core, hook, jobs, onboard, procs, slots
|
|
10
|
+
|
|
11
|
+
USAGE = """{n} {v} -- coordination for several coding agents on one machine
|
|
12
|
+
|
|
13
|
+
{n} claim TOPIC [--desc TEXT] [--paths a,b] [--pid self|PID] [--ttl MIN] [--share] [--by WHO]
|
|
14
|
+
{n} release TOPIC [--by WHO] {n} renew TOPIC [--ttl MIN]
|
|
15
|
+
{n} who PATH... which claim covers these paths (exit 1 if any)
|
|
16
|
+
{n} check TOPIC | list [--json] | reap
|
|
17
|
+
{n} slot NAME N [--wait SEC] [--mem-free MB] [--max-mem MB] -- COMMAND...
|
|
18
|
+
{n} slots [NAME] [--json] holders, stale holders, waiters
|
|
19
|
+
{n} events emit KIND [--topic T] [--msg TEXT] [key=value...] | tail [-n N] [--kind K] [-f] | stats | wait --kind K
|
|
20
|
+
{n} jobs add TITLE [--prio N] | list [--all] | take [ID] | done ID [--result T] | drop ID [--why T]
|
|
21
|
+
{n} agents [--all] [--json] running coding-agent processes
|
|
22
|
+
{n} status one screen: agents, claims, slots, jobs, recent events
|
|
23
|
+
{n} init [--claude-code [--strict]] [--agents-md] [--claude-md] [--cursor]
|
|
24
|
+
set this project up (idempotent; merges, never overwrites)
|
|
25
|
+
{n} run [--claim NAME | --write PATH]... [--allow-tmp] [--allow-common] [--no-net] [--allow-port N] -- CMD...
|
|
26
|
+
Linux: start CMD with writes confined to its lanes by the kernel (Landlock)
|
|
27
|
+
{n} doctor check PATH, state dir, flock, hooks, Landlock; prints fixes
|
|
28
|
+
{n} hook claude-code|codex|cursor PreToolUse hook for that agent (see examples/)
|
|
29
|
+
|
|
30
|
+
State: {state} (override: --state-dir or ${e}_STATE_DIR)
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _by(o):
|
|
35
|
+
return o.by or procs.default_by()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def p_claims(sub):
|
|
39
|
+
for name in ('claim', 'renew'):
|
|
40
|
+
a = sub.add_parser(name)
|
|
41
|
+
a.add_argument('topic')
|
|
42
|
+
a.add_argument('--by')
|
|
43
|
+
a.add_argument('--desc', default='')
|
|
44
|
+
a.add_argument('--ttl', type=int, default=120, help='minutes (default 120)')
|
|
45
|
+
a.add_argument('--pid', help="'self' (enclosing agent) or a pid: claim dies with that process")
|
|
46
|
+
a.add_argument('--paths', default='', help='comma-separated files/dirs')
|
|
47
|
+
a.add_argument('--share', action='store_true')
|
|
48
|
+
a = sub.add_parser('release')
|
|
49
|
+
a.add_argument('topic')
|
|
50
|
+
a.add_argument('--by')
|
|
51
|
+
a.add_argument('--force', action='store_true', help='release even if held by someone else')
|
|
52
|
+
a = sub.add_parser('who')
|
|
53
|
+
a.add_argument('paths', nargs='+')
|
|
54
|
+
a = sub.add_parser('check')
|
|
55
|
+
a.add_argument('topic')
|
|
56
|
+
a = sub.add_parser('list')
|
|
57
|
+
a.add_argument('--json', action='store_true')
|
|
58
|
+
sub.add_parser('reap')
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def p_events():
|
|
62
|
+
a = argparse.ArgumentParser(prog='%s events' % NAME)
|
|
63
|
+
a.add_argument('action', choices=['emit', 'tail', 'stats', 'wait'])
|
|
64
|
+
a.add_argument('rest', nargs='*')
|
|
65
|
+
a.add_argument('--by')
|
|
66
|
+
a.add_argument('--topic')
|
|
67
|
+
a.add_argument('--msg')
|
|
68
|
+
a.add_argument('--kind')
|
|
69
|
+
a.add_argument('--since', help='e.g. 30m, 2h, 1d')
|
|
70
|
+
a.add_argument('--timeout', type=float, default=600)
|
|
71
|
+
a.add_argument('-n', type=int, default=30)
|
|
72
|
+
a.add_argument('-f', '--follow', action='store_true')
|
|
73
|
+
a.add_argument('--json', action='store_true')
|
|
74
|
+
return a
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def events_cmd(o):
|
|
78
|
+
if o.action == 'emit':
|
|
79
|
+
if not o.rest:
|
|
80
|
+
print('usage: %s events emit KIND [--topic T] [--msg TEXT] [key=value ...]' % NAME, file=sys.stderr)
|
|
81
|
+
return 2
|
|
82
|
+
kv = dict(x.split('=', 1) for x in o.rest[1:] if '=' in x)
|
|
83
|
+
return 0 if core.emit(o.rest[0], by=_by(o), topic=o.topic, msg=o.msg, **kv) else 1
|
|
84
|
+
show = (lambda e: json.dumps(e, ensure_ascii=False)) if o.json else core.fmt_event
|
|
85
|
+
|
|
86
|
+
def match(e):
|
|
87
|
+
return ((not o.kind or str(e.get('kind', '')).startswith(o.kind)) and (not o.topic or e.get('topic') == o.topic)
|
|
88
|
+
and (not o.by or e.get('by') == o.by))
|
|
89
|
+
|
|
90
|
+
def follow(until=None, first_only=False):
|
|
91
|
+
ev = core.events_file()
|
|
92
|
+
pos = os.path.getsize(ev) if os.path.exists(ev) else 0
|
|
93
|
+
while until is None or time.time() < until:
|
|
94
|
+
try:
|
|
95
|
+
size = os.path.getsize(ev)
|
|
96
|
+
except OSError:
|
|
97
|
+
size = 0
|
|
98
|
+
if size < pos: # rotated
|
|
99
|
+
pos = 0
|
|
100
|
+
if size > pos:
|
|
101
|
+
with open(ev, encoding='utf-8') as fh:
|
|
102
|
+
fh.seek(pos)
|
|
103
|
+
for line in fh:
|
|
104
|
+
if not line.endswith('\n'):
|
|
105
|
+
break
|
|
106
|
+
pos += len(line.encode('utf-8'))
|
|
107
|
+
try:
|
|
108
|
+
e = json.loads(line)
|
|
109
|
+
except ValueError:
|
|
110
|
+
continue
|
|
111
|
+
if match(e):
|
|
112
|
+
print(show(e), flush=True)
|
|
113
|
+
if first_only:
|
|
114
|
+
return 0
|
|
115
|
+
time.sleep(0.2)
|
|
116
|
+
return 124
|
|
117
|
+
|
|
118
|
+
if o.action == 'wait':
|
|
119
|
+
if not o.kind:
|
|
120
|
+
print('events wait needs --kind', file=sys.stderr)
|
|
121
|
+
return 2
|
|
122
|
+
return follow(time.time() + o.timeout, first_only=True)
|
|
123
|
+
since = time.time() - core.parse_age(o.since) if o.since else None
|
|
124
|
+
if o.action == 'stats':
|
|
125
|
+
since = since or time.time() - 86400
|
|
126
|
+
kinds, actors = collections.Counter(), collections.Counter()
|
|
127
|
+
for e in core.read_events(since=since, kind=o.kind, by=o.by):
|
|
128
|
+
kinds[e.get('kind')] += 1
|
|
129
|
+
actors[e.get('by', '-')] += 1
|
|
130
|
+
if o.json:
|
|
131
|
+
print(json.dumps({'kinds': kinds, 'actors': actors}))
|
|
132
|
+
return 0
|
|
133
|
+
for k, n in kinds.most_common():
|
|
134
|
+
print('%6d %s' % (n, k))
|
|
135
|
+
print('by: ' + (', '.join('%s %d' % x for x in actors.most_common(12)) or '-'))
|
|
136
|
+
return 0
|
|
137
|
+
for e in [e for e in core.read_events(since=since) if match(e)][-o.n:]:
|
|
138
|
+
print(show(e))
|
|
139
|
+
if o.follow:
|
|
140
|
+
try:
|
|
141
|
+
follow()
|
|
142
|
+
except KeyboardInterrupt:
|
|
143
|
+
pass
|
|
144
|
+
return 0
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def p_jobs(sub):
|
|
148
|
+
a = sub.add_parser('jobs')
|
|
149
|
+
a.add_argument('action', choices=['add', 'list', 'take', 'done', 'drop'])
|
|
150
|
+
a.add_argument('arg', nargs='?')
|
|
151
|
+
a.add_argument('--by')
|
|
152
|
+
a.add_argument('--prio', type=int, default=50, help='lower runs sooner (default 50)')
|
|
153
|
+
a.add_argument('--note')
|
|
154
|
+
a.add_argument('--pid', default='self', help="lease for a taken job: 'self', a pid, or 'none'")
|
|
155
|
+
a.add_argument('--result')
|
|
156
|
+
a.add_argument('--why')
|
|
157
|
+
a.add_argument('--all', action='store_true')
|
|
158
|
+
a.add_argument('--json', action='store_true')
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def jobs_cmd(o):
|
|
162
|
+
if o.action == 'list':
|
|
163
|
+
return jobs.cmd_list(o.all, o.json)
|
|
164
|
+
if o.action == 'add':
|
|
165
|
+
if not o.arg:
|
|
166
|
+
print('usage: %s jobs add TITLE' % NAME, file=sys.stderr)
|
|
167
|
+
return 2
|
|
168
|
+
return jobs.add(o.arg, o.prio, o.note, o.by)
|
|
169
|
+
jid = int(o.arg.lstrip('#')) if o.arg else None
|
|
170
|
+
if o.action == 'take':
|
|
171
|
+
return jobs.take(jid, o.by, o.pid)
|
|
172
|
+
if jid is None:
|
|
173
|
+
print('usage: %s jobs %s ID' % (NAME, o.action), file=sys.stderr)
|
|
174
|
+
return 2
|
|
175
|
+
return jobs.finish(jid, 'done' if o.action == 'done' else 'dropped', o.by, o.result or o.why)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def agents_rows(include_sub=False):
|
|
179
|
+
rows = procs.list_agents(include_sub)
|
|
180
|
+
cl = claims.snapshot()
|
|
181
|
+
for a in rows:
|
|
182
|
+
a['claims'] = sorted(k for k, c in cl.items() if a['pid'] in (c.get('apid'), c.get('pid')))
|
|
183
|
+
return rows
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def agents_cmd(o, out=print):
|
|
187
|
+
rows = agents_rows(o.all)
|
|
188
|
+
if getattr(o, 'json', False):
|
|
189
|
+
out(json.dumps(rows, indent=1))
|
|
190
|
+
return 0
|
|
191
|
+
if not rows:
|
|
192
|
+
out('no coding-agent processes found (known: %s)' % ', '.join(sorted(procs.known_agents())))
|
|
193
|
+
return 0
|
|
194
|
+
out('%-13s %8s %7s %7s %-6s %s' % ('AGENT', 'PID', 'MEM', 'AGE', 'MODE', 'CLAIMS'))
|
|
195
|
+
for a in rows:
|
|
196
|
+
out('%-13s %8d %6dM %7s %-6s %s' % (a['kind'], a['pid'], a['mem_mb'], core.dur(a['age_s']),
|
|
197
|
+
'batch' if a['headless'] else 'chat', ','.join(a['claims']) or '-'))
|
|
198
|
+
return 0
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def status_cmd(o):
|
|
202
|
+
print('== agents')
|
|
203
|
+
agents_cmd(argparse.Namespace(all=False, json=False), out=lambda s: print(' ' + s))
|
|
204
|
+
print('== claims')
|
|
205
|
+
claims.cmd_list(out=lambda s: print(' ' + s))
|
|
206
|
+
print('== slots')
|
|
207
|
+
slots.cmd_status(out=lambda s: print(' ' + s))
|
|
208
|
+
print('== jobs')
|
|
209
|
+
jobs.cmd_list(out=lambda s: print(' ' + s))
|
|
210
|
+
print('== recent events')
|
|
211
|
+
evs = list(core.read_events(since=time.time() - 86400))[-8:]
|
|
212
|
+
for e in evs:
|
|
213
|
+
print(' ' + core.fmt_event(e))
|
|
214
|
+
if not evs:
|
|
215
|
+
print(' none in the last 24 h')
|
|
216
|
+
m = procs.mem_available_mb()
|
|
217
|
+
print('== memory available: %s' % ('%d MB' % m if m is not None else 'unknown'))
|
|
218
|
+
return 0
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def slot_cmd(argv):
|
|
222
|
+
"""slot NAME N [opts] -- CMD... (parsed by hand so CMD flags are never touched)."""
|
|
223
|
+
if '--' not in argv:
|
|
224
|
+
print('usage: %s slot NAME N [--wait SEC] [--mem-free MB] [--max-mem MB] [--by WHO] -- COMMAND...' % NAME,
|
|
225
|
+
file=sys.stderr)
|
|
226
|
+
return 2
|
|
227
|
+
i = argv.index('--')
|
|
228
|
+
head, cmd = argv[:i], argv[i + 1:]
|
|
229
|
+
a = argparse.ArgumentParser(prog='%s slot' % NAME)
|
|
230
|
+
a.add_argument('name')
|
|
231
|
+
a.add_argument('n', type=int)
|
|
232
|
+
a.add_argument('--wait', type=float, default=1800, help='seconds (default 1800); exit 75 on timeout')
|
|
233
|
+
a.add_argument('--mem-free', type=int, default=0, help='wait until this many MB are available')
|
|
234
|
+
a.add_argument('--max-mem', type=int, default=0, help='kill CMD above this many MB (systemd scope or watchdog)')
|
|
235
|
+
a.add_argument('--by')
|
|
236
|
+
o = a.parse_args(head)
|
|
237
|
+
return slots.run(o.name, o.n, cmd, o.wait, o.mem_free, o.max_mem, o.by)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def main(argv=None):
|
|
241
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
242
|
+
while argv[:1] and argv[0] in ('--state-dir', '--notify-cmd'):
|
|
243
|
+
if len(argv) < 2:
|
|
244
|
+
print('%s needs a value' % argv[0], file=sys.stderr)
|
|
245
|
+
return 2
|
|
246
|
+
key = 'STATE_DIR' if argv[0] == '--state-dir' else 'NOTIFY_CMD'
|
|
247
|
+
os.environ['%s_%s' % (core.ENV, key)] = argv[1]
|
|
248
|
+
argv = argv[2:]
|
|
249
|
+
if not argv or argv[0] in ('-h', '--help', 'help'):
|
|
250
|
+
print(USAGE.format(n=NAME, v=__version__, e=core.ENV, state=core.state_dir()))
|
|
251
|
+
return 0
|
|
252
|
+
if argv[0] in ('-V', '--version'):
|
|
253
|
+
print(NAME, __version__)
|
|
254
|
+
return 0
|
|
255
|
+
if argv[0] == 'slot':
|
|
256
|
+
return slot_cmd(argv[1:])
|
|
257
|
+
if argv[0] == 'run':
|
|
258
|
+
from . import run
|
|
259
|
+
return run.main(argv[1:])
|
|
260
|
+
if argv[0] == 'init':
|
|
261
|
+
a = argparse.ArgumentParser(prog='%s init' % NAME, description='Set up the current directory (idempotent).')
|
|
262
|
+
a.add_argument('--claude-code', action='store_true', help='merge the PreToolUse hook into .claude/settings.json')
|
|
263
|
+
a.add_argument('--strict', action='store_true', help='hook denies edits when %s is missing or broken' % NAME)
|
|
264
|
+
a.add_argument('--agents-md', action='store_true', help='append agent instructions to AGENTS.md')
|
|
265
|
+
a.add_argument('--claude-md', action='store_true', help='append agent instructions to CLAUDE.md')
|
|
266
|
+
a.add_argument('--cursor', action='store_true', help='write .cursor/rules/%s.mdc' % NAME)
|
|
267
|
+
o = a.parse_args(argv[1:])
|
|
268
|
+
return onboard.init(None, o.claude_code, o.agents_md, o.claude_md, o.cursor, o.strict)
|
|
269
|
+
if argv[0] == 'doctor':
|
|
270
|
+
return onboard.doctor()
|
|
271
|
+
if argv[0] == 'events':
|
|
272
|
+
return events_cmd(p_events().parse_intermixed_args(argv[1:]))
|
|
273
|
+
if argv[0] == 'hook':
|
|
274
|
+
fn = hook.ADAPTERS.get(argv[1] if len(argv) > 1 else '')
|
|
275
|
+
if not fn:
|
|
276
|
+
print('usage: %s hook %s' % (NAME, '|'.join(hook.ADAPTERS)), file=sys.stderr)
|
|
277
|
+
return 2
|
|
278
|
+
return fn()
|
|
279
|
+
|
|
280
|
+
ap = argparse.ArgumentParser(prog=NAME, usage=USAGE.format(n=NAME, v=__version__, e=core.ENV, state='...'))
|
|
281
|
+
sub = ap.add_subparsers(dest='cmd')
|
|
282
|
+
p_claims(sub)
|
|
283
|
+
p_jobs(sub)
|
|
284
|
+
a = sub.add_parser('slots')
|
|
285
|
+
a.add_argument('name', nargs='?')
|
|
286
|
+
a.add_argument('--json', action='store_true')
|
|
287
|
+
a = sub.add_parser('agents')
|
|
288
|
+
a.add_argument('--all', action='store_true')
|
|
289
|
+
a.add_argument('--json', action='store_true')
|
|
290
|
+
sub.add_parser('status')
|
|
291
|
+
o = ap.parse_args(argv)
|
|
292
|
+
c = o.cmd
|
|
293
|
+
if c in ('claim', 'renew'):
|
|
294
|
+
return claims.add(o.topic, _by(o), o.desc, o.ttl, o.pid, o.paths.split(','), o.share, renew=(c == 'renew'))
|
|
295
|
+
if c == 'release':
|
|
296
|
+
return claims.release(o.topic, None if o.force else _by(o))
|
|
297
|
+
if c == 'who':
|
|
298
|
+
return claims.cmd_who(o.paths)
|
|
299
|
+
if c == 'check':
|
|
300
|
+
return claims.cmd_check(o.topic)
|
|
301
|
+
if c == 'list':
|
|
302
|
+
return claims.cmd_list(o.json)
|
|
303
|
+
if c == 'reap':
|
|
304
|
+
return claims.cmd_reap()
|
|
305
|
+
if c == 'jobs':
|
|
306
|
+
return jobs_cmd(o)
|
|
307
|
+
if c == 'slots':
|
|
308
|
+
return slots.cmd_status(o.name, o.json)
|
|
309
|
+
if c == 'agents':
|
|
310
|
+
return agents_cmd(o)
|
|
311
|
+
if c == 'status':
|
|
312
|
+
return status_cmd(o)
|
|
313
|
+
ap.print_usage()
|
|
314
|
+
return 2
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def entry():
|
|
318
|
+
try:
|
|
319
|
+
sys.exit(main())
|
|
320
|
+
except KeyboardInterrupt:
|
|
321
|
+
sys.exit(130)
|
|
322
|
+
except BrokenPipeError:
|
|
323
|
+
sys.exit(0)
|