@clawscarf/cli 0.1.0-alpha.5 → 0.1.0-alpha.7

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 (33) hide show
  1. package/README.md +8 -0
  2. package/package.json +2 -1
  3. package/pnpm-lock.yaml +37 -0
  4. package/recipes/README.md +1 -1
  5. package/recipes/team-server/recipe.json +3 -2
  6. package/release/README.md +19 -0
  7. package/release/components.json +1 -1
  8. package/release/telemetry.json +4 -0
  9. package/runtime/configuration.js +2 -1
  10. package/runtime/releases/{0.1.0-alpha.5.json → 0.1.0-alpha.7.json} +16 -16
  11. package/scripts/clawscarf.js +9 -1
  12. package/scripts/deployment/configuration.js +1 -0
  13. package/scripts/deployment/connection-settings.js +4 -1
  14. package/scripts/deployment/launch.js +3 -3
  15. package/scripts/deployment/network-policy.js +120 -0
  16. package/scripts/deployment/policy.js +5 -3
  17. package/scripts/deployment/prepare.js +1 -1
  18. package/scripts/deployment/public-web.js +176 -0
  19. package/scripts/installation/command.js +6 -3
  20. package/scripts/installation/configuration.js +1 -0
  21. package/scripts/installation/configure.js +1 -0
  22. package/scripts/installation/installer/collect.js +15 -0
  23. package/scripts/installation/installer/menu.js +2 -1
  24. package/scripts/installation/installer/run.js +19 -3
  25. package/scripts/installation/installer/settings.js +4 -1
  26. package/scripts/installation/installer/summary.js +1 -0
  27. package/scripts/installation/options.js +7 -1
  28. package/scripts/installation/recipes/definition.js +1 -0
  29. package/scripts/installation/reconfigure.js +10 -2
  30. package/scripts/installation/resolve.js +1 -0
  31. package/scripts/installation/setup.js +1 -0
  32. package/scripts/telemetry.js +282 -0
  33. package/scripts/deployment/connection-policy.js +0 -80
