vis-agent 0.5.22.dev9311__py3-none-any.whl → 0.5.22.dev9332__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -37,7 +37,7 @@
37
37
  {
38
38
  "const": "attachments",
39
39
  "title": "Attachments",
40
- "description": "Attach files and look at pictures",
40
+ "description": "Attach files, look at pictures and play recordings",
41
41
  "x-vis-key": "a"
42
42
  },
43
43
  {
@@ -90,6 +90,13 @@
90
90
  "x-vis-key": "s",
91
91
  "x-vis-group": "session"
92
92
  },
93
+ {
94
+ "const": "rename-session",
95
+ "title": "rename session",
96
+ "description": "Change the title of this session",
97
+ "x-vis-key": "r",
98
+ "x-vis-group": "session"
99
+ },
93
100
  {
94
101
  "const": "delete-session",
95
102
  "title": "delete session",
@@ -350,6 +357,15 @@
350
357
  "x-vis-show-when": "has-images",
351
358
  "$comment": "The system viewer works on every terminal."
352
359
  },
360
+ {
361
+ "const": "play-recording",
362
+ "title": "play recording",
363
+ "description": "Play or stop a recording of the session",
364
+ "x-vis-key": "p",
365
+ "x-vis-group": "attachments",
366
+ "x-vis-show-when": "has-recordings",
367
+ "$comment": "A client with its own player in the conversation does not bind this verb."
368
+ },
353
369
  {
354
370
  "const": "toggle-voice-recording",
355
371
  "title": "record",
@@ -418,7 +434,7 @@
418
434
  },
419
435
  {
420
436
  "const": "has-panel",
421
- "description": "The session has a side panel view."
437
+ "description": "The session has a side panel view, or an app in the side panel."
422
438
  },
423
439
  {
424
440
  "const": "has-apps",
@@ -436,6 +452,10 @@
436
452
  "const": "has-images",
437
453
  "description": "The session has at least one picture."
438
454
  },
