@octopi-agent/engine 0.86.38 → 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 (218) 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/agent.js +12 -5
  21. package/dist/config-schema/context.d.ts +7 -2
  22. package/dist/config-schema/context.js +8 -0
  23. package/dist/config-schema/engine.d.ts +110 -8
  24. package/dist/config-schema/governance.d.ts +43 -1
  25. package/dist/config-schema/governance.js +160 -2
  26. package/dist/config-schema/models.d.ts +7 -4
  27. package/dist/config-schema/models.js +4 -1
  28. package/dist/config-schema/observability.d.ts +9 -0
  29. package/dist/config-schema/observability.js +29 -0
  30. package/dist/config-schema/run.d.ts +3 -0
  31. package/dist/config-schema/run.js +14 -0
  32. package/dist/config-schema/shared.d.ts +3 -0
  33. package/dist/config-schema/shared.js +12 -0
  34. package/dist/config-schema/substrate.d.ts +1 -1
  35. package/dist/config.d.ts +60 -13
  36. package/dist/config.js +81 -78
  37. package/dist/harness/activation/dispatcher.d.ts +8 -2
  38. package/dist/harness/activation/dispatcher.js +33 -5
  39. package/dist/harness/activation/inbox.d.ts +87 -0
  40. package/dist/harness/activation/inbox.js +169 -0
  41. package/dist/harness/activation/runtime.d.ts +9 -8
  42. package/dist/harness/activation/runtime.js +100 -8
  43. package/dist/harness/activation/types.d.ts +19 -0
  44. package/dist/harness/activation/types.js +2 -0
  45. package/dist/harness/agent/builder.d.ts +18 -3
  46. package/dist/harness/agent/builder.js +42 -17
  47. package/dist/harness/agent/config-bridge.d.ts +5 -0
  48. package/dist/harness/agent/config-bridge.js +7 -1
  49. package/dist/harness/agent/config-integrity.d.ts +72 -0
  50. package/dist/harness/agent/config-integrity.js +146 -0
  51. package/dist/harness/agent/tool-purpose.d.ts +9 -1
  52. package/dist/harness/agent/tool-purpose.js +11 -2
  53. package/dist/harness/agent/wire-agent-builder.js +11 -3
  54. package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.d.ts +11 -1
  55. package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.js +11 -1
  56. package/dist/harness/collaboration/autonomous-subsystem/loader.d.ts +13 -0
  57. package/dist/harness/collaboration/autonomous-subsystem/loader.js +16 -1
  58. package/dist/harness/collaboration/autonomous-subsystem/runtime.d.ts +4 -0
  59. package/dist/harness/collaboration/autonomous-subsystem/runtime.js +3 -1
  60. package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -1
  61. package/dist/harness/collaboration/delegation/child-run.js +21 -5
  62. package/dist/harness/collaboration/delegation/notifier.js +4 -3
  63. package/dist/harness/collaboration/delegation/service.js +2 -3
  64. package/dist/harness/collaboration/delegation/wiring.js +6 -5
  65. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.d.ts +1 -1
  66. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.js +1 -1
  67. package/dist/harness/context/capabilities/compact/engine.d.ts +30 -0
  68. package/dist/harness/context/capabilities/compact/engine.js +198 -46
  69. package/dist/harness/context/capabilities/compact/handover.d.ts +78 -0
  70. package/dist/harness/context/capabilities/compact/handover.js +107 -0
  71. package/dist/harness/context/capabilities/compact/index.d.ts +3 -1
  72. package/dist/harness/context/capabilities/compact/index.js +2 -1
  73. package/dist/harness/context/capabilities/compact/types.d.ts +30 -1
  74. package/dist/harness/context/capabilities/summary/executor.js +2 -1
  75. package/dist/harness/context/capabilities/summary/policies.js +8 -5
  76. package/dist/harness/context/constitution/default-agents.md +11 -10
  77. package/dist/harness/context/default-context-engine.d.ts +34 -4
  78. package/dist/harness/context/default-context-engine.js +198 -53
  79. package/dist/harness/context/hybrid-compressor.js +6 -0
  80. package/dist/harness/context/layer-types.d.ts +36 -0
  81. package/dist/harness/context/layer-types.js +38 -0
  82. package/dist/harness/context/llm-summarizer.d.ts +2 -8
  83. package/dist/harness/context/llm-summarizer.js +69 -91
  84. package/dist/harness/context/message-selector.js +4 -3
  85. package/dist/harness/context/root-instructions.js +1 -1
  86. package/dist/harness/context/summarize.d.ts +2 -0
  87. package/dist/harness/context/summarize.js +7 -2
  88. package/dist/harness/context/system-prompt-assembler.js +10 -4
  89. package/dist/harness/context/tool-result-aging.js +2 -2
  90. package/dist/harness/context/truncate-compressor.js +7 -0
  91. package/dist/harness/context/turn-envelope.d.ts +4 -3
  92. package/dist/harness/context/turn-envelope.js +4 -3
  93. package/dist/harness/context/types.d.ts +33 -1
  94. package/dist/harness/extension/execution-environment/dangerous-commands.d.ts +28 -0
  95. package/dist/harness/extension/execution-environment/dangerous-commands.js +129 -0
  96. package/dist/harness/extension/execution-environment/effect-policy.d.ts +133 -4
  97. package/dist/harness/extension/execution-environment/effect-policy.js +263 -14
  98. package/dist/harness/extension/execution-environment/index.d.ts +4 -2
  99. package/dist/harness/extension/execution-environment/index.js +2 -1
  100. package/dist/harness/extension/execution-environment/isolation.js +5 -1
  101. package/dist/harness/extension/execution-environment/kill-switch.d.ts +34 -0
  102. package/dist/harness/extension/execution-environment/kill-switch.js +46 -0
  103. package/dist/harness/extension/execution-environment/ops-audit.d.ts +200 -0
  104. package/dist/harness/extension/execution-environment/ops-audit.js +338 -0
  105. package/dist/harness/extension/execution-environment/privileged-exec.d.ts +158 -0
  106. package/dist/harness/extension/execution-environment/privileged-exec.js +418 -0
  107. package/dist/harness/extension/execution-environment/process-info.d.ts +180 -0
  108. package/dist/harness/extension/execution-environment/process-info.js +466 -0
  109. package/dist/harness/extension/execution-environment/process-isolation.d.ts +7 -0
  110. package/dist/harness/extension/execution-environment/process-isolation.js +9 -0
  111. package/dist/harness/extension/execution-environment/sandbox.d.ts +109 -0
  112. package/dist/harness/extension/execution-environment/sandbox.js +264 -29
  113. package/dist/harness/extension/execution-environment/tool-capabilities.d.ts +1 -1
  114. package/dist/harness/extension/execution-environment/tool-capabilities.js +6 -0
  115. package/dist/harness/extension/execution-environment/types.d.ts +19 -0
  116. package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +5 -0
  117. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.d.ts +6 -0
  118. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.js +50 -0
  119. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.d.ts +4 -5
  120. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.js +5 -15
  121. package/dist/harness/extension/plugin-ecosystem/tools/builtin.d.ts +3 -0
  122. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +53 -2
  123. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +10 -17
  124. package/dist/harness/extension/plugin-ecosystem/tools/git-runner.d.ts +31 -0
  125. package/dist/harness/extension/plugin-ecosystem/tools/git-runner.js +104 -0
  126. package/dist/harness/extension/plugin-ecosystem/tools/git-status-snapshot.d.ts +111 -0
  127. package/dist/harness/extension/plugin-ecosystem/tools/git-status-snapshot.js +197 -0
  128. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.d.ts +8 -8
  129. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +9 -100
  130. package/dist/harness/extension/plugin-ecosystem/tools/index.d.ts +6 -0
  131. package/dist/harness/extension/plugin-ecosystem/tools/index.js +4 -0
  132. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.d.ts +43 -0
  133. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.js +350 -0
  134. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.d.ts +30 -0
  135. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.js +137 -0
  136. package/dist/harness/governance/human-in-the-loop/decision-cache.d.ts +54 -4
  137. package/dist/harness/governance/human-in-the-loop/decision-cache.js +42 -16
  138. package/dist/harness/governance/security/temp-path.d.ts +9 -0
  139. package/dist/harness/governance/security/temp-path.js +13 -2
  140. package/dist/harness/governance/session-acl/seed-roles.js +14 -0
  141. package/dist/harness/index.d.ts +4 -0
  142. package/dist/harness/index.js +3 -0
  143. package/dist/harness/knowledge/file-identity.d.ts +8 -0
  144. package/dist/harness/knowledge/file-identity.js +26 -1
  145. package/dist/harness/knowledge/fts.js +1 -2
  146. package/dist/harness/knowledge/grounding.js +5 -5
  147. package/dist/harness/knowledge/index-store.d.ts +31 -4
  148. package/dist/harness/knowledge/index-store.js +180 -48
  149. package/dist/harness/knowledge/ingest.d.ts +115 -115
  150. package/dist/harness/knowledge/ingest.js +150 -150
  151. package/dist/harness/knowledge/knowledge-serve-child.js +1 -1
  152. package/dist/harness/knowledge/purge.js +4 -1
  153. package/dist/harness/memory/backfill-coverage.js +3 -1
  154. package/dist/harness/memory/sqlite/keyword-search.d.ts +1 -0
  155. package/dist/harness/memory/sqlite/keyword-search.js +4 -3
  156. package/dist/harness/observability/observer/hub.js +38 -1
  157. package/dist/harness/observability/observer/run-snapshot.js +1 -0
  158. package/dist/harness/observability/observer/types.d.ts +27 -0
  159. package/dist/harness/run/agent/agent.d.ts +7 -0
  160. package/dist/harness/run/agent/agent.js +23 -1
  161. package/dist/harness/run/reliability/fallback-provider.d.ts +117 -5
  162. package/dist/harness/run/reliability/fallback-provider.js +262 -22
  163. package/dist/harness/run/reliability/harness-events.d.ts +24 -1
  164. package/dist/harness/run/reliability/model-error-policy.d.ts +32 -0
  165. package/dist/harness/run/reliability/model-error-policy.js +42 -0
  166. package/dist/harness/run/reliability/provider-wrapper.js +29 -2
  167. package/dist/harness/run/reliability/refusal-guard.d.ts +20 -0
  168. package/dist/harness/run/reliability/refusal-guard.js +102 -0
  169. package/dist/harness/run/reliability/run-agent.js +231 -33
  170. package/dist/harness/run/run-guard/default-run-guard.js +1 -1
  171. package/dist/harness/run/run-scope.d.ts +31 -0
  172. package/dist/harness/run/runner.d.ts +132 -2
  173. package/dist/harness/run/runner.js +679 -60
  174. package/dist/harness/session/attachments/llm-intent.js +2 -1
  175. package/dist/harness/session/history/port.js +15 -5
  176. package/dist/harness/session/in-memory-store.d.ts +5 -0
  177. package/dist/harness/session/in-memory-store.js +33 -2
  178. package/dist/harness/session/tasks/render.d.ts +4 -1
  179. package/dist/harness/session/tasks/render.js +10 -7
  180. package/dist/harness/session/title.js +25 -9
  181. package/dist/harness/shared/events/agent-event-map.d.ts +92 -0
  182. package/dist/harness/shared/events/agent-event-map.js +7 -0
  183. package/dist/index.d.ts +6 -4
  184. package/dist/index.js +4 -3
  185. package/dist/integration/agent-runtime/channel-message-source.js +19 -1
  186. package/dist/integration/index.d.ts +2 -0
  187. package/dist/integration/index.js +1 -0
  188. package/dist/integration/observability/loop-watchdog.d.ts +56 -0
  189. package/dist/integration/observability/loop-watchdog.js +177 -0
  190. package/dist/integration/observability/metrics.d.ts +3 -0
  191. package/dist/integration/observability/metrics.js +18 -7
  192. package/dist/integration/observability/run-telemetry.d.ts +8 -0
  193. package/dist/integration/observability/run-telemetry.js +31 -8
  194. package/dist/integration/observability/trace-collector.js +26 -4
  195. package/dist/integration/observability/trace-events.d.ts +1 -0
  196. package/dist/integration/observability/trace-events.js +2 -0
  197. package/dist/integration/observability/trace-logger.js +27 -17
  198. package/dist/integration/providers/anthropic.d.ts +23 -0
  199. package/dist/integration/providers/anthropic.js +97 -12
  200. package/dist/integration/providers/fetch-timeout.d.ts +42 -0
  201. package/dist/integration/providers/fetch-timeout.js +51 -0
  202. package/dist/integration/providers/openai.d.ts +10 -0
  203. package/dist/integration/providers/openai.js +58 -11
  204. package/dist/integration/providers/provider-diagnostics.d.ts +80 -0
  205. package/dist/integration/providers/provider-diagnostics.js +89 -0
  206. package/dist/integration/providers/timeout-coherence.d.ts +52 -0
  207. package/dist/integration/providers/timeout-coherence.js +68 -0
  208. package/dist/integration/providers/wire-dump.d.ts +62 -0
  209. package/dist/integration/providers/wire-dump.js +111 -2
  210. package/dist/integration/storage/jsonl.d.ts +19 -1
  211. package/dist/integration/storage/jsonl.js +100 -4
  212. package/dist/paths.d.ts +19 -0
  213. package/dist/paths.js +38 -1
  214. package/dist/subsystems/cognition-steward/conceptualize/handler.js +1 -1
  215. package/dist/subsystems/memory-steward/backfill/handler.js +1 -1
  216. package/dist/subsystems/safety-guard/config.yaml +3 -1
  217. package/dist/subsystems/wisdom-steward/formation/handler.js +1 -1
  218. package/package.json +3 -2
