@agentsdock/server 1.0.12-beta.1 → 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.
@@ -176,7 +176,7 @@ def _authority_path(path: str | None) -> Path:
176
176
  return Path(selected).expanduser()
177
177
 
178
178
 
179
- def authority(path: str | None) -> str:
179
+ def authority_with_run(path: str | None) -> tuple[str, str]:
180
180
  authority_path = _authority_path(path)
181
181
  try:
182
182
  mode = authority_path.stat().st_mode & 0o777
@@ -194,7 +194,11 @@ def authority(path: str | None) -> str:
194
194
  raise ChatsCLIError(
195
195
  "AGENTSDOCK_CHAT_ID does not match the authority file"
196
196
  )
197
- return token
197
+ return token, str(payload.get("source_run_id") or "").strip()
198
+
199
+
200
+ def authority(path: str | None) -> str:
201
+ return authority_with_run(path)[0]
198
202
 
199
203
 
200
204
  def positive_target_index(value: str) -> int:
@@ -626,6 +630,51 @@ def list_routes(args: argparse.Namespace) -> dict[str, Any]:
626
630
  return result
627
631
 
628
632
 
633
+ def create_chat(args: argparse.Namespace) -> dict[str, Any]:
634
+ """Create an independent chat and return its connection to the creator."""
635
+ title = str(args.title or "").strip()
636
+ if not title:
637
+ raise ChatsCLIError("--title must not be empty")
638
+ payload: dict[str, Any] = {"title": title}
639
+ for name in ("folder", "cwd", "backend", "model", "effort", "provider_connection"):
640
+ value = getattr(args, name, None)
641
+ if value is not None:
642
+ payload[name] = value
643
+ key = getattr(args, "idempotency_key", None)
644
+ if key is not None:
645
+ key = key.strip()
646
+ if not 8 <= len(key) <= 128:
647
+ raise ChatsCLIError("--idempotency-key must contain 8 to 128 characters")
648
+ capability, source_run_id = authority_with_run(args.authority_file)
649
+ if key is None:
650
+ if not source_run_id:
651
+ raise ChatsCLIError("authority file has no source run for the default chat creation key")
652
+ # Scope automatic keys to the logical run without depending on a
653
+ # rotating capability. Explicit keys remain reusable across runs.
654
+ key = "cli_" + hashlib.sha256(
655
+ (f"create\0{source_run_id}\0" + json.dumps(payload, sort_keys=True, ensure_ascii=False)).encode("utf-8")
656
+ ).hexdigest()
657
+ payload["idempotency_key"] = key
658
+ result = post_json("/api/agent/chats", payload, capability)
659
+ session = result.get("session")
660
+ route = result.get("route")
661
+ if (
662
+ result.get("ok") is not True
663
+ or type(result.get("created")) is not bool
664
+ or type(result.get("duplicate")) is not bool
665
+ or result["created"] == result["duplicate"]
666
+ or not isinstance(session, dict)
667
+ or not isinstance(session.get("id"), str)
668
+ or not session["id"]
669
+ or not isinstance(route, dict)
670
+ or not isinstance(route.get("route_id"), str)
671
+ or not route["route_id"]
672
+ or route.get("mode") != "async_route_v1"
673
+ ):
674
+ raise ChatsCLIError("AgentsServer returned an invalid chat creation receipt")
675
+ return result
676
+
677
+
629
678
  def inbox(args: argparse.Namespace) -> dict[str, Any]:
630
679
  """List body-free pending senders; never claim or start their messages."""
631
680
  capability = authority(args.authority_file)
@@ -709,10 +758,9 @@ def send_action(args: argparse.Namespace, action: str) -> dict[str, Any]:
709
758
  raise ChatsCLIError("--reply-to requires an exact asynchronous route and message ID from the inbox")
710
759
  if requested_mode and not route:
711
760
  raise ChatsCLIError("conversation mode requires an exact route")
712
- discover_mode = bool(requested_mode or reply_to) or (
713
- _bounded_runtime_value("AGENTSDOCK_CROSS_CHAT_MODE") == "async_route_v1"
714
- )
715
- mode = negotiated_route_mode(capability, route, requested_mode) if route and discover_mode else ""
761
+ # A create can add the first route after this shell's environment was
762
+ # captured. Negotiate exact routes from the current server capability.
763
+ mode = negotiated_route_mode(capability, route, requested_mode) if route else ""
716
764
  if reply_to and mode != "async_route_v1":
