@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,137 @@
1
+ /**
2
+ * process_list 工具 — 只读进程诊断(ops P1)
3
+ *
4
+ * 引擎侧枚举(procfs / ps / powershell),不经 shell 工具:
5
+ * macOS 牢笼拒 exec setuid 的 `ps`,Linux 牢笼在新 pidns 里看不到宿主进程,
6
+ * 「看进程」只能由牢笼外的引擎进程自己做。零权限放松——不杀进程、不改状态。
7
+ *
8
+ * 能力标签为 `host-read`(宿主内省,超出 workspace 信息面):
9
+ * reduced 工具面(untrusted 降级)**剥掉**本工具——argv 是凭证泄漏面
10
+ * (`--token=…`、内联脚本),且引擎侧数据源会绕过牢笼「看不到宿主进程」的边界。
11
+ */
12
+ import { getAncestorPidChain, listProcesses, resolveProcessImage, selectProcesses, } from '../../execution-environment/process-info.js';
13
+ function entryToJson(entry) {
14
+ return {
15
+ pid: entry.pid,
16
+ ppid: entry.ppid,
17
+ command: entry.command,
18
+ rssBytes: entry.rssBytes,
19
+ cpuTimeMs: entry.cpuTimeMs,
20
+ threads: entry.threads,
21
+ };
22
+ }
23
+ /**
24
+ * 创建 process_list 工具
25
+ *
26
+ * 参数:
27
+ * - pid (number, optional): 查单个 pid —— 返回该进程条目 + 祖先链(远祖在前,自身为链尾)+ 可执行映像;不可与其余参数同用
28
+ * - pids (number[], optional): 只列出这些 pid
29
+ * - nameContains (string, optional): 命令行子串过滤(大小写不敏感)
30
+ * - sort ('rss' | 'pid', optional): 排序键,缺省 'rss' 降序(重的在前)
31
+ * - limit (number, optional): 返回上限,缺省 200;截断时 `truncated` 为 true
32
+ *
33
+ * 返回:进程条目(pid/ppid/command/rssBytes/cpuTimeMs/threads)+ matched/total/truncated
34
+ * + source + complete + notes。complete=false 表示来源降级/不全(如牢笼内 ps 被拒、
35
+ * 表行被跳过),此时进程表不可当作「机器上只有这些」。
36
+ * pid 模式另有 chainComplete:祖先链是否每一环都解析到了(与 complete 相互独立)。
37
+ *
38
+ * @returns 注册好的只读工具
39
+ */
40
+ export function createProcessListTool() {
41
+ return {
42
+ definition: {
43
+ name: 'process_list',
44
+ capabilities: ['host-read'],
45
+ description: 'List running processes (read-only host diagnostics; engine-side procfs/ps read, works even where a jailed shell cannot run `ps`). ' +
46
+ 'Fields per entry: pid, ppid, command, rssBytes, cpuTimeMs (cumulative CPU time — no percentage without sampling), threads. ' +
47
+ 'Pass `pid` to inspect one process: returns its entry, its ancestor chain (root-first, ending with the pid itself) and executable image. ' +
48
+ 'Check `complete`: false means the source was degraded/unreadable or dropped unparseable lines and the list is partial or empty — never read it as "nothing is running". ' +
49
+ '`chainComplete` (pid mode) reports whether every ancestor link resolved.',
50
+ parameters: {
51
+ pid: {
52
+ type: 'number',
53
+ minimum: 1,
54
+ description: 'Inspect a single pid: returns that entry plus its ancestor chain and image. Cannot be combined with any other parameter.',
55
+ },
56
+ pids: {
57
+ type: 'array',
58
+ items: { type: 'number', minimum: 1, description: 'pid' },
59
+ description: 'Restrict the listing to these pids (composes with nameContains/sort/limit)',
60
+ },
61
+ nameContains: {
62
+ type: 'string',
63
+ description: 'Case-insensitive substring filter on the command line',
64
+ },
65
+ sort: {
66
+ type: 'string',
67
+ enum: ['rss', 'pid'],
68
+ description: "Sort key: 'rss' (default; heaviest first) or 'pid' (ascending)",
69
+ },
70
+ limit: {
71
+ type: 'number',
72
+ minimum: 1,
73
+ description: 'Maximum entries to return (default 200); `truncated` reports the cut',
74
+ },
75
+ },
76
+ timeoutMs: 60_000,
77
+ },
78
+ handler: async (args) => {
79
+ const pid = args.pid;
80
+ const pids = args.pids;
81
+ const nameContains = args.nameContains;
82
+ const sort = args.sort;
83
+ const limit = args.limit;
84
+ if (pid !== undefined && (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0)) {
85
+ throw new Error(`process_list: pid must be a positive integer, got ${JSON.stringify(pid)}`);
86
+ }
87
+ if (pid !== undefined && (pids !== undefined || nameContains !== undefined || sort !== undefined || limit !== undefined)) {
88
+ throw new Error('process_list: pid cannot be combined with pids/nameContains/sort/limit');
89
+ }
90
+ if (pids !== undefined &&
91
+ (!Array.isArray(pids) || pids.some((p) => typeof p !== 'number' || !Number.isInteger(p) || p <= 0))) {
92
+ throw new Error('process_list: pids must be an array of positive integers');
93
+ }
94
+ if (nameContains !== undefined && (typeof nameContains !== 'string' || nameContains === '')) {
95
+ throw new Error('process_list: nameContains must be a non-empty string');
96
+ }
97
+ if (sort !== undefined && sort !== 'rss' && sort !== 'pid') {
98
+ throw new Error(`process_list: sort must be 'rss' or 'pid', got ${JSON.stringify(sort)}`);
99
+ }
100
+ if (limit !== undefined && (typeof limit !== 'number' || !Number.isInteger(limit) || limit <= 0)) {
101
+ throw new Error(`process_list: limit must be a positive integer, got ${JSON.stringify(limit)}`);
102
+ }
103
+ const listed = await listProcesses();
104
+ if (pid !== undefined) {
105
+ const built = await getAncestorPidChain(pid, listed);
106
+ const found = listed.processes.find((p) => p.pid === pid) ?? null;
107
+ return {
108
+ process: found ? entryToJson(found) : null,
109
+ image: await resolveProcessImage(pid),
110
+ ancestors: built.chain.map((ancestorPid) => ({
111
+ pid: ancestorPid,
112
+ command: listed.processes.find((p) => p.pid === ancestorPid)?.command ?? null,
113
+ })),
114
+ chainComplete: built.complete,
115
+ source: listed.source,
116
+ complete: listed.complete,
117
+ notes: found ? listed.notes : [...listed.notes, `pid ${pid} not present in this enumeration`],
118
+ };
119
+ }
120
+ const selected = selectProcesses(listed.processes, {
121
+ pids: pids,
122
+ nameContains: nameContains,
123
+ sort: sort === 'pid' ? 'pid' : 'rss',
124
+ limit: limit === undefined ? 200 : limit,
125
+ });
126
+ return {
127
+ processes: selected.selected.map(entryToJson),
128
+ matched: selected.matched,
129
+ total: selected.total,
130
+ truncated: selected.truncated,
131
+ source: listed.source,
132
+ complete: listed.complete,
133
+ notes: listed.notes,
134
+ };
135
+ },
136
+ };
137
+ }
@@ -15,6 +15,32 @@ import type { HitlDecision } from '@octopi-agent/core/types/tools.js';
15
15
  export type HitlChannel = 'high_risk' | 'effect';
