-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdaemon.ts
More file actions
200 lines (176 loc) · 5.42 KB
/
Copy pathdaemon.ts
File metadata and controls
200 lines (176 loc) · 5.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
/**
* Daemon communication layer for the OpenClaw wallet plugin.
*
* Spawns `ocap daemon exec` commands and decodes Endo CapData responses.
*/
import { spawn } from 'node:child_process';
type ExecResult = { stdout: string; stderr: string; code: number | null };
type CapDataLike = { body: string; slots: unknown[] };
export type WalletCallOptions = {
cliPath: string;
walletKref: string;
method: string;
args: unknown[];
timeoutMs: number;
};
/**
* Bound wallet caller — pre-configured with CLI path, kref, and timeout.
*/
export type WalletCaller = (
method: string,
args: unknown[],
timeoutMs?: number,
) => Promise<unknown>;
/**
* Create a bound wallet caller from plugin config.
*
* @param options - Wallet connection options.
* @param options.cliPath - Path to the ocap CLI.
* @param options.walletKref - Kernel reference for the wallet coordinator.
* @param options.timeoutMs - Default timeout in ms.
* @returns A bound caller function.
*/
export function makeWalletCaller(options: {
cliPath: string;
walletKref: string;
timeoutMs: number;
}): WalletCaller {
const { cliPath, walletKref, timeoutMs } = options;
return async (method, args, overrideTimeout) =>
callWallet({
cliPath,
walletKref,
method,
args,
timeoutMs: overrideTimeout ?? timeoutMs,
});
}
/**
* Check if a value looks like Endo CapData.
*
* @param value - The parsed JSON value.
* @returns True when value has CapData shape.
*/
function isCapDataLike(value: unknown): value is CapDataLike {
if (typeof value !== 'object' || value === null) {
return false;
}
if (!('body' in value) || !('slots' in value)) {
return false;
}
const { body } = value as { body?: unknown };
const { slots } = value as { slots?: unknown };
return typeof body === 'string' && Array.isArray(slots);
}
/**
* Decode daemon JSON output, unwrapping Endo CapData.
*
* @param raw - Raw stdout from `ocap daemon exec`.
* @param method - Wallet method name (for better errors).
* @returns The decoded value.
*/
function decodeCapData(raw: string, method: string): unknown {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
throw new Error(`Wallet ${method} returned non-JSON output`);
}
if (!isCapDataLike(parsed)) {
return parsed;
}
if (!parsed.body.startsWith('#')) {
throw new Error(`Wallet ${method} returned invalid CapData body`);
}
const bodyContent = parsed.body.slice(1);
// Handle error bodies from vat exceptions (e.g. "#error:message")
if (bodyContent.startsWith('error:')) {
throw new Error(`Wallet ${method} vat error: ${bodyContent.slice(6)}`);
}
let decoded: unknown;
try {
decoded = JSON.parse(bodyContent);
} catch {
throw new Error(`Wallet ${method} returned undecodable CapData body`);
}
// Handle Endo CapData error encoding: #{"#error": "message", ...}
if (decoded !== null && typeof decoded === 'object' && '#error' in decoded) {
const errorMsg = (decoded as Record<string, unknown>)['#error'];
throw new Error(
`Wallet ${method} failed: ${typeof errorMsg === 'string' ? errorMsg : JSON.stringify(errorMsg)}`,
);
}
return decoded;
}
/**
* Run an `ocap daemon exec` command and return its output.
*
* @param options - Execution options.
* @param options.cliPath - Path to the ocap CLI.
* @param options.method - The daemon RPC method.
* @param options.params - The method parameters.
* @param options.timeoutMs - Timeout in ms.
* @returns The command result.
*/
async function runDaemonExec(options: {
cliPath: string;
method: string;
params: unknown;
timeoutMs: number;
}): Promise<ExecResult> {
const { cliPath, method, params, timeoutMs } = options;
const daemonArgs = ['daemon', 'exec', method, JSON.stringify(params)];
// If cliPath points to a .mjs file, invoke it via node.
const command = cliPath.endsWith('.mjs') ? 'node' : cliPath;
const args = cliPath.endsWith('.mjs') ? [cliPath, ...daemonArgs] : daemonArgs;
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
stdio: ['ignore', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
child.stdout?.setEncoding('utf8');
child.stderr?.setEncoding('utf8');
child.stdout?.on('data', (chunk: string) => {
stdout += chunk;
});
child.stderr?.on('data', (chunk: string) => {
stderr += chunk;
});
const timer = setTimeout(() => {
try {
child.kill('SIGKILL');
} finally {
reject(new Error(`ocap daemon exec timed out after ${timeoutMs}ms`));
}
}, timeoutMs);
child.once('error', (error: Error) => {
clearTimeout(timer);
reject(error);
});
child.once('exit', (code) => {
clearTimeout(timer);
resolve({ stdout, stderr, code: code ?? null });
});
});
}
/**
* Call a wallet coordinator method via the OCAP daemon.
*
* @param options - Call options.
* @returns The decoded response value.
*/
async function callWallet(options: WalletCallOptions): Promise<unknown> {
const { cliPath, walletKref, method, args, timeoutMs } = options;
const result = await runDaemonExec({
cliPath,
method: 'queueMessage',
params: [walletKref, method, args],
timeoutMs,
});
if (result.code !== 0) {
const detail = result.stderr.trim() || result.stdout.trim();
throw new Error(`Wallet ${method} failed (exit ${result.code}): ${detail}`);
}
return decodeCapData(result.stdout.trim(), method);
}