717
765
  raise ChatsCLIError("--reply-to is not supported by legacy exchanges")
718
766
  if mode == "async_route_v1":
@@ -1046,7 +1094,7 @@ def add_message_arguments(command: argparse.ArgumentParser) -> None:
1046
1094
 
1047
1095
  def parser() -> argparse.ArgumentParser:
1048
1096
  root = argparse.ArgumentParser(
1049
- description="Contact an eligible chat on this AgentsDock server.",
1097
+ description="Create or contact a chat on this AgentsDock server.",
1050
1098
  allow_abbrev=False,
1051
1099
  )
1052
1100
  root.add_argument(
@@ -1057,6 +1105,30 @@ def parser() -> argparse.ArgumentParser:
1057
1105
  ),
1058
1106
  )
1059
1107
  commands = root.add_subparsers(dest="command", required=True)
1108
+ create_command = commands.add_parser(
1109
+ "create",
1110
+ help="create an independent AgentsDock chat and automatically connect it to this chat",
1111
+ description=(
1112
+ "Create an independent AgentsDock chat and automatically connect the creator and new chat. "
1113
+ "Omitted settings inherit from the creator. Use send with the returned route to send a message."
1114
+ ),
1115
+ allow_abbrev=False,
1116
+ )
1117
+ create_command.add_argument("--title", required=True)
1118
+ create_command.add_argument("--folder", help="folder for the new chat; inherits when omitted")
1119
+ create_command.add_argument("--cwd", help="working directory on the server; inherits when omitted")
1120
+ create_command.add_argument("--backend", help="agent backend; inherits when omitted")
1121
+ create_command.add_argument("--model", help="model; inherits when omitted")
1122
+ create_command.add_argument("--effort", help="reasoning effort; inherits when omitted")
1123
+ create_command.add_argument("--provider-connection", choices=["default", "custom"])
1124
+ create_command.add_argument(
1125
+ "--idempotency-key",
1126
+ help=(
1127
+ "8 to 128 character retry key; defaults to the same key for identical settings in this run. "
1128
+ "Explicit keys can be reused across runs. Use a different key to intentionally create another chat"
1129
+ ),
1130
+ )
1131
+ create_command.set_defaults(handler=create_chat)
1060
1132
  list_command = commands.add_parser(
1061
1133
  "list",
1062
1134
  help="list one page of eligible same-server chats for this live run",
@@ -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
 
@@ -0,0 +1,158 @@
1
+ """Keep native Claude child messages separate from AgentsDock chat routes.
2
+
3
+ Native SendMessage also accepts local/cloud sessions and display names. Only
4
+ identities observed in the provider's SubagentStart hooks may use that tool;
5
+ AgentsDock recipients must use the separately authorized provider helper.
6
+ The same policy runs as SDK callbacks and as print-mode command hooks.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ import shlex
16
+ import stat
17
+ import sys
18
+ from typing import Any
19
+
20
+
21
+ NATIVE_CHAT_TOOL_MATCHER = "^(ListAgents|ListPeers|SendMessage)$"
22
+ CHAT_ROUTING_REASON = (
23
+ "Not sent or listed. Native Claude messaging is not AgentsDock chat routing. "
24
+ "For an AgentsDock @Chat, use the run-bound AgentsDock provider tool with "
25
+ "helper=chats and the exact server-issued route/target index (or the authorized "
26
+ "helper CLI in print mode). Never substitute a similarly named Claude session. "
27
+ "Native SendMessage is only for a child of this Claude session: use its exact "
28
+ "agent ID from Agent/Task, or main when replying from that child. A native "
29
+ "success is not an AgentsDock delivery receipt."
30
+ )
31
+
32
+
33
+ def denied() -> dict[str, Any]:
34
+ return {"hookSpecificOutput": {
35
+ "hookEventName": "PreToolUse",
36
+ "permissionDecision": "deny",
37
+ "permissionDecisionReason": CHAT_ROUTING_REASON,
38
+ }}
39
+
40
+
41
+ def identity(value: Any) -> str:
42
+ # These are provider hook fields, never IDs asserted in the message body.
43
+ if not isinstance(value, str) or not value or len(value) > 200:
44
+ return ""
45
+ if any(not (c.isascii() and (c.isalnum() or c in "_-")) for c in value):
46
+ return ""
47
+ return value
48
+
49
+
50
+ class ClaudeChatRouting:
51
+ def __init__(self, registry: Path | None = None) -> None:
52
+ self.registry = registry
53
+ self.children: set[tuple[str, str]] = set()
54
+
55
+ def _marker(self, session: str, agent: str) -> Path:
56
+ assert self.registry is not None
57
+ digest = hashlib.sha256(f"{session}\0{agent}".encode()).hexdigest()
58
+ return self.registry / digest
59
+
60
+ def _private_registry(self) -> None:
61
+ assert self.registry is not None
62
+ self.registry.mkdir(mode=0o700, exist_ok=True)
63
+ info = self.registry.lstat()
64
+ if not stat.S_ISDIR(info.st_mode):
65
+ raise ValueError("Invalid Claude child registry")
66
+ if os.name != "nt" and (info.st_uid != os.getuid() or info.st_mode & 0o077):
67
+ raise ValueError("Claude child registry must be private")
68
+
69
+ def record_child(self, event: dict[str, Any]) -> dict[str, Any]:
70
+ session, agent = identity(event.get("session_id")), identity(event.get("agent_id"))
71
+ if event.get("hook_event_name") != "SubagentStart" or not session or not agent:
72
+ return {}
73
+ if self.registry is None:
74
+ self.children.add((session, agent))
75
+ else:
76
+ self._private_registry()
77
+ # One immutable empty marker per provider-owned child. Concurrent
78
+ # hooks do not overwrite one another or store conversation text.
79
+ try:
80
+ fd = os.open(self._marker(session, agent), os.O_CREAT | os.O_EXCL | os.O_WRONLY,
81
+ 0o600)
82
+ except FileExistsError:
83
+ pass
84
+ else:
85
+ os.close(fd)
86
+ return {}
87
+
88
+ def _owns(self, session: str, agent: str) -> bool:
89
+ if not session or not agent:
90
+ return False
91
+ if self.registry is None:
92
+ return (session, agent) in self.children
93
+ self._private_registry()
94
+ try:
95
+ info = self._marker(session, agent).lstat()
96
+ except FileNotFoundError:
97
+ return False
98
+ return (stat.S_ISREG(info.st_mode) and info.st_size == 0 and info.st_nlink == 1
99
+ and (os.name == "nt" or (info.st_uid == os.getuid() and not info.st_mode & 0o077)))
100
+
101
+ def before_tool(self, event: dict[str, Any]) -> dict[str, Any]:
102
+ name = event.get("tool_name")
103
+ if name not in {"SendMessage", "ListAgents", "ListPeers"}:
104
+ return {}
105
+ if name != "SendMessage":
106
+ return denied()
107
+ data = event.get("tool_input")
108
+ if not isinstance(data, dict):
109
+ return denied()
110
+ # Claude changed recipient/content to to/message. Do not accept
111
+ # disagreeing legacy fields, broadcasts, socket addresses or names.
112
+ target = data.get("to", data.get("recipient"))
113
+ if "to" in data and "recipient" in data and data["to"] != data["recipient"]:
114
+ return denied()
115
+ session = identity(event.get("session_id"))
116
+ sender = identity(event.get("agent_id"))
117
+ try:
118
+ if target == "main" and self._owns(session, sender):
119
+ return {}
120
+ if self._owns(session, identity(target)):
121
+ # Defer to native permissions; never auto-approve a child tool.
122
+ return {}
123
+ except (OSError, ValueError):
124
+ pass
125
+ return denied()
126
+
127
+ async def subagent_start(self, event: dict[str, Any], *_: Any) -> dict[str, Any]:
128
+ return self.record_child(event)
129
+
130
+ async def pre_tool_use(self, event: dict[str, Any], *_: Any) -> dict[str, Any]:
131
+ return self.before_tool(event)
132
+
133
+
134
+ def print_routing_settings(manifest: Path) -> dict[str, Any]:
135
+ registry = manifest.with_name("claude-child-routing")
136
+ # Claude command hooks run through the user's shell. No authority or
137
+ # endpoint credentials appear in this command or in its registry.
138
+ command = shlex.join([sys.executable, str(Path(__file__).resolve()), str(registry)])
139
+ hook = {"type": "command", "command": command, "timeout": 5}
140
+ return {"hooks": {
141
+ "SubagentStart": [{"hooks": [hook]}],
142
+ "PreToolUse": [{"matcher": NATIVE_CHAT_TOOL_MATCHER, "hooks": [hook]}],
143
+ }}
144
+
145
+
146
+ def main() -> None:
147
+ try:
148
+ event = json.loads(sys.stdin.buffer.read(1024 * 1024 + 1))
149
+ policy = ClaudeChatRouting(Path(sys.argv[1]))
150
+ result = (policy.record_child(event) if event.get("hook_event_name") == "SubagentStart"
151
+ else policy.before_tool(event))
152
+ except (OSError, ValueError, TypeError, AttributeError, IndexError):
153
+ result = denied()
154
+ print(json.dumps(result))
155
+
156
+
157
+ if __name__ == "__main__":
158
+ main()
@@ -97,6 +97,126 @@ class ClaudeGoalHistoryNormalizer:
97
97
  self._parents.popitem(last=False)
98
98
 
99
99
 
100
+ CLAUDE_LOCAL_COMMAND_OUTPUT = re.compile(
101
+ r"\A<local-command-(stdout|stderr)>([\s\S]*)</local-command-\1>\Z"
102
+ )
103
+ CLAUDE_LOCAL_COMMAND_WRAPPER = re.compile(
104
+ r"\A<command-name>/([A-Za-z0-9_][A-Za-z0-9_.:-]{0,127})</command-name>\s*"
105
+ r"<command-message>\1</command-message>\s*<command-args>([\s\S]*)</command-args>\Z"
106
+ )
107
+
108
+
109
+ def claude_local_command_output(content: Any) -> str | None:
110
+ """Return the text of a native local-command output record, or None."""
111
+ if not isinstance(content, str) or len(content) > 1024 * 1024:
112
+ return None
113
+ match = CLAUDE_LOCAL_COMMAND_OUTPUT.fullmatch(content)
114
+ return match[2].strip() if match else None
115
+
116
+
117
+ class ClaudeLocalCommandHistoryNormalizer:
118
+ """Project native local slash commands (e.g. /compact) as Claude shows them.
119
+
120
+ Claude records a local command as user-role rows: a metadata caveat, the
121
+ ``<command-name>`` wrapper, then ``<local-command-stdout>`` output (and
122
+ optionally stderr), all sharing one ``promptId``. Native Claude Code
123
+ renders these as the typed command and its output, not as human messages.
124
+ Only rows proven by that parent chain within the same command occurrence
125
+ are rewritten. A human quoting the markup starts a new prompt (or lacks the
126
+ chain) and stays unchanged. ``/goal`` remains owned by
127
+ ClaudeGoalHistoryNormalizer.
128
+ """
129
+
130
+ # Seeding must recover the complete records preceding an incremental
131
+ # cursor: a command's arguments can make its wrapper far larger than a
132
+ # fixed lookback. Bounded by the transcript reader's own record limit.
133
+ SEED_MAX_RECORDS = 8
134
+ SEED_MAX_BYTES = 32 * 1024 * 1024 + 64 * 1024
135
+ SEED_CHUNK_BYTES = 1024 * 1024
136
+
137
+ def __init__(self):
138
+ self._caveats: OrderedDict[str, dict] = OrderedDict()
139
+ # Wrapper and output rows of one occurrence; the value is shared.
140
+ self._commands: OrderedDict[str, dict] = OrderedDict()
141
+
142
+ def seed(self, path: Path, offset: int) -> None:
143
+ if offset <= 0:
144
+ return
145
+ try:
146
+ with path.open("rb") as stream:
147
+ lines = self._records_before(stream, offset)
148
+ except OSError:
149
+ return
150
+ for line in lines:
151
+ try:
152
+ self.consume(json.loads(line))
153
+ except (ValueError, RecursionError):
154
+ continue
155
+
156
+ @classmethod
157
+ def _records_before(cls, stream, offset: int) -> list[bytes]:
158
+ """Return up to SEED_MAX_RECORDS complete lines ending at ``offset``."""
159
+ position, region = offset, b""
160
+ while position > 0 and region.count(b"\n") <= cls.SEED_MAX_RECORDS:
161
+ if offset - position >= cls.SEED_MAX_BYTES:
162
+ break
163
+ size = min(cls.SEED_CHUNK_BYTES, position, cls.SEED_MAX_BYTES - (offset - position))
164
+ position -= size
165
+ stream.seek(position)
166
+ region = stream.read(size) + region
167
+ if position > 0:
168
+ # The first line may be partial; only complete records are trusted.
169
+ region = region.partition(b"\n")[2]
170
+ return [line for line in region.splitlines() if line.strip()][-cls.SEED_MAX_RECORDS:]
171
+
172
+ def consume(self, event: Any) -> Any:
173
+ if (not isinstance(event, dict) or event.get("isSidechain") is True
174
+ or event.get("type") != "user"):
175
+ return event
176
+ identity, session = event.get("uuid"), event.get("sessionId")
177
+ if not isinstance(identity, str) or not isinstance(session, str):
178
+ return event
179
+ message = event.get("message")
180
+ content = message.get("content") if isinstance(message, dict) else None
181
+ if not isinstance(content, str) or message.get("role") != "user":
182
+ return event
183
+ parent_id, prompt = event.get("parentUuid"), event.get("promptId")
184
+ if event.get("isMeta") is True:
185
+ if content.startswith("<local-command-caveat>"):
186
+ self._remember(self._caveats, identity, {"sessionId": session, "promptId": prompt})
187
+ return event
188
+ caveat = self._caveats.get(parent_id)
189
+ if caveat is not None and caveat["sessionId"] == session and caveat["promptId"] == prompt:
190
+ match = CLAUDE_LOCAL_COMMAND_WRAPPER.fullmatch(content)
191
+ if match and match[1] != "goal":
192
+ self._remember(self._commands, identity,
193
+ {"sessionId": session, "promptId": prompt, "outputs": set()})
194
+ args = match[2].strip()
195
+ return {**event, "message": {**message, "content": f"/{match[1]}" + (f" {args}" if args else "")}}
196
+ return event
197
+ occurrence = self._commands.get(parent_id)
198
+ output = (CLAUDE_LOCAL_COMMAND_OUTPUT.fullmatch(content)
199
+ if occurrence is not None and len(content) <= 1024 * 1024 else None)
200
+ if (output is None or occurrence["sessionId"] != session or occurrence["promptId"] != prompt
201
+ or output[1] in occurrence["outputs"]):
202
+ return event
203
+ # At most one stdout and one stderr per occurrence, chained in order.
204
+ occurrence["outputs"].add(output[1])
205
+ self._remember(self._commands, identity, occurrence)
206
+ text = output[2].strip()
207
+ if not text:
208
+ return {**event, "isMeta": True}
209
+ return {**event, "type": "assistant",
210
+ "message": {"role": "assistant", "content": [{"type": "text", "text": text}]}}
211
+
212
+ @staticmethod
213
+ def _remember(store: OrderedDict, identity: str, value: dict) -> None:
214
+ store[identity] = value
215
+ store.move_to_end(identity)
216
+ while len(store) > 32:
217
+ store.popitem(last=False)
218
+
219
+
100
220
  def _timestamp_ms(value: Any) -> int | None:
101
221
  if not isinstance(value, str) or len(value) > 64:
102
222
  return None
@@ -117,7 +237,8 @@ class ClaudeGoalProjection:
117
237
  A native set sentinel establishes the goal. Evaluator and clear records
118
238
  update that exact condition; unrelated sessions/sidechains cannot establish
119
239
  or finish it. A fork starts empty until its own native set evidence arrives.
120
- No failure, pause, or success is inferred from a result/assistant message.
240
+ Native failed evaluations are terminal. No failure, pause, or success is
241
+ inferred from a result/assistant message.
121
242
  """
122
243
 
123
244
  def __init__(self, provider_session_id: str):
@@ -162,6 +283,7 @@ class ClaudeGoalProjection:
162
283
  timestamp = _timestamp_ms(event.get("timestamp"))
163
284
  condition = attachment.get("condition")
164
285
  met = attachment.get("met")
286
+ failed = attachment.get("failed", False)
165
287
  sentinel = attachment.get("sentinel", False)
166
288
  if (
167
289
  timestamp is None or timestamp < self._last_timestamp
@@ -169,6 +291,7 @@ class ClaudeGoalProjection:
169
291
  or not isinstance(condition, str) or not condition.strip()
170
292
  or len(condition) > 16_384
171
293
  or type(met) is not bool or type(sentinel) is not bool
294
+ or type(failed) is not bool or failed and (met or sentinel)
172
295
  ):
173
296
  return False
174
297
  previous = self.goal
@@ -180,7 +303,7 @@ class ClaudeGoalProjection:
180
303
  if not sentinel and previous["status"] != "active":
181
304
  return False
182
305
  goal = dict(previous)
183
- goal["status"] = "cleared" if sentinel else "achieved" if met else "active"
306
+ goal["status"] = "cleared" if sentinel else "failed" if failed else "achieved" if met else "active"
184
307
  if stopped:
185
308
  goal["execution_stop_reason"] = "continuation_limit"
186
309
  goal["execution_stopped_at"] = timestamp