16
16
  /** Cached scope of a remembered approval */
17
17
  export type HitlCacheScope = 'session' | 'always';
18
+ /** 非人工拒绝来源(人工决策不带此标注);用于错误面与审计如实归因 */
19
+ export type HitlDenyReason = 'no_channel' | 'channel_error' | 'aborted' | 'cancelled';
20
+ /** ask 回调结果:裸决策或带来源/归因标注(同 key 并发合流共享) */
21
+ export interface HitlAskResult {
22
+ decision: HitlDecision;
23
+ /** 确认窗到期(超时=拒绝,T1 硬约束) */
24
+ timedOut?: boolean;
25
+ /** 非人工拒绝来源 */
26
+ denyReason?: HitlDenyReason;
27
+ /** 拒绝来源细节(如宿主 reason 原文) */
28
+ denyDetail?: string;
29
+ /** 确认人署名(随 channel 判读可信度) */
30
+ approver?: string;
31
+ /** 确认通道 */
32
+ channel?: string;
33
+ }
34
+ /** HITL 决策结果(同 key 并发合流共享同一结果对象,杜绝各说各话) */
35
+ export interface HitlOutcome {
36
+ allowed: boolean;
37
+ decision: HitlDecision;
38
+ timedOut: boolean;
39
+ denyReason?: HitlDenyReason;
40
+ denyDetail?: string;
41
+ approver?: string;
42
+ channel?: string;
43
+ }
18
44
  /**
19
45
  * In-memory HITL approval cache.
20
46
  *
@@ -73,16 +99,25 @@ export declare class HitlDecisionCache {
73
99
  clear(): void;
74
100
  /**
75
101
  * Resolve through cache + host hook with in-flight de-dup.
76
- * Concurrent callers for the same key share one `ask()`.
102
+ * Concurrent callers for the same key share one `ask()` and one outcome object
103
+ * (decision + timedOut + attribution — 合流者不得各自编造拒绝来源).
77
104
  */
