@octopi-agent/engine 0.90.11 → 0.98.4

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 (246) 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 +45 -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 +110 -4
  23. package/dist/config-schema/governance.d.ts +45 -1
  24. package/dist/config-schema/governance.js +187 -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 +26 -1
  42. package/dist/harness/agent/builder.js +85 -37
  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 +138 -0
  46. package/dist/harness/agent/config-integrity.js +235 -0
  47. package/dist/harness/agent/wire-agent-builder.js +7 -1
  48. package/dist/harness/collaboration/autonomous-subsystem/index.d.ts +2 -2
  49. package/dist/harness/collaboration/autonomous-subsystem/index.js +1 -1
  50. package/dist/harness/collaboration/autonomous-subsystem/loader.js +3 -0
  51. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +19 -2
  52. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.d.ts +40 -0
  53. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.js +59 -0
  54. package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -1
  55. package/dist/harness/collaboration/autonomous-subsystem/think/index.d.ts +2 -0
  56. package/dist/harness/collaboration/autonomous-subsystem/think/index.js +1 -0
  57. package/dist/harness/collaboration/autonomous-subsystem/think/model-resolver.js +1 -1
  58. package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +9 -0
  59. package/dist/harness/collaboration/delegation/child-run.js +21 -5
  60. package/dist/harness/collaboration/delegation/notifier.js +4 -3
  61. package/dist/harness/collaboration/delegation/service.js +2 -3
  62. package/dist/harness/collaboration/delegation/wiring.js +6 -5
  63. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.d.ts +1 -1
  64. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.js +1 -1
  65. package/dist/harness/context/capabilities/compact/engine.d.ts +30 -0
  66. package/dist/harness/context/capabilities/compact/engine.js +198 -46
  67. package/dist/harness/context/capabilities/compact/handover.d.ts +78 -0
  68. package/dist/harness/context/capabilities/compact/handover.js +107 -0
  69. package/dist/harness/context/capabilities/compact/index.d.ts +3 -1
  70. package/dist/harness/context/capabilities/compact/index.js +2 -1
  71. package/dist/harness/context/capabilities/compact/types.d.ts +30 -1
  72. package/dist/harness/context/capabilities/summary/executor.js +2 -1
  73. package/dist/harness/context/capabilities/summary/policies.js +8 -5
  74. package/dist/harness/context/capabilities/summary/resolver.d.ts +1 -1
  75. package/dist/harness/context/capabilities/summary/resolver.js +4 -4
  76. package/dist/harness/context/capabilities/summary/types.d.ts +2 -2
  77. package/dist/harness/context/constitution/default-agents.md +11 -10
  78. package/dist/harness/context/default-context-engine.d.ts +34 -4
  79. package/dist/harness/context/default-context-engine.js +194 -49
  80. package/dist/harness/context/hybrid-compressor.js +6 -0
  81. package/dist/harness/context/layers.d.ts +2 -4
  82. package/dist/harness/context/layers.js +9 -11
  83. package/dist/harness/context/llm-summarizer.d.ts +2 -8
  84. package/dist/harness/context/llm-summarizer.js +69 -91
  85. package/dist/harness/context/message-selector.js +4 -3
  86. package/dist/harness/context/summarize.d.ts +3 -1
  87. package/dist/harness/context/summarize.js +9 -4
  88. package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
  89. package/dist/harness/context/system-prompt-assembler.js +1 -0
  90. package/dist/harness/context/truncate-compressor.js +7 -0
  91. package/dist/harness/context/turn-envelope.d.ts +3 -2
  92. package/dist/harness/context/turn-envelope.js +3 -2
  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 +149 -8
  97. package/dist/harness/extension/execution-environment/effect-policy.js +274 -19
  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/kill-switch.d.ts +34 -0
  101. package/dist/harness/extension/execution-environment/kill-switch.js +46 -0
  102. package/dist/harness/extension/execution-environment/ops-audit.d.ts +204 -0
  103. package/dist/harness/extension/execution-environment/ops-audit.js +337 -0
  104. package/dist/harness/extension/execution-environment/privileged-exec.d.ts +158 -0
  105. package/dist/harness/extension/execution-environment/privileged-exec.js +418 -0
  106. package/dist/harness/extension/execution-environment/process-info.d.ts +180 -0
  107. package/dist/harness/extension/execution-environment/process-info.js +466 -0
  108. package/dist/harness/extension/execution-environment/process-isolation.d.ts +7 -0
  109. package/dist/harness/extension/execution-environment/process-isolation.js +9 -0
  110. package/dist/harness/extension/execution-environment/sandbox.d.ts +109 -0
  111. package/dist/harness/extension/execution-environment/sandbox.js +228 -21
  112. package/dist/harness/extension/execution-environment/tool-capabilities.d.ts +1 -1
  113. package/dist/harness/extension/execution-environment/tool-capabilities.js +6 -0
  114. package/dist/harness/extension/execution-environment/types.d.ts +19 -0
  115. package/dist/harness/extension/execution-environment/undo-log.d.ts +6 -2
  116. package/dist/harness/extension/execution-environment/undo-log.js +31 -10
  117. package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +5 -0
  118. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.js +33 -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 +70 -26
  123. package/dist/harness/extension/plugin-ecosystem/tools/document-tools.js +3 -9
  124. package/dist/harness/extension/plugin-ecosystem/tools/file-edit.js +3 -6
  125. package/dist/harness/extension/plugin-ecosystem/tools/file-ops.js +9 -5
  126. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +9 -130
  127. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +122 -14
  128. package/dist/harness/extension/plugin-ecosystem/tools/index.d.ts +2 -0
  129. package/dist/harness/extension/plugin-ecosystem/tools/index.js +2 -0
  130. package/dist/harness/extension/plugin-ecosystem/tools/package-tools.js +4 -13
  131. package/dist/harness/extension/plugin-ecosystem/tools/platform.d.ts +25 -11
  132. package/dist/harness/extension/plugin-ecosystem/tools/platform.js +168 -62
  133. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.d.ts +43 -0
  134. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.js +350 -0
  135. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.d.ts +30 -0
  136. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.js +137 -0
  137. package/dist/harness/governance/human-in-the-loop/decision-cache.d.ts +54 -4
  138. package/dist/harness/governance/human-in-the-loop/decision-cache.js +42 -16
  139. package/dist/harness/governance/security/default-risk-policy.d.ts +1 -0
  140. package/dist/harness/governance/security/default-risk-policy.js +1 -0
  141. package/dist/harness/governance/security/default-security-guard.js +9 -0
  142. package/dist/harness/governance/security/index.d.ts +1 -0
  143. package/dist/harness/governance/security/index.js +2 -0
  144. package/dist/harness/governance/security/risk-evaluator.js +13 -0
  145. package/dist/harness/governance/security/risk-types.d.ts +12 -0
  146. package/dist/harness/governance/security/shell-parser-fallback.d.ts +29 -0
  147. package/dist/harness/governance/security/shell-parser-fallback.js +410 -0
  148. package/dist/harness/governance/security/shell-parser-shared.d.ts +83 -0
  149. package/dist/harness/governance/security/shell-parser-shared.js +188 -0
  150. package/dist/harness/governance/security/shell-parser-treesitter.d.ts +52 -0
  151. package/dist/harness/governance/security/shell-parser-treesitter.js +370 -0
  152. package/dist/harness/governance/security/shell-parser.d.ts +23 -10
  153. package/dist/harness/governance/security/shell-parser.js +37 -496
  154. package/dist/harness/governance/security/temp-path.d.ts +9 -0
  155. package/dist/harness/governance/security/temp-path.js +13 -2
  156. package/dist/harness/governance/security/vendor/README.md +24 -0
  157. package/dist/harness/governance/security/vendor/tree-sitter-bash.LICENSE.txt +21 -0
  158. package/dist/harness/governance/security/vendor/tree-sitter-bash.wasm +0 -0
  159. package/dist/harness/governance/session-acl/seed-roles.js +14 -0
  160. package/dist/harness/index.d.ts +2 -0
  161. package/dist/harness/index.js +2 -0
  162. package/dist/harness/knowledge/fts.js +1 -2
  163. package/dist/harness/knowledge/index-store.js +59 -9
  164. package/dist/harness/memory/index.d.ts +6 -2
  165. package/dist/harness/memory/index.js +4 -1
  166. package/dist/harness/memory/memory-events.d.ts +25 -0
  167. package/dist/harness/memory/memory-events.js +38 -0
  168. package/dist/harness/memory/sqlite/agent-db.js +15 -0
  169. package/dist/harness/memory/sqlite/keyword-search.d.ts +1 -0
  170. package/dist/harness/memory/sqlite/keyword-search.js +4 -3
  171. package/dist/harness/memory/sqlite/wisdom-store.d.ts +7 -2
  172. package/dist/harness/memory/sqlite/wisdom-store.js +51 -2
  173. package/dist/harness/memory/steward-policy.d.ts +3 -0
  174. package/dist/harness/memory/steward-policy.js +1 -1
  175. package/dist/harness/memory/types.d.ts +41 -3
  176. package/dist/harness/memory/wisdom-attribution.d.ts +136 -0
  177. package/dist/harness/memory/wisdom-attribution.js +287 -0
  178. package/dist/harness/memory/wisdom-events.d.ts +37 -0
  179. package/dist/harness/memory/wisdom-events.js +61 -0
  180. package/dist/harness/memory/wisdom-formation.d.ts +20 -1
  181. package/dist/harness/memory/wisdom-formation.js +55 -21
  182. package/dist/harness/memory/wisdom.d.ts +7 -2
  183. package/dist/harness/memory/wisdom.js +40 -2
  184. package/dist/harness/observability/observer/hub.js +8 -0
  185. package/dist/harness/observability/observer/run-snapshot.js +1 -0
  186. package/dist/harness/observability/observer/types.d.ts +4 -0
  187. package/dist/harness/run/agent/agent.d.ts +7 -0
  188. package/dist/harness/run/agent/agent.js +23 -1
  189. package/dist/harness/run/reliability/fallback-provider.d.ts +117 -5
  190. package/dist/harness/run/reliability/fallback-provider.js +262 -22
  191. package/dist/harness/run/reliability/harness-events.d.ts +24 -1
  192. package/dist/harness/run/reliability/model-error-policy.d.ts +32 -0
  193. package/dist/harness/run/reliability/model-error-policy.js +42 -0
  194. package/dist/harness/run/reliability/provider-wrapper.js +29 -2
  195. package/dist/harness/run/reliability/refusal-guard.d.ts +20 -0
  196. package/dist/harness/run/reliability/refusal-guard.js +102 -0
  197. package/dist/harness/run/reliability/run-agent.js +231 -33
  198. package/dist/harness/run/run-guard/default-run-guard.js +1 -1
  199. package/dist/harness/run/run-scope.d.ts +35 -0
  200. package/dist/harness/run/runner.d.ts +141 -2
  201. package/dist/harness/run/runner.js +592 -42
  202. package/dist/harness/session/attachments/llm-intent.js +2 -1
  203. package/dist/harness/session/tasks/render.d.ts +4 -1
  204. package/dist/harness/session/tasks/render.js +10 -7
  205. package/dist/harness/shared/events/agent-event-map.d.ts +66 -0
  206. package/dist/harness/shared/events/agent-event-map.js +5 -0
  207. package/dist/harness/shared/paths/glob.d.ts +52 -0
  208. package/dist/harness/shared/paths/glob.js +218 -0
  209. package/dist/harness/shared/paths/index.d.ts +84 -0
  210. package/dist/harness/shared/paths/index.js +179 -0
  211. package/dist/index.d.ts +3 -3
  212. package/dist/index.js +2 -2
  213. package/dist/integration/agent-runtime/channel-message-source.js +19 -1
  214. package/dist/integration/index.d.ts +2 -0
  215. package/dist/integration/index.js +1 -0
  216. package/dist/integration/observability/loop-watchdog.d.ts +56 -0
  217. package/dist/integration/observability/loop-watchdog.js +177 -0
  218. package/dist/integration/observability/metrics.d.ts +3 -0
  219. package/dist/integration/observability/metrics.js +18 -7
  220. package/dist/integration/providers/anthropic.d.ts +23 -0
  221. package/dist/integration/providers/anthropic.js +97 -12
  222. package/dist/integration/providers/fetch-timeout.d.ts +42 -0
  223. package/dist/integration/providers/fetch-timeout.js +51 -0
  224. package/dist/integration/providers/openai.d.ts +10 -0
  225. package/dist/integration/providers/openai.js +58 -11
  226. package/dist/integration/providers/provider-diagnostics.d.ts +80 -0
  227. package/dist/integration/providers/provider-diagnostics.js +89 -0
  228. package/dist/integration/providers/timeout-coherence.d.ts +52 -0
  229. package/dist/integration/providers/timeout-coherence.js +68 -0
  230. package/dist/integration/providers/wire-dump.d.ts +62 -0
  231. package/dist/integration/providers/wire-dump.js +111 -2
  232. package/dist/integration/storage/jsonl.js +4 -1
  233. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +4 -2
  234. package/dist/subsystems/cognition-steward/conceptualize/handler.js +12 -20
  235. package/dist/subsystems/memory-steward/backfill/config.yaml +4 -2
  236. package/dist/subsystems/memory-steward/backfill/handler.js +44 -52
  237. package/dist/subsystems/wisdom-steward/attribute/SUBSYSTEM.md +24 -0
  238. package/dist/subsystems/wisdom-steward/attribute/config.yaml +60 -0
  239. package/dist/subsystems/wisdom-steward/attribute/handler.d.ts +23 -0
  240. package/dist/subsystems/wisdom-steward/attribute/handler.js +167 -0
  241. package/dist/subsystems/wisdom-steward/evaluate/handler.js +3 -1
  242. package/dist/subsystems/wisdom-steward/formation/config.yaml +12 -5
  243. package/dist/subsystems/wisdom-steward/formation/handler.js +12 -18
  244. package/dist/subsystems/wisdom-steward/govern/config.yaml +1 -1
  245. package/dist/subsystems/wisdom-steward/govern/handler.js +4 -0
  246. package/package.json +8 -2
