Repository navigation
Expand file tree
/
Copy pathruntime_pi.py
More file actions
575 lines (519 loc) · 24.1 KB
/
Copy pathruntime_pi.py
File metadata and controls
575 lines (519 loc) · 24.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
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
"""Pi coding-agent runner integration."""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Optional
from feishu_bridge.runtime import BaseRunner, StreamState, _extract_hint_data, log
class PiRunner(BaseRunner):
"""badlogic/pi-mono coding-agent runner.
Pi emits JSONL events in ``--mode json``. The bridge keeps its own
session id and maps it to a deterministic Pi session file under the
configured workspace.
"""
ALWAYS_STREAMING = True
# Pi emits lowercase native tool names (read/bash/edit/write/ls/grep/find).
# Normalize to the bridge's canonical PascalCase vocabulary so ui.py's
# _TOOL_STATUS_MAP / _format_tool_hint (keyed on canonical names) and the
# shared _extract_hint_data both apply. Mirrors omp's _normalize_tool_name.
_TOOL_NAME_MAP = {
"bash": "Bash",
"read": "Read",
"write": "Write",
"edit": "Edit",
"ls": "Ls",
"grep": "Grep",
"find": "Find",
"subagent": "Subagent",
"web_search": "WebSearch",
"web_fetch": "WebFetch",
"get_subagent_result": "GetSubagentResult",
}
@classmethod
def _normalize_pi_tool(cls, raw_name: str) -> str:
return cls._TOOL_NAME_MAP.get((raw_name or "").lower(), (raw_name or "").title())
def display_default_model(self) -> Optional[str]:
"""Pi pins no ``--model`` under the default provider; it reads its own
``defaultModel`` from ``~/.pi/agent/settings.json``. Surface that for the
card footer / status display (mirrors OmpRunner.display_default_model).
Returns ``None`` when unreadable. Display only — never feeds build_args."""
if self.model:
return self.model
return self._read_pi_default_model()
@staticmethod
def _read_pi_default_model() -> Optional[str]:
"""Read defaultModel from ~/.pi/agent/settings.json."""
config_path = Path.home() / ".pi" / "agent" / "settings.json"
try:
with open(config_path) as f:
config = json.load(f)
except (OSError, ValueError) as e:
log.debug("Cannot read pi settings for default model: %s", e)
return None
if isinstance(config, dict):
model = config.get("defaultModel")
if isinstance(model, str) and model.strip():
return model.strip()
return None
def build_args(self, prompt: str, session_id: Optional[str],
resume: bool, streaming: bool, *,
fork_session: bool = False,
fresh_context: Optional[str] = None) -> list:
args = [self.command, "--mode", "json"]
if self._extra_cli_args:
args.extend(self._extra_cli_args)
if self.model and not self._has_arg(args, "--model"):
args.extend(["--model", self.model])
# No tool-policy injection: the bridge is a pure conduit for pi. Pi
# uses its native toolset (read/bash/edit/write) governed by pi's own
# config (~/.pi/agent/settings.json, AGENTS.md). Operators can still
# scope tools per provider via config args_by_type (--tools/--no-tools/
# --exclude-tools), which arrive through _extra_cli_args above. Unlike
# Claude, pi has no tool_deferred approval flow, so access is gated by
# the bot's allowed_users, not a per-call approval card.
system_prompt = self._build_system_prompt(extra=fresh_context)
if system_prompt:
args.extend(["--append-system-prompt", system_prompt])
has_session_override = self._has_any_arg(args, {"--session", "--no-session"})
if session_id and not has_session_override:
args.extend(["--session", str(self._session_path(session_id))])
elif not session_id and not has_session_override:
args.append("--no-session")
args.extend(["-p", prompt])
return args
def parse_streaming_line(self, event: dict, state: StreamState) -> None:
etype = event.get("type")
if etype == "message_update":
self._handle_message_update(event, state)
return
if etype == "tool_execution_start":
state.tool_active_count += 1
state.pending_silent_reset = True
# pi's JSON output (≥v3) carries toolCallId + args in
# tool_execution_start. Forward them as a pending status
# entry so the UI can render rich input-argument blocks
# alongside the tool label (like pi-feishu does).
tool_name = event.get("toolName")
call_id = event.get("toolCallId")
exec_args = event.get("args")
norm_name = self._normalize_pi_tool(tool_name or "")
if tool_name and isinstance(exec_args, dict):
if norm_name in {"Subagent", "GetSubagentResult"}:
# These pi tools are user-visible operations. Render them
# as ordinary tool panels; if a toolcall_start already
# created the entry, only backfill args.
if not (call_id and call_id in state._tool_seen_starts):
entry = {
"name": norm_name,
"hint_data": _extract_hint_data(norm_name, exec_args),
}
if call_id:
entry["id"] = call_id
state._tool_seen_starts.add(call_id)
state.pending_tool_status.append(entry)
backfill = {
"name": norm_name,
"hint_data": "",
"_exec_args": exec_args,
}
if call_id:
backfill["id"] = call_id
state.pending_tool_status.append(backfill)
return
if call_id:
state.pending_tool_status.append({
"name": norm_name,
"hint_data": "",
"id": call_id,
"_exec_args": exec_args,
})
return
if etype == "tool_execution_end":
state.tool_active_count = max(0, state.tool_active_count - 1)
state.pending_silent_reset = True
tool_name = event.get("toolName")
call_id = event.get("toolCallId")
result = event.get("result")
is_error = event.get("isError", False)
norm_name = self._normalize_pi_tool(tool_name or "")
# Forward execution result to UI for rich output display
# (pi-feishu parity: args in the expandable card).
if tool_name and call_id:
state.pending_tool_status.append({
"name": norm_name,
"hint_data": "",
"id": call_id,
"_exec_result": result,
"_is_error": is_error,
})
return
if etype == "turn_end":
state.final_result = event
# Turn boundary: clear any tool-active count left dangling by a missing
# tool_execution_end (best-effort lifecycle), so the silent budget does
# not stay extended into a text-only tail.
state.tool_active_count = 0
message = event.get("message") or {}
stop_reason = message.get("stopReason")
terminating = bool(stop_reason) and stop_reason != "toolUse"
# Fallback accumulation: if message_end didn't accumulate yet
# (error/aborted path) and this turn is terminating, do it now.
if terminating and not state._current_message_accumulated:
self._update_usage(message.get("usage"), state,
event_message=message, accumulate=True)
state._current_message_accumulated = True
else:
self._update_usage(message.get("usage"), state,
event_message=message)
if terminating:
text = self._message_text(message)
if text:
should_emit = text != state.accumulated_text
state.accumulated_text = text
if should_emit:
state.pending_output.append(state.accumulated_text)
state.is_error = stop_reason in {"error", "aborted"}
state.done = True
# Reset for next turn so the flag doesn't leak across turns.
state._current_message_accumulated = False
return
if etype == "error":
raw = (
event.get("message")
or event.get("errorMessage")
or event.get("error")
or "Unknown Pi protocol error"
)
if isinstance(raw, dict):
raw = raw.get("message") or raw.get("error") or str(raw)
state.accumulated_text = self._format_error(str(raw))
state.pending_output.append(state.accumulated_text)
state.is_error = True
state.done = True
state.tool_active_count = 0 # clear lifecycle count on error path
return
if etype == "message_end":
message = event.get("message") or {}
self._update_usage(message.get("usage"), state,
event_message=message, accumulate=True)
state._current_message_accumulated = True
return
def _build_streaming_result(self, state: StreamState,
session_id: Optional[str]) -> Optional[dict]:
if not state.done:
return None
message = (state.final_result or {}).get("message") or {}
stop_reason = message.get("stopReason")
error_message = message.get("errorMessage")
text = state.accumulated_text or self._message_text(message)
is_error = state.is_error or stop_reason in {"error", "aborted"}
if is_error and not text:
text = error_message or "Pi request failed."
if is_error:
text = self._format_error(text)
if not text:
return None
usage = state.last_call_usage or {}
provider = message.get("provider")
actual_model = message.get("model")
if provider and actual_model:
model_name = f"{provider}/{actual_model}"
else:
model_name = actual_model or self.display_default_model() or "(cli-default)"
# pi footer data: cumulative usage + context + provider info
pi_footer_data = {
"cumulative_input": state.cumulative_input,
"cumulative_output": state.cumulative_output,
"cumulative_cache_read": state.cumulative_cache_read,
"cumulative_cache_write": state.cumulative_cache_write,
"cumulative_cost_total": state.cumulative_cost_total,
"latest_cache_hit_rate": state.latest_cache_hit_rate,
"context_window": state.context_window,
"context_tokens": state.peak_context_tokens,
"is_oauth": (provider or "").strip().lower() in {"anthropic", "openai-codex"},
"model": actual_model or None,
}
return {
"result": text,
"session_id": state.session_id or session_id,
"is_error": is_error,
"usage": usage,
"last_call_usage": usage,
"modelUsage": {
model_name: {
"contextWindow": 0,
"inputTokens": (usage.get("input_tokens", 0) or 0),
"outputTokens": (usage.get("output_tokens", 0) or 0),
"cacheReadInputTokens": (usage.get("cache_read_input_tokens", 0) or 0),
"cacheCreationInputTokens": (usage.get(
"cache_creation_input_tokens", 0
) or 0),
},
},
"peak_context_tokens": state.peak_context_tokens,
"compact_detected": False,
"pi_footer_data": pi_footer_data,
}
def parse_blocking_output(self, stdout: str, session_id: Optional[str]) -> dict:
raise NotImplementedError("PiRunner always uses streaming mode")
def get_display_name(self) -> str:
return "Pi"
def supports_compact(self) -> bool:
return False
def wants_auth_file(self) -> bool:
return False
@staticmethod
def _has_arg(args: list, flag: str) -> bool:
return any(arg == flag or str(arg).startswith(flag + "=") for arg in args)
@classmethod
def _has_any_arg(cls, args: list, flags: set[str]) -> bool:
return any(cls._has_arg(args, flag) for flag in flags)
def _session_path(self, session_id: str) -> Path:
safe_id = re.sub(r"[^A-Za-z0-9_.-]", "_", session_id)
session_dir = (
Path(self.workspace)
/ "state"
/ "feishu-bridge"
/ "pi-sessions"
)
session_dir.mkdir(parents=True, exist_ok=True)
return session_dir / f"{safe_id}.jsonl"
def _handle_message_update(self, event: dict, state: StreamState) -> None:
update = event.get("assistantMessageEvent") or {}
utype = update.get("type")
if utype == "text_delta":
delta = update.get("delta") or ""
if delta:
state.accumulated_text += str(delta)
state.pending_output.append(state.accumulated_text)
return
if utype == "text_end":
content = update.get("content") or ""
if content and not state.accumulated_text:
state.accumulated_text = str(content)
state.pending_output.append(state.accumulated_text)
partial = update.get("partial") or {}
self._update_usage(partial.get("usage"), state)
return
if utype in {"toolcall_start", "toolcall_end"}:
self._emit_tool_status(update, state,
is_start=(utype == "toolcall_start"))
def _emit_tool_status(self, update: dict, state: StreamState,
is_start: bool) -> None:
"""Surface a pi tool call as one ``{name, hint_data}`` entry.
Authoritative source for pi tool status (``message_update.toolcall_*``).
Start and end events are deduped independently (``_tool_seen_starts`` /
``_tool_seen_ends``) so a start never suppresses an end (Bug #4 fix).
End events push the call-id into ``pending_tool_end_ids`` for the
drain-loop ``on_tool_end`` callback (F-1). Never raises.
"""
try:
tc = self._tool_call_from_update(update)
if not tc:
return
name = tc.get("name")
if not name:
return
call_id = tc.get("id")
# Dedup: start and end tracked separately.
seen_set = state._tool_seen_starts if is_start else state._tool_seen_ends
if call_id and call_id in seen_set:
return
if not call_id and not is_start:
# id-less call: act on start only to avoid start+end double.
# Known limitation: an id-less split call whose args arrive only
# on `end` surfaces a bare label (no hint). Real pi always emits
# a tool-call id (verified), so this affects only malformed
# streams — an acceptable degradation, never a crash.
return
canonical = self._normalize_pi_tool(name)
args = tc.get("arguments")
if not isinstance(args, dict):
args = {}
# General tool path.
start_already_emitted = bool(
call_id and call_id in state._tool_seen_starts)
if not args:
# No usable arguments. With an id on a *start* event, defer —
# a later toolcall_end may carry them. Otherwise:
# - start without call_id → bare label (never-raises contract)
# - end with call_id → only pending_tool_end_ids (no bare
# status entry; unmatched warning at drain time)
if call_id and is_start:
return
if not is_start and call_id:
# End without args: only end-id (unmatched warning path).
state.pending_tool_end_ids.append(call_id)
state._tool_seen_ends.add(call_id)
return
# Start without call_id or bare start (id but no args,
# not deferred above because !is_start path already returned).
entry = {"name": canonical, "hint_data": ""}
if call_id:
entry["id"] = call_id
state.pending_tool_status.append(entry)
if call_id:
state._tool_seen_starts.add(call_id)
return
hint = _extract_hint_data(canonical, args)
entry = {"name": canonical, "hint_data": hint}
if call_id:
entry["id"] = call_id
if is_start:
# Normal start with args → one status entry.
state.pending_tool_status.append(entry)
if call_id:
state._tool_seen_starts.add(call_id)
else:
# End with args.
if call_id:
state.pending_tool_end_ids.append(call_id)
state._tool_seen_ends.add(call_id)
if not start_already_emitted:
# Deferred start: end carries the args → emit status
# as compensation (UI gets entry + immediate done).
state.pending_tool_status.append(entry)
state._tool_seen_starts.add(call_id)
except Exception as e: # never-raises hot path
log.debug("pi tool-status extract failed: %s", e)
@staticmethod
def _tool_call_from_update(update: dict) -> Optional[dict]:
"""Return the toolCall object (id/name/arguments) from an update."""
tool_call = update.get("toolCall")
if isinstance(tool_call, dict) and tool_call.get("name"):
return tool_call
partial = update.get("partial") or {}
content = partial.get("content") or []
if isinstance(content, list):
# Prefer the toolCall at the update's own contentIndex.
# Without this, multi-tool turns return the *first* toolCall for
# every start event, causing subsequent starts to be deduped (id
# already in _tool_seen_starts) and their entries silently lost.
content_index = update.get("contentIndex")
if isinstance(content_index, int) and 0 <= content_index < len(content):
item = content[content_index]
if (isinstance(item, dict)
and item.get("type") == "toolCall"
and item.get("name")):
return item
# Legacy fallback for events that lack contentIndex.
for item in content:
if (isinstance(item, dict)
and item.get("type") == "toolCall"
and item.get("name")):
return item
return None
@classmethod
def _message_text(cls, message: dict) -> str:
content = message.get("content") or []
if not isinstance(content, list):
return ""
parts = []
for item in content:
if isinstance(item, dict) and item.get("type") == "text":
text = item.get("text")
if text:
parts.append(str(text))
return "".join(parts)
@classmethod
def _format_error(cls, message: str) -> str:
raw = (message or "").strip() or "Unknown Pi error"
redacted = re.sub(
r"(?i)(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+",
r"\1=<redacted>",
raw,
)
lower = redacted.lower()
if redacted.startswith((
"Pi provider ",
"Pi 模型",
"Pi 工具",
"Pi 协议",
"Pi 请求",
)):
return redacted
if "invalid api key" in lower or "401" in lower or "unauthorized" in lower:
return f"Pi provider 鉴权失败:{redacted}"
if "model not found" in lower or "404" in lower:
return f"Pi 模型不可用或不存在:{redacted}"
if (
"econnrefused" in lower
or "connection refused" in lower
or "failed to fetch" in lower
or "network error" in lower
):
return f"Pi provider 不可用:{redacted}"
if (
"tool denied" in lower
or "tool not allowed" in lower
or "not permitted" in lower
or "permission denied" in lower
):
return f"Pi 工具调用被拒绝:{redacted}"
if "protocol" in lower or "invalid json" in lower or "jsonrpc" in lower:
return f"Pi 协议错误:{redacted}"
return f"Pi 请求失败:{redacted}"
def _update_usage(self, usage: Optional[dict], state: StreamState,
event_message: Optional[dict] = None,
*, accumulate: bool = False) -> None:
"""Refresh last-call state (always) and optionally accumulate.
``last_call_usage``, ``peak_context_tokens``, and
``context_window`` are refreshed on every call.
Cumulative fields (``cumulative_input``, ``cumulative_output``,
``cumulative_cache_read``, ``cumulative_cache_write``,
``cumulative_cost_total``, ``latest_cache_hit_rate``) are only
updated when *accumulate* is True — this prevents double/triple
counting when usage arrives on text_end, message_end, *and*
turn_end for the same message.
"""
normalized = self._normalize_usage(usage)
if not normalized:
return
state.last_call_usage = normalized
ctx_tokens = (
normalized.get("input_tokens", 0)
+ normalized.get("cache_read_input_tokens", 0)
+ normalized.get("cache_creation_input_tokens", 0)
)
if ctx_tokens > state.peak_context_tokens:
state.peak_context_tokens = ctx_tokens
# contextWindow from message or usage (pi event common fields)
if event_message and isinstance(event_message, dict):
cw = event_message.get("contextWindow")
else:
cw = None
if cw is None and isinstance(usage, dict):
cw = usage.get("contextWindow")
if isinstance(cw, (int, float)) and cw > 0:
state.context_window = int(cw)
if not accumulate:
return
# ── Cumulative pi usage tracking ──
state.cumulative_input += normalized.get("input_tokens", 0)
state.cumulative_output += normalized.get("output_tokens", 0)
state.cumulative_cache_read += normalized.get("cache_read_input_tokens", 0)
state.cumulative_cache_write += normalized.get("cache_creation_input_tokens", 0)
state.cumulative_cost_total += normalized.get("cost_total", 0.0)
# Cache hit rate
denom = (
state.cumulative_input
+ state.cumulative_cache_read
+ state.cumulative_cache_write
)
if denom > 0:
state.latest_cache_hit_rate = (
state.cumulative_cache_read / denom * 100
)
@staticmethod
def _normalize_usage(usage: Optional[dict]) -> dict:
if not isinstance(usage, dict):
return {}
cost = usage.get("cost", {}) or {}
cost_total = float(cost.get("total", 0) or 0)
return {
"input_tokens": int(usage.get("input", 0) or 0),
"cache_read_input_tokens": int(usage.get("cacheRead", 0) or 0),
"cache_creation_input_tokens": int(usage.get("cacheWrite", 0) or 0),
"output_tokens": int(usage.get("output", 0) or 0),
"cost_total": cost_total,
}