@octopi-agent/engine 0.90.11 → 0.97.15

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.
Files changed (169) hide show
  1. package/dist/config-admin/agent-presets.d.ts +70 -0
  2. package/dist/config-admin/agent-presets.js +243 -0
  3. package/dist/config-admin/discover.d.ts +30 -0
  4. package/dist/config-admin/discover.js +48 -0
  5. package/dist/config-admin/env.d.ts +22 -0
  6. package/dist/config-admin/env.js +41 -0
  7. package/dist/config-admin/index.d.ts +20 -0
  8. package/dist/config-admin/index.js +15 -0
  9. package/dist/config-admin/model-presets.d.ts +75 -0
  10. package/dist/config-admin/model-presets.js +249 -0
  11. package/dist/config-admin/name-guard.d.ts +14 -0
  12. package/dist/config-admin/name-guard.js +24 -0
  13. package/dist/config-admin/patch.d.ts +56 -0
  14. package/dist/config-admin/patch.js +201 -0
  15. package/dist/config-admin/port.d.ts +68 -0
  16. package/dist/config-admin/port.js +21 -0
  17. package/dist/config-admin/redact.d.ts +39 -0
  18. package/dist/config-admin/redact.js +42 -0
  19. package/dist/config-schema/agent.d.ts +43 -1
  20. package/dist/config-schema/context.d.ts +6 -1
  21. package/dist/config-schema/context.js +8 -0
  22. package/dist/config-schema/engine.d.ts +106 -4
  23. package/dist/config-schema/governance.d.ts +43 -1
  24. package/dist/config-schema/governance.js +157 -0
  25. package/dist/config-schema/models.d.ts +5 -2
  26. package/dist/config-schema/models.js +4 -1
  27. package/dist/config-schema/observability.d.ts +9 -0
  28. package/dist/config-schema/observability.js +29 -0
  29. package/dist/config-schema/run.d.ts +3 -0
  30. package/dist/config-schema/run.js +14 -0
  31. package/dist/config.d.ts +29 -4
  32. package/dist/config.js +15 -4
  33. package/dist/harness/activation/dispatcher.d.ts +8 -2
  34. package/dist/harness/activation/dispatcher.js +33 -5
  35. package/dist/harness/activation/inbox.d.ts +87 -0
  36. package/dist/harness/activation/inbox.js +169 -0
  37. package/dist/harness/activation/runtime.d.ts +9 -8
  38. package/dist/harness/activation/runtime.js +100 -8
  39. package/dist/harness/activation/types.d.ts +19 -0
  40. package/dist/harness/activation/types.js +2 -0
  41. package/dist/harness/agent/builder.d.ts +15 -1
  42. package/dist/harness/agent/builder.js +31 -10
  43. package/dist/harness/agent/config-bridge.d.ts +5 -0
  44. package/dist/harness/agent/config-bridge.js +3 -0
  45. package/dist/harness/agent/config-integrity.d.ts +72 -0
  46. package/dist/harness/agent/config-integrity.js +146 -0
  47. package/dist/harness/agent/wire-agent-builder.js +2 -1
  48. package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -1
  49. package/dist/harness/collaboration/delegation/child-run.js +21 -5
  50. package/dist/harness/collaboration/delegation/notifier.js +4 -3
  51. package/dist/harness/collaboration/delegation/service.js +2 -3
  52. package/dist/harness/collaboration/delegation/wiring.js +6 -5
  53. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.d.ts +1 -1
  54. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.js +1 -1
  55. package/dist/harness/context/capabilities/compact/engine.d.ts +30 -0
  56. package/dist/harness/context/capabilities/compact/engine.js +198 -46
  57. package/dist/harness/context/capabilities/compact/handover.d.ts +78 -0
  58. package/dist/harness/context/capabilities/compact/handover.js +107 -0
  59. package/dist/harness/context/capabilities/compact/index.d.ts +3 -1
  60. package/dist/harness/context/capabilities/compact/index.js +2 -1
  61. package/dist/harness/context/capabilities/compact/types.d.ts +30 -1
  62. package/dist/harness/context/capabilities/summary/executor.js +2 -1
  63. package/dist/harness/context/capabilities/summary/policies.js +8 -5
  64. package/dist/harness/context/constitution/default-agents.md +11 -10
  65. package/dist/harness/context/default-context-engine.d.ts +34 -4
  66. package/dist/harness/context/default-context-engine.js +194 -49
  67. package/dist/harness/context/hybrid-compressor.js +6 -0
  68. package/dist/harness/context/llm-summarizer.d.ts +2 -8
  69. package/dist/harness/context/llm-summarizer.js +69 -91
  70. package/dist/harness/context/message-selector.js +4 -3
  71. package/dist/harness/context/summarize.d.ts +2 -0
  72. package/dist/harness/context/summarize.js +7 -2
  73. package/dist/harness/context/truncate-compressor.js +7 -0
  74. package/dist/harness/context/turn-envelope.d.ts +3 -2
  75. package/dist/harness/context/turn-envelope.js +3 -2
  76. package/dist/harness/context/types.d.ts +33 -1
  77. package/dist/harness/extension/execution-environment/dangerous-commands.d.ts +28 -0
  78. package/dist/harness/extension/execution-environment/dangerous-commands.js +129 -0
  79. package/dist/harness/extension/execution-environment/effect-policy.d.ts +127 -8
  80. package/dist/harness/extension/execution-environment/effect-policy.js +244 -19
  81. package/dist/harness/extension/execution-environment/index.d.ts +4 -2
  82. package/dist/harness/extension/execution-environment/index.js +2 -1
  83. package/dist/harness/extension/execution-environment/kill-switch.d.ts +34 -0
  84. package/dist/harness/extension/execution-environment/kill-switch.js +46 -0
  85. package/dist/harness/extension/execution-environment/ops-audit.d.ts +200 -0
  86. package/dist/harness/extension/execution-environment/ops-audit.js +338 -0
  87. package/dist/harness/extension/execution-environment/privileged-exec.d.ts +158 -0
  88. package/dist/harness/extension/execution-environment/privileged-exec.js +418 -0
  89. package/dist/harness/extension/execution-environment/process-info.d.ts +180 -0
  90. package/dist/harness/extension/execution-environment/process-info.js +466 -0
  91. package/dist/harness/extension/execution-environment/process-isolation.d.ts +7 -0
  92. package/dist/harness/extension/execution-environment/process-isolation.js +9 -0
  93. package/dist/harness/extension/execution-environment/sandbox.d.ts +109 -0
  94. package/dist/harness/extension/execution-environment/sandbox.js +228 -21
  95. package/dist/harness/extension/execution-environment/tool-capabilities.d.ts +1 -1
  96. package/dist/harness/extension/execution-environment/tool-capabilities.js +6 -0
  97. package/dist/harness/extension/execution-environment/types.d.ts +19 -0
  98. package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +5 -0
  99. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.js +33 -0
  100. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.d.ts +4 -5
  101. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.js +5 -15
  102. package/dist/harness/extension/plugin-ecosystem/tools/builtin.d.ts +3 -0
  103. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +53 -2
  104. package/dist/harness/extension/plugin-ecosystem/tools/index.d.ts +2 -0
  105. package/dist/harness/extension/plugin-ecosystem/tools/index.js +2 -0
  106. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.d.ts +43 -0
  107. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.js +350 -0
  108. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.d.ts +30 -0
  109. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.js +137 -0
  110. package/dist/harness/governance/human-in-the-loop/decision-cache.d.ts +54 -4
  111. package/dist/harness/governance/human-in-the-loop/decision-cache.js +42 -16
  112. package/dist/harness/governance/security/temp-path.d.ts +9 -0
  113. package/dist/harness/governance/security/temp-path.js +13 -2
  114. package/dist/harness/governance/session-acl/seed-roles.js +14 -0
  115. package/dist/harness/index.d.ts +2 -0
  116. package/dist/harness/index.js +2 -0
  117. package/dist/harness/knowledge/fts.js +1 -2
  118. package/dist/harness/knowledge/index-store.js +59 -9
  119. package/dist/harness/memory/sqlite/keyword-search.d.ts +1 -0
  120. package/dist/harness/memory/sqlite/keyword-search.js +4 -3
  121. package/dist/harness/observability/observer/hub.js +8 -0
  122. package/dist/harness/observability/observer/run-snapshot.js +1 -0
  123. package/dist/harness/observability/observer/types.d.ts +4 -0
  124. package/dist/harness/run/agent/agent.d.ts +7 -0
  125. package/dist/harness/run/agent/agent.js +23 -1
  126. package/dist/harness/run/reliability/fallback-provider.d.ts +117 -5
  127. package/dist/harness/run/reliability/fallback-provider.js +262 -22
  128. package/dist/harness/run/reliability/harness-events.d.ts +24 -1
  129. package/dist/harness/run/reliability/model-error-policy.d.ts +32 -0
  130. package/dist/harness/run/reliability/model-error-policy.js +42 -0
  131. package/dist/harness/run/reliability/provider-wrapper.js +29 -2
  132. package/dist/harness/run/reliability/refusal-guard.d.ts +20 -0
  133. package/dist/harness/run/reliability/refusal-guard.js +102 -0
  134. package/dist/harness/run/reliability/run-agent.js +231 -33
  135. package/dist/harness/run/run-guard/default-run-guard.js +1 -1
  136. package/dist/harness/run/run-scope.d.ts +31 -0
  137. package/dist/harness/run/runner.d.ts +116 -2
  138. package/dist/harness/run/runner.js +547 -41
  139. package/dist/harness/session/attachments/llm-intent.js +2 -1
  140. package/dist/harness/session/tasks/render.d.ts +4 -1
  141. package/dist/harness/session/tasks/render.js +10 -7
  142. package/dist/harness/shared/events/agent-event-map.d.ts +66 -0
  143. package/dist/harness/shared/events/agent-event-map.js +5 -0
  144. package/dist/index.d.ts +3 -3
  145. package/dist/index.js +2 -2
  146. package/dist/integration/agent-runtime/channel-message-source.js +19 -1
  147. package/dist/integration/index.d.ts +2 -0
  148. package/dist/integration/index.js +1 -0
  149. package/dist/integration/observability/loop-watchdog.d.ts +56 -0
  150. package/dist/integration/observability/loop-watchdog.js +177 -0
  151. package/dist/integration/observability/metrics.d.ts +3 -0
  152. package/dist/integration/observability/metrics.js +18 -7
  153. package/dist/integration/providers/anthropic.d.ts +23 -0
  154. package/dist/integration/providers/anthropic.js +97 -12
  155. package/dist/integration/providers/fetch-timeout.d.ts +42 -0
  156. package/dist/integration/providers/fetch-timeout.js +51 -0
  157. package/dist/integration/providers/openai.d.ts +10 -0
  158. package/dist/integration/providers/openai.js +58 -11
  159. package/dist/integration/providers/provider-diagnostics.d.ts +80 -0
  160. package/dist/integration/providers/provider-diagnostics.js +89 -0
  161. package/dist/integration/providers/timeout-coherence.d.ts +52 -0
  162. package/dist/integration/providers/timeout-coherence.js +68 -0
  163. package/dist/integration/providers/wire-dump.d.ts +62 -0
  164. package/dist/integration/providers/wire-dump.js +111 -2
  165. package/dist/integration/storage/jsonl.js +4 -1
  166. package/dist/subsystems/cognition-steward/conceptualize/handler.js +1 -1
  167. package/dist/subsystems/memory-steward/backfill/handler.js +1 -1
  168. package/dist/subsystems/wisdom-steward/formation/handler.js +1 -1
  169. package/package.json +3 -2