@@ -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
  *
@@ -6,11 +6,21 @@
6
6
  * Public contract: `docs/process-isolation.md`.
7
7
  */
8
8
  import { spawn } from 'node:child_process';
9
- import { realpath, unlink, writeFile } from 'node:fs/promises';
9
+ import { realpath, stat, unlink, writeFile } from 'node:fs/promises';
10
10
  import { homedir, tmpdir } from 'node:os';
11
11
  import { join, resolve } from 'node:path';
12
12
  import { StringDecoder } from 'node:string_decoder';
13
13
  import { assessL4ProcessMinimum, killProcessTree, probeProcessIsolation, scrubEnv, supervisedSpawnProfile, } from './process-isolation.js';
14
+ /**
15
+ * Run 级失笼降级的归一码前缀(ops P0):probe 缺笼与运行时失笼共用 `no_process_jail`
16
+ * 前缀,消费面按前缀匹配即可覆盖全部失笼路径。
17
+ *
18
+ * @param detail - 失笼细节(jail_setup_failed / jail_spawn_failed / …)
19
+ * @returns 归一后的 securityDegraded 代码
20
+ */
21
+ export function jailDegradationCode(detail) {
22
+ return `no_process_jail: ${detail}`;
23
+ }
14
24
  /**
15
25
  * Supervised process runner: tree-killable spawn with scrubbed env.
16
26
  * This is NOT a filesystem jail — `isolation.filesystem` stays `cwd-pin`.
@@ -63,6 +73,22 @@ export class ProcessSandbox {
63
73
  const env = scrubEnv(config?.env, { forceKeys: this.forceEnvKeys });
64
74
  const timeoutMs = config?.limits?.timeoutMs ?? 60_000;
65
75
  const maxOutputBytes = config?.limits?.maxOutputBytes ?? 10 * 1024 * 1024;
76
+ if (config?.disableJail && config?.requireJail) {
77
+ // 库契约守卫:两个都设 = 配置矛盾,绝不静默取舍
78
+ return Promise.reject(new Error('sandbox_config_conflict: disableJail and requireJail are mutually exclusive'));
79
+ }
80
+ // 授权无笼(ops P0:jail=none + privilegedAck 已过配置闸):显式注记,不是降级
81
+ if (config?.disableJail) {
82
+ return this.withExecDiagnostics(this.runSupervised(file, args, config, {
83
+ ...profile,
84
+ backend: 'supervised-spawn',
85
+ processTree: 'killable',
86
+ filesystem: 'cwd-pin',
87
+ privilege: 'same',
88
+ network: 'open',
89
+ notes: [...(profile.notes ?? []), 'jail=disabled_by_config (privileged)'],
90
+ }, { cwd, env, timeoutMs, maxOutputBytes }), cwd, []);
91
+ }
66
92
  // Jail backends wrap the spawn; fall back to supervised spawn.
67
93
  if (profile.backend === 'linux-bwrap' && process.platform === 'linux') {
68
94
  return this.runBwrap(file, args, config, profile, { cwd, env, timeoutMs, maxOutputBytes });
@@ -71,9 +97,44 @@ export class ProcessSandbox {
71
97
  return this.runSeatbelt(file, args, config, profile, { cwd, env, timeoutMs, maxOutputBytes });
72
98
  }
73
99
  if (config?.requireJail) {
74
- return Promise.reject(new Error(`untrusted_jail_failed: no process jail backend (probe=${profile.backend}); refuse unsandboxed execute`));
100
+ return Promise.reject(new Error(`jail_required_unavailable: no process jail backend (probe=${profile.backend}); refuse unsandboxed execute`));
75
101
  }
76
- return this.runSupervised(file, args, config, profile, { cwd, env, timeoutMs, maxOutputBytes });
102
+ // jail 意图落空(auto+degrade):逐条命令如实注记;run 级 securityDegraded
103
+ // 已由 resolveEffectiveEffectPolicy 记 `no_process_jail`(probe 期缺笼)
104
+ return this.withExecDiagnostics(this.runSupervised(file, args, config, {
105
+ ...profile,
106
+ notes: [...(profile.notes ?? []), 'jail=unavailable (supervised-spawn); running unsandboxed'],
107
+ }, { cwd, env, timeoutMs, maxOutputBytes }), cwd, []);
108
+ }
109
+ /**
110
+ * Attribute a setuid/privilege exec denial on the caller's channels.
111
+ *
112
+ * A jail that does not apply (nested sandbox, wrapper missing) still refuses
113
+ * setuid exec when an **enclosing** jail is in force, so attribution cannot
114
+ * live only in `runSeatbelt`. `denyExec` stays empty there: without proof we
115
+ * own the profile, claiming a specific deny-list entry would be a guess.
116
+ *
117
+ * @param pending - result promise from whichever backend ran
118
+ * @param cwd - run cwd, used to resolve bare command names
119
+ * @param denyExec - deny list we know is in force (empty when unknown)
120
+ * @returns result, with one explanation attached when stderr was attributable
121
+ */
122
+ withExecDiagnostics(pending, cwd, denyExec) {
123
+ if (process.platform !== 'darwin')
124
+ return Promise.resolve(pending);
125
+ return Promise.resolve(pending).then(async (result) => {
126
+ const denial = await explainSeatbeltExecDenial({ stderr: result.stderr, cwd, denyExec });
127
+ if (!denial)
128
+ return result;
129
+ return {
130
+ ...result,
131
+ isolation: {
132
+ ...result.isolation,
133
+ notes: [...(result.isolation.notes ?? []), denial.note],
134
+ },
135
+ diagnostics: { hints: [denial.hint] },
136
+ };
137
+ });
77
138
  }
