gifos-agent 0.1.0__tar.gz
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.
- gifos_agent-0.1.0/LICENSE +24 -0
- gifos_agent-0.1.0/PKG-INFO +98 -0
- gifos_agent-0.1.0/README.md +77 -0
- gifos_agent-0.1.0/gifos_agent/__init__.py +21 -0
- gifos_agent-0.1.0/gifos_agent/meeting.py +378 -0
- gifos_agent-0.1.0/gifos_agent.egg-info/PKG-INFO +98 -0
- gifos_agent-0.1.0/gifos_agent.egg-info/SOURCES.txt +10 -0
- gifos_agent-0.1.0/gifos_agent.egg-info/dependency_links.txt +1 -0
- gifos_agent-0.1.0/gifos_agent.egg-info/top_level.txt +1 -0
- gifos_agent-0.1.0/pyproject.toml +33 -0
- gifos_agent-0.1.0/setup.cfg +4 -0
- gifos_agent-0.1.0/tests/test_meeting.py +208 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Crowd Concepts, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
The GifOS service, the gifos.app website and the GifOS meeting page are not
|
|
24
|
+
part of this package and are not covered by this license.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gifos-agent
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Join a GifOS meeting as an AI agent from Python: chat, lines, people, hand, voice and the room's sound (the seat is held by the @gifos-app/agent Node package).
|
|
5
|
+
Author: Crowd Concepts, Inc.
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://gifos.app
|
|
8
|
+
Project-URL: Source, https://github.com/nwcnwc/gifos-agent
|
|
9
|
+
Keywords: gifos,meeting,agent,ai,video call
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Framework :: AsyncIO
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Topic :: Communications :: Conferencing
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# gifos-agent (Python)
|
|
23
|
+
|
|
24
|
+
Join a GifOS meeting as an AI agent from Python: read and write chat, follow the room's lines, see who is there,
|
|
25
|
+
raise a hand, speak aloud, and hear the room.
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
pip install gifos-agent
|
|
29
|
+
npm install -g @gifos-app/agent # the Node seat this package drives (Node 22 or later)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## How it works
|
|
33
|
+
|
|
34
|
+
The seat is held by the Node package [`@gifos-app/agent`](https://www.npmjs.com/package/@gifos-app/agent) in a
|
|
35
|
+
child process (its `gifos-agent-stdio` program), driven over JSON lines. That seat opens the real GifOS meeting page
|
|
36
|
+
in agent mode in a browser already on this computer, so every room rule stays with the meeting: proof of work,
|
|
37
|
+
passwords, the host's orders, slow mode, blur and consent. This package has no dependencies beyond the Python
|
|
38
|
+
standard library.
|
|
39
|
+
|
|
40
|
+
What it needs:
|
|
41
|
+
|
|
42
|
+
- Python 3.9 or later.
|
|
43
|
+
- Node 22 or later, and the Node package. The seat is found in this order:
|
|
44
|
+
1. `GIFOS_AGENT_BRIDGE`: a path to the Node package's `src/stdio.js` (run with `node`, or `GIFOS_NODE`);
|
|
45
|
+
2. `gifos-agent-stdio` on `PATH` (`npm install -g @gifos-app/agent` puts it there);
|
|
46
|
+
3. otherwise `npx --yes -p @gifos-app/agent gifos-agent-stdio` (downloads it on first use).
|
|
47
|
+
- A Chrome or Edge on the computer. With neither, run `npx playwright install chromium` once, or set
|
|
48
|
+
`GIFOS_CHROME` to a Chrome or Chromium binary. Nothing downloads a browser by itself.
|
|
49
|
+
|
|
50
|
+
## Example
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
import asyncio
|
|
54
|
+
from gifos_agent import join
|
|
55
|
+
|
|
56
|
+
async def main():
|
|
57
|
+
async with await join("https://gifos.app/meet/abc", name="Ada", owner="Sam") as meet:
|
|
58
|
+
await meet.chat("Hello, I'm Ada, Sam's assistant.")
|
|
59
|
+
async for line in meet.lines(to_me=True):
|
|
60
|
+
await meet.chat("You said: " + line["text"])
|
|
61
|
+
|
|
62
|
+
asyncio.run(main())
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The name must say whose agent it is: `name="Ada (Sam's assistant)"`, or `name="Ada", owner="Sam"`. A room with a
|
|
66
|
+
password raises `MeetingError`: ask your human for it and pass `password=`; never guess it.
|
|
67
|
+
|
|
68
|
+
## What you get
|
|
69
|
+
|
|
70
|
+
- `await join(url, name=, owner=, password=, tts=, ...)` returns a `Meeting` once the seat is in.
|
|
71
|
+
- `meet.lines(to_me=, trusted=, from_admin=, kinds=)`: an async iterator of lines from now on (chat, others'
|
|
72
|
+
captions), each with the speaker, `kind`, `toMe` and `trust` (`own`, `trusted`, `unchecked`, `distrusted`:
|
|
73
|
+
captions are claims, not facts). Its own words never come back.
|
|
74
|
+
- `meet.transcript()`: the lines the seat already holds, its own spoken lines included.
|
|
75
|
+
- `meet.chat(text)`, `meet.hand(up)`, `meet.stage_ask()`, `meet.stage_leave()`, `meet.people()`, `meet.state()`,
|
|
76
|
+
`meet.app.run(id)`, `meet.app.data(...)`, `meet.app.room(...)`.
|
|
77
|
+
- `meet.say(text)`: speaks aloud. The page plays the voice and writes the text as the agent's own spoken line.
|
|
78
|
+
The voice comes from `tts=` given to `join()` (a function, plain or async, from text to WAV bytes or to
|
|
79
|
+
`(pcm, rate)`; `to_wav(pcm, rate)` helps), else from the Node seat's own voice (`npm install -g kokoro-js` beside
|
|
80
|
+
it). Without either, `say()` raises "No voice": answer in chat instead. It waits until the clip has played.
|
|
81
|
+
- `meet.audio_in()`: the room's sound as this seat hears it, as 20 ms frames of 16-bit mono PCM
|
|
82
|
+
(`async for frame in ear: frame["pcm"]`); `close()` it when done. Hearing marks the agent as taking notes, and a
|
|
83
|
+
host's "AI notes" setting is obeyed.
|
|
84
|
+
- `meet.on(event, fn)`: `joined`, `people`, `speaking`, `line`, `hand`, `stage`, `app`, `host`, `left`, ...
|
|
85
|
+
- `meet.call(name, args)`: any call of the meeting's agent contract. A refused call raises `MeetingError` with the
|
|
86
|
+
meeting's own sentence, ready to show a person.
|
|
87
|
+
- `meet.leave()` (or leaving the `async with` block) says goodbye and ends the seat.
|
|
88
|
+
|
|
89
|
+
Joining with no browser (`core=True`) is not available yet: the seat refuses it with a sentence, raised as
|
|
90
|
+
`MeetingError`.
|
|
91
|
+
|
|
92
|
+
`say()` with no `tts=` and `audio_in()` need `@gifos-app/agent` 0.2.1 or later.
|
|
93
|
+
|
|
94
|
+
## Tests
|
|
95
|
+
|
|
96
|
+
`python3 -m unittest discover -s python/tests` (from the repository root; no network, no meeting).
|
|
97
|
+
|
|
98
|
+
MIT licensed. The GifOS service, the gifos.app website and the meeting page are not part of this package.
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# gifos-agent (Python)
|
|
2
|
+
|
|
3
|
+
Join a GifOS meeting as an AI agent from Python: read and write chat, follow the room's lines, see who is there,
|
|
4
|
+
raise a hand, speak aloud, and hear the room.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
pip install gifos-agent
|
|
8
|
+
npm install -g @gifos-app/agent # the Node seat this package drives (Node 22 or later)
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## How it works
|
|
12
|
+
|
|
13
|
+
The seat is held by the Node package [`@gifos-app/agent`](https://www.npmjs.com/package/@gifos-app/agent) in a
|
|
14
|
+
child process (its `gifos-agent-stdio` program), driven over JSON lines. That seat opens the real GifOS meeting page
|
|
15
|
+
in agent mode in a browser already on this computer, so every room rule stays with the meeting: proof of work,
|
|
16
|
+
passwords, the host's orders, slow mode, blur and consent. This package has no dependencies beyond the Python
|
|
17
|
+
standard library.
|
|
18
|
+
|
|
19
|
+
What it needs:
|
|
20
|
+
|
|
21
|
+
- Python 3.9 or later.
|
|
22
|
+
- Node 22 or later, and the Node package. The seat is found in this order:
|
|
23
|
+
1. `GIFOS_AGENT_BRIDGE`: a path to the Node package's `src/stdio.js` (run with `node`, or `GIFOS_NODE`);
|
|
24
|
+
2. `gifos-agent-stdio` on `PATH` (`npm install -g @gifos-app/agent` puts it there);
|
|
25
|
+
3. otherwise `npx --yes -p @gifos-app/agent gifos-agent-stdio` (downloads it on first use).
|
|
26
|
+
- A Chrome or Edge on the computer. With neither, run `npx playwright install chromium` once, or set
|
|
27
|
+
`GIFOS_CHROME` to a Chrome or Chromium binary. Nothing downloads a browser by itself.
|
|
28
|
+
|
|
29
|
+
## Example
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
import asyncio
|
|
33
|
+
from gifos_agent import join
|
|
34
|
+
|
|
35
|
+
async def main():
|
|
36
|
+
async with await join("https://gifos.app/meet/abc", name="Ada", owner="Sam") as meet:
|
|
37
|
+
await meet.chat("Hello, I'm Ada, Sam's assistant.")
|
|
38
|
+
async for line in meet.lines(to_me=True):
|
|
39
|
+
await meet.chat("You said: " + line["text"])
|
|
40
|
+
|
|
41
|
+
asyncio.run(main())
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The name must say whose agent it is: `name="Ada (Sam's assistant)"`, or `name="Ada", owner="Sam"`. A room with a
|
|
45
|
+
password raises `MeetingError`: ask your human for it and pass `password=`; never guess it.
|
|
46
|
+
|
|
47
|
+
## What you get
|
|
48
|
+
|
|
49
|
+
- `await join(url, name=, owner=, password=, tts=, ...)` returns a `Meeting` once the seat is in.
|
|
50
|
+
- `meet.lines(to_me=, trusted=, from_admin=, kinds=)`: an async iterator of lines from now on (chat, others'
|
|
51
|
+
captions), each with the speaker, `kind`, `toMe` and `trust` (`own`, `trusted`, `unchecked`, `distrusted`:
|
|
52
|
+
captions are claims, not facts). Its own words never come back.
|
|
53
|
+
- `meet.transcript()`: the lines the seat already holds, its own spoken lines included.
|
|
54
|
+
- `meet.chat(text)`, `meet.hand(up)`, `meet.stage_ask()`, `meet.stage_leave()`, `meet.people()`, `meet.state()`,
|
|
55
|
+
`meet.app.run(id)`, `meet.app.data(...)`, `meet.app.room(...)`.
|
|
56
|
+
- `meet.say(text)`: speaks aloud. The page plays the voice and writes the text as the agent's own spoken line.
|
|
57
|
+
The voice comes from `tts=` given to `join()` (a function, plain or async, from text to WAV bytes or to
|
|
58
|
+
`(pcm, rate)`; `to_wav(pcm, rate)` helps), else from the Node seat's own voice (`npm install -g kokoro-js` beside
|
|
59
|
+
it). Without either, `say()` raises "No voice": answer in chat instead. It waits until the clip has played.
|
|
60
|
+
- `meet.audio_in()`: the room's sound as this seat hears it, as 20 ms frames of 16-bit mono PCM
|
|
61
|
+
(`async for frame in ear: frame["pcm"]`); `close()` it when done. Hearing marks the agent as taking notes, and a
|
|
62
|
+
host's "AI notes" setting is obeyed.
|
|
63
|
+
- `meet.on(event, fn)`: `joined`, `people`, `speaking`, `line`, `hand`, `stage`, `app`, `host`, `left`, ...
|
|
64
|
+
- `meet.call(name, args)`: any call of the meeting's agent contract. A refused call raises `MeetingError` with the
|
|
65
|
+
meeting's own sentence, ready to show a person.
|
|
66
|
+
- `meet.leave()` (or leaving the `async with` block) says goodbye and ends the seat.
|
|
67
|
+
|
|
68
|
+
Joining with no browser (`core=True`) is not available yet: the seat refuses it with a sentence, raised as
|
|
69
|
+
`MeetingError`.
|
|
70
|
+
|
|
71
|
+
`say()` with no `tts=` and `audio_in()` need `@gifos-app/agent` 0.2.1 or later.
|
|
72
|
+
|
|
73
|
+
## Tests
|
|
74
|
+
|
|
75
|
+
`python3 -m unittest discover -s python/tests` (from the repository root; no network, no meeting).
|
|
76
|
+
|
|
77
|
+
MIT licensed. The GifOS service, the gifos.app website and the meeting page are not part of this package.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""gifos-agent: join a GifOS meeting as an AI agent, from Python.
|
|
2
|
+
|
|
3
|
+
The seat itself is held by the Node package (@gifos-app/agent) in a child process, driven over JSON lines (its
|
|
4
|
+
gifos-agent-stdio program). That child drives the real meeting page in a browser already on this computer, so every
|
|
5
|
+
room rule stays with the meeting: chat, lines, people, hands, the Stage, apps, voice (say) and the room's sound
|
|
6
|
+
(audio_in).
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
from gifos_agent import join
|
|
10
|
+
|
|
11
|
+
async def main():
|
|
12
|
+
async with await join("https://gifos.app/meet/abc", name="Ada (Sam's assistant)") as meet:
|
|
13
|
+
async for line in meet.lines(to_me=True):
|
|
14
|
+
await meet.chat("You said: " + line["text"])
|
|
15
|
+
|
|
16
|
+
asyncio.run(main())
|
|
17
|
+
"""
|
|
18
|
+
from .meeting import Meeting, MeetingError, join, bridge_command, to_wav
|
|
19
|
+
|
|
20
|
+
__version__ = "0.1.0"
|
|
21
|
+
__all__ = ["Meeting", "MeetingError", "join", "bridge_command", "to_wav", "__version__"]
|
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
"""A meeting seat held by a gifos-agent-stdio child process (see the Node package's src/stdio.js)."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import base64
|
|
4
|
+
import inspect
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import struct
|
|
10
|
+
import wave
|
|
11
|
+
|
|
12
|
+
__all__ = ["Meeting", "MeetingError", "join", "bridge_command", "to_wav"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MeetingError(Exception):
|
|
16
|
+
"""The meeting's own sentence for a call it refused, ready to show a person."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def bridge_command():
|
|
20
|
+
"""The command that starts the seat: GIFOS_AGENT_BRIDGE (a path to src/stdio.js, run with node), else the
|
|
21
|
+
gifos-agent-stdio program on PATH (npm install -g @gifos-app/agent), else npx."""
|
|
22
|
+
path = os.environ.get("GIFOS_AGENT_BRIDGE")
|
|
23
|
+
if path:
|
|
24
|
+
return [os.environ.get("GIFOS_NODE", "node"), path]
|
|
25
|
+
exe = shutil.which("gifos-agent-stdio")
|
|
26
|
+
if exe:
|
|
27
|
+
return [exe]
|
|
28
|
+
return ["npx", "--yes", "-p", "@gifos-app/agent", "gifos-agent-stdio"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def to_wav(pcm, rate=24000):
|
|
32
|
+
"""Mono 16-bit PCM (bytes, little-endian, or a sequence of ints) as a WAV file's bytes: what say() plays."""
|
|
33
|
+
if not isinstance(pcm, (bytes, bytearray, memoryview)):
|
|
34
|
+
pcm = struct.pack("<%dh" % len(pcm), *[max(-32768, min(32767, int(x))) for x in pcm])
|
|
35
|
+
buf = io.BytesIO()
|
|
36
|
+
with wave.open(buf, "wb") as w:
|
|
37
|
+
w.setnchannels(1)
|
|
38
|
+
w.setsampwidth(2)
|
|
39
|
+
w.setframerate(int(rate))
|
|
40
|
+
w.writeframes(bytes(pcm))
|
|
41
|
+
return buf.getvalue()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _line_matches(line, to_me=False, trusted=False, from_admin=False, kinds=None):
|
|
45
|
+
"""What a lines() filter keeps: the Node package's lineMatches, rule for rule. Captions are self-reported, so
|
|
46
|
+
trusted keeps only the speaker's own engine or a line this page trusts."""
|
|
47
|
+
if not isinstance(line, dict) or line.get("final") is False:
|
|
48
|
+
return False
|
|
49
|
+
kind = line.get("kind")
|
|
50
|
+
if kinds and kind not in kinds:
|
|
51
|
+
return False
|
|
52
|
+
if not kinds and kind in ("spoken", "system"):
|
|
53
|
+
return False # never its own words back
|
|
54
|
+
if line.get("mine"):
|
|
55
|
+
return False
|
|
56
|
+
if to_me and not line.get("toMe"):
|
|
57
|
+
return False
|
|
58
|
+
if from_admin and not line.get("fromAdmin"):
|
|
59
|
+
return False
|
|
60
|
+
if trusted and kind != "chat" and line.get("trust") not in ("own", "trusted"):
|
|
61
|
+
return False
|
|
62
|
+
return True
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class _AudioIn:
|
|
66
|
+
"""The room's sound as this seat hears it: an async iterator of {"pcm": bytes (16-bit mono), "rate", "ts"}, 20 ms a
|
|
67
|
+
frame. Ends when closed or when the meeting does."""
|
|
68
|
+
|
|
69
|
+
def __init__(self, meet, port, info):
|
|
70
|
+
self._m = meet
|
|
71
|
+
self.id = port
|
|
72
|
+
self.info = info
|
|
73
|
+
self._q = asyncio.Queue()
|
|
74
|
+
|
|
75
|
+
def _push(self, item):
|
|
76
|
+
self._q.put_nowait(item)
|
|
77
|
+
|
|
78
|
+
def __aiter__(self):
|
|
79
|
+
return self
|
|
80
|
+
|
|
81
|
+
async def __anext__(self):
|
|
82
|
+
item = await self._q.get()
|
|
83
|
+
if item is None:
|
|
84
|
+
raise StopAsyncIteration
|
|
85
|
+
return item
|
|
86
|
+
|
|
87
|
+
async def close(self):
|
|
88
|
+
if self._m._ports.pop(self.id, None) is None:
|
|
89
|
+
return
|
|
90
|
+
self._q.put_nowait(None)
|
|
91
|
+
if not self._m.closed:
|
|
92
|
+
try:
|
|
93
|
+
await self._m.call("audio.in.close", {"port": self.id})
|
|
94
|
+
except MeetingError:
|
|
95
|
+
pass
|
|
96
|
+
|
|
97
|
+
async def __aenter__(self):
|
|
98
|
+
return self
|
|
99
|
+
|
|
100
|
+
async def __aexit__(self, *exc):
|
|
101
|
+
await self.close()
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class _App:
|
|
105
|
+
def __init__(self, meet):
|
|
106
|
+
self._m = meet
|
|
107
|
+
|
|
108
|
+
async def run(self, app_id):
|
|
109
|
+
return await self._m.call("app.run", {"id": app_id})
|
|
110
|
+
|
|
111
|
+
async def stop(self):
|
|
112
|
+
return await self._m.call("app.stop")
|
|
113
|
+
|
|
114
|
+
async def room(self, op, args=None):
|
|
115
|
+
"""The shared app's people and gifos.room session: room("state"), room("join"), room("move", {...})."""
|
|
116
|
+
return (await self._m.call("app.room", {"op": op, "args": args or {}})).get("result")
|
|
117
|
+
|
|
118
|
+
async def data(self, op, collection, key=None, value=None):
|
|
119
|
+
"""The shared app's data, as the app reads and writes it: get, getAll, put, delete."""
|
|
120
|
+
return (await self._m.call("app.data", {"op": op, "collection": collection, "key": key, "value": value})).get("result")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class Meeting:
|
|
124
|
+
"""One agent seat. Every method is one call of the meeting page's gifosAgent contract."""
|
|
125
|
+
|
|
126
|
+
def __init__(self, proc, tts=None, cmd=()):
|
|
127
|
+
self._proc = proc
|
|
128
|
+
self._cmd = list(cmd)
|
|
129
|
+
self.joined = False
|
|
130
|
+
self._tts = tts
|
|
131
|
+
self._next = 0
|
|
132
|
+
self._waiting = {}
|
|
133
|
+
self._handlers = {}
|
|
134
|
+
self._queues = []
|
|
135
|
+
self._ports = {}
|
|
136
|
+
self._unclaimed = {} # frames of a port whose open answer is still on its way to audio_in()
|
|
137
|
+
self.closed = False
|
|
138
|
+
self.core = False
|
|
139
|
+
self.app = _App(self)
|
|
140
|
+
self._reader = asyncio.ensure_future(self._read())
|
|
141
|
+
|
|
142
|
+
async def _read(self):
|
|
143
|
+
try:
|
|
144
|
+
while True:
|
|
145
|
+
raw = await self._proc.stdout.readline()
|
|
146
|
+
if not raw:
|
|
147
|
+
break
|
|
148
|
+
try:
|
|
149
|
+
m = json.loads(raw)
|
|
150
|
+
except ValueError:
|
|
151
|
+
continue
|
|
152
|
+
if "event" in m:
|
|
153
|
+
self._event(m["event"] or {})
|
|
154
|
+
continue
|
|
155
|
+
fut = self._waiting.pop(m.get("id"), None)
|
|
156
|
+
if fut and not fut.done():
|
|
157
|
+
fut.set_result(m)
|
|
158
|
+
finally:
|
|
159
|
+
self._finish(self._seat_gone())
|
|
160
|
+
|
|
161
|
+
def _event(self, ev):
|
|
162
|
+
t, d = ev.get("type"), ev.get("data")
|
|
163
|
+
port = self._ports.get(d.get("port")) if isinstance(d, dict) else None
|
|
164
|
+
if t == "audio.in.frame" and isinstance(d, dict):
|
|
165
|
+
f = {"pcm": base64.b64decode(d.get("pcm") or ""), "rate": d.get("rate"), "ts": d.get("ts")}
|
|
166
|
+
if port:
|
|
167
|
+
port._push(f)
|
|
168
|
+
else: # the first frames can come in right behind the open's answer, before audio_in() files the port
|
|
169
|
+
self._unclaimed.setdefault(d.get("port"), []).append(f)
|
|
170
|
+
del self._unclaimed[d.get("port")][:-250]
|
|
171
|
+
return
|
|
172
|
+
if port and t == "port.closed":
|
|
173
|
+
self._ports.pop(port.id, None)
|
|
174
|
+
port._push(None)
|
|
175
|
+
return
|
|
176
|
+
calls = [(fn, d) for fn in self._handlers.get(t, ())] + [(fn, ev) for fn in self._handlers.get("*", ())]
|
|
177
|
+
for fn, arg in calls:
|
|
178
|
+
try:
|
|
179
|
+
fn(arg)
|
|
180
|
+
except Exception: # a handler's fault is its own
|
|
181
|
+
pass
|
|
182
|
+
if t == "line":
|
|
183
|
+
for q, flt in list(self._queues):
|
|
184
|
+
if _line_matches(d, **flt):
|
|
185
|
+
q.put_nowait(d)
|
|
186
|
+
if t == "left":
|
|
187
|
+
self._finish()
|
|
188
|
+
|
|
189
|
+
def _seat_gone(self):
|
|
190
|
+
if self.joined:
|
|
191
|
+
return "The meeting seat closed."
|
|
192
|
+
return ("The GifOS agent seat (" + " ".join(self._cmd) + ") stopped before joining. It needs Node 22 or later and "
|
|
193
|
+
"the @gifos-app/agent package (npm install -g @gifos-app/agent, or GIFOS_AGENT_BRIDGE set to its src/stdio.js); "
|
|
194
|
+
"its own error is printed above.")
|
|
195
|
+
|
|
196
|
+
def _finish(self, why="The meeting seat closed."):
|
|
197
|
+
if self.closed:
|
|
198
|
+
return
|
|
199
|
+
self.closed = True
|
|
200
|
+
for q, _ in self._queues:
|
|
201
|
+
q.put_nowait(None)
|
|
202
|
+
for p in list(self._ports.values()):
|
|
203
|
+
p._push(None)
|
|
204
|
+
self._ports.clear()
|
|
205
|
+
for fut in self._waiting.values():
|
|
206
|
+
if not fut.done():
|
|
207
|
+
fut.set_exception(MeetingError(why))
|
|
208
|
+
self._waiting.clear()
|
|
209
|
+
|
|
210
|
+
async def _send(self, msg):
|
|
211
|
+
if self.closed:
|
|
212
|
+
raise MeetingError("This meeting is closed.")
|
|
213
|
+
self._next += 1
|
|
214
|
+
msg["id"] = self._next
|
|
215
|
+
fut = asyncio.get_running_loop().create_future()
|
|
216
|
+
self._waiting[self._next] = fut
|
|
217
|
+
try:
|
|
218
|
+
self._proc.stdin.write((json.dumps(msg) + "\n").encode())
|
|
219
|
+
await self._proc.stdin.drain()
|
|
220
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
221
|
+
self._waiting.pop(self._next, None)
|
|
222
|
+
raise MeetingError(self._seat_gone()) from None
|
|
223
|
+
r = await fut
|
|
224
|
+
if not r.get("ok"):
|
|
225
|
+
raise MeetingError(r.get("error") or "The meeting page did not answer.")
|
|
226
|
+
return r
|
|
227
|
+
|
|
228
|
+
async def call(self, name, args=None):
|
|
229
|
+
"""Any call of the contract by name, e.g. call("hand", {"up": True}). Returns the page's answer."""
|
|
230
|
+
return (await self._send({"call": name, "args": args or {}})).get("answer") or {}
|
|
231
|
+
|
|
232
|
+
def on(self, event_type, fn):
|
|
233
|
+
"""fn(data) for every event of that type ("*": fn({type, data}) for all). Returns a function that removes it."""
|
|
234
|
+
self._handlers.setdefault(event_type, set()).add(fn)
|
|
235
|
+
return lambda: self._handlers.get(event_type, set()).discard(fn)
|
|
236
|
+
|
|
237
|
+
def lines(self, to_me=False, trusted=False, from_admin=False, kinds=None):
|
|
238
|
+
"""Lines said or typed from now on, filtered (to_me, trusted, from_admin, kinds such as ["chat"] or ["spoken"];
|
|
239
|
+
without kinds, chat and others' captions but never spoken/system lines). An async iterator that listens from the
|
|
240
|
+
moment it is made and ends when the meeting does."""
|
|
241
|
+
q = asyncio.Queue()
|
|
242
|
+
entry = (q, {"to_me": to_me, "trusted": trusted, "from_admin": from_admin, "kinds": kinds})
|
|
243
|
+
self._queues.append(entry)
|
|
244
|
+
return self._drain(q, entry)
|
|
245
|
+
|
|
246
|
+
async def _drain(self, q, entry):
|
|
247
|
+
try:
|
|
248
|
+
while True:
|
|
249
|
+
item = await q.get()
|
|
250
|
+
if item is None:
|
|
251
|
+
return
|
|
252
|
+
yield item
|
|
253
|
+
finally:
|
|
254
|
+
if entry in self._queues:
|
|
255
|
+
self._queues.remove(entry)
|
|
256
|
+
|
|
257
|
+
async def people(self):
|
|
258
|
+
return (await self.call("people")).get("people")
|
|
259
|
+
|
|
260
|
+
async def state(self):
|
|
261
|
+
return (await self.call("state")).get("state")
|
|
262
|
+
|
|
263
|
+
async def chat(self, text):
|
|
264
|
+
return await self.call("chat", {"text": str(text)})
|
|
265
|
+
|
|
266
|
+
async def hand(self, up=True):
|
|
267
|
+
return await self.call("hand", {"up": bool(up)})
|
|
268
|
+
|
|
269
|
+
async def stage_ask(self):
|
|
270
|
+
return await self.call("stage.ask")
|
|
271
|
+
|
|
272
|
+
async def stage_leave(self):
|
|
273
|
+
return await self.call("stage.leave")
|
|
274
|
+
|
|
275
|
+
async def transcript(self, since=0):
|
|
276
|
+
"""The room's lines this seat already holds (chat, captions, the agent's own spoken lines), newest last."""
|
|
277
|
+
return (await self.call("lines", {"since": since})).get("lines") or []
|
|
278
|
+
|
|
279
|
+
async def say(self, text, interrupt="stop", wait=True):
|
|
280
|
+
"""Say text aloud. The page plays the voice and writes the text as this agent's own spoken line (captioned from
|
|
281
|
+
the text, not from speech). The voice: the tts given to join() (text -> WAV bytes, or (pcm, rate)), else the
|
|
282
|
+
Node seat's own (kokoro-js installed beside it). Waits until it has played (or was stopped) unless wait=False;
|
|
283
|
+
returns {"id", "ms", "stopped"?}. interrupt="never" keeps talking when someone talks over it."""
|
|
284
|
+
text = str(text)
|
|
285
|
+
args = {"text": text, "interrupt": interrupt}
|
|
286
|
+
if self._tts is not None:
|
|
287
|
+
v = self._tts(text)
|
|
288
|
+
if inspect.isawaitable(v):
|
|
289
|
+
v = await v
|
|
290
|
+
wav = v if isinstance(v, (bytes, bytearray)) else to_wav(v[0], v[1])
|
|
291
|
+
args["wav"] = base64.b64encode(bytes(wav)).decode("ascii")
|
|
292
|
+
# listen before calling: a short clip can end before the answer to the call reaches us
|
|
293
|
+
ended, waiters = {}, {}
|
|
294
|
+
|
|
295
|
+
def done(d):
|
|
296
|
+
if not isinstance(d, dict) or not d.get("id"):
|
|
297
|
+
return
|
|
298
|
+
fut = waiters.pop(d["id"], None)
|
|
299
|
+
if fut and not fut.done():
|
|
300
|
+
fut.set_result(d)
|
|
301
|
+
else:
|
|
302
|
+
ended[d["id"]] = d
|
|
303
|
+
off = self.on("say.done", done)
|
|
304
|
+
try:
|
|
305
|
+
r = await self.call("say", args)
|
|
306
|
+
if not wait:
|
|
307
|
+
return r
|
|
308
|
+
if r.get("id") in ended:
|
|
309
|
+
return dict(r, **ended[r["id"]])
|
|
310
|
+
fut = asyncio.get_running_loop().create_future()
|
|
311
|
+
waiters[r.get("id")] = fut
|
|
312
|
+
return dict(r, **(await fut))
|
|
313
|
+
finally:
|
|
314
|
+
off()
|
|
315
|
+
|
|
316
|
+
async def stop_saying(self):
|
|
317
|
+
return await self.call("say.stop")
|
|
318
|
+
|
|
319
|
+
async def audio_in(self, who="room", rate=16000):
|
|
320
|
+
"""Open the room's sound (who="room") or one person's own voice where this seat holds it. Returns an async
|
|
321
|
+
iterator of 20 ms frames; close() it (or use "async with") when done. Subscribing marks the agent as taking notes."""
|
|
322
|
+
r = await self.call("audio.in.open", {"who": who, "rate": rate})
|
|
323
|
+
port = _AudioIn(self, r.get("port"), r)
|
|
324
|
+
self._ports[port.id] = port
|
|
325
|
+
for f in self._unclaimed.pop(port.id, []):
|
|
326
|
+
port._push(f)
|
|
327
|
+
return port
|
|
328
|
+
|
|
329
|
+
async def leave(self):
|
|
330
|
+
"""Leave the meeting (the goodbye goes out first), then end the seat process."""
|
|
331
|
+
if not self.closed:
|
|
332
|
+
try:
|
|
333
|
+
await self._send({"call": "leave"})
|
|
334
|
+
except MeetingError:
|
|
335
|
+
pass
|
|
336
|
+
self._finish()
|
|
337
|
+
try:
|
|
338
|
+
await asyncio.wait_for(self._proc.wait(), 10)
|
|
339
|
+
except asyncio.TimeoutError:
|
|
340
|
+
self._proc.terminate()
|
|
341
|
+
await self._proc.wait()
|
|
342
|
+
|
|
343
|
+
async def __aenter__(self):
|
|
344
|
+
return self
|
|
345
|
+
|
|
346
|
+
async def __aexit__(self, *exc):
|
|
347
|
+
await self.leave()
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
async def join(url, name=None, owner=None, core=False, password=None, relay=None, profile=None, join_ms=None, command=None, core_keys=None, tts=None, voice=None):
|
|
351
|
+
"""Join a meeting and return its Meeting once the seat is in. The Node seat drives the meeting page in a Chrome or
|
|
352
|
+
Edge already on this computer (or a Chromium installed for Playwright; GIFOS_CHROME names one). The name must say
|
|
353
|
+
whose agent it is ("Ada (Sam's assistant)", or name="Ada", owner="Sam"). A room with a password raises
|
|
354
|
+
MeetingError: ask your human for it and pass password=. tts: text -> WAV bytes or (pcm, rate), sync or async, the
|
|
355
|
+
voice of say(); without it the Node seat's own voice (kokoro-js) is used; voice=False turns that off.
|
|
356
|
+
core=True (joining with no browser) is not available yet: the seat refuses it with a sentence, raised as
|
|
357
|
+
MeetingError. core_keys: public keys (base64) to trust for a core you signed yourself, once core mode ships."""
|
|
358
|
+
cmd = list(command or bridge_command())
|
|
359
|
+
try:
|
|
360
|
+
proc = await asyncio.create_subprocess_exec(*cmd, stdin=asyncio.subprocess.PIPE,
|
|
361
|
+
stdout=asyncio.subprocess.PIPE, limit=16 * 1024 * 1024)
|
|
362
|
+
except OSError as e:
|
|
363
|
+
raise MeetingError("Could not start the GifOS agent seat (" + " ".join(cmd) + "): " + str(e) + ". It needs Node 22 "
|
|
364
|
+
"or later and the @gifos-app/agent package: npm install -g @gifos-app/agent (or set "
|
|
365
|
+
"GIFOS_AGENT_BRIDGE to its src/stdio.js).") from None
|
|
366
|
+
meet = Meeting(proc, tts=tts, cmd=cmd)
|
|
367
|
+
opts = {"name": name, "owner": owner, "core": bool(core), "password": password, "relay": relay, "profile": profile, "joinMs": join_ms, "coreKeys": list(core_keys) if core_keys else None, "voice": voice}
|
|
368
|
+
try:
|
|
369
|
+
r = await meet._send({"join": url, "opts": {k: v for k, v in opts.items() if v is not None}})
|
|
370
|
+
except MeetingError:
|
|
371
|
+
meet._finish()
|
|
372
|
+
if proc.returncode is None:
|
|
373
|
+
proc.terminate()
|
|
374
|
+
await proc.wait()
|
|
375
|
+
raise
|
|
376
|
+
meet.core = bool(r.get("core"))
|
|
377
|
+
meet.joined = True
|
|
378
|
+
return meet
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gifos-agent
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Join a GifOS meeting as an AI agent from Python: chat, lines, people, hand, voice and the room's sound (the seat is held by the @gifos-app/agent Node package).
|
|
5
|
+
Author: Crowd Concepts, Inc.
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://gifos.app
|
|
8
|
+
Project-URL: Source, https://github.com/nwcnwc/gifos-agent
|
|
9
|
+
Keywords: gifos,meeting,agent,ai,video call
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Framework :: AsyncIO
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Topic :: Communications :: Conferencing
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# gifos-agent (Python)
|
|
23
|
+
|
|
24
|
+
Join a GifOS meeting as an AI agent from Python: read and write chat, follow the room's lines, see who is there,
|
|
25
|
+
raise a hand, speak aloud, and hear the room.
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
pip install gifos-agent
|
|
29
|
+
npm install -g @gifos-app/agent # the Node seat this package drives (Node 22 or later)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## How it works
|
|
33
|
+
|
|
34
|
+
The seat is held by the Node package [`@gifos-app/agent`](https://www.npmjs.com/package/@gifos-app/agent) in a
|
|
35
|
+
child process (its `gifos-agent-stdio` program), driven over JSON lines. That seat opens the real GifOS meeting page
|
|
36
|
+
in agent mode in a browser already on this computer, so every room rule stays with the meeting: proof of work,
|
|
37
|
+
passwords, the host's orders, slow mode, blur and consent. This package has no dependencies beyond the Python
|
|
38
|
+
standard library.
|
|
39
|
+
|
|
40
|
+
What it needs:
|
|
41
|
+
|
|
42
|
+
- Python 3.9 or later.
|
|
43
|
+
- Node 22 or later, and the Node package. The seat is found in this order:
|
|
44
|
+
1. `GIFOS_AGENT_BRIDGE`: a path to the Node package's `src/stdio.js` (run with `node`, or `GIFOS_NODE`);
|
|
45
|
+
2. `gifos-agent-stdio` on `PATH` (`npm install -g @gifos-app/agent` puts it there);
|
|
46
|
+
3. otherwise `npx --yes -p @gifos-app/agent gifos-agent-stdio` (downloads it on first use).
|
|
47
|
+
- A Chrome or Edge on the computer. With neither, run `npx playwright install chromium` once, or set
|
|
48
|
+
`GIFOS_CHROME` to a Chrome or Chromium binary. Nothing downloads a browser by itself.
|
|
49
|
+
|
|
50
|
+
## Example
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
import asyncio
|
|
54
|
+
from gifos_agent import join
|
|
55
|
+
|
|
56
|
+
async def main():
|
|
57
|
+
async with await join("https://gifos.app/meet/abc", name="Ada", owner="Sam") as meet:
|
|
58
|
+
await meet.chat("Hello, I'm Ada, Sam's assistant.")
|
|
59
|
+
async for line in meet.lines(to_me=True):
|
|
60
|
+
await meet.chat("You said: " + line["text"])
|
|
61
|
+
|
|
62
|
+
asyncio.run(main())
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The name must say whose agent it is: `name="Ada (Sam's assistant)"`, or `name="Ada", owner="Sam"`. A room with a
|
|
66
|
+
password raises `MeetingError`: ask your human for it and pass `password=`; never guess it.
|
|
67
|
+
|
|
68
|
+
## What you get
|
|
69
|
+
|
|
70
|
+
- `await join(url, name=, owner=, password=, tts=, ...)` returns a `Meeting` once the seat is in.
|
|
71
|
+
- `meet.lines(to_me=, trusted=, from_admin=, kinds=)`: an async iterator of lines from now on (chat, others'
|
|
72
|
+
captions), each with the speaker, `kind`, `toMe` and `trust` (`own`, `trusted`, `unchecked`, `distrusted`:
|
|
73
|
+
captions are claims, not facts). Its own words never come back.
|
|
74
|
+
- `meet.transcript()`: the lines the seat already holds, its own spoken lines included.
|
|
75
|
+
- `meet.chat(text)`, `meet.hand(up)`, `meet.stage_ask()`, `meet.stage_leave()`, `meet.people()`, `meet.state()`,
|
|
76
|
+
`meet.app.run(id)`, `meet.app.data(...)`, `meet.app.room(...)`.
|
|
77
|
+
- `meet.say(text)`: speaks aloud. The page plays the voice and writes the text as the agent's own spoken line.
|
|
78
|
+
The voice comes from `tts=` given to `join()` (a function, plain or async, from text to WAV bytes or to
|
|
79
|
+
`(pcm, rate)`; `to_wav(pcm, rate)` helps), else from the Node seat's own voice (`npm install -g kokoro-js` beside
|
|
80
|
+
it). Without either, `say()` raises "No voice": answer in chat instead. It waits until the clip has played.
|
|
81
|
+
- `meet.audio_in()`: the room's sound as this seat hears it, as 20 ms frames of 16-bit mono PCM
|
|
82
|
+
(`async for frame in ear: frame["pcm"]`); `close()` it when done. Hearing marks the agent as taking notes, and a
|
|
83
|
+
host's "AI notes" setting is obeyed.
|
|
84
|
+
- `meet.on(event, fn)`: `joined`, `people`, `speaking`, `line`, `hand`, `stage`, `app`, `host`, `left`, ...
|
|
85
|
+
- `meet.call(name, args)`: any call of the meeting's agent contract. A refused call raises `MeetingError` with the
|
|
86
|
+
meeting's own sentence, ready to show a person.
|
|
87
|
+
- `meet.leave()` (or leaving the `async with` block) says goodbye and ends the seat.
|
|
88
|
+
|
|
89
|
+
Joining with no browser (`core=True`) is not available yet: the seat refuses it with a sentence, raised as
|
|
90
|
+
`MeetingError`.
|
|
91
|
+
|
|
92
|
+
`say()` with no `tts=` and `audio_in()` need `@gifos-app/agent` 0.2.1 or later.
|
|
93
|
+
|
|
94
|
+
## Tests
|
|
95
|
+
|
|
96
|
+
`python3 -m unittest discover -s python/tests` (from the repository root; no network, no meeting).
|
|
97
|
+
|
|
98
|
+
MIT licensed. The GifOS service, the gifos.app website and the meeting page are not part of this package.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
gifos_agent
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "gifos-agent"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Join a GifOS meeting as an AI agent from Python: chat, lines, people, hand, voice and the room's sound (the seat is held by the @gifos-app/agent Node package)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "Crowd Concepts, Inc." }]
|
|
13
|
+
# 3.9: the oldest Python still common on long-term-support systems; the package uses only asyncio, json, wave and
|
|
14
|
+
# struct from the standard library, with no syntax newer than 3.9.
|
|
15
|
+
requires-python = ">=3.9"
|
|
16
|
+
dependencies = []
|
|
17
|
+
keywords = ["gifos", "meeting", "agent", "ai", "video call"]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 3 - Alpha",
|
|
20
|
+
"Framework :: AsyncIO",
|
|
21
|
+
"Intended Audience :: Developers",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
25
|
+
"Topic :: Communications :: Conferencing",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://gifos.app"
|
|
30
|
+
Source = "https://github.com/nwcnwc/gifos-agent"
|
|
31
|
+
|
|
32
|
+
[tool.setuptools]
|
|
33
|
+
packages = ["gifos_agent"]
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""The Python seat against a stand-in bridge that speaks gifos-agent-stdio's JSON lines (no meeting, no network).
|
|
2
|
+
Run: python3 -m unittest discover -s python/tests"""
|
|
3
|
+
import asyncio
|
|
4
|
+
import base64
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import struct
|
|
9
|
+
import sys
|
|
10
|
+
import textwrap
|
|
11
|
+
import unittest
|
|
12
|
+
import wave
|
|
13
|
+
|
|
14
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
|
15
|
+
from gifos_agent import join, to_wav, MeetingError, __version__ # noqa: E402
|
|
16
|
+
from gifos_agent.meeting import _line_matches # noqa: E402
|
|
17
|
+
|
|
18
|
+
CORE_OFF = "Core mode (joining without a browser) isn't available yet; join without { core: true }."
|
|
19
|
+
|
|
20
|
+
FAKE = textwrap.dedent(r'''
|
|
21
|
+
import base64, json, struct, sys
|
|
22
|
+
CORE_OFF = %r
|
|
23
|
+
def out(o): sys.stdout.write(json.dumps(o) + "\n"); sys.stdout.flush()
|
|
24
|
+
log = []
|
|
25
|
+
for raw in sys.stdin:
|
|
26
|
+
m = json.loads(raw)
|
|
27
|
+
log.append(m)
|
|
28
|
+
if "join" in m:
|
|
29
|
+
if m["opts"].get("core"):
|
|
30
|
+
out({"id": m["id"], "ok": False, "error": CORE_OFF}); continue
|
|
31
|
+
if m["opts"].get("name") == "NoOwner":
|
|
32
|
+
out({"id": m["id"], "ok": False, "error": "The name must say whose agent it is."}); continue
|
|
33
|
+
out({"id": m["id"], "ok": True, "core": False, "state": {"joined": True}})
|
|
34
|
+
continue
|
|
35
|
+
c, a = m.get("call"), m.get("args") or {}
|
|
36
|
+
if c == "chat":
|
|
37
|
+
out({"id": m["id"], "ok": True, "answer": {"ok": True, "id": "m_1", "held": False}})
|
|
38
|
+
out({"event": {"type": "line", "data": {"kind": "chat", "name": "Ada", "text": "hello", "toMe": False}}})
|
|
39
|
+
out({"event": {"type": "line", "data": {"kind": "spoken", "name": "Pyra", "text": "my own words", "mine": True, "toMe": True}}})
|
|
40
|
+
out({"event": {"type": "line", "data": {"kind": "chat", "name": "Ada", "text": "for you", "toMe": True}}})
|
|
41
|
+
elif c == "people":
|
|
42
|
+
out({"id": m["id"], "ok": True, "answer": {"ok": True, "people": [{"name": "Ada"}, {"name": "Pyra"}]}})
|
|
43
|
+
elif c == "say":
|
|
44
|
+
# the page's own rule: no WAV, no voice (here the stand-in seat has no text-to-speech of its own)
|
|
45
|
+
if not a.get("wav"):
|
|
46
|
+
out({"id": m["id"], "ok": False, "error": "No voice: pass { tts } to join(), or install kokoro-js."}); continue
|
|
47
|
+
w = base64.b64decode(a["wav"])
|
|
48
|
+
ok = w[:4] == b"RIFF" and w[8:12] == b"WAVE"
|
|
49
|
+
# say.done may come before the call's answer (a short clip on a busy page)
|
|
50
|
+
out({"event": {"type": "say.done", "data": {"id": "say7", "stopped": False}}})
|
|
51
|
+
out({"id": m["id"], "ok": True, "answer": {"ok": True, "id": "say7", "ms": 1000, "wavOk": ok, "text": a.get("text"), "interrupt": a.get("interrupt")}})
|
|
52
|
+
elif c == "audio.in.open":
|
|
53
|
+
out({"id": m["id"], "ok": True, "answer": {"ok": True, "port": "audio.in:3", "rate": a.get("rate"), "who": a.get("who")}})
|
|
54
|
+
for i in range(3):
|
|
55
|
+
pcm = struct.pack("<4h", i, i, i, i)
|
|
56
|
+
out({"event": {"type": "audio.in.frame", "data": {"port": "audio.in:3", "rate": 16000, "ts": i, "pcm": base64.b64encode(pcm).decode()}}})
|
|
57
|
+
elif c == "audio.in.close":
|
|
58
|
+
out({"id": m["id"], "ok": True, "answer": {"ok": True}})
|
|
59
|
+
out({"event": {"type": "port.closed", "data": {"port": a.get("port"), "why": "closed"}}})
|
|
60
|
+
elif c == "lines":
|
|
61
|
+
out({"id": m["id"], "ok": True, "answer": {"ok": True, "lines": [{"kind": "spoken", "text": "Hello", "mine": True}]}})
|
|
62
|
+
elif c == "echo":
|
|
63
|
+
out({"id": m["id"], "ok": True, "answer": {"ok": True, "log": log[:-1]}})
|
|
64
|
+
elif c == "leave":
|
|
65
|
+
out({"id": m["id"], "ok": True}); out({"event": {"type": "left", "data": {"reason": "leave"}}}); break
|
|
66
|
+
else:
|
|
67
|
+
out({"id": m["id"], "ok": False, "error": "No such call: " + str(c)})
|
|
68
|
+
''') % CORE_OFF
|
|
69
|
+
CMD = [sys.executable, "-c", FAKE]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def tone(n=480):
|
|
73
|
+
return [int(8000 * ((i % 20) - 10) / 10) for i in range(n)]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class MeetingTest(unittest.TestCase):
|
|
77
|
+
def run_async(self, coro):
|
|
78
|
+
return asyncio.run(coro)
|
|
79
|
+
|
|
80
|
+
def test_join_defaults_to_browser_mode(self):
|
|
81
|
+
async def go():
|
|
82
|
+
meet = await join("https://example.invalid/meet/x", name="Pyra", owner="Sam", command=CMD)
|
|
83
|
+
self.assertFalse(meet.core)
|
|
84
|
+
log = (await meet.call("echo"))["log"]
|
|
85
|
+
self.assertIs(log[0]["opts"]["core"], False) # core=False is what goes to the seat
|
|
86
|
+
self.assertEqual(log[0]["opts"]["owner"], "Sam")
|
|
87
|
+
await meet.leave()
|
|
88
|
+
self.run_async(go())
|
|
89
|
+
|
|
90
|
+
def test_core_true_raises_the_seats_sentence(self):
|
|
91
|
+
async def go():
|
|
92
|
+
with self.assertRaises(MeetingError) as e:
|
|
93
|
+
await join("https://example.invalid/meet/x", name="Pyra", owner="Sam", core=True, command=CMD)
|
|
94
|
+
self.assertEqual(str(e.exception), CORE_OFF)
|
|
95
|
+
self.run_async(go())
|
|
96
|
+
|
|
97
|
+
def test_join_calls_lines_leave(self):
|
|
98
|
+
async def go():
|
|
99
|
+
meet = await join("https://example.invalid/meet/x", name="Pyra", owner="Sam", command=CMD)
|
|
100
|
+
async def first(it):
|
|
101
|
+
async for line in it:
|
|
102
|
+
return line["text"]
|
|
103
|
+
to_me = asyncio.ensure_future(first(meet.lines(to_me=True)))
|
|
104
|
+
spoken = asyncio.ensure_future(first(meet.lines(kinds=["spoken"])))
|
|
105
|
+
r = await meet.chat("hi")
|
|
106
|
+
self.assertEqual(r["id"], "m_1") # the page's own id survives (the call id is the envelope's)
|
|
107
|
+
self.assertEqual(await asyncio.wait_for(to_me, 5), "for you") # not to me, and its own spoken line, are skipped
|
|
108
|
+
self.assertFalse(spoken.done()) # its own words never come back, even asked by kind
|
|
109
|
+
spoken.cancel()
|
|
110
|
+
self.assertEqual([p["name"] for p in await meet.people()], ["Ada", "Pyra"])
|
|
111
|
+
self.assertEqual((await meet.transcript())[0]["text"], "Hello")
|
|
112
|
+
with self.assertRaises(MeetingError) as e:
|
|
113
|
+
await meet.call("nope")
|
|
114
|
+
self.assertIn("No such call", str(e.exception))
|
|
115
|
+
await meet.leave()
|
|
116
|
+
self.assertTrue(meet.closed)
|
|
117
|
+
with self.assertRaises(MeetingError):
|
|
118
|
+
await meet.chat("after leaving")
|
|
119
|
+
self.run_async(go())
|
|
120
|
+
|
|
121
|
+
def test_join_refused_raises_the_sentence(self):
|
|
122
|
+
async def go():
|
|
123
|
+
with self.assertRaises(MeetingError) as e:
|
|
124
|
+
await join("https://example.invalid/meet/x", name="NoOwner", command=CMD)
|
|
125
|
+
self.assertIn("whose agent", str(e.exception))
|
|
126
|
+
self.run_async(go())
|
|
127
|
+
|
|
128
|
+
def test_no_seat_program_says_what_is_needed(self):
|
|
129
|
+
async def go():
|
|
130
|
+
with self.assertRaises(MeetingError) as e:
|
|
131
|
+
await join("https://example.invalid/meet/x", name="Pyra", owner="Sam", command=["/nonexistent/gifos-agent-stdio"])
|
|
132
|
+
self.assertIn("Node 22", str(e.exception))
|
|
133
|
+
self.assertIn("npm install -g @gifos-app/agent", str(e.exception))
|
|
134
|
+
self.run_async(go())
|
|
135
|
+
|
|
136
|
+
def test_seat_that_dies_before_joining_says_what_is_needed(self):
|
|
137
|
+
async def go():
|
|
138
|
+
with self.assertRaises(MeetingError) as e:
|
|
139
|
+
await join("https://example.invalid/meet/x", name="Pyra", owner="Sam", command=[sys.executable, "-c", "import sys; sys.exit(3)"])
|
|
140
|
+
self.assertIn("stopped before joining", str(e.exception))
|
|
141
|
+
self.assertIn("@gifos-app/agent", str(e.exception))
|
|
142
|
+
self.run_async(go())
|
|
143
|
+
|
|
144
|
+
def test_say_with_python_tts_waits_for_say_done(self):
|
|
145
|
+
async def go():
|
|
146
|
+
async def tts(text): # async tts returning (pcm, rate)
|
|
147
|
+
return tone(), 24000
|
|
148
|
+
meet = await join("https://example.invalid/meet/x", name="Pyra", owner="Sam", command=CMD, tts=tts)
|
|
149
|
+
r = await asyncio.wait_for(meet.say("Hello there", interrupt="never"), 5)
|
|
150
|
+
self.assertEqual(r["id"], "say7")
|
|
151
|
+
self.assertIs(r["stopped"], False) # say.done reached it though it came before the answer
|
|
152
|
+
self.assertTrue(r["wavOk"])
|
|
153
|
+
self.assertEqual((r["text"], r["interrupt"]), ("Hello there", "never"))
|
|
154
|
+
await meet.leave()
|
|
155
|
+
self.run_async(go())
|
|
156
|
+
|
|
157
|
+
def test_say_without_a_voice_raises_the_sentence(self):
|
|
158
|
+
async def go():
|
|
159
|
+
meet = await join("https://example.invalid/meet/x", name="Pyra", owner="Sam", command=CMD)
|
|
160
|
+
with self.assertRaises(MeetingError) as e:
|
|
161
|
+
await meet.say("hi")
|
|
162
|
+
self.assertIn("No voice", str(e.exception))
|
|
163
|
+
await meet.leave()
|
|
164
|
+
self.run_async(go())
|
|
165
|
+
|
|
166
|
+
def test_audio_in_frames_then_close(self):
|
|
167
|
+
async def go():
|
|
168
|
+
meet = await join("https://example.invalid/meet/x", name="Pyra", owner="Sam", command=CMD)
|
|
169
|
+
ear = await meet.audio_in(rate=16000)
|
|
170
|
+
self.assertEqual(ear.info["who"], "room")
|
|
171
|
+
got = []
|
|
172
|
+
async for f in ear:
|
|
173
|
+
got.append(struct.unpack("<4h", f["pcm"])[0])
|
|
174
|
+
if len(got) == 3:
|
|
175
|
+
break
|
|
176
|
+
self.assertEqual(got, [0, 1, 2])
|
|
177
|
+
await ear.close()
|
|
178
|
+
self.assertEqual(meet._ports, {})
|
|
179
|
+
await meet.leave()
|
|
180
|
+
self.run_async(go())
|
|
181
|
+
|
|
182
|
+
def test_to_wav(self):
|
|
183
|
+
w = to_wav(tone(), 16000)
|
|
184
|
+
with wave.open(io.BytesIO(w)) as r:
|
|
185
|
+
self.assertEqual((r.getnchannels(), r.getsampwidth(), r.getframerate(), r.getnframes()), (1, 2, 16000, 480))
|
|
186
|
+
self.assertEqual(to_wav(struct.pack("<2h", 1, -1), 8000)[-4:], struct.pack("<2h", 1, -1))
|
|
187
|
+
|
|
188
|
+
def test_line_filter_matches_the_node_rules(self):
|
|
189
|
+
chat = {"kind": "chat", "text": "x"}
|
|
190
|
+
self.assertTrue(_line_matches(chat))
|
|
191
|
+
self.assertFalse(_line_matches(dict(chat, final=False)))
|
|
192
|
+
self.assertFalse(_line_matches({"kind": "spoken"}))
|
|
193
|
+
self.assertTrue(_line_matches({"kind": "spoken"}, kinds=["spoken"]))
|
|
194
|
+
self.assertFalse(_line_matches(dict(chat, mine=True)))
|
|
195
|
+
self.assertFalse(_line_matches(chat, to_me=True))
|
|
196
|
+
self.assertFalse(_line_matches(chat, from_admin=True))
|
|
197
|
+
self.assertTrue(_line_matches(chat, trusted=True)) # chat needs no caption trust
|
|
198
|
+
self.assertFalse(_line_matches({"kind": "caption", "trust": "unchecked"}, trusted=True))
|
|
199
|
+
self.assertTrue(_line_matches({"kind": "caption", "trust": "own"}, trusted=True))
|
|
200
|
+
|
|
201
|
+
def test_version_matches_pyproject(self):
|
|
202
|
+
here = os.path.join(os.path.dirname(__file__), "..", "pyproject.toml")
|
|
203
|
+
with open(here) as f:
|
|
204
|
+
self.assertIn('version = "%s"' % __version__, f.read())
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
if __name__ == "__main__":
|
|
208
|
+
unittest.main()
|