Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions docs/reference/commands-nemohermes.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1101,13 +1101,18 @@ nemohermes my-assistant sessions delete agent:main:slack:c-9 --json

### `nemohermes <name> sessions export [keys...]`

Export the OpenClaw session JSONL from a running sandbox to the host, replacing the two-hop `docker exec kubectl cp` plus `docker cp` workaround.
Export the agent's session history from a running sandbox to the host.
The command routes by the sandbox's agent kind recorded in the registry.

The command always enumerates the session store through `openclaw sessions list --agent <id> --json` and copies only the matching `<sessionId>.jsonl` (plus optional `<sessionId>.trajectory.jsonl`) files, so the export never picks up `sessions.json`, stale `.jsonl.lock` files, or other store bookkeeping.
For an OpenClaw sandbox, the command enumerates the session store through `openclaw sessions list --agent <id> --json` and copies only the matching `<sessionId>.jsonl` (plus optional `<sessionId>.trajectory.jsonl`) files, so the export never picks up `sessions.json`, stale `.jsonl.lock` files, or other store bookkeeping.
By default it writes a browsable directory of session files (`dir` format); pass `--format tar` for a single `.tgz` bundle suited to sharing or upload.
With no positional keys, the command exports every session for the agent.
Pass one or more keys (alias or canonical `agent:<id>:<rest>`) to filter.

For a Hermes sandbox, the command invokes the in-sandbox `hermes sessions export` against a staging path, then downloads the resulting single JSONL stream to the host.
Hermes stores session history in a SQLite database, so the command refuses positional keys, `--agent`, `--format tar`, and `--include-trajectory` with a clear error when the sandbox is Hermes.
The host destination defaults to `./sessions-<sandbox>.jsonl`; `--out` picks a different path.

```bash
nemohermes my-assistant sessions export
nemohermes my-assistant sessions export main --agent main
Expand All @@ -1117,15 +1122,15 @@ nemohermes my-assistant sessions export --format tar --out ./bundles/alpha.tgz -

| Flag | Description |
|------|-------------|
| `--agent <id>` | Agent id when `<keys>` are aliases rather than the canonical `agent:<id>:<rest>` form. |
| `--format <dir\|tar>` | `dir` (default) writes a directory of session files; `tar` writes a single `.tgz` bundle for sharing/upload. |
| `--out <path>` | Host destination. Defaults to `./sessions-<sandbox>/` for `dir`, or `./sessions-<sandbox>-<agent>.tgz` for `tar`. |
| `--include-trajectory` | Include the (large) `*.trajectory.jsonl` files in the export. Excluded by default. |
| `--agent <id>` | OpenClaw only. Agent id when `<keys>` are aliases rather than the canonical `agent:<id>:<rest>` form. |
| `--format <dir\|tar>` | OpenClaw only. `dir` (default) writes a directory of session files; `tar` writes a single `.tgz` bundle for sharing/upload. |
| `--out <path>` | Host destination. OpenClaw defaults to `./sessions-<sandbox>/` for `dir` or `./sessions-<sandbox>-<agent>.tgz` for `tar`; Hermes defaults to `./sessions-<sandbox>.jsonl`. |
| `--include-trajectory` | OpenClaw only. Include the (large) `*.trajectory.jsonl` files in the export. Excluded by default. |
| `--json` | Print the export manifest as JSON instead of a status line. |

Mismatched `--agent` plus canonical-key combinations are refused before any download runs.
Session keys that begin with `-` are rejected at the command boundary instead of being silently dropped.
Session JSONL can contain pasted secrets (API keys, tokens), so exported files are written owner-only (`0600`); for `tar` format the in-sandbox staging tarball is additionally created with `umask 077` and removed after the host download completes.
Session JSONL can contain pasted secrets (API keys, tokens), so exported files are written owner-only (`0600`); the in-sandbox staging artefact is additionally created with `umask 077` and removed after the host download completes.

### `nemohermes <name> download <sandbox-path> [host-dest]`

Expand Down
19 changes: 12 additions & 7 deletions docs/reference/commands.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1390,13 +1390,18 @@ $$nemoclaw my-assistant sessions delete agent:main:slack:c-9 --json

### `$$nemoclaw <name> sessions export [keys...]`

Export the OpenClaw session JSONL from a running sandbox to the host, replacing the two-hop `docker exec kubectl cp` plus `docker cp` workaround.
Export the agent's session history from a running sandbox to the host.
The command routes by the sandbox's agent kind recorded in the registry.

The command always enumerates the session store through `openclaw sessions list --agent <id> --json` and copies only the matching `<sessionId>.jsonl` (plus optional `<sessionId>.trajectory.jsonl`) files, so the export never picks up `sessions.json`, stale `.jsonl.lock` files, or other store bookkeeping.
For an OpenClaw sandbox, the command enumerates the session store through `openclaw sessions list --agent <id> --json` and copies only the matching `<sessionId>.jsonl` (plus optional `<sessionId>.trajectory.jsonl`) files, so the export never picks up `sessions.json`, stale `.jsonl.lock` files, or other store bookkeeping.
By default it writes a browsable directory of session files (`dir` format); pass `--format tar` for a single `.tgz` bundle suited to sharing or upload.
With no positional keys, the command exports every session for the agent.
Pass one or more keys (alias or canonical `agent:<id>:<rest>`) to filter.

For a Hermes sandbox, the command invokes the in-sandbox `hermes sessions export` against a staging path, then downloads the resulting single JSONL stream to the host.
Hermes stores session history in a SQLite database, so the command refuses positional keys, `--agent`, `--format tar`, and `--include-trajectory` with a clear error when the sandbox is Hermes.
The host destination defaults to `./sessions-<sandbox>.jsonl`; `--out` picks a different path.

```bash
$$nemoclaw my-assistant sessions export
$$nemoclaw my-assistant sessions export main --agent main
Expand All @@ -1406,15 +1411,15 @@ $$nemoclaw my-assistant sessions export --format tar --out ./bundles/alpha.tgz -