@@ -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).
@@ -7,6 +7,14 @@
7
7
  */
8
8
  import type { SandboxProvider, SandboxConfig, SandboxResult, IsolationLevel } from './types.js';
9
9
  import { assessL4ProcessMinimum, supervisedSpawnProfile, type ProcessIsolationProfile } from './process-isolation.js';
10
+ /**
11
+ * Run 级失笼降级的归一码前缀(ops P0):probe 缺笼与运行时失笼共用 `no_process_jail`
12
+ * 前缀,消费面按前缀匹配即可覆盖全部失笼路径。
13
+ *
14
+ * @param detail - 失笼细节(jail_setup_failed / jail_spawn_failed / …)
15
+ * @returns 归一后的 securityDegraded 代码
16
+ */
17
+ export declare function jailDegradationCode(detail: string): string;
10
18
  export interface ProcessSandboxOptions {
11
19
  /** Force a profile (tests). Otherwise probes on construct. */
12
20
  profile?: ProcessIsolationProfile;
@@ -41,6 +49,20 @@ export declare class ProcessSandbox implements SandboxProvider {
41
49
  */
42
50
  executeArgv(argv: string[], config?: SandboxConfig): Promise<SandboxResult>;
43
51
  private run;
52
+ /**
53
+ * Attribute a setuid/privilege exec denial on the caller's channels.
54
+ *
55
+ * A jail that does not apply (nested sandbox, wrapper missing) still refuses
56
+ * setuid exec when an **enclosing** jail is in force, so attribution cannot
57
+ * live only in `runSeatbelt`. `denyExec` stays empty there: without proof we
58
+ * own the profile, claiming a specific deny-list entry would be a guess.
59
+ *
60
+ * @param pending - result promise from whichever backend ran
61
+ * @param cwd - run cwd, used to resolve bare command names
62
+ * @param denyExec - deny list we know is in force (empty when unknown)
63
+ * @returns result, with one explanation attached when stderr was attributable
64
+ */
65
+ private withExecDiagnostics;
44
66
  private runSupervised;
45
67
  private runBwrap;
46
68
  private runSeatbelt;
@@ -117,6 +139,93 @@ export declare function buildSeatbeltProfile(roots: string[], network: 'open' |
117
139
  * bwrap supplies its own /dev). Character sinks cannot escape the jail.
118
140
  */
119
141
  export declare const SEATBELT_DEVICE_WRITE_ALLOW: readonly ["/dev/null", "/dev/zero", "/dev/tty", "/dev/stdin", "/dev/stdout", "/dev/stderr"];
142
+ /**
143
+ * Privilege-gaining binaries, grouped by the capability they grant.
144
+ *
145
+ * This is a **cross-platform superset on purpose**, not a survey of the host
146
+ * running it. Two reasons:
147
+ * - Seatbelt's `(literal ...)` matches a path string exactly; it does not
148
+ * normalise `/bin` vs `/usr/bin` or `sbin` vs `bin`. Distributions disagree
149
+ * on all of them (`su` is `/bin/su` on Debian, `/usr/bin/su` on macOS;
150
+ * `chroot` lives under `/usr/sbin` on macOS and additionally under
151
+ * `/usr/bin` / `/sbin` elsewhere). A missing spelling is an open door.
152
+ * - A deny line for a path that does not exist on this host never matches and
153
+ * costs nothing: no error, no runtime penalty. So the asymmetry is one-way —
154
+ * dead entries are free, missing entries are a hole.
155
+ *
156
+ * **Do not trim this list by inspecting one machine.** Every entry that looks
157
+ * dead on macOS is live on some Linux distribution. New privilege-gaining
158
+ * helpers (`pkexec`, `doas`, `run0`, `sudoedit`) are inherited by every jail
159
+ * backend that shares this table, so the risk of a stale entry is the cheaper
160
+ * side of the trade.
161
+ */
162
+ export declare const PRIVILEGE_DENY_EXEC_GROUPS: {
163
+ /** Full privilege switch to any user. */
164
+ readonly su: readonly ["/bin/su", "/usr/bin/su", "/sbin/su"];
165
+ /** Run a command as another user (sudo family). */
166
+ readonly sudo: readonly ["/usr/bin/sudo", "/bin/sudo", "/usr/local/bin/sudo"];
167
+ /** Edit a file as root through sudo. */
168
+ readonly sudoedit: readonly ["/usr/bin/sudoedit", "/bin/sudoedit"];
169
+ /** Polkit-mediated privilege escalation (desktop Linux). */
170
+ readonly pkexec: readonly ["/usr/bin/pkexec", "/usr/local/bin/pkexec"];
171
+ /** Minimal sudo replacement (OpenBSD, Alpine, some Linux). */
172
+ readonly doas: readonly ["/usr/bin/doas", "/usr/local/bin/doas", "/usr/local/sbin/doas"];
173
+ /** systemd-run privilege escalation (systemd >= 256). */
174
+ readonly run0: readonly ["/usr/bin/run0"];
175
+ /** Replace the session, bypassing the caller's credentials. */
176
+ readonly login: readonly ["/usr/bin/login", "/bin/login"];
177
+ /** Change the process group ID without a password. */
178
+ readonly newgrp: readonly ["/usr/bin/newgrp", "/bin/newgrp", "/usr/bin/sg", "/bin/sg"];
179
+ /** Start a process in a different root / namespace. */
180
+ readonly chroot: readonly ["/usr/sbin/chroot", "/usr/bin/chroot", "/sbin/chroot", "/bin/chroot"];
181
+ /** Read or modify the local directory service (macOS account DB). */
182
+ readonly dscl: readonly ["/usr/bin/dscl", "/usr/sbin/dscl"];
183
+ };
184
+ /**
185
+ * Flat deny list in force unless the host overrides it.
186
+ *
187
+ * Derived from {@link PRIVILEGE_DENY_EXEC_GROUPS} so the grouped table stays
188
+ * the single source of truth.
189
+ */
190
+ export declare const DEFAULT_PRIVILEGE_DENY_EXEC: readonly string[];
191
+ /**
192
+ * One denial the jail produced, attributed to the mechanism that caused it.
193
+ *
194
+ * Two mechanisms print `Operation not permitted`, and they need **different**
195
+ * advice:
196
+ * - `setuid-exec` — the OS refuses `execve` of a setuid binary inside
197
+ * Seatbelt. This is a kernel invariant: no profile edit can allow it. `ps`
198
+ * and `top` are setuid on macOS, which is why process listing dies there.
199
+ * - `privilege-deny` — an explicit `(deny process-exec ...)` line written by
200
+ * `buildSeatbeltProfile` for privileged helpers that are **not** setuid
201
+ * (`chroot`, `dscl`); the implicit setuid rule does not cover them.
202
+ *
203
+ * Write and network denials print the same EPERM wording but are left
204
+ * unattributed on purpose — blaming them on exec would misdirect the caller.
205
+ */
206
+ export interface SeatbeltExecDenial {
207
+ /** Absolute path of the denied binary (PATH-resolved when reported bare). */
208
+ target: string;
209
+ /** Which mechanism refused the exec. */
210
+ kind: 'setuid-exec' | 'privilege-deny';
211
+ /** Factual one-liner for the isolation notes (what the jail did). */
212
+ note: string;
213
+ /** Actionable one-liner for the caller (what to do instead). */
214
+ hint: string;
215
+ }
216
+ /**
217
+ * Attribute an exec denial inside the macOS jail so the caller can correct
218
+ * itself without re-discovering the sandbox's invariants by trial and error.
219
+ *
220
+ * @param args - captured stderr, run cwd, and the deny list written into the profile
221
+ * @returns the first attributable denial, or null when EPERM had another cause
222
+ */
223
+ export declare function explainSeatbeltExecDenial(args: {
224
+ stderr: string;
225
+ cwd: string;
226
+ /** Deny list actually emitted into the profile; defaults to the built-in one. */
227
+ denyExec?: readonly string[];
228
+ }): Promise<SeatbeltExecDenial | null>;
120
229
  /**
121
230
  * Create the best process sandbox this host can offer.
122
231
  *