@dreamlake/dreamlake-cli 0.97.2 → 0.99.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/client.d.ts +1 -1
- package/dist/api/client.js +4 -4
- package/dist/api/http.d.ts +48 -1
- package/dist/api/http.js +111 -4
- package/dist/api/index.d.ts +217 -511
- package/dist/api/index.js +12 -2
- package/dist/api/native-experiments.d.ts +77 -0
- package/dist/api/native-experiments.js +31 -0
- package/dist/api/note-edits.d.ts +40 -2
- package/dist/api/note-edits.js +197 -2
- package/dist/api/note-events.d.ts +40 -4
- package/dist/api/note-events.js +55 -2
- package/dist/api/note-facade.d.ts +268 -0
- package/dist/api/note-facade.js +376 -0
- package/dist/api/note-reading.d.ts +27 -0
- package/dist/api/note-reading.js +27 -0
- package/dist/api/note-write.d.ts +110 -0
- package/dist/api/note-write.js +217 -0
- package/dist/api/notes.d.ts +33 -44
- package/dist/api/notes.js +44 -34
- 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/client.d.ts +2 -41
- package/dist/cli/client.js +13 -90
- 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 +23 -6
- package/dist/cli/index.js +2 -0
- package/dist/cli/notes/api-transport.js +6 -6
- package/dist/cli/notes/document.d.ts +32 -26
- package/dist/cli/notes/document.js +150 -95
- package/dist/cli/notes/edit-commands.d.ts +26 -5
- package/dist/cli/notes/edit-commands.js +163 -36
- package/dist/cli/notes/events.d.ts +3 -33
- package/dist/cli/notes/events.js +4 -51
- package/dist/cli/notes/html-read.d.ts +6 -0
- package/dist/cli/notes/html-read.js +12 -0
- package/dist/cli/notes/index.d.ts +10 -1
- package/dist/cli/notes/index.js +98 -27
- package/dist/cli/notes/move-command.d.ts +4 -0
- package/dist/cli/notes/move-command.js +7 -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/vault/sshTransfer.d.ts +1 -1
- package/dist/cli/version.d.ts +1 -1
- package/dist/cli/version.js +1 -1
- package/package.json +9 -9
|
@@ -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);
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hook relay: the two commands a Claude Code (or Codex) hook runs to tell DreamLake what a session is
|
|
3
|
+
* doing now — `sessions heartbeat` (live state, current tool, prompt head) and `sessions event`
|
|
4
|
+
* (SubagentStart / SubagentStop). Light integration: the stock CLI runs them from `settings.json`;
|
|
5
|
+
* nothing here forks or wraps the agent. The relay is bounded (one 5 s request, inputs truncated to the
|
|
6
|
+
* server's limits), prints nothing a hook could leak (the prompt head is never written to stdout or
|
|
7
|
+
* stderr) and exits 1, never 2, so a failed relay can never block a tool call.
|
|
8
|
+
*/
|
|
9
|
+
import type { Command } from 'commander';
|
|
10
|
+
import { type HeartbeatInput, type HeartbeatResult, type LiveState, type LiveStateSource, type SessionEventInput, type SessionTree, type WatchEvent } from '../../api/index.js';
|
|
11
|
+
import type { SavedSessionRef } from '../session-affiliation.js';
|
|
12
|
+
/** The fields of a Claude Code hook's stdin JSON this relay reads. Everything else (tool input, tool
|
|
13
|
+
* response, transcript path, cwd) is ignored and never forwarded. */
|
|
14
|
+
export interface HookPayload {
|
|
15
|
+
sessionId?: string;
|
|
16
|
+
toolName?: string;
|
|
17
|
+
prompt?: string;
|
|
18
|
+
agentId?: string;
|
|
19
|
+
agentType?: string;
|
|
20
|
+
eventName?: string;
|
|
21
|
+
}
|
|
22
|
+
export declare function parseHookPayload(text: string): HookPayload;
|
|
23
|
+
/** The server's bounds, applied here so a long prompt or tool name is a truncated beat, not a 400. */
|
|
24
|
+
export declare const boundedPromptHead: (text: string) => string;
|
|
25
|
+
export declare const boundedTool: (text: string) => string;
|
|
26
|
+
export declare const boundedName: (text: string) => string;
|
|
27
|
+
/** The native session this process belongs to, as the provider itself set it: Claude Code exports
|
|
28
|
+
* `CLAUDE_CODE_SESSION_ID` to its hook and tool subprocesses, Codex `CODEX_THREAD_ID`; an explicit
|
|
29
|
+
* `CLAUDE_SESSION_ID` wins. Anything a hook payload says is data and is checked against this. */
|
|
30
|
+
export declare function nativeIdentity(env: NodeJS.ProcessEnv): string | null;
|
|
31
|
+
/** Which saved session a relay speaks for, trusted evidence first: an explicit `--session`; the native
|
|
32
|
+
* identity the provider put in this process's environment, resolved through the env file
|
|
33
|
+
* `sessions register --write-env` wrote for it; the saved-session pair a shell sourced. A `session_id` read
|
|
34
|
+
* from the hook's stdin is never a source of identity on its own: it is accepted only when it names the
|
|
35
|
+
* same native session as the environment, and refused otherwise — nothing is posted on a disagreement. */
|
|
36
|
+
export declare function resolveLiveTarget(opts: {
|
|
37
|
+
session?: string;
|
|
38
|
+
namespace?: string;
|
|
39
|
+
}, hook: HookPayload | null, env?: NodeJS.ProcessEnv, home?: string): Promise<SavedSessionRef>;
|
|
40
|
+
/** `runnerId` decides the source on the server; `--source` may only agree. */
|
|
41
|
+
export declare function sourceFields(opts: {
|
|
42
|
+
source?: string;
|
|
43
|
+
runner?: string;
|
|
44
|
+
}): {
|
|
45
|
+
source?: LiveStateSource;
|
|
46
|
+
runnerId?: string;
|
|
47
|
+
};
|
|
48
|
+
export declare function heartbeatBody(opts: {
|
|
49
|
+
state: string;
|
|
50
|
+
tool?: string;
|
|
51
|
+
promptHead?: string;
|
|
52
|
+
at?: string;
|
|
53
|
+
source?: string;
|
|
54
|
+
runner?: string;
|
|
55
|
+
}, hook: HookPayload | null): HeartbeatInput;
|
|
56
|
+
export declare function eventBody(opts: {
|
|
57
|
+
kind: string;
|
|
58
|
+
subagent?: string;
|
|
59
|
+
name?: string;
|
|
60
|
+
finished?: string | boolean;
|
|
61
|
+
tokens?: string;
|
|
62
|
+
at?: string;
|
|
63
|
+
source?: string;
|
|
64
|
+
runner?: string;
|
|
65
|
+
}, hook: HookPayload | null): SessionEventInput;
|
|
66
|
+
/** What the relay prints: the receipt without the prompt head. The head is the one field a hook could
|
|
67
|
+
* leak into a transcript or a log, so it never leaves this process again. */
|
|
68
|
+
export declare const printableHeartbeat: (result: HeartbeatResult) => {
|
|
69
|
+
current: {
|
|
70
|
+
promptHeadChars?: number | undefined;
|
|
71
|
+
tool?: string | undefined;
|
|
72
|
+
} | null;
|
|
73
|
+
accepted: boolean;
|
|
74
|
+
liveState: LiveState;
|
|
75
|
+
liveStateReported: LiveState;
|
|
76
|
+
liveStateAt: string;
|
|
77
|
+
liveStateReceivedAt: string;
|
|
78
|
+
liveStateSource: LiveStateSource;
|
|
79
|
+
};
|
|
80
|
+
/** One line per node, children indented; a session shows its live state, level, isolation and runner, a
|
|
81
|
+
* subagent its state, tokens and last event. Control characters never reach the terminal. */
|
|
82
|
+
export declare function renderTree(tree: SessionTree): string;
|
|
83
|
+
/** One readable line per watch frame; `null` for frames that carry nothing to say. */
|
|
84
|
+
export declare function renderWatchEvent(event: WatchEvent): string | null;
|
|
85
|
+
export declare function registerSessionLive(group: Command): void;
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { resolveHostNamespace } from '../hosts/inventory.js';
|
|
2
|
+
import { resolveRemote, resolveToken } from '../config.js';
|
|
3
|
+
import { ApiError, createClient, isObjectId, LIVE_LIMITS, LIVE_STATES } from '../../api/index.js';
|
|
4
|
+
import { readSessionEnvFile, sessionEnvFilePath } from './affiliation.js';
|
|
5
|
+
const SUBAGENT_ID = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
6
|
+
const EVENT_KINDS = ['SubagentStart', 'SubagentStop'];
|
|
7
|
+
const control = (value) => value.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ');
|
|
8
|
+
export function parseHookPayload(text) {
|
|
9
|
+
if (text.length > 1_048_576)
|
|
10
|
+
throw new Error('Hook payload exceeds 1 MiB');
|
|
11
|
+
let value;
|
|
12
|
+
try {
|
|
13
|
+
value = JSON.parse(text);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
throw new Error('Hook payload is not JSON');
|
|
17
|
+
}
|
|
18
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
19
|
+
throw new Error('Hook payload is not an object');
|
|
20
|
+
const o = value, str = (key) => typeof o[key] === 'string' ? o[key] : undefined;
|
|
21
|
+
const sessionId = str('session_id');
|
|
22
|
+
return {
|
|
23
|
+
...(sessionId && /^[a-f0-9-]{36}$/i.test(sessionId) ? { sessionId: sessionId.toLowerCase() } : {}),
|
|
24
|
+
...(str('tool_name') ? { toolName: str('tool_name') } : {}),
|
|
25
|
+
...(str('prompt') ? { prompt: str('prompt') } : {}),
|
|
26
|
+
...(str('agent_id') ? { agentId: str('agent_id') } : {}),
|
|
27
|
+
...(str('agent_type') ? { agentType: str('agent_type') } : {}),
|
|
28
|
+
...(str('hook_event_name') ? { eventName: str('hook_event_name') } : {}),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
async function readStdin() {
|
|
32
|
+
if (process.stdin.isTTY)
|
|
33
|
+
throw new Error('--hook-stdin reads the hook JSON from stdin; run this from a hook, or pass --session and the fields explicitly');
|
|
34
|
+
let text = '';
|
|
35
|
+
for await (const chunk of process.stdin) {
|
|
36
|
+
text += chunk;
|
|
37
|
+
if (text.length > 1_048_576)
|
|
38
|
+
throw new Error('Hook payload exceeds 1 MiB');
|
|
39
|
+
}
|
|
40
|
+
return text;
|
|
41
|
+
}
|
|
42
|
+
/** The server's bounds, applied here so a long prompt or tool name is a truncated beat, not a 400. */
|
|
43
|
+
export const boundedPromptHead = (text) => text.replace(/\s+/g, ' ').trim().slice(0, LIVE_LIMITS.promptHead);
|
|
44
|
+
export const boundedTool = (text) => control(text).trim().slice(0, LIVE_LIMITS.tool);
|
|
45
|
+
export const boundedName = (text) => control(text).trim().slice(0, LIVE_LIMITS.name);
|
|
46
|
+
/** The native session this process belongs to, as the provider itself set it: Claude Code exports
|
|
47
|
+
* `CLAUDE_CODE_SESSION_ID` to its hook and tool subprocesses, Codex `CODEX_THREAD_ID`; an explicit
|
|
48
|
+
* `CLAUDE_SESSION_ID` wins. Anything a hook payload says is data and is checked against this. */
|
|
49
|
+
export function nativeIdentity(env) {
|
|
50
|
+
const value = env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || env.CODEX_THREAD_ID;
|
|
51
|
+
return value && /^[a-f0-9-]{36}$/i.test(value) ? value.toLowerCase() : null;
|
|
52
|
+
}
|
|
53
|
+
/** Which saved session a relay speaks for, trusted evidence first: an explicit `--session`; the native
|
|
54
|
+
* identity the provider put in this process's environment, resolved through the env file
|
|
55
|
+
* `sessions register --write-env` wrote for it; the saved-session pair a shell sourced. A `session_id` read
|
|
56
|
+
* from the hook's stdin is never a source of identity on its own: it is accepted only when it names the
|
|
57
|
+
* same native session as the environment, and refused otherwise — nothing is posted on a disagreement. */
|
|
58
|
+
export async function resolveLiveTarget(opts, hook, env = process.env, home) {
|
|
59
|
+
if (opts.session) {
|
|
60
|
+
if (!isObjectId(opts.session))
|
|
61
|
+
throw new Error('--session takes the 24-hex saved session id (sessions list), not the native UUID');
|
|
62
|
+
return { id: opts.session, namespace: await resolveHostNamespace(opts.namespace) };
|
|
63
|
+
}
|
|
64
|
+
const native = nativeIdentity(env);
|
|
65
|
+
if (hook?.sessionId) {
|
|
66
|
+
if (!native)
|
|
67
|
+
throw new Error(`The hook payload names native session ${hook.sessionId}, but this process carries no native identity (CLAUDE_CODE_SESSION_ID) to check it against; nothing was sent. Run this from a Claude Code hook, or pass --session <id>.`);
|
|
68
|
+
if (hook.sessionId !== native)
|
|
69
|
+
throw new Error(`The hook payload names native session ${hook.sessionId}, but this process belongs to ${native}; nothing was sent.`);
|
|
70
|
+
}
|
|
71
|
+
const withNamespace = async (ref) => opts.namespace ? { id: ref.id, namespace: await resolveHostNamespace(opts.namespace) } : ref;
|
|
72
|
+
if (native) {
|
|
73
|
+
const fromFile = readSessionEnvFile(sessionEnvFilePath(native, home));
|
|
74
|
+
if (fromFile)
|
|
75
|
+
return withNamespace(fromFile);
|
|
76
|
+
throw new Error(`No saved session for native session ${native}: register it first (dreamlake sessions register --provider ${env.CODEX_THREAD_ID && !env.CLAUDE_SESSION_ID && !env.CLAUDE_CODE_SESSION_ID ? 'codex' : 'claude'} --session ${native} --cwd "$PWD" --write-env "${sessionEnvFilePath(native, home)}") or pass --session <id>`);
|
|
77
|
+
}
|
|
78
|
+
const id = env.DREAMLAKE_TERMINAL_SESSION_ID, ns = env.DREAMLAKE_SESSION_NAMESPACE;
|
|
79
|
+
if (id && isObjectId(id) && ns && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(ns))
|
|
80
|
+
return withNamespace({ id, namespace: ns });
|
|
81
|
+
throw new Error('No saved session: pass --session <24-hex id>, run from a Claude Code hook after `sessions register --write-env`, or source the session env file');
|
|
82
|
+
}
|
|
83
|
+
/** `runnerId` decides the source on the server; `--source` may only agree. */
|
|
84
|
+
export function sourceFields(opts) {
|
|
85
|
+
if (opts.source !== undefined && !['hook', 'runner'].includes(opts.source))
|
|
86
|
+
throw new Error('--source must be hook or runner');
|
|
87
|
+
if (opts.runner !== undefined && !isObjectId(opts.runner))
|
|
88
|
+
throw new Error('--runner takes the 24-hex runner id (sessions runners)');
|
|
89
|
+
if (opts.source === 'runner' && !opts.runner)
|
|
90
|
+
throw new Error('--source runner needs --runner <id>: the server attributes a beat to the runner that names itself');
|
|
91
|
+
if (opts.source === 'hook' && opts.runner)
|
|
92
|
+
throw new Error('--source hook cannot name a runner');
|
|
93
|
+
return { ...(opts.source ? { source: opts.source } : {}), ...(opts.runner ? { runnerId: opts.runner } : {}) };
|
|
94
|
+
}
|
|
95
|
+
const at = (value) => { if (value === undefined)
|
|
96
|
+
return new Date().toISOString(); const ms = Date.parse(String(value)); if (!Number.isFinite(ms))
|
|
97
|
+
throw new Error('--at / --finished must be an ISO-8601 time'); return new Date(ms).toISOString(); };
|
|
98
|
+
export function heartbeatBody(opts, hook) {
|
|
99
|
+
if (!LIVE_STATES.includes(opts.state))
|
|
100
|
+
throw new Error(`--state must be one of ${LIVE_STATES.join(', ')}`);
|
|
101
|
+
const tool = opts.tool ?? hook?.toolName, prompt = opts.promptHead ?? hook?.prompt;
|
|
102
|
+
const current = { ...(tool && boundedTool(tool) ? { tool: boundedTool(tool) } : {}), ...(prompt && boundedPromptHead(prompt) ? { promptHead: boundedPromptHead(prompt) } : {}) };
|
|
103
|
+
return { liveState: opts.state, ...(Object.keys(current).length ? { current } : {}), at: at(opts.at), ...sourceFields(opts) };
|
|
104
|
+
}
|
|
105
|
+
export function eventBody(opts, hook) {
|
|
106
|
+
if (!EVENT_KINDS.includes(opts.kind))
|
|
107
|
+
throw new Error('--kind must be SubagentStart or SubagentStop');
|
|
108
|
+
const subagentId = opts.subagent ?? hook?.agentId;
|
|
109
|
+
if (!subagentId || !SUBAGENT_ID.test(subagentId))
|
|
110
|
+
throw new Error('--subagent <id> is required (1–128 of A-Z a-z 0-9 . _ : -); a hook supplies it as agent_id');
|
|
111
|
+
const name = opts.name ?? hook?.agentType;
|
|
112
|
+
const when = at(opts.at);
|
|
113
|
+
let tokens;
|
|
114
|
+
if (opts.tokens !== undefined) {
|
|
115
|
+
if (!/^\d{1,10}$/.test(opts.tokens) || Number(opts.tokens) > 2147483647)
|
|
116
|
+
throw new Error('--tokens must be an integer total, 0–2147483647');
|
|
117
|
+
tokens = Number(opts.tokens);
|
|
118
|
+
}
|
|
119
|
+
if (opts.finished !== undefined && opts.kind !== 'SubagentStop')
|
|
120
|
+
throw new Error('--finished belongs to SubagentStop');
|
|
121
|
+
return { kind: opts.kind, subagentId, ...(name && boundedName(name) ? { name: boundedName(name) } : {}), at: when,
|
|
122
|
+
...(opts.finished !== undefined ? { finished: opts.finished === true ? when : at(opts.finished) } : {}), ...(tokens !== undefined ? { tokens } : {}), ...sourceFields(opts) };
|
|
123
|
+
}
|
|
124
|
+
/** What the relay prints: the receipt without the prompt head. The head is the one field a hook could
|
|
125
|
+
* leak into a transcript or a log, so it never leaves this process again. */
|
|
126
|
+
export const printableHeartbeat = (result) => ({ ...result, current: result.current ? { ...(result.current.tool ? { tool: result.current.tool } : {}), ...(result.current.promptHead ? { promptHeadChars: result.current.promptHead.length } : {}) } : null });
|
|
127
|
+
/** One line per node, children indented; a session shows its live state, level, isolation and runner, a
|
|
128
|
+
* subagent its state, tokens and last event. Control characters never reach the terminal. */
|
|
129
|
+
export function renderTree(tree) {
|
|
130
|
+
const lines = [];
|
|
131
|
+
const session = (n, depth) => {
|
|
132
|
+
const where = n.isolation ? `${n.isolation.kind}${n.isolation.branch ? ` ${n.isolation.branch}` : ''}` : n.pod ? 'pod' : n.cwd;
|
|
133
|
+
lines.push(`${' '.repeat(depth)}${n.id} ${control(n.name)} ${n.provider} ${n.liveState ?? 'no live state'}${n.current?.tool ? ` (${control(n.current.tool)})` : ''} ${n.permissionLevel ?? 'no level'} ${control(where)}${n.runnerId ? ` runner ${n.runnerId}` : ''}${n.finishedAt ? ` finished ${n.finishedAt}` : ''}`);
|
|
134
|
+
for (const child of n.children)
|
|
135
|
+
child.kind === 'session' ? session(child, depth + 1) : subagent(child, depth + 1);
|
|
136
|
+
};
|
|
137
|
+
const subagent = (n, depth) => lines.push(`${' '.repeat(depth)}↳ ${control(n.id)}${n.name ? ` (${control(n.name)})` : ''} ${n.liveState}${n.tokens !== null ? ` tokens ${n.tokens}` : ''} ${n.lastEvent} ${n.lastEventAt}${n.finishedAt ? ` finished ${n.finishedAt}` : ''}`);
|
|
138
|
+
session(tree.session, 0);
|
|
139
|
+
lines.push(`${tree.nodeCount} session${tree.nodeCount === 1 ? '' : 's'}, ${tree.subagentCount} subagent${tree.subagentCount === 1 ? '' : 's'}${tree.truncated ? '; truncated (depth 3, 200 nodes, 500 subagents)' : ''}${tree.cycleDetected ? '; a parent link loops and was cut' : ''}`);
|
|
140
|
+
return lines.join('\n');
|
|
141
|
+
}
|
|
142
|
+
/** One readable line per watch frame; `null` for frames that carry nothing to say. */
|
|
143
|
+
export function renderWatchEvent(event) {
|
|
144
|
+
const at = (value) => control(value).replace(/\.\d{3}Z$/, 'Z');
|
|
145
|
+
switch (event.type) {
|
|
146
|
+
case 'ready': return `watching ${event.sessionId ?? 'all your sessions'} from ${at(event.at)} (live only, no catch-up; the server ends the stream after ${Math.round(event.timeoutMs / 60000)} min)`;
|
|
147
|
+
case 'liveState':
|
|
148
|
+
case 'heartbeat': return `${at(event.at)} ${event.sessionId} ${control(event.liveState)}${event.liveState !== event.liveStateReported ? ` (reported ${control(event.liveStateReported)})` : ''} via ${control(event.liveStateSource)}${event.current?.tool ? ` ${control(event.current.tool)}` : ''}${event.current?.promptHead ? ` “${control(event.current.promptHead)}”` : ''}`;
|
|
149
|
+
case 'subagent': {
|
|
150
|
+
const s = event.subagent;
|
|
151
|
+
return `${at(event.at)} ${event.sessionId} subagent ${control(s.id)}${s.name ? ` (${control(s.name)})` : ''} ${control(s.lastEvent)} → ${control(s.liveState)}${s.tokens !== null ? ` tokens ${s.tokens}` : ''}`;
|
|
152
|
+
}
|
|
153
|
+
case 'receipt': {
|
|
154
|
+
const c = event.command, r = (c.result ?? {});
|
|
155
|
+
return `${at(event.at)} ${event.sessionId} ${control(c.kind)} ${control(c.status)}${c.error ? ` ${control(String(c.error))}` : ''}${typeof r.permissionLevel === 'string' ? ` ${control(r.permissionLevel)}` : ''}${Array.isArray(r.argv) ? ` argv: ${control(r.argv.map(String).join(' '))}` : ''}`;
|
|
156
|
+
}
|
|
157
|
+
case 'permission': return `${at(event.at)} ${event.sessionId} permission → ${control(event.permissionLevel)} (${control(event.entry?.origin ?? 'unknown')}${event.entry?.reason ? `: ${control(event.entry.reason)}` : ''})`;
|
|
158
|
+
case 'end': return `stream ended (${control(event.reason)}); re-read sessions list and sessions tree before watching again`;
|
|
159
|
+
case 'error': return `stream error: ${control(event.error)}`;
|
|
160
|
+
default: return null;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function client() {
|
|
164
|
+
const token = resolveToken();
|
|
165
|
+
if (!token)
|
|
166
|
+
throw new Error('Log in to DreamLake before relaying session state');
|
|
167
|
+
return createClient({ remote: resolveRemote(), token });
|
|
168
|
+
}
|
|
169
|
+
export function registerSessionLive(group) {
|
|
170
|
+
const guard = async (opts, work) => {
|
|
171
|
+
try {
|
|
172
|
+
await work();
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
const message = error instanceof ApiError ? `(${error.status}) ${error.code}` : error instanceof Error ? error.message : 'Session relay failed';
|
|
176
|
+
if (opts.json)
|
|
177
|
+
console.log(JSON.stringify({ status: 'error', error: message }));
|
|
178
|
+
else
|
|
179
|
+
console.error(message);
|
|
180
|
+
process.exitCode = 1;
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
const common = (c) => c.option('--session <id>', 'saved 24-hex session id (default: the env file sessions register --write-env left for the native session this process belongs to (CLAUDE_CODE_SESSION_ID), else the sourced DREAMLAKE_TERMINAL_SESSION_ID pair)')
|
|
184
|
+
.option('--namespace <namespace>', 'personal namespace (default: from the env file or the signed-in personal namespace)')
|
|
185
|
+
.option('--hook-stdin', 'read a Claude Code hook JSON from stdin: tool_name / prompt / agent_id / agent_type fill the fields not given explicitly; its session_id must match the native identity in the environment')
|
|
186
|
+
.option('--at <iso>', 'when it happened (default: now)').option('--source <source>', 'hook (default) or runner; runner needs --runner').option('--runner <id>', 'report as this runner (the session must be bound to it)').option('--json', 'emit the receipt as JSON');
|
|
187
|
+
common(group.command('heartbeat').description('relay what a session is doing now (hook target): live state, current tool and prompt head; the prompt head is never printed'))
|
|
188
|
+
.requiredOption('--state <liveState>', LIVE_STATES.join(' | ')).option('--tool <name>', `current tool (truncated to ${LIVE_LIMITS.tool})`).option('--prompt-head <text>', `start of the prompt (truncated to ${LIVE_LIMITS.promptHead}, redacted by the server, owner-only)`)
|
|
189
|
+
.action(opts => guard(opts, async () => {
|
|
190
|
+
const hook = opts.hookStdin ? parseHookPayload(await readStdin()) : null;
|
|
191
|
+
const body = heartbeatBody(opts, hook), target = await resolveLiveTarget(opts, hook);
|
|
192
|
+
const result = await client().sessions(target.namespace).heartbeat(target.id, body);
|
|
193
|
+
if (opts.json)
|
|
194
|
+
return console.log(JSON.stringify({ sessionId: target.id, namespace: target.namespace, ...printableHeartbeat(result) }, null, 2));
|
|
195
|
+
console.log(`${target.id} ${control(result.liveState)}${result.liveState !== result.liveStateReported ? ` (reported ${control(result.liveStateReported)})` : ''} via ${control(result.liveStateSource)}${result.accepted ? '' : ' not written: older than the recorded beat'}`);
|
|
196
|
+
}));
|
|
197
|
+
common(group.command('event').description('relay a native subagent start or stop (hook target); one child row per session and subagent id'))
|
|
198
|
+
.requiredOption('--kind <kind>', 'SubagentStart or SubagentStop').option('--subagent <id>', 'subagent id (a hook supplies agent_id)').option('--name <name>', 'subagent name or type (a hook supplies agent_type)')
|
|
199
|
+
.option('--finished [iso]', 'SubagentStop: when it finished (default: --at)').option('--tokens <n>', 'token total so far')
|
|
200
|
+
.action(opts => guard(opts, async () => {
|
|
201
|
+
const hook = opts.hookStdin ? parseHookPayload(await readStdin()) : null;
|
|
202
|
+
const body = eventBody(opts, hook), target = await resolveLiveTarget(opts, hook);
|
|
203
|
+
const result = await client().sessions(target.namespace).event(target.id, body);
|
|
204
|
+
if (opts.json)
|
|
205
|
+
return console.log(JSON.stringify({ namespace: target.namespace, ...result }, null, 2));
|
|
206
|
+
const s = result.subagent;
|
|
207
|
+
console.log(`${result.sessionId} ${control(s.lastEvent)} ${control(s.id)}${s.name ? ` (${control(s.name)})` : ''} ${control(s.liveState)}${s.tokens !== null ? ` tokens ${s.tokens}` : ''}`);
|
|
208
|
+
}));
|
|
209
|
+
group.command('tree <id>').description('the session with its managed children and native subagents: live state, permission level, isolation, runner, tokens and finish time per node')
|
|
210
|
+
.option('--namespace <namespace>', 'personal namespace (default: signed-in personal namespace)').option('--json', 'emit the tree as JSON')
|
|
211
|
+
.action((id, opts) => guard(opts, async () => {
|
|
212
|
+
if (!isObjectId(id))
|
|
213
|
+
throw new Error('Use the 24-hex session id from sessions list');
|
|
214
|
+
const ns = await resolveHostNamespace(opts.namespace), tree = await client().sessions(ns).tree(id);
|
|
215
|
+
console.log(opts.json ? JSON.stringify({ namespace: ns, ...tree }, null, 2) : renderTree(tree));
|
|
216
|
+
}));
|
|
217
|
+
group.command('watch').description('follow live state, subagent events, receipts and permission changes as they happen (SSE); one session or all of yours; exits 0 when the server ends the stream after 15 minutes')
|
|
218
|
+
.option('--session <id>', 'one saved session (default: every session of the namespace)').option('--namespace <namespace>', 'personal namespace (default: signed-in personal namespace)').option('--json', 'NDJSON: one typed frame per line')
|
|
219
|
+
.action(opts => guard(opts, async () => {
|
|
220
|
+
if (opts.session !== undefined && !isObjectId(opts.session))
|
|
221
|
+
throw new Error('--session takes the 24-hex saved session id');
|
|
222
|
+
const ns = await resolveHostNamespace(opts.namespace), abort = new AbortController();
|
|
223
|
+
const stop = () => abort.abort();
|
|
224
|
+
process.once('SIGINT', stop);
|
|
225
|
+
process.once('SIGTERM', stop);
|
|
226
|
+
let ended = false;
|
|
227
|
+
try {
|
|
228
|
+
for await (const event of client().sessions(ns).watch(opts.session ? { sessionId: opts.session } : {}, abort.signal)) {
|
|
229
|
+
if (opts.json)
|
|
230
|
+
console.log(JSON.stringify(event));
|
|
231
|
+
else {
|
|
232
|
+
const line = renderWatchEvent(event);
|
|
233
|
+
if (line)
|
|
234
|
+
console.log(line);
|
|
235
|
+
}
|
|
236
|
+
if (event.type === 'end')
|
|
237
|
+
ended = true;
|
|
238
|
+
if (event.type === 'error') {
|
|
239
|
+
ended = true;
|
|
240
|
+
process.exitCode = 1;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
if (!abort.signal.aborted)
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
finally {
|
|
249
|
+
process.off('SIGINT', stop);
|
|
250
|
+
process.off('SIGTERM', stop);
|
|
251
|
+
}
|
|
252
|
+
// A stream that closed without `end` (network, server restart) is not the clean 15-minute timeout.
|
|
253
|
+
if (!ended && !abort.signal.aborted) {
|
|
254
|
+
console.error('stream closed without an end frame; re-read sessions list and sessions tree before watching again');
|
|
255
|
+
process.exitCode = 1;
|
|
256
|
+
}
|
|
257
|
+
}));
|
|
258
|
+
}
|