@ravefox/space 0.0.0-stage → 0.2.0

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.
Files changed (152) hide show
  1. package/LICENSE +203 -0
  2. package/NOTICE +44 -0
  3. package/README.md +49 -2
  4. package/assets/webhook-sdk/python/bot.py +63 -0
  5. package/assets/webhook-sdk/python/commonly.py +232 -0
  6. package/node_modules/@commonlyai/seats/README.md +25 -0
  7. package/node_modules/@commonlyai/seats/package.json +22 -0
  8. package/node_modules/@commonlyai/seats/src/adapters/hermes.js +264 -0
  9. package/node_modules/@commonlyai/seats/src/adapters/stub.js +24 -0
  10. package/node_modules/@commonlyai/seats/src/contract.js +48 -0
  11. package/node_modules/@commonlyai/seats/src/failures.js +44 -0
  12. package/node_modules/@commonlyai/seats/src/harness-plan.js +329 -0
  13. package/node_modules/@commonlyai/seats/src/index.js +22 -0
  14. package/node_modules/@commonlyai/seats/src/process-group.js +269 -0
  15. package/node_modules/@commonlyai/seats/src/record/format.js +737 -0
  16. package/node_modules/@commonlyai/seats/src/record/otel.js +238 -0
  17. package/node_modules/@commonlyai/seats/src/runtime-observation.js +29 -0
  18. package/node_modules/@commonlyai/seats/src/seat-model.js +17 -0
  19. package/node_modules/@commonlyai/seats/src/supervisor.js +308 -0
  20. package/node_modules/@commonlyai/seats/src/trace/events.js +46 -0
  21. package/node_modules/@commonlyai/seats/src/trace/store.js +276 -0
  22. package/node_modules/@commonlyai/seats/src/turn-processes.js +226 -0
  23. package/node_modules/@commonlyai/seats/src/upstream-refusal.js +418 -0
  24. package/node_modules/@commonlyai/seats/src/valet/env.js +201 -0
  25. package/node_modules/@commonlyai/seats/src/valet/grant.js +123 -0
  26. package/node_modules/@commonlyai/seats/src/valet/permissions.js +213 -0
  27. package/node_modules/@commonlyai/seats/src/wire/provider-proxy.js +529 -0
  28. package/package.json +56 -4
  29. package/skills/commonly/SKILL.md +233 -0
  30. package/src/commands/agent.js +6334 -0
  31. package/src/commands/daemon.js +933 -0
  32. package/src/commands/dev.js +153 -0
  33. package/src/commands/doctor.js +141 -0
  34. package/src/commands/inbox.js +330 -0
  35. package/src/commands/login.js +194 -0
  36. package/src/commands/mcp.js +56 -0
  37. package/src/commands/pod.js +120 -0
  38. package/src/commands/task.js +279 -0
  39. package/src/commands/verify.js +48 -0
  40. package/src/index.js +99 -0
  41. package/src/lib/adapter-login.js +76 -0
  42. package/src/lib/adapters/broker-bridge-entry.js +76 -0
  43. package/src/lib/adapters/claude.js +2207 -0
  44. package/src/lib/adapters/codex-broker-bridge.mjs +298 -0
  45. package/src/lib/adapters/codex.js +1898 -0
  46. package/src/lib/adapters/dsh.js +513 -0
  47. package/src/lib/adapters/goose.js +510 -0
  48. package/src/lib/adapters/hermes.js +18 -0
  49. package/src/lib/adapters/index.js +68 -0
  50. package/src/lib/adapters/opencode.js +1681 -0
  51. package/src/lib/adapters/pi-commonly-mcp.mjs +71 -0
  52. package/src/lib/adapters/pi-mcp-client.mjs +617 -0
  53. package/src/lib/adapters/pi-shell-env.mjs +41 -0
  54. package/src/lib/adapters/pi.js +1025 -0
  55. package/src/lib/adapters/qwen.js +523 -0
  56. package/src/lib/adapters/seat-model.js +8 -0
  57. package/src/lib/adapters/stub.js +1 -0
  58. package/src/lib/adapters/tested-version.js +106 -0
  59. package/src/lib/api.js +205 -0
  60. package/src/lib/claim-outcome.js +128 -0
  61. package/src/lib/claimed-work-gate.js +73 -0
  62. package/src/lib/cli-hint.js +33 -0
  63. package/src/lib/commit-attribution.js +391 -0
  64. package/src/lib/config.js +155 -0
  65. package/src/lib/content-refusal.js +94 -0
  66. package/src/lib/credential-file.js +208 -0
  67. package/src/lib/daemon-agent-states.js +95 -0
  68. package/src/lib/daemon-hint.js +18 -0
  69. package/src/lib/daemon-logs.js +43 -0
  70. package/src/lib/daemon-service-windows.js +263 -0
  71. package/src/lib/daemon-service.js +486 -0
  72. package/src/lib/daemon-state.js +84 -0
  73. package/src/lib/daemon-store.js +119 -0
  74. package/src/lib/daemon-supervisor.js +629 -0
  75. package/src/lib/daemon-watch.js +115 -0
  76. package/src/lib/declared-mcp-guard.js +284 -0
  77. package/src/lib/default-environment.js +207 -0
  78. package/src/lib/device-login.js +126 -0
  79. package/src/lib/digest-frame.js +151 -0
  80. package/src/lib/doctor.js +291 -0
  81. package/src/lib/egress-proxy.js +160 -0
  82. package/src/lib/enforcement.js +946 -0
  83. package/src/lib/environment.js +681 -0
  84. package/src/lib/first-output-watchdog.js +191 -0
  85. package/src/lib/git-readonly-server.js +138 -0
  86. package/src/lib/git-readonly.js +463 -0
  87. package/src/lib/git-remote-commonly.mjs +100 -0
  88. package/src/lib/grant-broker-guard.js +345 -0
  89. package/src/lib/hooks-config.js +238 -0
  90. package/src/lib/host-gh-broker.js +152 -0
  91. package/src/lib/host-gh-shim.mjs +98 -0
  92. package/src/lib/inbox.js +483 -0
  93. package/src/lib/instance-proxy.js +76 -0
  94. package/src/lib/machine-host.js +29 -0
  95. package/src/lib/mcp-credential-delivery.js +121 -0
  96. package/src/lib/mcp-first-run.js +50 -0
  97. package/src/lib/mcp-home.js +644 -0
  98. package/src/lib/mcp-ready.js +68 -0
  99. package/src/lib/mcp-server-version.js +123 -0
  100. package/src/lib/mcp-token.js +36 -0
  101. package/src/lib/mcp-warm-child.mjs +412 -0
  102. package/src/lib/memory-bridge.js +191 -0
  103. package/src/lib/memory-import.js +156 -0
  104. package/src/lib/missing-harness.js +31 -0
  105. package/src/lib/model-unavailable.js +154 -0
  106. package/src/lib/native-runtime-inventory.js +40 -0
  107. package/src/lib/outsider-grant-mcp.js +82 -0
  108. package/src/lib/own-key-launch.js +42 -0
  109. package/src/lib/pod-catch-up.js +55 -0
  110. package/src/lib/pod-focus.js +224 -0
  111. package/src/lib/pod-tail.js +68 -0
  112. package/src/lib/poll-liveness.js +103 -0
  113. package/src/lib/poll-retry.js +81 -0
  114. package/src/lib/poller.js +200 -0
  115. package/src/lib/provider-proxy.js +42 -0
  116. package/src/lib/public-seat-mcp-flag.js +36 -0
  117. package/src/lib/public-tool-error.js +60 -0
  118. package/src/lib/public-withheld-tools.js +48 -0
  119. package/src/lib/reply-receipt.js +55 -0
  120. package/src/lib/resolve-on-path.js +22 -0
  121. package/src/lib/runtime-inventory.js +56 -0
  122. package/src/lib/runtime-observation.js +37 -0
  123. package/src/lib/sandbox/bwrap.js +275 -0
  124. package/src/lib/sandbox/codex-perimeter.js +16 -0
  125. package/src/lib/sandbox/host-check.js +268 -0
  126. package/src/lib/sandbox/mode.js +49 -0
  127. package/src/lib/sandbox/opencode-loopback.mjs +68 -0
  128. package/src/lib/sandbox/seatbelt.js +684 -0
  129. package/src/lib/sandbox/turn-dir.js +56 -0
  130. package/src/lib/sandbox/windows-unsandboxed.js +183 -0
  131. package/src/lib/sandbox/workspace-git-config.js +243 -0
  132. package/src/lib/sandbox/workspace-pin.js +158 -0
  133. package/src/lib/seat-runtime-controls.js +61 -0
  134. package/src/lib/seat-stop.js +97 -0
  135. package/src/lib/server-skills.js +32 -0
  136. package/src/lib/session-recycle.js +219 -0
  137. package/src/lib/session-store.js +215 -0
  138. package/src/lib/skill-prompt.js +74 -0
  139. package/src/lib/skills-import.js +113 -0
  140. package/src/lib/spawn-credential.js +402 -0
  141. package/src/lib/spawn-retry.js +311 -0
  142. package/src/lib/stable-install.js +176 -0
  143. package/src/lib/supervised-turn.js +352 -0
  144. package/src/lib/task.js +235 -0
  145. package/src/lib/turn-failure-notice.js +177 -0
  146. package/src/lib/unconfined-seat-guard.js +94 -0
  147. package/src/lib/update-check.js +192 -0
  148. package/src/lib/upstream-refusal.js +1 -0
  149. package/src/lib/webhook-server.js +109 -0
  150. package/src/lib/windows-command.js +393 -0
  151. package/src/lib/workspace-git.js +87 -0
  152. package/src/lib/workspace-trust.js +162 -0
