@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,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
|
+
}
|
|
@@ -19,23 +19,37 @@ export interface RunOptions {
|
|
|
19
19
|
export type Run = (command: string, args: string[], options?: RunOptions) => Promise<RunResult>;
|
|
20
20
|
/** Default process runner: own process group, bounded output and time, killable through `signal`. */
|
|
21
21
|
export declare const run: Run;
|
|
22
|
+
/** `checkpoint` is what is known about a side effect; `detail` is why it failed (exit code, signal, bounded
|
|
23
|
+
* and redacted output tails), so a receipt carries the underlying error text and not only a code. */
|
|
22
24
|
export declare class RunnerError extends Error {
|
|
23
25
|
readonly code: string;
|
|
24
26
|
readonly uncertain: boolean;
|
|
25
27
|
readonly checkpoint: Record<string, unknown>;
|
|
26
|
-
|
|
28
|
+
readonly detail: Record<string, unknown>;
|
|
29
|
+
constructor(code: string, message?: string, uncertain?: boolean, checkpoint?: Record<string, unknown>, detail?: Record<string, unknown>);
|
|
27
30
|
}
|
|
28
31
|
export type PermissionLevel = 'read-only' | 'workspace-write' | 'full-access';
|
|
29
32
|
export declare function hasTmux(exec: Run): Promise<boolean>;
|
|
30
33
|
export declare function tmuxAlive(exec: Run, name: string): Promise<boolean>;
|
|
31
34
|
/** The owner marker is written by this runner at creation; a session with another or no marker is not ours to type into or kill. */
|
|
32
35
|
export declare const ownerMarker: (runnerKey: string, nativeSessionId: string) => string;
|
|
33
|
-
|
|
36
|
+
/** `policy` records the permission level the process was launched under (`@dreamlake_policy`), so a later
|
|
37
|
+
* resume or send can tell whether the live process still matches the authorized level. */
|
|
38
|
+
export declare function markOwnership(exec: Run, name: string, marker: string, policy?: PermissionLevel): Promise<void>;
|
|
39
|
+
/** The level an owned tmux session's process was launched under, or `null` when it was not recorded (a
|
|
40
|
+
* session launched by an older runner) — which is not proof of anything, and is treated as such. */
|
|
41
|
+
export declare function livePolicy(exec: Run, name: string): Promise<PermissionLevel | null>;
|
|
42
|
+
/** Refuses to type into a live process whose launch level is not the authorized one. Equal: proceed.
|
|
43
|
+
* Different: the caller relaunches at the authorized level. Unknown: refused, a restart is the way out. */
|
|
44
|
+
export declare function assertLivePolicy(live: PermissionLevel | null, authorized: PermissionLevel): 'matches' | 'relaunch';
|
|
34
45
|
export declare function verifyOwnership(exec: Run, name: string, marker: string): Promise<'absent' | 'owned' | 'foreign'>;
|
|
35
46
|
/** One message, pasted whole (bracketed) and submitted once; every step's exit code counts. */
|
|
36
47
|
export declare function tmuxSend(exec: Run, name: string, marker: string, text: string, signal?: AbortSignal): Promise<void>;
|
|
37
48
|
export declare function tmuxStop(exec: Run, name: string, marker: string): Promise<boolean>;
|
|
38
|
-
/** A fresh worktree next to the user's other DreamLake worktrees, never inside the source checkout.
|
|
49
|
+
/** A fresh worktree next to the user's other DreamLake worktrees, never inside the source checkout.
|
|
50
|
+
* `prepared` receives the record (path, branch, whether the branch is new, its starting tip) just before
|
|
51
|
+
* `git worktree add`: an add that is cancelled or times out may already have registered the worktree and
|
|
52
|
+
* created the branch, and that record is what lets the caller reconcile such a partial creation. */
|
|
39
53
|
export declare function createWorktree(exec: Run, input: {
|
|
40
54
|
repo: string;
|
|
41
55
|
branch?: string;
|
|
@@ -43,11 +57,45 @@ export declare function createWorktree(exec: Run, input: {
|
|
|
43
57
|
home: string;
|
|
44
58
|
signal?: AbortSignal;
|
|
45
59
|
checkpoint?: (value: Record<string, unknown>) => void;
|
|
60
|
+
prepared?: (record: Worktree) => void;
|
|
46
61
|
}): Promise<{
|
|
62
|
+
gitDir: string | null;
|
|
63
|
+
branchOid: string | null;
|
|
47
64
|
path: string;
|
|
48
65
|
branch: string;
|
|
49
66
|
root: string;
|
|
67
|
+
createdBranch: boolean;
|
|
68
|
+
identity: string;
|
|
50
69
|
}>;
|
|
70
|
+
/** A worktree this runner created, with what cleanup needs to recognise it later: `identity` is the nonce
|
|
71
|
+
* of this creation, written to `<gitDir>/dreamlake-session` once `git worktree add` returned; `gitDir` the
|
|
72
|
+
* admin directory git assigned (the `gitdir:` pointer in `<path>/.git`); `branchOid` where the branch
|
|
73
|
+
* pointed when the start began. */
|
|
74
|
+
export interface Worktree {
|
|
75
|
+
path: string;
|
|
76
|
+
branch: string;
|
|
77
|
+
root: string;
|
|
78
|
+
createdBranch: boolean;
|
|
79
|
+
gitDir: string | null;
|
|
80
|
+
branchOid: string | null;
|
|
81
|
+
identity: string;
|
|
82
|
+
}
|
|
83
|
+
export interface WorktreeTeardown {
|
|
84
|
+
removed: boolean;
|
|
85
|
+
branchDeleted: boolean;
|
|
86
|
+
reason?: string;
|
|
87
|
+
}
|
|
88
|
+
/** The identity of the creation that made the worktree at `path`, or null when it carries none. */
|
|
89
|
+
export declare function worktreeIdentity(path: string): string | null;
|
|
90
|
+
/** Remove a worktree this runner created for a start that never became a session, and the branch it
|
|
91
|
+
* created for it. Nothing is destroyed unless it is still exactly what this start made: the worktree at
|
|
92
|
+
* the path must carry this creation's identity file (a replacement, a re-creation at the same path or a
|
|
93
|
+
* worktree whose creation never completed does not, and is kept as `identity_missing`), be checked out
|
|
94
|
+
* on the branch, and the branch must still point at its initial tip (a provider that committed and then
|
|
95
|
+
* failed has made the branch worth keeping). Removal is never `--force` (edits keep it); the branch is
|
|
96
|
+
* deleted with `update-ref -d <old>`, which refuses a branch that moved, and never while any worktree
|
|
97
|
+
* has it checked out. A kept worktree or branch is reported with the reason. */
|
|
98
|
+
export declare function removeWorktree(exec: Run, where: Worktree): Promise<WorktreeTeardown>;
|
|
51
99
|
export interface Launch {
|
|
52
100
|
provider: Provider;
|
|
53
101
|
cwd: string;
|
|
@@ -55,21 +103,62 @@ export interface Launch {
|
|
|
55
103
|
prompt?: string;
|
|
56
104
|
nativeSessionId?: string;
|
|
57
105
|
claudeConfigDir?: string | null;
|
|
106
|
+
defaultClaudeConfigDir?: string;
|
|
58
107
|
codexRoot: string;
|
|
59
108
|
signal?: AbortSignal;
|
|
60
109
|
checkpoint?: (value: Record<string, unknown>) => void;
|
|
61
110
|
}
|
|
111
|
+
export type ClaudeConfigReason = 'inherited' | 'default_config_dir' | 'profile_missing' | 'profile_not_owned' | 'profile_logged_out' | 'exported';
|
|
112
|
+
/** What the runner did with a session's recorded `claudeConfigDir`; reported in every receipt of a Claude turn. */
|
|
113
|
+
export interface ClaudeConfigDecision {
|
|
114
|
+
dir: string | null;
|
|
115
|
+
exported: boolean;
|
|
116
|
+
reason: ClaudeConfigReason;
|
|
117
|
+
}
|
|
118
|
+
/** Whose profile directories the runner may export: those owned by this Unix user (by uid), or inside this user's home. */
|
|
119
|
+
export interface ProfileOwner {
|
|
120
|
+
home: string;
|
|
121
|
+
uid: number | null;
|
|
122
|
+
}
|
|
123
|
+
export declare const currentProfileOwner: () => ProfileOwner;
|
|
124
|
+
/** Claude Code keeps its login in `<config dir>/.claude.json`, and the default profile is `~/.claude.json`,
|
|
125
|
+
* not `~/.claude/.claude.json`. Exporting `CLAUDE_CONFIG_DIR=~/.claude` (what Nymph records for a default
|
|
126
|
+
* session) therefore makes Claude create an empty, logged-out profile and answer "Not logged in". The
|
|
127
|
+
* variable is exported only for a non-default directory that holds a logged-in profile; otherwise the
|
|
128
|
+
* process inherits the runner's own environment, which is how the user runs Claude.
|
|
129
|
+
*
|
|
130
|
+
* A session descriptor can name any readable path, so the directory is accepted only when it is this
|
|
131
|
+
* user's own — owned by the current uid, or inside the current home — and that is decided on the resolved
|
|
132
|
+
* path (symlinks followed first, so a link inside this home to a directory elsewhere is judged by where
|
|
133
|
+
* it points) before its profile is read; another Unix user's profile is not this user's login. A login
|
|
134
|
+
* means a non-empty `oauthAccount` object or a non-empty `primaryApiKey`; `{ "oauthAccount": {} }` is
|
|
135
|
+
* logged out. */
|
|
136
|
+
export declare function claudeConfigDecision(requested: string | null | undefined, defaultDir: string, owner?: ProfileOwner): ClaudeConfigDecision;
|
|
137
|
+
/** The exact command line of a headless turn (`claude -p` / `codex exec`); echoed in every receipt so the
|
|
138
|
+
* permission mode a process actually ran under is readable next to the level that was authorized. */
|
|
139
|
+
export declare function headlessArgv(input: {
|
|
140
|
+
provider: Provider;
|
|
141
|
+
nativeSessionId?: string;
|
|
142
|
+
permissionLevel: PermissionLevel;
|
|
143
|
+
resume: boolean;
|
|
144
|
+
cwd?: string;
|
|
145
|
+
}): string[];
|
|
62
146
|
/** Headless: one provider turn that creates the session; the prompt travels on stdin. */
|
|
63
147
|
export declare function startHeadless(exec: Run, launch: Launch): Promise<{
|
|
64
148
|
nativeSessionId: string;
|
|
65
149
|
reply: string | null;
|
|
150
|
+
argv: string[];
|
|
151
|
+
claudeConfig?: ClaudeConfigDecision;
|
|
66
152
|
}>;
|
|
67
|
-
/** Interactive: a detached, owner-marked tmux session. Prompts sit behind `--`.
|
|
153
|
+
/** Interactive: a detached, owner-marked tmux session. Prompts sit behind `--`. `argv` is the program the
|
|
154
|
+
* tmux session runs (with an `env CLAUDE_CONFIG_DIR=…` prefix when one was exported). */
|
|
68
155
|
export declare function startTmux(exec: Run, launch: Launch & {
|
|
69
156
|
marker: (nativeSessionId: string) => string;
|
|
70
157
|
}): Promise<{
|
|
71
158
|
nativeSessionId: string;
|
|
72
159
|
tmuxSession: string;
|
|
160
|
+
argv: string[];
|
|
161
|
+
claudeConfig?: ClaudeConfigDecision;
|
|
73
162
|
}>;
|
|
74
163
|
export interface Resume {
|
|
75
164
|
provider: Provider;
|
|
@@ -77,6 +166,7 @@ export interface Resume {
|
|
|
77
166
|
nativeSessionId: string;
|
|
78
167
|
permissionLevel: PermissionLevel;
|
|
79
168
|
claudeConfigDir?: string | null;
|
|
169
|
+
defaultClaudeConfigDir?: string;
|
|
80
170
|
prompt?: string;
|
|
81
171
|
marker: string;
|
|
82
172
|
signal?: AbortSignal;
|
|
@@ -88,6 +178,17 @@ export declare function resumeTmux(exec: Run, input: Resume): Promise<{
|
|
|
88
178
|
tmuxSession: string;
|
|
89
179
|
created: boolean;
|
|
90
180
|
delivered: boolean;
|
|
181
|
+
argv: string[] | null;
|
|
182
|
+
processLevel: PermissionLevel | null;
|
|
183
|
+
} | {
|
|
184
|
+
claudeConfig?: ClaudeConfigDecision | undefined;
|
|
185
|
+
relaunched?: true | undefined;
|
|
186
|
+
previousProcessLevel?: PermissionLevel | undefined;
|
|
187
|
+
tmuxSession: string;
|
|
188
|
+
created: boolean;
|
|
189
|
+
delivered: boolean;
|
|
190
|
+
argv: string[] | null;
|
|
191
|
+
processLevel: PermissionLevel;
|
|
91
192
|
}>;
|
|
92
193
|
/** Headless message: one resumed turn under the session's permission ceiling; the text travels on stdin. */
|
|
93
194
|
export declare function sendHeadless(exec: Run, input: {
|
|
@@ -96,13 +197,24 @@ export declare function sendHeadless(exec: Run, input: {
|
|
|
96
197
|
nativeSessionId: string;
|
|
97
198
|
permissionLevel: PermissionLevel;
|
|
98
199
|
claudeConfigDir?: string | null;
|
|
200
|
+
defaultClaudeConfigDir?: string;
|
|
99
201
|
text: string;
|
|
100
202
|
signal?: AbortSignal;
|
|
101
203
|
}): Promise<{
|
|
102
204
|
reply: string | null;
|
|
205
|
+
argv: string[];
|
|
206
|
+
claudeConfig?: ClaudeConfigDecision;
|
|
103
207
|
}>;
|
|
104
|
-
/**
|
|
105
|
-
export
|
|
208
|
+
/** The exact transcript state one of this runner's own turns left behind, keyed by the native session. */
|
|
209
|
+
export interface TranscriptMark {
|
|
210
|
+
mtimeMs: number;
|
|
211
|
+
size: number;
|
|
212
|
+
}
|
|
213
|
+
export declare function transcriptMark(transcriptPath: string | null): TranscriptMark | null;
|
|
214
|
+
/** Someone (a person, another runner) is writing this conversation right now. A transcript that still
|
|
215
|
+
* reads exactly as this runner's own last turn left it was not written by anyone else, however recent;
|
|
216
|
+
* the runner identifies its own writes by that recorded state, never by how long ago they happened. */
|
|
217
|
+
export declare function nativeWriterBusy(transcriptPath: string | null, now?: number, windowMs?: number, own?: TranscriptMark | null): boolean;
|
|
106
218
|
export declare function claudeReply(stdout: string): string | null;
|
|
107
219
|
export declare function codexThreadId(stdout: string): string | null;
|
|
108
220
|
export declare function codexReply(stdout: string): string | null;
|