-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpm_coder.py
More file actions
3687 lines (3135 loc) · 134 KB
/
Copy pathpm_coder.py
File metadata and controls
3687 lines (3135 loc) · 134 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
r"""Local coding agent built to run unattended for days.
One agent, one host shell, MCP tools, skills, project instructions. Every
model turn -- interactive or scripted -- goes through :func:`run_turn`, which
has three failure policies and no exit condition:
* the context is full
-> summarize older history into a checkpoint and resume where we left off;
* a response outgrew --max-tokens with context to spare
-> keep what it wrote and tell it to continue;
* the endpoint could not use what the model produced (a tool call whose JSON
never parsed, or tool arguments it failed to repair until pydantic-ai's
retries ran out)
-> retry, and once that has failed twice running, retry as a
fresh user turn so the request is not byte-identical;
* anything else
-> print it, wait, and retry the same turn.
Nothing else stops the loop. There are no request limits, no wall-clock
limits, and no output caps. Values that must exist are used directly so a
logic error crashes loudly instead of being papered over.
Two things ride along inside that loop:
* loop detection -- every tool call is normalized and counted; when the
last LOOP_WINDOW calls repeat at most LOOP_MAX_DISTINCT operations, a
fake user turn tells the model to stop, and each compaction hands the
model a stats view of every call and its amount;
* sub-agents -- the `subagent` tool runs 1-5 fresh pm-coder sessions to
completion concurrently and returns one report:
how each finished, a summary of its chat, and its final answer.
"""
from __future__ import annotations
import argparse
import asyncio
import difflib
import io
import itertools
import json
import os
import random
import re
import shutil
import string
import subprocess
import sys
import tempfile
import textwrap
import threading
import time
import urllib.request
from abc import ABC, abstractmethod
from collections import Counter
from contextlib import asynccontextmanager, suppress
from dataclasses import asdict, dataclass, is_dataclass, replace
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, Literal, Mapping, Sequence, List
from xml.sax.saxutils import escape, quoteattr
from openai import AsyncOpenAI
from pydantic import BaseModel, ConfigDict, Field
from pydantic_ai import Agent, Tool, UsageLimits, capture_run_messages
from pydantic_ai.capabilities import ProcessHistory
from pydantic_ai.mcp import load_mcp_toolsets
from pydantic_ai.messages import (
BinaryContent,
ModelMessagesTypeAdapter,
ModelRequest,
ModelResponse,
TextPart,
TextPartDelta,
ThinkingPartDelta,
ToolCallPartDelta,
UserPromptPart, is_multi_modal_content, ToolReturnPart, ModelMessage, UploadedFile, ImageUrl,
)
from pydantic_ai.models import OpenAIChatCompatibleProvider, StreamedResponse
from pydantic_ai.models.openai import (
OpenAIChatModel,
OpenAIChatModelSettings,
OpenAIModelName,
)
from pydantic_ai.models.wrapper import WrapperModel
from pydantic_ai.profiles import ModelProfileSpec
from pydantic_ai.profiles.openai import OpenAIModelProfile
from pydantic_ai.providers import Provider
from pydantic_ai.providers.openai import OpenAIProvider
from pydantic_ai.settings import ModelSettings
from pydantic_ai.toolsets import CombinedToolset, FunctionToolset, WrapperToolset
from pydantic_core import to_jsonable_python
from ruamel.yaml import YAML
APP_NAME = "pm-coder"
DEFAULT_BASE_URL = "http://127.0.0.1:8080/v1"
DEFAULT_LOG_ROOT = Path("~/.pm/pm-coder").expanduser()
DEFAULT_SHELL_TIMEOUT = 240
SHELL_TERMINATE_GRACE_SECONDS = 2.0
# Sub-agents: the `subagent` tool accepts this inclusive prompt-count range.
SUBAGENT_MIN_PROMPTS = 1
SUBAGENT_MAX_PROMPTS = 5
# Loop detection: when the last LOOP_WINDOW tool calls hold at most
# LOOP_MAX_DISTINCT distinct calls, the agent is stuck. Two distinct calls
# catch the ping-pong loop (read A, grep B, read A, grep B) a small model
# falls into, which a same-call-only check would miss.
LOOP_WINDOW = 6
LOOP_MAX_DISTINCT = 2
# Seconds to wait before retrying after any failure that is not a context
# problem. One fixed delay: a week-long run has no deadline to race.
RETRY_DELAY_SECONDS = 30.0
# 0 means use the actual serving context advertised by the selected model.
DEFAULT_CONTEXT_WINDOW = 0
@dataclass(frozen=True)
class ContextLimits:
"""Conservative text budgets, in characters unless explicitly named lines.
These are tuning defaults, not tokenizer estimates or model benchmarks.
Write size is guidance; exceeding it never discards a generated edit.
"""
read_lines: int
read_columns: int
read_output_chars: int
shell_lines: int
shell_chars: int
write_chunk_chars: int
compact_tail_chars: int
compact_summary_chars: int
summary_overlap_chars: int
@property
def read_body_chars(self) -> int:
return self.read_output_chars - 2_000
# Decimal minimum context sizes: 96_000 and 98_304 both select the 96k row.
# Large contexts grow sublinearly to avoid encouraging whole-repository reads.
# read lines/cols/cap, shell lines/cap, write, tail, summary, overlap
CONTEXT_LIMITS = {
32_000: ContextLimits(128, 256, 12_000, 40, 3_000, 6_000, 16_000, 6_000, 2_000),
64_000: ContextLimits(192, 512, 20_000, 60, 5_000, 10_000, 32_000, 10_000, 4_000),
96_000: ContextLimits(256, 512, 28_000, 100, 8_000, 14_000, 48_000, 16_000, 6_000),
128_000: ContextLimits(384, 768, 36_000, 120, 10_000, 18_000, 64_000, 20_000, 6_000),
180_000: ContextLimits(512, 1024, 48_000, 160, 12_000, 24_000, 80_000, 24_000, 8_000),
230_000: ContextLimits(640, 1024, 56_000, 200, 16_000, 28_000, 96_000, 28_000, 8_000),
512_000: ContextLimits(768, 1536, 80_000, 250, 24_000, 40_000, 128_000, 32_000, 10_000),
1_000_000: ContextLimits(1024, 2048, 112_000, 300, 32_000, 56_000, 192_000, 48_000, 12_000),
}
def context_limits() -> ContextLimits:
size = active_session.context_window
tier = max(minimum for minimum in CONTEXT_LIMITS if size >= minimum)
return CONTEXT_LIMITS[tier]
# One agent.run can last all night, so the history is snapshotted mid-turn
# after a tool call, at most this often.
SNAPSHOT_SECONDS = 30.0
# Images are pruned from the stored history with a high/low watermark. While
# the history holds at most IMAGE_HIGH_WATER images nothing is touched, so
# consecutive requests differ only by appended messages and prefix caches
# keep hitting; past the watermark, all but the newest IMAGE_LOW_WATER images
# are swapped for placeholders. Swapping content -- never deleting messages --
# keeps every tool-call/tool-return pair intact, so the pruned history can
# never end in unprocessed tool calls.
IMAGE_HIGH_WATER = 32
IMAGE_LOW_WATER = 8
OMITTED = "[older image omitted]"
VISION_REMOVED = "[image removed: this endpoint does not support image input]"
MCP_CONFIG_CANDIDATES = (
".mcp.json",
"mcp.json",
"mcp_config.json",
".pi/mcp.json",
".codex/mcp.json",
)
FRONTMATTER_RE = re.compile(r"\A---\s*\r?\n(.*?)\r?\n---\s*(?:\r?\n|$)", re.DOTALL)
# Unlimited must be spelled out: UsageLimits() alone defaults to 50 requests.
NO_LIMITS = UsageLimits(request_limit=None)
# The library surface. Everything here can be imported and used without the
# CLI; anything not listed is an internal detail and may change.
__all__ = [
"DiscoveryResult",
"SessionStore",
"Settings",
"Skill",
"TurnResult",
"async_run_auto",
"async_run_auto_with_bash_machine",
"build_agent",
"build_settings",
"build_summary_agent",
"build_system_prompt",
"compact",
"discover_workspace",
"find_mcp_config",
"find_skill",
"load_skills",
"loop_alert_injector",
"make_bash_machine_tool",
"make_file_tools",
"make_shell_tool",
"make_subagent_tool",
"open_bash_machine_session",
"open_session",
"probe_endpoint",
"prompt_text",
"run_auto",
"run_auto_with_bash_machine",
"run_turn",
"select_shell",
"shell_backend",
"summarize",
"wait_for_endpoint",
]
def utc_now() -> str:
return datetime.now(UTC).isoformat()
def env_first(*names: str) -> str | None:
for name in names:
value = os.environ.get(name)
if value:
return value
return None
def env_int(name: str, default: int) -> int:
raw = os.environ.get(name)
if raw is None or not raw.strip():
return default
return int(raw)
def note(message: str) -> None:
"""Narrate to stderr. stdout carries only the turn's result."""
print(f"{APP_NAME}: {message}", file=sys.stderr, flush=True)
def atomic_write_bytes(path: Path, data: bytes) -> None:
"""Replace one file atomically after flushing its temporary peer."""
path.parent.mkdir(parents=True, exist_ok=True)
descriptor, raw_temp = tempfile.mkstemp(
prefix=f".{path.name}.", suffix=".tmp", dir=path.parent
)
temp_path = Path(raw_temp)
try:
with os.fdopen(descriptor, "wb") as handle:
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
for attempt in range(4):
try:
os.replace(temp_path, path)
break
except PermissionError:
# Windows virus scanners hold the handle for a few ms.
if attempt == 3:
raise
time.sleep(0.01 * (2**attempt))
finally:
if temp_path.exists():
temp_path.unlink()
def load_yaml(raw: str) -> Any:
yaml = YAML(typ="safe", pure=True)
yaml.allow_duplicate_keys = False
return yaml.load(raw)
# ---------------------------------------------------------------------------
# Session storage
# ---------------------------------------------------------------------------
def _is_image(x) -> bool:
return (
isinstance(x, ImageUrl)
or isinstance(x, (BinaryContent, UploadedFile))
and x.media_type.startswith("image/")
)
def count_images(messages: list[ModelMessage]) -> int:
"""Images anywhere in request content, including nested tool returns."""
def walk(x) -> int:
if _is_image(x):
return 1
if isinstance(x, Mapping):
return sum(walk(v) for v in x.values())
if isinstance(x, Sequence) and not isinstance(x, (str, bytes, bytearray)):
return sum(walk(v) for v in x)
return 0
total = 0
for msg in messages:
if not isinstance(msg, ModelRequest):
continue
for part in msg.parts:
if isinstance(part, UserPromptPart) or (
isinstance(part, ToolReturnPart) and part.tool_kind is None
):
total += walk(part.content)
return total
def _omit_older_images(
messages: list[ModelMessage], keep: int, placeholder: str = OMITTED
) -> list[ModelMessage]:
"""Swap every image but the newest ``keep`` for a placeholder."""
kept = 0
# Walk content newest -> oldest.
def prune(x):
nonlocal kept
if _is_image(x):
if kept < keep:
kept += 1
return x
return placeholder
# Tool returns can contain arbitrarily nested multimodal data.
if isinstance(x, Mapping):
rev = [(k, prune(v)) for k, v in reversed(x.items())]
return dict(reversed(rev))
if isinstance(x, Sequence) and not isinstance(x, (str, bytes, bytearray)):
return list(reversed([prune(v) for v in reversed(x)]))
return x
result = []
# Messages also need to be processed newest -> oldest.
for msg in reversed(messages):
if not isinstance(msg, ModelRequest):
result.append(msg)
continue
parts = list(msg.parts)
changed = False
for i in range(len(parts) - 1, -1, -1):
part = parts[i]
if isinstance(part, UserPromptPart):
new_content = prune(part.content)
elif isinstance(part, ToolReturnPart) and part.tool_kind is None:
new_content = prune(part.content)
else:
continue
parts[i] = replace(part, content=new_content)
changed = True
result.append(replace(msg, parts=parts) if changed else msg)
return list(reversed(result))
def keep_recent_images(messages: list[ModelMessage]) -> list[ModelMessage]:
"""High/low watermark image pruner for the history Pydantic AI stores.
Runs as a ``ProcessHistory`` capability, and Pydantic AI writes the
processed list back into the run's message history (the same list our
mid-turn snapshots persist), so this edits the stored history, not just
one outgoing request -- which is what makes the watermark stick.
While the history holds at most ``IMAGE_HIGH_WATER`` images the list is
returned untouched, so consecutive requests differ only by appended
messages and prefix caches keep hitting. Past the watermark, all but the
newest ``IMAGE_LOW_WATER`` images become placeholders -- a content swap,
never a message removal, so tool-call/tool-return pairing survives and
the history can never end in unprocessed tool calls.
"""
total = count_images(messages)
if total <= IMAGE_HIGH_WATER:
return messages
note(f"{total} images in history; keeping the newest {IMAGE_LOW_WATER}")
return _omit_older_images(messages, IMAGE_LOW_WATER)
def loop_alert_injector(session: SessionStore):
"""Build the ProcessHistory that turns a pending alert into a user turn.
The alert is appended after the newest message. At this point every tool
call is answered, so the request stays valid. It is a user turn, not a
tool retry, because a retried request resamples the same distribution.
"""
def inject(messages: list[Any]) -> list[Any]:
alert = session.pending_alert
if alert is None:
return messages
session.pending_alert = None
note("injecting user turn: " + alert.splitlines()[0])
return [*messages, ModelRequest(parts=[UserPromptPart(content=alert)])]
return inject
class SessionStore:
"""One conversation on disk as Pydantic AI model messages.
``messages.json`` is replayed verbatim into ``message_history``, so
resuming a session does not re-summarize or re-prompt anything.
"""
context_window: int
schema = "pm-coder-session.v1"
def __init__(self, path: Path, cwd: Path) -> None:
self.path = path
self.cwd = cwd.resolve()
self.turn_id = ""
self.auto_compact_cnt = 0
self.metadata_path = path / "session.json"
self.messages_path = path / "messages.json"
self.runs_path = path / "runs.jsonl"
self.path.mkdir(parents=True, exist_ok=True)
# Set by run_turn to the list Pydantic AI appends to as a turn runs,
# so a mid-turn snapshot writes the whole conversation and not just
# the fragment produced so far.
self.live_history: list[Any] | None = None
self.active_stream_path = path / "active-stream.jsonl"
self._stream_savepoint_counter = itertools.count(1)
self.last_snapshot = 0.0
# Normalized tool-call history since the last compaction: loop
# detection reads the tail, the compaction stats view reads it all.
self.tool_calls: list[str] = []
# Text the next model request gets as a fake user turn: a loop alert
# or the compaction stats view. Cleared once injected.
self.pending_alert: str | None = None
def record_tool_call(self, name: str, tool_args: dict[str, Any]) -> None:
"""Count one normalized tool call, and flag a loop when it repeats."""
key = (name + " " + json.dumps(tool_args, sort_keys=True, default=str)).casefold()
self.tool_calls.append(key)
window = self.tool_calls[-LOOP_WINDOW:]
if len(window) == LOOP_WINDOW and len(set(window)) <= LOOP_MAX_DISTINCT:
repeated = "".join(f"- {call[:200]}\n" for call in sorted(set(window)))
self.pending_alert = (
f"[loop alert] The last {LOOP_WINDOW} tool calls repeated the "
f"same {len(set(window))} operations:\n{repeated}"
"Stop this loop. State a new hypothesis, then use a different "
"tool or different arguments. Do not repeat these calls."
)
def tool_stats_report(self) -> str:
"""The compaction stats view: each call and the amount of times."""
if not self.tool_calls:
return "(no tool calls since the last checkpoint)"
counts = Counter(self.tool_calls)
lines = [f"{amount}x {call[:200]}" for call, amount in counts.most_common()]
return "tool calls since the last checkpoint (amount x call):\n" + "\n".join(lines)
@property
def run_id(self) -> str:
return self.path.name
@classmethod
def open(
cls,
cwd: Path,
run_id: str | None = None,
*,
log_root: Path = DEFAULT_LOG_ROOT,
) -> SessionStore:
root = log_root.expanduser().resolve()
root.mkdir(parents=True, exist_ok=True)
if run_id is None:
stamp = datetime.now().astimezone().strftime("%Y-%m-%d_%H-%M-%S")
cwd_id = re.sub(r"[^A-Za-z0-9._-]+", "_", str(cwd.resolve())).strip("_")
base_name = f"{stamp}_{cwd_id or 'workspace'}"
path = root / base_name
suffix = 2
while path.exists():
path = root / f"{base_name}-{suffix}"
suffix += 1
else:
if Path(run_id).name != run_id or run_id in {".", ".."}:
raise ValueError("run_id must be a single safe directory name")
path = root / run_id
store = cls(path, cwd)
if not store.metadata_path.exists():
atomic_write_bytes(
store.metadata_path,
json.dumps(
{
"schema": cls.schema,
"run_id": store.run_id,
"created_at": utc_now(),
"cwd": str(cwd.resolve()),
},
ensure_ascii=False,
indent=2,
).encode("utf-8"),
)
return store
def load_messages(self) -> list[Any]:
if not self.messages_path.exists():
return []
return ModelMessagesTypeAdapter.validate_json(self.messages_path.read_bytes())
def save_messages(self, messages: list[Any]) -> None:
atomic_write_bytes(
self.messages_path,
json.dumps(
to_jsonable_python(messages),
ensure_ascii=False,
separators=(",", ":"),
).encode("utf-8"),
)
def snapshot(self) -> None:
"""Persist the in-progress turn, at most every SNAPSHOT_SECONDS."""
if self.live_history is None:
return
now = time.monotonic()
if now - self.last_snapshot < SNAPSHOT_SECONDS:
return
self.last_snapshot = now
self.save_messages(self.live_history)
note(f"snapshot: {len(self.live_history)} messages persisted mid-turn")
def begin_stream_capture(self) -> Any:
"""Reset the main agent's rolling response-stream spool."""
handle = self.active_stream_path.open("w", encoding="utf-8", newline="\n")
handle.write(json.dumps({"started_at": utc_now()}) + "\n")
handle.flush()
return handle
def save_stream_savepoint(self) -> Path | None:
"""Copy the last streamed response before compaction discards its context."""
if not self.active_stream_path.exists():
return None
stamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
target = self.path / (
f"precompact_{stamp}_{next(self._stream_savepoint_counter):06d}.stream.jsonl"
)
shutil.copyfile(self.active_stream_path, target)
atomic_write_bytes(self.active_stream_path, b"")
return target
def clear(self) -> None:
self.save_messages([])
def append_run(self, value: dict[str, Any]) -> None:
with self.runs_path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(value, ensure_ascii=False, separators=(",", ":")))
handle.write("\n")
# The HTTP logger below sits under Pydantic AI's message layer and has no
# route to the active session, so the store is published here at open time.
active_session: SessionStore | None = None
@dataclass(init=False)
class LoggingOpenAIChatModel(OpenAIChatModel):
"""OpenAIChatModel that dumps every /chat/completions body to the session.
Logging happens below Pydantic AI's message and tool conversion, so the
files are exactly what the endpoint received: the raw bytes plus an
indented copy. Nothing here may break inference.
"""
def __init__(
self,
model_name: OpenAIModelName,
*,
provider: OpenAIChatCompatibleProvider | Provider[AsyncOpenAI],
profile: ModelProfileSpec | None = None,
settings: ModelSettings | None = None,
):
super().__init__(
model_name, provider=provider, profile=profile, settings=settings
)
self._log_counter = itertools.count(1)
# The only private API involved: AsyncOpenAI's underlying HTTP client.
hooks = self.client._client.event_hooks
hooks.setdefault("request", [])
hooks["request"].append(self._log_http_request)
async def _log_http_request(self, request: Any) -> None:
if request.method != "POST":
return
if not request.url.path.rstrip("/").endswith("/chat/completions"):
return
if active_session is None:
return
try:
raw = bytes(request.content)
payload = json.loads(raw)
dump = json.dumps(payload, ensure_ascii=False, indent=2)
sequence = next(self._log_counter)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
stem = active_session.path / f"turn_{active_session.turn_id}_ac_{active_session.auto_compact_cnt}.json"
if stem.exists():
try:
os.remove(stem)
except:
stem = stem / f"{timestamp}.json"
stem.write_text(dump, encoding="utf-8")
except Exception as exc:
note(f"prompt logger failed: {exc!r}")
# ---------------------------------------------------------------------------
# Settings
# ---------------------------------------------------------------------------
class Settings(BaseModel):
model_config = ConfigDict(extra="forbid", validate_assignment=True)
cwd: Path
base_url: str
api_key: str
model: str
mcp_config: Path | None
shell_kind: Literal["powershell", "bash"]
shell_executable: str
shell_timeout: int = Field(gt=0)
disable_thinking: bool
skill: str | None
verbose: bool
context_window: int = Field(gt=0)
enable_write: bool
def probe_endpoint(
base_url: str, api_key: str, *, timeout: float = 10.0, model: str | None = None
) -> dict[str, Any] | None:
"""Return the selected model (or first if unspecified), or None if unreachable.
llama.cpp reports ``meta.n_ctx`` (what a slot can actually fit) alongside
``n_ctx_train`` (the model's native length). The runtime budget must
respect the serving value, not the larger training figure.
"""
request = urllib.request.Request(
base_url.rstrip("/") + "/models",
headers={"Authorization": f"Bearer {api_key}"},
)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
payload = json.loads(response.read().decode("utf-8"))
except Exception as exc:
note(f"{type(exc).__name__}: {exc}; endpoint not answering at {base_url}")
return None
entries = payload["data"]
entry = next(item for item in entries if item["id"] == model) if model else entries[0]
n_ctx = entry["context_length"] if "openrouter.ai" in base_url else entry["meta"]["n_ctx"]
return {"id": entry["id"], "n_ctx": n_ctx}
def wait_for_endpoint(base_url: str, api_key: str, *, model: str | None = None) -> dict[str, Any]:
"""Block until the endpoint answers. Startup must survive a cold server."""
while True:
capabilities = probe_endpoint(base_url, api_key, model=model)
if capabilities is not None:
return capabilities
note(f"trying reconnect in {RETRY_DELAY_SECONDS:g}s...")
time.sleep(RETRY_DELAY_SECONDS)
def build_settings(
*,
cwd: str | Path | None = None,
base_url: str | None = None,
api_key: str | None = None,
model: str | None = None,
mcp_config: str | Path | None = None,
shell: str = "auto",
shell_timeout: int = DEFAULT_SHELL_TIMEOUT,
enable_thinking: bool = True,
skill: str | None = None,
verbose: bool = False,
context_window: int = DEFAULT_CONTEXT_WINDOW,
enable_write: bool = True
) -> Settings:
"""Resolve one runtime configuration, probing the endpoint if needed.
The model id and the context window are both discoverable from
``/v1/models``. When either is left to discovery this blocks until the
endpoint answers rather than starting a run against a server that is not
there yet.
"""
cwd_path = Path(cwd or os.getcwd()).expanduser().resolve()
if not cwd_path.is_dir():
raise ValueError(f"working directory does not exist: {cwd_path}")
resolved_base_url = (
base_url or env_first("LOCAL_AGENT_BASE_URL", "OPENAI_BASE_URL") or DEFAULT_BASE_URL
).rstrip("/")
resolved_api_key = (
api_key or env_first("LOCAL_AGENT_API_KEY", "OPENAI_API_KEY") or "local"
)
resolved_model = model or env_first("LOCAL_AGENT_MODEL", "OPENAI_MODEL")
capabilities: dict[str, Any] | None = None
if resolved_model is None or context_window <= 0:
capabilities = wait_for_endpoint(resolved_base_url, resolved_api_key, model=resolved_model)
if resolved_model is None:
resolved_model = capabilities["id"]
if context_window <= 0:
served = capabilities["n_ctx"]
context_window = served
backend = select_shell(shell)
resolved_mcp_config = find_mcp_config(cwd_path, mcp_config)
return Settings(
cwd=cwd_path,
base_url=resolved_base_url,
api_key=resolved_api_key,
model=resolved_model,
mcp_config=resolved_mcp_config,
shell_kind=backend.kind,
shell_executable=backend.executable,
shell_timeout=shell_timeout,
disable_thinking=not enable_thinking,
skill=skill,
verbose=verbose,
context_window=context_window,
enable_write=enable_write
)
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Local coding agent with interactive and one-shot modes."
)
parser.add_argument(
"--mode",
choices=("interactive", "auto"),
default="interactive",
help="Persistent chat session, or one prompt that runs to completion.",
)
parser.add_argument(
"--auto",
dest="mode",
action="store_const",
const="auto",
help="Shortcut for --mode auto.",
)
parser.add_argument(
"prompt",
nargs="?",
help="Prompt text in auto mode, or a path to a UTF-8 text file.",
)
parser.add_argument("--prompt-file", help="Read the auto-mode prompt from this file.")
parser.add_argument("--run-id", help="Resume this session directory under --log-root.")
parser.add_argument("--log-root", default=str(DEFAULT_LOG_ROOT))
parser.add_argument("--cwd", default=os.getcwd())
parser.add_argument("--base-url")
parser.add_argument("--api-key")
parser.add_argument("--model")
parser.add_argument("--mcp-config")
parser.add_argument(
"--shell",
choices=("auto", "powershell", "bash"),
default=os.environ.get("LOCAL_AGENT_SHELL", "auto"),
help="Host shell. auto selects PowerShell on Windows and Bash elsewhere.",
)
parser.add_argument(
"--shell-timeout",
type=int,
default=env_int("LOCAL_AGENT_SHELL_TIMEOUT", DEFAULT_SHELL_TIMEOUT),
help="Seconds allowed for one host-shell tool call.",
)
parser.add_argument(
"--skill",
help=(
"Load exactly one skill and inject its full SKILL.md into the "
"system prompt, replacing the skill index. Accepts the skill's "
"name or a path to its SKILL.md."
),
)
parser.add_argument(
"--context-window",
type=int,
default=env_int("LOCAL_AGENT_CONTEXT_WINDOW", DEFAULT_CONTEXT_WINDOW),
help=(
"Token budget used to size compaction. 0 (default) reads the "
"selected model's advertised serving context length."
),
)
parser.add_argument(
"--enable-thinking", dest="enable_thinking", action="store_true", default=True
)
parser.add_argument("--disable-thinking", dest="enable_thinking", action="store_false")
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="Print the raw model stream to stderr as it arrives.",
)
parser.add_argument("--enable-write",dest="enable_write", action="store_true", default=True,
help="Enable tools with write access to FS.")
parser.add_argument("--disable-write", dest="enable_write", action="store_false",
help="Disable tools with write access to FS.")
return parser.parse_args(argv)
def settings_from_args(args: argparse.Namespace) -> Settings:
return build_settings(
cwd=args.cwd,
base_url=args.base_url,
api_key=args.api_key,
model=args.model,
mcp_config=args.mcp_config,
shell=args.shell,
shell_timeout=args.shell_timeout,
enable_thinking=args.enable_thinking,
skill=args.skill,
verbose=args.verbose,
context_window=args.context_window,
enable_write=args.enable_write
)
# ---------------------------------------------------------------------------
# Host shell
# ---------------------------------------------------------------------------
class ShellBackend(ABC):
"""Only the platform-specific mechanics of the agent's host shell."""
kind: Literal["powershell", "bash"]
file_suffix: str
file_encoding: str = "utf-8"
def __init__(self, executable: str) -> None:
self.executable = executable
@property
@abstractmethod
def preamble(self) -> str:
"""Text prepended to every model-proposed script."""
@abstractmethod
def invocation(self, script_path: str) -> list[str]:
"""Command used to execute a temporary script file."""
class PowerShellBackend(ShellBackend):
kind: Literal["powershell"] = "powershell"
file_suffix = ".ps1"
file_encoding = "utf-8-sig"
@property
def preamble(self) -> str:
return (
"$OutputEncoding = [Console]::OutputEncoding = "
"[System.Text.UTF8Encoding]::new($false)\n"
"$ProgressPreference = 'SilentlyContinue'\n"
)
def invocation(self, script_path: str) -> list[str]:
return [
self.executable,
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-File",
script_path,
]
class BashBackend(ShellBackend):
kind: Literal["bash"] = "bash"
file_suffix = ".sh"
@property
def preamble(self) -> str:
# No `set -e`: the tool reports the script's real exit code and
# diagnostics instead of changing ordinary shell semantics.
return "set -o pipefail\n"
def invocation(self, script_path: str) -> list[str]:
return [self.executable, "--noprofile", "--norc", script_path]
def select_shell(requested: str = "auto") -> ShellBackend:
kind = requested
if kind == "auto":
kind = "powershell" if os.name == "nt" else "bash"
if kind == "powershell":
for executable in ("pwsh.exe", "pwsh", "powershell.exe", "powershell"):
resolved = shutil.which(executable)
if resolved:
return PowerShellBackend(resolved)
raise RuntimeError("PowerShell was requested but is not on PATH")
if kind == "bash":
resolved = shutil.which("bash")
if resolved:
return BashBackend(resolved)
raise RuntimeError("Bash was requested but is not on PATH")
raise ValueError(f"unsupported shell: {requested}")
def shell_backend(settings: Settings) -> ShellBackend:
if settings.shell_kind == "powershell":
return PowerShellBackend(settings.shell_executable)
return BashBackend(settings.shell_executable)
def _terminate_shell_wrapper(process: subprocess.Popen[bytes]) -> bool:
"""Kill and reap one shell wrapper without introducing another open-ended wait."""
if process.poll() is not None:
return True
with suppress(OSError):
process.kill()
try:
process.wait(timeout=SHELL_TERMINATE_GRACE_SECONDS)
except (OSError, subprocess.TimeoutExpired):
return False
return True
def _shell_output_preview(capture: Any, path: Path) -> str:
"""Read a bounded tail without loading the complete shell output into RAM."""
capture.seek(0, os.SEEK_END)
size = capture.tell()
start = max(0, size - context_limits().shell_chars * 4)
capture.seek(start)
text = capture.read(size - start).decode("utf-8", errors="replace")
lines = text.splitlines(keepends=True)
preview = "".join(lines[-context_limits().shell_lines:])[-context_limits().shell_chars:]
truncated = start > 0 or preview != text
notice = (
f"[output truncated: showing only the tail, at most {context_limits().shell_lines} "
f"lines / {context_limits().shell_chars} characters]\n"
if truncated else ""
)
return (
f"{notice}{preview or '(empty)'}\n"
f"[full output: {path} ({size} bytes captured)]"
)
def _run_host_shell(
backend: ShellBackend,
cwd: Path,
command: str,
timeout_seconds: int,
log_dir: Path | None = None,
) -> str:
"""Run one shell script with a timeout that cannot be held open by descendants.
Pipes are deliberately not used here. On Windows a background descendant can
inherit a pipe handle after the shell wrapper exits. ``subprocess.run`` then
waits for pipe EOF, and its timeout cleanup performs another unbounded
``communicate()``. Seekable temporary files let us wait only on the wrapper's
process handle and read whatever output exists after that bounded wait.
"""
if timeout_seconds <= 0:
raise ValueError("timeout_seconds must be greater than zero")
log_root = log_dir or active_session.path / "shell-output"
log_root.mkdir(parents=True, exist_ok=True)
output_dir = Path(tempfile.mkdtemp(prefix="call_", dir=log_root))
stdout_path = output_dir / "stdout.log"
stderr_path = output_dir / "stderr.log"
script_path: str | None = None
process: subprocess.Popen[bytes] | None = None
try:
with tempfile.NamedTemporaryFile(
mode="w",
suffix=backend.file_suffix,
prefix="pm_coder_worker_",
encoding=backend.file_encoding,
delete=False,
) as script_file:
script_file.write(backend.preamble + command)
script_path = script_file.name
with (