@@ -0,0 +1,282 @@
1
+ import packageInfo from "../package.json" with { type: "json" };
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdir, open, readFile } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { PostHog } from "posthog-node";
7
+ import { Agent, fetch } from "undici";
8
+ import { z } from "zod";
9
+ const destinationSchema = z.strictObject({
10
+ host: z.url().refine((value) => {
11
+ const url = new URL(value);
12
+ return (!url.username &&
13
+ !url.password &&
14
+ !url.search &&
15
+ !url.hash &&
16
+ url.pathname === "/" &&
17
+ (url.protocol === "https:" ||
18
+ (url.protocol === "http:" && url.hostname === "127.0.0.1")));
19
+ }),
20
+ projectToken: z.string().regex(/^phc_[A-Za-z0-9_-]+$/),
21
+ });
22
+ // Deliberately finite: remote errors and OperatorError.code can contain arbitrary text.
23
+ const errorCodeSchema = z.enum([
24
+ "invalid_configuration",
25
+ "unsupported_platform",
26
+ "release_mismatch",
27
+ "stale_plan",
28
+ "change_unsupported",
29
+ "unavailable",
30
+ "operation_failed",
31
+ "invalid_arguments",
32
+ "operation_busy",
33
+ "invalid_team_configuration",
34
+ "upgrade_pending",
35
+ "upgrade_refused",
36
+ "upgrade_outcome_unknown",
37
+ "runtime_binding_changed",
38
+ "runtime_binding_unavailable",
39
+ "administrator_unverified",
40
+ "bootstrap_outcome_unknown",
41
+ "browser_unavailable",
42
+ "command_failed",
43
+ "configuration_changed",
44
+ "database_start_failed",
45
+ "executable_unavailable",
46
+ "incomplete_certificate",
47
+ "invalid_certificate",
48
+ "invalid_model_setup",
49
+ "model_credential_pending",
50
+ "invalid_connections_setup",
51
+ "connections_catalog_blocked",
52
+ "connections_configuration_pending",
53
+ "connections_configuration_refused",
54
+ "connections_configuration_unavailable",
55
+ "invalid_runtime_policy",
56
+ "native_unavailable",
57
+ "network_identity_changed",
58
+ "network_lookup_incomplete",
59
+ "network_outcome_unknown",
60
+ "network_unprepared",
61
+ "platform_unqualified",
62
+ "port_check_failed",
63
+ "port_in_use",
64
+ "private_directory_required",
65
+ "runtime_failed",
66
+ "runtime_identity_changed",
67
+ "runtime_lookup_incomplete",
68
+ "runtime_outcome_unknown",
69
+ "runtime_start_failed",
70
+ "runtime_stop_pending",
71
+ "startup_interrupted",
72
+ "startup_timed_out",
73
+ "unowned_directory",
74
+ "ownership_conflict",
75
+ "runtime_credentials_changed",
76
+ "database_setup_failed",
77
+ "outcome_unknown",
78
+ "unauthorized",
79
+ "forbidden",
80
+ "ENOENT",
81
+ "ENOTDIR",
82
+ "EACCES",
83
+ "EPERM",
84
+ "EEXIST",
85
+ "ELOOP",
86
+ "ENOSPC",
87
+ ]);
88
+ /** One CLI invocation. No runtime, server, browser, or automatic exception instrumentation. */
89
+ export class CliTelemetry {
90
+ environment;
91
+ destinationFile;
92
+ client;
93
+ dispatcher;
94
+ started;
95
+ startTime = 0;
96
+ distinctId = "";
97
+ command = "";
98
+ action;
99
+ interactive = false;
100
+ version = "";
101
+ invocationId = randomUUID();
102
+ outcome = "success";
103
+ mode;
104
+ configuration;
105
+ constructor(environment = process.env, destinationFile = new URL("../release/telemetry.json", import.meta.url)) {
106
+ this.environment = environment;
107
+ this.destinationFile = destinationFile;
108
+ }
109
+ async start(command) {
110
+ if (this.environment.CLAWSCARF_TELEMETRY_DISABLED === "1")
111
+ return;
112
+ try {
113
+ const destination = destinationSchema
114
+ .nullable()
115
+ .parse(JSON.parse(await readFile(this.destinationFile, "utf8")));
116
+ if (!destination)
117
+ return;
118
+ const manifest = z
119
+ .object({
120
+ version: z.string().regex(/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/),
121
+ })
122
+ .parse(packageInfo);
123
+ this.version = manifest.version;
124
+ const directory = join(this.environment.XDG_CONFIG_HOME || homedir(), this.environment.XDG_CONFIG_HOME ? "clawscarf" : ".config/clawscarf");
125
+ await mkdir(directory, { recursive: true, mode: 0o700 });
126
+ const file = join(directory, "telemetry-id");
127
+ try {
128
+ const handle = await open(file, "wx", 0o600);
129
+ try {
130
+ await handle.writeFile(randomUUID() + "\n");
131
+ }
132
+ finally {
133
+ await handle.close();
134
+ }
135
+ process.stderr.write("ClawScarf reports CLI usage and failure codes to PostHog. Disable with CLAWSCARF_TELEMETRY_DISABLED=1. Details: https://github.com/clawscarf/clawscarf/blob/main/deploy/deployment/installation.md#telemetry\n");
136
+ }
137
+ catch (error) {
138
+ if (!(error instanceof Error &&
139
+ "code" in error &&
140
+ error.code === "EEXIST"))
141
+ throw error;
142
+ }
143
+ // A concurrent creator may still be writing. Skip this invocation if incomplete.
144
+ this.distinctId = z.uuid().parse((await readFile(file, "utf8")).trim());
145
+ const names = [];
146
+ for (let current = command; current.parent; current = current.parent)
147
+ names.unshift(current.name());
148
+ this.command = names.join(" ");
149
+ const options = command.optsWithGlobals();
150
+ this.interactive =
151
+ [process.stdin.isTTY, process.stdout.isTTY].every((isTTY) => isTTY) &&
152
+ !options.nonInteractive;
153
+ if (this.command === "stop")
154
+ this.action = options.delete ? "delete" : "stop";
155
+ const dispatcher = new Agent({ connect: { timeout: 500 } });
156
+ this.dispatcher = dispatcher;
157
+ this.client = new PostHog(destination.projectToken, {
158
+ host: destination.host,
159
+ isServer: false,
160
+ disableGeoip: true,
161
+ enableExceptionAutocapture: false,
162
+ enableLocalEvaluation: false,
163
+ flushInterval: 0,
164
+ fetchRetryCount: 0,
165
+ requestTimeout: 500,
166
+ disableCompression: true,
167
+ fetch: async (url, options) => {
168
+ // Only uncompressed event JSON is supported; never follow ingestion redirects.
169
+ if (typeof options.body !== "string")
170
+ throw Error("Expected event JSON");
171
+ const response = await fetch(url, {
172
+ method: options.method,
173
+ headers: options.headers,
174
+ body: options.body,
175
+ dispatcher,
176
+ redirect: "error",
177
+ signal: AbortSignal.timeout(500),
178
+ });
179
+ const body = await response.text();
180
+ return {
181
+ status: response.status,
182
+ headers: response.headers,
183
+ text: () => Promise.resolve(body),
184
+ json: () => Promise.resolve().then(() => JSON.parse(body)),
185
+ };
186
+ },
187
+ });
188
+ this.startTime = performance.now();
189
+ this.started = this.capture("cli_command_started");
190
+ }
191
+ catch {
192
+ // Telemetry configuration/storage must never prevent a command from running.
193
+ await this.dispatcher?.destroy().catch(() => { });
194
+ this.client = undefined;
195
+ }
196
+ }
197
+ configurationMode(mode) {
198
+ this.mode = mode;
199
+ }
200
+ result(value) {
201
+ if (!value || typeof value !== "object")
202
+ return;
203
+ if ("state" in value && value.state === "cancelled")
204
+ this.outcome = "cancelled";
205
+ else if ("state" in value && value.state === "action_required")
206
+ this.outcome = "action_required";
207
+ else if (this.command === "configure" || this.command === "start") {
208
+ if ("ready" in value && value.ready === false)
209
+ this.outcome = "action_required";
210
+ }
211
+ if (this.command !== "configure")
212
+ return;
213
+ if ("ready" in value && value.ready === true)
214
+ this.configuration = "ready";
215
+ else if ("state" in value && value.state === "unchanged")
216
+ this.configuration = "unchanged";
217
+ else if ("state" in value && value.state === "prepared")
218
+ this.configuration = "saved";
219
+ }
220
+ async finish(exitCode, failureCode) {
221
+ if (!this.client)
222
+ return;
223
+ const outcome = exitCode === 130 || failureCode === "cancelled"
224
+ ? "cancelled"
225
+ : failureCode !== undefined ||
226
+ (exitCode !== undefined && Number(exitCode) !== 0)
227
+ ? "failure"
228
+ : this.outcome;
229
+ const code = errorCodeSchema.safeParse(failureCode);
230
+ try {
231
+ await Promise.all([
232
+ this.started,
233
+ this.capture("cli_command_finished", {
234
+ outcome,
235
+ duration_ms: Math.round(performance.now() - this.startTime),
236
+ ...(outcome === "failure"
237
+ ? {
238
+ error_code: code.success ? code.data : "operation_failed",
239
+ operation: this.command,
240
+ }
241
+ : {}),
242
+ ...(this.mode ? { configuration_mode: this.mode } : {}),
243
+ ...(this.configuration
244
+ ? { configuration_outcome: this.configuration }
245
+ : {}),
246
+ }),
247
+ ]);
248
+ await this.client.shutdown(1000);
249
+ }
250
+ catch {
251
+ // Best effort only: no retries, offline queue, output, or changed exit status.
252
+ }
253
+ finally {
254
+ await this.dispatcher?.destroy().catch(() => { });
255
+ this.client = undefined;
256
+ }
257
+ }
258
+ async capture(event, result = {}) {
259
+ try {
260
+ await this.client?.captureImmediate({
261
+ distinctId: this.distinctId,
262
+ event,
263
+ timestamp: new Date(),
264
+ properties: {
265
+ command: this.command,
266
+ invocation_id: this.invocationId,
267
+ cli_version: this.version,
268
+ os: process.platform,
269
+ architecture: process.arch,
270
+ interactive: this.interactive,
271
+ ...(this.action ? { action: this.action } : {}),
272
+ ...result,
273
+ $process_person_profile: false,
274
+ $ip: null,
275
+ },
276
+ });
277
+ }
278
+ catch {
279
+ // Never forward telemetry errors (including remote response bodies) to output.
280
+ }
281
+ }
282
+ }
@@ -1,80 +0,0 @@
1
- import { isDeepStrictEqual } from "node:util";
2
- import { readFile, rm } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import { z } from "zod";
5
- import { run } from "./process.js";
6
- import { resourceNames, writePrivate } from "./state.js";
7
- import { runtimeManager } from "./runtime.js";
8
- const ruleSchema = z.object({
9
- name: z.string(),
10
- endpoints: z.array(z.object({ host: z.string(), port: z.number(), tls: z.string() })),
11
- binaries: z.array(z.object({ path: z.string() })),
12
- });
13
- const policySchema = z.looseObject({
14
- network_policies: z.record(z.string(), z.unknown()),
15
- });
16
- /** Apply only the explicitly selected broker rule; never regenerate an operator's other policies. */
17
- export async function applyConnectionPolicy(directory, state, env, verify = false) {
18
- const pending = join(directory, "private/connection-policy-change.json");
19
- let text;
20
- try {
21
- text = await readFile(pending, "utf8");
22
- }
23
- catch (error) {
24
- if (error instanceof Error && "code" in error && error.code === "ENOENT")
25
- return;
26
- throw error;
27
- }
28
- const change = z
29
- .strictObject({
30
- ownerId: z.literal(state.ownerId),
31
- rule: ruleSchema.nullable(),
32
- })
33
- .parse(JSON.parse(text));
34
- const base = join(directory, "private/runtime-policy.json");
35
- const update = (policy) => {
36
- if (change.rule)
37
- policy.network_policies.connections_broker = change.rule;
38
- else
39
- delete policy.network_policies.connections_broker;
40
- return policy;
41
- };
42
- const matches = (rule) => {
43
- if (change.rule === null)
44
- return rule === undefined;
45
- const parsed = ruleSchema.safeParse(rule);
46
- return parsed.success && isDeepStrictEqual(parsed.data, change.rule);
47
- };
48
- const name = resourceNames(state).sandbox;
49
- if (!(await runtimeManager(directory, state, env, run).recorded()).receipt) {
50
- if (verify)
51
- throw Error("The configured runtime has not been recorded.");
52
- await writePrivate(base, JSON.stringify(update(policySchema.parse(JSON.parse(await readFile(base, "utf8"))))));
53
- return;
54
- }
55
- const observed = z
56
- .object({
57
- sandbox: z.literal(name),
58
- policy_source: z.literal("sandbox"),
59
- policy: policySchema,
60
- })
61
- .parse(JSON.parse(await run(state.input.openshellCli, [
62
- "policy",
63
- "get",
64
- name,
65
- "--gateway",
66
- name,
67
- "--base",
68
- "--output",
69
- "json",
70
- ], { env })));
71
- if (matches(observed.policy.network_policies.connections_broker)) {
72
- if (verify)
73
- await rm(pending);
74
- return;
75
- }
76
- if (verify)
77
- throw Error("The Connections network permission was not confirmed. The installation remains unavailable.");
78
- await writePrivate(base, JSON.stringify(update(observed.policy)));
79
- await run(state.input.openshellCli, ["policy", "set", name, "--gateway", name, "--policy", base], { env });
80
- }