Skip to content

native

Class info

Classes

Name Children Inherits
ApprovalOption
pyt3client.native.models
A choice an approval request offers (`ProviderApprovalOption`).
    DomainEvent
    pyt3client.native.models
    A thread event (`OrchestrationV2DomainEvent`); `payload` depends on `type`.
      NativeItemRef
      pyt3client.native.models
      The provider's own id of what an item stands for (`OrchestrationV2ProviderRef`).
        RpcSocket
        pyt3client.native.rpc
        Requests and streams over one Effect RPC WebSocket; many may run at once.
          Run
          pyt3client.native.models
          A run of a thread (`run.created` / `run.updated`).
            RuntimeRequest
            pyt3client.native.models
            An approval or question a provider waits on (`OrchestrationV2RuntimeRequest`).
              T3NativeClient
              pyt3client.native.client
              One socket to an environment's native RPC; subscriptions and commands share it.
                ThreadEvent
                pyt3client.native.models
                One event of the thread, in `sequence` order.
                  ThreadSnapshot
                  pyt3client.native.models
                  The thread as it is when the subscription starts; events continue after it.
                    ThreadSynchronized
                    pyt3client.native.models
                    The subscription caught up with the thread.
                      TurnItem
                      pyt3client.native.models
                      A timeline row (`OrchestrationV2TurnItem`): a message, reasoning, tool work, a request.
                        UnknownStreamItem
                        pyt3client.native.models
                        A stream item of a kind this client does not know (newer servers).

                          🛈 DocStrings

                          T3 Code's native surface: the WebSocket RPC its web, desktop and mobile clients use.

                          Unlike /mcp, it streams a thread's events as they happen and can answer approvals. It needs its own sign-in (see sign_in_native); install the native extra (pip install pyt3client[native]) for the WebSocket dependency.

                          from pyt3client.native import T3NativeClient, sign_in_native
                          
                          credentials = await sign_in_native("http://127.0.0.1:3773", "PAIRING-TOKEN")
                          async with T3NativeClient.from_credentials(credentials) as t3:
                              async for item in t3.subscribe_thread(thread_id):
                                  ...
                          

                          ApprovalDecision

                          ApprovalDecision = Literal['accept', 'acceptForSession', 'acceptAlways', 'decline', 'cancel']
                          

                          ProviderApprovalDecision (upstream packages/contracts/src/providerPolicy.ts).

                          ApprovalOption

                          Bases: _Open

                          A choice an approval request offers (ProviderApprovalOption).

                          Source code in src/pyt3client/native/models.py
                          34
                          35
                          36
                          37
                          38
                          39
                          class ApprovalOption(_Open):
                              """A choice an approval request offers (`ProviderApprovalOption`)."""
                          
                              decision: ApprovalDecision
                              label: str
                              warning: str | None = None
                          

                          DomainEvent

                          Bases: _Open

                          A thread event (OrchestrationV2DomainEvent); payload depends on type.

                          Source code in src/pyt3client/native/models.py
                          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
                          class DomainEvent(_Open):
                              """A thread event (`OrchestrationV2DomainEvent`); `payload` depends on `type`."""
                          
                              type: str
                              thread_id: str | None = None
                              run_id: str | None = None
                              payload: dict[str, JsonValue]
                          
                              def turn_item(self) -> TurnItem | None:
                                  """The item of a `turn-item.updated` event."""
                                  if self.type != "turn-item.updated":
                                      return None
                                  return TurnItem.model_validate(self.payload)
                          
                              def run(self) -> Run | None:
                                  """The run of a `run.created` or `run.updated` event."""
                                  if self.type not in ("run.created", "run.updated"):
                                      return None
                                  return Run.model_validate(self.payload)
                          
                              def runtime_request(self) -> RuntimeRequest | None:
                                  """The request of a `runtime-request.updated` event."""
                                  if self.type != "runtime-request.updated":
                                      return None
                                  return RuntimeRequest.model_validate(self.payload)
                          

                          run

                          run() -> Run | None
                          

                          The run of a run.created or run.updated event.

                          Source code in src/pyt3client/native/models.py
                          122
                          123
                          124
                          125
                          126
                          def run(self) -> Run | None:
                              """The run of a `run.created` or `run.updated` event."""
                              if self.type not in ("run.created", "run.updated"):
                                  return None
                              return Run.model_validate(self.payload)
                          

                          runtime_request

                          runtime_request() -> RuntimeRequest | None
                          

                          The request of a runtime-request.updated event.

                          Source code in src/pyt3client/native/models.py
                          128
                          129
                          130
                          131
                          132
                          def runtime_request(self) -> RuntimeRequest | None:
                              """The request of a `runtime-request.updated` event."""
                              if self.type != "runtime-request.updated":
                                  return None
                              return RuntimeRequest.model_validate(self.payload)
                          

                          turn_item

                          turn_item() -> TurnItem | None
                          

                          The item of a turn-item.updated event.

                          Source code in src/pyt3client/native/models.py
                          116
                          117
                          118
                          119
                          120
                          def turn_item(self) -> TurnItem | None:
                              """The item of a `turn-item.updated` event."""
                              if self.type != "turn-item.updated":
                                  return None
                              return TurnItem.model_validate(self.payload)
                          

                          NativeItemRef

                          Bases: _Open

                          The provider's own id of what an item stands for (OrchestrationV2ProviderRef).

                          An approval request shares it with the tool call it is about.

                          Source code in src/pyt3client/native/models.py
                          42
                          43
                          44
                          45
                          46
                          47
                          48
                          49
                          class NativeItemRef(_Open):
                              """The provider's own id of what an item stands for (`OrchestrationV2ProviderRef`).
                          
                              An approval request shares it with the tool call it is about.
                              """
                          
                              driver: str
                              native_id: str
                          

                          RpcSocket

                          Requests and streams over one Effect RPC WebSocket; many may run at once.

                          Use RpcSocket.connect(url). Each request gets its own id; a reader task routes the server's frames to the request they answer.

                          Source code in src/pyt3client/native/rpc.py
                          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
                          class RpcSocket:
                              """Requests and streams over one Effect RPC WebSocket; many may run at once.
                          
                              Use `RpcSocket.connect(url)`. Each request gets its own id; a reader task routes
                              the server's frames to the request they answer.
                              """
                          
                              def __init__(self, connection: ClientConnection) -> None:
                                  self._connection = connection
                                  self._next_id = 0
                                  self._pending: dict[str, asyncio.Queue[_Delivery]] = {}
                                  self._closed: T3RpcError | None = None
                                  self._tasks: list[asyncio.Task[None]] = []
                          
                              @classmethod
                              @asynccontextmanager
                              async def connect(cls, url: str) -> AsyncGenerator[RpcSocket]:
                                  """Open the socket at `url` (with its `wsTicket`) and close it on exit."""
                                  from websockets.asyncio.client import connect
                          
                                  async with connect(url, max_size=None) as connection:
                                      socket = cls(connection)
                                      socket._tasks = [
                                          asyncio.create_task(socket._read(), name="t3-rpc-read"),
                                          asyncio.create_task(socket._keepalive(), name="t3-rpc-keepalive"),
                                      ]
                                      try:
                                          yield socket
                                      finally:
                                          for task in socket._tasks:
                                              task.cancel()
                                          for task in socket._tasks:
                                              with suppress(asyncio.CancelledError):
                                                  await task
                          
                              async def call(self, tag: str, payload: Mapping[str, JsonValue]) -> JsonValue:
                                  """Send a request and return its result.
                          
                                  Raises:
                                      T3RpcError: The request failed, or the socket closed before it ended.
                                  """
                                  request_id, queue = self._open()
                                  try:
                                      await self._request(request_id, tag, payload)
                                      while True:
                                          match await queue.get():
                                              case _Exit(exit=_ExitSuccess(value=value)):
                                                  return value
                                              case _Exit(exit=_ExitFailure() as failure):
                                                  raise T3RpcError(tag, _failure_message(failure), cause=_dump(failure))
                                              case _Closed(error=error):
                                                  raise error
                                              case _Chunk():
                                                  continue  # Not expected for a plain request
                                  finally:
                                      self._pending.pop(request_id, None)
                          
                              async def stream(self, tag: str, payload: Mapping[str, JsonValue]) -> AsyncIterator[JsonValue]:
                                  """Send a streaming request and yield its items until the server ends it.
                          
                                  Leaving the loop early interrupts the request on the server.
                          
                                  Raises:
                                      T3RpcError: The request failed, or the socket closed before it ended.
                                  """
                                  request_id, queue = self._open()
                                  ended = False
                                  try:
                                      await self._request(request_id, tag, payload)
                                      while True:
                                          match await queue.get():
                                              case _Chunk(values=values):
                                                  await self._send({"_tag": "Ack", "requestId": request_id})
                                                  for value in values:
                                                      yield value
                                              case _Exit(exit=_ExitSuccess()):
                                                  ended = True
                                                  return
                                              case _Exit(exit=_ExitFailure() as failure):
                                                  ended = True
                                                  raise T3RpcError(tag, _failure_message(failure), cause=_dump(failure))
                                              case _Closed(error=error):
                                                  ended = True
                                                  raise error
                                  finally:
                                      self._pending.pop(request_id, None)
                                      if not ended and self._closed is None:
                                          interrupt = {"_tag": "Interrupt", "requestId": request_id, "interruptors": []}
                                          with suppress(Exception):
                                              await self._send(interrupt)
                          
                              def _open(self) -> tuple[str, asyncio.Queue[_Delivery]]:
                                  if self._closed is not None:
                                      raise self._closed
                                  self._next_id += 1
                                  request_id = str(self._next_id)
                                  queue: asyncio.Queue[_Delivery] = asyncio.Queue()
                                  self._pending[request_id] = queue
                                  return request_id, queue
                          
                              async def _request(self, request_id: str, tag: str, payload: Mapping[str, JsonValue]) -> None:
                                  frame: dict[str, JsonValue] = {
                                      "_tag": "Request",
                                      "id": request_id,
                                      "tag": tag,
                                      "payload": dict(payload),
                                      "headers": [],
                                  }
                                  await self._send(frame)
                          
                              async def _send(self, frame: Mapping[str, JsonValue]) -> None:
                                  await self._connection.send(json.dumps(frame))
                          
                              async def _read(self) -> None:
                                  from websockets.exceptions import ConnectionClosed
                          
                                  error = T3RpcError("socket", "the connection closed")
                                  try:
                                      async for raw in self._connection:
                                          try:
                                              frame = _SERVER_FRAME.validate_json(raw)
                                          except ValidationError:
                                              logger.debug("Ignoring an unknown RPC frame: %s", str(raw)[:200])
                                              continue
                                          match frame:
                                              case _Chunk(request_id=request_id) | _Exit(request_id=request_id):
                                                  if queue := self._pending.get(str(request_id)):
                                                      queue.put_nowait(frame)
                                              case _Ping():
                                                  await self._send({"_tag": "Pong"})
                                              case _Pong():
                                                  pass
                                              case _Defect(defect=defect):
                                                  error = T3RpcError("socket", f"server defect: {json.dumps(defect)[:500]}")
                                                  break
                                              case _ProtocolError(error=protocol_error):
                                                  message = f"protocol error: {json.dumps(protocol_error)[:500]}"
                                                  error = T3RpcError("socket", message)
                                                  break
                                  except ConnectionClosed as closed:
                                      error = T3RpcError("socket", f"the connection closed: {closed}")
                                  finally:
                                      self._closed = error
                                      for queue in self._pending.values():
                                          queue.put_nowait(_Closed(error))
                          
                              async def _keepalive(self) -> None:
                                  while self._closed is None:
                                      await asyncio.sleep(KEEPALIVE_SECONDS)
                                      with suppress(Exception):
                                          await self._send({"_tag": "Ping"})
                          

                          call async

                          call(tag: str, payload: Mapping[str, JsonValue]) -> JsonValue
                          

                          Send a request and return its result.

                          Raises:

                          Type Description
                          T3RpcError

                          The request failed, or the socket closed before it ended.

                          Source code in src/pyt3client/native/rpc.py
                          171
                          172
                          173
                          174
                          175
                          176
                          177
                          178
                          179
                          180
                          181
                          182
                          183
                          184
                          185
                          186
                          187
                          188
                          189
                          190
                          191
                          async def call(self, tag: str, payload: Mapping[str, JsonValue]) -> JsonValue:
                              """Send a request and return its result.
                          
                              Raises:
                                  T3RpcError: The request failed, or the socket closed before it ended.
                              """
                              request_id, queue = self._open()
                              try:
                                  await self._request(request_id, tag, payload)
                                  while True:
                                      match await queue.get():
                                          case _Exit(exit=_ExitSuccess(value=value)):
                                              return value
                                          case _Exit(exit=_ExitFailure() as failure):
                                              raise T3RpcError(tag, _failure_message(failure), cause=_dump(failure))
                                          case _Closed(error=error):
                                              raise error
                                          case _Chunk():
                                              continue  # Not expected for a plain request
                              finally:
                                  self._pending.pop(request_id, None)
                          

                          connect async classmethod

                          connect(url: str) -> AsyncGenerator[RpcSocket]
                          

                          Open the socket at url (with its wsTicket) and close it on exit.

                          Source code in src/pyt3client/native/rpc.py
                          150
                          151
                          152
                          153
                          154
                          155
                          156
                          157
                          158
                          159
                          160
                          161
                          162
                          163
                          164
                          165
                          166
                          167
                          168
                          169
                          @classmethod
                          @asynccontextmanager
                          async def connect(cls, url: str) -> AsyncGenerator[RpcSocket]:
                              """Open the socket at `url` (with its `wsTicket`) and close it on exit."""
                              from websockets.asyncio.client import connect
                          
                              async with connect(url, max_size=None) as connection:
                                  socket = cls(connection)
                                  socket._tasks = [
                                      asyncio.create_task(socket._read(), name="t3-rpc-read"),
                                      asyncio.create_task(socket._keepalive(), name="t3-rpc-keepalive"),
                                  ]
                                  try:
                                      yield socket
                                  finally:
                                      for task in socket._tasks:
                                          task.cancel()
                                      for task in socket._tasks:
                                          with suppress(asyncio.CancelledError):
                                              await task
                          

                          stream async

                          stream(tag: str, payload: Mapping[str, JsonValue]) -> AsyncIterator[JsonValue]
                          

                          Send a streaming request and yield its items until the server ends it.

                          Leaving the loop early interrupts the request on the server.

                          Raises:

                          Type Description
                          T3RpcError

                          The request failed, or the socket closed before it ended.

                          Source code in src/pyt3client/native/rpc.py
                          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
                          async def stream(self, tag: str, payload: Mapping[str, JsonValue]) -> AsyncIterator[JsonValue]:
                              """Send a streaming request and yield its items until the server ends it.
                          
                              Leaving the loop early interrupts the request on the server.
                          
                              Raises:
                                  T3RpcError: The request failed, or the socket closed before it ended.
                              """
                              request_id, queue = self._open()
                              ended = False
                              try:
                                  await self._request(request_id, tag, payload)
                                  while True:
                                      match await queue.get():
                                          case _Chunk(values=values):
                                              await self._send({"_tag": "Ack", "requestId": request_id})
                                              for value in values:
                                                  yield value
                                          case _Exit(exit=_ExitSuccess()):
                                              ended = True
                                              return
                                          case _Exit(exit=_ExitFailure() as failure):
                                              ended = True
                                              raise T3RpcError(tag, _failure_message(failure), cause=_dump(failure))
                                          case _Closed(error=error):
                                              ended = True
                                              raise error
                              finally:
                                  self._pending.pop(request_id, None)
                                  if not ended and self._closed is None:
                                      interrupt = {"_tag": "Interrupt", "requestId": request_id, "interruptors": []}
                                      with suppress(Exception):
                                          await self._send(interrupt)
                          

                          Run

                          Bases: _Open

                          A run of a thread (run.created / run.updated).

                          Source code in src/pyt3client/native/models.py
                          88
                          89
                          90
                          91
                          92
                          93
                          94
                          95
                          class Run(_Open):
                              """A run of a thread (`run.created` / `run.updated`)."""
                          
                              id: str
                              thread_id: str
                              status: str
                              """`preparing`, `queued`, `starting`, `running`, `waiting`, `completed`,
                              `interrupted`, `failed`, `cancelled` or `rolled_back`."""
                          

                          status instance-attribute

                          status: str
                          

                          preparing, queued, starting, running, waiting, completed, interrupted, failed, cancelled or rolled_back.

                          RuntimeRequest

                          Bases: _Open

                          An approval or question a provider waits on (OrchestrationV2RuntimeRequest).

                          Source code in src/pyt3client/native/models.py
                           98
                           99
                          100
                          101
                          102
                          103
                          104
                          105
                          class RuntimeRequest(_Open):
                              """An approval or question a provider waits on (`OrchestrationV2RuntimeRequest`)."""
                          
                              id: str
                              kind: str
                              """A `ProviderRequestKind`, or `dynamic_tool_call`, `user_input`, `auth_refresh`."""
                              status: Literal["pending", "resolved", "expired", "cancelled"]
                              decision: ApprovalDecision | None = None
                          

                          kind instance-attribute

                          kind: str
                          

                          A ProviderRequestKind, or dynamic_tool_call, user_input, auth_refresh.

                          T3NativeClient

                          One socket to an environment's native RPC; subscriptions and commands share it.

                          async with T3NativeClient.from_credentials(credentials) as t3:
                              async for item in t3.subscribe_thread(thread_id):
                                  ...
                          
                          Source code in src/pyt3client/native/client.py
                          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
                          class T3NativeClient:
                              """One socket to an environment's native RPC; subscriptions and commands share it.
                          
                              ```python
                              async with T3NativeClient.from_credentials(credentials) as t3:
                                  async for item in t3.subscribe_thread(thread_id):
                                      ...
                              ```
                              """
                          
                              def __init__(
                                  self, base_url: str, access_token: str, *, http_client: httpx.AsyncClient | None = None
                              ) -> None:
                                  self.base_url = _origin(base_url)
                                  self._access_token = access_token
                                  self._http_client = http_client
                                  self._socket: RpcSocket | None = None
                                  self._connection: AbstractAsyncContextManager[RpcSocket] | None = None
                          
                              @classmethod
                              def from_credentials(
                                  cls, credentials: T3NativeCredentials, *, http_client: httpx.AsyncClient | None = None
                              ) -> Self:
                                  return cls(
                                      credentials.base_url,
                                      credentials.access_token.get_secret_value(),
                                      http_client=http_client,
                                  )
                          
                              async def __aenter__(self) -> Self:
                                  url = await websocket_url(self.base_url, self._access_token, http_client=self._http_client)
                                  connection = RpcSocket.connect(url)
                                  self._socket = await connection.__aenter__()
                                  self._connection = connection
                                  return self
                          
                              async def __aexit__(
                                  self,
                                  exc_type: type[BaseException] | None,
                                  exc_val: BaseException | None,
                                  exc_tb: TracebackType | None,
                              ) -> None:
                                  if self._connection is not None:
                                      await self._connection.__aexit__(exc_type, exc_val, exc_tb)
                                  self._connection = self._socket = None
                          
                              @property
                              def socket(self) -> RpcSocket:
                                  """The open socket, for methods this client has no wrapper for."""
                                  if self._socket is None:
                                      msg = "T3NativeClient is not connected; use `async with`"
                                      raise RuntimeError(msg)
                                  return self._socket
                          
                              async def subscribe_thread(
                                  self, thread_id: str, *, after_sequence: int | None = None
                              ) -> AsyncIterator[ThreadStreamItem]:
                                  """The thread's snapshot, then its events as they happen (`subscribeThread`).
                          
                                  Args:
                                      thread_id: The thread to follow.
                                      after_sequence: Resume after this event (a snapshot's `snapshot_sequence`
                                          or an event's `sequence`) instead of starting with a snapshot.
                                  """
                                  payload: dict[str, JsonValue] = {"threadId": thread_id}
                                  if after_sequence is not None:
                                      payload["afterSequence"] = after_sequence
                                  async for value in self.socket.stream("orchestration.subscribeThread", payload):
                                      yield parse_stream_item(value)
                          
                              async def dispatch(self, command: Mapping[str, JsonValue]) -> int:
                                  """Run an orchestration command (`dispatchCommand`); returns its event sequence.
                          
                                  `command` is an `OrchestrationV2Command` (upstream `orchestrationV2.ts`), such
                                  as `{"type": "thread.interrupt", "threadId": ...}`; a `commandId` is added
                                  when missing.
                          
                                  Raises:
                                      T3RpcError: The command was refused.
                                  """
                                  payload = {"commandId": str(uuid4()), **command}
                                  result = await self.socket.call("orchestration.dispatchCommand", payload)
                                  try:
                                      return _Dispatched.model_validate(result).sequence
                                  except ValueError as error:
                                      msg = f"dispatchCommand: unexpected result {result!r}"
                                      raise T3ProtocolError(msg) from error
                          
                              async def respond_to_request(
                                  self,
                                  thread_id: str,
                                  request_id: str,
                                  *,
                                  decision: ApprovalDecision | None = None,
                                  answers: Mapping[str, JsonValue] | None = None,
                                  feedback: str | None = None,
                              ) -> int:
                                  """Answer an approval (`decision`) or a question (`answers`) a thread waits on.
                          
                                  Args:
                                      thread_id: The thread.
                                      request_id: The runtime request (`TurnItem.request_id`).
                                      decision: For approvals.
                                      answers: For questions: question id -> answer.
                                      feedback: Text sent along with the decision, where the provider takes it.
                                  """
                                  command: dict[str, JsonValue] = {
                                      "type": "runtime-request.respond",
                                      "threadId": thread_id,
                                      "requestId": request_id,
                                  }
                                  if decision is not None:
                                      command["decision"] = decision
                                  if answers is not None:
                                      command["answers"] = dict(answers)
                                  if feedback is not None:
                                      command["feedback"] = feedback
                                  return await self.dispatch(command)
                          

                          socket property

                          socket: RpcSocket
                          

                          The open socket, for methods this client has no wrapper for.

                          dispatch async

                          dispatch(command: Mapping[str, JsonValue]) -> int
                          

                          Run an orchestration command (dispatchCommand); returns its event sequence.

                          command is an OrchestrationV2Command (upstream orchestrationV2.ts), such as {"type": "thread.interrupt", "threadId": ...}; a commandId is added when missing.

                          Raises:

                          Type Description
                          T3RpcError

                          The command was refused.

                          Source code in src/pyt3client/native/client.py
                          214
                          215
                          216
                          217
                          218
                          219
                          220
                          221
                          222
                          223
                          224
                          225
                          226
                          227
                          228
                          229
                          230
                          async def dispatch(self, command: Mapping[str, JsonValue]) -> int:
                              """Run an orchestration command (`dispatchCommand`); returns its event sequence.
                          
                              `command` is an `OrchestrationV2Command` (upstream `orchestrationV2.ts`), such
                              as `{"type": "thread.interrupt", "threadId": ...}`; a `commandId` is added
                              when missing.
                          
                              Raises:
                                  T3RpcError: The command was refused.
                              """
                              payload = {"commandId": str(uuid4()), **command}
                              result = await self.socket.call("orchestration.dispatchCommand", payload)
                              try:
                                  return _Dispatched.model_validate(result).sequence
                              except ValueError as error:
                                  msg = f"dispatchCommand: unexpected result {result!r}"
                                  raise T3ProtocolError(msg) from error
                          

                          respond_to_request async

                          respond_to_request(
                              thread_id: str,
                              request_id: str,
                              *,
                              decision: ApprovalDecision | None = None,
                              answers: Mapping[str, JsonValue] | None = None,
                              feedback: str | None = None
                          ) -> int
                          

                          Answer an approval (decision) or a question (answers) a thread waits on.

                          Parameters:

                          Name Type Description Default
                          thread_id str

                          The thread.

                          required
                          request_id str

                          The runtime request (TurnItem.request_id).

                          required
                          decision ApprovalDecision | None

                          For approvals.

                          None
                          answers Mapping[str, JsonValue] | None

                          For questions: question id -> answer.

                          None
                          feedback str | None

                          Text sent along with the decision, where the provider takes it.

                          None
                          Source code in src/pyt3client/native/client.py
                          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
                          async def respond_to_request(
                              self,
                              thread_id: str,
                              request_id: str,
                              *,
                              decision: ApprovalDecision | None = None,
                              answers: Mapping[str, JsonValue] | None = None,
                              feedback: str | None = None,
                          ) -> int:
                              """Answer an approval (`decision`) or a question (`answers`) a thread waits on.
                          
                              Args:
                                  thread_id: The thread.
                                  request_id: The runtime request (`TurnItem.request_id`).
                                  decision: For approvals.
                                  answers: For questions: question id -> answer.
                                  feedback: Text sent along with the decision, where the provider takes it.
                              """
                              command: dict[str, JsonValue] = {
                                  "type": "runtime-request.respond",
                                  "threadId": thread_id,
                                  "requestId": request_id,
                              }
                              if decision is not None:
                                  command["decision"] = decision
                              if answers is not None:
                                  command["answers"] = dict(answers)
                              if feedback is not None:
                                  command["feedback"] = feedback
                              return await self.dispatch(command)
                          

                          subscribe_thread async

                          subscribe_thread(
                              thread_id: str, *, after_sequence: int | None = None
                          ) -> AsyncIterator[ThreadStreamItem]
                          

                          The thread's snapshot, then its events as they happen (subscribeThread).

                          Parameters:

                          Name Type Description Default
                          thread_id str

                          The thread to follow.

                          required
                          after_sequence int | None

                          Resume after this event (a snapshot's snapshot_sequence or an event's sequence) instead of starting with a snapshot.

                          None
                          Source code in src/pyt3client/native/client.py
                          198
                          199
                          200
                          201
                          202
                          203
                          204
                          205
                          206
                          207
                          208
                          209
                          210
                          211
                          212
                          async def subscribe_thread(
                              self, thread_id: str, *, after_sequence: int | None = None
                          ) -> AsyncIterator[ThreadStreamItem]:
                              """The thread's snapshot, then its events as they happen (`subscribeThread`).
                          
                              Args:
                                  thread_id: The thread to follow.
                                  after_sequence: Resume after this event (a snapshot's `snapshot_sequence`
                                      or an event's `sequence`) instead of starting with a snapshot.
                              """
                              payload: dict[str, JsonValue] = {"threadId": thread_id}
                              if after_sequence is not None:
                                  payload["afterSequence"] = after_sequence
                              async for value in self.socket.stream("orchestration.subscribeThread", payload):
                                  yield parse_stream_item(value)
                          

                          ThreadEvent

                          Bases: _Open

                          One event of the thread, in sequence order.

                          Source code in src/pyt3client/native/models.py
                          144
                          145
                          146
                          147
                          148
                          149
                          class ThreadEvent(_Open):
                              """One event of the thread, in `sequence` order."""
                          
                              kind: Literal["event"]
                              sequence: int
                              event: DomainEvent
                          

                          ThreadSnapshot

                          Bases: _Open

                          The thread as it is when the subscription starts; events continue after it.

                          Source code in src/pyt3client/native/models.py
                          135
                          136
                          137
                          138
                          139
                          140
                          141
                          class ThreadSnapshot(_Open):
                              """The thread as it is when the subscription starts; events continue after it."""
                          
                              kind: Literal["snapshot"]
                              snapshot_sequence: int
                              projection: dict[str, JsonValue]
                              """`OrchestrationV2ThreadProjection`: thread, runs, turn items, requests, ..."""
                          

                          projection instance-attribute

                          projection: dict[str, JsonValue]
                          

                          OrchestrationV2ThreadProjection: thread, runs, turn items, requests, ...

                          ThreadSynchronized

                          Bases: _Open

                          The subscription caught up with the thread.

                          Source code in src/pyt3client/native/models.py
                          152
                          153
                          154
                          155
                          class ThreadSynchronized(_Open):
                              """The subscription caught up with the thread."""
                          
                              kind: Literal["synchronized"]
                          

                          TurnItem

                          Bases: _Open

                          A timeline row (OrchestrationV2TurnItem): a message, reasoning, tool work, a request.

                          type is e.g. user_message, assistant_message, reasoning, command_execution, file_change, dynamic_tool, approval_request, user_input_request, checkpoint. status is one of idle, pending, running, waiting, completed, interrupted, failed, cancelled, rolled_back.

                          Source code in src/pyt3client/native/models.py
                          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
                          class TurnItem(_Open):
                              """A timeline row (`OrchestrationV2TurnItem`): a message, reasoning, tool work, a request.
                          
                              `type` is e.g. `user_message`, `assistant_message`, `reasoning`, `command_execution`,
                              `file_change`, `dynamic_tool`, `approval_request`, `user_input_request`,
                              `checkpoint`. `status` is one of `idle`, `pending`, `running`, `waiting`,
                              `completed`, `interrupted`, `failed`, `cancelled`, `rolled_back`.
                              """
                          
                              id: str
                              thread_id: str
                              run_id: str | None = None
                              type: str
                              status: str
                              title: str | None = None
                              text: str | None = None
                              """Text of message and reasoning items; complete once `streaming` is false."""
                              streaming: bool | None = None
                              native_item_ref: NativeItemRef | None = None
                              request_id: str | None = None
                              """For `approval_request` and `user_input_request`: the runtime request to answer."""
                              request_kind: str | None = None
                              """For `approval_request`: `command`, `file-read`, `file-change`, `mcp-elicitation`
                              or `permission` (`ProviderRequestKind`)."""
                              prompt: str | None = None
                              """For `approval_request`: what is to be approved, such as the command."""
                              reason: str | None = None
                              options: list[ApprovalOption] | None = None
                              """For `approval_request`: the decisions on offer, when the provider names them."""
                          
                              @property
                              def item_id(self) -> str:
                                  """The item's id, as `/mcp`'s thread reads name it (`itemId`)."""
                                  return self.id
                          

                          item_id property

                          item_id: str
                          

                          The item's id, as /mcp's thread reads name it (itemId).

                          options class-attribute instance-attribute

                          options: list[ApprovalOption] | None = None
                          

                          For approval_request: the decisions on offer, when the provider names them.

                          prompt class-attribute instance-attribute

                          prompt: str | None = None
                          

                          For approval_request: what is to be approved, such as the command.

                          request_id class-attribute instance-attribute

                          request_id: str | None = None
                          

                          For approval_request and user_input_request: the runtime request to answer.

                          request_kind class-attribute instance-attribute

                          request_kind: str | None = None
                          

                          For approval_request: command, file-read, file-change, mcp-elicitation or permission (ProviderRequestKind).

                          text class-attribute instance-attribute

                          text: str | None = None
                          

                          Text of message and reasoning items; complete once streaming is false.

                          UnknownStreamItem

                          Bases: _Open

                          A stream item of a kind this client does not know (newer servers).

                          Source code in src/pyt3client/native/models.py
                          158
                          159
                          160
                          161
                          class UnknownStreamItem(_Open):
                              """A stream item of a kind this client does not know (newer servers)."""
                          
                              kind: str
                          

                          parse_stream_item

                          parse_stream_item(value: JsonValue) -> ThreadStreamItem
                          

                          A subscribeThread stream value as a model.

                          Raises:

                          Type Description
                          ValidationError

                          A known kind with an unexpected shape.

                          Source code in src/pyt3client/native/models.py
                          167
                          168
                          169
                          170
                          171
                          172
                          173
                          174
                          175
                          176
                          177
                          178
                          179
                          180
                          181
                          182
                          def parse_stream_item(value: JsonValue) -> ThreadStreamItem:
                              """A `subscribeThread` stream value as a model.
                          
                              Raises:
                                  pydantic.ValidationError: A known kind with an unexpected shape.
                              """
                              kind = value.get("kind") if isinstance(value, dict) else None
                              match kind:
                                  case "snapshot":
                                      return ThreadSnapshot.model_validate(value)
                                  case "event":
                                      return ThreadEvent.model_validate(value)
                                  case "synchronized":
                                      return ThreadSynchronized.model_validate(value)
                                  case _:
                                      return UnknownStreamItem.model_validate(value)
                          

                          sign_in_native async

                          sign_in_native(
                              base_url: str,
                              pairing_token: str,
                              *,
                              label: str = "pyt3client",
                              scopes: Sequence[str] | None = None,
                              http_client: AsyncClient | None = None
                          ) -> T3NativeCredentials
                          

                          Exchange a one-time pairing token for a native bearer.

                          Parameters:

                          Name Type Description Default
                          base_url str

                          Environment origin, such as http://127.0.0.1:3773.

                          required
                          pairing_token str

                          The pairing token's credential (it can be used once).

                          required
                          label str

                          Client name shown in T3 Code under Settings -> Sharing & access.

                          'pyt3client'
                          scopes Sequence[str] | None

                          Scopes to ask for, at most those of the pairing token; all of them when omitted.

                          None
                          http_client AsyncClient | None

                          Client to reuse; a short-lived one is created otherwise.

                          None

                          Raises:

                          Type Description
                          T3AuthError

                          The pairing token was refused (used, expired or revoked).

                          Source code in src/pyt3client/native/client.py
                           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
                          async def sign_in_native(
                              base_url: str,
                              pairing_token: str,
                              *,
                              label: str = "pyt3client",
                              scopes: Sequence[str] | None = None,
                              http_client: httpx.AsyncClient | None = None,
                          ) -> T3NativeCredentials:
                              """Exchange a one-time pairing token for a native bearer.
                          
                              Args:
                                  base_url: Environment origin, such as `http://127.0.0.1:3773`.
                                  pairing_token: The pairing token's credential (it can be used once).
                                  label: Client name shown in T3 Code under Settings -> Sharing & access.
                                  scopes: Scopes to ask for, at most those of the pairing token; all of them
                                      when omitted.
                                  http_client: Client to reuse; a short-lived one is created otherwise.
                          
                              Raises:
                                  T3AuthError: The pairing token was refused (used, expired or revoked).
                              """
                              origin = _origin(base_url)
                              form = {
                                  "grant_type": _TOKEN_EXCHANGE,
                                  "subject_token": pairing_token.strip(),
                                  "subject_token_type": _BOOTSTRAP_TOKEN,
                                  "requested_token_type": _ACCESS_TOKEN,
                                  "client_label": label,
                                  "client_device_type": "bot",
                              }
                              if scopes:
                                  form["scope"] = " ".join(scopes)
                              async with _client(http_client) as client:
                                  response = await client.post(f"{origin}/oauth/token", data=form)
                              if response.status_code in (httpx.codes.BAD_REQUEST, httpx.codes.UNAUTHORIZED):
                                  msg = f"the pairing token was refused: {response.text[:300]}"
                                  raise T3AuthError(msg)
                              if response.status_code != httpx.codes.OK:
                                  msg = "native sign-in failed"
                                  raise T3HttpError(msg, status=response.status_code, body=response.text)
                              token = _TokenResponse.model_validate_json(response.content)
                              return T3NativeCredentials(
                                  base_url=origin,
                                  access_token=SecretStr(token.access_token),
                                  expires_at=datetime.now(UTC) + timedelta(seconds=token.expires_in),
                                  scopes=tuple(token.scope.split()),
                              )
                          

                          websocket_url async

                          websocket_url(base_url: str, access_token: str, *, http_client: AsyncClient | None = None) -> str
                          

                          The URL of a new socket, with a fresh one-time ticket.

                          Raises:

                          Type Description
                          T3AuthError

                          The bearer was refused (revoked, expired, or an MCP token).

                          Source code in src/pyt3client/native/client.py
                          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
                          async def websocket_url(
                              base_url: str, access_token: str, *, http_client: httpx.AsyncClient | None = None
                          ) -> str:
                              """The URL of a new socket, with a fresh one-time ticket.
                          
                              Raises:
                                  T3AuthError: The bearer was refused (revoked, expired, or an MCP token).
                              """
                              origin = _origin(base_url)
                              headers = {
                                  "authorization": f"Bearer {access_token}",
                                  "x-t3-orchestration-protocol": str(ORCHESTRATION_PROTOCOL),
                              }
                              async with _client(http_client) as client:
                                  response = await client.post(f"{origin}/api/auth/websocket-ticket", headers=headers)
                              if response.status_code == httpx.codes.UNAUTHORIZED:
                                  msg = (
                                      "the environment refused the native credential: it may be revoked or expired,"
                                      " or be an MCP token (the native surface needs its own sign-in)"
                                  )
                                  raise T3AuthError(msg)
                              if response.status_code != httpx.codes.OK:
                                  msg = "websocket ticket"
                                  raise T3HttpError(msg, status=response.status_code, body=response.text)
                              ticket = _Ticket.model_validate_json(response.content).ticket
                              scheme = "wss" if origin.startswith("https:") else "ws"
                              host = origin.split("://", 1)[1]
                              return (
                                  f"{scheme}://{host}/ws?orchestrationProtocol={ORCHESTRATION_PROTOCOL}"
                                  f"&wsTicket={quote(ticket, safe='')}"
                              )