@@ -0,0 +1,180 @@
1
+ /**
2
+ * 进程只读诊断原语(ops P1,零权限放松)
3
+ *
4
+ * 引擎侧实现,**不经 shell 工具 / ProcessSandbox**:
5
+ * - macOS 牢笼拒 exec setuid 的 `ps`(OS 不变量),笼内 shell 拿不到进程表;
6
+ * - Linux bwrap 自带新 pidns,笼内 shell 物理看不到宿主进程。
7
+ * 因此「看进程」只能由引擎进程自己(牢笼外)读 procfs / 调 `ps`。
8
+ * 契约见 `arch/ops-privileged-mode.md` §5 P1。只读:不杀进程、不改任何状态。
9
+ *
10
+ * 所有 spawn 走异步 `execFile`(对齐 runGit 惯例):daemon 单线程,同步 spawn
11
+ * 会在 ps/powershell 挂起的最坏情形冻结 gateway 与全部并发 session。
12
+ */
13
+ /** 单个进程的只读快照 */
14
+ export interface ProcessInfoEntry {
15
+ pid: number;
16
+ /** 父 pid;来源给不出时为 null(如实反映,不猜) */
17
+ ppid: number | null;
18
+ /** 完整命令行(argv 空格连接);给不出时退化为可执行名 */
19
+ command: string | null;
20
+ rssBytes: number | null;
21
+ /**
22
+ * 累计 CPU 时间(user+sys,毫秒)。
23
+ * CPU 占用率需要采样语义,不混进本字段(一个字段一个含义)。
24
+ */
25
+ cpuTimeMs: number | null;
26
+ threads: number | null;
27
+ }
28
+ /** 一次枚举的结果(含来源与诚实降级) */
29
+ export interface ProcessListResult {
30
+ processes: ProcessInfoEntry[];
31
+ source: 'procfs' | 'ps' | 'powershell';
32
+ /** false = 来源整体取不到/明显不全(降级),不等于「成功但没有进程」 */
33
+ complete: boolean;
34
+ notes: string[];
35
+ }
36
+ /** 枚举选项(全部如实生效,不静默忽略) */
37
+ export interface ListProcessesOptions {
38
+ /** 只保留这些 pid(扫描仍按来源读取,过滤在内存完成) */
39
+ pids?: number[];
40
+ /** 命令行子串过滤(ASCII 大小写不敏感) */
41
+ nameContains?: string;
42
+ /** 排序键:`pid` 升序 / `rss` 降序(并列按 pid 升序) */
43
+ sort?: 'pid' | 'rss';
44
+ /** 截断上限;被截断时 `truncated` 为 true */
45
+ limit?: number;
46
+ }
47
+ /** 过滤/排序/截断的结果 */
48
+ export interface SelectedProcesses {
49
+ selected: ProcessInfoEntry[];
50
+ /** 过滤前条目数 */
51
+ total: number;
52
+ /** 过滤后、截断前条目数(与 `total` 并列,避免「被过滤」误读成「被吞」) */
53
+ matched: number;
54
+ truncated: boolean;
55
+ }
56
+ /** 祖先链查找结果 */
57
+ export interface AncestorChain {
58
+ /** 从最远已知祖先到 `pid` 自身(含);链尾恒为 `pid` */
59
+ chain: number[];
60
+ /** false = 中间有断链(来源缺 pid/ppid),链不完整 */
61
+ complete: boolean;
62
+ notes: string[];
63
+ }
64
+ /** 表解析结果:条目 + 被跳过的非空行数(诚实记账,禁止静默丢行) */
65
+ export interface TableParseResult {
66
+ entries: ProcessInfoEntry[];
67
+ /** 非空但不可解析的行数(warning / 截断 / 列错位);>0 = 来源不全 */
68
+ skipped: number;
69
+ }
70
+ /**
71
+ * Pick the executable image out of `lsof -a -d txt -Fn` output.
72
+ *
73
+ * lsof prints one `n<name>` line per matching descriptor, in descriptor order.
74
+ * The first `txt` entry is the executable itself; every later one is a
75
+ * dyld/mmap'd library (`/usr/lib/dyld`, framework dylibs). Taking "the first n
76
+ * line" is therefore the executable, not "any n line".
77
+ *
78
+ * @param output - raw stdout of `lsof -p <pid> -a -d txt -Fn`
79
+ * @returns absolute executable path, or null when the output carries none
80
+ */
81
+ export declare function firstExecutableFromLsof(output: string): string | null;
82
+ /**
83
+ * Parse `ps` table output (`-o pid=,ppid=,rss=,time=,[thcount=,]command=`).
84
+ *
85
+ * `command` is the remainder of the line after the numeric columns, so argv
86
+ * spacing inside it is preserved verbatim. Lines that do not parse are counted
87
+ * in `skipped` (never dropped silently): a warning line and a corrupted data
88
+ * line look the same to a regex, so any skip degrades `complete` upstream.
89
+ *
90
+ * @param output - raw stdout of the ps invocation
91
+ * @param includeThreads - whether the table carried a `thcount` column
92
+ * @returns parsed entries plus the count of skipped non-empty lines
93
+ */
94
+ export declare function parsePsProcessTable(output: string, includeThreads: boolean): TableParseResult;
95
+ /**
96
+ * Parse a ps `time` cell (`[[dd-]hh:]mm:ss[.fraction]`, cumulative CPU).
97
+ *
98
+ * @param text - the raw cell
99
+ * @returns cumulative CPU milliseconds, or null when the cell is unparseable
100
+ */
101
+ export declare function parseCpuTimeToMs(text: string): number | null;
102
+ /**
103
+ * Assemble one entry from `/proc/<pid>` file contents (pure; procfs I/O stays
104
+ * in {@link listProcesses}).
105
+ *
106
+ * `stat` comm may contain spaces and parentheses, so it is taken between the
107
+ * first `(` and the **last** `)` — never by splitting on whitespace. ppid comes
108
+ * from `stat` field 4; `threads` deliberately comes from `status:Threads`
109
+ * instead of `stat` field 20 (one less positional index to get wrong).
110
+ *
111
+ * @param pid - the pid these contents came from
112
+ * @param stat - `/proc/<pid>/stat`
113
+ * @param status - `/proc/<pid>/status`
114
+ * @param cmdline - `/proc/<pid>/cmdline` (NUL-separated argv; empty for kernel threads)
115
+ * @returns parsed entry
116
+ */
117
+ export declare function parseProcPidEntry(pid: number, stat: string, status: string, cmdline: Buffer | string): ProcessInfoEntry;
118
+ /**
119
+ * Parse the tab-separated `Get-CimInstance Win32_Process` table produced by
120
+ * {@link listProcesses} on win32.
121
+ *
122
+ * Columns: pid, ppid, workingSet, kernelModeTime, userModeTime (100ns units),
123
+ * threadCount, command. A command containing tabs keeps them (join back).
124
+ * Unparseable lines are counted in `skipped`, never dropped silently.
125
+ *
126
+ * @param output - raw powershell stdout
127
+ * @returns parsed entries plus the count of skipped non-empty lines
128
+ */
129
+ export declare function parsePowerShellProcessTable(output: string): TableParseResult;
130
+ /**
131
+ * Walk the ppid map from `pid` up to the topmost reachable ancestor (pure).
132
+ *
133
+ * @param ppidByPid - pid → parent pid (null = source reported unknown)
134
+ * @param pid - starting pid (always included as the chain tail)
135
+ * @returns chain (topmost ancestor first, `pid` last) and whether every link resolved
136
+ */
137
+ export declare function buildAncestorChain(ppidByPid: ReadonlyMap<number, number | null>, pid: number): {
138
+ chain: number[];
139
+ complete: boolean;
140
+ };
141
+ /**
142
+ * Apply filters, sort and limit to an enumeration (pure; all options honored).
143
+ *
144
+ * @param processes - enumerated entries
145
+ * @param options - filter/sort/limit options
146
+ * @returns selection with totals (`total` = pre-filter, `matched` = post-filter)
147
+ */
148
+ export declare function selectProcesses(processes: readonly ProcessInfoEntry[], options?: ListProcessesOptions): SelectedProcesses;
149
+ /**
150
+ * Enumerate running processes (read-only, engine-side).
151
+ *
152
+ * Sources: Linux `/proc` (works on slim images without `ps`), other POSIX `ps`,
153
+ * win32 `Get-CimInstance`. A source that cannot be read at all degrades
154
+ * honestly (`complete: false` + notes) — never an empty success.
155
+ *
156
+ * @returns the enumeration with its source and degradation notes
157
+ */
158
+ export declare function listProcesses(): Promise<ProcessListResult>;
159
+ /**
160
+ * Find the ancestor chain of a pid (read-only).
161
+ *
162
+ * `process.ppid` is seeded for the caller's own pid so a degraded listing still
163
+ * yields the one link Node already knows.
164
+ *
165
+ * @param pid - target pid
166
+ * @param listed - a fresh enumeration to walk (reuse to avoid a second scan)
167
+ * @returns chain (topmost first, `pid` last) with completeness and source notes
168
+ */
169
+ export declare function getAncestorPidChain(pid: number, listed?: ProcessListResult): Promise<AncestorChain>;
170
+ /**
171
+ * Resolve the executable image of a pid (read-only, best-effort).
172
+ *
173
+ * linux: `/proc/<pid>/exe` readlink (then `ps -o comm=`); darwin: `lsof` txt
174
+ * (then `ps`; lsof is not setuid so it also works inside the Seatbelt jail);
175
+ * win32: `tasklist` name (no path without elevation).
176
+ *
177
+ * @param pid - target pid
178
+ * @returns image path (or bare name where paths are unavailable), null when unresolvable
179
+ */
180
+ export declare function resolveProcessImage(pid: number): Promise<string | null>;
@@ -0,0 +1,466 @@
1
+ /**
2
+ * 进程只读诊断原语(ops P1,零权限放松)
3
+ *
4
+ * 引擎侧实现,**不经 shell 工具 / ProcessSandbox**:
5
+ * - macOS 牢笼拒 exec setuid 的 `ps`(OS 不变量),笼内 shell 拿不到进程表;
6
+ * - Linux bwrap 自带新 pidns,笼内 shell 物理看不到宿主进程。
7
+ * 因此「看进程」只能由引擎进程自己(牢笼外)读 procfs / 调 `ps`。
8
+ * 契约见 `arch/ops-privileged-mode.md` §5 P1。只读:不杀进程、不改任何状态。
9
+ *
10
+ * 所有 spawn 走异步 `execFile`(对齐 runGit 惯例):daemon 单线程,同步 spawn
11
+ * 会在 ps/powershell 挂起的最坏情形冻结 gateway 与全部并发 session。
12
+ */
13
+ import { execFile } from 'node:child_process';
14
+ import { readFileSync, readdirSync, readlinkSync } from 'node:fs';
15
+ /**
16
+ * Pick the executable image out of `lsof -a -d txt -Fn` output.
17
+ *
18
+ * lsof prints one `n<name>` line per matching descriptor, in descriptor order.
19
+ * The first `txt` entry is the executable itself; every later one is a
20
+ * dyld/mmap'd library (`/usr/lib/dyld`, framework dylibs). Taking "the first n
21
+ * line" is therefore the executable, not "any n line".
22
+ *
23
+ * @param output - raw stdout of `lsof -p <pid> -a -d txt -Fn`
24
+ * @returns absolute executable path, or null when the output carries none
25
+ */
26
+ export function firstExecutableFromLsof(output) {
27
+ for (const line of output.split('\n')) {
28
+ if (!line.startsWith('n'))
29
+ continue;
30
+ const path = line.slice(1).trim();
31
+ if (path)
32
+ return path;
33
+ }
34
+ return null;
35
+ }
36
+ /**
37
+ * Parse `ps` table output (`-o pid=,ppid=,rss=,time=,[thcount=,]command=`).
38
+ *
39
+ * `command` is the remainder of the line after the numeric columns, so argv
40
+ * spacing inside it is preserved verbatim. Lines that do not parse are counted
41
+ * in `skipped` (never dropped silently): a warning line and a corrupted data
42
+ * line look the same to a regex, so any skip degrades `complete` upstream.
43
+ *
44
+ * @param output - raw stdout of the ps invocation
45
+ * @param includeThreads - whether the table carried a `thcount` column
46
+ * @returns parsed entries plus the count of skipped non-empty lines
47
+ */
48
+ export function parsePsProcessTable(output, includeThreads) {
49
+ const withThreads = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(.*)$/;
50
+ const withoutThreads = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/;
51
+ const entries = [];
52
+ let skipped = 0;
53
+ for (const line of output.split('\n')) {
54
+ if (line.trim() === '')
55
+ continue;
56
+ const m = includeThreads ? withThreads.exec(line) : withoutThreads.exec(line);
57
+ if (!m) {
58
+ skipped += 1;
59
+ continue;
60
+ }
61
+ const pid = parseInt(m[1], 10);
62
+ const ppid = parseInt(m[2], 10);
63
+ const rssKb = parseInt(m[3], 10);
64
+ const threadsRaw = includeThreads ? parseInt(m[5], 10) : NaN;
65
+ entries.push({
66
+ pid,
67
+ ppid: Number.isInteger(ppid) && ppid >= 0 ? ppid : null,
68
+ command: m[includeThreads ? 6 : 5].trim() || null,
69
+ rssBytes: Number.isInteger(rssKb) && rssKb >= 0 ? rssKb * 1024 : null,
70
+ cpuTimeMs: parseCpuTimeToMs(m[4]),
71
+ threads: Number.isInteger(threadsRaw) && threadsRaw >= 0 ? threadsRaw : null,
72
+ });
73
+ }
74
+ return { entries, skipped };
75
+ }
76
+ /**
77
+ * Parse a ps `time` cell (`[[dd-]hh:]mm:ss[.fraction]`, cumulative CPU).
78
+ *
79
+ * @param text - the raw cell
80
+ * @returns cumulative CPU milliseconds, or null when the cell is unparseable
81
+ */
82
+ export function parseCpuTimeToMs(text) {
83
+ const m = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)(?:\.(\d+))?$/.exec(text.trim());
84
+ if (!m)
85
+ return null;
86
+ const days = m[1] ? parseInt(m[1], 10) : 0;
87
+ const hours = m[2] ? parseInt(m[2], 10) : 0;
88
+ const minutes = parseInt(m[3], 10);
89
+ const seconds = parseInt(m[4], 10);
90
+ const fraction = m[5] ? parseInt(m[5], 10) / 10 ** m[5].length : 0;
91
+ return Math.round(((days * 24 + hours) * 3600 + minutes * 60 + seconds + fraction) * 1000);
92
+ }
93
+ /**
94
+ * Assemble one entry from `/proc/<pid>` file contents (pure; procfs I/O stays
95
+ * in {@link listProcesses}).
96
+ *
97
+ * `stat` comm may contain spaces and parentheses, so it is taken between the
98
+ * first `(` and the **last** `)` — never by splitting on whitespace. ppid comes
99
+ * from `stat` field 4; `threads` deliberately comes from `status:Threads`
100
+ * instead of `stat` field 20 (one less positional index to get wrong).
101
+ *
102
+ * @param pid - the pid these contents came from
103
+ * @param stat - `/proc/<pid>/stat`
104
+ * @param status - `/proc/<pid>/status`
105
+ * @param cmdline - `/proc/<pid>/cmdline` (NUL-separated argv; empty for kernel threads)
106
+ * @returns parsed entry
107
+ */
108
+ export function parseProcPidEntry(pid, stat, status, cmdline) {
109
+ const open = stat.indexOf('(');
110
+ const close = stat.lastIndexOf(')');
111
+ const comm = open >= 0 && close > open ? stat.slice(open + 1, close) : null;
112
+ // After the comm field: state(3) ppid(4) ... utime(14) stime(15) ...
113
+ const rest = close > 0 ? stat.slice(close + 2).split(' ') : [];
114
+ const ppidRaw = rest[1] !== undefined ? parseInt(rest[1], 10) : NaN;
115
+ const utime = rest[11] !== undefined ? parseInt(rest[11], 10) : NaN;
116
+ const stime = rest[12] !== undefined ? parseInt(rest[12], 10) : NaN;
117
+ const fields = new Map();
118
+ for (const line of status.split('\n')) {
119
+ const idx = line.indexOf(':');
120
+ if (idx <= 0)
121
+ continue;
122
+ fields.set(line.slice(0, idx).trim(), line.slice(idx + 1).trim());
123
+ }
124
+ const vmRssRaw = fields.get('VmRSS');
125
+ const rssMatch = vmRssRaw ? /^(\d+)\s*kB$/.exec(vmRssRaw) : null;
126
+ const threadsRaw = fields.get('Threads');
127
+ const cmdlineText = typeof cmdline === 'string' ? cmdline : cmdline.toString('utf8');
128
+ // NUL 是 argv 分隔符也是「argv 末尾终止」;空实参因此不可还原(丢弃即已知局限)
129
+ const argv = cmdlineText
130
+ .split('\0')
131
+ .filter((part) => part !== '')
132
+ .join(' ');
133
+ return {
134
+ pid,
135
+ ppid: Number.isInteger(ppidRaw) && ppidRaw >= 0 ? ppidRaw : null,
136
+ command: argv || fields.get('Name') || comm,
137
+ // VmRSS is reported in kB; kernel threads carry no VmRSS line at all
138
+ rssBytes: rssMatch ? parseInt(rssMatch[1], 10) * 1024 : null,
139
+ // Linux USER_HZ is 100 on every shipping kernel (10 ms per tick)
140
+ cpuTimeMs: Number.isInteger(utime) && Number.isInteger(stime) ? (utime + stime) * 10 : null,
141
+ threads: threadsRaw !== undefined && /^\d+$/.test(threadsRaw) ? parseInt(threadsRaw, 10) : null,
142
+ };
143
+ }
144
+ /**
145
+ * Parse the tab-separated `Get-CimInstance Win32_Process` table produced by
146
+ * {@link listProcesses} on win32.
147
+ *
148
+ * Columns: pid, ppid, workingSet, kernelModeTime, userModeTime (100ns units),
149
+ * threadCount, command. A command containing tabs keeps them (join back).
150
+ * Unparseable lines are counted in `skipped`, never dropped silently.
151
+ *
152
+ * @param output - raw powershell stdout
153
+ * @returns parsed entries plus the count of skipped non-empty lines
154
+ */
155
+ export function parsePowerShellProcessTable(output) {
156
+ const entries = [];
157
+ let skipped = 0;
158
+ for (const line of output.split(/\r?\n/)) {
159
+ if (line.trim() === '')
160
+ continue;
161
+ const parts = line.split('\t');
162
+ if (parts.length < 7) {
163
+ skipped += 1;
164
+ continue;
165
+ }
166
+ const pid = parseInt(parts[0], 10);
167
+ const ppid = parseInt(parts[1], 10);
168
+ const ws = parseInt(parts[2], 10);
169
+ const kernel100ns = parseInt(parts[3], 10);
170
+ const user100ns = parseInt(parts[4], 10);
171
+ const threads = parseInt(parts[5], 10);
172
+ if (!Number.isInteger(pid) || pid <= 0) {
173
+ skipped += 1;
174
+ continue;
175
+ }
176
+ entries.push({
177
+ pid,
178
+ ppid: Number.isInteger(ppid) && ppid >= 0 ? ppid : null,
179
+ command: parts.slice(6).join('\t').trim() || null,
180
+ rssBytes: Number.isInteger(ws) && ws >= 0 ? ws : null,
181
+ cpuTimeMs: Number.isInteger(kernel100ns) && Number.isInteger(user100ns)
182
+ ? Math.round((kernel100ns + user100ns) / 10_000)
183
+ : null,
184
+ threads: Number.isInteger(threads) && threads >= 0 ? threads : null,
185
+ });
186
+ }
187
+ return { entries, skipped };
188
+ }
189
+ /**
190
+ * Walk the ppid map from `pid` up to the topmost reachable ancestor (pure).
191
+ *
192
+ * @param ppidByPid - pid → parent pid (null = source reported unknown)
193
+ * @param pid - starting pid (always included as the chain tail)
194
+ * @returns chain (topmost ancestor first, `pid` last) and whether every link resolved
195
+ */
196
+ export function buildAncestorChain(ppidByPid, pid) {
197
+ const upward = [pid];
198
+ const seen = new Set([pid]);
199
+ let complete = true;
200
+ let current = pid;
201
+ for (;;) {
202
+ const parent = ppidByPid.get(current);
203
+ if (parent === undefined || parent === null) {
204
+ complete = false;
205
+ break;
206
+ }
207
+ if (parent <= 0)
208
+ break;
209
+ if (seen.has(parent)) {
210
+ // ppid cycle (racy pid reuse): stop, the chain is already suspect
211
+ complete = false;
212
+ break;
213
+ }
214
+ seen.add(parent);
215
+ upward.push(parent);
216
+ current = parent;
217
+ }
218
+ return { chain: upward.reverse(), complete };
219
+ }
220
+ /**
221
+ * Apply filters, sort and limit to an enumeration (pure; all options honored).
222
+ *
223
+ * @param processes - enumerated entries
224
+ * @param options - filter/sort/limit options
225
+ * @returns selection with totals (`total` = pre-filter, `matched` = post-filter)
226
+ */
227
+ export function selectProcesses(processes, options) {
228
+ let selected = processes;
229
+ if (options?.pids) {
230
+ const wanted = new Set(options.pids);
231
+ selected = selected.filter((p) => wanted.has(p.pid));
232
+ }
233
+ if (options?.nameContains) {
234
+ const needle = options.nameContains.toLowerCase();
235
+ selected = selected.filter((p) => (p.command ?? '').toLowerCase().includes(needle));
236
+ }
237
+ const sorted = [...selected];
238
+ if (options?.sort === 'rss') {
239
+ sorted.sort((a, b) => (b.rssBytes ?? -1) - (a.rssBytes ?? -1) || a.pid - b.pid);
240
+ }
241
+ else {
242
+ sorted.sort((a, b) => a.pid - b.pid);
243
+ }
244
+ const limit = options?.limit;
245
+ if (limit !== undefined && sorted.length > limit) {
246
+ return { selected: sorted.slice(0, limit), total: processes.length, matched: sorted.length, truncated: true };
247
+ }
248
+ return { selected: sorted, total: processes.length, matched: sorted.length, truncated: false };
249
+ }
250
+ function errText(err) {
251
+ return err instanceof Error ? err.message : String(err);
252
+ }
253
+ /**
254
+ * Run a diagnostic binary without a shell (async; bounded output and time).
255
+ *
256
+ * @param file - executable
257
+ * @param args - argv tail
258
+ * @param timeoutMs - hard timeout
259
+ * @param env - explicit environment (never `{...process.env}`)
260
+ * @returns stdout on success, or the error text (callers decide degradation)
261
+ */
262
+ function runCapture(file, args, timeoutMs, env) {
263
+ return new Promise((resolve) => {
264
+ let settled = false;
265
+ const done = (result) => {
266
+ if (settled)
267
+ return;
268
+ settled = true;
269
+ resolve(result);
270
+ };
271
+ try {
272
+ const child = execFile(file, args, { encoding: 'utf8', timeout: timeoutMs, maxBuffer: 32 * 1024 * 1024, windowsHide: true, env }, (err, stdout) => {
273
+ if (err)
274
+ done({ ok: false, error: errText(err) });
275
+ else
276
+ done({ ok: true, stdout });
277
+ });
278
+ child.on('error', (err) => done({ ok: false, error: errText(err) }));
279
+ }
280
+ catch (err) {
281
+ // uv_spawn 同步失败(如牢笼拒 exec setuid 的 EPERM)从这里抛出:
282
+ // 吞成 { ok:false } 即诚实降级,绝不让「看进程」把调用方整个拒掉
283
+ done({ ok: false, error: errText(err) });
284
+ }
285
+ });
286
+ }
287
+ /** ps 的最小环境:剔除 COLUMNS(会截断 command 列)与 PS_PERSONALITY(行为漂移) */
288
+ function psEnv() {
289
+ return { PATH: process.env.PATH ?? '/usr/bin:/bin', LANG: 'C' };
290
+ }
291
+ /** ps `-o thcount` 能力探测缓存(macOS 的 ps 无此关键字,退列是常态路径) */
292
+ let psThcountSupported = null;
293
+ function tableResult(parsed, source, notes) {
294
+ const all = [...notes];
295
+ if (parsed.skipped > 0) {
296
+ // 非空行被跳过 = warning 或坏数据,二者不可分辨 → 一律申报不完整
297
+ all.push(`${parsed.skipped} unparseable ${source} line(s) skipped; listing is partial`);
298
+ return { processes: parsed.entries, source, complete: false, notes: all };
299
+ }
300
+ return { processes: parsed.entries, source, complete: true, notes: all };
301
+ }
302
+ async function listProcessesProcfs() {
303
+ let names;
304
+ try {
305
+ names = readdirSync('/proc');
306
+ }
307
+ catch (err) {
308
+ // procfs 读不到(非 Linux / 隐藏挂载):整源降级,不返回空表冒充成功
309
+ return { processes: [], source: 'procfs', complete: false, notes: [`/proc unreadable: ${errText(err)}`] };
310
+ }
311
+ const notes = [];
312
+ const out = [];
313
+ let denied = 0;
314
+ for (const name of names) {
315
+ if (!/^\d+$/.test(name))
316
+ continue;
317
+ const pid = parseInt(name, 10);
318
+ try {
319
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
320
+ const status = readFileSync(`/proc/${pid}/status`, 'utf8');
321
+ const cmdline = readFileSync(`/proc/${pid}/cmdline`);
322
+ out.push(parseProcPidEntry(pid, stat, status, cmdline));
323
+ }
324
+ catch (err) {
325
+ const code = err?.code;
326
+ if (code === 'ENOENT' || code === 'ESRCH') {
327
+ // 扫描窗口内退出的进程:跳过即事实,不造条目
328
+ continue;
329
+ }
330
+ denied += 1;
331
+ }
332
+ }
333
+ if (denied > 0) {
334
+ // hidepid=2 / 权限收紧:列出的是可见子集,必须申报不完整
335
+ notes.push(`${denied} /proc entries unreadable (permission denied); listing is partial`);
336
+ return { processes: out, source: 'procfs', complete: false, notes };
337
+ }
338
+ return { processes: out, source: 'procfs', complete: true, notes };
339
+ }
340
+ async function listProcessesPs() {
341
+ const colsWith = 'pid=,ppid=,rss=,time=,thcount=,command=';
342
+ const colsWithout = 'pid=,ppid=,rss=,time=,command=';
343
+ if (psThcountSupported !== false) {
344
+ const first = await runCapture('ps', ['-ww', '-axo', colsWith], 10_000, psEnv());
345
+ if (first.ok) {
346
+ psThcountSupported = true;
347
+ return tableResult(parsePsProcessTable(first.stdout, true), 'ps', []);
348
+ }
349
+ }
350
+ // 无 thcount 形态(macOS 即常态):threads 如实为 null。
351
+ // 记忆只在退列成功时落 false——首跑失败也可能是 ps 整体不可用(EPERM),
352
+ // 那不是「关键字不存在」的证据,不能污染能力探测结论。
353
+ const second = await runCapture('ps', ['-ww', '-axo', colsWithout], 10_000, psEnv());
354
+ if (second.ok) {
355
+ psThcountSupported = false;
356
+ return tableResult(parsePsProcessTable(second.stdout, false), 'ps', [
357
+ 'ps has no thcount column on this host; threads=null',
358
+ ]);
359
+ }
360
+ // ps 整体不可用。注意 macOS 牢笼拒 exec setuid 的 ps(OS 不变量)——
361
+ // 引擎进程在牢笼外时走不到这里;agent 侧测试跑在笼内会如实降级。
362
+ return {
363
+ processes: [],
364
+ source: 'ps',
365
+ complete: false,
366
+ notes: [`ps unavailable: ${'error' in second ? second.error : ''}`],
367
+ };
368
+ }
369
+ async function listProcessesPowerShell() {
370
+ const script = 'Get-CimInstance Win32_Process | ForEach-Object { ' +
371
+ '$c = $_.CommandLine; if (-not $c) { $c = $_.Name }; ' +
372
+ '"$($_.ProcessId)`t$($_.ParentProcessId)`t$($_.WorkingSetSize)`t$($_.KernelModeTime)`t$($_.UserModeTime)`t$($_.ThreadCount)`t$c" }';
373
+ const out = await runCapture('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], 20_000, { WINDIR: process.env.WINDIR ?? 'C:\\Windows', SystemRoot: process.env.SystemRoot ?? 'C:\\Windows' });
374
+ if (!out.ok) {
375
+ return { processes: [], source: 'powershell', complete: false, notes: [`powershell unavailable: ${out.error}`] };
376
+ }
377
+ return tableResult(parsePowerShellProcessTable(out.stdout), 'powershell', []);
378
+ }
379
+ /**
380
+ * Enumerate running processes (read-only, engine-side).
381
+ *
382
+ * Sources: Linux `/proc` (works on slim images without `ps`), other POSIX `ps`,
383
+ * win32 `Get-CimInstance`. A source that cannot be read at all degrades
384
+ * honestly (`complete: false` + notes) — never an empty success.
385
+ *
386
+ * @returns the enumeration with its source and degradation notes
387
+ */
388
+ export function listProcesses() {
389
+ if (process.platform === 'linux')
390
+ return listProcessesProcfs();
391
+ if (process.platform === 'win32')
392
+ return listProcessesPowerShell();
393
+ return listProcessesPs();
394
+ }
395
+ /**
396
+ * Find the ancestor chain of a pid (read-only).
397
+ *
398
+ * `process.ppid` is seeded for the caller's own pid so a degraded listing still
399
+ * yields the one link Node already knows.
400
+ *
401
+ * @param pid - target pid
402
+ * @param listed - a fresh enumeration to walk (reuse to avoid a second scan)
403
+ * @returns chain (topmost first, `pid` last) with completeness and source notes
404
+ */
405
+ export async function getAncestorPidChain(pid, listed) {
406
+ const listing = listed ?? (await listProcesses());
407
+ const map = new Map();
408
+ for (const entry of listing.processes)
409
+ map.set(entry.pid, entry.ppid);
410
+ if (pid === process.pid && !map.has(pid)) {
411
+ map.set(pid, typeof process.ppid === 'number' && process.ppid > 0 ? process.ppid : null);
412
+ }
413
+ const built = buildAncestorChain(map, pid);
414
+ return { ...built, notes: listing.notes };
415
+ }
416
+ /**
417
+ * Resolve the executable image of a pid (read-only, best-effort).
418
+ *
419
+ * linux: `/proc/<pid>/exe` readlink (then `ps -o comm=`); darwin: `lsof` txt
420
+ * (then `ps`; lsof is not setuid so it also works inside the Seatbelt jail);
421
+ * win32: `tasklist` name (no path without elevation).
422
+ *
423
+ * @param pid - target pid
424
+ * @returns image path (or bare name where paths are unavailable), null when unresolvable
425
+ */
426
+ export async function resolveProcessImage(pid) {
427
+ if (!Number.isInteger(pid) || pid <= 0)
428
+ return null;
429
+ if (process.platform === 'win32') {
430
+ const out = await runCapture('tasklist', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], 5000, psEnv());
431
+ if (!out.ok) {
432
+ // 进程可能已退出或无权限查询:名字是锦上添花,缺失不阻塞调用方
433
+ return null;
434
+ }
435
+ const line = out.stdout.trim();
436
+ if (!line || line.startsWith('INFO'))
437
+ return null;
438
+ return line.split(',')[0]?.replace(/^"|"$/g, '').trim() || null;
439
+ }
440
+ if (process.platform === 'linux') {
441
+ try {
442
+ const link = readlinkSync(`/proc/${pid}/exe`);
443
+ if (link)
444
+ return link;
445
+ }
446
+ catch {
447
+ // 内核线程/已退出/无权限:落 ps 兜底
448
+ }
449
+ }
450
+ if (process.platform === 'darwin') {
451
+ const viaLsof = await runCapture('/usr/sbin/lsof', ['-p', String(pid), '-a', '-d', 'txt', '-Fn'], 5000, psEnv());
452
+ if (viaLsof.ok) {
453
+ const image = firstExecutableFromLsof(viaLsof.stdout);
454
+ if (image)
455
+ return image;
456
+ }
457
+ // lsof exits non-zero for a vanished pid or a process owned by another
458
+ // user; fall through to ps
459
+ }
460
+ const viaPs = await runCapture('ps', ['-p', String(pid), '-o', 'comm='], 5000, psEnv());
461
+ if (!viaPs.ok) {
462
+ // 进程可能已退出或无权限查询:缺失是可接受降级,不猜
463
+ return null;
464
+ }
465
+ return viaPs.stdout.trim() || null;
466
+ }
@@ -26,6 +26,13 @@ export type PrivilegeIsolation = 'same' | 'dropped';
26
26
  export type EnvHygiene = 'inherit' | 'scrubbed';
