@online-tools/work-agent-runner 0.0.4-alpha-1 → 0.1.0-alpha-1

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.
@@ -0,0 +1,330 @@
1
+ // The local control interface (docs/design.md 2.1, 3.10, 第 8 章): how a
2
+ // terminal command talks to the running instance of the same program home —
3
+ // `status`, `jobs`, `update`, `setup`'s knowledge pool, `doctor` — instead of
4
+ // writing the same files and repositories from a second process.
5
+ //
6
+ // <program home>/control/runner.sock Unix socket (0600; directory 0700)
7
+ // <program home>/control/token 32 random bytes (hex), new at every start
8
+ // <program home>/control/endpoint where the socket really is, when that
9
+ // path is too long for one (Linux 107,
10
+ // macOS 103 bytes): $XDG_RUNTIME_DIR, a
11
+ // private /tmp directory, or macOS $TMPDIR
12
+ //
13
+ // One JSON message per line:
14
+ // → { v: 1, id, token, method, params }
15
+ // ← { v: 1, id, ok: true, result } | { v: 1, id, ok: false, error: { code, message } }
16
+ // ← { v: 1, id, event, data } progress before the result (long methods)
17
+ //
18
+ // Jobs cannot use it: the sandbox gives their commands no Unix sockets (this
19
+ // program never sets allowUnixSockets), the control directories are on the
20
+ // jobs' deny list, and every request carries the token. Other accounts on the
21
+ // host cannot even reach the directory.
22
+ //
23
+ // Only node: built-ins and files in this directory.
24
+
25
+ import crypto from 'node:crypto';
26
+ import fs from 'node:fs';
27
+ import net from 'node:net';
28
+ import os from 'node:os';
29
+ import path from 'node:path';
30
+
31
+ export const CONTROL_VERSION = 1;
32
+ const MAX_LINE_BYTES = 64 * 1024;
33
+ const MAX_CONNECTIONS = 16;
34
+ const IDLE_MS = 60_000;
35
+
36
+ export class ControlError extends Error {
37
+ constructor(code, message) {
38
+ super(message);
39
+ this.code = code;
40
+ }
41
+ }
42
+
43
+ /** No instance answers for this program home (no socket, nobody listening, no token). */
44
+ export class NotRunningError extends Error {
45
+ constructor() {
46
+ super('程序没有在运行');
47
+ }
48
+ }
49
+
50
+ function socketPathMax(platform) {
51
+ return platform === 'darwin' ? 103 : 107;
52
+ }
53
+
54
+ function realpathOr(value) {
55
+ try {
56
+ return fs.realpathSync(value);
57
+ } catch {
58
+ return path.resolve(value);
59
+ }
60
+ }
61
+
62
+ /** A directory only this user can enter (not a symlink). */
63
+ function privateDir(dir, uid) {
64
+ try {
65
+ const stat = fs.lstatSync(dir);
66
+ return stat.isDirectory() && (!Number.isInteger(uid) || stat.uid === uid) && (stat.mode & 0o077) === 0;
67
+ } catch {
68
+ return false;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Where the socket goes: { dir, socket, fallback }. The program home's
74
+ * control/ when the path fits, else a directory named with a hash of the
75
+ * program home, in $XDG_RUNTIME_DIR, /tmp (Linux) or $TMPDIR (macOS).
76
+ * Throws ControlError E1112 when even that is too long.
77
+ */
78
+ export function socketLocation(paths, { env = process.env, platform = process.platform, uid = process.getuid?.() } = {}) {
79
+ const max = socketPathMax(platform);
80
+ const primary = path.join(paths.controlDir, 'runner.sock');
81
+ if (Buffer.byteLength(primary) <= max) return { dir: paths.controlDir, socket: primary, fallback: false };
82
+ const hash = crypto.createHash('sha256').update(realpathOr(paths.baseDir)).digest('hex').slice(0, 8);
83
+ let dir;
84
+ if (platform === 'darwin') dir = path.join(env.TMPDIR || os.tmpdir(), `work-agent-runner-${hash}`);
85
+ else if (env.XDG_RUNTIME_DIR && privateDir(env.XDG_RUNTIME_DIR, uid)) dir = path.join(env.XDG_RUNTIME_DIR, `work-agent-runner-${hash}`);
86
+ else dir = path.join('/tmp', `work-agent-runner-${uid ?? 0}-${hash}`);
87
+ const socket = path.join(dir, 'runner.sock');
88
+ if (Buffer.byteLength(socket) > max) {
89
+ throw new ControlError('E1112', `管理接口的 socket 路径太长(${socket}):请把 WORK_AGENT_RUNNER_HOME 设为更短的路径`);
90
+ }
91
+ return { dir, socket, fallback: true };
92
+ }
93
+
94
+ /** The directories a job must never reach: control/ and the fallback, if any. */
95
+ export function controlDirectories(paths, options) {
96
+ const dirs = [paths.controlDir];
97
+ try {
98
+ const where = socketLocation(paths, options);
99
+ if (where.fallback) dirs.push(where.dir);
100
+ } catch {
101
+ // No socket possible: nothing more to hide.
102
+ }
103
+ return dirs;
104
+ }
105
+
106
+ /** Creates `dir` 0700, or checks that it is this user's, private and not a symlink. */
107
+ function ensurePrivateDir(dir, uid) {
108
+ try {
109
+ fs.mkdirSync(dir, { mode: 0o700 });
110
+ } catch (error) {
111
+ if (error.code !== 'EEXIST') throw error;
112
+ }
113
+ if (!privateDir(dir, uid)) {
114
+ throw new ControlError('E1112', `${dir} 不是只属于当前用户的目录,不能放管理接口的 socket`);
115
+ }
116
+ }
117
+
118
+ function writePrivate(file, text) {
119
+ const temp = `${file}.${process.pid}.tmp`;
120
+ fs.writeFileSync(temp, text, { mode: 0o600 });
121
+ fs.renameSync(temp, file);
122
+ }
123
+
124
+ function canConnect(socket) {
125
+ return new Promise((resolve) => {
126
+ const probe = net.connect(socket);
127
+ probe.once('connect', () => {
128
+ probe.destroy();
129
+ resolve(true);
130
+ });
131
+ probe.once('error', () => resolve(false));
132
+ });
133
+ }
134
+
135
+ function sameToken(given, token) {
136
+ if (typeof given !== 'string' || given.length !== token.length) return false;
137
+ return crypto.timingSafeEqual(Buffer.from(given), Buffer.from(token));
138
+ }
139
+
140
+ /**
141
+ * Starts serving `handlers` ({ [method](params, { send(event, data), signal }) → result }).
142
+ * Resolves { socket, close() }. Throws when another process already answers there.
143
+ * `idleMs`: a connection with no request in progress is closed after this long.
144
+ */
145
+ export async function startControlServer({
146
+ paths,
147
+ handlers,
148
+ log = null,
149
+ env = process.env,
150
+ platform = process.platform,
151
+ uid = process.getuid?.(),
152
+ idleMs = IDLE_MS,
153
+ }) {
154
+ fs.mkdirSync(paths.controlDir, { recursive: true, mode: 0o700 });
155
+ fs.chmodSync(paths.controlDir, 0o700);
156
+ const where = socketLocation(paths, { env, platform, uid });
157
+ if (where.fallback) ensurePrivateDir(where.dir, uid);
158
+ if (fs.existsSync(where.socket)) {
159
+ if (await canConnect(where.socket)) throw new ControlError('E9002', '另一个进程正在使用这个管理接口');
160
+ fs.rmSync(where.socket, { force: true });
161
+ }
162
+ const token = crypto.randomBytes(32).toString('hex');
163
+ writePrivate(paths.controlTokenFile, `${token}\n`);
164
+ if (where.fallback) writePrivate(paths.controlEndpointFile, `${where.socket}\n`);
165
+ else fs.rmSync(paths.controlEndpointFile, { force: true });
166
+
167
+ const connections = new Set();
168
+ const server = net.createServer((socket) => {
169
+ connections.add(socket);
170
+ socket.on('close', () => connections.delete(socket));
171
+ serveConnection(socket, { token, handlers, log, idleMs });
172
+ });
173
+ server.maxConnections = MAX_CONNECTIONS;
174
+ await new Promise((resolve, reject) => {
175
+ server.once('error', reject);
176
+ server.listen(where.socket, () => {
177
+ server.off('error', reject);
178
+ resolve();
179
+ });
180
+ });
181
+ fs.chmodSync(where.socket, 0o600);
182
+ server.on('error', (error) => log?.warn(`管理接口出错:${error.message}`));
183
+ return {
184
+ socket: where.socket,
185
+ close: () =>
186
+ new Promise((resolve) => {
187
+ for (const socket of connections) socket.destroy();
188
+ server.close(() => resolve());
189
+ for (const file of [where.socket, paths.controlTokenFile, paths.controlEndpointFile]) fs.rmSync(file, { force: true });
190
+ }),
191
+ };
192
+ }
193
+
194
+ function serveConnection(socket, { token, handlers, log, idleMs }) {
195
+ let buffer = '';
196
+ let inFlight = 0;
197
+ const controller = new AbortController();
198
+ socket.setEncoding('utf8');
199
+ // Idle between requests only: a download of the pool may be silent for minutes.
200
+ socket.setTimeout(idleMs, () => {
201
+ if (!inFlight) socket.destroy();
202
+ });
203
+ socket.on('close', () => controller.abort());
204
+ socket.on('error', () => {});
205
+ const write = (message) => {
206
+ if (!socket.destroyed) socket.write(`${JSON.stringify({ v: CONTROL_VERSION, ...message })}\n`);
207
+ };
208
+ socket.on('data', (text) => {
209
+ buffer += text;
210
+ if (Buffer.byteLength(buffer) > MAX_LINE_BYTES && !buffer.includes('\n')) {
211
+ write({ id: null, ok: false, error: { code: 'E9003', message: '请求过大' } });
212
+ socket.destroy();
213
+ return;
214
+ }
215
+ let index;
216
+ while ((index = buffer.indexOf('\n')) >= 0) {
217
+ const line = buffer.slice(0, index);
218
+ buffer = buffer.slice(index + 1);
219
+ if (line.trim()) handleLine(line);
220
+ }
221
+ });
222
+ const handleLine = async (line) => {
223
+ let request;
224
+ try {
225
+ request = JSON.parse(line);
226
+ } catch {
227
+ write({ id: null, ok: false, error: { code: 'E9003', message: '请求不是 JSON' } });
228
+ return;
229
+ }
230
+ const id = typeof request?.id === 'string' ? request.id.slice(0, 100) : null;
231
+ if (request?.v !== CONTROL_VERSION) {
232
+ write({ id, ok: false, error: { code: 'E9004', message: '管理接口的版本不一致:请用同一版本的程序' } });
233
+ return;
234
+ }
235
+ if (!sameToken(request.token, token)) {
236
+ write({ id, ok: false, error: { code: 'E9001', message: '管理接口的令牌不正确' } });
237
+ return;
238
+ }
239
+ const handler = typeof request.method === 'string' && Object.hasOwn(handlers, request.method) ? handlers[request.method] : null;
240
+ if (!handler) {
241
+ write({ id, ok: false, error: { code: 'E9005', message: `不支持的操作:${String(request.method).slice(0, 40)}` } });
242
+ return;
243
+ }
244
+ inFlight += 1;
245
+ try {
246
+ const result = await handler(request.params && typeof request.params === 'object' ? request.params : {}, {
247
+ send: (event, data) => write({ id, event, data }),
248
+ signal: controller.signal,
249
+ });
250
+ write({ id, ok: true, result: result ?? null });
251
+ } catch (error) {
252
+ log?.warn(`管理接口的「${request.method}」失败:${error?.message || error}`);
253
+ const code = typeof error?.code === 'string' && /^E\d{4}$/.test(error.code) ? error.code : 'E9000';
254
+ write({ id, ok: false, error: { code, message: String(error?.message || error) } });
255
+ } finally {
256
+ inFlight -= 1;
257
+ }
258
+ };
259
+ }
260
+
261
+ function readText(file) {
262
+ try {
263
+ return fs.readFileSync(file, 'utf8').trim();
264
+ } catch {
265
+ return '';
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Asks the running instance: resolves `result`, calls `onEvent(event, data)`
271
+ * for progress on the way. Rejects NotRunningError when no instance answers,
272
+ * ControlError when it refuses. `timeoutMs`: silence allowed (0 = none, for
273
+ * long methods).
274
+ */
275
+ export function controlRequest(paths, method, params = {}, { onEvent = () => {}, timeoutMs = 30_000 } = {}) {
276
+ const token = readText(paths.controlTokenFile);
277
+ const socketPath = readText(paths.controlEndpointFile) || path.join(paths.controlDir, 'runner.sock');
278
+ if (!token) return Promise.reject(new NotRunningError());
279
+ return new Promise((resolve, reject) => {
280
+ const id = crypto.randomUUID();
281
+ const socket = net.connect(socketPath);
282
+ let buffer = '';
283
+ let settled = false;
284
+ const settle = (fn, value) => {
285
+ if (settled) return;
286
+ settled = true;
287
+ socket.destroy();
288
+ fn(value);
289
+ };
290
+ socket.setEncoding('utf8');
291
+ if (timeoutMs) socket.setTimeout(timeoutMs, () => settle(reject, new ControlError('E9006', '程序没有响应')));
292
+ socket.once('connect', () => socket.write(`${JSON.stringify({ v: CONTROL_VERSION, id, token, method, params })}\n`));
293
+ socket.on('error', (error) => {
294
+ settle(reject, ['ENOENT', 'ECONNREFUSED', 'ENOTSOCK'].includes(error.code) ? new NotRunningError() : error);
295
+ });
296
+ socket.on('close', () => settle(reject, new ControlError('E9006', '程序中断了连接')));
297
+ socket.on('data', (text) => {
298
+ buffer += text;
299
+ let index;
300
+ while ((index = buffer.indexOf('\n')) >= 0) {
301
+ const line = buffer.slice(0, index);
302
+ buffer = buffer.slice(index + 1);
303
+ let message;
304
+ try {
305
+ message = JSON.parse(line);
306
+ } catch {
307
+ continue;
308
+ }
309
+ if (message.id !== id && message.id !== null) continue;
310
+ if (message.event) {
311
+ try {
312
+ onEvent(message.event, message.data);
313
+ } catch {
314
+ // The caller's display problem, not the request's.
315
+ }
316
+ } else if (message.ok) settle(resolve, message.result);
317
+ else settle(reject, new ControlError(message.error?.code || 'E9000', message.error?.message || '失败'));
318
+ }
319
+ });
320
+ });
321
+ }
322
+
323
+ /** Whether an instance answers for this program home (its pid and version), or null. */
324
+ export async function pingInstance(paths) {
325
+ try {
326
+ return await controlRequest(paths, 'ping', {}, { timeoutMs: 5000 });
327
+ } catch {
328
+ return null;
329
+ }
330
+ }
package/lib/doctor.mjs CHANGED
@@ -9,6 +9,7 @@ import path from 'node:path';
9
9
  import readline from 'node:readline';
10
10
 
11
11
  import { claudeArgs, claudeEnv } from './claude-cli.mjs';
12
+ import { removeTree } from './fs-safe.mjs';
12
13
  import { SANDBOX_TOOLS, SKILL_TOOLS, detectPackageManager } from './packages.mjs';
13
14
  import { PROBE_MARKER, PROBE_TOOL_ID, startProbeModel } from './probe-model.mjs';
14
15
  import {
@@ -247,7 +248,8 @@ export async function probeSandbox({
247
248
  return result;
248
249
  } finally {
249
250
  await model?.close();
250
- fs.rmSync(layout.runDir, { recursive: true, force: true });
251
+ // Never throws: whatever is left goes to trash/ next to runs/.
252
+ removeTree(layout.runDir, { trashDir: path.join(workRoot, 'trash') });
251
253
  }
252
254
  }
253
255
 
package/lib/errors.mjs ADDED
@@ -0,0 +1,34 @@
1
+ // Error codes (docs/design.md 附录 B) the program writes into its job history,
2
+ // its status and the messages it sends: one code per kind of failure, so a
3
+ // report can be matched to its explanation. Only what the program reports so
4
+ // far; the catalog grows with it.
5
+
6
+ export const ERROR_CODES = {
7
+ E1112: '本机管理接口无法启动(socket 路径太长或目录不安全)',
8
+ E1301: 'Claude Code 未安装或无法运行',
9
+ E3101: '任务参数不合法',
10
+ E3201: '等待执行条件超时',
11
+ E3301: '工作目录磁盘空间不足',
12
+ E3401: '准备任务失败',
13
+ E3501: '输出无法送达网站',
14
+ E4101: '沙箱不可用',
15
+ E5101: 'work-agent 仓库刷新失败',
16
+ E5201: '知识仓更新失败',
17
+ E5202: '知识仓长时间未能更新',
18
+ E5301: '清理失败(已移入回收站)',
19
+ E9000: '本机管理接口:操作失败',
20
+ E9001: '本机管理接口:令牌不正确',
21
+ E9002: '本机管理接口:已被另一个进程占用',
22
+ E9003: '本机管理接口:请求格式不正确',
23
+ E9004: '本机管理接口:两端版本不一致',
24
+ E9005: '本机管理接口:不支持的操作',
25
+ E9006: '本机管理接口:程序没有响应',
26
+ E9007: '仓名不正确',
27
+ E9008: '知识仓正被另一个进程下载或更新',
28
+ E9009: '任务 ID 对应多个任务',
29
+ };
30
+
31
+ /** "message(E3201)": the code goes last, so the sentence still reads first. */
32
+ export function withCode(code, message) {
33
+ return code ? `${message}(${code})` : message;
34
+ }
@@ -0,0 +1,163 @@
1
+ // Deleting only what this program made, without ever throwing out of a
2
+ // cleanup (docs/design.md 3.1, 3.4.3, 7.5).
3
+ //
4
+ // A job may leave a directory it made read-only (chmod 555, a Go module
5
+ // cache…): fs.rmSync gives up on those with EACCES, and one such directory
6
+ // used to stop the service for good (every start removed runs/ and crashed).
7
+ // removeTree() makes the job's own directories writable again; what still
8
+ // cannot go is moved into trash/ and retried later. Cleanups only touch run
9
+ // and probe directories by name, never a directory the user named.
10
+ //
11
+ // Only node: built-ins.
12
+
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+
16
+ /** A run (r) or probe (p) directory: one letter and mkdtemp's six characters. */
17
+ export const RUN_ENTRY = /^[rp][A-Za-z0-9]{6}$/;
18
+
19
+ const RETRY_CODES = new Set(['EACCES', 'EPERM']);
20
+
21
+ function stamp(date = new Date()) {
22
+ return date.toISOString().replace(/[:.]/g, '-');
23
+ }
24
+
25
+ /** Gives the owner rwx on `dir` again (never through a symlink, never someone else's). */
26
+ function makeWritable(dir, ops, uid) {
27
+ const stat = ops.lstatSync(dir);
28
+ if (stat.isSymbolicLink() || !stat.isDirectory()) return false;
29
+ if (Number.isInteger(uid) && stat.uid !== uid) return false;
30
+ ops.chmodSync(dir, (stat.mode & 0o7777) | 0o700);
31
+ return true;
32
+ }
33
+
34
+ /** Runs `operation`; on EACCES / EPERM makes `dir` writable and tries once more. */
35
+ function withRetry(operation, dir, ops, uid) {
36
+ try {
37
+ return operation();
38
+ } catch (error) {
39
+ if (!RETRY_CODES.has(error.code) || !makeWritable(dir, ops, uid)) throw error;
40
+ return operation();
41
+ }
42
+ }
43
+
44
+ function removeEntry(target, ops, uid) {
45
+ let stat;
46
+ try {
47
+ stat = ops.lstatSync(target);
48
+ } catch (error) {
49
+ if (error.code === 'ENOENT') return;
50
+ throw error;
51
+ }
52
+ const parent = path.dirname(target);
53
+ if (!stat.isDirectory()) {
54
+ withRetry(() => ops.unlinkSync(target), parent, ops, uid);
55
+ return;
56
+ }
57
+ // A directory without r/x cannot even be listed; one without w keeps its
58
+ // entries (each unlink / rmdir below retries after fixing its parent).
59
+ const names = withRetry(() => ops.readdirSync(target), target, ops, uid);
60
+ for (const name of names) removeEntry(path.join(target, name), ops, uid);
61
+ withRetry(() => ops.rmdirSync(target), parent, ops, uid);
62
+ }
63
+
64
+ /**
65
+ * Removes `target` (file or directory tree) without following symlinks.
66
+ * Never throws. Returns { removed: true } or { removed: false, error } — with
67
+ * `trashDir`, what cannot be removed is renamed into it ({ trashed }), which
68
+ * must be on the same filesystem. `ops` replaces node:fs in tests.
69
+ */
70
+ export function removeTree(target, { trashDir = '', ops = fs, uid = process.getuid?.() } = {}) {
71
+ try {
72
+ removeEntry(target, ops, uid);
73
+ return { removed: true };
74
+ } catch (error) {
75
+ if (trashDir) {
76
+ try {
77
+ ops.mkdirSync(trashDir, { recursive: true, mode: 0o700 });
78
+ const trashed = path.join(trashDir, `${stamp()}-${path.basename(target)}`);
79
+ ops.renameSync(target, trashed);
80
+ return { removed: false, trashed, error };
81
+ } catch {
82
+ // Not even that: leave it where it is for the next cleanup.
83
+ }
84
+ }
85
+ return { removed: false, error };
86
+ }
87
+ }
88
+
89
+ /** Whether `name` in `dir` is a run or probe directory of this user (never a symlink). */
90
+ export function isRunEntry(dir, name, { uid = process.getuid?.() } = {}) {
91
+ if (!RUN_ENTRY.test(name)) return false;
92
+ try {
93
+ const stat = fs.lstatSync(path.join(dir, name));
94
+ return stat.isDirectory() && (!Number.isInteger(uid) || stat.uid === uid);
95
+ } catch {
96
+ return false;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Removes the run and probe directories left in `runsDir` (and retries what
102
+ * is in `trashDir`). Anything else in runsDir is left alone and reported.
103
+ * Never throws: { removed, trashed: [paths], failed: [paths], unknown: [names] }.
104
+ */
105
+ export function cleanRunsDir(runsDir, { trashDir = '', uid = process.getuid?.() } = {}) {
106
+ const summary = { removed: 0, trashed: [], failed: [], unknown: [] };
107
+ let names = [];
108
+ try {
109
+ names = fs.readdirSync(runsDir);
110
+ } catch {
111
+ return summary;
112
+ }
113
+ for (const name of names) {
114
+ if (!isRunEntry(runsDir, name, { uid })) {
115
+ summary.unknown.push(name);
116
+ continue;
117
+ }
118
+ const outcome = removeTree(path.join(runsDir, name), { trashDir, uid });
119
+ if (outcome.removed) summary.removed += 1;
120
+ else if (outcome.trashed) summary.trashed.push(outcome.trashed);
121
+ else summary.failed.push(path.join(runsDir, name));
122
+ }
123
+ if (trashDir) summary.failed.push(...retryTrash(trashDir, { uid }));
124
+ return summary;
125
+ }
126
+
127
+ /** Tries again to remove everything in `trashDir`; returns what is still there. */
128
+ export function retryTrash(trashDir, { uid = process.getuid?.() } = {}) {
129
+ let names = [];
130
+ try {
131
+ names = fs.readdirSync(trashDir);
132
+ } catch {
133
+ return [];
134
+ }
135
+ const left = [];
136
+ for (const name of names) {
137
+ const entry = path.join(trashDir, name);
138
+ if (!removeTree(entry, { uid }).removed) left.push(entry);
139
+ }
140
+ return left;
141
+ }
142
+
143
+ /** JSON written atomically (temporary file, then rename), mode 0600. */
144
+ export function writeJsonAtomic(file, value) {
145
+ const temp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
146
+ try {
147
+ fs.writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
148
+ fs.renameSync(temp, file);
149
+ } catch (error) {
150
+ fs.rmSync(temp, { force: true });
151
+ throw error;
152
+ }
153
+ }
154
+
155
+ /** Parsed JSON object from `file`, or null when it is missing or not an object. */
156
+ export function readJsonFile(file) {
157
+ try {
158
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
159
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
160
+ } catch {
161
+ return null;
162
+ }
163
+ }