78
105
  resolve(options: {
79
106
  channel: HitlChannel;
80
107
  key: string;
81
108
  sessionId?: string;
82
109
  agentId?: string;
83
- ask: () => Promise<HitlDecision>;
110
+ ask: () => Promise<HitlDecision | HitlAskResult>;
84
111
  }): Promise<boolean>;
85
- private resolveUncached;
112
+ /** 同 {@link resolve},但回传完整结果(timedOut / 拒绝来源 / 归因),供错误面与审计口径一致。 */
113
+ resolveOutcome(options: {
114
+ channel: HitlChannel;
115
+ key: string;
116
+ sessionId?: string;
117
+ agentId?: string;
118
+ ask: () => Promise<HitlDecision | HitlAskResult>;
119
+ }): Promise<HitlOutcome>;
120
+ private resolveOutcomeUncached;
86
121
  }
87
122
  /** Process-wide default cache (keys include sessionId / agentId). */
88
123
  export declare const defaultHitlCache: HitlDecisionCache;
@@ -101,5 +136,20 @@ export declare function resolveHitlDecision(options: {
101
136
  key: string;
102
137
  sessionId?: string;
103
138
  agentId?: string;
104
- ask: () => Promise<HitlDecision>;
139
+ ask: () => Promise<HitlDecision | HitlAskResult>;
105
140
  }): Promise<boolean>;
141
+ /**
142
+ * 同 {@link resolveHitlDecision},但回传完整结果(timedOut / 拒绝来源 / 归因)——
143
+ * 供调用方把错误面标注得与审计一致:超时 ≠ 人工拒绝 ≠ 通道故障,三者不得混为一谈。
144
+ *
145
+ * @param options - 同 resolveHitlDecision
146
+ * @returns 完整决策结果(同 key 并发合流共享同一对象)
147
+ */
148
+ export declare function resolveHitlOutcome(options: {
149
+ cache?: HitlDecisionCache;
150
+ channel: HitlChannel;
151
+ key: string;
152
+ sessionId?: string;
153
+ agentId?: string;
154
+ ask: () => Promise<HitlDecision | HitlAskResult>;
155
+ }): Promise<HitlOutcome>;
@@ -123,9 +123,14 @@ export class HitlDecisionCache {
123
123
  }
124
124
  /**
125
125
  * Resolve through cache + host hook with in-flight de-dup.
126
- * Concurrent callers for the same key share one `ask()`.
126
+ * Concurrent callers for the same key share one `ask()` and one outcome object
127
+ * (decision + timedOut + attribution — 合流者不得各自编造拒绝来源).
127
128
  */
