@lizard-build/cli 4.0.104 โ†’ 4.0.107

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.
@@ -0,0 +1,112 @@
1
+ // Support tickets from the CLI: what `lizard support` attaches, and the support inbox.
2
+ //
3
+ // Two small pieces of local state in ~/.lizard/support.json:
4
+ // - the last failed platform calls (method, path, status, error), so a ticket carries the real
5
+ // error even when an agent describes it vaguely;
6
+ // - which support replies have been shown, so a reply is printed after the next commands (twice
7
+ // at most) and then stays in `lizard support show`.
8
+ // The inbox is checked after a command at most once a minute (GET /api/support/unread) and
9
+ // printed to stderr, so --json output on stdout never changes.
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import chalk from "chalk";
14
+ import { configDir } from "./config.js";
15
+ import { CURRENT_VERSION } from "./updater.js";
16
+ import { detectAgent } from "./agent.js";
17
+
18
+ interface FailedCall { method: string; path: string; status: number | string; error: string; requestId?: string; at: string }
19
+ interface SupportState { lastErrors?: FailedCall[]; checkedAt?: number; shown?: Record<string, number> }
20
+
21
+ const CHECK_EVERY_MS = 60_000;
22
+ const SHOW_TIMES = 2;
23
+
24
+ function stateFile(): string { return path.join(configDir(), "support.json"); }
25
+
26
+ function load(): SupportState {
27
+ try { return JSON.parse(fs.readFileSync(stateFile(), "utf8")) as SupportState; } catch { return {}; }
28
+ }
29
+
30
+ function save(s: SupportState): void {
31
+ try {
32
+ fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 });
33
+ fs.writeFileSync(stateFile(), JSON.stringify(s), { mode: 0o600 });
34
+ } catch { /* best effort */ }
35
+ }
36
+
37
+ /** Called for every failed platform call. Never throws. */
38
+ export function recordFailedCall(method: string, urlPath: string, status: number | string, error: string, requestId?: string | null): void {
39
+ if (urlPath.startsWith("/api/support/")) return;
40
+ const s = load();
41
+ const entry: FailedCall = {
42
+ method, path: urlPath.split("?")[0], status,
43
+ error: String(error).replace(/\bliz_[A-Za-z0-9_-]{8,}/g, "liz_[redacted]").slice(0, 400),
44
+ ...(requestId ? { requestId } : {}), at: new Date().toISOString(),
45
+ };
46
+ s.lastErrors = [...(s.lastErrors ?? []), entry].slice(-5);
47
+ save(s);
48
+ }
49
+
50
+ /** What a new ticket carries besides the message. Only the last hour's failures. */
51
+ export function ticketContext(): Record<string, unknown> {
52
+ const hourAgo = Date.now() - 3600_000;
53
+ const lastErrors = (load().lastErrors ?? []).filter((e) => Date.parse(e.at) > hourAgo);
54
+ return {
55
+ cliVersion: CURRENT_VERSION,
56
+ os: `${os.platform()} ${os.arch()} node ${process.versions.node}`,
57
+ ...(lastErrors.length ? { lastErrors } : {}),
58
+ };
59
+ }
60
+
61
+ export function agentName(): string | undefined {
62
+ return detectAgent() ?? undefined;
63
+ }
64
+
65
+ /** Server-side or network failures are worth a ticket; a 4xx about the request usually is not. */
66
+ export function isPlatformFailure(status: number | undefined, netCode?: string): boolean {
67
+ if (process.env.AGENT_SUPPORT === "0") return false;
68
+ if (status === undefined) return !!netCode;
69
+ return status >= 500 || status === 408;
70
+ }
71
+
72
+ export const SUPPORT_HINT =
73
+ 'If this keeps failing, tell the Lizard team: lizard support open "<what you ran and what happened>" (the error above is attached automatically)';
74
+
75
+ interface UnreadTicket { ticket: string; subject: string; status: string; messages: Array<{ from: string; body: string; at: string }> }
76
+
77
+ /**
78
+ * Prints support replies the user has not seen yet, after a command. Throttled to one request
79
+ * a minute; each reply is printed at most twice. Never throws and never waits more than 2 s.
80
+ */
81
+ export async function printSupportInbox(fetchUnread: () => Promise<{ tickets: UnreadTicket[] }>, opts: { force?: boolean } = {}): Promise<void> {
82
+ try {
83
+ const s = load();
84
+ if (!opts.force && s.checkedAt && Date.now() - s.checkedAt < CHECK_EVERY_MS) return;
85
+ s.checkedAt = Date.now();
86
+ save(s);
87
+ const res = await Promise.race([
88
+ fetchUnread(),
89
+ new Promise<null>((r) => setTimeout(() => r(null), 2000).unref()),
90
+ ]);
91
+ if (!res?.tickets?.length) return;
92
+ const shown = { ...(load().shown ?? {}) };
93
+ const out: string[] = [];
94
+ for (const t of res.tickets) {
95
+ const fresh = t.messages.filter((m) => (shown[`${t.ticket}@${m.at}`] ?? 0) < SHOW_TIMES);
96
+ if (!fresh.length) continue;
97
+ out.push(chalk.bold.green(`๐Ÿ“ฌ Lizard support replied on ${t.ticket}`) + chalk.dim(` (${t.subject})`));
98
+ for (const m of fresh) {
99
+ shown[`${t.ticket}@${m.at}`] = (shown[`${t.ticket}@${m.at}`] ?? 0) + 1;
100
+ out.push(chalk.dim(` ${m.from}:`));
101
+ for (const line of m.body.split("\n")) out.push(` ${line}`);
102
+ }
103
+ out.push(chalk.dim(` โ†’ answer: lizard support reply ${t.ticket} "<your answer>" ยท full thread: lizard support show ${t.ticket}`));
104
+ }
105
+ // Forget entries for replies that are no longer unread.
106
+ const live = new Set(res.tickets.flatMap((t) => t.messages.map((m) => `${t.ticket}@${m.at}`)));
107
+ const next = load();
108
+ next.shown = Object.fromEntries(Object.entries(shown).filter(([k]) => live.has(k)));
109
+ save(next);
110
+ if (out.length) process.stderr.write("\n" + out.join("\n") + "\n");
111
+ } catch { /* the inbox must never break a command */ }
112
+ }
@@ -5,7 +5,7 @@ import { join, dirname } from "node:path";
5
5
  import os from "node:os";
