@dreamlake/dreamlake-cli 0.98.0 → 0.100.0
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/dist/api/index.d.ts +212 -10
- package/dist/api/index.js +6 -0
- package/dist/api/native-experiments.d.ts +77 -0
- package/dist/api/native-experiments.js +31 -0
- package/dist/api/sessions.d.ts +240 -7
- package/dist/api/sessions.js +56 -1
- package/dist/api/skills.d.ts +122 -0
- package/dist/api/skills.js +220 -0
- package/dist/cli/experiments/index.js +2 -0
- package/dist/cli/experiments/native-commands.d.ts +13 -0
- package/dist/cli/experiments/native-commands.js +88 -0
- package/dist/cli/help-examples.generated.js +22 -5
- package/dist/cli/hosts/inventory.d.ts +28 -0
- package/dist/cli/hosts/inventory.js +68 -3
- package/dist/cli/hosts/picker.d.ts +34 -0
- package/dist/cli/hosts/picker.js +116 -0
- package/dist/cli/hosts/ssh.d.ts +16 -0
- package/dist/cli/hosts/ssh.js +47 -3
- package/dist/cli/index.js +2 -0
- package/dist/cli/session-affiliation.js +3 -2
- package/dist/cli/sessions/affiliation.d.ts +12 -1
- package/dist/cli/sessions/affiliation.js +37 -0
- package/dist/cli/sessions/control.d.ts +11 -0
- package/dist/cli/sessions/control.js +49 -4
- package/dist/cli/sessions/index.js +70 -17
- package/dist/cli/sessions/live.d.ts +85 -0
- package/dist/cli/sessions/live.js +258 -0
- package/dist/cli/sessions/runner/exec.d.ts +118 -6
- package/dist/cli/sessions/runner/exec.js +298 -47
- package/dist/cli/sessions/runner/native.js +4 -1
- package/dist/cli/sessions/runner/serve.d.ts +37 -2
- package/dist/cli/sessions/runner/serve.js +273 -28
- package/dist/cli/sessions/wrap.d.ts +63 -0
- package/dist/cli/sessions/wrap.js +226 -0
- package/dist/cli/skill/index.d.ts +19 -1
- package/dist/cli/skill/index.js +65 -12
- package/dist/cli/skill/read.d.ts +25 -0
- package/dist/cli/skill/read.js +65 -0
- package/dist/cli/skill/registry.d.ts +95 -0
- package/dist/cli/skill/registry.js +284 -0
- package/dist/cli/skill/reminders.js +2 -1
- package/dist/cli/version.d.ts +1 -1
- package/dist/cli/version.js +1 -1
- package/package.json +9 -9
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { HOST_MATCH_LIMIT, completeHostSegment, highlightMatches, hostRows, matchHosts, table } from "./inventory.js";
|
|
2
|
+
const ESC = "\x1b", INVERSE = "\x1b[7m", DIM = "\x1b[2m", RESET = "\x1b[0m";
|
|
3
|
+
const plainLength = (text) => text.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "").length;
|
|
4
|
+
/** Matches for what is typed so far; an empty query lists the whole inventory. */
|
|
5
|
+
export function pickerMatches(inventory, query) {
|
|
6
|
+
return query ? matchHosts(inventory.hosts, query) : { keyword: "", hosts: inventory.hosts };
|
|
7
|
+
}
|
|
8
|
+
/** One frame of the picker: the command being built, the match table with the cursor row marked, and a count. */
|
|
9
|
+
export function renderPicker(inventory, selector, command, state, color, limit = HOST_MATCH_LIMIT) {
|
|
10
|
+
const matches = pickerMatches(inventory, state.query);
|
|
11
|
+
const paint = (text, code) => color ? `${code}${text}${RESET}` : text;
|
|
12
|
+
const lines = [
|
|
13
|
+
paint(`Host ${JSON.stringify(selector)} not found. ↑↓ move · Tab complete · Enter connect · Esc cancel`, DIM),
|
|
14
|
+
`> dreamlake ${command} ${state.query}${paint("▏", DIM)}`,
|
|
15
|
+
];
|
|
16
|
+
if (!matches.hosts.length) {
|
|
17
|
+
lines.push(`No hosts match ${JSON.stringify(matches.keyword)} in namespace ${inventory.namespace}. Keep typing or press Esc.`);
|
|
18
|
+
return lines.join("\n");
|
|
19
|
+
}
|
|
20
|
+
const start = Math.max(0, Math.min(state.cursor - Math.floor(limit / 2), matches.hosts.length - limit));
|
|
21
|
+
const shown = matches.hosts.slice(start, start + limit);
|
|
22
|
+
const selectedRow = (row) => row > 0 && start + row - 1 === state.cursor;
|
|
23
|
+
// Inside the inverse cursor row the highlight ends with "bold/underline off" so the inverse survives.
|
|
24
|
+
const decorate = (value, row, column) => color && row > 0 && column < 2 ? highlightMatches(value, matches.keyword, selectedRow(row) ? "\x1b[22;24m" : RESET) : value;
|
|
25
|
+
lines.push(...table(hostRows(shown), decorate).split("\n").map((line, row) => selectedRow(row) ? `${paint("❯", "\x1b[32m")} ${color ? `${INVERSE}${line}${RESET}` : line}` : ` ${line}`));
|
|
26
|
+
const hidden = matches.hosts.length - shown.length;
|
|
27
|
+
lines.push(`${matches.hosts.length} of ${inventory.total} hosts match.${hidden ? ` Showing ${shown.length}; type more to narrow.` : ""}`);
|
|
28
|
+
return lines.join("\n");
|
|
29
|
+
}
|
|
30
|
+
/** Pure key handling, so the loop and the tests share one definition. */
|
|
31
|
+
export function reducePicker(inventory, state, key) {
|
|
32
|
+
const count = pickerMatches(inventory, state.query).hosts.length;
|
|
33
|
+
const clamp = (cursor) => Math.max(0, Math.min(cursor, count - 1));
|
|
34
|
+
if (key === `${ESC}[A`)
|
|
35
|
+
return { state: { ...state, cursor: clamp(state.cursor - 1) } };
|
|
36
|
+
if (key === `${ESC}[B`)
|
|
37
|
+
return { state: { ...state, cursor: clamp(state.cursor + 1) } };
|
|
38
|
+
if (key === ESC || key === "\x03" || key === "\x04")
|
|
39
|
+
return { state, done: "cancel" };
|
|
40
|
+
if (key === "\r" || key === "\n")
|
|
41
|
+
return count ? { state, done: "pick" } : { state };
|
|
42
|
+
if (key === "\t") {
|
|
43
|
+
const target = pickerMatches(inventory, state.query).hosts[clamp(state.cursor)];
|
|
44
|
+
return target ? { state: { query: completeHostSegment(state.query, target.name), cursor: 0 } } : { state };
|
|
45
|
+
}
|
|
46
|
+
if (key === "\x7f" || key === "\b")
|
|
47
|
+
return { state: { query: state.query.slice(0, -1), cursor: 0 } };
|
|
48
|
+
if (key === "\x15")
|
|
49
|
+
return { state: { query: "", cursor: 0 } };
|
|
50
|
+
if (key.length === 1 && key >= " " && key !== "\x7f")
|
|
51
|
+
return { state: { query: state.query + key, cursor: 0 } };
|
|
52
|
+
return { state };
|
|
53
|
+
}
|
|
54
|
+
/** Split a raw-mode chunk into keys: arrow sequences stay whole, everything else is one character per key. */
|
|
55
|
+
export function splitKeys(chunk) {
|
|
56
|
+
const keys = [];
|
|
57
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
58
|
+
if (chunk[i] === ESC && chunk[i + 1] === "[" && /[A-D]/.test(chunk[i + 2] ?? "")) {
|
|
59
|
+
keys.push(chunk.slice(i, i + 3));
|
|
60
|
+
i += 2;
|
|
61
|
+
}
|
|
62
|
+
else if (chunk[i] === ESC && chunk[i + 1] === "[") {
|
|
63
|
+
i = chunk.length;
|
|
64
|
+
} // An unknown CSI sequence; drop the rest of the chunk.
|
|
65
|
+
else
|
|
66
|
+
keys.push(chunk[i]);
|
|
67
|
+
}
|
|
68
|
+
return keys;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Interactive host picker for a selector that named no host. Lists keyword matches with the best one
|
|
72
|
+
* highlighted; typing filters, Tab completes toward the highlighted host one segment at a time, Enter
|
|
73
|
+
* resolves to that host's full name, and Esc or Ctrl-C resolves to undefined. Draws on `io.output`.
|
|
74
|
+
*/
|
|
75
|
+
export function pickHost(inventory, selector, command, io) {
|
|
76
|
+
let state = { query: selector, cursor: 0 };
|
|
77
|
+
let drawn = 0;
|
|
78
|
+
const draw = () => {
|
|
79
|
+
const width = io.output.columns;
|
|
80
|
+
const lines = renderPicker(inventory, selector, command, state, io.color).split("\n")
|
|
81
|
+
.map(line => width && plainLength(line) >= width ? line.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "").slice(0, width - 1) : line);
|
|
82
|
+
io.output.write(`${drawn > 1 ? `${ESC}[${drawn - 1}A` : ""}\r${ESC}[0J${lines.join("\n")}`);
|
|
83
|
+
drawn = lines.length;
|
|
84
|
+
};
|
|
85
|
+
const clear = () => { io.output.write(`${drawn > 1 ? `${ESC}[${drawn - 1}A` : ""}\r${ESC}[0J${ESC}[?25h`); drawn = 0; };
|
|
86
|
+
const raw = io.input.isTTY && typeof io.input.setRawMode === "function";
|
|
87
|
+
return new Promise(resolve => {
|
|
88
|
+
const finish = (picked) => {
|
|
89
|
+
io.input.off("data", onData);
|
|
90
|
+
if (raw)
|
|
91
|
+
io.input.setRawMode(false);
|
|
92
|
+
io.input.pause();
|
|
93
|
+
clear();
|
|
94
|
+
if (picked !== undefined)
|
|
95
|
+
io.output.write(`dreamlake ${command} ${picked}\n`);
|
|
96
|
+
resolve(picked);
|
|
97
|
+
};
|
|
98
|
+
const onData = (chunk) => {
|
|
99
|
+
for (const key of splitKeys(chunk.toString())) {
|
|
100
|
+
const next = reducePicker(inventory, state, key);
|
|
101
|
+
state = next.state;
|
|
102
|
+
if (next.done === "cancel")
|
|
103
|
+
return finish(undefined);
|
|
104
|
+
if (next.done === "pick")
|
|
105
|
+
return finish(pickerMatches(inventory, state.query).hosts[state.cursor].name);
|
|
106
|
+
}
|
|
107
|
+
draw();
|
|
108
|
+
};
|
|
109
|
+
if (raw)
|
|
110
|
+
io.input.setRawMode(true);
|
|
111
|
+
io.input.on("data", onData);
|
|
112
|
+
io.input.resume();
|
|
113
|
+
io.output.write(`${ESC}[?25l`);
|
|
114
|
+
draw();
|
|
115
|
+
});
|
|
116
|
+
}
|
package/dist/cli/hosts/ssh.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { Duplex } from 'node:stream';
|
|
|
3
3
|
import WebSocket from 'ws';
|
|
4
4
|
import type { Command } from 'commander';
|
|
5
5
|
import { hostRequest } from './api.js';
|
|
6
|
+
import { type HostInventory } from './inventory.js';
|
|
6
7
|
/** Wait the server's Retry-After (capped at 5s) or exponential backoff, whichever is longer. */
|
|
7
8
|
export declare function busyRetryDelay(attempt: number, retryAt?: string, now?: number): number;
|
|
8
9
|
export interface SshTarget {
|
|
@@ -46,8 +47,23 @@ export interface SshIO {
|
|
|
46
47
|
socket: (url: string, ticket: string) => WebSocket;
|
|
47
48
|
spawn: (args: string[]) => ChildProcess;
|
|
48
49
|
chooseTarget?: (targets: SshTarget[]) => Promise<string>;
|
|
50
|
+
/** Whether a person is reading stderr; host suggestions and their highlight are terminal-only. */
|
|
51
|
+
terminal?: () => boolean;
|
|
52
|
+
/** Whether a person can also type (stdin is a terminal); only then does the picker replace the static list. */
|
|
53
|
+
interactive?: () => boolean;
|
|
54
|
+
/** The interactive picker: resolves to a full host name, or undefined when the person cancels. */
|
|
55
|
+
pick?: (inventory: HostInventory, selector: string, command: 'ssh' | 'exec') => Promise<string | undefined>;
|
|
49
56
|
}
|
|
50
57
|
export declare const defaultSshIO: SshIO;
|
|
58
|
+
/** Only a selector that named no host earns suggestions; auth, namespace and transport errors pass through unchanged. */
|
|
59
|
+
export declare function isHostLookupMiss(error: unknown): boolean;
|
|
60
|
+
/**
|
|
61
|
+
* Every host in the namespace the selector points at (its first segment, else the configured one),
|
|
62
|
+
* for suggesting what a partial or misspelled selector meant. Throws when the inventory cannot be read.
|
|
63
|
+
*/
|
|
64
|
+
export declare function suggestionInventory(selector: string, opts: SshOptions, io?: SshIO): Promise<HostInventory>;
|
|
65
|
+
/** The `hosts list` table filtered to the selector's keyword, with every match highlighted, for a terminal reader who cannot type back. */
|
|
66
|
+
export declare function suggestHosts(selector: string, opts: SshOptions, command: 'ssh' | 'exec', io?: SshIO): Promise<string>;
|
|
51
67
|
export declare function chooseSshTarget(targets: SshTarget[], selector: string, opts: SshOptions, argv: string[] | undefined, choose?: SshIO['chooseTarget']): Promise<SshTarget>;
|
|
52
68
|
export declare function sshPublicKey(value: string): string;
|
|
53
69
|
export declare function validateSshTarget(t: SshTarget, hostId: string, namespace: string): void;
|
package/dist/cli/hosts/ssh.js
CHANGED
|
@@ -11,7 +11,8 @@ import WebSocket from 'ws';
|
|
|
11
11
|
import { select } from '@inquirer/prompts';
|
|
12
12
|
import { HostApiError, hostApiPath, hostRequest } from './api.js';
|
|
13
13
|
import { hostStatus } from './enroll.js';
|
|
14
|
-
import { resolveHostNamespace } from './inventory.js';
|
|
14
|
+
import { formatHostMatches, listHosts, matchHosts, resolveHostNamespace } from './inventory.js';
|
|
15
|
+
import { pickHost } from './picker.js';
|
|
15
16
|
const ID = /^[a-f0-9]{24}$/;
|
|
16
17
|
// Same budget as the browser relay: 4 delegation attempts within 25s.
|
|
17
18
|
const BUSY_MAX_ATTEMPTS = 4, BUSY_RETRY_BUDGET_MS = 25000;
|
|
@@ -21,11 +22,34 @@ export function busyRetryDelay(attempt, retryAt, now = Date.now()) {
|
|
|
21
22
|
return Math.max(Number.isFinite(hinted) ? hinted : 0, 1000 * 2 ** (attempt - 1));
|
|
22
23
|
}
|
|
23
24
|
export const defaultSshIO = {
|
|
24
|
-
request: hostRequest, fetch: (...args) => fetch(...args),
|
|
25
|
+
request: hostRequest, fetch: (...args) => fetch(...args), terminal: () => Boolean(process.stderr.isTTY),
|
|
26
|
+
interactive: () => Boolean(process.stdin.isTTY && process.stderr.isTTY),
|
|
27
|
+
pick: (inventory, selector, command) => pickHost(inventory, selector, command, { input: process.stdin, output: process.stderr, color: !process.env.NO_COLOR }),
|
|
25
28
|
socket: (url, ticket) => new WebSocket(url, 'nymph-ssh.v1', { headers: { Authorization: `Bearer ${ticket}` },
|
|
26
29
|
perMessageDeflate: false, maxPayload: 65537, handshakeTimeout: 10000, followRedirects: false }),
|
|
27
30
|
spawn: args => spawn('ssh', args, { stdio: 'inherit' }),
|
|
28
31
|
};
|
|
32
|
+
/** Only a selector that named no host earns suggestions; auth, namespace and transport errors pass through unchanged. */
|
|
33
|
+
export function isHostLookupMiss(error) {
|
|
34
|
+
if (error instanceof HostApiError)
|
|
35
|
+
return error.status === 403 || error.status === 404;
|
|
36
|
+
const message = error instanceof Error ? error.message : '';
|
|
37
|
+
return message.startsWith('Host selector must be') || message.startsWith('Host not found');
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Every host in the namespace the selector points at (its first segment, else the configured one),
|
|
41
|
+
* for suggesting what a partial or misspelled selector meant. Throws when the inventory cannot be read.
|
|
42
|
+
*/
|
|
43
|
+
export async function suggestionInventory(selector, opts, io = defaultSshIO) {
|
|
44
|
+
const parts = selector.split('/');
|
|
45
|
+
const namespace = parts.length === 3 && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(parts[0]) && !opts.namespace ? parts[0] : await resolveHostNamespace(opts.namespace);
|
|
46
|
+
return listHosts({ namespace, all: true }, io.request);
|
|
47
|
+
}
|
|
48
|
+
/** The `hosts list` table filtered to the selector's keyword, with every match highlighted, for a terminal reader who cannot type back. */
|
|
49
|
+
export async function suggestHosts(selector, opts, command, io = defaultSshIO) {
|
|
50
|
+
const inventory = await suggestionInventory(selector, opts, io);
|
|
51
|
+
return formatHostMatches(inventory, matchHosts(inventory.hosts, selector), !process.env.NO_COLOR, command);
|
|
52
|
+
}
|
|
29
53
|
export async function chooseSshTarget(targets, selector, opts, argv, choose) {
|
|
30
54
|
if (targets.length === 0)
|
|
31
55
|
throw new Error('No ready SSH enrollment for this host');
|
|
@@ -145,7 +169,27 @@ export async function runHostSsh(selector, opts, argv, io = defaultSshIO) {
|
|
|
145
169
|
throw new Error('--timeout must be 1–duration seconds');
|
|
146
170
|
if (opts.enrollment !== undefined && !ID.test(opts.enrollment))
|
|
147
171
|
throw new Error('Use an exact enrollment ID');
|
|
148
|
-
|
|
172
|
+
let detail;
|
|
173
|
+
try {
|
|
174
|
+
detail = await hostStatus(selector, opts, io.request);
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
if (!isHostLookupMiss(error) || !io.terminal?.())
|
|
178
|
+
throw error;
|
|
179
|
+
const command = argv === undefined ? 'ssh' : 'exec';
|
|
180
|
+
const inventory = await suggestionInventory(selector, opts, io).catch(() => undefined);
|
|
181
|
+
if (!inventory)
|
|
182
|
+
throw error;
|
|
183
|
+
if (!io.interactive?.() || !io.pick) {
|
|
184
|
+
throw new Error(`${error instanceof Error ? error.message : 'Host lookup failed'}\n${formatHostMatches(inventory, matchHosts(inventory.hosts, selector), !process.env.NO_COLOR, command)}`);
|
|
185
|
+
}
|
|
186
|
+
// A person is typing: let them pick the host they meant. Cancelling keeps the original error and exit code.
|
|
187
|
+
const picked = await io.pick(inventory, selector, command);
|
|
188
|
+
if (picked === undefined)
|
|
189
|
+
throw error;
|
|
190
|
+
selector = picked;
|
|
191
|
+
detail = await hostStatus(selector, opts, io.request);
|
|
192
|
+
}
|
|
149
193
|
const namespace = selector.includes('/') ? selector.split('/')[0] : await resolveHostNamespace(opts.namespace);
|
|
150
194
|
if (!ID.test(detail?.host?.id) || !Array.isArray(detail.enrollments))
|
|
151
195
|
throw new Error('Invalid host response');
|
package/dist/cli/index.js
CHANGED
|
@@ -39,6 +39,7 @@ import { registerNotesCommand } from "./notes/index.js";
|
|
|
39
39
|
import { registerDeclareCommand } from "./declare/index.js";
|
|
40
40
|
import { registerHostsCommand } from "./hosts/index.js";
|
|
41
41
|
import { registerSessionsCommand } from "./sessions/index.js";
|
|
42
|
+
import { registerAgentWrappers } from "./sessions/wrap.js";
|
|
42
43
|
import { registerInfraCommand } from "./infra/index.js";
|
|
43
44
|
import { registerVaultCommand } from "./vault/index.js";
|
|
44
45
|
import { registerAgentsCommand } from "./agents/index.js";
|
|
@@ -228,6 +229,7 @@ async function main(argv) {
|
|
|
228
229
|
registerNymphCommand(program);
|
|
229
230
|
registerHostsCommand(program);
|
|
230
231
|
registerSessionsCommand(program);
|
|
232
|
+
registerAgentWrappers(program);
|
|
231
233
|
registerInfraCommand(program);
|
|
232
234
|
registerRunsCommands(program);
|
|
233
235
|
registerJobsCommand(program);
|
|
@@ -7,8 +7,9 @@ export function sessionContext(env = process.env) {
|
|
|
7
7
|
const id = env.DREAMLAKE_TERMINAL_SESSION_ID, ns = env.DREAMLAKE_SESSION_NAMESPACE;
|
|
8
8
|
if (id)
|
|
9
9
|
return id && ns && objectId.test(id) && namespace.test(ns) ? { saved: { id, namespace: ns } } : null;
|
|
10
|
-
// Never infer a native identity from arbitrary agent/presence labels.
|
|
11
|
-
|
|
10
|
+
// Never infer a native identity from arbitrary agent/presence labels. Claude Code exports
|
|
11
|
+
// CLAUDE_CODE_SESSION_ID to its subprocesses; an explicit CLAUDE_SESSION_ID wins when both are set.
|
|
12
|
+
const codex = env.CODEX_THREAD_ID, claude = env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID;
|
|
12
13
|
if (codex && claude)
|
|
13
14
|
return null;
|
|
14
15
|
if (codex && uuid.test(codex))
|
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
import type { Command } from 'commander';
|
|
2
|
-
import { type ResourceSessionRef } from '../session-affiliation.js';
|
|
2
|
+
import { type ResourceSessionRef, type SavedSessionRef } from '../session-affiliation.js';
|
|
3
|
+
/** The saved-session context `sessionContext()` reads first: a shell that sources this file links its
|
|
4
|
+
* note and artifact writes to the session without any native id in its environment. The assignments are
|
|
5
|
+
* `export`ed, because a plain `KEY=value` line only sets a shell variable that the `dreamlake` child
|
|
6
|
+
* process never receives. Private (0600). */
|
|
7
|
+
export declare function writeSessionEnvFile(path: string, session: SavedSessionRef): string;
|
|
8
|
+
/** Where the `/dreamlake` skill and the SessionStart hook keep the env file of a native session, so a hook
|
|
9
|
+
* that only knows the native id (Claude Code hands it over on stdin) can find the saved session. */
|
|
10
|
+
export declare const sessionEnvFilePath: (nativeId: string, home?: string) => string;
|
|
11
|
+
/** Read back exactly what `writeSessionEnvFile` wrote: the two exported, single-quoted assignments. Anything
|
|
12
|
+
* else — another shape, a value that is not a saved id or namespace, a missing file — is `null`, never a guess. */
|
|
13
|
+
export declare function readSessionEnvFile(path: string): SavedSessionRef | null;
|
|
3
14
|
export declare function resourceFromOptions(opts: {
|
|
4
15
|
note?: string;
|
|
5
16
|
artifact?: string;
|
|
@@ -1,6 +1,43 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
1
4
|
import { resolveHostNamespace } from '../hosts/inventory.js';
|
|
2
5
|
import { affiliationPath } from '../session-affiliation.js';
|
|
3
6
|
import { connection, requestJson, sessionPath } from './api.js';
|
|
7
|
+
/** POSIX single-quoting: safe for any value, and identical in sh, bash and zsh. */
|
|
8
|
+
const shellQuoted = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
|
|
9
|
+
/** The saved-session context `sessionContext()` reads first: a shell that sources this file links its
|
|
10
|
+
* note and artifact writes to the session without any native id in its environment. The assignments are
|
|
11
|
+
* `export`ed, because a plain `KEY=value` line only sets a shell variable that the `dreamlake` child
|
|
12
|
+
* process never receives. Private (0600). */
|
|
13
|
+
export function writeSessionEnvFile(path, session) {
|
|
14
|
+
if (!/^[a-f0-9]{24}$/.test(session.id) || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(session.namespace))
|
|
15
|
+
throw new Error('Use an exact saved session ID and namespace for the env file');
|
|
16
|
+
const target = resolve(path);
|
|
17
|
+
mkdirSync(dirname(target), { recursive: true, mode: 0o700 });
|
|
18
|
+
writeFileSync(target, `export DREAMLAKE_TERMINAL_SESSION_ID=${shellQuoted(session.id)}\nexport DREAMLAKE_SESSION_NAMESPACE=${shellQuoted(session.namespace)}\n`, { mode: 0o600 });
|
|
19
|
+
chmodSync(target, 0o600);
|
|
20
|
+
return target;
|
|
21
|
+
}
|
|
22
|
+
/** Where the `/dreamlake` skill and the SessionStart hook keep the env file of a native session, so a hook
|
|
23
|
+
* that only knows the native id (Claude Code hands it over on stdin) can find the saved session. */
|
|
24
|
+
export const sessionEnvFilePath = (nativeId, home = homedir()) => join(home, '.dreamlake', 'sessions', `${nativeId.toLowerCase()}.env`);
|
|
25
|
+
/** Read back exactly what `writeSessionEnvFile` wrote: the two exported, single-quoted assignments. Anything
|
|
26
|
+
* else — another shape, a value that is not a saved id or namespace, a missing file — is `null`, never a guess. */
|
|
27
|
+
export function readSessionEnvFile(path) {
|
|
28
|
+
let text;
|
|
29
|
+
try {
|
|
30
|
+
text = readFileSync(path, 'utf8');
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
if (text.length > 4096)
|
|
36
|
+
return null;
|
|
37
|
+
const read = (key) => { const m = text.match(new RegExp(`^export ${key}='([^'\n]*)'$`, 'm')); return m ? m[1] : null; };
|
|
38
|
+
const id = read('DREAMLAKE_TERMINAL_SESSION_ID'), namespace = read('DREAMLAKE_SESSION_NAMESPACE');
|
|
39
|
+
return id && namespace && /^[a-f0-9]{24}$/.test(id) && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(namespace) ? { id, namespace } : null;
|
|
40
|
+
}
|
|
4
41
|
export function resourceFromOptions(opts) {
|
|
5
42
|
if (Boolean(opts.note) === Boolean(opts.artifact))
|
|
6
43
|
throw new Error('Choose exactly one --note NOTE_ID or --artifact ARTIFACT_ID');
|
|
@@ -3,4 +3,15 @@
|
|
|
3
3
|
* over the TypeScript API (`src/api`), so behaviour, permissions and error
|
|
4
4
|
* codes are identical in both. */
|
|
5
5
|
import type { Command } from 'commander';
|
|
6
|
+
import { type PermissionLevel, type SessionsApi } from '../../api/index.js';
|
|
7
|
+
/** The raise rule, applied before anything is submitted. The server cannot tell a token holder from a
|
|
8
|
+
* person, so a raise carries `raise: true` only when a person asked: `--raise` on the command line AND a
|
|
9
|
+
* confirmation typed on a terminal. Without a terminal nobody can be asked, so a raise is refused: a script
|
|
10
|
+
* or an agent holding the token must not be able to widen a session on its own. Lowering or keeping the
|
|
11
|
+
* level sends no flag. */
|
|
12
|
+
export declare function raiseConfirmation(api: Pick<SessionsApi, 'get'>, sessionId: string, level: PermissionLevel, opts: {
|
|
13
|
+
raise?: boolean;
|
|
14
|
+
}, ask?: (message: string) => Promise<boolean>, interactive?: boolean): Promise<{
|
|
15
|
+
raise?: true;
|
|
16
|
+
}>;
|
|
6
17
|
export declare function registerSessionControl(group: Command): void;
|
|
@@ -4,8 +4,9 @@ import { homedir } from 'node:os';
|
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { resolveHostNamespace } from '../hosts/inventory.js';
|
|
6
6
|
import { resolveRemote, resolveToken } from '../config.js';
|
|
7
|
-
import { ApiError, createClient, isObjectId } from '../../api/index.js';
|
|
7
|
+
import { ApiError, createClient, isObjectId, isPermissionRaise, PERMISSION_LEVELS } from '../../api/index.js';
|
|
8
8
|
import { VERSION } from '../version.js';
|
|
9
|
+
import { confirm } from '../prompt.js';
|
|
9
10
|
import { serve } from './runner/serve.js';
|
|
10
11
|
function client() {
|
|
11
12
|
const token = resolveToken();
|
|
@@ -29,10 +30,30 @@ const guard = async (opts, work) => {
|
|
|
29
30
|
};
|
|
30
31
|
const needId = (value) => { if (!isObjectId(value))
|
|
31
32
|
throw new Error('Use the 24-hex session id from sessions list'); return value; };
|
|
33
|
+
const needLevel = (value, flag = '--permission') => { if (!PERMISSION_LEVELS.includes(String(value)))
|
|
34
|
+
throw new Error(`${flag} must be read-only, workspace-write or full-access`); return value; };
|
|
35
|
+
/** The raise rule, applied before anything is submitted. The server cannot tell a token holder from a
|
|
36
|
+
* person, so a raise carries `raise: true` only when a person asked: `--raise` on the command line AND a
|
|
37
|
+
* confirmation typed on a terminal. Without a terminal nobody can be asked, so a raise is refused: a script
|
|
38
|
+
* or an agent holding the token must not be able to widen a session on its own. Lowering or keeping the
|
|
39
|
+
* level sends no flag. */
|
|
40
|
+
export async function raiseConfirmation(api, sessionId, level, opts, ask = message => confirm(message, false), interactive = !!process.stdin.isTTY) {
|
|
41
|
+
const row = await api.get(sessionId), current = row.permissionLevel ?? null;
|
|
42
|
+
if (!isPermissionRaise(current, level))
|
|
43
|
+
return {};
|
|
44
|
+
const from = current ?? 'an unrecorded level';
|
|
45
|
+
if (!opts.raise)
|
|
46
|
+
throw new Error(`Raising ${from} to ${level} widens what the agent may do. Pass --raise to ask for it as the person responsible; the runner must have been started with --max-human-permission ${level} or higher.`);
|
|
47
|
+
if (!interactive)
|
|
48
|
+
throw new Error(`Raising ${from} to ${level} needs an interactive confirmation: run this on a terminal. A script or an agent cannot raise a session on its own.`);
|
|
49
|
+
if (!await ask(`Raise session ${sessionId} from ${from} to ${level}? The agent gets wider access from its next turn.`))
|
|
50
|
+
throw new Error('Raise not confirmed; nothing was changed');
|
|
51
|
+
return { raise: true };
|
|
52
|
+
}
|
|
32
53
|
export function registerSessionControl(group) {
|
|
33
54
|
const common = (c) => c.option('--namespace <namespace>', 'personal namespace (default: signed-in personal namespace)').option('--json', 'emit JSON');
|
|
34
55
|
common(group.command('serve').description('run the session runner on this machine: executes start/resume/stop/send/sync/status/subagents commands for your sessions with the Codex/Claude CLIs (tmux when available, headless otherwise)'))
|
|
35
|
-
.option('--allow-repo <path>', 'trusted repository for built-in-origin starts; repeat (default current directory)', (value, all) => [...all, value], []).option('--max-agent-permission <level>', 'maximum built-in-origin startup permission', 'workspace-write').option('--pod-config <file>', 'explicit Docker image, repository allowlist, credentials and resource limits').option('--once', 'handle at most one command, then exit').option('--poll <seconds>', 'long-poll length per claim, 1–25', '25')
|
|
56
|
+
.option('--allow-repo <path>', 'trusted repository for built-in-origin starts; repeat (default current directory)', (value, all) => [...all, value], []).option('--max-agent-permission <level>', 'maximum built-in-origin startup permission', 'workspace-write').option('--max-human-permission <level>', 'highest level a person may raise a session to on this runner (control restart --raise, sessions permission --raise); default: no raise above the start level').option('--pod-config <file>', 'explicit Docker image, repository allowlist, credentials and resource limits').option('--once', 'handle at most one command, then exit').option('--poll <seconds>', 'long-poll length per claim, 1–25', '25')
|
|
36
57
|
.action(opts => guard(opts, async () => {
|
|
37
58
|
const ns = await resolveHostNamespace(opts.namespace), abort = new AbortController();
|
|
38
59
|
process.once('SIGINT', () => abort.abort());
|
|
@@ -42,7 +63,8 @@ export function registerSessionControl(group) {
|
|
|
42
63
|
throw new Error('--poll must be 1–25 seconds');
|
|
43
64
|
if (!['read-only', 'workspace-write', 'full-access'].includes(opts.maxAgentPermission))
|
|
44
65
|
throw new Error('Invalid --max-agent-permission');
|
|
45
|
-
const
|
|
66
|
+
const maxHumanPermission = opts.maxHumanPermission === undefined ? undefined : needLevel(opts.maxHumanPermission, '--max-human-permission');
|
|
67
|
+
const result = await serve({ client: client(), namespace: ns, version: VERSION, trustedRepositories: opts.allowRepo.length ? opts.allowRepo : undefined, maxAgentPermission: opts.maxAgentPermission, maxHumanPermission, podConfig: opts.podConfig ? loadPodConfig(opts.podConfig) : undefined, once: !!opts.once, signal: abort.signal, pollSeconds: poll });
|
|
46
68
|
if (opts.json)
|
|
47
69
|
emit(result, true);
|
|
48
70
|
}));
|
|
@@ -59,7 +81,7 @@ export function registerSessionControl(group) {
|
|
|
59
81
|
const ns = await resolveHostNamespace(opts.namespace), runners = await client().sessions(ns).runners.list();
|
|
60
82
|
if (opts.json)
|
|
61
83
|
return emit({ namespace: ns, runners }, true);
|
|
62
|
-
console.log(runners.map(r => `${r.id} ${r.hostname} ${r.unixUser} ${r.online ? 'online' : 'offline'} modes=${r.capabilities.modes.join('/')} seen ${r.lastSeenAt}`).join('\n') || 'No runners registered. Start one with: dreamlake sessions serve');
|
|
84
|
+
console.log(runners.map(r => `${r.id} ${r.hostname} ${r.unixUser} ${r.online ? 'online' : 'offline'} modes=${r.capabilities.modes.join('/')} human-cap=${r.capabilities.humanPermissionCap ?? 'none'} seen ${r.lastSeenAt}`).join('\n') || 'No runners registered. Start one with: dreamlake sessions serve');
|
|
63
85
|
}));
|
|
64
86
|
const control = group.command('control').description('durable session commands executed by your runner (dreamlake sessions serve)');
|
|
65
87
|
const waitOption = (c) => c.option('--wait <seconds>', 'wait for the receipt (0 returns the pending command)', '60').option('--runner <id>', 'target an explicit runner id');
|
|
@@ -88,6 +110,17 @@ export function registerSessionControl(group) {
|
|
|
88
110
|
throw new Error('--permission must be read-only, workspace-write or full-access'); return value === undefined ? {} : { permissionLevel: value }; };
|
|
89
111
|
waitOption(common(control.command('resume <id>').description('resume a session on its runner, optionally with a prompt'))).option('--prompt <text>').option('--mode <mode>', 'tmux or headless').option('--permission <level>', 'permission ceiling for the new provider process (default: the level recorded at start)')
|
|
90
112
|
.action((id, opts) => guard(opts, () => submit(opts, 'resume', { sessionId: needId(id), ...(opts.prompt ? { prompt: opts.prompt } : {}), ...(opts.mode ? { mode: opts.mode } : {}), ...level(opts.permission) })));
|
|
113
|
+
waitOption(common(control.command('restart <id>').description('stop the session process and resume the same conversation under a new recorded permission level; the receipt echoes the command line it ran')))
|
|
114
|
+
.requiredOption('--permission <level>', 'read-only, workspace-write or full-access; the level recorded for every later turn')
|
|
115
|
+
.option('--raise', 'ask, as the person responsible, to raise the level (needs a runner started with --max-human-permission; confirmed interactively on a terminal)')
|
|
116
|
+
.option('--prompt <text>', 'first prompt after the restart (headless mode runs one turn with it)').option('--mode <mode>', 'tmux or headless').option('--reason <text>', 'recorded in the permission history (1–200 characters)')
|
|
117
|
+
.action((id, opts) => guard(opts, async () => {
|
|
118
|
+
const level = needLevel(opts.permission), ns = await resolveHostNamespace(opts.namespace);
|
|
119
|
+
if (opts.reason !== undefined && (!String(opts.reason).trim() || String(opts.reason).length > 200))
|
|
120
|
+
throw new Error('--reason must be 1–200 characters');
|
|
121
|
+
const raise = await raiseConfirmation(client().sessions(ns), needId(id), level, opts);
|
|
122
|
+
return submit({ ...opts, namespace: ns }, 'restart', { sessionId: id, permissionLevel: level, ...(opts.prompt ? { prompt: opts.prompt } : {}), ...(opts.mode ? { mode: opts.mode } : {}), ...(opts.reason ? { reason: opts.reason } : {}), ...raise });
|
|
123
|
+
}));
|
|
91
124
|
waitOption(common(control.command('stop <id>').description('stop the managed process of a session; descriptor and conversation are kept'))).option('--yes', 'confirm stopping the process')
|
|
92
125
|
.action((id, opts) => guard(opts, () => { if (!opts.yes)
|
|
93
126
|
throw new Error('Stopping ends the agent process. Pass --yes to confirm'); return submit(opts, 'stop', { sessionId: needId(id) }); }));
|
|
@@ -108,6 +141,18 @@ export function registerSessionControl(group) {
|
|
|
108
141
|
common(control.command('list').description('list recent commands and their receipts')).option('--session <id>').option('--status <status>').option('--limit <n>', 'max 100', '25')
|
|
109
142
|
.action(opts => guard(opts, async () => { const ns = await resolveHostNamespace(opts.namespace); emit({ namespace: ns, ...(await client().sessions(ns).commands.list({ ...(opts.session ? { sessionId: needId(opts.session) } : {}), ...(opts.status ? { status: opts.status } : {}), limit: Number(opts.limit) })) }, !!opts.json); }));
|
|
110
143
|
common(group.command('children <id>').description('list managed child sessions; control each child by its stable session ID')).option('--cursor <cursor>').action((id, opts) => guard(opts, async () => { const ns = await resolveHostNamespace(opts.namespace); emit(await client().sessions(ns).list({ parentSessionId: needId(id), cursor: opts.cursor, archived: 'include' }), !!opts.json); }));
|
|
144
|
+
common(group.command('permission <id> <level>').description('move the recorded permission level of a session without a runner round-trip; the running process keeps its level until the next resume or restart'))
|
|
145
|
+
.option('--raise', 'ask, as the person responsible, to raise the level (needs a runner started with --max-human-permission; confirmed interactively on a terminal)').option('--reason <text>', 'recorded in the permission history (1–200 characters)')
|
|
146
|
+
.action((id, level, opts) => guard(opts, async () => {
|
|
147
|
+
const wanted = needLevel(level, 'level'), ns = await resolveHostNamespace(opts.namespace), api = client().sessions(ns);
|
|
148
|
+
if (opts.reason !== undefined && (!String(opts.reason).trim() || String(opts.reason).length > 200))
|
|
149
|
+
throw new Error('--reason must be 1–200 characters');
|
|
150
|
+
const raise = await raiseConfirmation(api, needId(id), wanted, opts);
|
|
151
|
+
const result = await api.permission(id, { permissionLevel: wanted, ...(opts.reason ? { reason: opts.reason } : {}), ...raise });
|
|
152
|
+
if (opts.json)
|
|
153
|
+
return emit({ namespace: ns, ...result }, true);
|
|
154
|
+
console.log(`${result.session.id} permission ${result.session.permissionLevel}${result.changed ? '' : ' (unchanged)'}${result.session.observedPermissionLevel && result.session.observedPermissionLevel !== result.session.permissionLevel ? ` (runner last ran under ${result.session.observedPermissionLevel}; applied on the next resume or restart)` : ''}`);
|
|
155
|
+
}));
|
|
111
156
|
common(group.command('rename <id> <name>').description('rename one of your sessions')).action((id, name, opts) => guard(opts, async () => { const ns = await resolveHostNamespace(opts.namespace); emit({ session: await client().sessions(ns).rename(needId(id), name) }, !!opts.json); }));
|
|
112
157
|
common(group.command('archive <id>').description('hide a session from default listings; conversation and links are kept')).action((id, opts) => guard(opts, async () => { const ns = await resolveHostNamespace(opts.namespace); emit({ session: await client().sessions(ns).archive(needId(id), true) }, !!opts.json); }));
|
|
113
158
|
common(group.command('unarchive <id>').description('return an archived session to default listings')).action((id, opts) => guard(opts, async () => { const ns = await resolveHostNamespace(opts.namespace); emit({ session: await client().sessions(ns).archive(needId(id), false) }, !!opts.json); }));
|
|
@@ -5,11 +5,20 @@ import { attachSession, requireTerminal } from './transport.js';
|
|
|
5
5
|
import { attachmentKind, managedOperation, stopGuard } from './managed.js';
|
|
6
6
|
import { syncTarget } from './sync.js';
|
|
7
7
|
import { registerSessionConversation } from './conversation.js';
|
|
8
|
-
import { registerSessionAffiliations } from './affiliation.js';
|
|
8
|
+
import { registerSessionAffiliations, writeSessionEnvFile } from './affiliation.js';
|
|
9
9
|
import { registerSessionControl } from './control.js';
|
|
10
|
-
|
|
10
|
+
import { registerSessionLive } from './live.js';
|
|
11
|
+
// Tolerates the fields a registered (host-less) descriptor leaves empty.
|
|
12
|
+
const cell = (value) => String(value ?? '').replace(/[\x00-\x1f\x7f-\x9f]/g, ' ');
|
|
11
13
|
const summary = (s) => `${cell(s.id)} ${cell(s.name)}\n ${cell(s.username)}@${cell(s.machineId)} ${cell(s.cwd)}\n ${s.provider === 'claude' ? 'Claude' : 'Codex'} ${cell(s.codexSessionId)}${s.runState ? ` · ${cell(s.runState)}` : ''}`;
|
|
12
14
|
const runtimeSummary = (s, r) => `${summary(s)}\n Runtime: ${r.kind === 'direct' ? 'Direct' : `tmux ${cell(s.tmuxSession)}`}\n State: ${r.status}${r.reason ? ` (${r.reason})` : ''} · managed: ${r.managed ? 'yes' : 'no'} · viewers: ${r.clients ?? 'unknown'}\n Observed: ${r.observedAt}${r.pane ? ` · pane ${r.pane.id} · PID ${r.pane.pid}` : ''}`;
|
|
15
|
+
/** What the session is doing now, from its hooks or runner (`liveState`), next to the Nymph/runner `runState`. */
|
|
16
|
+
const liveSummary = (s) => {
|
|
17
|
+
const live = s.liveState ? `${cell(s.liveState)}${s.liveStateReported && s.liveStateReported !== s.liveState ? ` (reported ${cell(s.liveStateReported)})` : ''}${s.liveStateSource ? ` via ${cell(s.liveStateSource)}` : ''}${s.liveStateAt ? ` at ${cell(s.liveStateAt)}` : ''}` : 'none reported (no hooks or runner heartbeat yet)';
|
|
18
|
+
const current = s.current?.tool || s.current?.promptHead ? `\n Current: ${s.current.tool ? cell(s.current.tool) : ''}${s.current.tool && s.current.promptHead ? ' · ' : ''}${s.current.promptHead ? `“${cell(s.current.promptHead)}”` : ''}` : '';
|
|
19
|
+
const permission = s.permissionLevel ? `\n Permission: ${cell(s.permissionLevel)}${s.observedPermissionLevel && s.observedPermissionLevel !== s.permissionLevel ? ` (runner last ran under ${cell(s.observedPermissionLevel)})` : ''}` : '';
|
|
20
|
+
return `\n Live: ${live}${current}${permission}${s.runnerId ? `\n Runner: ${cell(s.runnerId)}` : ''}`;
|
|
21
|
+
};
|
|
13
22
|
const openingMessage = (id, kind) => kind === 'direct'
|
|
14
23
|
? `Opening session ${id} directly. Ctrl-] disconnects; disconnecting may end the process. Use sessions open to resume explicitly.`
|
|
15
24
|
: `Opening session ${id}. Ctrl-] detaches; reopen the same ID to reattach.`;
|
|
@@ -18,6 +27,7 @@ export function registerSessionsCommand(program) {
|
|
|
18
27
|
registerSessionAffiliations(group);
|
|
19
28
|
registerSessionConversation(group);
|
|
20
29
|
registerSessionControl(group);
|
|
30
|
+
registerSessionLive(group);
|
|
21
31
|
const common = (c) => c.option('--namespace <namespace>', 'personal namespace (default: signed-in personal namespace)');
|
|
22
32
|
const gateway = (c) => c.option('--gateway <url>', 'explicit terminal gateway HTTPS origin; requires --origin').option('--origin <url>', 'allowed web origin for the selected gateway');
|
|
23
33
|
const target = (c) => c.requiredOption('--target <id>', 'exact target ID from sessions targets').option('--enrollment <id>', 'pin exact enrollment ID (default: discover the selected target enrollment)').requiredOption('--cwd <path>', 'absolute working directory on the target host').option('--name <name>', 'readable session name').option('--provider <provider>', 'agent tool: codex (default) or claude').option('--claude-config-dir <path>', 'absolute Claude configuration root on the target host');
|
|
@@ -34,20 +44,45 @@ export function registerSessionsCommand(program) {
|
|
|
34
44
|
process.exitCode = 1;
|
|
35
45
|
}
|
|
36
46
|
};
|
|
37
|
-
group.command('register').description('register native session metadata without an enrolled host or terminal launch')
|
|
47
|
+
group.command('register').description('register native session metadata without an enrolled host or terminal launch; idempotent for the same provider and native UUID')
|
|
38
48
|
.requiredOption('--provider <provider>', 'codex or claude').requiredOption('--session <uuid>', 'native conversation UUID')
|
|
39
49
|
.requiredOption('--cwd <path>', 'original absolute working directory').option('--name <name>')
|
|
40
|
-
.option('--visibility <visibility>', 'public (default for new sessions) or private')
|
|
50
|
+
.option('--visibility <visibility>', 'public (default for new sessions) or private')
|
|
51
|
+
.option('--write-env <path>', 'write DREAMLAKE_TERMINAL_SESSION_ID and DREAMLAKE_SESSION_NAMESPACE (mode 600) so a shell that sources it links its note and artifact writes to this session')
|
|
52
|
+
.option('--json')
|
|
41
53
|
.action(opts => run(opts, async () => {
|
|
42
54
|
if (!['codex', 'claude'].includes(opts.provider) || !/^[a-f0-9-]{36}$/i.test(opts.session) || !opts.cwd.startsWith('/') ||
|
|
43
55
|
(opts.visibility !== undefined && !['public', 'private'].includes(opts.visibility)))
|
|
44
56
|
throw new Error('Use codex/claude, an exact native UUID, an absolute cwd, and public/private visibility');
|
|
57
|
+
// The server returns the existing row for an already registered provider + native UUID, so a
|
|
58
|
+
// second registration (another cwd, another day) is the same saved session, never a duplicate.
|
|
45
59
|
const result = await requestJson(connection(), '/terminal-sessions/register', 'POST', { provider: opts.provider,
|
|
46
60
|
nativeSessionId: opts.session.toLowerCase(), cwd: opts.cwd, ...(opts.name ? { name: opts.name } : {}),
|
|
47
61
|
...(opts.visibility ? { visibility: opts.visibility } : {}) });
|
|
48
|
-
if (!result?.session?.id || result.session.codexSessionId !== opts.session.toLowerCase() || result.session.canManage !== true)
|
|
62
|
+
if (!result?.session?.id || !/^[a-f0-9]{24}$/.test(result.session.id) || result.session.codexSessionId !== opts.session.toLowerCase() || result.session.canManage !== true)
|
|
49
63
|
throw new Error('Invalid registration receipt');
|
|
50
|
-
|
|
64
|
+
const saved = result.session, ns = typeof saved.namespaceSlug === 'string' && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(saved.namespaceSlug) ? saved.namespaceSlug : null;
|
|
65
|
+
let envFile;
|
|
66
|
+
if (opts.writeEnv) {
|
|
67
|
+
if (!ns)
|
|
68
|
+
throw new Error('Registration receipt carries no namespace; the env file was not written');
|
|
69
|
+
envFile = writeSessionEnvFile(opts.writeEnv, { id: saved.id, namespace: ns });
|
|
70
|
+
}
|
|
71
|
+
if (opts.json) {
|
|
72
|
+
console.log(JSON.stringify({ ...result, executed: false, ...(envFile ? { envFile } : {}) }, null, 2));
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const namespaceFlag = ns ? ` --namespace ${ns}` : '';
|
|
76
|
+
console.log([
|
|
77
|
+
`Session ${cell(saved.id)} saved${ns ? ` in @${cell(ns)}` : ''}: ${opts.provider} ${cell(String(saved.codexSessionId).slice(0, 8))}… · ${cell(String(saved.visibility ?? 'public')).toLowerCase()} · ${cell(saved.cwd ?? opts.cwd)}`,
|
|
78
|
+
// A registered session has no recorded permission level, and a runner refuses a turn without one;
|
|
79
|
+
// one restart records it (a raise from "unrecorded", confirmed on a terminal), then sends are plain.
|
|
80
|
+
`Message it from anywhere (needs \`dreamlake sessions serve --max-human-permission workspace-write\` on this machine; record the level once, on a terminal):`,
|
|
81
|
+
` dreamlake sessions control restart ${cell(saved.id)} --permission workspace-write --raise${namespaceFlag}`,
|
|
82
|
+
` dreamlake sessions control send ${cell(saved.id)} "Summarize your state"${namespaceFlag}`,
|
|
83
|
+
` dreamlake sessions control status ${cell(saved.id)}${namespaceFlag}`,
|
|
84
|
+
envFile ? `Env file written: ${cell(envFile)} — \`source\` it in another shell so its note and artifact writes link to this session.` : 'Note and artifact writes from this Claude Code session link to it automatically (CLAUDE_CODE_SESSION_ID).',
|
|
85
|
+
].join('\n'));
|
|
51
86
|
}));
|
|
52
87
|
common(group.command('visibility <id>')).requiredOption('--visibility <visibility>', 'public or private').option('--json')
|
|
53
88
|
.action((id, opts) => run(opts, async () => {
|
|
@@ -156,17 +191,35 @@ export function registerSessionsCommand(program) {
|
|
|
156
191
|
console.error(openingMessage(session.id, kind));
|
|
157
192
|
await attachSession(conn, endpoint, ns, session, kind);
|
|
158
193
|
}));
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
194
|
+
// `status` reads the descriptor first (`/:id/metadata`, no gateway binding needed), so a native or
|
|
195
|
+
// runner session answers with its live state instead of 503 / 409; only a gateway-saved descriptor
|
|
196
|
+
// (one with a target) is then asked about its tmux runtime, and a gateway that cannot answer is
|
|
197
|
+
// reported inline rather than hiding the state the descriptor already carries.
|
|
198
|
+
gateway(common(group.command('status <id>').description('live state, run state and permission level of any saved session; the remote tmux runtime too for gateway-saved descriptors, never starting it'))).option('--json', 'print the descriptor (and runtime) as JSON').action((id, opts) => run(opts, async () => {
|
|
199
|
+
const ns = await resolveHostNamespace(opts.namespace), conn = connection();
|
|
200
|
+
const session = readSession((await requestJson(conn, sessionPath(ns, id) + '/metadata')).session);
|
|
201
|
+
let runtime = null, runtimeError = null;
|
|
202
|
+
if (session.launch !== null) {
|
|
203
|
+
try {
|
|
204
|
+
runtime = await managedOperation(conn, gatewayFor(conn.remote, opts), ns, session, 'status');
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
runtimeError = error instanceof Error ? error.message : String(error);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (opts.json)
|
|
211
|
+
return console.log(JSON.stringify({ session, runtime, ...(runtimeError ? { runtimeError } : {}) }, null, 2));
|
|
212
|
+
console.log((runtime ? runtimeSummary(session, runtime) : summary(session) + (runtimeError ? `\n Runtime: unavailable (${cell(runtimeError)})` : '')) + liveSummary(session));
|
|
213
|
+
}));
|
|
214
|
+
gateway(common(group.command('start <id>').description('start persistent tmux when available, or check readiness for direct open'))).option('--json', 'print runtime JSON; start can execute a persistent process').action((id, opts) => run(opts, async () => {
|
|
215
|
+
const ns = await resolveHostNamespace(opts.namespace), conn = connection(), endpoint = gatewayFor(conn.remote, opts);
|
|
216
|
+
const session = readSession((await requestJson(conn, sessionPath(ns, id))).session);
|
|
217
|
+
const runtime = await managedOperation(conn, endpoint, ns, session, 'start');
|
|
218
|
+
const direct = runtime.kind === 'direct' && runtime.status === 'ready';
|
|
219
|
+
console.log(opts.json ? JSON.stringify({ session, runtime, ...(direct ? { executed: false } : {}) }, null, 2) : runtimeSummary(session, runtime) + (direct ? `\nDirect connection ready; no detached process started. Use sessions open ${session.id} --namespace ${ns}. Disconnecting may end the process.` : ''));
|
|
220
|
+
if (!direct && (!['running', 'legacy'].includes(runtime.status) || !runtime.pane || runtime.pane.dead))
|
|
221
|
+
process.exitCode = 1;
|
|
222
|
+
}));
|
|
170
223
|
gateway(common(group.command('reconnect <id>').description('attach only to an existing runtime; never start or restart it'))).action((id, opts) => run(opts, async () => {
|
|
171
224
|
requireTerminal();
|
|
172
225
|
const ns = await resolveHostNamespace(opts.namespace), conn = connection(), endpoint = gatewayFor(conn.remote, opts);
|