| Flag | Description |
|------|-------------|
| `--agent <id>` | Agent id when `<keys>` are aliases rather than the canonical `agent:<id>:<rest>` form. |
| `--format <dir\|tar>` | `dir` (default) writes a directory of session files; `tar` writes a single `.tgz` bundle for sharing/upload. |
| `--out <path>` | Host destination. Defaults to `./sessions-<sandbox>/` for `dir`, or `./sessions-<sandbox>-<agent>.tgz` for `tar`. |
| `--include-trajectory` | Include the (large) `*.trajectory.jsonl` files in the export. Excluded by default. |
| `--agent <id>` | OpenClaw only. Agent id when `<keys>` are aliases rather than the canonical `agent:<id>:<rest>` form. |
| `--format <dir\|tar>` | OpenClaw only. `dir` (default) writes a directory of session files; `tar` writes a single `.tgz` bundle for sharing/upload. |
| `--out <path>` | Host destination. OpenClaw defaults to `./sessions-<sandbox>/` for `dir` or `./sessions-<sandbox>-<agent>.tgz` for `tar`; Hermes defaults to `./sessions-<sandbox>.jsonl`. |
| `--include-trajectory` | OpenClaw only. Include the (large) `*.trajectory.jsonl` files in the export. Excluded by default. |
| `--json` | Print the export manifest as JSON instead of a status line. |

Mismatched `--agent` plus canonical-key combinations are refused before any download runs.
Session keys that begin with `-` are rejected at the command boundary instead of being silently dropped.
Session JSONL can contain pasted secrets (API keys, tokens), so exported files are written owner-only (`0600`); for `tar` format the in-sandbox staging tarball is additionally created with `umask 077` and removed after the host download completes.
Session JSONL can contain pasted secrets (API keys, tokens), so exported files are written owner-only (`0600`); the in-sandbox staging artefact is additionally created with `umask 077` and removed after the host download completes.

### `$$nemoclaw <name> download <sandbox-path> [host-dest]`