6
6
  import { spawn } from "node:child_process";
7
7
 
8
- export const CURRENT_VERSION = "4.0.104";
8
+ export const CURRENT_VERSION = "4.0.107";
9
9
  const RELEASES_API = "https://api.github.com/repos/lizard-build/lizard-cli/releases/latest";
10
10
  const RELEASE_BASE = "https://github.com/lizard-build/lizard-cli/releases/latest/download";
11
11
 
@@ -200,6 +200,11 @@ describe("private sandbox snapshots", () => {
200
200
  // No scope unless asked: the server picks 'user', or for a scoped key only what it covers.
201
201
  expect(api.post).toHaveBeenCalledWith('/api/sandboxes/sandbox-test/snapshot', { name: 'My app', scope: undefined });
202
202
  });
203
+ it.each([[['--full'], { memory: true }], [['--fast'], { memory: false }]])("snapshot %j sends %j", async (flags, choice) => {
204
+ const program = new Command().exitOverride(); registerSandbox(program);
205
+ await program.parseAsync(['sandbox', 'snapshot', 'sandbox-test', '--name', 'My app', ...flags as string[], '--no-wait'], { from: 'user' });
206
+ expect(api.post).toHaveBeenCalledWith('/api/sandboxes/sandbox-test/snapshot', { name: 'My app', scope: undefined, ...choice });
207
+ });
203
208
  it("no longer takes --warm", async () => {
204
209
  const program = new Command().exitOverride(); registerSandbox(program);
205
210
  await expect(program.parseAsync(['sandbox', 'snapshot', 'sandbox-test', '--name', 'app', '--warm', '3', '--no-wait'], { from: 'user' })).rejects.toThrow(/unknown option/);
@@ -214,6 +219,20 @@ describe("private sandbox snapshots", () => {
214
219
  await program.parseAsync(['sandbox', operation, 'sandbox-test', '--no-wait'], { from: 'user' });
215
220
  expect(api.post).toHaveBeenCalledWith(`/api/sandboxes/sandbox-test/${operation}`, {});
216
221
  });
222
+ it.each([
223
+ [[], {}], // no choice: the platform's default (files only)
224
+ [['--full'], { memory: true }], // memory + processes; "memory" works on older servers
225
+ [['--fast'], { memory: false }],
226
+ ])("pause %j sends %j", async (flags, body) => {
227
+ const program = new Command().exitOverride(); registerSandbox(program);
228
+ await program.parseAsync(['sandbox', 'pause', 'sandbox-test', ...flags as string[], '--no-wait'], { from: 'user' });
229
+ expect(api.post).toHaveBeenCalledWith('/api/sandboxes/sandbox-test/pause', body);
230
+ });
231
+ it("refuses --full together with --fast", async () => {
232
+ const program = new Command().exitOverride(); registerSandbox(program);
233
+ await expect(program.parseAsync(['sandbox', 'pause', 'sandbox-test', '--full', '--fast', '--no-wait'], { from: 'user' })).rejects.toThrow(/either --full or --fast/);
234
+ expect(api.post).not.toHaveBeenCalled();
235
+ });
217
236
  it("passes the private snapshot ID to create", async () => {
218
237
  await create(['--snapshot', 'snap-test']);
219
238
  expect(api.post).toHaveBeenCalledWith('/api/sandboxes', expect.objectContaining({ snapshotId: 'snap-test' }));
@@ -0,0 +1,52 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
+ import { isPlatformFailure, printSupportInbox, recordFailedCall, ticketContext } from "../../src/lib/support.js";
6
+
7
+ let home: string;
8
+ beforeEach(() => { home = fs.mkdtempSync(path.join(os.tmpdir(), "lz-support-")); process.env.LIZARD_HOME = home; });
9
+ afterEach(() => { delete process.env.LIZARD_HOME; fs.rmSync(home, { recursive: true, force: true }); vi.restoreAllMocks(); });
10
+
11
+ const unread = { tickets: [{ ticket: "T-1043", subject: "eu create 500", status: "answered", messages: [{ from: "Lizard support (Mike)", body: "Which region?", at: "2026-11-07T18:00:00.000Z" }] }] };
12
+
13
+ describe("support inbox", () => {
14
+ it("prints a reply on stderr at most twice, never on stdout", async () => {
15
+ const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
16
+ const out = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
17
+ const fetch = vi.fn(async () => unread);
18
+ for (let i = 0; i < 3; i++) await printSupportInbox(fetch, { force: true });
19
+ const shown = err.mock.calls.map((c) => String(c[0])).filter((s) => s.includes("Which region?"));
20
+ expect(shown).toHaveLength(2);
21
+ expect(shown[0]).toContain("lizard support reply T-1043");
22
+ expect(out).not.toHaveBeenCalled();
23
+ });
24
+ it("checks at most once a minute", async () => {
25
+ vi.spyOn(process.stderr, "write").mockImplementation(() => true);
26
+ const fetch = vi.fn(async () => ({ tickets: [] }));
27
+ await printSupportInbox(fetch);
28
+ await printSupportInbox(fetch);
29
+ expect(fetch).toHaveBeenCalledTimes(1);
30
+ });
31
+ it("never throws when the platform fails", async () => {
32
+ await expect(printSupportInbox(async () => { throw new Error("down"); }, { force: true })).resolves.toBeUndefined();
33
+ });
34
+ });
35
+
36
+ describe("ticket context", () => {
37
+ it("attaches recent failures with keys redacted", () => {
38
+ recordFailedCall("POST", "/api/sandboxes?workspaceId=w1", 500, "boom liz_abcdefghijkl123");
39
+ const ctx = ticketContext() as any;
40
+ expect(ctx.lastErrors).toHaveLength(1);
41
+ expect(ctx.lastErrors[0]).toMatchObject({ method: "POST", path: "/api/sandboxes", status: 500 });
42
+ expect(ctx.lastErrors[0].error).not.toContain("abcdefghijkl");
43
+ expect(ctx.cliVersion).toBeTruthy();
44
+ });
45
+ it("treats only platform-side failures as ticket-worthy", () => {
46
+ expect(isPlatformFailure(500)).toBe(true);
47
+ expect(isPlatformFailure(504)).toBe(true);
48
+ expect(isPlatformFailure(404)).toBe(false);
49
+ expect(isPlatformFailure(402)).toBe(false);
50
+ expect(isPlatformFailure(undefined, "ECONNRESET")).toBe(true);
51
+ });
52
+ });