-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathruntime.py
More file actions
1974 lines (1773 loc) · 88 KB
/
Copy pathruntime.py
File metadata and controls
1974 lines (1773 loc) · 88 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
"""
runtime — LLM call interface with automatic DAG integration.
Runtime is a class that wraps an LLM provider. You instantiate it once
with your provider config, then call rt.exec() inside @agentic_functions.
exec() automatically:
1. Builds the prompt's message history from the DAG (the
``_store`` GraphStore the dispatcher installed for this turn)
2. Calls _call() (override this for your provider)
3. Appends a ModelCall node recording the reply into the DAG
Usage:
from openprogram import agentic_function
from openprogram.agentic_programming.runtime import Runtime
rt = Runtime(call=my_llm_func)
# or: subclass Runtime and override _call()
@agentic_function
def observe(task):
'''Look at the screen and describe what you see.'''
return rt.exec(content=[
{"type": "text", "text": "Find the login button."},
{"type": "image", "path": "screenshot.png"},
])
"""
from __future__ import annotations
import asyncio
import contextvars
import inspect
import json
import os
import random
import time
from typing import TYPE_CHECKING, Any, Callable, Optional
if TYPE_CHECKING:
from openprogram.providers.utils.errors import (
ErrorReason, LLMError, RetryInfo,
)
# Backoff base (seconds) between exec() retry attempts. Retries sleep
# _RETRY_BACKOFF * 2**attempt before the next try, with ±25% jitter
# so multiple concurrent retries don't fire in lock-step against the
# same upstream and re-trigger whatever connection-pool / rate-limit
# threshold caused the original failure.
#
# Default 1.5s; ``OPENPROGRAM_RETRY_BACKOFF_BASE`` env overrides so
# deployments with non-default network characteristics (proxied,
# offline-capable, very-low-latency local models) can re-tune without
# touching code.
_RETRY_BACKOFF = float(os.environ.get("OPENPROGRAM_RETRY_BACKOFF_BASE", "1.5"))
def _default_max_retries() -> int:
"""Process-wide default for ``Runtime(max_retries=...)``.
Reads ``OPENPROGRAM_MAX_RETRIES`` lazily on every Runtime
construction so tests / scripts can flip the env after this
module is imported and still see the new value. Falls back to
6 — the legacy hard-coded default (try once + retry five times,
total ≈46s of sleeping at the default backoff base).
"""
try:
v = int(os.environ.get("OPENPROGRAM_MAX_RETRIES", "6"))
except ValueError:
v = 6
return max(1, v)
def _default_exec_timeout_s() -> Optional[float]:
"""Process-wide fallback wall-clock budget for ``exec()`` /
``async_exec()`` when the caller passes ``timeout_s=None``.
Default ``0`` ⇒ ``None`` ⇒ the historical unbounded behaviour, so
existing callers are unaffected. Set ``OPENPROGRAM_EXEC_TIMEOUT_S`` to
a positive number to arm a deadline on EVERY exec from one place — the
cheapest way to stop an un-armed caller (a benchmark that forgot to
pass ``timeout_s``, a worker turn) from running an unbounded nested
retry storm. A deliberately non-arming default: a too-tight blanket
timeout would false-positive on legitimately long reasoning turns, so
the value is left to the deployment rather than hard-coded here.
"""
try:
v = float(os.environ.get("OPENPROGRAM_EXEC_TIMEOUT_S", "0") or 0)
except ValueError:
return None
return v if v > 0 else None
def _retry_sleep_seconds(attempt: int, retry_after_s: Optional[float] = None) -> float:
"""Exponential backoff + jitter, honoring a server-supplied
``Retry-After`` hint as a lower bound.
Without a hint (default): ``base * 2^attempt`` scaled by
``[0.75, 1.25]`` (symmetric jitter) so a burst of retries spreads
out instead of slamming the upstream simultaneously. Attempt 0
sleeps ~1.5s, attempt 1 ~3s, ..., attempt 5 ~48s.
With a hint (server returned ``Retry-After``): the delay is the
larger of the exponential base and ``retry_after_s``, then scaled
by ``[1.0, 1.25]`` — positive-only jitter so we never wake up
before the server-specified deadline. Honoring the lower bound
matters during rate-limit storms: ±25% symmetric jitter would
let a quarter of retries fire too early, defeating the server's
backpressure and triggering 429 again.
Mirrors OpenClaw's ``computeBackoffDelay`` (references/openclaw/
src/infra/retry.ts) which uses the same "positive-only when
Retry-After present" rule.
"""
base = _RETRY_BACKOFF * (2 ** attempt)
if retry_after_s and retry_after_s > 0:
floor = max(base, retry_after_s)
return floor * random.uniform(1.0, 1.25)
return base * random.uniform(0.75, 1.25)
# Substrings marking a *permanent* provider error. Retrying these only
# burns attempts and wall-clock time — the request is malformed or the
# credentials are bad, so the next identical attempt fails identically.
_PERMANENT_ERROR_MARKERS = (
"not a valid image",
"invalid image",
"image data is not",
"login expired",
"login failed",
"re-auth",
"unauthorized",
"invalid api key",
"invalid_api_key",
)
def _is_permanent_error(exc: Exception) -> bool:
"""True if retrying ``exc`` is pointless (malformed request / bad auth).
Honors a provider's explicit verdict first: a ``ProviderStreamError``
(or any exception) that already set ``retryable=False`` has been judged
non-retryable by the provider's own stream-retry layer — exec must NOT
re-retry it with a fresh budget. Without this, exec only string-matched
the message and so re-tried provider-declared-permanent failures (e.g.
codex's empty ``{"type":"error"}`` event surfaced as
"Error Code None: None", retryable=False) the full max_retries times,
multiplying one transient backend hiccup into a long, doomed retry storm
that still crashed the run.
"""
if getattr(exc, "retryable", None) is False:
return True
msg = f"{type(exc).__name__}: {exc}".lower()
return any(marker in msg for marker in _PERMANENT_ERROR_MARKERS)
def _build_llm_error(
*,
cause: BaseException,
attempts: int,
elapsed_s: float,
content: Any,
model: Optional[str],
provider: Optional[str],
history: list[str],
permanent: bool,
override_reason: "Optional[ErrorReason]" = None,
) -> "LLMError": # type: ignore[name-defined]
"""Construct the structured exception ``exec()`` raises when it
gives up.
Collects everything a caller needs to decide "retry the whole
turn", "reauthenticate", "trim prompt", or "circuit-break this
provider":
* ``reason`` — classified by :func:`classify_error`, or forced
via ``override_reason`` (e.g. TIMEOUT for deadline hits where
the underlying cause was incidental, not the real reason
we're giving up).
* ``retryable`` — honest about whether the underlying kind was
transient; ``False`` for permanent failures (auth / invalid
request / context overflow / timeout). Note: ``retryable=True``
means "the kind was transient but we exhausted our budget",
not "you should retry this immediately"
* ``attempts`` / ``elapsed_s`` / ``had_image`` — observability
* ``cause`` — original exception, preserved for traceback
via ``raise ... from cause``
The ``history`` list (per-attempt error strings) is folded into
the message so the LLMError's text is greppable like the old
RuntimeError. Localised to this helper so the two retry loops
stay tidy.
"""
from openprogram.providers.utils.errors import (
LLMError, classify_error, had_image as _had_image,
)
# Try to pull HTTP status from the cause if the provider attached
# it (HTTP providers stash it on the exc via ProviderStreamError).
http_status = getattr(cause, "http_status", None) or getattr(cause, "status_code", None)
retry_after_s = getattr(cause, "retry_after_s", None)
error_text = getattr(cause, "error_text", "") or ""
if override_reason is not None:
reason = override_reason
# An overridden reason (currently only TIMEOUT) is always
# non-retryable in this attempt budget: even if the underlying
# transport error was transient, *we* gave up because of a
# deadline, not because the kind was permanent.
retryable = False
else:
reason, kind_retryable = classify_error(
cause, http_status=http_status, error_text=error_text,
)
# Even if the underlying kind was retryable, when we gave up
# because the budget was exhausted, retryable stays True
# (caller may decide to retry the whole turn with a fresh
# budget). When the failure was permanent, force
# retryable=False regardless of what classify_error said.
retryable = kind_retryable and not permanent
label = "permanently" if permanent else f"after {attempts} attempt(s)"
detail = "\n".join(history) if history else f"{type(cause).__name__}: {cause}"
message = f"exec() failed {label}:\n{detail}"
return LLMError(
message=message,
reason=reason,
retryable=retryable,
http_status=http_status,
retry_after_s=retry_after_s,
attempts=attempts,
elapsed_s=elapsed_s,
had_image=_had_image(content),
provider=provider,
model=model,
last_error_type=type(cause).__name__,
cause=cause,
)
def _fire_on_retry(
on_retry: "Optional[Callable[[RetryInfo], None]]",
*,
cause: BaseException,
attempt: int,
max_attempts: int,
sleep_s: float,
elapsed_s: float,
retry_after_s: Optional[float],
) -> None:
"""Invoke an ``on_retry`` callback safely.
Exceptions inside the callback are swallowed — a broken hook
must never prevent the retry loop from making progress. The
callback receives a fully-populated :class:`RetryInfo`,
classified the same way as the final :class:`LLMError` would
be, so consumers can route on ``info.reason`` without
re-classifying.
"""
if on_retry is None:
return
from openprogram.providers.utils.errors import (
RetryInfo, classify_error, ErrorReason,
)
http_status = getattr(cause, "http_status", None) or getattr(cause, "status_code", None)
reason, _ = classify_error(cause, http_status=http_status,
error_text=getattr(cause, "error_text", "") or "")
info = RetryInfo(
attempt=attempt,
max_attempts=max_attempts,
reason=reason,
sleep_s=sleep_s,
elapsed_s=elapsed_s,
retry_after_s=retry_after_s,
last_error_type=type(cause).__name__,
last_error_msg=str(cause),
)
try:
on_retry(info)
except Exception:
# Don't break the retry loop on a buggy hook. Print once for
# the operator; future identical hook failures stay silent.
import sys as _sys
print(f"[runtime] on_retry callback raised; ignoring: "
f"{type(_sys.exc_info()[1]).__name__}", file=_sys.stderr)
# Context var for the tools passed into the current exec() call.
# _call_via_providers reads it to feed AgentSession without changing
# the _call() signature subclasses override.
_current_tools: contextvars.ContextVar[Optional[list]] = contextvars.ContextVar(
"_current_tools", default=None,
)
# OpenClaw-style tool policy that overlays on top of the chosen tool
# list. Set by callers (dispatcher / channels / runtime.exec kwargs)
# to filter the resolved tools per-call without renaming them. Shape:
# ``{"toolset": "research", "source": "wechat", "allow": [...], "deny": [...]}``.
# Any subset of keys is valid; missing keys mean "no constraint".
_current_tool_policy: contextvars.ContextVar[Optional[dict]] = contextvars.ContextVar(
"_current_tool_policy", default=None,
)
# Agent-loop options for the current exec() call — tool_choice /
# parallel_tool_calls / max_iterations travel to _call_via_providers'
# AgentSession the same way the tools list does (the _call() signature
# subclasses override stays unchanged). Only non-default values are
# stored; missing keys mean "provider / loop default".
_current_loop_opts: contextvars.ContextVar[Optional[dict]] = contextvars.ContextVar(
"_current_loop_opts", default=None,
)
# Per-exec stream-fn override. exec(stream_fn=...) sets it so the dispatcher
# (and integration tests) can inject a fake / pre-built stream into the same
# _call_via_providers → AgentSession path real provider calls use. None →
# fall back to the runtime's own _stream_fn (CallableModel) or the provider.
_current_stream_fn: contextvars.ContextVar[Optional[Any]] = contextvars.ContextVar(
"_current_stream_fn", default=None,
)
def _situational_prefix(
fn_name: str,
fn_doc: str,
call_path: str = "",
position: str = "",
output_contract: str = "",
) -> str:
"""L2 situation prompt prefixed to the inner model's turn — tells it
which agentic function it is inside, what its job is, the call path that
led here, where it sits, and where its output goes. Also the
self-recursion guidance (the function's own tool stays visible; the model
is steered away from re-entering it).
Design: docs/design/context/context-composition.md §四'·situation. Wrapped
in a <situation> tag (paired XML, like the other context sections).
Optional fields render only when provided, so existing call sites that pass
just (fn_name, fn_doc) stay backward-compatible.
English to match the rest of the model-facing prompt.
"""
lines = [f"You are running INSIDE the agentic function `{fn_name}`."]
if fn_doc and fn_doc.strip():
lines.append(f"Job: {fn_doc.strip()}")
if call_path and call_path.strip():
lines.append(f"Call path: {call_path.strip()}")
if position and position.strip():
lines.append(f"Position: {position.strip()}")
if output_contract and output_contract.strip():
lines.append(f"Your output: {output_contract.strip()}")
lines.append(
f"The tool list may include `{fn_name}` itself — do NOT call it "
"(re-entering causes infinite recursion). Use lower-level tools "
"(search / read-write files / run code) to do the work directly."
)
return "<situation>\n" + "\n".join(lines) + "\n</situation>"
def _compute_call_path(graph, frame_node_id: str, max_depth: int = 20) -> str:
"""Walk up the ``caller`` chain from ``frame_node_id`` to the root,
collecting the names of agentic-function (code) nodes, and join them
into ``"root → ... → current"``.
Read-only over ``graph``. Never raises — any failure returns "" so the
caller degrades to "fn_name only, no call path" (the prior behaviour).
- Only nodes that have a ``name`` are collected (skips anonymous /
meaningless intermediate nodes).
- Cycle-guarded (``seen``) and depth-capped (``max_depth``); when the
cap is hit the path is truncated with a leading "…".
- Stops when a node's ``caller`` is empty or points outside the graph.
"""
try:
if not graph or frame_node_id not in graph.nodes:
return ""
names: list[str] = []
seen: set[str] = set()
cur: Optional[str] = frame_node_id
truncated = False
while cur and cur in graph.nodes:
if cur in seen:
break
seen.add(cur)
if len(seen) > max_depth:
truncated = True
break
node = graph.nodes[cur]
name = getattr(node, "name", "") or ""
if name:
names.append(name)
cur = getattr(node, "caller", "") or None
if not names:
return ""
names.reverse() # root → ... → current
if truncated:
names.insert(0, "…")
return " → ".join(names)
except Exception:
return ""
class Runtime:
"""
LLM runtime. Wraps a provider and handles Context integration.
Two ways to use:
1. Pass a call function:
rt = Runtime(call=my_func, model="gpt-4o")
2. Subclass and override _call():
class MyRuntime(Runtime):
def _call(self, content, response_format=None):
# your API logic here
return reply_text
"""
def __init__(
self,
call: Optional[callable] = None,
model: str = "default",
max_retries: Optional[int] = None,
api_key: Optional[str] = None,
skills: "bool | list[str] | None" = None,
):
"""
Args:
call: LLM provider function.
Signature: fn(content: list[dict], model: str, response_format: dict) -> str
If None, the default pi-ai backend is used (when `model`
is "provider:model_id"). Subclasses may override _call().
model: Default model. Two forms:
- "provider:model_id" (e.g. "anthropic:claude-sonnet-4.5")
→ resolved via openprogram.providers; _call() goes
through complete() by default.
- Any other string → legacy path (subclass overrides
_call, or pass a `call` function).
max_retries: Maximum number of exec() attempts before raising.
``None`` (default) → read ``OPENPROGRAM_MAX_RETRIES``
env, fall back to 6. Set explicitly to override
env. 6 means try once + retry five times on
transient failure, with exponential backoff +
±25% jitter — wall-clock at worst ≈ 1.5 + 3 +
6 + 12 + 24 = 46s of sleeping before giving
up (tunable via ``OPENPROGRAM_RETRY_BACKOFF_BASE``).
Permanent errors (bad image, expired auth) are
not retried regardless of this value.
api_key: Optional API key. If omitted, resolved from the
provider's standard env var (OPENAI_API_KEY, etc).
skills: Skill discovery for the system prompt. Three shapes:
- None (default) or False → skills disabled
- True → probe default_skill_dirs() (user + repo)
- list[str] → explicit directory list
When enabled, the <available_skills> block is
appended to system_prompt on every exec() call.
"""
import uuid as _uuid
self._closed = False # Set early so __del__ is safe even if __init__ raises.
self._active_llm_node_id = None # llm node of the in-flight exec (for tool-loop attribution)
self._prompted_functions: set[str] = set() # Functions whose docstrings have been sent
# 提问通道(runtime.ask 的出口)。默认 None → 走事件层(前端卡片 + 总线)。
# @agentic_function 跑的子进程里,process_runner 会换成 QueueTransport
# (经 mp.Queue 把问题送回父进程)。对齐 logging:通道显式挂在对象上。
self._question_transport = None
if max_retries is None:
max_retries = _default_max_retries()
if max_retries < 1:
raise ValueError("max_retries must be >= 1")
self._call_fn = call
# When ``call=fn`` is supplied, the user's function is wrapped into the
# single provider/AgentSession path: ``api_model`` becomes a
# CallableModel stand-in and ``_stream_fn`` the adapter that calls
# ``fn``. This collapses the old "legacy call" branch — every exec now
# flows through _call_via_providers, writing one llm DAG node and
# honouring tool-loop attribution uniformly.
self._stream_fn = None
self.model = model
self.max_retries = max_retries
self.has_session = False # Subclasses set True if they manage their own context
self.on_stream = None # Optional callback: fn(event_dict) for streaming events
self.last_usage = None # Last call's token usage: {input_tokens, output_tokens, ...}
self.usage_is_cumulative = False # True if last_usage accumulates across calls (e.g. Codex CLI)
self.api_key = api_key
# Skills config: resolved to a (possibly empty) list of dirs at
# first use; actual SKILL.md loading is lazy and cached so we
# don't rescan the filesystem every exec().
self._skills_config = skills
self._skills_cache_key: tuple[str, ...] | None = None
self._skills_prompt_block: str = ""
# Unified reasoning knob, matches pi-ai's ThinkingLevel:
# "off" | "low" | "medium" | "high" | "xhigh"
# API runtimes pass this straight through to AgentSession → provider
# SimpleStreamOptions.reasoning. CLI subclasses override however their
# backend expects (flags, env vars, etc).
self.thinking_level: str = "off"
# Stable id across successive exec() calls — provider uses it as
# prompt_cache_key (Codex) so repeat prefixes hit the cache.
self.session_id = f"op-{_uuid.uuid4().hex[:16]}"
# Resolve "provider:model_id" form against the pi-ai model registry.
self.api_model = None
if call is not None:
# Wrap the user callable into the provider path: a stand-in model
# + a stream_fn that calls ``fn``. The model is never used for a
# real network call — the stream_fn intercepts it.
from openprogram.providers.callable_model import (
make_callable_model, make_callable_stream_fn,
)
self.api_model = make_callable_model(call)
self._stream_fn = make_callable_stream_fn(call)
elif isinstance(model, str) and ":" in model:
provider, model_id = model.split(":", 1)
from openprogram.providers import get_model
resolved = get_model(provider, model_id)
if resolved is None:
raise ValueError(
f"Unknown model {provider!r}:{model_id!r}. "
f"Pass `call=`, subclass Runtime, or use a valid pi-ai model id."
)
self.api_model = resolved
# --- Skills ---
def _resolved_skill_dirs(self) -> list[str]:
"""Turn the constructor's ``skills`` argument into a concrete dir list.
None / False → []. True → default dirs. list → as-is.
"""
cfg = self._skills_config
if not cfg:
return []
if cfg is True:
from openprogram.agentic_programming.skills import default_skill_dirs
return default_skill_dirs()
if isinstance(cfg, (list, tuple)):
return [str(d) for d in cfg]
return []
def _skills_block(self) -> str:
"""Return the ``<available_skills>`` XML block for this runtime.
Cached per dir tuple so repeat exec() calls don't rescan unless the
configured dirs change. Empty string when skills are disabled or no
SKILL.md files were found — callers can unconditionally concatenate.
"""
dirs = tuple(self._resolved_skill_dirs())
if self._skills_cache_key == dirs:
return self._skills_prompt_block
if not dirs:
self._skills_cache_key = dirs
self._skills_prompt_block = ""
return ""
from openprogram.agentic_programming.skills import (
format_skills_for_prompt, load_skills,
)
self._skills_prompt_block = format_skills_for_prompt(load_skills(dirs))
self._skills_cache_key = dirs
return self._skills_prompt_block
# --- Path dispatch ---
#
# There is now a single path: exec → _call → _call_via_providers →
# AgentSession → agent_loop. ``Runtime(call=fn)`` is wrapped into this
# path via a CallableModel (see __init__), and provider CLI subclasses
# override _call to reach _call_via_providers too. The old
# ``_uses_legacy_call`` fork (legacy text-merge vs provider render) is
# gone; some tests still define a ``_uses_legacy_call`` override on their
# fake-runtime subclasses — harmless dead overrides, nothing reads them.
def _render_history_messages(self, content) -> Optional[list]:
"""Build the provider message list for an in-progress exec()
from the DAG.
Source of truth: the ``_store`` ContextVar set by the dispatcher
at turn entry (``openprogram.context.storage._store``). When no
store is installed (standalone scripts, tests without the
dispatcher), returns ``None`` so the caller falls back to the
tree-Context render path.
Algorithm:
1. Load the DAG state from the store.
2. Read the enclosing ``@agentic_function`` call id from
``_call_id`` ContextVar; pull its node from the graph to
get seq + render_range.
3. Compute reads → render pi-ai messages.
4. Append a fresh UserMessage built from ``content``.
"""
from openprogram.store import _store
store = _store.get()
if store is None:
return None
try:
from openprogram.context.nodes import render_context
from openprogram.context.render import render_dag_messages
from openprogram.agentic_programming.function import _call_id
graph = store.load()
frame_node_id = _call_id.get()
frame_entry_seq = -1
render_range = None
if frame_node_id and frame_node_id in graph.nodes:
frame_node = graph.nodes[frame_node_id]
frame_entry_seq = frame_node.seq
render_range = (frame_node.metadata or {}).get(
"render_range"
)
head_seq = max(
(n.seq for n in graph.nodes.values()), default=-1,
)
read_ids = render_context(
graph,
head_seq=head_seq,
frame_entry_seq=frame_entry_seq,
render_range=render_range,
)
# Resolve the session's history/ dir so an over-cap node's
# truncation marker can cite the exact node file the agent can
# ``read`` back. Best-effort: any failure → generic marker.
history_dir = None
try:
_sess_dir = store.store._session_dir(store.session_id)
history_dir = str(_sess_dir / "history")
except Exception:
history_dir = None
history = render_dag_messages(graph, read_ids, history_dir)
# Inject current-frame identity so the inner model knows
# which function it is executing (prevents self-recursion
# and gives the model its role context).
frame_prefix_blocks: list[dict] = []
if frame_node_id and frame_node_id in graph.nodes:
fn_name = frame_node.name
fn_doc = (frame_node.metadata or {}).get("doc") or ""
if fn_name:
call_path = _compute_call_path(graph, frame_node_id)
text = _situational_prefix(
fn_name, fn_doc, call_path=call_path,
)
frame_prefix_blocks.append({
"type": "text",
"text": text,
})
# Synthesize the current turn from ``content`` blocks via
# the same helper the no-store fallback uses, so image /
# video / audio blocks survive the DAG render path. The old
# version concatenated text parts only — any screenshot the
# caller attached to this turn (gui_agent's verify / plan /
# locate sub-calls all do this) was silently dropped, so
# the LLM ended up reasoning over the OCR/component text
# alone and missed the current frame.
ctx, _sp = _build_pi_context(frame_prefix_blocks + (content or []))
return history + [ctx.messages[0]]
except Exception:
# If anything goes wrong building DAG messages, fall back
# to the legacy render_messages path. Never break exec().
return None
def _open_model_call_node(
self,
*,
model: str,
system_prompt: Optional[str] = None,
content_text: str = "",
) -> Optional[str]:
"""Write a *running* llm-role Call node at the start of one exec()
LLM call. Returns its node id (or None when no store is installed).
One ``runtime.exec`` == one llm node (the same way one
``@agentic_function`` == one code node). The node is written with
``output=None`` / ``status=running`` here; :meth:`_close_model_call_node`
fills in the reply and flips the status on return.
Note: this does NOT repoint ``_call_id``. The history renderer
(``_render_history_messages``) reads ``_call_id`` to locate the
enclosing *function* frame, and that read happens inside ``_call``
AFTER this node is opened — so flipping ``_call_id`` here would
corrupt history rendering. The repoint to this llm node (so the
tool loop attributes its tool calls here) is done later, inside
``_call_via_providers`` once the prompt is already built. See
:meth:`_enter_model_frame`.
``reads`` is intentionally left empty for now — wiring the exact
read-id set the prompt consumed is a future refinement.
"""
try:
from openprogram.store import _store
from openprogram.context.nodes import Call, ROLE_LLM
from openprogram.agentic_programming.function import _call_id
store = _store.get()
if store is None:
return None
node = Call(
role=ROLE_LLM,
name=model or self.model or "",
input=({"system": system_prompt} if system_prompt else None),
output=None,
reads=[],
caller=_call_id.get() or "",
metadata={
"status": "running",
**({"prompt_text": content_text[:8000]} if content_text else {}),
},
)
store.append(node)
return node.id
except Exception:
# DAG bookkeeping failure must not break the LLM call.
return None
def _close_model_call_node(
self,
node_id: Optional[str],
*,
reply: str,
status: str = "completed",
usage: Optional[dict] = None,
blocks: Optional[list] = None,
error: Optional[BaseException] = None,
) -> None:
"""Fill in the reply + terminal status on the running llm node
opened by :meth:`_open_model_call_node`.
Per session-dag.md decision 3, an llm node carries the SAME
fields regardless of entry point: besides ``output`` + ``status``,
an exec-path llm node now also records ``usage`` (token columns —
a function call costs tokens just like chat) and ``blocks`` (the
reply's thinking/text/tool structure). When ``usage``/``blocks``
are None they fall back to the runtime's last-call values, since
``_call`` has populated ``self.last_usage`` / ``self.last_blocks``
by the time this runs.
Status vocabulary is unified with the chat path (decision 2):
``completed`` / ``error`` / ``cancelled`` — not ``success``.
When ``error`` is provided (step 6-C), the same structured error
fields the chat path writes (error, error_type, trace) are
included in metadata — unified shape across both entry points.
No-op when ``node_id`` is None (no store was installed at open time).
"""
if node_id is None:
return
try:
from openprogram.store import _store
store = _store.get()
if store is None:
return
_usage = usage if usage is not None else getattr(self, "last_usage", None)
_blocks = blocks if blocks is not None else getattr(self, "last_blocks", None)
meta: dict = {"status": status}
if _usage:
meta["usage"] = _usage
if _blocks:
meta["blocks"] = _blocks
if error is not None:
import traceback as _tb
meta["error"] = str(error)
meta["error_type"] = type(error).__name__
meta["trace"] = "".join(
_tb.format_exception(type(error), error,
error.__traceback__))[:2000]
store.update(node_id, output=reply, metadata=meta)
except Exception:
pass
# --- Asking the user (user-input-requests.md Phase 1) ---
def _ui_session_id(self) -> str:
"""前端路由用的 webui session(dispatcher 在执行上下文里设的
ContextVar),不是 Runtime 自己的 op-xxx id。无 webui 时为空串。"""
try:
from openprogram.webui._pause_stop import get_current_session_id
return get_current_session_id() or ""
except Exception:
return ""
def can_ask(self) -> bool:
"""当前是否有人能回答(有前端会话连着)。headless 跑时为 False,
作者可据此分支(user-input-requests.md API)。"""
return bool(self._ui_session_id())
def set_question_transport(self, transport) -> None:
"""换掉这个 runtime 的提问通道(QuestionTransport)。子进程入口用它
装上 QueueTransport,把 runtime.ask 的问题经 mp.Queue 送回父进程。
传 None 恢复默认(事件层)。"""
self._question_transport = transport
def _ask_raw(self, *, kind, prompt, options=None, multi=False,
allow_custom=True, detail="", schema=None, questions=None,
timeout=300.0):
from openprogram.agent.questions import ask_blocking, emit_question_asked
transport = getattr(self, "_question_transport", None) # None → 默认事件层通道
def _on_asked(q):
# 经本 runtime 的提问通道把问题送出去:worker 进程默认走事件层
# (前端卡片 + 总线);@agentic_function 跑的子进程被 process_runner
# 换成 QueueTransport(经 mp.Queue 送回父进程 registry)。
emit_question_asked({
"id": q.id, "session_id": q.session_id, "kind": q.kind,
"prompt": q.prompt, "options": q.options, "multi": q.multi,
"allow_custom": q.allow_custom, "detail": q.detail,
"schema": q.schema, # kind="form" 时非空
"questions": q.questions, # kind="ask_many" 时非空
"expires_at": q.expires_at,
}, transport)
return ask_blocking(
session_id=self._ui_session_id(), kind=kind, prompt=prompt,
options=options, multi=multi, allow_custom=allow_custom,
detail=detail, schema=schema, questions=questions,
timeout=timeout, on_asked=_on_asked,
transport=transport, # 超时收回前端卡片走同一条通道
)
def ask(self, prompt: str | None = None, *, options=None, multi: bool = False,
allow_custom: bool = True, questions: list | None = None,
timeout: float = 300.0, default=None):
"""问用户,阻塞到有答案。统一入口——可一次问 1 题或多题。
两种用法(对齐 Claude Code 的 AskUserQuestion:不区分问几个):
1) 单题:``ask("你喜欢哪个?", options=["A","B"], multi=False)``
返回该题答案(multi=True 返回 list[str],纯文本无 options 返回 str)。
2) 多题:``ask(questions=[{"prompt": "...", "options": [...],
"multi": False, "allow_custom": True}, ...], prompt="组标题")``
前端一屏内在各题间切换着答、全答完一起提交。返回 list(与
questions 等长,每项是该题答案)。
三态:答了→返回答案;用户拒绝→抛 UserDeclined;超时→有 default
返回 default,否则抛 AskTimeout。
"""
from openprogram.agent.questions import UserDeclined, AskTimeout
# 多题分支 —— 一屏切换、一起提交(原 ask_many)。
if questions is not None:
qs = [
{
"prompt": str(q.get("prompt", "")),
"options": list(q.get("options") or []),
"multi": bool(q.get("multi")),
"allow_custom": q.get("allow_custom", True) is not False,
}
for q in (questions or [])
]
outcome, value = self._ask_raw(
kind="ask_many", prompt=prompt or "", questions=qs,
allow_custom=False, timeout=timeout,
)
if outcome == "answered":
return value if isinstance(value, list) else []
if outcome == "declined":
raise UserDeclined(prompt or "ask")
if default is not None:
return default
raise AskTimeout(prompt or "ask")
# 单题分支。
outcome, value = self._ask_raw(
kind="ask", prompt=prompt or "", options=options, multi=multi,
allow_custom=allow_custom, timeout=timeout,
)
if outcome == "answered":
return value
if outcome == "declined":
raise UserDeclined(prompt or "ask")
if default is not None:
return default
raise AskTimeout(prompt or "ask")
def confirm(self, prompt: str, *, detail: str = "",
timeout: float = 300.0, default: bool = False) -> bool:
"""问一个是/否,返回 bool。拒绝=False;超时返回 default(不抛)。"""
outcome, value = self._ask_raw(
kind="confirm", prompt=prompt, detail=detail,
options=["确认", "取消"], allow_custom=False, timeout=timeout,
)
if outcome == "answered":
if isinstance(value, str):
return value.strip() in ("确认", "yes", "y", "true", "ok", "是")
return bool(value)
if outcome == "declined":
return False
return default # timeout
def form(self, prompt: str, fields: dict, *,
detail: str = "", timeout: float = 300.0, default: dict | None = None):
"""问用户一个多字段表单(MCP-elicitation 风格),阻塞到提交。
``fields`` 是 flat-object 字段 schema:字段名 → 字段定义,例如
``{"name": {"type": "string", "title": "名字"},
"count": {"type": "integer", "default": 1},
"mode": {"type": "string", "enum": ["fast", "slow"]}}``。
只支持一层(无嵌套 object/array);字段类型限 string(可带 enum)/
integer / number / boolean。
三态(与 ask 一致):提交 → 返回 dict(字段名 → 值);用户拒绝 →
抛 UserDeclined;超时 → 有 default 返回 default,否则抛 AskTimeout。
"""
from openprogram.agent.questions import UserDeclined, AskTimeout
outcome, value = self._ask_raw(
kind="form", prompt=prompt, schema=dict(fields or {}),
allow_custom=False, detail=detail, timeout=timeout,
)
if outcome == "answered":
return value if isinstance(value, dict) else {}
if outcome == "declined":
raise UserDeclined(prompt)
if default is not None:
return default
raise AskTimeout(prompt)
def ask_many(self, questions: list, *, prompt: str = "",
timeout: float = 300.0, default: list | None = None):
"""已并入 ``ask``。保留为薄别名(向后兼容现有调用):等价于
``ask(questions=questions, prompt=prompt, ...)``。新代码直接用
``runtime.ask(questions=[...])``。"""
return self.ask(questions=questions, prompt=prompt,
timeout=timeout, default=default)
# --- Working directory ---
def set_workdir(self, path: str) -> None:
"""Set the provider's working directory.
For runtimes that spawn subprocesses (Codex CLI via --cd), this
determines where shell/tool commands execute and where the LLM
writes relative-path files. Default: no-op — runtimes that don't
spawn subprocesses ignore this.
"""
pass
# --- Lifecycle ---
def close(self):
"""Close this runtime: release resources, kill processes, end session.
After close(), exec() will raise RuntimeError.
Subclasses should override this to clean up provider-specific resources
(kill CLI processes, clear session IDs, etc.) and call super().close().
"""
self.has_session = False
self._prompted_functions.clear()
self._closed = True
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
return False
def __del__(self):
# Defensive: subclasses that raise mid-__init__ never reach
# Runtime.__init__, so `_closed` may be missing on the
# partially-built object the GC eventually reaps. Treat
# missing as already closed.
if not getattr(self, "_closed", True):
self.close()
def exec(
self,
content: list[dict],
context: Optional[str] = None,
response_format: Optional[dict] = None,
model: Optional[str] = None,
tools: Optional[list] = None,
toolset: Optional[str] = None,
tools_source: Optional[str] = None,
tools_allow: Optional[list[str]] = None,
tools_deny: Optional[list[str]] = None,
tool_choice: Any = "auto",
parallel_tool_calls: bool = True,
max_iterations: int = 20,
choices: Any = None,
timeout_s: Optional[float] = None,
on_retry: Optional["Callable[[RetryInfo], None]"] = None,
web_search: bool = False,
stream_fn: Any = None,
) -> Any:
"""
Call the LLM. Appends a ModelCall node to the DAG.
Args:
content: List of content blocks. Each block is a dict:
{"type": "text", "text": "..."}
{"type": "image", "path": "screenshot.png"}
{"type": "audio", "path": "recording.wav"}
{"type": "file", "path": "data.csv"}
context: Optional text prefix for the legacy ``_call``