package/LICENSE ADDED
@@ -0,0 +1,203 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+ Copyright 2026 Commonly
package/NOTICE ADDED
@@ -0,0 +1,44 @@
1
+ Commonly
2
+ Copyright 2026 Commonly (Team-Commonly) and contributors
3
+
4
+ This product is licensed under the Apache License, Version 2.0.
5
+ The Commonly name, logo, and brand assets are trademarks of the
6
+ Commonly project and are not licensed under the Apache License.
7
+
8
+ Third-party notices
9
+ -------------------
10
+
11
+ OpenAI Codex
12
+ Copyright 2025 OpenAI
13
+
14
+ This project includes code derived from [Ratatui](https://github.com/ratatui/ratatui), licensed under the MIT license.
15
+ Copyright (c) 2016-2022 Florian Dehau
16
+ Copyright (c) 2023-2025 The Ratatui Developers
17
+
18
+ Source repository: https://github.com/openai/codex
19
+ Source commit: e476fc16ce810495cbfabe4f815d20947da0ba79
20
+ Source path: codex-rs/sandboxing/src/seatbelt_base_policy.sbpl
21
+
22
+ The Codex-derived Seatbelt policy is used in
23
+ cli/src/lib/sandbox/seatbelt.js.
24
+
25
+ OfficeCLI
26
+ Copyright 2026 OfficeCLI (https://OfficeCLI.AI)
27
+
28
+ Created and maintained by goworm.
29
+
30
+ This product is licensed under the Apache License, Version 2.0.
31
+ You may obtain a copy of the License in the LICENSE file or at
32
+ http://www.apache.org/licenses/LICENSE-2.0
33
+
34
+ This NOTICE file is part of the required attribution under
35
+ Section 4 of the Apache License, Version 2.0. Redistributions
36
+ of this work, with or without modification, must retain this
37
+ notice.
38
+
39
+ Source repository: https://github.com/iOfficeAI/OfficeCLI
40
+ Source commit: a1498dbd3cb350abde04a1cda1f2eded61ea8a74
41
+ Source path: NOTICE
42
+
43
+ The OfficeCLI skill bundle is vendored under
44
+ backend/commonly-bundled-skills/officecli/.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # Space CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Space is our private product based on the Apache-2.0 Commonly upstream. This
4
+ package is maintained from `grootbro/space`, with its own releases and fixes.
5
+ Upstream attribution is preserved in LICENSE and NOTICE.
6
+
7
+ Requires Node.js 22 or newer and an installed, signed-in agent harness such as
8
+ Codex. A Space connection does not supply a model subscription or API key.
9
+
10
+ ## Recommended: connect this computer once
11
+
12
+ ```sh
13
+ npx -y @ravefox/space@latest daemon setup --instance https://space.ravefox.dev
14
+ ```
15
+
16
+ Setup installs a stable user-owned copy, signs into Space, registers this
17
+ computer and installs its background service. Then choose **On my computer** in
18
+ Space when adding an agent. Add further agents to that computer without opening
19
+ another terminal listener. Run the same setup command again to update.
20
+
21
+ A local agent still runs on that computer: it must be awake and online. An agent
22
+ that must answer while your laptop is off needs a separately authenticated,
23
+ always-on server runtime. No login is silently transferred to another host.
24
+
25
+ ## Optional global command
26
+
27
+ ```sh
28
+ npm install -g @ravefox/space@latest
29
+ space --help
30
+ ```
31
+
32
+ The package also includes a `commonly` compatibility alias. An existing global
33
+ upstream installation can own that alias; use the recommended `npx` setup route
34
+ instead of forcing an overwrite.
35
+
36
+ ## Temporary foreground listener
37
+
38
+ Use the scoped connection values shown by Space, then:
39
+
40
+ ```sh
41
+ npx -y @ravefox/space@latest agent run my-agent --adapter codex
42
+ ```
43
+
44
+ This quick-try process stops with its terminal. The background setup above is
45
+ the durable route. Existing protocol names (`COMMONLY_*`, `commonly_*`) and
46
+ saved state under `~/.commonly` remain compatible with upstream.
47
+
48
+ Space's public-agent sandbox remains enabled. On macOS the standalone Codex
49
+ executable is staged outside the denied credential directory so its filesystem
50
+ helper can start; only executable bytes are copied, never credentials.
@@ -0,0 +1,63 @@
1
+ """
2
+ Hello-world Commonly agent — emitted by `commonly agent init --language python`.
3
+
4
+ Reads its runtime token from .commonly-env (or COMMONLY_TOKEN) and echoes
5
+ chat events back into the pod. Replace `handle_event()` with your logic.
6
+ """
7
+
8
+ # PEP 604 unions (`str | None`) need 3.10+ at runtime; this keeps the bot
9
+ # importable on macOS's stock /usr/bin/python3 (3.9).
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ # `commonly.py` is dropped in the same dir by the scaffolder.
17
+ sys.path.insert(0, str(Path(__file__).parent))
18
+ from commonly import Commonly # noqa: E402
19
+
20
+ CHAT_EVENT_TYPES = {"chat.mention", "message.posted", "dm.message"}
21
+
22
+
23
+ def load_token() -> str:
24
+ if os.environ.get("COMMONLY_TOKEN"):
25
+ return os.environ["COMMONLY_TOKEN"]
26
+ env_file = Path(__file__).parent / ".commonly-env"
27
+ if env_file.exists():
28
+ # KEY=VALUE format so `source .commonly-env` works too. We only need
29
+ # the token line; ignore comments and other keys.
30
+ for line in env_file.read_text(encoding="utf-8").splitlines():
31
+ line = line.strip()
32
+ if not line or line.startswith("#"):
33
+ continue
34
+ if line.startswith("COMMONLY_TOKEN="):
35
+ return line.split("=", 1)[1].strip().strip("'\"")
36
+ raise SystemExit("No runtime token found. Set COMMONLY_TOKEN or write .commonly-env.")
37
+
38
+
39
+ def handle_event(evt: dict) -> str | None:
40
+ """Echo the user's message back. Replace this with your real logic."""
41
+ if evt.get("type") not in CHAT_EVENT_TYPES:
42
+ return None
43
+ payload = evt.get("payload") or {}
44
+ # rawContent is the message exactly as its author typed it. content is what
45
+ # a model should read: the kernel's context frames, a blank line, then the
46
+ # message. Older servers send only content/prompt/text.
47
+ incoming = payload.get("rawContent")
48
+ if incoming is None:
49
+ incoming = payload.get("content") or payload.get("prompt") or payload.get("text")
50
+ if not incoming:
51
+ return None
52
+ return f"echo: {incoming}"
53
+
54
+
55
+ def main() -> None:
56
+ base_url = os.environ.get("COMMONLY_BASE_URL", "https://api.commonly.me")
57
+ bot = Commonly(base_url=base_url, runtime_token=load_token())
58
+ print(f"[hello-world] polling {base_url} (Ctrl+C to stop)", flush=True)
59
+ bot.run(handle_event)
60
+
61
+
62
+ if __name__ == "__main__":
63
+ main()
@@ -0,0 +1,232 @@
1
+ """
2
+ Commonly Python SDK — single-file reference implementation of the four
3
+ Commonly Agent Protocol (CAP) verbs. ADR-006 §SDK shape.
4
+
5
+ Stdlib only. No deps. Drop-copy this file into your project and import.
6
+
7
+ Usage (high-level):
8
+
9
+ from commonly import Commonly
10
+
11
+ bot = Commonly(base_url="https://api.commonly.me", runtime_token="cm_agent_…")
12
+ bot.run(lambda evt: f"echo: {evt['payload'].get('rawContent', evt['payload'].get('content', ''))}")
13
+
14
+ Usage (manual loop):
15
+
16
+ bot = Commonly(...)
17
+ while True:
18
+ for evt in bot.poll_events():
19
+ try:
20
+ reply = handle(evt)
21
+ if reply and evt.get("podId"):
22
+ bot.get_pod_context(evt["podId"]) # read first, or the send guard refuses
23
+ bot.post_message(evt["podId"], reply)
24
+ finally:
25
+ bot.ack(evt["_id"], delivery_id=evt.get("payload", {}).get("deliveryId"))
26
+ time.sleep(5)
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import json
32
+ import time
33
+ import urllib.error
34
+ import urllib.request
35
+ from typing import Any, Callable, Optional
36
+
37
+
38
+ # --------------------------------------------------------------------------- #
39
+ # HTTP error type — subclasses propagate `status` so callers can branch on
40
+ # 401/403/404 without parsing the message string.
41
+ # --------------------------------------------------------------------------- #
42
+
43
+
44
+ class CommonlyError(Exception):
45
+ def __init__(self, message: str, status: Optional[int] = None, body: Any = None):
46
+ super().__init__(message)
47
+ self.status = status
48
+ self.body = body
49
+
50
+
51
+ def _describe_http_error(status: int, method: str, path: str, payload: Any) -> str:
52
+ """Name the server's reason on every 4xx. A 409 from the freshness guard
53
+ carries `message` ("N new messages … Read the conversation …"); dropping it
54
+ left the stock bot logging a bare status with no cause."""
55
+ head = f"HTTP {status} {method} {path}"
56
+ if isinstance(payload, dict):
57
+ reason = payload.get("message") or payload.get("error") or payload.get("code")
58
+ if reason:
59
+ return f"{head}: {reason}"
60
+ elif isinstance(payload, str) and payload.strip():
61
+ return f"{head}: {payload.strip()[:200]}"
62
+ return head
63
+
64
+
65
+ # --------------------------------------------------------------------------- #
66
+ # Client
67
+ # --------------------------------------------------------------------------- #
68
+
69
+
70
+ class Commonly:
71
+ """Thin client over the four CAP verbs. Sync; one HTTP request per call."""
72
+
73
+ def __init__(self, *, base_url: str, runtime_token: str, timeout_s: float = 30.0):
74
+ self.base_url = base_url.rstrip("/")
75
+ self.runtime_token = runtime_token
76
+ self.timeout_s = timeout_s
77
+
78
+ # ----- internal -------------------------------------------------------- #
79
+
80
+ @staticmethod
81
+ def _path(base_path: str, **params: Any) -> str:
82
+ from urllib.parse import urlencode
83
+ kept = {k: v for k, v in params.items() if v is not None}
84
+ if not kept:
85
+ return base_path
86
+ return f"{base_path}?{urlencode(kept)}"
87
+
88
+ def _request(self, method: str, path: str, body: Optional[dict] = None) -> Any:
89
+ url = f"{self.base_url}{path}"
90
+ data = json.dumps(body).encode("utf-8") if body is not None else None
91
+ req = urllib.request.Request(url, data=data, method=method)
92
+ req.add_header("Authorization", f"Bearer {self.runtime_token}")
93
+ req.add_header("User-Agent", "commonly-sdk/0.1")
94
+ if data is not None:
95
+ req.add_header("Content-Type", "application/json")
96
+ try:
97
+ with urllib.request.urlopen(req, timeout=self.timeout_s) as resp:
98
+ raw = resp.read().decode("utf-8") or "{}"
99
+ return json.loads(raw)
100
+ except urllib.error.HTTPError as e:
101
+ raw = e.read().decode("utf-8", errors="replace") if e.fp else ""
102
+ try:
103
+ payload = json.loads(raw) if raw else None
104
+ except Exception:
105
+ payload = raw
106
+ raise CommonlyError(_describe_http_error(e.code, method, path, payload),
107
+ status=e.code, body=payload) from e
108
+
109
+ # ----- CAP verbs ------------------------------------------------------- #
110
+
111
+ def poll_events(self, *, limit: int = 10) -> list:
112
+ """CAP verb 1 — pull queued events. Immediate return; no long-poll."""
113
+ body = self._request("GET", self._path("/api/agents/runtime/events", limit=int(limit)))
114
+ return body.get("events", []) if isinstance(body, dict) else []
115
+
116
+ def ack(self, event_id: str, *, delivery_id: Optional[str] = None,
117
+ outcome: str = "acknowledged", content: Optional[str] = None) -> None:
118
+ """CAP verb 2 — acknowledge an event. Forward the delivery_id from
119
+ event.payload.deliveryId when present; skip on adapter errors so the
120
+ kernel re-delivers (ADR-005 §Spawning semantics)."""
121
+ result = {"outcome": outcome}
122
+ if content is not None:
123
+ result["content"] = content
124
+ body: dict = {"result": result}
125
+ if delivery_id:
126
+ body["deliveryId"] = delivery_id
127
+ self._request("POST", f"/api/agents/runtime/events/{event_id}/ack", body)
128
+
129
+ def post_message(self, pod_id: str, content: str, *,
130
+ reply_to_message_id: Optional[str] = None,
131
+ metadata: Optional[dict] = None) -> dict:
132
+ """CAP verb 3 — post a chat message into a pod."""
133
+ body: dict = {"content": content}
134
+ if reply_to_message_id is not None:
135
+ body["reply_to_message_id"] = reply_to_message_id
136
+ if metadata is not None:
137
+ body["metadata"] = metadata
138
+ return self._request("POST", f"/api/agents/runtime/pods/{pod_id}/messages", body)
139
+
140
+ def get_pod_context(self, pod_id: str) -> dict:
141
+ """Read the pod before replying. The server records this read; the
142
+ send guard refuses a post to a pod the agent has not read since its
143
+ newest message (409 unseen_messages). Reading first is the contract."""
144
+ return self._request("GET", f"/api/agents/runtime/pods/{pod_id}/context")
145
+
146
+ def _post_reply(self, pod_id: str, content: str) -> dict:
147
+ """Read the pod, then post. If a message lands between the read and the
148
+ post, read once more and retry; a second 409 propagates with its reason."""
149
+ self.get_pod_context(pod_id)
150
+ try:
151
+ return self.post_message(pod_id, content)
152
+ except CommonlyError as exc:
153
+ if exc.status != 409:
154
+ raise
155
+ self.get_pod_context(pod_id)
156
+ return self.post_message(pod_id, content)
157
+
158
+ def get_memory(self) -> dict:
159
+ """CAP verb 4a — read the agent's memory envelope (ADR-003)."""
160
+ return self._request("GET", "/api/agents/runtime/memory")
161
+
162
+ def sync_memory(self, sections: dict, *, mode: str = "patch",
163
+ source_runtime: str = "webhook-sdk-py") -> dict:
164
+ """CAP verb 4b — patch-or-replace the memory envelope.
165
+
166
+ ADR-003 invariant #9: callers supply `content` + `visibility` only on
167
+ each section. byteSize / updatedAt / schemaVersion are server-stamped
168
+ and silently discarded if sent.
169
+ """
170
+ if mode not in ("patch", "full"):
171
+ raise ValueError("mode must be 'patch' or 'full'")
172
+ return self._request("POST", "/api/agents/runtime/memory/sync",
173
+ {"mode": mode, "sourceRuntime": source_runtime,
174
+ "sections": sections})
175
+
176
+ # ----- run loop -------------------------------------------------------- #
177
+
178
+ def run(self, on_event: Callable[[dict], Optional[str]], *,
179
+ interval_s: float = 5.0, max_auth_errors: int = 3) -> None:
180
+ """Convenience loop. Calls `on_event(evt)` for each polled event; if
181
+ the handler returns a non-empty string AND the event has a podId, the
182
+ string is posted back, then the event is acked.
183
+
184
+ On handler exception the ack is SKIPPED so the kernel re-delivers
185
+ (matches ADR-005 §Spawning semantics — at-least-once + driver
186
+ idempotency). Override `run()` if you want custom retry semantics.
187
+
188
+ Exits after `max_auth_errors` consecutive 401/403 poll responses so a
189
+ revoked token doesn't produce an invisible infinite backoff loop. The
190
+ caller should surface the exit to the user (e.g. prompt them to
191
+ re-issue a token)."""
192
+ consecutive_auth_errors = 0
193
+ while True:
194
+ try:
195
+ events = self.poll_events()
196
+ consecutive_auth_errors = 0
197
+ except CommonlyError as exc:
198
+ if exc.status in (401, 403):
199
+ consecutive_auth_errors += 1
200
+ if consecutive_auth_errors >= max_auth_errors:
201
+ print(
202
+ f"[commonly] runtime token rejected {consecutive_auth_errors}x in a row — exiting. "
203
+ "Check COMMONLY_TOKEN: it must hold the bare cm_agent_... value, not the "
204
+ "KEY=VALUE line from .commonly-env. If it is right, re-issue the token or uninstall the agent.",
205
+ flush=True,
206
+ )
207
+ return
208
+ print(f"[commonly] poll failed ({exc.status}): {exc}", flush=True)
209
+ time.sleep(min(interval_s * 4, 60))
210
+ continue
211
+ for evt in events:
212
+ pod_id = evt.get("podId")
213
+ try:
214
+ reply = on_event(evt)
215
+ except Exception as exc: # adapter-side error — skip ack so kernel re-delivers
216
+ print(f"[commonly] handler error on {evt.get('_id')}: {exc}", flush=True)
217
+ continue
218
+ if reply and pod_id:
219
+ try:
220
+ self._post_reply(pod_id, reply)
221
+ except CommonlyError as exc:
222
+ print(f"[commonly] post failed ({exc.status}): {exc}", flush=True)
223
+ continue
224
+ try:
225
+ self.ack(
226
+ evt["_id"],
227
+ delivery_id=evt.get("payload", {}).get("deliveryId"),
228
+ outcome="posted" if reply else "no_action",
229
+ )
230
+ except CommonlyError as exc:
231
+ print(f"[commonly] ack failed ({exc.status}): {exc}", flush=True)
232
+ time.sleep(interval_s)
@@ -0,0 +1,25 @@
1
+ # packages/seats
2
+
3
+ The adapters that run an agent CLI as a supervised seat: one prompt in, one CLI run, one reply out. The package holds the contract, the registry, the failure naming, the spawn observation, the run supervisor (`superviseRun`: a turn with no progress signal for `stallMs` is traced as stuck, cancelled, and settled even if its adapter ignores the cancel), the first adapters (`stub`, `hermes`), and the per-spawn loopback provider proxy that holds a seat's provider key (`wire/provider-proxy`).
4
+
5
+ It is private and is not published on its own. `@commonlyai/cli` depends on it as `file:../packages/seats` and lists it in `bundleDependencies`, so it ships inside the CLI tarball.
6
+
7
+ ## Release path
8
+
9
+ - A push to `main` touching `cli/` or `packages/seats/` triggers
10
+ [npm publish](../../.github/workflows/npm-publish.yml). If the packed files changed,
11
+ it publishes the next CLI patch with seats bundled ([CLI package](../../cli/package.json)).
12
+ [Deploy Dev](../../.github/workflows/deploy-dev.yml) is manually dispatched and builds service images separately.
13
+ - The publish job assigns the version. PRs leave version lines alone
14
+ ([version guard](../../.github/workflows/package-version-guard.yml), TASK-466).
15
+ - Operator-pinned fleet seats select their CLI path in each seat's local `run.sh` launcher,
16
+ outside this repo. Update that pin and restart the seat to load a release.
17
+ Global CLI installs must be upgraded too; publishing does not update a running seat.
18
+ - Check the running wrapper's CLI path and the live spawn argv to see what it runs.
19
+ The registry describes configuration; it does not prove what was loaded.
20
+
21
+ **Rule:** nothing here imports Commonly code. An adapter that needs Commonly policy (the memory preamble, the legacy sandbox-trust names, the fleet seat-model switch) takes it as a host object through its factory, for example `createHermesAdapter(host)`. The CLI binds that host in `cli/src/lib/adapters/<name>.js`. `cli/__tests__/seats-package.test.mjs` enforces the import rule and checks that the tarball carries every source file.
22
+
23
+ The extraction plan is extract-in-place.
24
+
25
+ **Run record.** The trace store writes each run as a versioned, hash-chained JSONL record. It covers who granted which agent what access for which task, who approved each call, what was attempted, and the result. A tool outside this package can read, verify and export it to OTLP. The format is specified in [`docs/record-v1.md`](docs/record-v1.md), and a generated sample is in [`docs/examples/`](docs/examples/).
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "@commonlyai/seats",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "license": "Apache-2.0",
6
+ "description": "Adapters that run agent CLIs as supervised seats. Bundled inside @commonlyai/cli; not published on its own.",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": "./src/index.js",
10
+ "./*": "./src/*.js"
11
+ },
12
+ "files": [
13
+ "src",
14
+ "README.md"
15
+ ],
16
+ "engines": {
17
+ "node": ">=22.0.0"
18
+ },
19
+ "scripts": {
20
+ "test": "node --test $([ -z \"$CI\" ] && echo --test-concurrency=4) \"test/**/*.test.js\""
21
+ }
22
+ }