128
129
  resolve(options) {
130
+ return this.resolveOutcome(options).then((outcome) => outcome.allowed);
131
+ }
132
+ /** 同 {@link resolve},但回传完整结果(timedOut / 拒绝来源 / 归因),供错误面与审计口径一致。 */
133
+ resolveOutcome(options) {
129
134
  const inflightKey = options.sessionId
130
135
  ? sessionKey(options.channel, options.sessionId, options.key)
131
136
  : options.agentId
@@ -134,37 +139,48 @@ export class HitlDecisionCache {
134
139
  const existing = this.inflight.get(inflightKey);
135
140
  if (existing)
136
141
  return existing;
137
- const pending = this.resolveUncached(options).finally(() => {
142
+ const pending = this.resolveOutcomeUncached(options).finally(() => {
138
143
  this.inflight.delete(inflightKey);
139
144
  });
140
145
  this.inflight.set(inflightKey, pending);
141
146
  return pending;
142
147
  }
143
- async resolveUncached(options) {
148
+ async resolveOutcomeUncached(options) {
144
149
  const cached = this.get(options.channel, options.key, {
145
150
  sessionId: options.sessionId,
146
151
  agentId: options.agentId,
147
152
  });
148
- if (cached === 'approve')
149
- return true;
150
- let decision;
153
+ if (cached === 'approve') {
154
+ return { allowed: true, decision: 'approve', timedOut: false };
155
+ }
156
+ let outcome;
151
157
  try {
152
- decision = await options.ask();
158
+ const raw = await options.ask();
159
+ const result = typeof raw === 'string' ? { decision: raw } : raw;
160
+ outcome = {
161
+ allowed: result.decision === 'approve' ||
162
+ result.decision === 'approve_session' ||
163
+ result.decision === 'approve_always',
164
+ decision: result.decision,
165
+ timedOut: result.timedOut ?? false,
166
+ ...(result.denyReason !== undefined ? { denyReason: result.denyReason } : {}),
167
+ ...(result.denyDetail !== undefined ? { denyDetail: result.denyDetail } : {}),
168
+ ...(result.approver !== undefined ? { approver: result.approver } : {}),
169
+ ...(result.channel !== undefined ? { channel: result.channel } : {}),
170
+ };
153
171
  }
154
172
  catch {
155
- // 审批通道异常按拒绝处理(fail-safe);此处吞掉仅因「异常不改变不放行」结论
156
- return false;
173
+ // 审批通道异常按拒绝处理(fail-safe);吞掉异常体只因「不放行」结论不变——
174
+ // 但来源如实标注 channel_error,异常绝不伪装成人工拒绝
175
+ outcome = { allowed: false, decision: 'deny', timedOut: false, denyReason: 'channel_error' };
157
176
  }
158
- if (decision === 'approve' ||
159
- decision === 'approve_session' ||
160
- decision === 'approve_always') {
161
- this.remember(decision, options.channel, options.key, {
177
+ if (outcome.allowed) {
178
+ this.remember(outcome.decision, options.channel, options.key, {
162
179
  sessionId: options.sessionId,
163
180
  agentId: options.agentId,
164
181
  });
165
- return true;
166
182
  }
167
- return false;
183
+ return outcome;
168
184
  }
169
185
  }
170
186
  /** Process-wide default cache (keys include sessionId / agentId). */
@@ -179,6 +195,16 @@ export const defaultHitlCache = new HitlDecisionCache();
179
195
  * @returns true only when the call is approved (cached or live)
180
196
  */
181
197
  export async function resolveHitlDecision(options) {
198
+ return (await resolveHitlOutcome(options)).allowed;
199
+ }
200
+ /**
201
+ * 同 {@link resolveHitlDecision},但回传完整结果(timedOut / 拒绝来源 / 归因)——
202
+ * 供调用方把错误面标注得与审计一致:超时 ≠ 人工拒绝 ≠ 通道故障,三者不得混为一谈。
203
+ *
204
+ * @param options - 同 resolveHitlDecision
205
+ * @returns 完整决策结果(同 key 并发合流共享同一对象)
206
+ */
207
+ export async function resolveHitlOutcome(options) {
182
208
  const cache = options.cache ?? defaultHitlCache;
183
- return cache.resolve(options);
209
+ return cache.resolveOutcome(options);
184
210
  }
@@ -30,6 +30,15 @@ export declare function ensureTrailingSep(p: string): string;
30
30
  * Windows 风格路径大小写不敏感、分隔符归一为 `\`。
31
31
  */
32
32
  export declare function startsWithPathPrefix(path: string, prefix: string): boolean;
33
+ /**
34
+ * 当前用户 home(用户目录推导的单一来源)
35
+ *
36
+ * 实现与测试共用,防两侧推导漂移:env 被清洗(HOME 缺失)时实现落 `homedir()`、
37
+ * 测试若走 `?? ''` 就会分叉(曾在 darwin 上把测试打挂)。
38
+ *
39
+ * @returns 用户 home 目录(原始分隔符风格)
40
+ */
41
+ export declare function currentUserHome(): string;
33
42
  /**
34
43
  * 临时目录前缀清单
35
44
  *
@@ -68,6 +68,18 @@ export function startsWithPathPrefix(path, prefix) {
68
68
  return true;
69
69
  return p.startsWith(b + '/');
70
70
  }
71
+ /**
72
+ * 当前用户 home(用户目录推导的单一来源)
73
+ *
74
+ * 实现与测试共用,防两侧推导漂移:env 被清洗(HOME 缺失)时实现落 `homedir()`、
75
+ * 测试若走 `?? ''` 就会分叉(曾在 darwin 上把测试打挂)。
76
+ *
77
+ * @returns 用户 home 目录(原始分隔符风格)
78
+ */
79
+ export function currentUserHome() {
80
+ // `||` 而非 `??`:HOME 为空串时视为未设置,回落 homedir()(旧实现同语义)
81
+ return process.env.USERPROFILE || process.env.HOME || homedir();
82
+ }
71
83
  /**
72
84
  * 临时目录前缀清单
73
85
  *
@@ -101,8 +113,7 @@ export function getTempPrefixes() {
101
113
  prefixes.push(ensureTrailingSep(systemRoot) + 'Temp\\');
102
114
  }
103
115
  // 用户 AppData Temp(无 TEMP 环境变量时的静态路径)
104
- const userProfile = process.env.USERPROFILE ?? process.env.HOME;
105
- const home = userProfile ? userProfile.replace(/\//g, '\\') : homedir().replace(/\//g, '\\');
116
+ const home = currentUserHome().replace(/\//g, '\\');
106
117
  if (home) {
107
118
  const base = home.endsWith('\\') ? home : home + '\\';
108
119
  prefixes.push(base + 'AppData\\Local\\Temp\\');
@@ -14,6 +14,16 @@ function rights(input) {
14
14
  toolRights: input.toolRights ?? { allow: undefined, deny: [], denyCapabilities: [] },
15
15
  };
16
16
  }
17
+ /**
18
+ * 提权请求者授权(ops §8.6 拍板:T1 缺省仅 owner 可请求):
19
+ * 非 owner 角色默认 deny `priv_exec`——缺权参与者在 toolRights 层即拒,
20
+ * 连确认闸都到不了。owner 显式不受限。
21
+ */
22
+ const NON_OWNER_PRIVILEGE = {
23
+ allow: undefined,
24
+ deny: ['priv_exec'],
25
+ denyCapabilities: [],
26
+ };
17
27
  /** Built-in five-role catalog (v1: no consultant) */
18
28
  export const BUILTIN_SESSION_ROLES = [
19
29
  {
@@ -37,6 +47,7 @@ export const BUILTIN_SESSION_ROLES = [
37
47
  readScope: 'full',
38
48
  writeMemory: true,
39
49
  canManageTasks: true,
50
+ toolRights: NON_OWNER_PRIVILEGE,
40
51
  canHandoff: false,
41
52
  }),
42
53
  },
@@ -49,6 +60,7 @@ export const BUILTIN_SESSION_ROLES = [
49
60
  readScope: 'full',
50
61
  writeMemory: false,
51
62
  canManageTasks: false,
63
+ toolRights: NON_OWNER_PRIVILEGE,
52
64
  canHandoff: false,
53
65
  }),
54
66
  },
@@ -61,6 +73,7 @@ export const BUILTIN_SESSION_ROLES = [
61
73
  readScope: 'none',
62
74
  writeMemory: false,
63
75
  canManageTasks: false,
76
+ toolRights: NON_OWNER_PRIVILEGE,
64
77
  canHandoff: false,
65
78
  }),
66
79
  },
@@ -73,6 +86,7 @@ export const BUILTIN_SESSION_ROLES = [
73
86
  readScope: 'full',
74
87
  writeMemory: true,
75
88
  canManageTasks: true,
89
+ toolRights: NON_OWNER_PRIVILEGE,
76
90
  canHandoff: false,
77
91
  }),
78
92
  },
@@ -47,6 +47,8 @@ export { RunMetricsCollector } from './run/reliability/run-metrics-collector.js'
47
47
  export { CircuitBreaker } from './run/reliability/circuit-breaker.js';
48
48
  export { wrapProviderWithCircuitBreaker } from './run/reliability/provider-wrapper.js';
49
49
  export { FallbackProvider } from './run/reliability/fallback-provider.js';
50
+ export { guardRefusalProvider } from './run/reliability/refusal-guard.js';
51
+ export { detectSummaryContamination } from './context/capabilities/compact/engine.js';
50
52
  export { PluginManager } from './extension/plugin-ecosystem/plugins/manager.js';
51
53
  export { definePluginEntry, defineChannelPluginEntry } from './extension/plugin-ecosystem/plugins/entry.js';
52
54
  export type { OctopiPluginDefinition, OctopiChannelPluginDefinition } from './extension/plugin-ecosystem/plugins/entry.js';
@@ -38,6 +38,8 @@ export { RunMetricsCollector } from './run/reliability/run-metrics-collector.js'
38
38
  export { CircuitBreaker } from './run/reliability/circuit-breaker.js';
39
39
  export { wrapProviderWithCircuitBreaker } from './run/reliability/provider-wrapper.js';
40
40
  export { FallbackProvider } from './run/reliability/fallback-provider.js';
41
+ export { guardRefusalProvider } from './run/reliability/refusal-guard.js';
42
+ export { detectSummaryContamination } from './context/capabilities/compact/engine.js';
41
43
  // ── Plugin Ecosystem ──
42
44
  export { PluginManager } from './extension/plugin-ecosystem/plugins/manager.js';
43
45
  export { definePluginEntry, defineChannelPluginEntry } from './extension/plugin-ecosystem/plugins/entry.js';
@@ -4,9 +4,8 @@
4
4
  * 中文不靠默认分词:索引/查询都写入「词 + CJK 二元组」token 流(对齐 Memory)。
5
5
  * FTS 表非权威;upsert/remove 同步维护,可整库 rebuild。
6
6
  */
7
- import { tokenizeKeywordQuery } from '../memory/sqlite/keyword-search.js';
7
+ import { CJK_RE, tokenizeKeywordQuery } from '../memory/sqlite/keyword-search.js';
8
8
  const TOKEN_SPLIT = /[^\p{L}\p{N}_]+/u;
9
- const CJK_RE = /[㐀-䶿一-鿿豈-﫿぀-ヿ]/;
10
9
  /** 超长 token(base64/uuid/hash/压缩 JS 标识)不进倒排,避免 FTS 膨胀 */
11
10
  const MAX_TOKEN_CHARS = 32;
12
11
  /** 单 chunk token 流上限,防止病态正文写爆 FTS */
@@ -12,6 +12,29 @@ import { toVecBlob } from '../memory/sqlite/sqlite-vec.js';
12
12
  import { asChunkId, asSourceId } from './types.js';
13
13
  import { normalizePathLexical, realIdentitySync } from './file-identity.js';
14
14
  const EMBEDDABLE_WHERE = "(f.adapter_id IS NULL OR f.adapter_id NOT IN ('code-tree'))";
15
+ /** B+ 匹配语义分界:2–3 字符纯 ASCII 字母数字词用词边界,其余用子串(语义细节见 search 兜底注释)。 */
16
+ const SUBSTRING_FALLBACK_MIN_CHARS = 4; // 3 字符(api/db)碰撞面大需边界保护;≥4 起子词召回价值高于碰撞成本
17
+ /**
18
+ * weak-only 命中的绝对相关性地板(scoreKeywordCoverage 口径)。
19
+ * 中文长段查询靠二元组重叠召回是本义(「会话签名校验」须命中「校验会话签名」,4/5 重叠 ≈ 0.57),
20
+ * 但 1–2 个虚词二元组擦边是噪音(≈ 0.14–0.29)——界线 0.3。
21
+ */
22
+ const WEAK_ONLY_SCORE_FLOOR = 0.3;
23
+ /** B+ 分类单源:该 token 是否走词边界语义(兜底 SQL 子句与 JS 判定共用,防语义漂移)。 */
24
+ function isBoundaryToken(token) {
25
+ return token.length < SUBSTRING_FALLBACK_MIN_CHARS && /^[a-z0-9]+$/.test(token);
26
+ }
27
+ /** B+ 语义命中判定:token 是否命中 text/path(与兜底 SQL 子句同源的边界/子串语义)。 */
28
+ function tokenMatchesBPlus(token, text, path) {
29
+ const t = token.toLowerCase();
30
+ const textL = text.toLowerCase();
31
+ const pathL = path.toLowerCase();
32
+ if (isBoundaryToken(token)) {
33
+ const boundary = new RegExp(`(^|[^a-z0-9])${t}([^a-z0-9]|$)`);
34
+ return boundary.test(textL) || boundary.test(pathL);
35
+ }
36
+ return textL.includes(t) || pathL.includes(t);
37
+ }
15
38
  function defaultIdentityKey(path) {
16
39
  try {
17
40
  return `path:${normalizePathLexical(path)}`;
@@ -875,14 +898,34 @@ export class KnowledgeIndexStore {
875
898
  .all(...ftsIds, ...opts.sourceIds);
876
899
  }
877
900
  if (!rows || rows.length === 0) {
878
- const likeClauses = [];
879
- const likeParams = [];
901
+ // 兜底匹配语义(B+):SQL 子串取候选、按 token 分类给精确判定——
902
+ // · 2–3 字符纯 ASCII 字母数字词:词边界命中(防跨词字母碰撞 be ⊂ obeswy)。
903
+ // GLOB 字符类回溯较 LIKE 慢约 10×(20k chunk 实测 235ms vs 23ms),故仅此小类承担,
904
+ // 且只在 FTS 零命中时触发。不用「LIKE 取候选 + JS 边界校验」:LIMIT 窗口会被子串噪音
905
+ // 占满而丢真命中,GLOB 在 SQL 侧精确过滤无此问题。
906
+ // · 其余 token(≥ SUBSTRING_FALLBACK_MIN_CHARS、非纯 ASCII 字母数字):子串命中——
907
+ // 长词保留子词/词干召回(assembly → contextAssembly;其边界命中是子串命中的子集,
908
+ // 词边界子句纯冗余);非 ASCII(CJK/韩/西里尔/混合)无词边界语义,显式并入子串。
909
+ // 边界 = 非 [a-z0-9] 字符(含 _/标点/CJK):_ 与 FTS unicode61 切分一致;CJK 作为边界是
910
+ // **有意放宽**(「api接口」须能命中 api),并非对齐 unicode61(其视 foo文bar 为单 token)。
911
+ // GLOB 不变式由 ^[a-z0-9]+$ 守门:将来 tokenizer 放行 `-`/`.`/`*`/`[`/`]` 等也不会进 GLOB 分支。
912
+ const matchClauses = [];
913
+ const matchParams = [];
880
914
  for (const token of tokens) {
881
- const like = `%${token.toLowerCase().replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
882
- likeClauses.push(`LOWER(c.text) LIKE ? ESCAPE '\\'`);
883
- likeParams.push(like);
884
- likeClauses.push(`LOWER(m.logical_path) LIKE ? ESCAPE '\\'`);
885
- likeParams.push(like);
915
+ if (!isBoundaryToken(token)) {
916
+ const likePattern = `%${token.toLowerCase().replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
917
+ matchClauses.push(`LOWER(c.text) LIKE ? ESCAPE '\\'`);
918
+ matchParams.push(likePattern);
919
+ matchClauses.push(`LOWER(m.logical_path) LIKE ? ESCAPE '\\'`);
920
+ matchParams.push(likePattern);
921
+ }
922
+ else {
923
+ const globPattern = `*[^a-z0-9]${token}[^a-z0-9]*`;
924
+ matchClauses.push(`(' ' || LOWER(c.text) || ' ') GLOB ?`);
925
+ matchParams.push(globPattern);
926
+ matchClauses.push(`(' ' || LOWER(m.logical_path) || ' ') GLOB ?`);
927
+ matchParams.push(globPattern);
928
+ }
886
929
  }
887
930
  rows = this.db.raw
888
931
  .prepare(`SELECT c.id, c.file_id, c.ordinal, c.text, c.start_line, c.end_line,
@@ -891,9 +934,9 @@ export class KnowledgeIndexStore {
891
934
  JOIN knowledge_files f ON f.id = c.file_id AND f.status <> 'indexing'
892
935
  JOIN knowledge_memberships m ON m.file_id = c.file_id
893
936
  WHERE m.source_id IN (${placeholders})
894
- AND (${likeClauses.join(' OR ')})
937
+ AND (${matchClauses.join(' OR ')})
895
938
  LIMIT ?`)
896
- .all(...opts.sourceIds, ...likeParams, Math.max(limit * 8, 64));
939
+ .all(...opts.sourceIds, ...matchParams, Math.max(limit * 8, 64));
897
940
  }
898
941
  const byChunk = new Map();
899
942
  for (const r of rows) {
@@ -901,6 +944,8 @@ export class KnowledgeIndexStore {
901
944
  if (!h) {
902
945
  if (byChunk.size >= limit * 3)
903
946
  continue;
947
+ // 打分仍是子串口径(scoreKeywordCoverage 共享 memory 域):与匹配语义的差异是有意留待统一的
948
+ // 已知项(见 v0.97.2 CHANGELOG 遗留),本层不改共享打分契约。
904
949
  const score = scoreKeywordCoverage({ content: r.text, tags: r.logical_path }, tokenDetail);
905
950
  h = {
906
951
  chunkId: r.id,
@@ -920,7 +965,12 @@ export class KnowledgeIndexStore {
920
965
  h.sourceIds.push(r.source_id);
921
966
  h.logicalPaths[r.source_id] = r.logical_path;
922
967
  }
968
+ // 弱命中地板(执行分词器既有契约:weak 滑窗二元组单独命中不足以过相关性地板):
969
+ // strong 命中直接过;weak-only 命中须过 WEAK_ONLY_SCORE_FLOOR——防中文虚词二元组
970
+ // (的时/是的…)擦边命中灌满结果集,同时保住长段复合查询的二元组重叠召回。
923
971
  return [...byChunk.values()]
972
+ .filter((h) => tokenDetail.strong.some((t) => tokenMatchesBPlus(t, h.text, h.path)) ||
973
+ h.score >= WEAK_ONLY_SCORE_FLOOR)
924
974
  .sort((a, b) => b.score - a.score)
925
975
  .slice(0, limit)
926
976
  .map((h) => ({
@@ -12,6 +12,7 @@ export interface KeywordFields {
12
12
  anchors?: string[] | string | null;
13
13
  evidence?: string | null;
14
14
  }
15
+ export declare const CJK_RE: RegExp;
15
16
  /**
16
17
  * 查询分词:空白/标点切分;连续 CJK 片段额外产出二元组。
17
18
  *
@@ -4,7 +4,7 @@
4
4
  * 中英混合:空格/标点切词 + CJK 二元组,扩大「技术栈 vs 技术选型」类弱重叠召回。
5
5
  * 字段权重:content > future_use/tags > evidence/anchors。
6
6
  */
7
- const CJK_RE = /[㐀-䶿一-鿿豈-﫿぀-ヿ]/;
7
+ export const CJK_RE = /[㐀-䶿一-鿿豈-﫿぀-ヿ]/;
8
8
  function isCjk(ch) {
9
9
  return CJK_RE.test(ch);
10
10
  }
@@ -190,9 +190,10 @@ export function buildKeywordLikeSql(tokens) {
190
190
  const clauses = [];
191
191
  const params = [];
192
192
  for (const token of tokens) {
193
- const like = `%${token.toLowerCase()}%`;
193
+ // LIKE 通配符转义:`_`/`%` 对用户是字面量(get_user_id 不得命中 getXuserXid)
194
+ const like = `%${token.toLowerCase().replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
194
195
  for (const col of columns) {
195
- clauses.push(`${col} LIKE ?`);
196
+ clauses.push(`${col} LIKE ? ESCAPE '\\'`);
196
197
  params.push(like);
197
198
  }
198
199
  }
@@ -50,6 +50,8 @@ const TIMELINE_TYPES = new Set([
50
50
  'engine.start',
51
51
  'engine.end',
52
52
  'engine.error',
53
+ // 模型重试:排查「为什么等了这么久」时,时间线必须能看出重试发生与次数
54
+ 'engine.model_retry',
53
55
  'iteration.start',
54
56
  'turn.end',
55
57
  'tool.exec.start',
@@ -60,6 +62,7 @@ const TIMELINE_TYPES = new Set([
60
62
  'context.compact.start',
61
63
  'context.compact.end',
62
64
  'context.compact.error',
65
+ 'context.compact.summarize_fallback',
63
66
  'context.layers.assembled',
64
67
  'persona.resolve.failed',
65
68
  'injection.detected',
@@ -68,6 +71,10 @@ const TIMELINE_TYPES = new Set([
68
71
  'security.blocked',
69
72
  'security.behavior_blocked',
70
73
  'run.timing',
74
+ // ops P0/P2:jail 意图、降级申报、配置漂移——安全事件必须落 run timeline
75
+ 'ops.jail.state',
76
+ 'ops.policy.degraded',
77
+ 'ops.config.security_changed',
71
78
  ]);
72
79
  let runSeq = 0;
73
80
  /** Hub 兜底:scope 未带 runId 时使用(生产路径应由 Runner/createRunId 提供) */
@@ -525,6 +532,7 @@ export class ObserverHub {
525
532
  const effect = record.toolEffect;
526
533
  effect.cwd = effect.cwd ?? record.scope.toolRuntime?.cwd;
527
534
  effect.isolation = effect.isolation ?? record.scope.toolRuntime?.isolation;
535
+ effect.privileged = effect.privileged ?? record.scope.toolRuntime?.privileged;
528
536
  let row = effect.tools.find((t) => t.name === toolName);
529
537
  if (!row) {
530
538
  row = { name: toolName, calls: 0, errors: 0 };
@@ -29,6 +29,7 @@ export function buildRunScopeView(input) {
29
29
  messagesCount: scope.toolRuntime.messages?.length ?? 0,
30
30
  cwd: scope.toolRuntime.cwd,
31
31
  isolation: scope.toolRuntime.isolation,
32
+ privileged: scope.toolRuntime.privileged,
32
33
  }
33
34
  : undefined,
34
35
  resolvedModel: input.resolvedModel,
@@ -236,6 +236,8 @@ export interface RunToolRuntimeView {
236
236
  messagesCount: number;
237
237
  cwd?: string;
238
238
  isolation?: string;
239
+ /** ops P4:特权部署标记(jail=none / full 档 / root·elevated)——UI 常驻 `PRIVILEGED` */
240
+ privileged?: boolean;
239
241
  }
240
242
  export interface RunScopeView {
241
243
  sessionId: string;
@@ -339,6 +341,8 @@ export interface RunToolEffectView {
339
341
  runId?: string;
340
342
  cwd?: string;
341
343
  isolation?: string;
344
+ /** ops P4:特权部署标记(同 RunToolRuntimeView.privileged) */
345
+ privileged?: boolean;
342
346
  tools: Array<{
343
347
  name: string;
344
348
  calls: number;