@agentsdock/server 1.0.7-beta.5

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 (113) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +19 -0
  3. package/README.md +60 -0
  4. package/npm/cli.cjs +289 -0
  5. package/package.json +32 -0
  6. package/server/LICENSE +202 -0
  7. package/server/NOTICE +19 -0
  8. package/server/VERSION +1 -0
  9. package/server/activation_transaction.py +2458 -0
  10. package/server/agent_server.py +93226 -0
  11. package/server/agentsdock_chats.py +1237 -0
  12. package/server/agentsdock_emergency.py +338 -0
  13. package/server/agentsdock_jobs.py +640 -0
  14. package/server/agentsdock_mail.py +325 -0
  15. package/server/agentsdock_publish.py +404 -0
  16. package/server/agentsdock_team.py +793 -0
  17. package/server/agentsdock_team_hub/__init__.py +33 -0
  18. package/server/agentsdock_team_hub/auth.py +710 -0
  19. package/server/agentsdock_team_hub/cli.py +647 -0
  20. package/server/agentsdock_team_hub/database.py +310 -0
  21. package/server/agentsdock_team_hub/mail_hint_streams.py +176 -0
  22. package/server/agentsdock_team_hub/mail_hints.py +201 -0
  23. package/server/agentsdock_team_hub/migrations/0001_identity_auth.sql +690 -0
  24. package/server/agentsdock_team_hub/migrations/0002_teamspace_ledger.sql +1336 -0
  25. package/server/agentsdock_team_hub/migrations/0003_service_runtime.sql +361 -0
  26. package/server/agentsdock_team_hub/migrations/0004_managed_host_binding.sql +22 -0
  27. package/server/agentsdock_team_hub/migrations/0005_tailnet_bootstrap_delegations.sql +63 -0
  28. package/server/agentsdock_team_hub/migrations/0006_team_network_mailbox.sql +423 -0
  29. package/server/agentsdock_team_hub/migrations/0007_local_agent_mail.sql +63 -0
  30. package/server/agentsdock_team_hub/migrations/0008_managed_server_session.sql +73 -0
  31. package/server/agentsdock_team_hub/migrations/0009_team_messages.sql +324 -0
  32. package/server/agentsdock_team_hub/migrations/0010_team_attachment_orphan_reclamation.sql +52 -0
  33. package/server/agentsdock_team_hub/migrations/0011_human_admin_paging.sql +65 -0
  34. package/server/agentsdock_team_hub/migrations/0012_network_content_deletions.sql +69 -0
  35. package/server/agentsdock_team_hub/migrations/0013_team_message_revisions.sql +48 -0
  36. package/server/agentsdock_team_hub/migrations/0014_managed_network_owner.sql +50 -0
  37. package/server/agentsdock_team_hub/migrations/0015_team_message_inbox_dismissals.sql +3 -0
  38. package/server/agentsdock_team_hub/migrations/0016_team_message_all_servers.sql +4 -0
  39. package/server/agentsdock_team_hub/migrations/0017_skill_announcement_deletions.sql +16 -0
  40. package/server/agentsdock_team_hub/migrations/0018_team_mail_subjects.sql +8 -0
  41. package/server/agentsdock_team_hub/migrations/0019_team_mailbox_state.sql +5 -0
  42. package/server/agentsdock_team_hub/migrations/0020_team_mail_arrivals.sql +44 -0
  43. package/server/agentsdock_team_hub/migrations/0021_team_mail_threads.sql +4 -0
  44. package/server/agentsdock_team_hub/migrations/0022_team_bulletin_changes.sql +49 -0
  45. package/server/agentsdock_team_hub/migrations/0023_team_message_search.sql +93 -0
  46. package/server/agentsdock_team_hub/migrations/__init__.py +1 -0
  47. package/server/agentsdock_team_hub/notification_hints.py +306 -0
  48. package/server/agentsdock_team_hub/secure_peer.py +11215 -0
  49. package/server/agentsdock_team_hub/secure_peer_hub.py +1372 -0
  50. package/server/agentsdock_team_hub/security.py +318 -0
  51. package/server/agentsdock_team_hub/service.py +1737 -0
  52. package/server/agentsdock_team_hub/store.py +16276 -0
  53. package/server/chat_mailbox.py +448 -0
  54. package/server/claude_background_reconciliation.py +92 -0
  55. package/server/claude_goals.py +245 -0
  56. package/server/claude_history_provenance.py +137 -0
  57. package/server/claude_history_repair.py +1601 -0
  58. package/server/claude_sdk_client.py +3731 -0
  59. package/server/claude_side_question.py +212 -0
  60. package/server/codex_app_server.py +3030 -0
  61. package/server/codex_auth.py +93 -0
  62. package/server/codex_history_repair.py +1247 -0
  63. package/server/codex_provider.py +1120 -0
  64. package/server/codex_side_question.py +301 -0
  65. package/server/cursor_agent_client.py +654 -0
  66. package/server/cursor_process_guard.py +347 -0
  67. package/server/execution_activation.py +610 -0
  68. package/server/execution_control.py +233 -0
  69. package/server/execution_durability.py +184 -0
  70. package/server/execution_http.py +256 -0
  71. package/server/execution_install.py +792 -0
  72. package/server/execution_legacy_runner.py +406 -0
  73. package/server/execution_maintenance.py +137 -0
  74. package/server/execution_manage.py +615 -0
  75. package/server/execution_ownership.py +83 -0
  76. package/server/execution_preparation.py +362 -0
  77. package/server/execution_recovery.py +845 -0
  78. package/server/execution_recovery_status.py +195 -0
  79. package/server/execution_service.py +387 -0
  80. package/server/execution_transport.py +622 -0
  81. package/server/execution_uninstall.py +406 -0
  82. package/server/execution_update_status.py +49 -0
  83. package/server/install.sh +7074 -0
  84. package/server/interactive_chat_controls.py +153 -0
  85. package/server/interactive_chat_native.py +66 -0
  86. package/server/interactive_chat_projection.py +152 -0
  87. package/server/interactive_chat_runtime.py +132 -0
  88. package/server/interactive_chat_share_routes.py +534 -0
  89. package/server/interactive_chat_share_web.py +12 -0
  90. package/server/interactive_chat_shares.py +238 -0
  91. package/server/provider_commands.py +425 -0
  92. package/server/public_chat_share_routes.py +426 -0
  93. package/server/public_chat_shares.py +759 -0
  94. package/server/public_chat_transcript.py +357 -0
  95. package/server/pyproject.toml +29 -0
  96. package/server/release-public-key.pem +3 -0
  97. package/server/secure_peer_delivery.py +1236 -0
  98. package/server/secure_peer_runtime.py +7694 -0
  99. package/server/shared_chat_video_stream.py +262 -0
  100. package/server/shared_chat_videos.py +155 -0
  101. package/server/side_questions.py +594 -0
  102. package/server/team_hub_host.py +1354 -0
  103. package/server/team_mail_grants.py +136 -0
  104. package/server/team_mail_runtime.py +302 -0
  105. package/server/team_mail_websocket.py +211 -0
  106. package/server/title_generation.py +333 -0
  107. package/server/uninstall.sh +359 -0
  108. package/server/update_handoff.py +237 -0
  109. package/server/update_preparation.py +264 -0
  110. package/server/update_recovery.py +140 -0
  111. package/server/update_runner.py +1819 -0
  112. package/server/uv.lock +1101 -0
  113. package/server/workspace_git.py +545 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
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.
package/NOTICE ADDED
@@ -0,0 +1,19 @@
1
+ AgentsDock
2
+ Copyright 2026 Zhengyi Luo and contributors
3
+
4
+ AgentsDock's original code is licensed under the Apache License, Version 2.0,
5
+ except where a component explicitly states another license. See LICENSE.
6
+
7
+ Third-party and separately licensed components retain their own copyrights,
8
+ licenses, and attribution notices. In particular:
9
+
10
+ - mobile-react/LICENSE preserves the Expo template's MIT license and
11
+ copyright notice for 650 Industries, Inc. (Expo).
12
+ - The agentsdock-native-video, agentsdock-native-terminal, and
13
+ agentsdock-android-updater modules retain the MIT license declared in
14
+ their package metadata.
15
+ - SwiftTerm retains its MIT license in
16
+ mobile-react/modules/agentsdock-native-terminal/ios/Vendor/SwiftTerm/LICENSE.
17
+
18
+ Dependencies and other bundled third-party materials remain subject to their
19
+ respective license terms. This notice does not replace those licenses.
package/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # @agentsdock/server
2
+
3
+ AgentsDock's self-hosted server, distributed with its existing Python runtime
4
+ installer. The desktop app remains a separate signed native download.
5
+
6
+ This package has no installation lifecycle hooks. Installing the npm package
7
+ does not start, stop, upgrade, or log into a server. The service runs from its
8
+ own versioned installation directory, never from an npm or npx cache.
9
+
10
+ ## First installation
11
+
12
+ This opt-in beta is for testing fresh installations. It does not enable
13
+ automatic app-to-server updates or migrate existing installations. To install:
14
+
15
+ ```sh
16
+ npx @agentsdock/server@beta install --port 7850
17
+ ```
18
+
19
+ Use an exact package version for reproducible installations. The command needs
20
+ the same prerequisites as the source installer: a trusted `uv`, Linux with a
21
+ working user systemd session or Apple silicon macOS with a GUI launchd session,
22
+ and the desired provider CLIs. It runs as the current user without `sudo`.
23
+
24
+ The npm entrypoint only permits a fresh default installation. It refuses an
25
+ existing managed installation, legacy service, or custom installation roots;
26
+ changing directories does not create a second service. Use AgentsDock's managed
27
+ update controls for an existing server. Multiple named services are not enabled
28
+ by this package.
29
+
30
+ ## Managed updates
31
+
32
+ The CLI also supports managed updates using a compatible running server and a
33
+ separately reviewed, signed release descriptor. Existing-installation migration
34
+ and recovery are outside this beta's fresh-install testing scope. The command
35
+ binds its request to a known server and its current process instance:
36
+
37
+ ```sh
38
+ agentsdock-server update --server-url https://server.example \
39
+ --server-identity ID --server-instance-id INSTANCE \
40
+ --token-file /private/path/server-token \
41
+ --manifest agents-server-npm-manifest.json \
42
+ --signature agents-server-npm-manifest.sig
43
+ ```
44
+
45
+ The token file must be a current-user-owned regular file readable only by that
46
+ user, containing the server token alone. HTTPS is required except for literal
47
+ loopback addresses and localhost. Redirects are refused. The command checks the
48
+ authenticated server identity, then submits the signed descriptor to its managed
49
+ update endpoint. The server verifies the signature and waits for idle before
50
+ activating an update. A pending response means scheduled, not installed. No
51
+ registry tag, unsigned descriptor, or local installer bypasses this lifecycle.
52
+
53
+ ## Packaging
54
+
55
+ The source `server/package.json` is deliberately private. Run
56
+ `python3 server/scripts/package_npm_release.py --output dist/npm-server` from
57
+ the repository root to stage only the audited runtime allowlist, stamp
58
+ `server/VERSION`, and produce the publishable tarball plus its unsigned release
59
+ descriptor. The manual preparation workflow signs that descriptor. This command
60
+ does not publish to npm. Publish only a reviewed and verified prepared tarball.
package/npm/cli.cjs ADDED
@@ -0,0 +1,289 @@
1
+ #!/usr/bin/env node
2
+ 'use strict'
3
+
4
+ const fs = require('node:fs')
5
+ const path = require('node:path')
6
+ const os = require('node:os')
7
+ const net = require('node:net')
8
+ const crypto = require('node:crypto')
9
+ const http = require('node:http')
10
+ const https = require('node:https')
11
+ const { spawnSync } = require('node:child_process')
12
+
13
+ const HELP = `Usage: agentsdock-server install [--port PORT] [--bind IP] [--non-interactive] [--dry-run]
14
+ agentsdock-server recover
15
+ agentsdock-server update --server-url URL --server-identity ID --server-instance-id ID
16
+ --token-file PATH --manifest PATH --signature PATH
17
+ agentsdock-server --version
18
+
19
+ install: fresh default user service only; existing installations must use managed updates.
20
+ recover: on the server computer, recover an interrupted pre-activation migration; then retry the app update.
21
+ update: verify the signed descriptor and request an update when the exact server is idle.
22
+ No installation hooks run when this npm package is installed.
23
+ `
24
+ const ROOT_SELECTORS = ['AGENTS_SERVER_INSTALL_DIR', 'AGENTS_SERVER_CONFIG_DIR', 'AGENTS_SERVER_STATE_DIR', 'AGENTSDOCK_STATE_DIR', 'ZENITHBOT_AGENT_DIR', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME']
25
+
26
+ function parse(argv) {
27
+ const [command = 'help', ...args] = argv
28
+ if (['help', '--help', '-h', '--version'].includes(command)) {
29
+ if (args.length) throw new Error('Unexpected arguments.')
30
+ return { command }
31
+ }
32
+ const values = command === 'install' ? ['--port', '--bind'] : command === 'update'
33
+ ? ['--server-url', '--server-identity', '--server-instance-id', '--token-file', '--manifest', '--signature'] : []
34
+ if (!['install', 'update', 'recover'].includes(command)) throw new Error('Use install, update, recover, or --help.')
35
+ const flags = command === 'install' ? ['--non-interactive', '--dry-run'] : []
36
+ const options = {}
37
+ for (let index = 0; index < args.length; index++) {
38
+ const name = args[index]
39
+ if (Object.hasOwn(options, name)) throw new Error(`Duplicate option: ${name}`)
40
+ if (flags.includes(name)) options[name] = true
41
+ else if (values.includes(name)) {
42
+ const value = args[++index]
43
+ if (!value || value.startsWith('--') || /[\x00-\x1f\x7f]/.test(value)) throw new Error(`Missing or invalid value for ${name}`)
44
+ options[name] = value
45
+ } else throw new Error(`Unsupported option: ${name}`)
46
+ }
47
+ if (command === 'update') for (const name of values) if (!options[name]) throw new Error(`Required option: ${name}`)
48
+ if (options['--port'] && (!/^[1-9][0-9]{0,4}$/.test(options['--port']) || Number(options['--port']) > 65535)) throw new Error('Port must be an integer from 1 to 65535.')
49
+ if (options['--bind'] && !net.isIP(options['--bind'])) throw new Error('Bind address must be a literal IP address.')
50
+ return { command, options }
51
+ }
52
+
53
+ function readRegular(filename, maxBytes, { privateFile = false, uid = process.getuid?.() } = {}) {
54
+ const descriptor = fs.openSync(filename, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0))
55
+ try {
56
+ const info = fs.fstatSync(descriptor)
57
+ if (!info.isFile() || info.size > maxBytes || info.nlink !== 1) throw new Error('Expected a bounded regular file.')
58
+ if (privateFile && (info.uid !== uid || (info.mode & 0o077) !== 0)) throw new Error('Token file must be owned by the current user and readable only by that user.')
59
+ const bytes = fs.readFileSync(descriptor)
60
+ if (bytes.length > maxBytes) throw new Error('File exceeded its size limit.')
61
+ return bytes
62
+ } finally { fs.closeSync(descriptor) }
63
+ }
64
+
65
+ function ensureFreshInstall(context) {
66
+ if (context.uid === 0) throw new Error('Run as the user who will own the server, without sudo.')
67
+ if (!['darwin', 'linux'].includes(context.platform)) throw new Error('Server installation requires Linux or Apple silicon macOS.')
68
+ for (const name of ROOT_SELECTORS) if (context.env[name]) throw new Error(`Custom installation selector ${name} is unsupported by the fresh-install CLI. Use the existing server's managed updater.`)
69
+ const existingInstall = () => new Error('An existing server installation or state was found. Use AgentsDock or agentsdock-server update; no installer was started.')
70
+ const safeDirectory = info => info.isDirectory() && !info.isSymbolicLink() && info.uid === context.uid && (info.mode & 0o022) === 0 && (info.mode & 0o500) === 0o500
71
+ const allowEmptyScaffold = (relative, child) => {
72
+ const root = path.join(context.home, relative)
73
+ let rootInfo
74
+ try { rootInfo = fs.lstatSync(root) } catch (error) { if (error.code !== 'ENOENT') throw error }
75
+ if (!rootInfo) return
76
+ // Failed bootstrap or preactivation can leave these exact empty directories.
77
+ // Never delete them or admit files, credentials, histories, links or locks.
78
+ // install.sh repeats this check under exclusive installation ownership.
79
+ if (!safeDirectory(rootInfo)) throw existingInstall()
80
+ const entries = fs.readdirSync(root)
81
+ if (entries.length > 1 || (entries.length === 1 && entries[0] !== child)) throw existingInstall()
82
+ if (entries.length === 1) {
83
+ const nested = path.join(root, child)
84
+ if (!safeDirectory(fs.lstatSync(nested)) || fs.readdirSync(nested).length !== 0) throw existingInstall()
85
+ }
86
+ }
87
+ allowEmptyScaffold('.local/share/agents-server', 'releases')
88
+ allowEmptyScaffold('.config/agents-server')
89
+ allowEmptyScaffold('.agentsdock', 'admin')
90
+ const targets = [
91
+ '.zenithbot-agent',
92
+ '.config/systemd/user/agents-server.service', '.config/systemd/user/zenithbot-agent.service',
93
+ 'Library/LaunchAgents/com.agentsdock.server.plist',
94
+ ]
95
+ for (const relative of targets) {
96
+ try {
97
+ fs.lstatSync(path.join(context.home, relative))
98
+ throw existingInstall()
99
+ } catch (error) { if (error.code !== 'ENOENT') throw error }
100
+ }
101
+ if (context.platform === 'darwin') {
102
+ const check = context.spawn('/bin/launchctl', ['print', `gui/${context.uid}/com.agentsdock.server`], { encoding: 'utf8', timeout: 10000 })
103
+ if (check.status === 0) throw new Error('An AgentsServer service already exists. Use its managed updater.')
104
+ if (check.error || !/could not find service|service.*not found/i.test(`${check.stdout || ''} ${check.stderr || ''}`)) throw new Error('Could not verify the user service is absent. No installer was started.')
105
+ } else {
106
+ for (const unit of ['agents-server.service', 'zenithbot-agent.service']) {
107
+ const check = context.spawn('systemctl', ['--user', 'show', unit, '--property=LoadState', '--value'], { encoding: 'utf8', timeout: 10000 })
108
+ if (check.error || String(check.stdout).trim() !== 'not-found') throw new Error('An existing user service was found or its absence could not be verified. Use its managed updater.')
109
+ }
110
+ }
111
+ }
112
+
113
+ function recoveryContext(context) {
114
+ if (context.uid === 0) throw new Error('Run as the user who owns the server, without sudo.')
115
+ if (!['darwin', 'linux'].includes(context.platform)) throw new Error('Server recovery requires Linux or Apple silicon macOS.')
116
+ for (const name of ROOT_SELECTORS) if (context.env[name]) throw new Error(`Custom installation selector ${name} is unsupported by recovery; no installer was started.`)
117
+ const inspect = filename => {
118
+ try { return fs.lstatSync(filename) } catch (error) { if (error.code !== 'ENOENT') throw error; return null }
119
+ }
120
+ const directory = (filename, { optional = false, privateDirectory = false } = {}) => {
121
+ const info = inspect(filename)
122
+ if (!info && optional) return null
123
+ if (!info || !info.isDirectory() || info.isSymbolicLink() || info.uid !== context.uid ||
124
+ (info.mode & (privateDirectory ? 0o077 : 0o022)) !== 0 || (info.mode & 0o500) !== 0o500) {
125
+ throw new Error('Recovery requires owned, unlinked, safely permissioned default installation directories.')
126
+ }
127
+ return info
128
+ }
129
+ const readPrivate = (filename, limit) => {
130
+ const fd = fs.openSync(filename, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK)
131
+ try {
132
+ const info = fs.fstatSync(fd)
133
+ if (!info.isFile() || info.uid !== context.uid || (info.mode & 0o077) !== 0 || info.nlink !== 1 || info.size > limit) {
134
+ throw new Error('Recovery requires a bounded, private, current-user-owned regular control file.')
135
+ }
136
+ const bytes = fs.readFileSync(fd)
137
+ if (bytes.length > limit) throw new Error('Recovery control file exceeded its size limit.')
138
+ return bytes
139
+ } finally { fs.closeSync(fd) }
140
+ }
141
+ directory(context.home)
142
+ let root = context.home
143
+ for (const component of ['.local', 'share', 'agents-server']) {
144
+ root = path.join(root, component)
145
+ if (!directory(root, { optional: true })) return null
146
+ }
147
+ const rootInfo = directory(root)
148
+ const journalDirectory = path.join(root, '.activation-transaction')
149
+ if (!directory(journalDirectory, { optional: true, privateDirectory: true })) return null
150
+ const journal = JSON.parse(readPrivate(path.join(journalDirectory, 'manifest.json'), 256 * 1024))
151
+ const origin = ['rolling-back', 'rolled-back', 'rollback-healthy'].includes(journal.phase) ? journal.rollback_from : journal.phase
152
+ const config = path.join(context.home, '.config/agents-server')
153
+ const state = path.join(context.home, '.agentsdock')
154
+ const service = context.platform === 'darwin' ? path.join(context.home, 'Library/LaunchAgents/com.agentsdock.server.plist') : path.join(context.home, '.config/systemd/user/agents-server.service')
155
+ if (journal.format !== 3 || !['prepared', 'guarded'].includes(origin) || journal.intent !== 'server-update' ||
156
+ !/^activation-[0-9a-f]{24}$/.test(journal.transaction_id) ||
157
+ !/^\d+\.\d+\.\d+(?:-beta\.[1-9]\d*)?$/.test(journal.release_version) ||
158
+ journal.release_dir !== path.join(root, 'releases', journal.release_version) ||
159
+ journal.env_path !== path.join(config, 'env') || journal.service_path !== service ||
160
+ journal.service_state !== 'running' || journal.execution?.gateway_state !== 'absent' ||
161
+ journal.execution?.runtime_dir !== path.join(state, 'execution') ||
162
+ !Number.isSafeInteger(journal.execution?.api_contract) || journal.execution.api_contract < 1 ||
163
+ journal.hub?.kind !== 'server-update' || journal.hub?.data_dir !== path.join(state, 'team-hub')) {
164
+ throw new Error('This journal is not a supported interrupted pre-activation migration; no installer was started.')
165
+ }
166
+ directory(state, { privateDirectory: true })
167
+ const identity = readPrivate(path.join(state, 'server-identity'), 1024).toString('utf8').trim()
168
+ if (!/^[A-Za-z0-9_.:-]{8,240}$/.test(identity) || journal.hub.host_identity !== identity) {
169
+ throw new Error('The pending migration belongs to a different server identity; no installer was started.')
170
+ }
171
+ // The installer validates complete native configuration, links, ownership and
172
+ // authenticated incumbent health under its lock. These checks only select
173
+ // the exact existing transaction; they never grant recovery authority.
174
+ const ownerParent = path.join(root, '.activation-recovery')
175
+ if (directory(ownerParent, { optional: true, privateDirectory: true }) && inspect(path.join(ownerParent, journal.transaction_id))) {
176
+ throw new Error('This activation already has a recovery owner; no competing recovery was started.')
177
+ }
178
+ return { root, rootInfo, journalDirectory, journal, identity }
179
+ }
180
+
181
+ function validateOrigin(value) {
182
+ const url = new URL(value)
183
+ if (url.username || url.password || url.search || url.hash || !['', '/'].includes(url.pathname)) throw new Error('Server URL must be an origin without credentials, path, query, or fragment.')
184
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) throw new Error('Use HTTPS for remote servers; HTTP is allowed only on loopback.')
185
+ return url.origin
186
+ }
187
+
188
+ async function requestJSON(context, url, token, body) {
189
+ // Native admin routes intentionally reject browser transport headers. Node's
190
+ // fetch adds Sec-Fetch-Mode, so use the native HTTP client without redirects.
191
+ const payload = body ? Buffer.from(JSON.stringify(body)) : null
192
+ return new Promise((resolve, reject) => {
193
+ let deadline
194
+ const fail = error => { clearTimeout(deadline); reject(error) }
195
+ const finish = value => { clearTimeout(deadline); resolve(value) }
196
+ const send = context.request || (url.startsWith('https:') ? https.request : http.request)
197
+ const request = send(url, {
198
+ method: body ? 'POST' : 'GET',
199
+ headers: { 'X-AgentsDock-Token': token, ...(payload ? { 'Content-Type': 'application/json', 'Content-Length': payload.length } : {}) },
200
+ }, response => {
201
+ if (response.statusCode < 200 || response.statusCode >= 300) {
202
+ response.destroy()
203
+ fail(new Error(`Server request failed (HTTP ${response.statusCode}); no installer fallback was attempted.`))
204
+ return
205
+ }
206
+ const chunks = []
207
+ let size = 0
208
+ response.on('data', chunk => {
209
+ size += chunk.length
210
+ if (size > 1024 * 1024) { request.destroy(new Error('Server response exceeded its size limit.')); return }
211
+ chunks.push(chunk)
212
+ })
213
+ response.on('error', fail)
214
+ response.on('end', () => {
215
+ try { finish(JSON.parse(Buffer.concat(chunks).toString('utf8'))) } catch { fail(new Error('Server returned invalid JSON.')) }
216
+ })
217
+ })
218
+ request.on('error', fail)
219
+ deadline = setTimeout(() => request.destroy(new Error('Server request timed out.')), 30000)
220
+ deadline.unref()
221
+ request.setTimeout(30000, () => request.destroy(new Error('Server request timed out.')))
222
+ request.end(payload)
223
+ })
224
+ }
225
+
226
+ async function run(argv, overrides = {}) {
227
+ const context = { env: process.env, home: os.homedir(), uid: process.getuid?.(), platform: process.platform, spawn: spawnSync, packageRoot: path.resolve(__dirname, '..'), print: text => process.stdout.write(`${text}\n`), ...overrides }
228
+ const { command, options } = parse(argv)
229
+ if (['help', '--help', '-h'].includes(command)) { context.print(HELP); return 0 }
230
+ const metadata = JSON.parse(readRegular(path.join(context.packageRoot, 'package.json'), 64000))
231
+ if (command === '--version') { context.print(metadata.version); return 0 }
232
+ const payload = path.join(context.packageRoot, 'server')
233
+ const payloadVersion = readRegular(path.join(payload, 'VERSION'), 200).toString('utf8').trim()
234
+ if (payloadVersion !== metadata.version) throw new Error('Package and server payload versions do not match.')
235
+ if (command === 'recover') {
236
+ const recovery = recoveryContext(context)
237
+ if (!recovery) { context.print('No unfinished default server migration was found. No changes were made.'); return 0 }
238
+ const installer = path.join(payload, 'install.sh')
239
+ readRegular(installer, 2 * 1024 * 1024)
240
+ const args = [installer, '--recover-only', '--recover-unarmed-only', '--non-interactive', '--execution-mode', 'split',
241
+ '--expected-activation-id', recovery.journal.transaction_id, '--release-version', recovery.journal.release_version,
242
+ '--expected-api-contract', String(recovery.journal.execution.api_contract), '--expected-server-identity', recovery.identity]
243
+ const env = { HOME: context.home }
244
+ for (const key of ['PATH', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'LANG', 'LC_ALL', 'TERM', 'TERMINFO', 'SSL_CERT_FILE', 'SSL_CERT_DIR']) {
245
+ if (context.env[key]) env[key] = context.env[key]
246
+ }
247
+ const result = context.spawn('/bin/bash', args, { stdio: 'inherit', env })
248
+ if (result.error) throw new Error('Could not launch the bundled recovery installer.')
249
+ if (![0, 75].includes(result.status)) return Number.isInteger(result.status) ? result.status : 1
250
+ const rootAfter = fs.lstatSync(recovery.root)
251
+ if (!rootAfter.isDirectory() || rootAfter.isSymbolicLink() || rootAfter.dev !== recovery.rootInfo.dev || rootAfter.ino !== recovery.rootInfo.ino) {
252
+ throw new Error('Installation ownership changed during recovery; verify the server before retrying.')
253
+ }
254
+ try { fs.lstatSync(recovery.journalDirectory); throw new Error('The activation journal remains; recovery is not complete.') } catch (error) { if (error.code !== 'ENOENT') throw error }
255
+ context.print('The interrupted migration was recovered. Reconnect to AgentsDock and retry the update; the server has not been upgraded by this command.')
256
+ return 0
257
+ }
258
+ if (command === 'install') {
259
+ ensureFreshInstall(context)
260
+ const installer = path.join(payload, 'install.sh')
261
+ readRegular(installer, 2 * 1024 * 1024)
262
+ const args = [installer, '--fresh-install-only', '--release-version', metadata.version]
263
+ for (const name of ['--port', '--bind']) if (options[name]) args.push(name, options[name])
264
+ if (options['--non-interactive']) args.push('--non-interactive')
265
+ if (options['--dry-run']) { context.print(JSON.stringify({ command: '/bin/bash', args, executed: false })); return 0 }
266
+ const result = context.spawn('/bin/bash', args, { stdio: 'inherit', env: context.env })
267
+ if (result.error) throw new Error('Could not launch the bundled installer.')
268
+ return Number.isInteger(result.status) ? result.status : 1
269
+ }
270
+ const origin = validateOrigin(options['--server-url'])
271
+ for (const name of ['--server-identity', '--server-instance-id']) if (!/^[A-Za-z0-9_.:-]{1,128}$/.test(options[name])) throw new Error('Invalid expected server identity.')
272
+ const manifest = readRegular(options['--manifest'], 8192)
273
+ const signature = readRegular(options['--signature'], 64)
274
+ const publicKey = readRegular(path.join(payload, 'release-public-key.pem'), 4096)
275
+ if (signature.length !== 64 || !crypto.verify(null, manifest, publicKey, signature)) throw new Error('Release descriptor signature is invalid.')
276
+ const descriptor = JSON.parse(manifest)
277
+ if (descriptor.schema !== 2 || descriptor.distribution !== 'npm' || descriptor.npm?.name !== '@agentsdock/server') throw new Error('Expected a signed npm server release descriptor.')
278
+ const token = readRegular(options['--token-file'], 4096, { privateFile: true, uid: context.uid }).toString('utf8').trim()
279
+ if (!token || /[\x00-\x20\x7f]/.test(token)) throw new Error('Token file must contain one nonempty server token.')
280
+ const identity = { expected_server_identity: options['--server-identity'], expected_server_instance_id: options['--server-instance-id'] }
281
+ const health = await requestJSON(context, `${origin}/api/health`, token)
282
+ if (health.server_identity !== identity.expected_server_identity || health.server_instance_id !== identity.expected_server_instance_id) throw new Error('The connected server or its process instance changed. No update was requested.')
283
+ const result = await requestJSON(context, `${origin}/api/admin/update/ensure`, token, { ...identity, manifest_base64: manifest.toString('base64'), signature_base64: signature.toString('base64') })
284
+ context.print(JSON.stringify(result, null, 2))
285
+ return 0
286
+ }
287
+
288
+ if (require.main === module) run(process.argv.slice(2)).then(code => { process.exitCode = code }).catch(error => { process.stderr.write(`agentsdock-server: ${error.message}\n`); process.exitCode = 1 })
289
+ module.exports = { parse, readRegular, ensureFreshInstall, recoveryContext, validateOrigin, run }
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@agentsdock/server",
3
+ "version": "1.0.7-beta.5",
4
+ "description": "AgentsDock's self-hosted Python server and explicit installation CLI",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/ZhengyiLuo/AgentsDock.git",
9
+ "directory": "server"
10
+ },
11
+ "bin": {
12
+ "agentsdock-server": "npm/cli.cjs"
13
+ },
14
+ "engines": {
15
+ "node": ">=22.14.0"
16
+ },
17
+ "os": [
18
+ "darwin",
19
+ "linux"
20
+ ],
21
+ "files": [
22
+ "npm/cli.cjs",
23
+ "server/",
24
+ "README.md",
25
+ "LICENSE",
26
+ "NOTICE"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public",
30
+ "registry": "https://registry.npmjs.org/"
31
+ }
32
+ }