Expand Down
25 changes: 16 additions & 9 deletions src/commands/sandbox/sessions/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,26 @@ import { NemoClawCommand } from "../../../lib/cli/nemoclaw-oclif-command";
export default class SandboxSessionsExportCommand extends NemoClawCommand {
static id = "sandbox:sessions:export";
static strict = false;
static summary = "Export OpenClaw session JSONL out of a running sandbox";
static summary = "Export agent session JSONL out of a running sandbox";
static description = [
"Tar the OpenClaw session store inside the sandbox and download the bundle to",
"the host via `openshell sandbox download`. By default every session for the",
"agent is exported; pass one or more positional keys to filter.",
"Routes by the sandbox's agent kind, recorded in the registry.",
"",
"Keys may be either an alias (e.g. `main`, `telegram:t-1`) or the canonical",
"`agent:<id>:<rest>` form. Use --agent to scope aliases to a non-default",
"agent; mismatched --agent + canonical-key combinations are refused.",
"",
"Trajectory files are excluded by default (large) and re-added with",
"OpenClaw sandbox: tar the per-session JSONL files inside the sandbox and",
"download the bundle to the host via `openshell sandbox download`. By default",
"every session for the agent is exported; pass one or more positional keys to",
"filter. Keys may be either an alias (e.g. `main`, `telegram:t-1`) or the",
"canonical `agent:<id>:<rest>` form. Use --agent to scope aliases to a",
"non-default agent; mismatched --agent + canonical-key combinations are",
"refused. Trajectory files are excluded by default (large) and re-added with",
"--include-trajectory.",
"",
"Hermes sandbox: invoke the in-sandbox `hermes sessions export` against a",
"staging path, then download the resulting single JSONL stream to the host.",
"Hermes stores the session history in a SQLite database, so positional keys,",
"--agent, --format tar, and --include-trajectory are OpenClaw-only and are",
"rejected with a clear error when the sandbox is Hermes. The host destination",
"defaults to ./sessions-<sandbox>.jsonl; --out picks a different path.",
"",
"Note: session JSONL can contain pasted secrets (API keys, tokens). The",
"downloaded bundle is written owner-only (0600); keep it private and avoid",
"committing or sharing it without review.",
Expand Down
149 changes: 149 additions & 0 deletions src/lib/actions/sandbox/sessions/export.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,17 @@ vi.mock("../../../adapters/openshell/runtime", () => ({
runOpenshell: vi.fn(),
}));

vi.mock("../../../state/registry", () => ({
getSandbox: vi.fn(() => null),
}));

import { captureOpenshell, runOpenshell } from "../../../adapters/openshell/runtime";
import * as registry from "../../../state/registry";
import { buildSandboxTarArgv, exportSandboxSessions, parseSessionIndex } from "./export";

const captureMock = captureOpenshell as unknown as ReturnType<typeof vi.fn>;
const runMock = runOpenshell as unknown as ReturnType<typeof vi.fn>;
const getSandboxMock = registry.getSandbox as unknown as ReturnType<typeof vi.fn>;

let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
let consoleLogSpy: ReturnType<typeof vi.spyOn>;
Expand All @@ -28,6 +34,8 @@ beforeEach(() => {
captureMock.mockReset();
runMock.mockReset();
runMock.mockReturnValue({ status: 0, stdout: "", stderr: "" });
getSandboxMock.mockReset();
getSandboxMock.mockReturnValue(null);
consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => undefined);
});
Expand Down Expand Up @@ -446,3 +454,144 @@ describe("exportSandboxSessions", () => {
expect(parsed).toHaveProperty("bundleBytes");
});
});

