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/core.py ADDED
@@ -0,0 +1,184 @@
1
+ """Shared plumbing: state directory, file locks, JSON files, the event log, notify hook, durations."""
2
+ import contextlib
3
+ import fcntl
4
+ import json
5
+ import os
6
+ import re
7
+ import subprocess
8
+ import time
9
+
10
+ from . import ENV, NAME, PROJECT_MARKER
11
+
12
+ DEFAULT_NOTIFY_KINDS = ('claim.conflict', 'claim.blocked', 'claim.reap', 'slot.stale', 'slot.timeout', 'slot.oom',
13
+ 'job.requeue')
14
+
15
+
16
+ def env(key, default=None):
17
+ return os.environ.get('%s_%s' % (ENV, key), default)
18
+
19
+
20
+ def state_dir():
21
+ """--state-dir / $AGENTLANES_STATE_DIR > nearest .agentlanes/ above cwd > $XDG_STATE_HOME/agentlanes."""
22
+ d = env('STATE_DIR')
23
+ if not d:
24
+ cur = os.getcwd()
25
+ while True:
26
+ if os.path.isdir(os.path.join(cur, PROJECT_MARKER)):
27
+ d = os.path.join(cur, PROJECT_MARKER)
28
+ break
29
+ parent = os.path.dirname(cur)
30
+ if parent == cur:
31
+ break
32
+ cur = parent
33
+ if not d:
34
+ base = os.environ.get('XDG_STATE_HOME') or os.path.expanduser('~/.local/state')
35
+ d = os.path.join(base, NAME)
36
+ d = os.path.abspath(os.path.expanduser(d))
37
+ os.makedirs(d, exist_ok=True)
38
+ return d
39
+
40
+
41
+ def path(*parts):
42
+ p = os.path.join(state_dir(), *parts)
43
+ os.makedirs(os.path.dirname(p), exist_ok=True)
44
+ return p
45
+
46
+
47
+ @contextlib.contextmanager
48
+ def locked(target):
49
+ """Exclusive flock on TARGET.lock for the duration of the block (data files are replaced atomically)."""
50
+ with open(target + '.lock', 'a') as lk:
51
+ fcntl.flock(lk, fcntl.LOCK_EX)
52
+ try:
53
+ yield
54
+ finally:
55
+ fcntl.flock(lk, fcntl.LOCK_UN)
56
+
57
+
58
+ def load_json(p, default):
59
+ try:
60
+ with open(p, encoding='utf-8') as fh:
61
+ return json.load(fh)
62
+ except (OSError, ValueError):
63
+ return default
64
+
65
+
66
+ def save_json(p, obj):
67
+ tmp = '%s.%d.tmp' % (p, os.getpid())
68
+ with open(tmp, 'w', encoding='utf-8') as fh:
69
+ json.dump(obj, fh, ensure_ascii=False, indent=1)
70
+ fh.flush()
71
+ os.fsync(fh.fileno())
72
+ os.replace(tmp, p)
73
+
74
+
75
+ def config():
76
+ c = load_json(os.path.join(state_dir(), 'config.json'), {})
77
+ return c if isinstance(c, dict) else {}
78
+
79
+
80
+ def parse_age(s):
81
+ """'90m' / '2h' / '1d' / '300' (seconds) -> seconds."""
82
+ m = re.fullmatch(r'(\d+(?:\.\d+)?)([smhd]?)', str(s).strip())
83
+ if not m:
84
+ raise ValueError('bad duration: %s' % s)
85
+ return float(m.group(1)) * {'': 1, 's': 1, 'm': 60, 'h': 3600, 'd': 86400}[m.group(2)]
86
+
87
+
88
+ def hm(t):
89
+ return time.strftime('%H:%M:%S', time.localtime(t))
90
+
91
+
92
+ def dur(s):
93
+ if s is None:
94
+ return '-'
95
+ s = int(s)
96
+ if s < 60:
97
+ return '%ds' % s
98
+ if s < 3600:
99
+ return '%dm' % (s // 60)
100
+ if s < 86400:
101
+ return '%dh%02d' % (s // 3600, s % 3600 // 60)
102
+ return '%dd%02dh' % (s // 86400, s % 86400 // 3600)
103
+
104
+
105
+ # ------------------------------------------------------------------ event log
106
+
107
+ def events_file():
108
+ return path('events.jsonl')
109
+
110
+
111
+ def emit(kind, **fields):
112
+ """Append one event to the log. Never raises: coordination must not break the caller. Returns the record or None."""
113
+ try:
114
+ rec = {'t': round(time.time(), 3), 'kind': str(kind)}
115
+ rec.update({k: v for k, v in fields.items() if v is not None and v != ''})
116
+ line = json.dumps(rec, ensure_ascii=False, default=str) + '\n'
117
+ ev = events_file()
118
+ max_bytes = int(env('EVENTS_MAX_BYTES', 4 << 20))
119
+ with locked(ev):
120
+ try:
121
+ if os.path.getsize(ev) > max_bytes:
122
+ os.replace(ev, ev + '.1')
123
+ except OSError:
124
+ pass
125
+ with open(ev, 'a', encoding='utf-8') as fh:
126
+ fh.write(line)
127
+ _notify(rec)
128
+ return rec
129
+ except Exception:
130
+ return None
131
+
132
+
133
+ def _notify(rec):
134
+ """Run the user's notify command (event JSON on stdin) for selected kinds. Fire and forget."""
135
+ cfg = config()
136
+ cmd = env('NOTIFY_CMD') or cfg.get('notify_cmd')
137
+ if not cmd:
138
+ return
139
+ kinds = env('NOTIFY_KINDS')
140
+ kinds = kinds.split(',') if kinds else cfg.get('notify_kinds', DEFAULT_NOTIFY_KINDS)
141
+ if not any(rec['kind'].startswith(k.strip()) for k in kinds if k.strip()):
142
+ return
143
+ try:
144
+ p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
145
+ stderr=subprocess.DEVNULL, start_new_session=True)
146
+ p.stdin.write(json.dumps(rec, ensure_ascii=False).encode())
147
+ p.stdin.close()
148
+ except Exception:
149
+ pass
150
+
151
+
152
+ def read_events(since=None, kind=None, by=None):
153
+ ev = events_file()
154
+ for p in (ev + '.1', ev):
155
+ try:
156
+ fh = open(p, encoding='utf-8')
157
+ except OSError:
158
+ continue
159
+ with fh:
160
+ for line in fh:
161
+ try:
162
+ e = json.loads(line)
163
+ except ValueError:
164
+ continue
165
+ if since and e.get('t', 0) < since:
166
+ continue
167
+ if kind and not str(e.get('kind', '')).startswith(kind):
168
+ continue
169
+ if by and e.get('by') != by:
170
+ continue
171
+ yield e
172
+
173
+
174
+ def fmt_event(e):
175
+ t = time.strftime('%m-%d %H:%M:%S', time.localtime(e.get('t', 0)))
176
+ extra = {k: v for k, v in e.items() if k not in ('t', 'kind', 'by', 'topic', 'msg')}
177
+ s = '%s %-16s %-14s' % (t, e.get('kind', ''), str(e.get('by', '-'))[:14])
178
+ if e.get('topic'):
179
+ s += ' [%s]' % e['topic']
180
+ if e.get('msg'):
181
+ s += ' ' + str(e['msg'])
182
+ if extra:
183
+ s += ' ' + ' '.join('%s=%s' % kv for kv in extra.items())
184
+ return s
agentlanes/hook.py ADDED
@@ -0,0 +1,166 @@
1
+ """Editor-tool hooks for coding agents.
2
+
3
+ `agentlanes hook claude-code` is a Claude Code PreToolUse hook: it reads the hook JSON on stdin and denies an
4
+ Edit/Write/MultiEdit/NotebookEdit whose file is covered by a claim held by a *different* agent. Paths that nobody
5
+ claimed, and paths claimed by this same agent, pass through untouched (no output = normal permission flow).
6
+ A claim counts as "mine" when its agent pid is this session's agent process, or its `by` equals $AGENTLANES_AGENT.
7
+
8
+ `agentlanes hook codex` does the same for Codex PreToolUse on apply_patch (file paths are read from the patch).
9
+ `agentlanes hook cursor` does the same for Cursor preToolUse (experimental; Cursor expects an explicit answer).
10
+
11
+ Fail-open by default: if the hook itself cannot work (bad input, unreadable or corrupt state), the edit is allowed,
12
+ because a coordination tool must not stop all work when it breaks. With $AGENTLANES_STRICT=1 those cases deny the
13
+ edit with a message that says what is broken. Note that if the `agentlanes` command is missing from PATH, the hook
14
+ never runs at all and the agent's harness decides; `agentlanes init --claude-code --strict` writes a hook command
15
+ that denies in that case too.
16
+ """
17
+ import json
18
+ import os
19
+ import re
20
+ import sys
21
+
22
+ from . import claims, core, procs
23
+
24
+ STRICT_HINT = ('Coordination state is broken, so edits are blocked (strict mode, %s_STRICT=1). Run `%s doctor` '
25
+ 'to see why. A human can unset %s_STRICT to fall back to fail-open.')
26
+
27
+
28
+ def strict():
29
+ return (core.env('STRICT') or '').strip().lower() not in ('', '0', 'false', 'no', 'off')
30
+
31
+
32
+ def _mine(c, my_pid, my_name):
33
+ if my_pid and c.get('apid') == my_pid:
34
+ return True
35
+ if my_pid and c.get('pid') == my_pid:
36
+ return True
37
+ return bool(my_name) and c.get('by') == my_name
38
+
39
+
40
+ def _check_state():
41
+ """Raise if the state directory or claims.json cannot be trusted (used in strict mode only)."""
42
+ f = claims.claims_file()
43
+ if os.path.exists(f):
44
+ with open(f, encoding='utf-8') as fh:
45
+ d = json.load(fh) # ValueError on a corrupt file
46
+ if not isinstance(d, dict):
47
+ raise ValueError('%s is not a JSON object' % f)
48
+ if not os.access(os.path.dirname(f), os.W_OK):
49
+ raise OSError('state directory %s is not writable' % os.path.dirname(f))
50
+
51
+
52
+ def blocking_claim(targets, tool=None):
53
+ """Return a deny reason if any of TARGETS is covered by another agent's claim, else None."""
54
+ my_pid, _ = procs.agent_self()
55
+ my_name = core.env('AGENT')
56
+ for target in targets:
57
+ hits = [(k, c, q) for k, c, q in claims.holders_of(target) if not _mine(c, my_pid, my_name)]
58
+ if not hits:
59
+ continue
60
+ k, c, q = hits[0]
61
+ core.emit('claim.blocked', by=my_name or ('agent-%s' % my_pid if my_pid else None), topic=k,
62
+ holder=c['by'], path=target, tool=tool)
63
+ return ('%s is claimed by %s (claim "%s": %s, since %s). Do not edit it. Pick other work, or ask that agent '
64
+ 'to release it; check with `%s who %s`.' % (q, c['by'], k, c.get('desc', ''), core.hm(c['since']),
65
+ core.NAME, target))
66
+ return None
67
+
68
+
69
+ def _abs(p, cwd):
70
+ p = os.path.expanduser(p.strip())
71
+ return p if os.path.isabs(p) else os.path.join(cwd or os.getcwd(), p)
72
+
73
+
74
+ PATCH_FILE_RE = re.compile(r'^\*\*\* (?:Add|Update|Delete) File: (.+?)\s*$|^\*\*\* Move to: (.+?)\s*$', re.M)
75
+
76
+
77
+ def patch_paths(patch):
78
+ """File paths named in a Codex apply_patch body (`*** Update File: x`, `*** Move to: y`, ...)."""
79
+ return [a or b for a, b in PATCH_FILE_RE.findall(patch or '')]
80
+
81
+
82
+ def targets_of(data):
83
+ ti = data.get('tool_input') or {}
84
+ if not isinstance(ti, dict):
85
+ return []
86
+ cwd = data.get('cwd')
87
+ out = []
88
+ for key in ('file_path', 'notebook_path', 'path', 'target_file', 'filePath'):
89
+ v = ti.get(key)
90
+ if isinstance(v, str) and v.strip():
91
+ out.append(_abs(v, cwd))
92
+ if data.get('tool_name') in ('apply_patch', 'Edit', 'Write') or '*** Begin Patch' in str(ti.get('command', '')):
93
+ out += [_abs(p, cwd) for p in patch_paths(str(ti.get('command') or ti.get('input') or ''))]
94
+ return list(dict.fromkeys(out))
95
+
96
+
97
+ def decide(stdin):
98
+ """(reason_or_None, tool). Raises only in strict mode."""
99
+ try:
100
+ data = json.load(stdin)
101
+ if not isinstance(data, dict):
102
+ raise ValueError('hook input is not a JSON object')
103
+ except ValueError:
104
+ if strict():
105
+ raise
106
+ return None, None # never break the agent on malformed input
107
+ targets = targets_of(data)
108
+ if not targets:
109
+ return None, data.get('tool_name')
110
+ if strict():
111
+ _check_state()
112
+ try:
113
+ return blocking_claim(targets, data.get('tool_name')), data.get('tool_name')
114
+ except Exception:
115
+ if strict():
116
+ raise
117
+ return None, data.get('tool_name')
118
+
119
+
120
+ def _run(stdin, emit_deny, emit_allow=None, emit_error=None):
121
+ try:
122
+ reason, _ = decide(stdin)
123
+ except Exception as e:
124
+ msg = STRICT_HINT % (core.ENV, core.NAME, core.ENV) + ' Error: %s: %s' % (type(e).__name__, e)
125
+ (emit_error or emit_deny)(msg)
126
+ return 0
127
+ if reason:
128
+ emit_deny(reason)
129
+ elif emit_allow:
130
+ emit_allow()
131
+ return 0
132
+
133
+
134
+ def _pretool_deny(out):
135
+ def f(reason):
136
+ json.dump({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'deny',
137
+ 'permissionDecisionReason': reason}}, out)
138
+ out.write('\n')
139
+ return f
140
+
141
+
142
+ def claude_code(stdin=None, out=None):
143
+ """Claude Code PreToolUse. No output = no opinion (normal permission flow)."""
144
+ out = out or sys.stdout
145
+ return _run(stdin or sys.stdin, _pretool_deny(out))
146
+
147
+
148
+ def codex(stdin=None, out=None):
149
+ """Codex PreToolUse (apply_patch / Edit / Write matchers). Same JSON answer as Claude Code."""
150
+ out = out or sys.stdout
151
+ return _run(stdin or sys.stdin, _pretool_deny(out))
152
+
153
+
154
+ def cursor(stdin=None, out=None):
155
+ """Cursor preToolUse (matcher Write). Cursor treats empty output as invalid, so always answer."""
156
+ out = out or sys.stdout
157
+
158
+ def answer(obj):
159
+ json.dump(obj, out)
160
+ out.write('\n')
161
+ return _run(stdin or sys.stdin,
162
+ lambda reason: answer({'permission': 'deny', 'agent_message': reason, 'user_message': reason}),
163
+ lambda: answer({'permission': 'allow'}))
164
+
165
+
166
+ ADAPTERS = {'claude-code': claude_code, 'codex': codex, 'cursor': cursor}
agentlanes/jobs.py ADDED
@@ -0,0 +1,126 @@
1
+ """Jobs: a small shared work queue. Agents add work, take the next item, and mark it done.
2
+
3
+ A taken job is tied to the taker's process (--pid, default: the enclosing agent). If that process dies the job
4
+ goes back to the queue (event job.requeue), so work is never lost with a crashed agent.
5
+ State: <state>/jobs.json under flock.
6
+ """
7
+ import json
8
+ import time
9
+
10
+ from . import core, procs
11
+
12
+
13
+ def jobs_file():
14
+ return core.path('jobs.json')
15
+
16
+
17
+ def _load():
18
+ q = core.load_json(jobs_file(), {})
19
+ if not isinstance(q, dict) or 'items' not in q:
20
+ q = {'next': 1, 'items': []}
21
+ events = []
22
+ for j in q['items']:
23
+ if j['state'] == 'taken' and j.get('pid') and not procs.same_process(j['pid'], j.get('pstart')):
24
+ events.append(('job.requeue', dict(by=j.get('taken_by'), topic='#%d' % j['id'], msg=j['title'])))
25
+ j.update(state='waiting', requeued=j.get('requeued', 0) + 1)
26
+ for k in ('pid', 'pstart', 'taken_by', 'taken_at'):
27
+ j.pop(k, None)
28
+ return q, events
29
+
30
+
31
+ def _locked(fn):
32
+ with core.locked(jobs_file()):
33
+ q, events = _load()
34
+ res, changed = fn(q)
35
+ if changed or events:
36
+ core.save_json(jobs_file(), q)
37
+ for kind, kw in events:
38
+ core.emit(kind, **kw)
39
+ return res
40
+
41
+
42
+ def _waiting(q):
43
+ return sorted((j for j in q['items'] if j['state'] == 'waiting'), key=lambda j: (j['prio'], j['id']))
44
+
45
+
46
+ def add(title, prio=50, note=None, by=None, out=print):
47
+ by = by or procs.default_by()
48
+
49
+ def fn(q):
50
+ j = {'id': q['next'], 'title': title, 'prio': prio, 'note': note, 'state': 'waiting', 'added': time.time(),
51
+ 'by': by}
52
+ q['next'] += 1
53
+ q['items'].append(j)
54
+ return j, True
55
+ j = _locked(fn)
56
+ core.emit('job.add', by=by, topic='#%d' % j['id'], msg=title, prio=prio)
57
+ out('queued #%d' % j['id'])
58
+ return 0
59
+
60
+
61
+ def take(job_id=None, by=None, pid='self', out=print):
62
+ by = by or procs.default_by()
63
+ lease_pid = None
64
+ if pid and pid != 'none':
65
+ from .claims import resolve_pid
66
+ lease_pid, err = resolve_pid(pid)
67
+ if err:
68
+ out(err)
69
+ return 2
70
+
71
+ def fn(q):
72
+ cand = [j for j in _waiting(q) if job_id is None or j['id'] == job_id]
73
+ if not cand:
74
+ return None, False
75
+ j = cand[0]
76
+ j.update(state='taken', taken_by=by, taken_at=time.time())
77
+ if lease_pid:
78
+ j.update(pid=lease_pid, pstart=procs.start_token(lease_pid))
79
+ return dict(j), True
80
+ j = _locked(fn)
81
+ if not j:
82
+ out('nothing to take')
83
+ return 1
84
+ core.emit('job.take', by=by, topic='#%d' % j['id'], msg=j['title'])
85
+ out('took #%d: %s' % (j['id'], j['title']))
86
+ return 0
87
+
88
+
89
+ def finish(job_id, state, by=None, text=None, out=print):
90
+ """state: done | dropped."""
91
+ by = by or procs.default_by()
92
+
93
+ def fn(q):
94
+ j = next((x for x in q['items'] if x['id'] == job_id), None)
95
+ if not j or j['state'] in ('done', 'dropped'):
96
+ return None, False
97
+ j.update(state=state, finished_by=by, finished_at=time.time(), result=text)
98
+ j.pop('pid', None)
99
+ return dict(j), True
100
+ j = _locked(fn)
101
+ if not j:
102
+ out('no open job #%d' % job_id)
103
+ return 1
104
+ core.emit('job.' + ('done' if state == 'done' else 'drop'), by=by, topic='#%d' % job_id, msg=text or j['title'])
105
+ out('%s #%d' % (state, job_id))
106
+ return 0
107
+
108
+
109
+ def items(include_all=False):
110
+ q = _locked(lambda q: (q, False))
111
+ its = q['items'] if include_all else [j for j in q['items'] if j['state'] in ('waiting', 'taken')]
112
+ order = {'taken': 0, 'waiting': 1, 'done': 2, 'dropped': 3}
113
+ return sorted(its, key=lambda j: (order.get(j['state'], 9), j['prio'], j['id']))
114
+
115
+
116
+ def cmd_list(include_all=False, as_json=False, out=print):
117
+ its = items(include_all)
118
+ if as_json:
119
+ out(json.dumps(its, ensure_ascii=False, indent=1))
120
+ return 0
121
+ if not its:
122
+ out('queue empty')
123
+ for j in its:
124
+ who = ' (%s)' % j.get('taken_by') if j['state'] == 'taken' else ''
125
+ out('#%-4d p%-3d %-8s %s%s' % (j['id'], j['prio'], j['state'], j['title'], who))
126
+ return 0