@swarm-agent/cli 0.1.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +130 -0
- package/bin/swarm-headless.js +20 -0
- package/package.json +34 -0
- package/runtime-image.json +9 -0
- package/src/launcher.js +201 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Swarm contributors
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# @swarm-agent/cli — unpublished Linux headless candidate
|
|
2
|
+
|
|
3
|
+
A thin Node 22+ launcher for a **local** Docker or rootless Podman engine. Installs
|
|
4
|
+
are inert: no lifecycle scripts, daemon downloads, image pulls or container starts.
|
|
5
|
+
The executable is `swarm-headless`, not the native `swarm` launcher. Only Linux
|
|
6
|
+
amd64 container images are supported. Docker must use its local Unix socket;
|
|
7
|
+
remote contexts/connections are rejected. Rootless Podman is explicitly local.
|
|
8
|
+
|
|
9
|
+
Package names are candidate identities, not a claim of npm scope ownership.
|
|
10
|
+
Nothing here authorizes registry publication. GitHub review/merge and separate
|
|
11
|
+
publication approval precede registry delivery.
|
|
12
|
+
|
|
13
|
+
## Image pin
|
|
14
|
+
|
|
15
|
+
`runtime-image.json` is the packaged authority. Release packaging supplies `version`
|
|
16
|
+
(semver), `distribution: "ghcr"`, `reference` (exactly
|
|
17
|
+
`ghcr.io/swarm-agent/swarm-headless@sha256:<manifest>`), `manifestDigest`, `imageId`
|
|
18
|
+
(the config digest), `platform: "linux/amd64"` and `sourceCommit` (40 hex characters).
|
|
19
|
+
`swarm-headless install` explicitly pulls that reference for Linux amd64 and verifies
|
|
20
|
+
RepoDigests, config ID and platform. It creates no containers, networks or state
|
|
21
|
+
volumes. Failed pulls/verification stop without tag or local-image fallback; an
|
|
22
|
+
engine may retain downloaded image layers. Retry explicitly after resolving errors.
|
|
23
|
+
|
|
24
|
+
Start and setup reverify the local immutable image before running anything. Start
|
|
25
|
+
uses the verified config ID with `--pull=never`; neither operation downloads images.
|
|
26
|
+
Help/version never access the engine. No install marker or second pin authority exists.
|
|
27
|
+
|
|
28
|
+
The checked-in metadata remains explicitly `local-candidate`, **not a published
|
|
29
|
+
registry digest**. In that mode install only verifies an already built/loaded image;
|
|
30
|
+
it never pulls the candidate tag. Release packaging must replace metadata using real
|
|
31
|
+
qualified registry provenance and repeat package/live checks before publication.
|
|
32
|
+
|
|
33
|
+
To transfer the unpublished image, on the build host (outside source directories):
|
|
34
|
+
|
|
35
|
+
<copy>
|
|
36
|
+
docker save --output "$IMAGE_ARCHIVE" localhost/swarm-headless:0.1.0-headless.1
|
|
37
|
+
# On the intended isolated runtime host:
|
|
38
|
+
docker load --input "$IMAGE_ARCHIVE"
|
|
39
|
+
</copy>
|
|
40
|
+
|
|
41
|
+
For Podman use `podman save --format docker-archive` and `podman load`. Verify the
|
|
42
|
+
loaded image ID against `runtime-image.json`; the launcher fails if it is absent.
|
|
43
|
+
|
|
44
|
+
## Install and explicit lifecycle
|
|
45
|
+
|
|
46
|
+
Install the local tarball from a clean consumer directory; no Swarm checkout is
|
|
47
|
+
needed by the installed launcher. Set `CLI_TARBALL` to its absolute path.
|
|
48
|
+
|
|
49
|
+
<copy>
|
|
50
|
+
npm install "$CLI_TARBALL"
|
|
51
|
+
npx --no-install swarm-headless --help
|
|
52
|
+
npx --no-install swarm-headless install
|
|
53
|
+
npx --no-install swarm-headless start --project "$PROJECT_DIR"
|
|
54
|
+
npx --no-install swarm-headless status
|
|
55
|
+
npx --no-install swarm-headless stop
|
|
56
|
+
npx --no-install swarm-headless start --project "$PROJECT_DIR" --recreate
|
|
57
|
+
</copy>
|
|
58
|
+
|
|
59
|
+
Set `PROJECT_DIR` to one clean, committed, ordinary Git checkout (not a linked
|
|
60
|
+
worktree), readable/writable by image UID/GID 10001. The launcher rejects the home
|
|
61
|
+
directory, its ancestors, root and comma/newline mount injection. Symlinks resolve
|
|
62
|
+
to the selected canonical directory. It never recursively changes ownership.
|
|
63
|
+
Rootless engines remap IDs: prepare the selected project for that mapping first.
|
|
64
|
+
|
|
65
|
+
Use `--engine podman` on **every** operation for rootless Podman. Use the same
|
|
66
|
+
`--name example` on lifecycle/setup operations for a separate instance (`install`
|
|
67
|
+
is image-only and accepts only `--engine`). `--port` is start-only
|
|
68
|
+
(default 7783, host binding always `127.0.0.1`). The four state volumes are
|
|
69
|
+
`NAME-config`, `NAME-data`, `NAME-cache`, `NAME-logs`; the dedicated network is
|
|
70
|
+
`NAME-network`. No home, engine socket, privileged mode or host network is mounted.
|
|
71
|
+
Keep that network free of untrusted peers. Local engine authority is administrative.
|
|
72
|
+
|
|
73
|
+
`stop` retains the container and all volumes. `start --recreate` requires a stopped,
|
|
74
|
+
launcher-labelled instance and the same project; it removes only that container,
|
|
75
|
+
without `--force` or `--volumes`, then attaches the original named state. Missing
|
|
76
|
+
state volumes, foreign name collisions and failed inspections fail closed. A failed
|
|
77
|
+
replacement may leave a stopped container removed, but state volumes remain; inspect
|
|
78
|
+
the engine before retrying. Never attach the same data volume to concurrent daemons.
|
|
79
|
+
The launcher does not delete data or perform automatic recovery/polling. To upgrade,
|
|
80
|
+
stop with the old package, install the new version's pinned image, then use
|
|
81
|
+
`start --recreate` with the same name/project. Back up durable state beforehand;
|
|
82
|
+
image verification does not establish database downgrade compatibility.
|
|
83
|
+
|
|
84
|
+
## Setup (explicit choices only)
|
|
85
|
+
|
|
86
|
+
`setup` forwards only the existing `swarmctl setup` operations through container
|
|
87
|
+
exec. No host settings or model assignments are changed. No setup step is automatic.
|
|
88
|
+
Set `PROVIDER`, `MODEL`, `THINKING` explicitly and choose a private existing key file
|
|
89
|
+
outside the project. Do not enable shell tracing or put keys in command arguments.
|
|
90
|
+
|
|
91
|
+
<copy>
|
|
92
|
+
npx --no-install swarm-headless setup -- status
|
|
93
|
+
npx --no-install swarm-headless setup -- identity --username owner --name Headless
|
|
94
|
+
npx --no-install swarm-headless setup -- credential --provider "$PROVIDER" --api-key-stdin < "$PROVIDER_KEY_FILE"
|
|
95
|
+
for role in action plan compact finder coder designer router; do
|
|
96
|
+
npx --no-install swarm-headless setup -- model --role "$role" --provider "$PROVIDER" --model "$MODEL" --thinking "$THINKING" || break
|
|
97
|
+
done
|
|
98
|
+
npx --no-install swarm-headless setup -- workspace --path /project --name Project
|
|
99
|
+
npx --no-install swarm-headless setup -- complete
|
|
100
|
+
</copy>
|
|
101
|
+
|
|
102
|
+
Execute steps individually and stop on any failure. The model loop explicitly
|
|
103
|
+
chooses the same model for all roles; use individual calls for different choices.
|
|
104
|
+
A saved credential is not proof of provider validity. Credentials are stdin-only;
|
|
105
|
+
the launcher refuses terminal key input and never allocates a TTY. `setup complete`
|
|
106
|
+
checks canonical prerequisites. `setup status` can be retried explicitly after the
|
|
107
|
+
private socket is ready; there is no TCP setup fallback.
|
|
108
|
+
|
|
109
|
+
To export a one-hour scoped SDK token, select a **new**, absolute token file in a
|
|
110
|
+
private directory outside the project:
|
|
111
|
+
|
|
112
|
+
<copy>
|
|
113
|
+
(umask 077; set -C; npx --no-install swarm-headless setup -- sdk-token --expires-in-seconds 3600 > "$SWARM_SDK_TOKEN_FILE")
|
|
114
|
+
# Revoke using the non-secret ID from the export, never the token itself:
|
|
115
|
+
npx --no-install swarm-headless setup -- revoke-sdk-token --id "$TOKEN_ID"
|
|
116
|
+
</copy>
|
|
117
|
+
|
|
118
|
+
Token export refuses terminal output; protect the plaintext file with mode 0600.
|
|
119
|
+
A failed export may already have minted a token: inspect/revoke before retrying.
|
|
120
|
+
Use the SDK's packaged `examples/headless-session.ts` with the loopback endpoint.
|
|
121
|
+
Scoped session write access is powerful and can approve tools; it is not a sandbox.
|
|
122
|
+
|
|
123
|
+
## Validation limits
|
|
124
|
+
|
|
125
|
+
`npm test` exercises command construction, negative paths and state-preserving
|
|
126
|
+
operation ordering against an injected engine. `tests/scripts/headless_npm_test.mjs`
|
|
127
|
+
builds the SDK outside the checkout, inspects packs, installs with normal lifecycle
|
|
128
|
+
behavior into an empty consumer and checks ESM/types/CLI commands. Neither starts
|
|
129
|
+
Swarm. Real setup, networking, permissions and restart persistence require the
|
|
130
|
+
separate isolated live qualification step.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { HELP, parseArgs, engineRunner, runLauncher } from '../src/launcher.js';
|
|
4
|
+
|
|
5
|
+
try {
|
|
6
|
+
const opts = parseArgs(process.argv.slice(2));
|
|
7
|
+
const pin = JSON.parse(readFileSync(new URL('../runtime-image.json', import.meta.url), 'utf8'));
|
|
8
|
+
if (opts.command === 'help') console.log(HELP);
|
|
9
|
+
else if (opts.command === 'version') console.log(pin.version);
|
|
10
|
+
else {
|
|
11
|
+
if (process.platform !== 'linux') throw Error('This candidate supports Linux hosts only');
|
|
12
|
+
runLauncher(opts, pin, engineRunner(opts.engine), { stdinTTY: process.stdin.isTTY, stdoutTTY: process.stdout.isTTY });
|
|
13
|
+
}
|
|
14
|
+
} catch (error) {
|
|
15
|
+
// Only our fixed messages are safe; filesystem/JSON errors can contain paths/data.
|
|
16
|
+
const message = error instanceof Error && !error.code && !(error instanceof SyntaxError)
|
|
17
|
+
? error.message : 'Cannot read package metadata or selected project';
|
|
18
|
+
console.error(`swarm-headless: ${message}`);
|
|
19
|
+
process.exitCode = 1;
|
|
20
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@swarm-agent/cli",
|
|
3
|
+
"version": "0.1.47",
|
|
4
|
+
"description": "Explicit headless Swarm container launcher",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"swarm-headless": "bin/swarm-headless.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src",
|
|
12
|
+
"runtime-image.json",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"publishConfig": {
|
|
17
|
+
"access": "public",
|
|
18
|
+
"registry": "https://registry.npmjs.org/"
|
|
19
|
+
},
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/swarm-agent/swarm.git"
|
|
23
|
+
},
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=22"
|
|
26
|
+
},
|
|
27
|
+
"os": [
|
|
28
|
+
"linux"
|
|
29
|
+
],
|
|
30
|
+
"scripts": {
|
|
31
|
+
"test": "node --test --test-concurrency=1 test/*.test.js"
|
|
32
|
+
},
|
|
33
|
+
"license": "Apache-2.0"
|
|
34
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": "0.1.47",
|
|
3
|
+
"manifestDigest": "sha256:875ef95fa73f97d8a2f39279989746522bede8147111690ee49afc5441e6930e",
|
|
4
|
+
"imageId": "sha256:31faa8dda74c53766d9401692451b1f1d66ea3a1d8352e99dd10c684f261f2e8",
|
|
5
|
+
"platform": "linux/amd64",
|
|
6
|
+
"sourceCommit": "81c1085e26f84500c478919578a898f15f6fe83d",
|
|
7
|
+
"distribution": "ghcr",
|
|
8
|
+
"reference": "ghcr.io/swarm-agent/swarm-headless@sha256:875ef95fa73f97d8a2f39279989746522bede8147111690ee49afc5441e6930e"
|
|
9
|
+
}
|
package/src/launcher.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { lstatSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { isAbsolute, join, parse, relative } from 'node:path';
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
|
|
7
|
+
const LABEL = 'dev.swarm.headless';
|
|
8
|
+
const VOLUMES = { config: '/etc/swarmd', data: '/var/lib/swarmd', cache: '/var/cache/swarmd', logs: '/var/log/swarmd' };
|
|
9
|
+
export const HELP = `swarm-headless <install|start|stop|status|setup> [options]
|
|
10
|
+
--engine docker|podman Local engine (default docker)
|
|
11
|
+
--name NAME Instance name (default swarm-headless)
|
|
12
|
+
start --project PATH [--port 7783] [--recreate]
|
|
13
|
+
setup [options] -- <status|identity|credential|model|workspace|complete|sdk-token|revoke-sdk-token> [flags]
|
|
14
|
+
--version | --help No engine access
|
|
15
|
+
install explicitly pulls/verifies the packaged GHCR digest (or verifies a loaded candidate).
|
|
16
|
+
No npm install-time actions, automatic pulls, model defaults or volume deletion.
|
|
17
|
+
Stop preserves the container and all named state volumes. Recreate requires a
|
|
18
|
+
stopped, launcher-owned container and the same project. See README for setup.`;
|
|
19
|
+
|
|
20
|
+
export function parseArgs(argv) {
|
|
21
|
+
const [command, ...rest] = argv;
|
|
22
|
+
if (!command || ['--help', 'help'].includes(command)) return { command: 'help' };
|
|
23
|
+
if (command === '--version') return { command: 'version' };
|
|
24
|
+
if (!['install', 'start', 'stop', 'status', 'setup'].includes(command)) throw Error('Unknown command; use --help');
|
|
25
|
+
const opts = { command, engine: 'docker', name: 'swarm-headless', port: 7783, recreate: false, setup: [] };
|
|
26
|
+
const seen = new Set();
|
|
27
|
+
for (let i = 0; i < rest.length; i++) {
|
|
28
|
+
const key = rest[i];
|
|
29
|
+
if (key === '--' && command === 'setup') { opts.setup = rest.slice(i + 1); break; }
|
|
30
|
+
if (seen.has(key)) throw Error('Duplicate option');
|
|
31
|
+
seen.add(key);
|
|
32
|
+
if (key === '--recreate' && command === 'start') { opts.recreate = true; continue; }
|
|
33
|
+
if (!['--engine', ...(command === 'install' ? [] : ['--name']), ...(command === 'start' ? ['--project', '--port'] : [])].includes(key)) throw Error('Invalid option; secrets must use stdin, never flags');
|
|
34
|
+
const value = rest[++i];
|
|
35
|
+
if (!value || value.startsWith('--')) throw Error('Option needs a value');
|
|
36
|
+
opts[key.slice(2)] = value;
|
|
37
|
+
}
|
|
38
|
+
if (!['docker', 'podman'].includes(opts.engine)) throw Error('Engine must be docker or podman');
|
|
39
|
+
if (!/^[a-z][a-z0-9-]{0,47}$/.test(opts.name)) throw Error('Invalid instance name');
|
|
40
|
+
if (!/^\d+$/.test(String(opts.port)) || Number(opts.port) < 1024 || Number(opts.port) > 65535) throw Error('Port must be 1024–65535');
|
|
41
|
+
opts.port = Number(opts.port);
|
|
42
|
+
if (command === 'setup') validateSetup(opts.setup);
|
|
43
|
+
return opts;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function validateSetup(args) {
|
|
47
|
+
const flags = {
|
|
48
|
+
status: [], complete: [], identity: ['username', 'name'],
|
|
49
|
+
credential: ['provider', 'api-key-stdin'],
|
|
50
|
+
model: ['role', 'provider', 'model', 'thinking', 'service-tier', 'context-mode'],
|
|
51
|
+
workspace: ['path', 'name'], 'sdk-token': ['expires-in-seconds'], 'revoke-sdk-token': ['id'],
|
|
52
|
+
};
|
|
53
|
+
if (!Object.hasOwn(flags, args[0])) throw Error('Select a supported setup operation after --');
|
|
54
|
+
const seen = new Set();
|
|
55
|
+
for (let i = 1; i < args.length; i++) {
|
|
56
|
+
const flag = args[i];
|
|
57
|
+
if (!flag.startsWith('--') || !flags[args[0]].includes(flag.slice(2)) || seen.has(flag)) throw Error('Invalid setup flags; secrets must use stdin');
|
|
58
|
+
seen.add(flag);
|
|
59
|
+
if (flag === '--api-key-stdin') continue;
|
|
60
|
+
const value = args[++i];
|
|
61
|
+
if (!value || value.startsWith('--')) throw Error('Setup flag needs a value');
|
|
62
|
+
if (flag === '--path' && value !== '/project') throw Error('Workspace must be /project');
|
|
63
|
+
}
|
|
64
|
+
if (args[0] === 'credential' && !seen.has('--api-key-stdin')) throw Error('Credentials require --api-key-stdin');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function selectedProject(path) {
|
|
68
|
+
if (!path || !isAbsolute(path)) throw Error('Select an absolute project path');
|
|
69
|
+
const result = realpathSync(path);
|
|
70
|
+
const home = realpathSync(homedir());
|
|
71
|
+
const toHome = relative(result, home);
|
|
72
|
+
if (result === parse(result).root || !toHome || (!toHome.startsWith('..') && !isAbsolute(toHome))) throw Error('Cannot mount the home directory or its ancestors');
|
|
73
|
+
if (/[\r\n,]/.test(result) || !lstatSync(result).isDirectory()) throw Error('Invalid project mount path');
|
|
74
|
+
// Linked worktrees can refer to metadata outside the only authorized mount.
|
|
75
|
+
if (!lstatSync(join(result, '.git')).isDirectory() || lstatSync(join(result, '.git')).isSymbolicLink()) throw Error('Select a normal Git checkout, not a linked worktree');
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function engineRunner(engine, env = process.env) {
|
|
80
|
+
if (env.DOCKER_CONTEXT || env.CONTAINER_CONNECTION || env.CONTAINER_HOST ||
|
|
81
|
+
(env.DOCKER_HOST && !env.DOCKER_HOST.startsWith('unix://'))) throw Error('Only a local Unix-socket engine is supported; unset remote context variables');
|
|
82
|
+
const prefix = engine === 'podman' ? ['--remote=false'] : ['--host', env.DOCKER_HOST || 'unix:///var/run/docker.sock'];
|
|
83
|
+
return (args, options = {}) => {
|
|
84
|
+
const result = spawnSync(engine, [...prefix, ...args], {
|
|
85
|
+
shell: false, encoding: 'utf8', maxBuffer: 1024 * 1024, timeout: 150000,
|
|
86
|
+
stdio: options.stream ? ['inherit', 'inherit', 'pipe'] : ['ignore', 'pipe', 'pipe'],
|
|
87
|
+
});
|
|
88
|
+
// Do not print engine stderr/argv: exec failures can contain private values.
|
|
89
|
+
if (result.error || result.status !== 0) throw Error('Container engine operation failed; inspect the engine and instance before retrying (details withheld)');
|
|
90
|
+
return result.stdout || '';
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function decode(text) {
|
|
95
|
+
const value = JSON.parse(text);
|
|
96
|
+
if (!Array.isArray(value) || value.length !== 1) throw Error('Unexpected engine inspection response');
|
|
97
|
+
return value[0];
|
|
98
|
+
}
|
|
99
|
+
const imageID = value => `sha256:${String(value).replace(/^sha256:/, '')}`;
|
|
100
|
+
const lines = text => text.trim().split('\n').filter(Boolean);
|
|
101
|
+
|
|
102
|
+
function validatePin(pin) {
|
|
103
|
+
const fields = ['version', 'imageId', 'platform', 'sourceCommit', 'distribution'];
|
|
104
|
+
if (pin.distribution === 'ghcr') fields.push('reference', 'manifestDigest');
|
|
105
|
+
if (fields.some(key => typeof pin[key] !== 'string' || pin[key] !== pin[key].trim())) throw Error('Invalid packaged image pin');
|
|
106
|
+
const digest = /^sha256:[a-f0-9]{64}$/;
|
|
107
|
+
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;
|
|
108
|
+
if (!digest.test(pin.imageId) || pin.platform !== 'linux/amd64' ||
|
|
109
|
+
!semver.test(pin.version) || !/^[a-f0-9]{40}$/.test(pin.sourceCommit)) throw Error('Invalid packaged image pin');
|
|
110
|
+
if (pin.distribution === 'local-candidate') return;
|
|
111
|
+
if (pin.distribution !== 'ghcr' || !digest.test(pin.manifestDigest) ||
|
|
112
|
+
pin.reference !== `ghcr.io/swarm-agent/swarm-headless@${pin.manifestDigest}`) throw Error('Invalid packaged registry pin');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function verifyImage(pin, run) {
|
|
116
|
+
// Inspect the manifest reference too: a matching config alone is not registry provenance.
|
|
117
|
+
const image = decode(run(['image', 'inspect', pin.distribution === 'ghcr' ? pin.reference : pin.imageId]));
|
|
118
|
+
if (imageID(image.Id) !== pin.imageId || image.Os !== 'linux' || image.Architecture !== 'amd64' ||
|
|
119
|
+
(pin.distribution === 'ghcr' && (!Array.isArray(image.RepoDigests) || !image.RepoDigests.includes(pin.reference)))) {
|
|
120
|
+
throw Error('Image does not match the packaged digest, config or platform; run install with the matching package');
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function runLauncher(opts, pin, run, io = {}) {
|
|
125
|
+
const show = io.show || console.log;
|
|
126
|
+
if (opts.command === 'help') { show(HELP); return; }
|
|
127
|
+
if (opts.command === 'version') { show(pin.version); return; }
|
|
128
|
+
validatePin(pin);
|
|
129
|
+
if (opts.command === 'install') {
|
|
130
|
+
if (pin.distribution === 'ghcr') run(['pull', '--platform', pin.platform, pin.reference]);
|
|
131
|
+
verifyImage(pin, run);
|
|
132
|
+
show('Verified packaged image; no container started or state volumes changed.');
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const names = lines(run(['container', 'ls', '--all', '--format', '{{.Names}}']));
|
|
136
|
+
const current = names.includes(opts.name) ? decode(run(['container', 'inspect', opts.name])) : null;
|
|
137
|
+
if (current && current.Config?.Labels?.[LABEL] !== opts.name) throw Error('Instance name belongs to an unmanaged container; refusing access');
|
|
138
|
+
if (opts.command === 'status') {
|
|
139
|
+
show(current ? `state=${current.State.Status} image=${imageID(current.Image)} endpoint=http://127.0.0.1:${current.Config.Labels[`${LABEL}.port`]}` : 'state=absent');
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (opts.command === 'stop') {
|
|
143
|
+
if (!current) throw Error('Instance does not exist');
|
|
144
|
+
if (current.State.Running) run(['container', 'stop', '--time', '30', current.Id]);
|
|
145
|
+
show('Stopped; named state volumes preserved.'); return;
|
|
146
|
+
}
|
|
147
|
+
if (opts.command === 'setup') {
|
|
148
|
+
if (!current?.State.Running) throw Error('Start the instance before setup');
|
|
149
|
+
if (imageID(current.Image) !== pin.imageId) throw Error('Instance does not match the packaged image pin');
|
|
150
|
+
if (opts.setup[0] === 'credential' && io.stdinTTY) throw Error('Redirect a private key file or secret-manager pipe to stdin');
|
|
151
|
+
if (opts.setup[0] === 'sdk-token' && io.stdoutTTY) throw Error('Redirect token output to a new private file or pipe');
|
|
152
|
+
verifyImage(pin, run);
|
|
153
|
+
run(['exec', ...(opts.setup[0] === 'credential' ? ['-i'] : []), current.Id, 'swarmctl', 'setup', ...opts.setup], { stream: true });
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const project = (io.project || selectedProject)(opts.project);
|
|
157
|
+
const spec = createHash('sha256').update(JSON.stringify([pin.imageId, project, opts.port])).digest('hex');
|
|
158
|
+
if (current) {
|
|
159
|
+
if (current.Config.Labels[`${LABEL}.project`] !== project) throw Error('Recreation must keep the same project');
|
|
160
|
+
if (current.State.Running) {
|
|
161
|
+
if (opts.recreate || current.Config.Labels[`${LABEL}.spec`] !== spec || imageID(current.Image) !== pin.imageId) throw Error('Stop the existing instance before changing or recreating it');
|
|
162
|
+
verifyImage(pin, run);
|
|
163
|
+
show('Already running.'); return;
|
|
164
|
+
}
|
|
165
|
+
if (!opts.recreate) throw Error('Instance is stopped; use start --recreate with the same project to preserve its volumes');
|
|
166
|
+
}
|
|
167
|
+
// Verification precedes any container removal or resource creation. Never auto-pull.
|
|
168
|
+
verifyImage(pin, run);
|
|
169
|
+
const network = `${opts.name}-network`;
|
|
170
|
+
const networks = lines(run(['network', 'ls', '--format', '{{.Name}}']));
|
|
171
|
+
if (networks.includes(network)) {
|
|
172
|
+
const n = decode(run(['network', 'inspect', network]));
|
|
173
|
+
if ((n.Labels || n.labels)?.[LABEL] !== opts.name) throw Error('Network name collision; refusing reuse');
|
|
174
|
+
}
|
|
175
|
+
const volumes = lines(run(['volume', 'ls', '--format', '{{.Name}}']));
|
|
176
|
+
// A partial existing set is never a new instance: do not silently reset identity.
|
|
177
|
+
const present = Object.keys(VOLUMES).filter(key => volumes.includes(`${opts.name}-${key}`)).length;
|
|
178
|
+
if (present !== 0 && present !== Object.keys(VOLUMES).length) throw Error('Incomplete state volumes; inspect and recover the existing instance before retrying');
|
|
179
|
+
// Check every collision before creating a volume or removing a stopped container.
|
|
180
|
+
for (const suffix of Object.keys(VOLUMES)) {
|
|
181
|
+
const name = `${opts.name}-${suffix}`;
|
|
182
|
+
if (volumes.includes(name)) {
|
|
183
|
+
const v = decode(run(['volume', 'inspect', name]));
|
|
184
|
+
if (v.Labels?.[LABEL] !== opts.name || v.Labels?.[`${LABEL}.project`] !== project) throw Error('Volume ownership/project collision; refusing reuse');
|
|
185
|
+
} else if (current) throw Error('Existing instance has a missing state volume; refusing silent reset');
|
|
186
|
+
}
|
|
187
|
+
if (!networks.includes(network)) run(['network', 'create', '--label', `${LABEL}=${opts.name}`, network]);
|
|
188
|
+
for (const suffix of Object.keys(VOLUMES)) {
|
|
189
|
+
const name = `${opts.name}-${suffix}`;
|
|
190
|
+
if (!volumes.includes(name)) run(['volume', 'create', '--label', `${LABEL}=${opts.name}`, '--label', `${LABEL}.project=${project}`, name]);
|
|
191
|
+
}
|
|
192
|
+
if (current) run(['container', 'rm', current.Id]); // Never --force or --volumes.
|
|
193
|
+
const mounts = Object.entries(VOLUMES).flatMap(([key, dst]) => ['--mount', `type=volume,src=${opts.name}-${key},dst=${dst}`]);
|
|
194
|
+
run(['run', '--detach', '--pull=never', '--platform', 'linux/amd64', '--name', opts.name,
|
|
195
|
+
'--label', `${LABEL}=${opts.name}`, '--label', `${LABEL}.project=${project}`,
|
|
196
|
+
'--label', `${LABEL}.port=${opts.port}`, '--label', `${LABEL}.spec=${spec}`,
|
|
197
|
+
'--network', network, '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges',
|
|
198
|
+
'--publish', `127.0.0.1:${opts.port}:7783`, ...mounts,
|
|
199
|
+
'--mount', `type=bind,src=${project},dst=/project`, pin.imageId, '--container-sdk-port=7783']);
|
|
200
|
+
show(`Started; endpoint=http://127.0.0.1:${opts.port}. Run setup status when the private socket is ready.`);
|
|
201
|
+
}
|