78
139
  runSupervised(file, args, config, profile, opts) {
79
140
  return new Promise((resolve, reject) => {
@@ -182,7 +243,7 @@ export class ProcessSandbox {
182
243
  const usage = this.usage(start, stdoutCaptured, stderrCaptured);
183
244
  const isJailWrapper = profile.backend === 'linux-bwrap' || profile.backend === 'mac-seatbelt';
184
245
  if (config?.requireJail && isJailWrapper) {
185
- fail(new Error(`untrusted_jail_failed: jail spawn failed: ${err.message} (requireJail=true; refuse unsandboxed execute)`));
246
+ fail(new Error(`jail_required_unavailable: jail spawn failed: ${err.message} (requireJail=true; refuse unsandboxed execute)`));
186
247
  return;
187
248
  }
188
249
  const honest = isJailWrapper
@@ -193,8 +254,10 @@ export class ProcessSandbox {
193
254
  notes: [...(profile.notes ?? []), `jail spawn failed: ${err.message}`],
194
255
  }
195
256
  : profile;
196
- if (isJailWrapper)
197
- config?.noteSecurityDegraded?.(`jail_spawn_failed: ${err.message}`);
257
+ // 归一码 no_process_jail(与 jailSetupFailed/jailWrapperRuntimeFailure 同前缀)
258
+ if (isJailWrapper) {
259
+ config?.noteSecurityDegraded?.(jailDegradationCode(`jail_spawn_failed: ${err.message}`));
260
+ }
198
261
  finish({
199
262
  exitCode: -1,
200
263
  stdout,
@@ -263,11 +326,14 @@ export class ProcessSandbox {
263
326
  // Host override wins; otherwise generate a profile covering allowRoots (D3-b+).
264
327
  let profilePath = process.env.OCTOPI_SB_PROFILE;
265
328
  let generatedPath;
329
+ /** Deny list in force, or null when an external profile owns it (unknown). */
330
+ let denyExec = null;
266
331
  if (!profilePath) {
267
332
  generatedPath = join(tmpdir(), `octopi-sb-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.sb`);
268
333
  try {
269
334
  await writeFile(generatedPath, buildSeatbeltProfile(roots, network), { encoding: 'utf8', mode: 0o600 });
270
335
  profilePath = generatedPath;
336
+ denyExec = DEFAULT_PRIVILEGE_DENY_EXEC;
271
337
  }
272
338
  catch (err) {
273
339
  return this.jailSetupFailed(file, args, config, profile, opts, `seatbelt profile generation failed: ${err instanceof Error ? err.message : String(err)}`);
@@ -294,7 +360,11 @@ export class ProcessSandbox {
294
360
  if (isJailWrapperSetupFailure(result, 'sandbox-exec')) {
295
361
  return await this.jailWrapperRuntimeFailure(result, config, profile, `seatbelt apply failed (exit=${result.exitCode}): ${result.stderr.slice(0, 200)}`);
296
362
  }
297
- return result;
363
+ // A real command may have printed EPERM for reasons the caller cannot see
364
+ // from inside the jail (setuid exec is an OS invariant; privileged
365
+ // helpers are denied by the profile). Attribute it once, on the honest
366
+ // channels: isolation notes (what the jail did) + diagnostics (next step).
367
+ return this.withExecDiagnostics(result, opts.cwd, denyExec ?? []);
298
368
  }
299
369
  finally {
300
370
  if (generatedPath) {
@@ -308,7 +378,7 @@ export class ProcessSandbox {
308
378
  */
309
379
  jailSetupFailed(file, args, config, profile, opts, reason) {
310
380
  if (config?.requireJail) {
311
- return Promise.reject(new Error(`untrusted_jail_failed: ${reason} (requireJail=true; refuse unsandboxed execute)`));
381
+ return Promise.reject(new Error(`jail_required_unavailable: ${reason} (requireJail=true; refuse unsandboxed execute)`));
312
382
  }
313
383
  const degraded = {
314
384
  ...profile,
@@ -319,7 +389,8 @@ export class ProcessSandbox {
319
389
  network: 'open',
320
390
  notes: [...(profile.notes ?? []), `jail_setup_failed: ${reason}; supervised fallback`],
321
391
  };
322
- config?.noteSecurityDegraded?.(`jail_setup_failed: ${reason}`);
392
+ // 归一码 no_process_jail:消费面按前缀匹配即可覆盖 probe 缺笼与运行时建笼失败两类路径
393
+ config?.noteSecurityDegraded?.(jailDegradationCode(`jail_setup_failed: ${reason}`));
323
394
  return this.runSupervised(file, args, config, degraded, opts);
324
395
  }
325
396
  /**
@@ -337,9 +408,10 @@ export class ProcessSandbox {
337
408
  */
338
409
  jailWrapperRuntimeFailure(result, config, profile, reason) {
339
410
  if (config?.requireJail) {
340
- return Promise.reject(new Error(`untrusted_jail_failed: ${reason} (requireJail=true; refuse unsandboxed execute)`));
411
+ return Promise.reject(new Error(`jail_required_unavailable: ${reason} (requireJail=true; refuse unsandboxed execute)`));
341
412
  }
342
- config?.noteSecurityDegraded?.(`jail_setup_failed: ${reason}`);
413
+ // 归一码 no_process_jail(同 jailSetupFailed)
414
+ config?.noteSecurityDegraded?.(jailDegradationCode(`jail_setup_failed: ${reason}`));
343
415
  return Promise.resolve({
344
416
  ...result,
345
417
  isolation: {
@@ -520,16 +592,151 @@ export const SEATBELT_DEVICE_WRITE_ALLOW = [
520
592
  '/dev/stdout',
521
593
  '/dev/stderr',
522
594
  ];
523
- /** Common privilege-gaining binaries denied inside Seatbelt (1-B). */
524
- const DEFAULT_PRIVILEGE_DENY_EXEC = [
525
- '/usr/bin/sudo',
526
- '/bin/su',
527
- '/usr/bin/su',
528
- '/usr/sbin/chroot',
529
- '/usr/bin/login',
530
- '/usr/bin/newgrp',
531
- '/usr/bin/dscl',
532
- ];
595
+ /**
596
+ * Privilege-gaining binaries, grouped by the capability they grant.
597
+ *
598
+ * This is a **cross-platform superset on purpose**, not a survey of the host
599
+ * running it. Two reasons:
600
+ * - Seatbelt's `(literal ...)` matches a path string exactly; it does not
601
+ * normalise `/bin` vs `/usr/bin` or `sbin` vs `bin`. Distributions disagree
602
+ * on all of them (`su` is `/bin/su` on Debian, `/usr/bin/su` on macOS;
603
+ * `chroot` lives under `/usr/sbin` on macOS and additionally under
604
+ * `/usr/bin` / `/sbin` elsewhere). A missing spelling is an open door.
605
+ * - A deny line for a path that does not exist on this host never matches and
606
+ * costs nothing: no error, no runtime penalty. So the asymmetry is one-way —
607
+ * dead entries are free, missing entries are a hole.
608
+ *
609
+ * **Do not trim this list by inspecting one machine.** Every entry that looks
610
+ * dead on macOS is live on some Linux distribution. New privilege-gaining
611
+ * helpers (`pkexec`, `doas`, `run0`, `sudoedit`) are inherited by every jail
612
+ * backend that shares this table, so the risk of a stale entry is the cheaper
613
+ * side of the trade.
614
+ */
615
+ export const PRIVILEGE_DENY_EXEC_GROUPS = {
616
+ /** Full privilege switch to any user. */
617
+ su: ['/bin/su', '/usr/bin/su', '/sbin/su'],
618
+ /** Run a command as another user (sudo family). */
619
+ sudo: ['/usr/bin/sudo', '/bin/sudo', '/usr/local/bin/sudo'],
620
+ /** Edit a file as root through sudo. */
621
+ sudoedit: ['/usr/bin/sudoedit', '/bin/sudoedit'],
622
+ /** Polkit-mediated privilege escalation (desktop Linux). */
623
+ pkexec: ['/usr/bin/pkexec', '/usr/local/bin/pkexec'],
624
+ /** Minimal sudo replacement (OpenBSD, Alpine, some Linux). */
625
+ doas: ['/usr/bin/doas', '/usr/local/bin/doas', '/usr/local/sbin/doas'],
626
+ /** systemd-run privilege escalation (systemd >= 256). */
627
+ run0: ['/usr/bin/run0'],
628
+ /** Replace the session, bypassing the caller's credentials. */
629
+ login: ['/usr/bin/login', '/bin/login'],
630
+ /** Change the process group ID without a password. */
631
+ newgrp: ['/usr/bin/newgrp', '/bin/newgrp', '/usr/bin/sg', '/bin/sg'],
632
+ /** Start a process in a different root / namespace. */
633
+ chroot: ['/usr/sbin/chroot', '/usr/bin/chroot', '/sbin/chroot', '/bin/chroot'],
634
+ /** Read or modify the local directory service (macOS account DB). */
635
+ dscl: ['/usr/bin/dscl', '/usr/sbin/dscl'],
636
+ };
637
+ /**
638
+ * Flat deny list in force unless the host overrides it.
639
+ *
640
+ * Derived from {@link PRIVILEGE_DENY_EXEC_GROUPS} so the grouped table stays
641
+ * the single source of truth.
642
+ */
643
+ export const DEFAULT_PRIVILEGE_DENY_EXEC = Object.values(PRIVILEGE_DENY_EXEC_GROUPS).flat();
644
+ /** POSIX binary directories searched for a bare command name. */
645
+ const EXEC_LOOKUP_DIRS = ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'];
646
+ /** Setuid file mode bit. */
647
+ const SETUID_BIT = 0o4000;
648
+ /** Cap on distinct paths probed from one stderr, to bound `stat` cost. */
649
+ const EXEC_DENIAL_PROBE_LIMIT = 8;
650
+ /**
651
+ * Locate a binary the shell named in an EPERM line.
652
+ *
653
+ * @param token - absolute path or bare command name from stderr
654
+ * @param cwd - base for relative paths
655
+ * @returns resolved absolute path with its mode, or null when nothing exists
656
+ */
657
+ async function resolveExecutable(token, cwd) {
658
+ const candidates = token.includes('/')
659
+ ? [resolve(cwd, token)]
660
+ : EXEC_LOOKUP_DIRS.map((dir) => join(dir, token));
661
+ for (const candidate of candidates) {
662
+ try {
663
+ const info = await stat(candidate);
664
+ if (info.isFile())
665
+ return { path: candidate, mode: info.mode };
666
+ }
667
+ catch {
668
+ // Not in this directory — try the next candidate.
669
+ }
670
+ }
671
+ return null;
672
+ }
673
+ /**
674
+ * Extract the subject of each EPERM line.
675
+ *
676
+ * Shells disagree on where the path sits:
677
+ * - bash/sh: `bash: line 1: /usr/bin/top: Operation not permitted`
678
+ * - zsh: `zsh:1: operation not permitted: /usr/bin/top`
679
+ *
680
+ * Deduped and capped: a pathological command can emit thousands of EPERM lines
681
+ * and each candidate costs up to one `stat` per lookup dir.
682
+ *
683
+ * @param stderr - captured stderr
684
+ * @returns distinct paths in emission order
685
+ */
686
+ function extractDeniedTargets(stderr) {
687
+ const targets = new Set();
688
+ for (const raw of stderr.split('\n')) {
689
+ if (targets.size >= EXEC_DENIAL_PROBE_LIMIT)
690
+ break;
691
+ const line = raw.trim();
692
+ if (!/operation not permitted/i.test(line))
693
+ continue;
694
+ const trailing = /(?:^|:)\s*([^\s:][^:\n]*?):\s*operation not permitted$/i.exec(line);
695
+ if (trailing?.[1]) {
696
+ targets.add(trailing[1].trim());
697
+ continue;
698
+ }
699
+ const leading = /operation not permitted:\s*(\S.*)$/i.exec(line);
700
+ if (leading?.[1])
701
+ targets.add(leading[1].trim());
702
+ }
703
+ return [...targets];
704
+ }
705
+ /**
706
+ * Attribute an exec denial inside the macOS jail so the caller can correct
707
+ * itself without re-discovering the sandbox's invariants by trial and error.
708
+ *
709
+ * @param args - captured stderr, run cwd, and the deny list written into the profile
710
+ * @returns the first attributable denial, or null when EPERM had another cause
711
+ */
712
+ export async function explainSeatbeltExecDenial(args) {
713
+ const deny = new Set(args.denyExec ?? DEFAULT_PRIVILEGE_DENY_EXEC);
714
+ for (const token of extractDeniedTargets(args.stderr)) {
715
+ const found = await resolveExecutable(token, args.cwd);
716
+ if (!found)
717
+ continue;
718
+ if (deny.has(found.path)) {
719
+ return {
720
+ target: found.path,
721
+ kind: 'privilege-deny',
722
+ note: `exec_denied: ${found.path} is on the jail privilege deny list`,
723
+ hint: `exec_denied: ${found.path} is on the sandbox privilege deny list (buildSeatbeltProfile) — ` +
724
+ `privileged helpers are blocked by design inside the jail; do not retry, find an unprivileged route.`,
725
+ };
726
+ }
727
+ if ((found.mode & SETUID_BIT) !== 0) {
728
+ return {
729
+ target: found.path,
730
+ kind: 'setuid-exec',
731
+ note: `exec_denied: ${found.path} is setuid; seatbelt refuses setuid exec (macOS invariant)`,
732
+ hint: `exec_denied: ${found.path} is setuid and seatbelt refuses setuid exec — a macOS invariant, ` +
733
+ `not configurable by the profile. Do not retry it; read the same state without exec'ing a ` +
734
+ `setuid binary (e.g. pgrep -fl, lsof, vm_stat, or libproc proc_pidinfo).`,
735
+ };
736
+ }
737
+ }
738
+ return null;
739
+ }
533
740
  function resolveShell() {
534
741
  if (process.platform === 'win32') {
535
742
  const comspec = process.env.COMSPEC || 'cmd.exe';
@@ -10,7 +10,7 @@
10
10
  import type { ToolCapability } from '@octopi-agent/core/types.js';
11
11
  export type { ToolCapability };
12
12
  /** Capabilities that are denied on the reduced tool surface. */
13
- export declare const REDUCED_DENIED_CAPABILITIES: readonly ["exec", "egress", "send", "dynamic-code", "runner"];
13
+ export declare const REDUCED_DENIED_CAPABILITIES: readonly ["exec", "egress", "send", "dynamic-code", "runner", "host-read"];
14
14
  /**
15
15
  * Builtin name → capability tags. Keep in sync with each tool definition's
16
16
  * `capabilities` field (backfilled for every builtin).
@@ -15,6 +15,8 @@ export const REDUCED_DENIED_CAPABILITIES = [
15
15
  'dynamic-code',
16
16
  /** project_run executes workspace-defined scripts (code execution) */
17
17
  'runner',
18
+ /** host introspection (process table/argv) — engine-side data bypasses the jail's "cannot see host processes" boundary */
19
+ 'host-read',
18
20
  ];
19
21
  /**
20
22
  * Builtin name → capability tags. Keep in sync with each tool definition's
@@ -48,6 +50,10 @@ export const BUILTIN_TOOL_CAPABILITIES = {
48
50
  document_read: ['fs-read'],
49
51
  document_probe: ['fs-read'],
50
52
  env_info: ['fs-read'],
53
+ // 只读进程诊断(ops P1):宿主内省(进程表/argv),reduced 面剥掉(host-read)
54
+ process_list: ['host-read'],
55
+ // exec 标签:reduced 面剥掉提权通道(降能力不降墙)
56
+ priv_exec: ['exec'],
51
57
  http_request: ['egress'],
52
58
  web_search: ['egress'],
53
59
  ask_user: [],
@@ -35,6 +35,13 @@ export interface SandboxConfig {
35
35
  * Setup failure throws instead of falling back to supervised spawn.
36
36
  */
37
37
  requireJail?: boolean;
38
+ /**
39
+ * ops P0: authorized no-jail (`effectPolicy.jail: "none"`, privilegedAck
40
+ * already enforced at config resolution). Skips jail wrapping even when a
41
+ * backend is present and notes `jail=disabled_by_config (privileged)` —
42
+ * this is an authorization, never a degradation.
43
+ */
44
+ disableJail?: boolean;
38
45
  /**
39
46
  * Allow `$HOME` writes inside the jail (project/host only per 2b).
40
47
  * tmpdir and, on POSIX, shared `/tmp` + `/var/tmp` are always writable (2a);
@@ -84,6 +91,18 @@ export interface SandboxResult {
84
91
  usage: ResourceUsage;
85
92
  /** Honest isolation actually applied for this run */
86
93
  isolation: ProcessIsolationProfile;
94
+ /** Structured diagnostics; absent when the run explained itself */
95
+ diagnostics?: SandboxDiagnostics;
96
+ }
97
+ /**
98
+ * Structured, machine-readable diagnostics for a sandboxed run.
99
+ *
100
+ * Hints exist so a caller can self-correct on the next attempt instead of
101
+ * re-discovering a sandbox invariant (mirrors `file_search` diagnostics).
102
+ */
103
+ export interface SandboxDiagnostics {
104
+ /** Actionable self-correction hints, one line each */
105
+ hints?: string[];
87
106
  }
88
107
  /**
89
108
  * SandboxProvider — execute commands under an isolation profile.
@@ -119,8 +119,12 @@ export declare class TurnFileUndoLog implements ToolFileEffects {
119
119
  }): Promise<TurnFileUndoLog>;
120
120
  get root(): string;
121
121
  get size(): number;
122
- writeFile(path: string, data: string | Uint8Array): Promise<void>;
123
- appendFile(path: string, data: string | Uint8Array): Promise<void>;
122
+ writeFile(path: string, data: string | Uint8Array, options?: {
123
+ refuseFinalSymlink?: boolean;
124
+ }): Promise<void>;
125
+ appendFile(path: string, data: string | Uint8Array, options?: {
126
+ refuseFinalSymlink?: boolean;
127
+ }): Promise<void>;
124
128
  /** 删除前调用:记 before,discard 时恢复 */
125
129
  recordDelete(path: string, before: string | Uint8Array): Promise<void>;
126
130
  /** 标记新建(零 before);已存在条目则不覆盖 first before */
@@ -9,7 +9,7 @@
9
9
  * 见 arch/tool-effect-policy.md §5.6。
10
10
  */
11
11
  import { createHash, randomBytes } from 'node:crypto';
12
- import { appendFile as fsAppendFile, chmod, mkdir, readFile, realpath, rename, rm, stat, writeFile, } from 'node:fs/promises';
12
+ import { appendFile as fsAppendFile, lstat, chmod, mkdir, readFile, realpath, rename, rm, stat, writeFile, } from 'node:fs/promises';
13
13
  import { join } from 'node:path';
14
14
  import { toSessionFileName } from '@octopi-agent/core/session-filename.js';
15
15
  import { isProbablyText, pathKey, reverseAgentOverwrite } from './undo-merge.js';
@@ -29,15 +29,35 @@ export function resolveSessionUndoPaths(sessionsDir, sessionId) {
29
29
  blobsDir: join(root, 'blobs'),
30
30
  };
31
31
  }
32
+ /**
33
+ * 最终组件为符号链接时拒绝(`refuseFinalSymlink` 开启时)。
34
+ *
35
+ * 检查与 fs 调用之间仍有极小窗口:本守卫的作用是把「包含检查 → 落盘」之间的
36
+ * 长窗口缩到两次相邻 syscall,而不是宣称彻底消除。中间路径段不在覆盖范围内。
37
+ */
38
+ async function assertFinalNotSymlink(path, options) {
39
+ if (options?.refuseFinalSymlink !== true)
40
+ return;
41
+ const entry = await lstat(path).catch(() => undefined);
42
+ if (entry?.isSymbolicLink()) {
43
+ throw new Error(`path_forbidden: "${path}" final component is a symlink (refuseFinalSymlink)`);
44
+ }
45
+ }
32
46
  /**
33
47
  * 原子覆写文件:tmp + rename,单次完整替换。
34
48
  * 防两类撕裂:同路径并发写交错字节、进程中途死掉留半截文件。
35
49
  * 语义差异(已接受):rename 以新 inode 替换目标,断开既有硬链接;
36
- * symlink 归一到实体(realpath)后落盘,保持 writeFile 穿透链接的语义;
50
+ * symlink 归一到实体(realpath)后落盘,保持 writeFile 穿透链接的语义
51
+ * (`refuseFinalSymlink` 开启时不再穿透,改为拒绝);
37
52
  * 既有文件的权限位经 chmod 保留;新建文件走默认 umask。
38
53
  */
39
- async function writeFileAtomic(path, data) {
40
- const target = await realpath(path).catch(() => path);
54
+ async function writeFileAtomic(path, data, options) {
55
+ // 守卫必须先于任何 realpath:realpath 会跟随链接,把「根内链接」解析成
56
+ // 「根外目标」,随后 rename 就落到根外去了。拒绝时直接以原路径为目标,
57
+ // rename 替换的是条目本身,不再穿过链接。
58
+ const refusing = options?.refuseFinalSymlink === true;
59
+ await assertFinalNotSymlink(path, options);
60
+ const target = refusing ? path : await realpath(path).catch(() => path);
41
61
  const mode = await stat(target).then((s) => s.mode & 0o7777).catch(() => undefined);
42
62
  const tmp = `${target}.octopi-tmp-${process.pid}-${randomBytes(6).toString('hex')}`;
43
63
  try {
@@ -153,11 +173,11 @@ export class TurnFileUndoLog {
153
173
  get size() {
154
174
  return this.entriesByPath.size;
155
175
  }
156
- async writeFile(path, data) {
157
- await this.recordWrite(path, data, 'overwrite');
176
+ async writeFile(path, data, options) {
177
+ await this.recordWrite(path, data, 'overwrite', options);
158
178
  }
159
- async appendFile(path, data) {
160
- await this.recordWrite(path, data, 'append');
179
+ async appendFile(path, data, options) {
180
+ await this.recordWrite(path, data, 'append', options);
161
181
  }
162
182
  /** 删除前调用:记 before,discard 时恢复 */
163
183
  async recordDelete(path, before) {
@@ -268,7 +288,7 @@ export class TurnFileUndoLog {
268
288
  }
269
289
  await this.flushLog();
270
290
  }
271
- async recordWrite(path, data, mode) {
291
+ async recordWrite(path, data, mode, options) {
272
292
  if (this.sealed) {
273
293
  throw new Error('turn file undo log already sealed');
274
294
  }
@@ -320,10 +340,11 @@ export class TurnFileUndoLog {
320
340
  }
321
341
  }
322
342
  if (mode === 'append') {
343
+ await assertFinalNotSymlink(path, options);
323
344
  await fsAppendFile(path, next);
324
345
  }
325
346
  else {
326
- await writeFileAtomic(path, next);
347
+ await writeFileAtomic(path, next, options);
327
348
  }
328
349
  await this.flushLog();
329
350
  }
@@ -9,6 +9,7 @@
9
9
  * - Plugin 通过 registerChannel(adapter) 注册实现
10
10
  * - Gateway / Integration 按部署形态挂载具体 adapter
11
11
  */
12
+ export type ChannelMessageDelivery = 'steered' | 'followup' | 'run';
12
13
  export interface ChannelMessage {
13
14
  id: string;
14
15
  channel: string;
@@ -18,6 +19,10 @@ export interface ChannelMessage {
18
19
  conversationId: string;
19
20
  timestamp: number;
20
21
  metadata?: Record<string, unknown>;
22
+ /** Runtime 受理后的真实去向;宿主回执用,不进入模型。 */
23
+ delivery?: ChannelMessageDelivery;
24
+ /** 宿主传入;Runtime 实际受理后由 Gateway 调用。 */
25
+ onDelivery?: (delivery: ChannelMessageDelivery) => void;
21
26
  }
22
27
  export interface ChannelReply {
23
28
  channel: string;