455
+ {
456
+ "const": "has-recordings",
457
+ "description": "The session has at least one recording."
458
+ },
439
459
  {
440
460
  "const": "has-agents",
441
461
  "description": "The session has subagents."
@@ -74,7 +74,7 @@ def request(frame):
74
74
  """Refuse a host session request outside a Vis process."""
75
75
  raise Refused(
76
76
  "vis.sessions, vis.session and vis.council need a Vis host. Outside an "
77
- "extension, use GatewayClient or LocalEngine from blockether.vis.engine."
77
+ "extension, use GatewayClient or StdioEngineClient from blockether.vis.engine."
78
78
  )
79
79
 
80
80
 
@@ -36,9 +36,9 @@ from ._council import (
36
36
  )
37
37
  from ._groups import SessionGroup
38
38
  from ._install import InstallError, ensure_installed, install
39
- from ._local import LocalEngine
39
+ from ._local import StdioEngineClient
40
40
  from ._models import Model, SessionModel
41
- from ._service import LocalService
41
+ from ._service import HttpLocalEngineClient
42
42
  from ._sounds import SoundPreset, Sounds, SoundSettings
43
43
  from ._speech import Speech, SpeechAudio, Transcript, Voice
44
44
 
@@ -59,12 +59,11 @@ __all__ = [
59
59
  "ExecutionLayer",
60
60
  "GatewayClient",
61
61
  "GatewayError",
62
+ "HttpLocalEngineClient",
62
63
  "InstallError",
63
64
  "JobEvent",
64
65
  "JobEvents",
65
66
  "JSONValue",
66
- "LocalEngine",
67
- "LocalService",
68
67
  "Model",
69
68
  "ProtocolError",
70
69
  "Query",
@@ -78,6 +77,7 @@ __all__ = [
78
77
  "SoundSettings",
79
78
  "Speech",
80
79
  "SpeechAudio",
80
+ "StdioEngineClient",
81
81
  "StructuredOutputError",
82
82
  "Transcript",
83
83
  "TransportError",
@@ -26,7 +26,7 @@ from ._client import (
26
26
  Turn,
27
27
  _duration,
28
28
  )
29
- from ._local import LocalEngine
29
+ from ._local import StdioEngineClient
30
30
 
31
31
  ResponseModel = TypeVar("ResponseModel", bound=BaseModel)
32
32
 
@@ -443,10 +443,11 @@ class Agent:
443
443
  Args:
444
444
  project: Project directory. Local execution resolves an existing directory
445
445
  immediately. Gateway execution requires an absolute path on the gateway.
446
- execution_layer: A `blockether.vis.engine.LocalEngine` or
446
+ client: A `blockether.vis.engine.StdioEngineClient`,
447
+ `blockether.vis.engine.HttpLocalEngineClient` or
447
448
  `blockether.vis.engine.GatewayClient` to borrow. When omitted, the agent
448
- creates and owns a local engine. Configure executable, credentials and
449
- transport timeouts on an explicit layer.
449
+ creates and owns a `StdioEngineClient`. Configure executable, credentials
450
+ and transport timeouts on an explicit client.
450
451
  extensions: Iterable of `blockether.vis.extension.Extension` declarations.
451
452
  Their Python callables stay in your application and execute on the
452
453
  calling thread while you read, wait or iterate events.
@@ -461,11 +462,11 @@ class Agent:
461
462
  Construction does not start a process or connect. Session access, context
462
463
  entry, `send` or `run` starts the conversation. Closing the default agent stops
463
464
  its private process and discards its temporary session database, not file edits.
464
- An explicitly supplied layer is borrowed: you must close it yourself, after
465
+ An explicitly supplied client is borrowed: you must close it yourself, after
465
466
  all agents using it have finished. An agent cannot be reused after `close`.
466
467
 
467
468
  Raises:
468
- TypeError: The supplied layer does not implement
469
+ TypeError: The supplied client does not implement
469
470
  `blockether.vis.engine.ExecutionLayer`, an extension is unsupported, or
470
471
  `tools` is not an iterable of strings.
471
472
  ValueError: A project or extension declaration is invalid, or only one of
@@ -478,7 +479,7 @@ class Agent:
478
479
  self,
479
480
  project=".",
480
481
  *,
481
- execution_layer: ExecutionLayer | None = None,
482
+ client: ExecutionLayer | None = None,
482
483
  extensions=(),
483
484
  tools=None,
484
485
  provider: str | None = None,
@@ -495,16 +496,12 @@ class Agent:
495
496
  tools = list(tools)
496
497
  if not all(isinstance(name, str) for name in tools):
497
498
  raise TypeError("tools must be an iterable of tool names")
498
- if execution_layer is not None and not isinstance(
499
- execution_layer, ExecutionLayer
500
- ):
501
- raise TypeError("execution_layer must be an ExecutionLayer")
502
- self._owns_execution_layer = execution_layer is None
503
- self.execution_layer = (
504
- LocalEngine(root=project) if execution_layer is None else execution_layer
505
- )
499
+ if client is not None and not isinstance(client, ExecutionLayer):
500
+ raise TypeError("client must be an ExecutionLayer")
501
+ self._owns_client = client is None
502
+ self.client = StdioEngineClient(root=project) if client is None else client
506
503
  self._session_options: dict[str, Any] = dict(
507
- self.execution_layer.session_options(project)
504
+ self.client.session_options(project)
508
505
  )
509
506
  if tools is not None:
510
507
  self._session_options["tools"] = tools
@@ -521,9 +518,9 @@ class Agent:
521
518
  raise TransportError("agent is closed")
522
519
  if self._session is None:
523
520
  try:
524
- self.execution_layer.connect()
521
+ self.client.connect()
525
522
  options: dict[str, Any] = self._session_options
526
- self._session = self.execution_layer.create_session(**options)
523
+ self._session = self.client.create_session(**options)
527
524
  self._mount_extensions(self._session, self._extensions)
528
525
  except BaseException:
529
526
  try:
@@ -535,11 +532,11 @@ class Agent:
535
532
 
536
533
  def _mount_extensions(self, session: Session, extensions):
537
534
  if extensions.manifest:
538
- self.execution_layer._ensure_client_lease()
539
- self.execution_layer.put_session_client_extensions(
535
+ self.client._ensure_client_lease()
536
+ self.client.put_session_client_extensions(
540
537
  session.id, body={"extensions": extensions.manifest}
541
538
  )
542
- self.execution_layer._client_extensions[session.id] = extensions
539
+ self.client._client_extensions[session.id] = extensions
543
540
 
544
541
  def _replace_extensions(self, candidate):
545
542
  if self._closed:
@@ -682,19 +679,17 @@ class Agent:
682
679
  self._closed = True
683
680
  try:
684
681
  if self._session is not None:
685
- for stream in tuple(self.execution_layer._streams):
682
+ for stream in tuple(self.client._streams):
686
683
  if getattr(stream, "session", None) == self._session:
687
684
  stream.close()
688
- if self._extensions.manifest and not self.execution_layer._closed:
689
- self.execution_layer.delete_session_client_extensions(
690
- self._session.id
691
- )
685
+ if self._extensions.manifest and not self.client._closed:
686
+ self.client.delete_session_client_extensions(self._session.id)
692
687
  finally:
693
688
  if self._session is not None:
694
- self.execution_layer._client_extensions.pop(self._session.id, None)
689
+ self.client._client_extensions.pop(self._session.id, None)
695
690
  self._extensions.clear()
696
- if self._owns_execution_layer:
697
- self.execution_layer.close()
691
+ if self._owns_client:
692
+ self.client.close()
698
693
 
699
694
  def __enter__(self):
700
695
  _ = self.session
@@ -232,6 +232,34 @@ class _Inflated:
232
232
  raise OSError("gzip answer cut short") from None
233
233
 
234
234
 
235
+ class _InflatedLines:
236
+ """The lines of one gzip event stream, each given when the gateway flushes it."""
237
+
238
+ def __init__(self, raw):
239
+ self._raw = raw
240
+ self._inflate = zlib.decompressobj(31)
241
+ self._plain = bytearray()
242
+
243
+ def readline(self, limit: int) -> bytes:
244
+ while True:
245
+ end = self._plain.find(b"\n", 0, limit)
246
+ if end >= 0 or len(self._plain) >= limit:
247
+ size = end + 1 if end >= 0 else limit
248
+ line = bytes(self._plain[:size])
249
+ del self._plain[:size]
250
+ return line
251
+ # read1 returns the bytes that are there; it does not wait for more.
252
+ packed = self._inflate.unconsumed_tail or self._raw.read1(8192)
253
+ if not packed:
254
+ line = bytes(self._plain)
255
+ self._plain.clear()
256
+ return line
257
+ try:
258
+ self._plain += self._inflate.decompress(packed, limit)
259
+ except zlib.error:
260
+ raise OSError("gzip event stream is damaged") from None
261
+
262
+
235
263
  def _duration(value: float) -> float:
236
264
  if not math.isfinite(value) or value <= 0:
237
265
  raise ValueError("timeout must be positive and finite")
@@ -408,7 +436,8 @@ class Event:
408
436
  class ExecutionLayer(ABC):
409
437
  """Shared session API for local processes and explicit gateway connections.
410
438
 
411
- Applications normally choose `blockether.vis.engine.LocalEngine` or
439
+ Applications normally choose `blockether.vis.engine.StdioEngineClient`,
440
+ `blockether.vis.engine.HttpLocalEngineClient` or
412
441
  `blockether.vis.engine.GatewayClient`, then use `create_session` to start a
413
442
  conversation or `session` to attach to an existing session ID. `Agent` wraps
414
443
  this API when you only need one conversation.
@@ -461,6 +490,10 @@ class ExecutionLayer(ABC):
461
490
  """Run one exchange whose answer the caller reads whole, not as a stream."""
462
491
  return self._open(method, route, **options)
463
492
 
493
+ def _open_events(self, route, **options) -> Any:
494
+ """Open one event stream. The caller inflates a gzip answer line by line."""
495
+ return self._open("GET", route, **options)
496
+
464
497
  def _ensure_client_lease(self, *, pid: int | None = None) -> str:
465
498
  if self._closed:
466
499
  raise TransportError("client is closed")
@@ -3644,8 +3677,8 @@ class GatewayClient(ExecutionLayer):
3644
3677
 
3645
3678
  with GatewayClient(
3646
3679
  "https://gateway.example.com", token=os.environ["VIS_GATEWAY_TOKEN"]
3647
- ) as layer:
3648
- with Agent(project="/workspace/project", execution_layer=layer) as agent:
3680
+ ) as client:
3681
+ with Agent(project="/workspace/project", client=client) as agent:
3649
3682
  result = agent.run("Summarize this project without changing files.")
3650
3683
  print(result["status"])
3651
3684
  ```
@@ -3702,7 +3735,7 @@ class GatewayClient(ExecutionLayer):
3702
3735
  timeout=None,
3703
3736
  upload_sha256=None,
3704
3737
  upload_length=None,
3705
- is_whole=False,
3738
+ is_inflated=False,
3706
3739
  ):
3707
3740
  if self._closed:
3708
3741
  raise TransportError("client is closed")
@@ -3727,8 +3760,9 @@ class GatewayClient(ExecutionLayer):
3727
3760
  if self._is_remote and self._inflates and len(content) >= _GZIP_MIN_BYTES:
3728
3761
  content = gzip.compress(content, 6, mtime=0)
3729
3762
  headers["Content-Encoding"] = "gzip"
3730
- # A stream stays plain: each event must arrive when the gateway writes it.
3731
- if is_whole and self._is_remote:
3763
+ # Only a caller that inflates the answer asks for gzip: a whole answer, or
3764
+ # an event stream, where the gateway flushes each event when it writes it.
3765
+ if is_inflated and self._is_remote:
3732
3766
  headers["Accept-Encoding"] = "gzip"
3733
3767
  if upload_sha256 is not None:
3734
3768
  headers["Content-Type"] = "application/zip"
@@ -3763,11 +3797,14 @@ class GatewayClient(ExecutionLayer):
3763
3797
  return raw
3764
3798
 
3765
3799
  def _open_whole(self, method, route, **options):
3766
- raw = self._open(method, route, is_whole=True, **options)
3800
+ raw = self._open(method, route, is_inflated=True, **options)
3767
3801
  if raw.headers.get("Content-Encoding") == "gzip":
3768
3802
  return _Inflated(raw)
3769
3803
  return raw
3770
3804
 
3805
+ def _open_events(self, route, **options):
3806
+ return self._open("GET", route, is_inflated=True, **options)
3807
+
3771
3808
  def _note_codings(self, answer):
3772
3809
  """Record that an answer says the gateway inflates gzip request bodies."""
3773
3810
  if "gzip" in (answer.headers.get("Accept-Encoding") or "").lower():
@@ -4809,8 +4846,8 @@ class _EventStream(Generic[_T]):
4809
4846
  return
4810
4847
  try:
4811
4848
  route, query = self._endpoint()
4812
- with self.client._open(
4813
- "GET", route, query=query, timeout=self._read_timeout()
4849
+ with self.client._open_events(
4850
+ route, query=query, timeout=self._read_timeout()
4814
4851
  ) as raw:
4815
4852
  if not self._attach(raw):
4816
4853
  return
@@ -4818,7 +4855,10 @@ class _EventStream(Generic[_T]):
4818
4855
  if raw.headers.get_content_type() != "text/event-stream":
4819
4856
  raise ProtocolError("expected event stream")
4820
4857
  data, size, event_name = [], 0, None
4821
- for line in iter(lambda: raw.readline(1048577), b""):
4858
+ lines = raw
4859
+ if raw.headers.get("Content-Encoding") == "gzip":
4860
+ lines = _InflatedLines(raw)
4861
+ while line := lines.readline(1048577):
4822
4862
  if self._should_stop():
4823
4863
  return
4824
4864
  if self._limit() is not None:
@@ -21,6 +21,7 @@ import tempfile
21
21
  import threading
22
22
  import time
23
23
  import weakref
24
+ from collections.abc import Sequence
24
25
  from email.message import Message
25
26
  from pathlib import Path
26
27
  from urllib.parse import urlencode
@@ -130,15 +131,19 @@ def _reply(status, decoded, headers):
130
131
  return _Reply(status, decoded, headers)
131
132
 
132
133
 
133
- class LocalEngine(ExecutionLayer):
134
- """Own a private Vis process without starting an HTTP server.
134
+ class StdioEngineClient(ExecutionLayer):
135
+ """Own a private Vis process over standard input and output, without an HTTP server.
135
136
 
136
- Use this layer when you need to choose an executable, share one local process
137
- between agents, or call the session API directly. With the default `vis-agent`,
138
- `connect` uses the installed command when it runs this SDK's release. Otherwise it
139
- downloads that release once into `$VIS_HOME/sdk` and checks it against the release
140
- checksums.
141
- Set `VIS_NO_AUTO_INSTALL=1` to turn off the download. This class never discovers
137
+ `Agent()` without a client creates one of these. Use this class yourself when
138
+ you need to choose an executable, share one local process between agents, or
139
+ call the session API directly. Its sessions are temporary. To keep sessions and
140
+ start the engine one time for many programs, use
141
+ `blockether.vis.engine.HttpLocalEngineClient`.
142
+
143
+ With the default `vis-agent`, `connect` uses the installed command when it runs
144
+ this SDK's release. Otherwise it downloads that release once into
145
+ `$VIS_HOME/sdk` and checks it against the release checksums. Set
146
+ `VIS_NO_AUTO_INSTALL=1` to turn off the download. This class never discovers
142
147
  a gateway. Supported platforms are Linux and macOS.
143
148
 
144
149
  Args:
@@ -164,10 +169,10 @@ class LocalEngine(ExecutionLayer):
164
169
  `create_session` waits up to `startup_timeout`.
165
170
 
166
171
  ```python
167
- from blockether.vis.engine import Agent, LocalEngine
172
+ from blockether.vis.engine import Agent, StdioEngineClient
168
173
 
169
- with LocalEngine(executable="vis-agent", root=".") as layer:
170
- with Agent(project=".", execution_layer=layer) as agent:
174
+ with StdioEngineClient(executable="vis-agent", root=".") as client:
175
+ with Agent(project=".", client=client) as agent:
171
176
  result = agent.run("Summarize this project without changing files.")
172
177
  print(result["status"])
173
178
  ```
@@ -181,7 +186,12 @@ class LocalEngine(ExecutionLayer):
181
186
  """
182
187
 
183
188
  def __init__(
184
- self, *, executable="vis-agent", root=".", timeout=30, startup_timeout=120
189
+ self,
190
+ *,
191
+ executable: str | os.PathLike[str] | Sequence[str] = "vis-agent",
192
+ root: str | os.PathLike[str] = ".",
193
+ timeout: float = 30,
194
+ startup_timeout: float = 120,
185
195
  ):
186
196
  super().__init__(timeout=timeout)
187
197
  if os.name != "posix":
@@ -195,7 +205,7 @@ class LocalEngine(ExecutionLayer):
195
205
  isinstance(arg, str) and arg for arg in self._command
196
206
  ):
197
207
  raise ValueError("executable must be a nonempty argv sequence")
198
- self._root = self.session_options(root)["root"]
208
+ self._root = self.session_options(os.fspath(root))["root"]
199
209
  self._startup_timeout = _duration(startup_timeout)
200
210
  self._process = None
201
211
  self._home = None
@@ -1,7 +1,7 @@
1
1
  """One warm local Vis gateway that SDK processes share (#489).
2
2
 
3
- `LocalService.ensure()` finds or starts one `vis-agent gateway` in a private state
4
- folder and returns a connected `GatewayClient` for it. While a client holds a lease,
3
+ `HttpLocalEngineClient` finds or starts one `vis-agent gateway` in a private state
4
+ folder and connects to it. While a client holds a lease,
5
5
  the next `Agent` attaches in milliseconds instead of starting an engine. The
6
6
  gateway stops by itself when its last client leaves. Supports Linux and macOS.
7
7
  """
@@ -56,98 +56,89 @@ class _Record(TypedDict):
56
56
  started_at: float
57
57
 
58
58
 
59
- class _ServiceClient(GatewayClient):
60
- """A client of the shared local gateway: local paths, startup-length session wait."""
59
+ class HttpLocalEngineClient(GatewayClient):
60
+ """Share one local Vis gateway between your programs, over HTTP on this computer.
61
61
 
62
- def __init__(self, url: str, *, token: str, timeout: float, startup_timeout: float):
63
- super().__init__(url, token=token, timeout=timeout)
64
- self._startup_timeout = startup_timeout
65
-
66
- def session_options(self, project=".") -> SessionOptions:
67
- """Resolve an existing local directory: the gateway runs on this computer."""
68
- path = Path(project).resolve(strict=True)
69
- if not path.is_dir():
70
- raise NotADirectoryError(str(path))
71
- return {"root": str(path), "channel": "app"}
72
-
73
- def _session_create_timeout(self, timeout: float | None) -> float | None:
74
- """Wait for a session up to the startup deadline of the service."""
75
- return max(self.timeout, self._startup_timeout) if timeout is None else timeout
76
-
77
-
78
- class LocalService:
79
- """Share one warm local Vis gateway between SDK processes.
80
-
81
- `Agent()` without an execution layer starts a private engine for each agent.
82
- The first start of a new engine copy can take 40 s or more, and each later
83
- start takes about 1.5 s. `ensure` starts one gateway once and keeps it running,
84
- so each later call attaches in milliseconds:
62
+ The first client starts the gateway. Each later client attaches in milliseconds,
63
+ where a `blockether.vis.engine.StdioEngineClient` starts a new engine in about
64
+ 1.5 s. Programs and threads that connect at the same time get one gateway. Its
65
+ sessions stay in its database.
85
66
 
86
67
  ```python
87
- from blockether.vis.engine import Agent, LocalService
68
+ from blockether.vis.engine import Agent, HttpLocalEngineClient
88
69
 
89
- with LocalService.ensure() as layer:
90
- with Agent(project=".", execution_layer=layer) as agent:
91
- print(agent.run("Summarize this project without changing files.")["status"])
70
+ with HttpLocalEngineClient() as client:
71
+ with Agent(project=".", client=client) as agent:
72
+ result = agent.run("Summarize this project without changing files.")
73
+ print(result["status"])
92
74
  ```
93
75
 
94
76
  The gateway keeps its database, token, runtime folder, logs and push state in
95
- `home` (default `$VIS_HOME/sdk/service`). It uses the provider settings of
96
- `VIS_HOME`, but never the database, the gateway or the paired devices of your
97
- own Vis. So its turns do not send notifications to your phone or browser. It listens only on
98
- 127.0.0.1, on a free port, and requires its token.
99
-
100
- The gateway stops by itself when no client holds a lease and no turn runs, as
101
- the gateway of the Vis terminal app does. A client that was not closed keeps
102
- its lease for up to 2 minutes after its process ends. A gateway that no client
103
- ever used stops after 30 s. Sessions stay in its database, so the next `ensure`
104
- starts the gateway again and finds them. Keep one client open while you work to
105
- keep the gateway warm.
77
+ `home`. It uses the provider settings of `VIS_HOME`, but never the database,
78
+ the gateway or the paired devices of your own Vis. So its turns do not send
79
+ notifications to your phone or browser. It listens only on 127.0.0.1, on a free
80
+ port, and requires its token.
81
+
82
+ Args:
83
+ executable: Executable path or name, or a nonempty argument sequence. The
84
+ SDK appends `gateway start` and its options. It does not parse shell
85
+ commands.
86
+ home: State folder of the gateway. Default `$VIS_HOME/sdk/service`.
87
+ timeout: Positive finite timeout in seconds for each request.
88
+ startup_timeout: Positive finite deadline in seconds for the start of the
89
+ gateway and for each session creation.
90
+
91
+ Construction starts nothing. `connect` or context entry attaches to the running
92
+ gateway of `home`, or starts it. `close` releases the lease of this client. The
93
+ gateway stops by itself when no client holds a lease and no turn runs. A client
94
+ that was not closed keeps its lease for up to 2 minutes after its process ends,
95
+ and a gateway that no client ever used stops after 30 s. Keep one client open
96
+ while you work to keep the gateway warm. `shutdown` stops the gateway for all
97
+ programs.
106
98
 
107
99
  With the default `vis-agent`, the engine comes from the same place as for
108
- `blockether.vis.engine.LocalEngine`: the installed command of this SDK's
109
- release, else a checked download into `$VIS_HOME/sdk`.
100
+ `StdioEngineClient`: the installed command of this SDK's release, else a checked
101
+ download into `$VIS_HOME/sdk`. Supported platforms are Linux and macOS.
110
102
  """
111
103
 
112
- @classmethod
113
- def ensure(
114
- cls,
104
+ def __init__(
105
+ self,
115
106
  *,
116
107
  executable: str | os.PathLike[str] | Sequence[str] = _COMMAND,
117
108
  home: str | os.PathLike[str] | None = None,
118
109
  timeout: float = 30,
119
110
  startup_timeout: float = 120,
120
- ) -> GatewayClient:
121
- """Return a connected client of the shared gateway, and start it when none runs.
122
-
123
- Processes and threads that call this at the same time get one gateway: a
124
- file lock in `home` lets only one of them start it. The client takes its
125
- lease while the call holds the lock, so the gateway cannot stop before the
126
- caller uses it. A record of a gateway that stopped, does not answer or
127
- stops during the call is replaced. A running gateway of another engine
128
- (for example after an SDK update) is replaced only when no client uses it
129
- and no turn runs; else the call reuses it.
130
-
131
- Args:
132
- executable: Executable path or name, or an argument sequence. The SDK
133
- appends `gateway start` and its options.
134
- home: State folder of the gateway. Default `$VIS_HOME/sdk/service`.
135
- timeout: Positive finite timeout in seconds for each request.
136
- startup_timeout: Positive finite deadline in seconds for the start of
137
- the gateway and for each session creation.
138
-
139
- Close the client, or use it as a context manager. Closing releases its lease.
140
- When it was the last lease, the gateway stops by itself.
111
+ ):
112
+ # The gateway takes a free port at its start, so `connect` sets the origin.
113
+ super().__init__(f"http://{_HOST}", timeout=timeout)
114
+ self._executable = executable
115
+ self._home = home
116
+ self._startup_timeout = _duration(startup_timeout)
117
+
118
+ def connect(self) -> HttpLocalEngineClient:
119
+ """Attach to the running gateway of `home`, or start it, and take a lease.
120
+
121
+ Return this client. Repeated calls reuse its lease. A file lock in `home`
122
+ lets only one caller start the gateway. The client takes its lease while
123
+ the call holds the lock, so the gateway cannot stop before the caller uses
124
+ it. A record of a gateway that stopped, does not answer or stops during the
125
+ call is replaced. A running gateway of another engine (for example after an
126
+ SDK update) is replaced only when no client uses it and no turn runs; else
127
+ the call reuses it.
141
128
 
142
129
  Raises:
143
130
  TransportError: The engine cannot be found or downloaded, or the
144
131
  gateway exited during its start. The message ends with its log.
145
132
  VisTimeout: The gateway did not answer within `startup_timeout`.
146
133
  """
147
- timeout, startup_timeout = _duration(timeout), _duration(startup_timeout)
148
- folder = _folder(home)
149
- command = _resolve(executable)
150
- deadline = time.monotonic() + startup_timeout + timeout
134
+ if self._closed:
135
+ raise TransportError("client is closed")
136
+ if self._lease or self._lease_error:
137
+ super().connect()
138
+ return self
139
+ folder = _folder(self._home)
140
+ command = _resolve(self._executable)
141
+ deadline = time.monotonic() + self._startup_timeout + self.timeout
151
142
  with _locked(folder / "lock", deadline):
152
143
  record = _read(folder)
153
144
  token = _token(folder)
@@ -155,59 +146,72 @@ class LocalService:
155
146
  if record and health:
156
147
  busy = health.get("clients") or health.get("running_turns")
157
148
  if record["command"] == command or busy:
158
- client = _connected(record, token, timeout, startup_timeout)
159
- if client is not None:
160
- return client
149
+ if self._attach(record, token):
150
+ return self
161
151
  # It stopped by itself after its last client left.
162
152
  _retire(folder, record)
163
153
  else:
164
154
  _stop(folder, record, token)
165
155
  elif record:
166
156
  _retire(folder, record)
167
- record, token = _start(folder, command, startup_timeout)
168
- return _client(record, token, timeout, startup_timeout).connect()
157
+ record, token = _start(folder, command, self._startup_timeout)
158
+ self._point(record, token)
159
+ super().connect()
160
+ return self
169
161
 
170
- @classmethod
171
- def discover(
172
- cls,
173
- *,
174
- home: str | os.PathLike[str] | None = None,
175
- timeout: float = 30,
176
- startup_timeout: float = 120,
177
- ) -> GatewayClient | None:
178
- """Return a connected client of the running shared gateway, or None. Never start one."""
179
- timeout, startup_timeout = _duration(timeout), _duration(startup_timeout)
180
- folder = _folder(home)
181
- record = _read(folder)
182
- token = _token(folder)
183
- if record is None or token is None or _health(record, token) is None:
184
- return None
185
- return _connected(record, token, timeout, startup_timeout)
186
-
187
- @classmethod
188
- def stop(cls, *, home: str | os.PathLike[str] | None = None) -> bool:
189
- """Stop the shared gateway, and return True when one was running.
190
-
191
- This stops the gateway for every process that uses it. Running turns stop
192
- too. Stored sessions stay in its database for the next start.
162
+ def shutdown(self) -> bool:
163
+ """Stop the gateway for every program, and close this client.
164
+
165
+ Return True when a gateway ran. Running turns stop too. Stored sessions
166
+ stay in its database for the next start. A client that never connected can
167
+ call this.
193
168
  """
194
- folder = _folder(home)
169
+ folder = _folder(self._home)
195
170
  with _locked(folder / "lock", time.monotonic() + 60):
196
171
  record = _read(folder)
197
- if record is None:
198
- return False
199
- token = _token(folder)
200
- if _health(record, token):
201
- _stop(folder, record, token)
202
- return True
203
- _retire(folder, record)
172
+ is_running = bool(record and _health(record, _token(folder)))
173
+ if record and is_running:
174
+ _stop(folder, record, _token(folder))
175
+ elif record:
176
+ _retire(folder, record)
177
+ # The lease ended with the gateway, so `close` has nothing to release.
178
+ self._lease = None
179
+ self.close()
180
+ return is_running
181
+
182
+ def session_options(self, project=".") -> SessionOptions:
183
+ """Resolve an existing local directory: the gateway runs on this computer."""
184
+ path = Path(project).resolve(strict=True)
185
+ if not path.is_dir():
186
+ raise NotADirectoryError(str(path))
187
+ return {"root": str(path), "channel": "app"}
188
+
189
+ def _session_create_timeout(self, timeout: float | None) -> float | None:
190
+ """Wait for a session up to the startup deadline of the gateway."""
191
+ return max(self.timeout, self._startup_timeout) if timeout is None else timeout
192
+
193
+ def _point(self, record: _Record, token: str | None) -> None:
194
+ """Aim this client at the gateway of `record`."""
195
+ if token is None:
196
+ raise TransportError(
197
+ "the shared local gateway has no token; call shutdown()"
198
+ )
199
+ self._url, self._token = record["url"], token
200
+
201
+ def _attach(self, record: _Record, token: str | None) -> bool:
202
+ """Take a lease on a running gateway. False when it stopped meanwhile."""
203
+ self._point(record, token)
204
+ try:
205
+ super().connect()
206
+ except (TransportError, GatewayError):
204
207
  return False
208
+ return True
205
209
 
206
210
 
207
211
  def _folder(home: str | os.PathLike[str] | None) -> Path:
208
212
  """Create the private state folder. The engine refuses a runtime folder others can write."""
209
213
  if os.name != "posix":
210
- raise ValueError("the local service currently supports Linux and macOS")
214
+ raise ValueError("the shared local gateway currently supports Linux and macOS")
211
215
  folder = Path(home) if home is not None else _vis_home() / "sdk" / "service"
212
216
  folder.mkdir(mode=0o700, parents=True, exist_ok=True)
213
217
  folder = folder.resolve(strict=True)
@@ -218,7 +222,7 @@ def _folder(home: str | os.PathLike[str] | None) -> Path:
218
222
 
219
223
 
220
224
  def _resolve(executable: str | os.PathLike[str] | Sequence[str]) -> list[str]:
221
- """Return the engine argv, with the same resolution and download as `LocalEngine`."""
225
+ """Return the engine argv, with the same resolution and download as `StdioEngineClient`."""
222
226
  command = (
223
227
  [os.fspath(executable)]
224
228
  if isinstance(executable, (str, os.PathLike))
@@ -230,7 +234,9 @@ def _resolve(executable: str | os.PathLike[str] | Sequence[str]) -> list[str]:
230
234
  try:
231
235
  return [ensure_installed()]
232
236
  except InstallError as error:
233
- raise TransportError(f"could not start local service: {error}") from None
237
+ raise TransportError(
238
+ f"could not start shared local gateway: {error}"
239
+ ) from None
234
240
  return command
235
241
 
236
242
 
@@ -248,7 +254,7 @@ def _locked(path: Path, deadline: float) -> Iterator[None]:
248
254
  except BlockingIOError:
249
255
  if time.monotonic() >= deadline:
250
256
  raise VisTimeout(
251
- "another process holds the local service lock"
257
+ "another process holds the lock of the shared local gateway"
252
258
  ) from None
253
259
  time.sleep(0.05)
254
260
  yield
@@ -464,7 +470,7 @@ def _start(
464
470
  start_new_session=True,
465
471
  )
466
472
  except OSError as error:
467
- raise TransportError(f"could not start local service: {error}") from None
473
+ raise TransportError(f"could not start shared local gateway: {error}") from None
468
474
  _STARTED.append(process)
469
475
  threading.Thread(
470
476
  target=_reap, args=(process,), name="vis-sdk-service", daemon=True
@@ -488,12 +494,14 @@ def _start(
488
494
  return record, token
489
495
  if process.poll() is not None:
490
496
  raise TransportError(
491
- f"local service exited with status {process.returncode}"
497
+ f"shared local gateway exited with status {process.returncode}"
492
498
  + _log_tail(log)
493
499
  )
494
500
  if time.monotonic() >= deadline:
495
501
  _signal_group(record, signal.SIGKILL)
496
- raise VisTimeout("local service did not answer in time" + _log_tail(log))
502
+ raise VisTimeout(
503
+ "shared local gateway did not answer in time" + _log_tail(log)
504
+ )
497
505
  time.sleep(0.1)
498
506
 
499
507
 
@@ -538,26 +546,4 @@ def _log_tail(log: Path) -> str:
538
546
  if size > _LOG_TAIL:
539
547
  end = end.partition(b"\n")[2] or end
540
548
  text = end.decode("utf-8", "replace").strip()
541
- return f"\nLocal service log:\n{text}" if text else ""
542
-
543
-
544
- def _connected(
545
- record: _Record, token: str | None, timeout: float, startup_timeout: float
546
- ) -> GatewayClient | None:
547
- """Return a client with a lease, or None when the gateway stopped meanwhile."""
548
- client = _client(record, token, timeout, startup_timeout)
549
- try:
550
- return client.connect()
551
- except (TransportError, GatewayError):
552
- client.close()
553
- return None
554
-
555
-
556
- def _client(
557
- record: _Record, token: str | None, timeout: float, startup_timeout: float
558
- ) -> GatewayClient:
559
- if token is None:
560
- raise TransportError("the local service has no token; call LocalService.stop()")
561
- return _ServiceClient(
562
- record["url"], token=token, timeout=timeout, startup_timeout=startup_timeout
563
- )
549
+ return f"\nShared local gateway log:\n{text}" if text else ""
@@ -1 +1 @@
1
- beta-a5bfead058214b6a161ff543594bd099f35c4ac3
1
+ beta-53e83def0f2b9d2a5accc16d5d8324e39d8f279c
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: vis-agent
3
- Version: 0.5.22.dev9311
3
+ Version: 0.5.22.dev9332
4
4
  Summary: The Vis Python SDK — author extensions and control local or remote engines.
5
5
  Project-URL: Homepage, https://vis.blockether.com
6
6
  Project-URL: Documentation, https://vis.blockether.com
@@ -53,7 +53,7 @@ with Agent(project=".") as agent:
53
53
 
54
54
  The SDK starts a private Vis process with a temporary session database and removes both
55
55
  when the block ends. Tasks can incur provider charges and can change project files. To
56
- choose the executable or share one process between agents, use `LocalEngine`. See the
56
+ choose the executable or share one process between agents, use `StdioEngineClient`. See the
57
57
  [stdio guide](https://vis.blockether.com/python-sdk.html#use-stdio-from-the-python-sdk).
58
58
  The first run with a new engine copy can take more than one minute. See
59
59
  [the first start of a private agent](https://vis.blockether.com/python-sdk.html#the-first-start-of-a-private-agent).
@@ -1,6 +1,6 @@
1
1
  blockether/vis/__init__.py,sha256=qZHO5GRQsM6_fzA98MOHo1XVIsESuPRlkaMjF9olP18,263
2
2
  blockether/vis/_contracts.py,sha256=WoeQOQsoqN3EyW6_pMYPb1CcwPLEDRuOKee_T5w_UI8,79606
3
- blockether/vis/_outside.py,sha256=XUd9ykksN1TJYaB-04-vbfJE17MRZR1pXQA0tiG0u2M,63285
3
+ blockether/vis/_outside.py,sha256=aLa1PX4OUrhgFY4yuyK-UYVMZ565lkk28NqtAMRkN5I,63291
4
4
  blockether/vis/_wire.py,sha256=UyOiARmcvPl6HpLp1u_uAdUIrScP1o0cK6DuvEheMKg,892
5
5
  blockether/vis/activity.py,sha256=8sQozSA3pV33RODOOqKMVchYLC0HalL49tz2Gfxpk5g,10934
6
6
  blockether/vis/extension.py,sha256=N99FLTZsNsLuggAJ3CcJEKtNKs0AFmwvMpwXoXyWwcU,334780
@@ -8,18 +8,18 @@ blockether/vis/extension_package.py,sha256=C9Bk-bLJK1BqXW866Ox3diDVRQuVrgrZgWzN-
8
8
  blockether/vis/live_check.py,sha256=A4nyKSSJLID5sIbmm0FiM0mLpL9VoTcpiFJDd6gq160,2507
9
9
  blockether/vis/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
10
  blockether/vis/views.py,sha256=lYzXHhb6fSW-OGL1P08WhVtqXy6OSGxbN6hRBfDvd_w,7598
11
- blockether/vis/engine/__init__.py,sha256=8m6-ihen_ZEa1BK1E7f3v84V3x_IoqHcmm4y4RuhNnc,1878
12
- blockether/vis/engine/_agent.py,sha256=KuTBN5I7f7vzvE2duSeg5a-dLQZT6klRVVtvk-ROXE4,28385
11
+ blockether/vis/engine/__init__.py,sha256=ZCnypWbkCrIf_hWV9IacdaZPSKAjWS2Hv1VnCo3ufrk,1908
12
+ blockether/vis/engine/_agent.py,sha256=N_zcL5w9jL3IZUEokBxNnQKNrUbPyH4MhbnBMX8utL0,28174
13
13
  blockether/vis/engine/_agents.py,sha256=uYBzwwkp6o5t69aTEoy0GGOKhavo4HUfOCQEE0ov0nU,3500
14
- blockether/vis/engine/_client.py,sha256=L124EBU9oO9doABc3W3cRkroBmg45avCwblCUEwtqO0,181946
14
+ blockether/vis/engine/_client.py,sha256=Vrka2NFUh0K8upTyRBVlYE2qQlUu6N_C78_F-zdfwWM,183613
15
15
  blockether/vis/engine/_council.py,sha256=4MCH6DQ9u3nHXX1ZzqIVyJYzh25ddubqstLicC2G4pY,16728
16
16
  blockether/vis/engine/_extensions.py,sha256=gCXRN1fkUMg8SkNB_3xcOKAeSatfaY6S9g_R8Yy-0sI,13950
17
17
  blockether/vis/engine/_groups.py,sha256=6ED7PihO1jFSjEmxUpccb0hxIAa_YWaOADvlkAji7-c,1281
18
18
  blockether/vis/engine/_host.py,sha256=GxiN2A5of4tUg5YBBcICqyBgzo2Il0rZd7UlOKfRMAQ,3080
19
19
  blockether/vis/engine/_install.py,sha256=5RUY8I3FdJ2xGSYg_qvmmoT6sEHjAocqrjrRkQm_Eco,11540
20
- blockether/vis/engine/_local.py,sha256=FcbcrYmJ0b6cPmiF4Yie2ExRhz5B6FyKQ_OjLnCr3MM,17841
20
+ blockether/vis/engine/_local.py,sha256=j0WUjxvtAvQIn9kGgysN66c4bS-JtZyMlLGXjBAFGRo,18266
21
21
  blockether/vis/engine/_models.py,sha256=Tajra-zkfmPIq5Tvajp57zgxDWAbjJiq4MDUKaL8dxs,3365
22
- blockether/vis/engine/_service.py,sha256=hQkx12dRVfIQvtEhmFnNk-MY361Op0jo1MLiPhZ2P0s,20666
22
+ blockether/vis/engine/_service.py,sha256=551dVIkzK2BcXgakGOsLoGfiLKs1_yNEWE1odyB4ogA,20121
23
23
  blockether/vis/engine/_sounds.py,sha256=kuYKATiH0azTs5BrUxN_-GF2ZSIxluqpe11hoZIwvPA,9460
24
24
  blockether/vis/engine/_speech.py,sha256=n5qNsOJKzDthhXFc6_5vOK3fmhfbb9brPSK4CJAvnTQ,10874
25
25
  blockether/vis/engine/_types.py,sha256=CeurdrExdEHplaHY0ntQBNWe3i9hUO2qtBrcbITtCAw,85737
@@ -84,13 +84,13 @@ blockether/vis/_data/schema/council.json,sha256=xiuTZnx7qp-Kx96XFE8Qv8zPMv1N10is
84
84
  blockether/vis/_data/schema/diff.json,sha256=NOQDBR98KMuVW4JF18IDB57YYTMqASVZCtg-BeBKEGY,2060
85
85
  blockether/vis/_data/schema/evals.json,sha256=TpP8OCv_1Yh1Ie_xmJYa7-d69bJrFRiZpUhn7tmniTs,23972
86
86
  blockether/vis/_data/schema/gateway.json,sha256=F7Sk1yBLjcOYvMrRrJFtS9st5tBbzNdE26IkAL_8BJI,214196
87
- blockether/vis/_data/schema/keymap.json,sha256=Z0ZX013i5scxuuruqytQYcRNdvC_O2lIBCobLEuNj0M,14756
87
+ blockether/vis/_data/schema/keymap.json,sha256=D7gpiGfOw0izF4kKeSFoFZJE2E79XH_lKZCJQx_Vxyc,15522
88
88
  blockether/vis/_data/schema/provider.json,sha256=iJeEFke3pRgs6ugkgDIokiMIRiUlVDubYn4aWI0GmSQ,10870
89
89
  blockether/vis/_data/schema/symbol.json,sha256=RiOf2vdWcuQGzKwCmCZrWQui6n2k4fVfhBRs1-PPnlw,5754
90
90
  blockether/vis/_data/schema/toggle.json,sha256=RJvAS0Hh8gjyPFcnnYR7GiN9MMf36YHd8IVZ5uxHA94,7829
91
91
  blockether/vis/_data/schema/view.json,sha256=RW9KleUYlwfl0o1O5gPR42gQ4iBTq7w2R4XHyKAw8TE,137563
92
- blockether/vis/engine/release-tag,sha256=1y6zUXMlOluFENQgM_xs213QnckInX13tZ8CGauUNj0,46
93
- vis_agent-0.5.22.dev9311.dist-info/METADATA,sha256=e8G8KQsDStfPwN9bbQ2SQvR1OVwf_k1cApLQsvIXlYg,3092
94
- vis_agent-0.5.22.dev9311.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
95
- vis_agent-0.5.22.dev9311.dist-info/licenses/LICENSE,sha256=Ds8Buu9Jm7CYdc8ZhLv4kvaHexBDIuDngh1UmIvHhRs,10766
96
- vis_agent-0.5.22.dev9311.dist-info/RECORD,,
92
+ blockether/vis/engine/release-tag,sha256=HOpoplAP0KN_VkQ2b0QZXEi46yeJNoMBmJtPc9hl-_w,46
93
+ vis_agent-0.5.22.dev9332.dist-info/METADATA,sha256=BDGycgBblQBrErkkObgPX3lkWZWTiM2QGPAtnP_N5Hs,3098
94
+ vis_agent-0.5.22.dev9332.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
95
+ vis_agent-0.5.22.dev9332.dist-info/licenses/LICENSE,sha256=Ds8Buu9Jm7CYdc8ZhLv4kvaHexBDIuDngh1UmIvHhRs,10766
96
+ vis_agent-0.5.22.dev9332.dist-info/RECORD,,