27
27
  /** Which backend produced the profile */
28
28
  export type IsolationBackend = 'supervised-spawn' | 'linux-bwrap' | 'mac-seatbelt' | 'win-job' | 'container';
29
+ /**
30
+ * 后端是否构成进程牢笼(vs supervised-spawn 这类「如实无笼」)。
31
+ *
32
+ * @param backend - 隔离画像后端
33
+ * @returns true = 真上笼
34
+ */
35
+ export declare function isJailBackend(backend: IsolationBackend): boolean;
29
36
  /** Honest isolation report for one execute/probe */
30
37
  export interface ProcessIsolationProfile {
31
38
  backend: IsolationBackend;
@@ -8,6 +8,15 @@
8
8
  import { spawn } from 'node:child_process';
9
9
  import { access, constants } from 'node:fs/promises';
10
10
  import { delimiter, join } from 'node:path';
11
+ /**
12
+ * 后端是否构成进程牢笼(vs supervised-spawn 这类「如实无笼」)。
13
+ *
14
+ * @param backend - 隔离画像后端
15
+ * @returns true = 真上笼
16
+ */
17
+ export function isJailBackend(backend) {
18
+ return backend === 'linux-bwrap' || backend === 'mac-seatbelt' || backend === 'win-job' || backend === 'container';
19
+ }
11
20
  /**
12
21
  * L4 process minimum (network is intentionally NOT required).
13
22
  * `filesystem: write-jailed-best-effort` counts as meeting the floor (Windows).