describe("exportSandboxSessions (hermes sandbox)", () => {
let mkdtempSpy: ReturnType<typeof vi.spyOn>;
let chmodSpy: ReturnType<typeof vi.spyOn>;
let renameSpy: ReturnType<typeof vi.spyOn>;
let rmSpy: ReturnType<typeof vi.spyOn>;

beforeEach(() => {
mkdtempSpy = vi
.spyOn(fs, "mkdtempSync")
.mockImplementation((prefix) => `${prefix as string}stubdir`);
chmodSpy = vi.spyOn(fs, "chmodSync").mockImplementation(() => {});
renameSpy = vi.spyOn(fs, "renameSync").mockImplementation(() => {});
rmSpy = vi.spyOn(fs, "rmSync").mockImplementation(() => {});
});

afterEach(() => {
mkdtempSpy.mockRestore();
chmodSpy.mockRestore();
renameSpy.mockRestore();
rmSpy.mockRestore();
});

it("routes to `hermes sessions export` instead of `openclaw sessions list` when the registry marks the sandbox as hermes", async () => {
getSandboxMock.mockReturnValue({ name: "alpha", agent: "hermes" });

const result = await exportSandboxSessions({ sandboxName: "alpha" });

expect(captureMock).not.toHaveBeenCalled();

const execCall = runMock.mock.calls[0]?.[0] as string[];
expect(execCall.slice(0, 7)).toEqual(["sandbox", "exec", "--name", "alpha", "--", "sh", "-c"]);
const shellCommand = execCall[7] as string;
expect(shellCommand).toMatch(
/^umask 077 && hermes sessions export \/tmp\/sessions-export-hermes-[0-9a-f]+\.jsonl && chmod 600 \/tmp\/sessions-export-hermes-[0-9a-f]+\.jsonl$/,
);

const downloadCall = runMock.mock.calls[1]?.[0] as string[];
expect(downloadCall.slice(0, 3)).toEqual(["sandbox", "download", "alpha"]);
expect(downloadCall[3]).toMatch(/^\/tmp\/sessions-export-hermes-[0-9a-f]+\.jsonl$/);
const hostStagingPath = downloadCall.at(-1) as string;
expect(hostStagingPath).toContain(".sessions-export-hermes-");
expect(hostStagingPath.endsWith("sessions-alpha.jsonl")).toBe(true);
expect(hostStagingPath).not.toBe("./sessions-alpha.jsonl");

const cleanupCall = runMock.mock.calls.at(-1);
expect(cleanupCall?.[0]).toContain("rm");
expect(cleanupCall?.[0]).toContain("-f");

expect(chmodSpy).toHaveBeenCalledWith(hostStagingPath, 0o600);
expect(renameSpy).toHaveBeenCalledWith(hostStagingPath, "./sessions-alpha.jsonl");

expect(result).toMatchObject({
sandboxName: "alpha",
agent: "hermes",
format: "jsonl",
selectedKeys: "all",
resolvedSessionIds: [],
resolvedFiles: ["sessions-alpha.jsonl"],
hostDest: "./sessions-alpha.jsonl",
sessions: [],
});
});

it("honours --out for the host destination on a hermes sandbox", async () => {
getSandboxMock.mockReturnValue({ name: "alpha", agent: "hermes" });

const result = await exportSandboxSessions({
sandboxName: "alpha",
out: "./hermes-bundle.jsonl",
});

const downloadCall = runMock.mock.calls[1]?.[0] as string[];
const hostStagingPath = downloadCall.at(-1) as string;
expect(hostStagingPath).toContain(".sessions-export-hermes-");
expect(hostStagingPath.endsWith("hermes-bundle.jsonl")).toBe(true);
expect(renameSpy).toHaveBeenCalledWith(hostStagingPath, "./hermes-bundle.jsonl");
expect(result.hostDest).toBe("./hermes-bundle.jsonl");
expect(result.resolvedFiles).toEqual(["hermes-bundle.jsonl"]);
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

it("aborts the export and skips download when the in-sandbox `hermes sessions export` exits non-zero, while still cleaning up the staging file", async () => {
getSandboxMock.mockReturnValue({ name: "alpha", agent: "hermes" });
runMock.mockReturnValueOnce(makeRun(1));

await expect(exportSandboxSessions({ sandboxName: "alpha" })).rejects.toThrow(
/Failed to export hermes sessions/,
);

expect(runMock).toHaveBeenCalledTimes(2);
const execCall = runMock.mock.calls[0]?.[0] as string[];
expect(execCall.slice(0, 3)).toEqual(["sandbox", "exec", "--name"]);
const cleanupCall = runMock.mock.calls[1]?.[0] as string[];
expect(cleanupCall).toContain("rm");
expect(cleanupCall).toContain("-f");
expect(renameSpy).not.toHaveBeenCalled();
});

it("cleans up the in-sandbox staging file even when the host download exits non-zero", async () => {
getSandboxMock.mockReturnValue({ name: "alpha", agent: "hermes" });
runMock.mockReturnValueOnce(makeRun(0)).mockReturnValueOnce(makeRun(1));

await expect(exportSandboxSessions({ sandboxName: "alpha" })).rejects.toThrow(
/Failed to download/,
);
const cleanupCall = runMock.mock.calls.at(-1);
expect(cleanupCall?.[0]).toContain("rm");
expect(cleanupCall?.[0]).toContain("-f");
expect(renameSpy).not.toHaveBeenCalled();
});

it("fails closed when chmod on the staging file errors so a permissive host cannot end up with a world-readable session bundle", async () => {
getSandboxMock.mockReturnValue({ name: "alpha", agent: "hermes" });
chmodSpy.mockImplementation(() => {
throw new Error("EPERM");
});

await expect(exportSandboxSessions({ sandboxName: "alpha" })).rejects.toThrow(/EPERM/);
expect(renameSpy).not.toHaveBeenCalled();
const cleanupCall = runMock.mock.calls.at(-1);
expect(cleanupCall?.[0]).toContain("rm");
expect(cleanupCall?.[0]).toContain("-f");
});

it("refuses OpenClaw-only flags on a hermes sandbox so users see a clear error rather than a silent half-export", async () => {
getSandboxMock.mockReturnValue({ name: "alpha", agent: "hermes" });
await expect(exportSandboxSessions({ sandboxName: "alpha", agent: "main" })).rejects.toThrow(
/--agent is OpenClaw-specific/,
);
await expect(exportSandboxSessions({ sandboxName: "alpha", keys: ["main"] })).rejects.toThrow(
/positional session keys are OpenClaw-specific/,
);
await expect(
exportSandboxSessions({ sandboxName: "alpha", includeTrajectory: true }),
).rejects.toThrow(/--include-trajectory is OpenClaw-specific/);
await expect(exportSandboxSessions({ sandboxName: "alpha", format: "tar" })).rejects.toThrow(
/--format tar is OpenClaw-specific/,
);
expect(runMock).not.toHaveBeenCalled();
});
});
Loading
Loading