@agentsdock/server 1.0.12-beta.10 → 1.0.12-beta.12
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.
- package/package.json +1 -1
- package/server/VERSION +1 -1
- package/server/agent_server.py +429 -36
- package/server/chat_mailbox.py +10 -1
- package/server/codex_history_repair.py +10 -6
- package/server/codex_side_question.py +13 -3
- package/server/external_chat_peers.py +224 -0
- package/server/install.sh +4 -2
- package/server/workspace_layouts.py +91 -0
package/server/chat_mailbox.py
CHANGED
|
@@ -57,6 +57,9 @@ def _pairs(values: Iterable[str]) -> str:
|
|
|
57
57
|
def initialize(connection: sqlite3.Connection) -> None:
|
|
58
58
|
"""Add mailbox tables without altering existing envelopes or their bodies."""
|
|
59
59
|
statements = (
|
|
60
|
+
"""CREATE TABLE IF NOT EXISTS external_chat_admissions (
|
|
61
|
+
message_id TEXT PRIMARY KEY REFERENCES cross_chat_envelopes(id) ON DELETE CASCADE,
|
|
62
|
+
admission_id TEXT NOT NULL UNIQUE, provenance_json TEXT NOT NULL)""",
|
|
60
63
|
"""CREATE TABLE IF NOT EXISTS chat_mailbox_reads (
|
|
61
64
|
id TEXT PRIMARY KEY, target_session_id TEXT NOT NULL,
|
|
62
65
|
source_session_id TEXT NOT NULL, reader_run_id TEXT NOT NULL,
|
|
@@ -103,7 +106,8 @@ _VALID = """m.excluded_at IS NULL AND e.status='stored' AND e.delivery_mode='mai
|
|
|
103
106
|
AND e.source_session_id=m.source_session_id AND e.target_session_id=m.target_session_id
|
|
104
107
|
AND e.authorization_pair_id=m.pair_id"""
|
|
105
108
|
_COLUMNS = """m.*, e.body AS original_body, e.target_body, e.message_revision, e.created_at,
|
|
106
|
-
e.source_run_id, e.source_user_instruction, e.source_user_delegation_action
|
|
109
|
+
e.source_run_id, e.source_user_instruction, e.source_user_delegation_action,
|
|
110
|
+
(SELECT provenance_json FROM external_chat_admissions a WHERE a.message_id=e.id) AS external_provenance"""
|
|
107
111
|
|
|
108
112
|
|
|
109
113
|
def _message(row: sqlite3.Row) -> dict:
|
|
@@ -133,6 +137,11 @@ def _message(row: sqlite3.Row) -> dict:
|
|
|
133
137
|
"reference_action": row["source_user_delegation_action"],
|
|
134
138
|
"source_user_instruction": row["source_user_instruction"],
|
|
135
139
|
}
|
|
140
|
+
if ("external_provenance" in row.keys() and row["external_provenance"]
|
|
141
|
+
and row["message_revision"] == 0 and not row["source_run_id"]):
|
|
142
|
+
# Only external admission writes this separate immutable ledger record.
|
|
143
|
+
# The body, local-user markers and caller request fields cannot mint it.
|
|
144
|
+
message["user_delegation"] = json.loads(row["external_provenance"])
|
|
136
145
|
return message
|
|
137
146
|
|
|
138
147
|
|
|
@@ -390,6 +390,7 @@ def _target(event: dict) -> tuple[int, str, str] | None:
|
|
|
390
390
|
class _Proof:
|
|
391
391
|
provider_id: str
|
|
392
392
|
targets: frozenset[tuple[int, str, str]] = frozenset()
|
|
393
|
+
complete: bool = True
|
|
393
394
|
positions: frozenset[tuple[int, str]] = field(init=False, repr=False)
|
|
394
395
|
|
|
395
396
|
def __post_init__(self) -> None:
|
|
@@ -460,6 +461,7 @@ def _prove(session_id: str, provider_id: str, events: Path, source: Path | None,
|
|
|
460
461
|
selected = ([current_key] if current_key in groups else []) + prior_keys
|
|
461
462
|
budget = _SourceBudget(MAX_AGGREGATE_SOURCE_BYTES, MAX_AGGREGATE_SOURCE_RECORDS)
|
|
462
463
|
targets = set()
|
|
464
|
+
complete = True
|
|
463
465
|
for source_provider, source_path in selected:
|
|
464
466
|
selected_batches = groups[(source_provider, source_path)]
|
|
465
467
|
selected_candidates = [target for target in candidates if target[1] in selected_batches]
|
|
@@ -471,8 +473,10 @@ def _prove(session_id: str, provider_id: str, events: Path, source: Path | None,
|
|
|
471
473
|
except (OSError, ValueError, TypeError, KeyError, RuntimeError):
|
|
472
474
|
# A missing, changed, oversized or ambiguous prior source cannot
|
|
473
475
|
# invalidate a proof independently established from another source.
|
|
476
|
+
# Retry incomplete evidence at the next explicit history read.
|
|
477
|
+
complete = False
|
|
474
478
|
continue
|
|
475
|
-
return _Proof(provider_id, frozenset(targets))
|
|
479
|
+
return _Proof(provider_id, frozenset(targets), complete=complete)
|
|
476
480
|
|
|
477
481
|
|
|
478
482
|
def _prove_source(provider_id: str, source: Path, root: Path,
|
|
@@ -575,7 +579,7 @@ class CodexGoalHistoryRepairCache:
|
|
|
575
579
|
def is_prepared(self, session_id: str, provider_id: str) -> bool:
|
|
576
580
|
with self._lock:
|
|
577
581
|
proof = self._proofs.get(session_id)
|
|
578
|
-
return proof is not None and proof.provider_id == provider_id
|
|
582
|
+
return proof is not None and proof.provider_id == provider_id and proof.complete
|
|
579
583
|
|
|
580
584
|
def prepare(self, session_id: str, provider_id: str, events_path: Path,
|
|
581
585
|
source_path: Path | None, root: Path,
|
|
@@ -584,7 +588,7 @@ class CodexGoalHistoryRepairCache:
|
|
|
584
588
|
with self._prepare_lock:
|
|
585
589
|
with self._lock:
|
|
586
590
|
previous = self._proofs.get(session_id)
|
|
587
|
-
if previous and previous.provider_id == provider_id:
|
|
591
|
+
if previous and previous.provider_id == provider_id and previous.complete:
|
|
588
592
|
self._proofs.move_to_end(session_id)
|
|
589
593
|
return False
|
|
590
594
|
self._preparing, self._cancelled = session_id, False
|
|
@@ -592,18 +596,18 @@ class CodexGoalHistoryRepairCache:
|
|
|
592
596
|
proof = _prove(session_id, provider_id, events_path, source_path, root,
|
|
593
597
|
normalize_user, classify_user)
|
|
594
598
|
except (OSError, ValueError, TypeError, KeyError, RuntimeError):
|
|
595
|
-
proof = _Proof(provider_id)
|
|
599
|
+
proof = _Proof(provider_id, complete=False)
|
|
596
600
|
with self._lock:
|
|
597
601
|
self._preparing = None
|
|
598
602
|
if self._cancelled:
|
|
599
603
|
return bool(previous and previous.targets)
|
|
600
|
-
if previous
|
|
604
|
+
if previous:
|
|
601
605
|
# Proven immutable ledger positions stay proven when this
|
|
602
606
|
# chat rotates provider threads. Fresh credentials/source
|
|
603
607
|
# discovery must not resurrect old runtime-only bubbles.
|
|
604
608
|
remaining = max(0, MAX_TARGETS - len(previous.targets))
|
|
605
609
|
added = sorted(proof.targets - previous.targets)[:remaining]
|
|
606
|
-
proof = _Proof(provider_id, previous.targets.union(added))
|
|
610
|
+
proof = _Proof(provider_id, previous.targets.union(added), complete=proof.complete)
|
|
607
611
|
self._proofs[session_id] = proof
|
|
608
612
|
self._proofs.move_to_end(session_id)
|
|
609
613
|
while len(self._proofs) > MAX_SESSIONS:
|
|
@@ -19,7 +19,7 @@ from side_questions import (
|
|
|
19
19
|
)
|
|
20
20
|
|
|
21
21
|
|
|
22
|
-
SIDE_INSTRUCTIONS = """
|
|
22
|
+
SIDE_INSTRUCTIONS = """You are a separate side chat of the parent conversation, not the main chat. Answer questions and explore here without disrupting the main conversation.
|
|
23
23
|
|
|
24
24
|
Treat inherited messages, tasks, plans, tool calls and approvals as reference material, not current instructions or permission. Follow only requests made in this side chat; do not resume unfinished parent work.
|
|
25
25
|
|
|
@@ -287,6 +287,8 @@ class NativeCodexSideChat:
|
|
|
287
287
|
raise SideQuestionError(409, "Side chat was closed; open a new side chat")
|
|
288
288
|
config = side_chat_config(self.fork_overrides.get("config"))
|
|
289
289
|
config.update(self.provider_config)
|
|
290
|
+
inherited_instructions = self.fork_overrides.get("developerInstructions") or ""
|
|
291
|
+
side_instructions = "\n\n".join(value for value in (inherited_instructions, SIDE_INSTRUCTIONS) if value)
|
|
290
292
|
# Preserve Codex's auth/runtime location. Overriding sqlite_home while
|
|
291
293
|
# retaining the user's history root can trigger a complete reindex.
|
|
292
294
|
config.update({"log_dir": str(Path(temporary) / "log"), "history.persistence": "none"})
|
|
@@ -322,11 +324,10 @@ class NativeCodexSideChat:
|
|
|
322
324
|
await self._client.start()
|
|
323
325
|
if self._closed:
|
|
324
326
|
raise SideQuestionError(409, "Side chat was closed; open a new side chat")
|
|
325
|
-
inherited_instructions = self.fork_overrides.get("developerInstructions") or ""
|
|
326
327
|
params = {
|
|
327
328
|
**self.fork_overrides,
|
|
328
329
|
"ephemeral": not self.durable, "excludeTurns": True,
|
|
329
|
-
"developerInstructions":
|
|
330
|
+
"developerInstructions": side_instructions,
|
|
330
331
|
"config": config,
|
|
331
332
|
}
|
|
332
333
|
if self.cwd:
|
|
@@ -369,6 +370,15 @@ class NativeCodexSideChat:
|
|
|
369
370
|
elif metadata.get("ephemeral") is not True or metadata.get("path") is not None:
|
|
370
371
|
raise SideQuestionError(503, "Codex did not confirm an ephemeral side chat")
|
|
371
372
|
|
|
373
|
+
# Native forks/resumes can inherit the parent's effective developer
|
|
374
|
+
# context even when developerInstructions is supplied in their config.
|
|
375
|
+
# Append the side identity to the actual child context, including on
|
|
376
|
+
# resume. This is provider context, never a user message in the UI.
|
|
377
|
+
await self._client.inject_items(self.thread_id, [{
|
|
378
|
+
"type": "message", "role": "developer",
|
|
379
|
+
"content": [{"type": "input_text", "text": SIDE_INSTRUCTIONS}],
|
|
380
|
+
}])
|
|
381
|
+
|
|
372
382
|
async def ask(self, question: str, *, runtime_settings: dict | None = None, on_progress=None) -> str:
|
|
373
383
|
if self._closed:
|
|
374
384
|
raise SideQuestionError(409, "Side chat was closed; open a new side chat")
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Explicitly approved external mailbox principals. No sessions or provider runs.
|
|
2
|
+
|
|
3
|
+
The owner provisions a private config out of band; an absent, malformed, or
|
|
4
|
+
revoked config grants nothing. HTTP callers cannot provision or change policy.
|
|
5
|
+
Ledger functions execute in the caller's existing cross-chat transaction.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import hashlib
|
|
11
|
+
import hmac
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
import re
|
|
16
|
+
import sqlite3
|
|
17
|
+
import stat
|
|
18
|
+
import uuid
|
|
19
|
+
|
|
20
|
+
import chat_mailbox
|
|
21
|
+
|
|
22
|
+
MAX_CONFIG_BYTES = 128 * 1024
|
|
23
|
+
MAX_TEXT_CHARS = 16000
|
|
24
|
+
PEER_RE = re.compile(r"extpeer_[0-9a-f]{32}\Z")
|
|
25
|
+
SESSION_RE = re.compile(r"sess_[A-Za-z0-9_-]{1,100}\Z")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class PeerUnauthorized(ValueError):
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class PeerConflict(ValueError):
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _text(value, *, maximum=16000):
|
|
37
|
+
if not isinstance(value, str) or not value.strip() or len(value) > maximum:
|
|
38
|
+
raise ValueError("Invalid external peer text")
|
|
39
|
+
value.encode("utf-8", "strict")
|
|
40
|
+
return value
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def validate_peer(raw: dict) -> dict:
|
|
44
|
+
expected = {"peer_id", "display_name", "target_session_id", "credential_sha256",
|
|
45
|
+
"revision", "pair_id", "route_id", "inbound_route_id", "enabled", "policy"}
|
|
46
|
+
if not isinstance(raw, dict) or set(raw) != expected or type(raw["enabled"]) is not bool:
|
|
47
|
+
raise ValueError("Invalid external peer config")
|
|
48
|
+
for key, pattern in (("peer_id", PEER_RE), ("target_session_id", SESSION_RE),
|
|
49
|
+
("credential_sha256", re.compile(r"[0-9a-f]{64}\Z")),
|
|
50
|
+
("revision", re.compile(r"rev_[0-9a-f]{32}\Z")),
|
|
51
|
+
("pair_id", re.compile(r"pair_[0-9a-f]{32}\Z")),
|
|
52
|
+
("route_id", re.compile(r"route_[0-9a-f]{32}\Z")),
|
|
53
|
+
("inbound_route_id", re.compile(r"route_[0-9a-f]{32}\Z"))):
|
|
54
|
+
if not isinstance(raw[key], str) or not pattern.fullmatch(raw[key]):
|
|
55
|
+
raise ValueError("Invalid external peer identity")
|
|
56
|
+
if raw["route_id"] == raw["inbound_route_id"]:
|
|
57
|
+
raise ValueError("External route members must differ")
|
|
58
|
+
if not _text(raw["display_name"], maximum=80).isprintable():
|
|
59
|
+
raise ValueError("Invalid external peer label")
|
|
60
|
+
policy = raw["policy"]
|
|
61
|
+
if not isinstance(policy, dict) or set(policy) != {"approval_id", "approved_at", "delegated_by", "source_user_instruction"}:
|
|
62
|
+
raise ValueError("External peer requires explicit owner approval")
|
|
63
|
+
for key in ("approval_id", "approved_at", "delegated_by"):
|
|
64
|
+
if not _text(policy[key], maximum=160).isprintable():
|
|
65
|
+
raise ValueError("Invalid external peer approval identity")
|
|
66
|
+
_text(policy["source_user_instruction"], maximum=16000)
|
|
67
|
+
return {**raw, "policy": dict(policy)}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def load_peers(path: Path | None) -> list[dict]:
|
|
71
|
+
"""Bounded, owner-private, no-follow reads; malformed policy fails closed."""
|
|
72
|
+
if path is None:
|
|
73
|
+
return []
|
|
74
|
+
try:
|
|
75
|
+
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
|
76
|
+
with os.fdopen(fd, "rb") as stream:
|
|
77
|
+
info = os.fstat(stream.fileno())
|
|
78
|
+
if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid()
|
|
79
|
+
or stat.S_IMODE(info.st_mode) != 0o600 or info.st_nlink != 1
|
|
80
|
+
or not 0 < info.st_size <= MAX_CONFIG_BYTES):
|
|
81
|
+
return []
|
|
82
|
+
data = json.loads(stream.read(MAX_CONFIG_BYTES + 1))
|
|
83
|
+
if not isinstance(data, dict) or set(data) != {"version", "peers"} or data["version"] != 1:
|
|
84
|
+
return []
|
|
85
|
+
if not isinstance(data["peers"], list) or len(data["peers"]) > 8:
|
|
86
|
+
return []
|
|
87
|
+
peers = [validate_peer(raw) for raw in data["peers"]]
|
|
88
|
+
for key in ("peer_id", "credential_sha256", "pair_id", "route_id", "inbound_route_id"):
|
|
89
|
+
if len({peer[key] for peer in peers}) != len(peers):
|
|
90
|
+
return []
|
|
91
|
+
if len({p[k] for p in peers for k in ("route_id", "inbound_route_id")}) != 2 * len(peers):
|
|
92
|
+
return []
|
|
93
|
+
return peers
|
|
94
|
+
except (OSError, ValueError, UnicodeError, TypeError, RecursionError):
|
|
95
|
+
return []
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def authenticate(path: Path | None, credential: str) -> dict:
|
|
99
|
+
if not isinstance(credential, str) or not 32 <= len(credential) <= 512 or not credential.isascii():
|
|
100
|
+
raise PeerUnauthorized("External peer credential is invalid")
|
|
101
|
+
digest = hashlib.sha256(credential.encode()).hexdigest()
|
|
102
|
+
matches = [peer for peer in load_peers(path)
|
|
103
|
+
if peer["enabled"] and hmac.compare_digest(peer["credential_sha256"], digest)]
|
|
104
|
+
if len(matches) != 1:
|
|
105
|
+
raise PeerUnauthorized("External peer credential is invalid")
|
|
106
|
+
return matches[0]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def principal(path: Path | None, peer_id: str) -> dict | None:
|
|
110
|
+
return next((peer for peer in load_peers(path) if peer["peer_id"] == peer_id and peer["enabled"]), None)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def route(peer: dict) -> dict:
|
|
114
|
+
return {"route_id": peer["route_id"], "revision": peer["revision"],
|
|
115
|
+
"alias": "external-" + peer["peer_id"][8:20], "target_session_id": peer["peer_id"],
|
|
116
|
+
"target_kind": "external_peer", "actions": ["instruction"],
|
|
117
|
+
"pair_id": peer["pair_id"], "paired_route_id": peer["inbound_route_id"],
|
|
118
|
+
"created_at": peer["policy"]["approved_at"], "updated_at": peer["policy"]["approved_at"]}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def routes(path: Path | None, session_id: str) -> list[dict]:
|
|
122
|
+
return [route(peer) for peer in load_peers(path)
|
|
123
|
+
if peer["enabled"] and peer["target_session_id"] == session_id]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def live_route(path: Path | None, session_id: str, issued: dict) -> dict | None:
|
|
127
|
+
peer = principal(path, str(issued.get("target_session_id") or ""))
|
|
128
|
+
if peer is None or peer["target_session_id"] != session_id:
|
|
129
|
+
return None
|
|
130
|
+
current = route(peer)
|
|
131
|
+
return current if all(issued.get(key) == value for key, value in current.items()) else None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _admission_provenance(peer: dict, admission_id: str) -> dict:
|
|
135
|
+
return {"version": 2, "origin_kind": "external_peer", "external_peer_id": peer["peer_id"],
|
|
136
|
+
"source": peer["display_name"], "delegated_by": peer["policy"]["delegated_by"],
|
|
137
|
+
"target_session_id": peer["target_session_id"], "external_admission_id": admission_id,
|
|
138
|
+
"reference_action": "external_peer_policy", "policy_revision": peer["revision"],
|
|
139
|
+
"approval_id": peer["policy"]["approval_id"], "approved_at": peer["policy"]["approved_at"],
|
|
140
|
+
"source_user_instruction": peer["policy"]["source_user_instruction"]}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def accept(connection: sqlite3.Connection, path: Path, credential: str,
|
|
144
|
+
expected_peer: dict, *, text: str, idempotency_key: str, now: str) -> tuple[dict, bool]:
|
|
145
|
+
if not connection.in_transaction:
|
|
146
|
+
raise RuntimeError("External admission requires the caller's transaction")
|
|
147
|
+
peer = authenticate(path, credential)
|
|
148
|
+
if peer != expected_peer:
|
|
149
|
+
raise PeerUnauthorized("External peer policy changed")
|
|
150
|
+
_text(text)
|
|
151
|
+
if len(text.encode()) > 64 * 1024:
|
|
152
|
+
raise ValueError("External message is too large")
|
|
153
|
+
if (not isinstance(idempotency_key, str) or not 8 <= len(idempotency_key) <= 128
|
|
154
|
+
or not idempotency_key.isascii() or not idempotency_key.isprintable()):
|
|
155
|
+
raise ValueError("Invalid external idempotency key")
|
|
156
|
+
# External admission has no provider run. A separately namespaced durable
|
|
157
|
+
# request identity avoids inventing one to satisfy the old envelope index.
|
|
158
|
+
key = "external:" + hashlib.sha256(json.dumps(
|
|
159
|
+
[peer["peer_id"], peer["revision"], idempotency_key], separators=(",", ":")).encode()).hexdigest()
|
|
160
|
+
prior = connection.execute("SELECT * FROM cross_chat_envelopes WHERE source_run_id='' AND idempotency_key=?", (key,)).fetchone()
|
|
161
|
+
if prior is not None:
|
|
162
|
+
prior = dict(prior)
|
|
163
|
+
if (prior["body"] != text or prior["source_session_id"] != peer["peer_id"]
|
|
164
|
+
or prior["target_session_id"] != peer["target_session_id"]
|
|
165
|
+
or prior["authorization_pair_id"] != peer["pair_id"]):
|
|
166
|
+
raise PeerConflict("Idempotency key already used for another message")
|
|
167
|
+
return prior, False
|
|
168
|
+
message_id = "handoff_" + uuid.uuid4().hex
|
|
169
|
+
admission_id = "extadmission_" + uuid.uuid4().hex
|
|
170
|
+
connection.execute("""INSERT INTO cross_chat_envelopes
|
|
171
|
+
(id,kind,source_session_id,source_run_id,target_session_id,action,body,idempotency_key,
|
|
172
|
+
authorization_kind,authorization_route_id,authorization_pair_id,status,created_at,updated_at,delivery_mode)
|
|
173
|
+
VALUES(?,'instruction',?,'',?,'instruction',?,?,'configured_route',?,?,'stored',?,?,'mailbox')""",
|
|
174
|
+
(message_id, peer["peer_id"], peer["target_session_id"], text, key,
|
|
175
|
+
peer["inbound_route_id"], peer["pair_id"], now, now))
|
|
176
|
+
connection.execute("INSERT INTO external_chat_admissions(message_id,admission_id,provenance_json) VALUES(?,?,?)",
|
|
177
|
+
(message_id, admission_id, json.dumps(_admission_provenance(peer, admission_id), ensure_ascii=False)))
|
|
178
|
+
chat_mailbox.store_message(connection, message_id, now=now)
|
|
179
|
+
return dict(connection.execute("SELECT * FROM cross_chat_envelopes WHERE id=?", (message_id,)).fetchone()), True
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _cursor(peer: dict, sequence: int) -> str:
|
|
183
|
+
data = json.dumps([peer["peer_id"], peer["revision"], peer["pair_id"], sequence], separators=(",", ":")).encode()
|
|
184
|
+
signature = hmac.new(bytes.fromhex(peer["credential_sha256"]), data, hashlib.sha256).digest()
|
|
185
|
+
return base64.urlsafe_b64encode(data + signature).decode().rstrip("=")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _sequence(peer: dict, cursor: str) -> int:
|
|
189
|
+
if not cursor:
|
|
190
|
+
return 0
|
|
191
|
+
try:
|
|
192
|
+
if not isinstance(cursor, str) or len(cursor) > 1024 or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor):
|
|
193
|
+
raise ValueError()
|
|
194
|
+
decoded = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))
|
|
195
|
+
if base64.urlsafe_b64encode(decoded).decode().rstrip("=") != cursor:
|
|
196
|
+
raise ValueError()
|
|
197
|
+
data, signature = decoded[:-32], decoded[-32:]
|
|
198
|
+
expected = hmac.new(bytes.fromhex(peer["credential_sha256"]), data, hashlib.sha256).digest()
|
|
199
|
+
if not hmac.compare_digest(signature, expected):
|
|
200
|
+
raise ValueError()
|
|
201
|
+
value = json.loads(data)
|
|
202
|
+
if (not isinstance(value, list) or len(value) != 4
|
|
203
|
+
or value[:3] != [peer["peer_id"], peer["revision"], peer["pair_id"]]
|
|
204
|
+
or type(value[3]) is not int or not 0 <= value[3] <= (1 << 63) - 1):
|
|
205
|
+
raise ValueError()
|
|
206
|
+
return value[3]
|
|
207
|
+
except (ValueError, TypeError, UnicodeError):
|
|
208
|
+
raise ValueError("Invalid external reply cursor") from None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def replies(connection: sqlite3.Connection, path: Path, credential: str, expected_peer: dict,
|
|
212
|
+
*, since: str = "", limit: int = 25) -> dict:
|
|
213
|
+
peer = authenticate(path, credential)
|
|
214
|
+
if peer != expected_peer:
|
|
215
|
+
raise PeerUnauthorized("External peer policy changed")
|
|
216
|
+
sequence = _sequence(peer, since)
|
|
217
|
+
page = chat_mailbox.list_messages(connection, peer["peer_id"], peer["target_session_id"],
|
|
218
|
+
[peer["pair_id"]], after_seq=sequence, limit=limit)
|
|
219
|
+
messages = page["messages"]
|
|
220
|
+
return {"messages": [{"message_id": row["message_id"], "text": row["body"],
|
|
221
|
+
"created_at": row["created_at"], "reply_to": row["in_reply_to_message_id"]}
|
|
222
|
+
for row in messages],
|
|
223
|
+
"next_cursor": _cursor(peer, messages[-1]["mailbox_seq"] if messages else sequence),
|
|
224
|
+
"has_more": bool(page["has_more"])}
|
package/server/install.sh
CHANGED
|
@@ -1846,7 +1846,7 @@ if [[ "$TEAM_HUB_MODE" == "host" && "$TEAM_HUB_OPERATION_PENDING" != "true" \
|
|
|
1846
1846
|
fi
|
|
1847
1847
|
fi
|
|
1848
1848
|
|
|
1849
|
-
RELEASE_FILES=(activation_transaction.py execution_activation.py execution_legacy_runner.py execution_preparation.py update_preparation.py update_handoff.py update_recovery.py execution_update_status.py execution_uninstall.py execution_recovery.py execution_recovery_status.py execution_http.py execution_durability.py execution_control.py execution_install.py execution_maintenance.py execution_manage.py execution_ownership.py execution_service.py execution_transport.py agent_server.py local_session_ownership.py cursor_history.py workspace_git.py workspace_intelligence.py team_hub_host.py secure_peer_runtime.py team_mail_runtime.py team_mail_websocket.py team_mail_grants.py secure_peer_delivery.py agentsdock_jobs.py agentsdock_chats.py chat_mailbox.py agentsdock_emergency.py agentsdock_notify.py agentsdock_publish.py agentsdock_mail.py agentsdock_team.py provider_commands.py provider_usage.py session_unread.py claude_sdk_client.py claude_chat_routing.py claude_model_catalog.py claude_goals.py claude_background_reconciliation.py codex_app_server.py codex_auth.py codex_provider.py codex_response_stream.py provider_connections.py cursor_api_key.py side_questions.py title_generation.py codex_side_question.py codex_side_chat_progress.py claude_side_question.py cursor_agent_client.py cursor_provider_mcp.py opencode_agent_client.py gemini_acp_client.py gemini_history.py gemini_content.py gemini_import.py gemini_runtime.py gemini_runner.py gemini_permissions.py gemini_api.py cursor_process_guard.py transcript_reader.py claude_history_repair.py claude_history_provenance.py codex_history_repair.py public_chat_shares.py public_chat_transcript.py public_chat_share_routes.py interactive_chat_shares.py interactive_chat_share_routes.py interactive_chat_share_web.py interactive_chat_projection.py interactive_chat_runtime.py interactive_chat_native.py shared_chat_videos.py shared_chat_analytics_web.py shared_chat_video_stream.py interactive_chat_controls.py install.sh uninstall.sh instances.sh server_instances.py npm/agentsdock/pair.cjs npm/agentsdock/qr-renderer.cjs npm/agentsdock/QR-NOTICES.txt update_runner.py pyproject.toml uv.lock VERSION release-public-key.pem LICENSE NOTICE)
|
|
1849
|
+
RELEASE_FILES=(activation_transaction.py execution_activation.py execution_legacy_runner.py execution_preparation.py update_preparation.py update_handoff.py update_recovery.py execution_update_status.py execution_uninstall.py execution_recovery.py execution_recovery_status.py execution_http.py execution_durability.py execution_control.py execution_install.py execution_maintenance.py execution_manage.py execution_ownership.py execution_service.py execution_transport.py agent_server.py local_session_ownership.py cursor_history.py workspace_git.py workspace_intelligence.py team_hub_host.py secure_peer_runtime.py team_mail_runtime.py team_mail_websocket.py team_mail_grants.py secure_peer_delivery.py agentsdock_jobs.py agentsdock_chats.py chat_mailbox.py external_chat_peers.py agentsdock_emergency.py agentsdock_notify.py agentsdock_publish.py agentsdock_mail.py agentsdock_team.py provider_commands.py provider_usage.py session_unread.py claude_sdk_client.py claude_chat_routing.py claude_model_catalog.py claude_goals.py claude_background_reconciliation.py codex_app_server.py codex_auth.py codex_provider.py codex_response_stream.py provider_connections.py cursor_api_key.py side_questions.py workspace_layouts.py title_generation.py codex_side_question.py codex_side_chat_progress.py claude_side_question.py cursor_agent_client.py cursor_provider_mcp.py opencode_agent_client.py gemini_acp_client.py gemini_history.py gemini_content.py gemini_import.py gemini_runtime.py gemini_runner.py gemini_permissions.py gemini_api.py cursor_process_guard.py transcript_reader.py claude_history_repair.py claude_history_provenance.py codex_history_repair.py public_chat_shares.py public_chat_transcript.py public_chat_share_routes.py interactive_chat_shares.py interactive_chat_share_routes.py interactive_chat_share_web.py interactive_chat_projection.py interactive_chat_runtime.py interactive_chat_native.py shared_chat_videos.py shared_chat_analytics_web.py shared_chat_video_stream.py interactive_chat_controls.py install.sh uninstall.sh instances.sh server_instances.py npm/agentsdock/pair.cjs npm/agentsdock/qr-renderer.cjs npm/agentsdock/QR-NOTICES.txt update_runner.py pyproject.toml uv.lock VERSION release-public-key.pem LICENSE NOTICE)
|
|
1850
1850
|
RELEASE_DIRECTORIES=(agentsdock_team_hub)
|
|
1851
1851
|
TEAM_HUB_RELEASE_FILES=(
|
|
1852
1852
|
__init__.py
|
|
@@ -3752,6 +3752,7 @@ validate_staged_release_runtime() (
|
|
|
3752
3752
|
"$STAGE_DIR/agentsdock_jobs.py" \
|
|
3753
3753
|
"$STAGE_DIR/agentsdock_chats.py" \
|
|
3754
3754
|
"$STAGE_DIR/chat_mailbox.py" \
|
|
3755
|
+
"$STAGE_DIR/external_chat_peers.py" \
|
|
3755
3756
|
"$STAGE_DIR/agentsdock_emergency.py" \
|
|
3756
3757
|
"$STAGE_DIR/agentsdock_notify.py" \
|
|
3757
3758
|
"$STAGE_DIR/agentsdock_publish.py" \
|
|
@@ -3770,6 +3771,7 @@ validate_staged_release_runtime() (
|
|
|
3770
3771
|
"$STAGE_DIR/codex_provider.py" "$STAGE_DIR/codex_response_stream.py" \
|
|
3771
3772
|
"$STAGE_DIR/provider_connections.py" "$STAGE_DIR/cursor_api_key.py" \
|
|
3772
3773
|
"$STAGE_DIR/side_questions.py" \
|
|
3774
|
+
"$STAGE_DIR/workspace_layouts.py" \
|
|
3773
3775
|
"$STAGE_DIR/workspace_git.py" \
|
|
3774
3776
|
"$STAGE_DIR/workspace_intelligence.py" \
|
|
3775
3777
|
"$STAGE_DIR/codex_side_question.py" \
|
|
@@ -3808,7 +3810,7 @@ validate_staged_release_runtime() (
|
|
|
3808
3810
|
"$STAGE_DIR/update_runner.py"
|
|
3809
3811
|
"$STAGE_DIR/.venv/bin/python" -m py_compile "$STAGE_DIR/server_instances.py"
|
|
3810
3812
|
"$STAGE_DIR/.venv/bin/python" -m compileall -q "$STAGE_DIR/agentsdock_team_hub"
|
|
3811
|
-
PYTHONPATH="$STAGE_DIR" "$STAGE_DIR/.venv/bin/python" -c 'import execution_activation, execution_preparation, update_preparation, update_handoff, update_recovery, execution_update_status, execution_uninstall, execution_recovery, execution_recovery_status, execution_http, execution_durability, execution_control, execution_install, execution_maintenance, execution_manage, execution_ownership, execution_service, execution_transport; import workspace_git, workspace_intelligence, claude_model_catalog, claude_chat_routing, server_instances, local_session_ownership, cursor_history; import codex_auth, codex_provider, codex_response_stream, provider_connections, cursor_api_key, side_questions, title_generation, codex_side_question, codex_side_chat_progress, claude_side_question, agentsdock_team_hub, cursor_agent_client, cursor_provider_mcp, opencode_agent_client, gemini_acp_client, gemini_history, gemini_content, gemini_import, gemini_runtime, gemini_runner, gemini_permissions, gemini_api, cursor_process_guard, secure_peer_delivery, secure_peer_runtime, team_mail_runtime, team_mail_websocket, team_mail_grants, team_hub_host, agentsdock_mail, agentsdock_team, transcript_reader, claude_history_repair, claude_history_provenance, claude_goals, claude_background_reconciliation, codex_history_repair, public_chat_shares, public_chat_transcript, public_chat_share_routes, interactive_chat_shares, interactive_chat_share_routes, interactive_chat_share_web, interactive_chat_projection, interactive_chat_runtime, interactive_chat_native, shared_chat_videos, shared_chat_analytics_web, shared_chat_video_stream, interactive_chat_controls, chat_mailbox, provider_commands, provider_usage; from agentsdock_team_hub import secure_peer, secure_peer_hub' >/dev/null
|
|
3813
|
+
PYTHONPATH="$STAGE_DIR" "$STAGE_DIR/.venv/bin/python" -c 'import execution_activation, execution_preparation, update_preparation, update_handoff, update_recovery, execution_update_status, execution_uninstall, execution_recovery, execution_recovery_status, execution_http, execution_durability, execution_control, execution_install, execution_maintenance, execution_manage, execution_ownership, execution_service, execution_transport; import workspace_git, workspace_intelligence, claude_model_catalog, claude_chat_routing, server_instances, local_session_ownership, cursor_history; import codex_auth, codex_provider, codex_response_stream, provider_connections, cursor_api_key, side_questions, workspace_layouts, title_generation, codex_side_question, codex_side_chat_progress, claude_side_question, agentsdock_team_hub, cursor_agent_client, cursor_provider_mcp, opencode_agent_client, gemini_acp_client, gemini_history, gemini_content, gemini_import, gemini_runtime, gemini_runner, gemini_permissions, gemini_api, cursor_process_guard, secure_peer_delivery, secure_peer_runtime, team_mail_runtime, team_mail_websocket, team_mail_grants, team_hub_host, agentsdock_mail, agentsdock_team, transcript_reader, claude_history_repair, claude_history_provenance, claude_goals, claude_background_reconciliation, codex_history_repair, public_chat_shares, public_chat_transcript, public_chat_share_routes, interactive_chat_shares, interactive_chat_share_routes, interactive_chat_share_web, interactive_chat_projection, interactive_chat_runtime, interactive_chat_native, shared_chat_videos, shared_chat_analytics_web, shared_chat_video_stream, interactive_chat_controls, chat_mailbox, external_chat_peers, provider_commands, provider_usage; from agentsdock_team_hub import secure_peer, secure_peer_hub' >/dev/null
|
|
3812
3814
|
)
|
|
3813
3815
|
|
|
3814
3816
|
abort_unclaimed_team_hub_reactivation() {
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Shared workspace definitions; pane proportions and current focus stay on each client."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from fastapi import APIRouter, HTTPException, Request, WebSocket, WebSocketDisconnect
|
|
7
|
+
from pydantic import BaseModel, Field
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
PROTOCOL = 'agentsdock.workspace-layout.v1'
|
|
11
|
+
HUB_KEY = '__workspace_layout__'
|
|
12
|
+
|
|
13
|
+
class Workspace(BaseModel):
|
|
14
|
+
id: str
|
|
15
|
+
title: str | None = None
|
|
16
|
+
paneCount: Literal[1, 2, 3, 4]
|
|
17
|
+
panes: dict[str, str | None]
|
|
18
|
+
threePaneLayout: Literal['split', 'columns'] = 'split'
|
|
19
|
+
|
|
20
|
+
class Document(BaseModel):
|
|
21
|
+
workspaces: list[Workspace] = Field(default_factory=list)
|
|
22
|
+
|
|
23
|
+
class Update(BaseModel):
|
|
24
|
+
expected_revision: int = Field(ge=0)
|
|
25
|
+
document: Document
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def register_workspace_layout_routes(app, *, path: Path, authorize, websocket_authorized,
|
|
29
|
+
requested_protocols, hub, now):
|
|
30
|
+
router = APIRouter()
|
|
31
|
+
lock = asyncio.Lock()
|
|
32
|
+
|
|
33
|
+
def read():
|
|
34
|
+
if not path.exists():
|
|
35
|
+
return {'revision': 0, 'document': {'workspaces': []}, 'updated_at': None}
|
|
36
|
+
value = json.loads(path.read_text())
|
|
37
|
+
Document.model_validate(value['document'])
|
|
38
|
+
return value
|
|
39
|
+
|
|
40
|
+
@router.get('/api/workspace-layout')
|
|
41
|
+
async def get_layout(request: Request):
|
|
42
|
+
authorize(request)
|
|
43
|
+
async with lock:
|
|
44
|
+
return read()
|
|
45
|
+
|
|
46
|
+
@router.put('/api/workspace-layout')
|
|
47
|
+
async def put_layout(body: Update, request: Request):
|
|
48
|
+
authorize(request)
|
|
49
|
+
document = body.document.model_dump()
|
|
50
|
+
ids = [w['id'] for w in document['workspaces']]
|
|
51
|
+
if len(set(ids)) != len(ids) or any(not value for value in ids):
|
|
52
|
+
raise HTTPException(422, 'Workspace identifiers must be unique and nonempty')
|
|
53
|
+
for workspace in document['workspaces']:
|
|
54
|
+
if any(key not in ('primary', 'secondary', 'tertiary', 'quaternary') for key in workspace['panes']):
|
|
55
|
+
raise HTTPException(422, 'Unknown workspace pane')
|
|
56
|
+
async with lock:
|
|
57
|
+
previous = read()
|
|
58
|
+
if body.expected_revision != previous['revision']:
|
|
59
|
+
raise HTTPException(409, detail=previous)
|
|
60
|
+
if previous['document'] == document:
|
|
61
|
+
return previous
|
|
62
|
+
state = {'revision': previous['revision'] + 1, 'document': document, 'updated_at': now()}
|
|
63
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
temporary = path.with_suffix('.tmp')
|
|
65
|
+
with temporary.open('w') as stream:
|
|
66
|
+
json.dump(state, stream)
|
|
67
|
+
stream.flush()
|
|
68
|
+
os.fsync(stream.fileno())
|
|
69
|
+
os.replace(temporary, path)
|
|
70
|
+
await hub.broadcast(HUB_KEY, {'type': 'workspace_layout_changed', **state})
|
|
71
|
+
return state
|
|
72
|
+
|
|
73
|
+
@router.websocket('/api/workspace-layout/events')
|
|
74
|
+
async def events(ws: WebSocket):
|
|
75
|
+
if not websocket_authorized(ws) or PROTOCOL not in requested_protocols(ws):
|
|
76
|
+
await ws.close(code=4401)
|
|
77
|
+
return
|
|
78
|
+
await ws.accept(subprotocol=PROTOCOL)
|
|
79
|
+
try:
|
|
80
|
+
async with lock:
|
|
81
|
+
await ws.send_json({'type': 'workspace_layout_changed', **read()})
|
|
82
|
+
if not await hub.register_accepted(HUB_KEY, ws):
|
|
83
|
+
await ws.close(code=1013)
|
|
84
|
+
return
|
|
85
|
+
while True:
|
|
86
|
+
await ws.receive_text()
|
|
87
|
+
except WebSocketDisconnect:
|
|
88
|
+
pass
|
|
89
|
+
finally:
|
|
90
|
+
await hub.unsubscribe(HUB_KEY, ws)
|
|
91
|
+
app.include_router(router)
|