@octopi-agent/engine 0.97.15 → 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 (100) hide show
  1. package/dist/config-schema/agent.d.ts +2 -0
  2. package/dist/config-schema/engine.d.ts +4 -0
  3. package/dist/config-schema/governance.d.ts +2 -0
  4. package/dist/config-schema/governance.js +30 -0
  5. package/dist/harness/agent/builder.d.ts +11 -0
  6. package/dist/harness/agent/builder.js +59 -32
  7. package/dist/harness/agent/config-integrity.d.ts +66 -0
  8. package/dist/harness/agent/config-integrity.js +89 -0
  9. package/dist/harness/agent/wire-agent-builder.js +5 -0
  10. package/dist/harness/collaboration/autonomous-subsystem/index.d.ts +2 -2
  11. package/dist/harness/collaboration/autonomous-subsystem/index.js +1 -1
  12. package/dist/harness/collaboration/autonomous-subsystem/loader.js +3 -0
  13. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +19 -2
  14. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.d.ts +40 -0
  15. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.js +59 -0
  16. package/dist/harness/collaboration/autonomous-subsystem/think/index.d.ts +2 -0
  17. package/dist/harness/collaboration/autonomous-subsystem/think/index.js +1 -0
  18. package/dist/harness/collaboration/autonomous-subsystem/think/model-resolver.js +1 -1
  19. package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +9 -0
  20. package/dist/harness/context/capabilities/summary/resolver.d.ts +1 -1
  21. package/dist/harness/context/capabilities/summary/resolver.js +4 -4
  22. package/dist/harness/context/capabilities/summary/types.d.ts +2 -2
  23. package/dist/harness/context/layers.d.ts +2 -4
  24. package/dist/harness/context/layers.js +9 -11
  25. package/dist/harness/context/summarize.d.ts +1 -1
  26. package/dist/harness/context/summarize.js +2 -2
  27. package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
  28. package/dist/harness/context/system-prompt-assembler.js +1 -0
  29. package/dist/harness/extension/execution-environment/effect-policy.d.ts +24 -2
  30. package/dist/harness/extension/execution-environment/effect-policy.js +30 -0
  31. package/dist/harness/extension/execution-environment/ops-audit.d.ts +6 -2
  32. package/dist/harness/extension/execution-environment/ops-audit.js +11 -12
  33. package/dist/harness/extension/execution-environment/undo-log.d.ts +6 -2
  34. package/dist/harness/extension/execution-environment/undo-log.js +31 -10
  35. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +17 -24
  36. package/dist/harness/extension/plugin-ecosystem/tools/document-tools.js +3 -9
  37. package/dist/harness/extension/plugin-ecosystem/tools/file-edit.js +3 -6
  38. package/dist/harness/extension/plugin-ecosystem/tools/file-ops.js +9 -5
  39. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +9 -130
  40. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +122 -14
  41. package/dist/harness/extension/plugin-ecosystem/tools/package-tools.js +4 -13
  42. package/dist/harness/extension/plugin-ecosystem/tools/platform.d.ts +25 -11
  43. package/dist/harness/extension/plugin-ecosystem/tools/platform.js +168 -62
  44. package/dist/harness/governance/security/default-risk-policy.d.ts +1 -0
  45. package/dist/harness/governance/security/default-risk-policy.js +1 -0
  46. package/dist/harness/governance/security/default-security-guard.js +9 -0
  47. package/dist/harness/governance/security/index.d.ts +1 -0
  48. package/dist/harness/governance/security/index.js +2 -0
  49. package/dist/harness/governance/security/risk-evaluator.js +13 -0
  50. package/dist/harness/governance/security/risk-types.d.ts +12 -0
  51. package/dist/harness/governance/security/shell-parser-fallback.d.ts +29 -0
  52. package/dist/harness/governance/security/shell-parser-fallback.js +410 -0
  53. package/dist/harness/governance/security/shell-parser-shared.d.ts +83 -0
  54. package/dist/harness/governance/security/shell-parser-shared.js +188 -0
  55. package/dist/harness/governance/security/shell-parser-treesitter.d.ts +52 -0
  56. package/dist/harness/governance/security/shell-parser-treesitter.js +370 -0
  57. package/dist/harness/governance/security/shell-parser.d.ts +23 -10
  58. package/dist/harness/governance/security/shell-parser.js +37 -496
  59. package/dist/harness/governance/security/vendor/README.md +24 -0
  60. package/dist/harness/governance/security/vendor/tree-sitter-bash.LICENSE.txt +21 -0
  61. package/dist/harness/governance/security/vendor/tree-sitter-bash.wasm +0 -0
  62. package/dist/harness/memory/index.d.ts +6 -2
  63. package/dist/harness/memory/index.js +4 -1
  64. package/dist/harness/memory/memory-events.d.ts +25 -0
  65. package/dist/harness/memory/memory-events.js +38 -0
  66. package/dist/harness/memory/sqlite/agent-db.js +15 -0
  67. package/dist/harness/memory/sqlite/wisdom-store.d.ts +7 -2
  68. package/dist/harness/memory/sqlite/wisdom-store.js +51 -2
  69. package/dist/harness/memory/steward-policy.d.ts +3 -0
  70. package/dist/harness/memory/steward-policy.js +1 -1
  71. package/dist/harness/memory/types.d.ts +41 -3
  72. package/dist/harness/memory/wisdom-attribution.d.ts +136 -0
  73. package/dist/harness/memory/wisdom-attribution.js +287 -0
  74. package/dist/harness/memory/wisdom-events.d.ts +37 -0
  75. package/dist/harness/memory/wisdom-events.js +61 -0
  76. package/dist/harness/memory/wisdom-formation.d.ts +20 -1
  77. package/dist/harness/memory/wisdom-formation.js +55 -21
  78. package/dist/harness/memory/wisdom.d.ts +7 -2
  79. package/dist/harness/memory/wisdom.js +40 -2
  80. package/dist/harness/run/run-scope.d.ts +4 -0
  81. package/dist/harness/run/runner.d.ts +27 -2
  82. package/dist/harness/run/runner.js +48 -4
  83. package/dist/harness/shared/paths/glob.d.ts +52 -0
  84. package/dist/harness/shared/paths/glob.js +218 -0
  85. package/dist/harness/shared/paths/index.d.ts +84 -0
  86. package/dist/harness/shared/paths/index.js +179 -0
  87. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +4 -2
  88. package/dist/subsystems/cognition-steward/conceptualize/handler.js +12 -20
  89. package/dist/subsystems/memory-steward/backfill/config.yaml +4 -2
  90. package/dist/subsystems/memory-steward/backfill/handler.js +44 -52
  91. package/dist/subsystems/wisdom-steward/attribute/SUBSYSTEM.md +24 -0
  92. package/dist/subsystems/wisdom-steward/attribute/config.yaml +60 -0
  93. package/dist/subsystems/wisdom-steward/attribute/handler.d.ts +23 -0
  94. package/dist/subsystems/wisdom-steward/attribute/handler.js +167 -0
  95. package/dist/subsystems/wisdom-steward/evaluate/handler.js +3 -1
  96. package/dist/subsystems/wisdom-steward/formation/config.yaml +12 -5
  97. package/dist/subsystems/wisdom-steward/formation/handler.js +12 -18
  98. package/dist/subsystems/wisdom-steward/govern/config.yaml +1 -1
  99. package/dist/subsystems/wisdom-steward/govern/handler.js +4 -0
  100. package/package.json +7 -2
@@ -25,6 +25,8 @@ export declare const AgentConfigSchema: z.ZodObject<{
25
25
  strict: "strict";
26
26
  soft: "soft";
27
27
  }>>;
28
+ refuseFinalSymlink: z.ZodOptional<z.ZodBoolean>;
29
+ pathDenylist: z.ZodOptional<z.ZodArray<z.ZodString>>;
28
30
  shellEscape: z.ZodOptional<z.ZodEnum<{
29
31
  deny: "deny";
30
32
  confirm: "confirm";
@@ -32,6 +32,8 @@ export declare const engineConfigSchema: z.ZodObject<{
32
32
  strict: "strict";
33
33
  soft: "soft";
34
34
  }>>;
35
+ refuseFinalSymlink: z.ZodOptional<z.ZodBoolean>;
36
+ pathDenylist: z.ZodOptional<z.ZodArray<z.ZodString>>;
35
37
  shellEscape: z.ZodOptional<z.ZodEnum<{
36
38
  deny: "deny";
37
39
  confirm: "confirm";
@@ -868,6 +870,8 @@ export declare const engineConfigSchema: z.ZodObject<{
868
870
  strict: "strict";
869
871
  soft: "soft";
870
872
  }>>;
873
+ refuseFinalSymlink: z.ZodOptional<z.ZodBoolean>;
874
+ pathDenylist: z.ZodOptional<z.ZodArray<z.ZodString>>;
871
875
  shellEscape: z.ZodOptional<z.ZodEnum<{
872
876
  deny: "deny";
873
877
  confirm: "confirm";
@@ -69,6 +69,8 @@ export declare const EffectPolicyConfigSchema: z.ZodObject<{
69
69
  strict: "strict";
70
70
  soft: "soft";
71
71
  }>>;
72
+ refuseFinalSymlink: z.ZodOptional<z.ZodBoolean>;
73
+ pathDenylist: z.ZodOptional<z.ZodArray<z.ZodString>>;
72
74
  shellEscape: z.ZodOptional<z.ZodEnum<{
73
75
  deny: "deny";
74
76
  confirm: "confirm";
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { z } from 'zod';
7
7
  import { ConfigPathSchema, SessionRightsSchema } from './shared.js';
8
+ import { validateDenyPattern } from '../harness/shared/paths/glob.js';
8
9
  export const SecurityConfigSchema = z.object({
9
10
  enforce: z.enum(['block', 'audit']).optional(),
10
11
  injectionSensitivity: z.enum(['low', 'medium', 'high']).optional(),
@@ -59,6 +60,35 @@ export const EffectPolicyConfigSchema = z.object({
59
60
  /** 额外事务 root(绝对路径或 ~ 形态);并入 allowRoots */
60
61
  transactionRoots: z.array(ConfigPathSchema).optional(),
61
62
  pathContainment: z.enum(['strict', 'soft', 'none']).optional(),
63
+ /**
64
+ * 拒绝最终组件为符号链接的文件读写(读写都拒,非跟随)。
65
+ * 缺省 false;`mode: 'untrusted'` 强制 true 且不可关闭。
66
+ */
67
+ refuseFinalSymlink: z.boolean().optional(),
68
+ /**
69
+ * 拒绝匹配这些 glob 的路径(相对允许根匹配,同时匹配文件名)。
70
+ * 默认空 = 不拒绝任何路径;声明即拒绝,任何 pathContainment 级别都生效。
71
+ *
72
+ * 只收「能真正匹配」的形状:以 `/` 开头/结尾、含 `.`/`..` 段、空串一律在配置
73
+ * 加载期报错——一条永不命中的安全配置比没有配置更危险。
74
+ */
75
+ pathDenylist: z
76
+ .array(z.string())
77
+ .optional()
78
+ .superRefine((patterns, ctx) => {
79
+ patterns?.forEach((pattern, index) => {
80
+ try {
81
+ validateDenyPattern(pattern);
82
+ }
83
+ catch (error) {
84
+ ctx.addIssue({
85
+ code: z.ZodIssueCode.custom,
86
+ path: [index],
87
+ message: error instanceof Error ? error.message : String(error),
88
+ });
89
+ }
90
+ });
91
+ }),
62
92
  shellEscape: z.enum(['deny', 'confirm', 'allow']).optional(),
63
93
  processLimits: z.boolean().optional(),
64
94
  commit: z.enum(['auto', 'manual']).optional(),
@@ -52,6 +52,9 @@ export interface ToolContextProvider {
52
52
  memoryEffects: import('@octopi-agent/core/types/tools.js').MemoryEffectJournal;
53
53
  pathRoots?: string[];
54
54
  pathContainment?: 'strict' | 'soft' | 'none';
55
+ /** 拒绝最终组件为符号链接的文件读写(来自 effectPolicy.refuseFinalSymlink) */
56
+ refuseFinalSymlink?: boolean;
57
+ pathDenylist?: readonly string[];
55
58
  confirmEffect?: import('@octopi-agent/core/types/tools.js').ToolExecutionContext['confirmEffect'];
56
59
  effectChannel?: 'engine' | 'host-gate';
57
60
  /** 提权策略(ops P3/P4,resolved;与 core ToolExecutionContext 同源) */
@@ -195,6 +198,8 @@ export declare class AgentBuilder {
195
198
  private _knowledgeGrounding?;
196
199
  /** 智慧(注入 system prompt WisdomLayer) */
197
200
  private _wisdomStore?;
201
+ /** Wisdom 注入策略(wisdom.injection:core/scenario 上限 + trialVisible) */
202
+ private _wisdomInjection?;
198
203
  /** 认知图谱(注入 system prompt CognitionLayer) */
199
204
  private _cognitionStore?;
200
205
  /** system prompt 装配器调参 */
@@ -351,6 +356,12 @@ export declare class AgentBuilder {
351
356
  }): this;
352
357
  /** 注入 WisdomStore(半静态思维范式,进 system prompt WisdomLayer) */
353
358
  wisdomStore(store: import('../memory/types.js').WisdomStore): this;
359
+ /** 注入策略(wisdom.injection.*:coreMaxItems/scenarioMaxItems/trialVisible) */
360
+ wisdomInjection(cfg: {
361
+ coreMaxItems?: number;
362
+ scenarioMaxItems?: number;
363
+ trialVisible?: boolean;
364
+ }): this;
354
365
  /** 注入 ConceptGraphStore(spreadingActivate 召回概念子图,进 system prompt CognitionLayer) */
355
366
  cognitionStore(store: import('../memory/types.js').ConceptGraphStore): this;
356
367
  /**
@@ -29,6 +29,7 @@ import { createSessionScheduleTools } from '../session/schedules/tools.js';
29
29
  import { InMemorySessionStore } from '../session/in-memory-store.js';
30
30
  import { DefaultEventBus, } from '@octopi-agent/core/primitives/event-bus.js';
31
31
  import { DefaultSecurityGuard, } from '../governance/security/default-security-guard.js';
32
+ import { initShellParser } from '../governance/security/shell-parser.js';
32
33
  import { BudgetPolicyEngine, } from '../run/budget/budget.js';
33
34
  import { PersonaSource } from './persona.js';
34
35
  import { getRunScope } from '../run/run-scope.js';
@@ -108,34 +109,17 @@ class RuntimeToolContextProvider {
108
109
  const unconfigured = createUnconfiguredFileEffects();
109
110
  const unconfiguredMemory = createUnconfiguredMemoryEffects();
110
111
  if (scope?.toolRuntime) {
112
+ // Spread rather than copy field by field: this list has already dropped a
113
+ // newly added security field twice (refuseFinalSymlink, and the gateway's
114
+ // sibling mapping dropped pathContainment/pathRoots). Enumerating is what
115
+ // makes that failure possible, and it fails silently because the field is
116
+ // optional. Everything on RunToolRuntime is context by construction.
111
117
  return {
112
- sessionId: scope.toolRuntime.sessionId,
113
- agentId: scope.toolRuntime.agentId,
118
+ ...scope.toolRuntime,
114
119
  runId: scope.runId,
115
- messages: scope.toolRuntime.messages,
116
120
  cwd: scope.toolRuntime.cwd ?? this.cwd,
117
- attachmentRoots: scope.toolRuntime.attachmentRoots,
118
121
  fileEffects: scope.toolRuntime.fileEffects ?? unconfigured,
119
122
  memoryEffects: scope.toolRuntime.memoryEffects ?? unconfiguredMemory,
120
- pathRoots: scope.toolRuntime.pathRoots,
121
- undoRoots: scope.toolRuntime.undoRoots,
122
- networkPolicy: scope.toolRuntime.networkPolicy,
123
- requireCredentialBindings: scope.toolRuntime.requireCredentialBindings,
124
- requireJail: scope.toolRuntime.requireJail,
125
- disableJail: scope.toolRuntime.disableJail,
126
- homeWrite: scope.toolRuntime.homeWrite,
127
- noteSecurityDegraded: scope.toolRuntime.noteSecurityDegraded,
128
- recordOpsEvent: scope.toolRuntime.recordOpsEvent,
129
- pathContainment: scope.toolRuntime.pathContainment,
130
- confirmEffect: scope.toolRuntime.confirmEffect,
131
- effectChannel: scope.toolRuntime.effectChannel,
132
- escalation: scope.toolRuntime.escalation,
133
- dangerousCommands: scope.toolRuntime.dangerousCommands,
134
- sessionParticipants: scope.toolRuntime.sessionParticipants,
135
- processLimits: scope.toolRuntime.processLimits,
136
- shellEscape: scope.toolRuntime.shellEscape,
137
- shellJournal: scope.toolRuntime.shellJournal,
138
- shellJournalLimit: scope.toolRuntime.shellJournalLimit,
139
123
  };
140
124
  }
141
125
  if (scope) {
@@ -392,6 +376,8 @@ export class AgentBuilder {
392
376
  _knowledgeGrounding;
393
377
  /** 智慧(注入 system prompt WisdomLayer) */
394
378
  _wisdomStore;
379
+ /** Wisdom 注入策略(wisdom.injection:core/scenario 上限 + trialVisible) */
380
+ _wisdomInjection;
395
381
  /** 认知图谱(注入 system prompt CognitionLayer) */
396
382
  _cognitionStore;
397
383
  /** system prompt 装配器调参 */
@@ -625,6 +611,11 @@ export class AgentBuilder {
625
611
  this._wisdomStore = store;
626
612
  return this;
627
613
  }
614
+ /** 注入策略(wisdom.injection.*:coreMaxItems/scenarioMaxItems/trialVisible) */
615
+ wisdomInjection(cfg) {
616
+ this._wisdomInjection = cfg;
617
+ return this;
618
+ }
628
619
  /** 注入 ConceptGraphStore(spreadingActivate 召回概念子图,进 system prompt CognitionLayer) */
629
620
  cognitionStore(store) {
630
621
  this._cognitionStore = store;
@@ -842,6 +833,8 @@ export class AgentBuilder {
842
833
  const mode = options?.mode ?? 'full';
843
834
  const events = this._events ?? new DefaultEventBus();
844
835
  this._events = events;
836
+ // Shell 解析引擎(安全风险评估依赖;失败自动降级 legacy,不阻断构建)
837
+ await initShellParser();
845
838
  // 并发控制:ProviderPool
846
839
  if (this._concurrencyConfig?.providerPool && this._namedProviders.size > 0) {
847
840
  const { ProviderPool } = await import('../run/concurrency/provider-pool.js');
@@ -903,17 +896,32 @@ export class AgentBuilder {
903
896
  gates: memCfg?.gates?.maxLength
904
897
  ? { maxLength: memCfg.gates.maxLength }
905
898
  : undefined,
906
- onStored: this._cognitionStore && events
899
+ onStored: events
907
900
  ? (info) => {
908
- void import('../memory/cognition-trigger.js')
909
- .then(({ emitConceptualizeRequest }) => {
910
- emitConceptualizeRequest(events, {
901
+ // 概念化请求只在 cognitionStore 存在时发(否则 conceptualize handler 无 store 会抛错)
902
+ if (this._cognitionStore) {
903
+ void import('../memory/cognition-trigger.js')
904
+ .then(({ emitConceptualizeRequest }) => {
905
+ emitConceptualizeRequest(events, {
906
+ memoryId: info.id,
907
+ proposition: info.proposition,
908
+ evidence: info.evidence,
909
+ memoryType: info.type,
910
+ memoryStatus: info.status,
911
+ channel: info.channel,
912
+ sessionId: info.sessionId,
913
+ });
914
+ })
915
+ .catch(() => {
916
+ // 动态加载失败不阻断 memory 写
917
+ });
918
+ }
919
+ void import('../memory/memory-events.js')
920
+ .then(({ emitMemoryStored }) => {
921
+ emitMemoryStored(events, {
911
922
  memoryId: info.id,
912
- proposition: info.proposition,
913
- evidence: info.evidence,
914
- memoryType: info.type,
915
- memoryStatus: info.status,
916
- channel: info.channel,
923
+ type: info.type,
924
+ status: info.status,
917
925
  sessionId: info.sessionId,
918
926
  });
919
927
  })
@@ -1012,6 +1020,9 @@ export class AgentBuilder {
1012
1020
  knowledgeGroupByScope: this._knowledgeCatalogOpts?.groupByScope,
1013
1021
  knowledgeShowProgress: this._knowledgeCatalogOpts?.showProgress,
1014
1022
  wisdomStore,
1023
+ wisdomCoreMaxItems: this._wisdomInjection?.coreMaxItems,
1024
+ wisdomScenarioMaxItems: this._wisdomInjection?.scenarioMaxItems,
1025
+ wisdomIncludeTrial: this._wisdomInjection?.trialVisible,
1015
1026
  cognitionStore,
1016
1027
  systemBudgetRatio: assemblerCfg?.systemBudgetRatio,
1017
1028
  systemBudgetTokens: assemblerCfg?.systemBudgetTokens,
@@ -1025,6 +1036,18 @@ export class AgentBuilder {
1025
1036
  },
1026
1037
  });
1027
1038
  runner.setSystemPromptAssembler((input) => systemPromptAssembler.assemble(input), (sid) => systemPromptAssembler.clearSession(sid));
1039
+ // Wisdom 归因窗口记账(学习环):run 收尾 → 窗口落库,待判官批量判决
1040
+ if (wisdomStore) {
1041
+ runner.setWisdomAttributionSink(async (info) => {
1042
+ try {
1043
+ const { recordWisdomRunWindow } = await import('../memory/wisdom-attribution.js');
1044
+ await recordWisdomRunWindow(wisdomStore, info);
1045
+ }
1046
+ catch {
1047
+ // 归因记账失败不得拖垮 run 收口
1048
+ }
1049
+ });
1050
+ }
1028
1051
  // turn 级 Knowledge grounding(消息插槽 knowledgeGrounding;不进 system)
1029
1052
  const groundingPort = this._knowledgeGroundingPort ?? this._knowledgeRetriever;
1030
1053
  if (groundingPort) {
@@ -1136,6 +1159,10 @@ export class AgentBuilder {
1136
1159
  if (this._cognitionStore) {
1137
1160
  subsystemRuntime.registerDependency('conceptGraphStore', this._cognitionStore);
1138
1161
  }
1162
+ {
1163
+ // eventBus 注入:steward handler 发 memory.stored 等信号用(可选依赖,缺失时静默跳过)
1164
+ subsystemRuntime.registerDependency('eventBus', events);
1165
+ }
1139
1166
  {
1140
1167
  const { InMemoryBackfillCoverageStore } = await import('../memory/backfill-coverage.js');
1141
1168
  let coverage = this._backfillCoverage;
@@ -22,6 +22,19 @@ export interface SecurityConfigDrift {
22
22
  /** 当前指纹(审计记录的「新摘要」) */
23
23
  currentFingerprint: string;
24
24
  }
25
+ /**
26
+ * effectPolicy 中**不进热应用**的子字段(§4.3.1:需重启 + 宿主确认)。
27
+ *
28
+ * 判据是 §4.3.1 **明列**的安全闸 + 注释明确「须重启 + 宿主署名」的字段,**不是**整个
29
+ * 指纹范围(EFFECT_POLICY_SECURITY_KEYS)——指纹范围只回答「哪些字段变化算漂移」,
30
+ * 热应用禁区回答「哪些字段改了必须重启确认」,两者不可混用(把 shellEscape 等一并
31
+ * 划入禁区会误拒 WebUI 的合法合并编辑)。
32
+ *
33
+ * `mode` 允许热改(WebUI「安全组」四选一);`shellEscape` / `untrustedAdmission` /
34
+ * `pathContainment` / `toolIsolation` / `network` 是普通配置旋钮,允许热改(仍在指纹内,
35
+ * 改了会重锚)。ApplyEngine 据此拒绝禁区字段(评审 M2 补全此前缺失的拒绝逻辑)。
36
+ */
37
+ export declare const EFFECT_POLICY_HOT_BLOCKED_KEYS: readonly string[];
25
38
  /**
26
39
  * 计算安全配置指纹(启动期锚定)。
27
40
  *
@@ -70,3 +83,56 @@ export declare function createFileSecurityIntegrity(options: {
70
83
  configPath: string;
71
84
  anchor: SecurityConfigFingerprint;
72
85
  }): () => SecurityConfigDrift;
86
+ /**
87
+ * 可重锚定守卫(ops P2 §8.4「WebUI 署名通道」落地):启动锚定 → 每 run 复核 →
88
+ * 受控写通道写盘成功后 {@link SecurityIntegrityGuard.reattest} 重新锚定。
89
+ *
90
+ * 威胁模型边界:reattest 的调用方是宿主的受控写通道(console 管理面,带鉴权),
91
+ * 等价于人工重启的署名确认;agent 绕过通道直改文件依然被 recheck 判漂移(拒新 run 不变)。
92
+ */
93
+ export interface SecurityIntegrityGuard {
94
+ /** 当前锚定指纹(活视图:reattest 后更新;漂移审计的「旧摘要」读它) */
95
+ readonly fingerprint: string;
96
+ /** 复核当前安全配置(读不到/解析失败按漂移对待,fail-closed) */
97
+ recheck(): SecurityConfigDrift;
98
+ /**
99
+ * 受控写通道写盘成功后重新锚定。
100
+ *
101
+ * 两道校验(缺一不可,评审 M1):
102
+ * - `expectHash`:写盘方给出的写后原文 hash。rename 与重锚之间若有第三方写入
103
+ * (TOCTOU),hash 不符 → 拒绝重锚。
104
+ * - `allowedChanged`:允许被本次写改变的顶层安全字段。changed 超出白名单 =
105
+ * 既存篡改或越权写(正是 §8.4 要防的自提权面)→ 拒绝重锚,防止一次无关的
106
+ * console 写把已存在的漂移「洗白」。
107
+ *
108
+ * 两者任一不符即抛错:调用方降级为 warning,守卫维持漂移态(fail-closed),
109
+ * 直至宿主重启采纳盘上配置。
110
+ *
111
+ * @param options - 校验参数(见上)
112
+ * @returns 旧→新指纹与变化字段
113
+ * @throws 校验不符 / 盘上文件读不到
114
+ */
115
+ reattest(options?: {
116
+ /** 写后原文 hash(`computeConfigHash`);不符 = TOCTOU,拒绝重锚 */
117
+ expectHash?: string;
118
+ /**
119
+ * 允许变化的顶层安全字段(`'agents'` | `'effectPolicy'` | `'security'` | `'plugins'`)。
120
+ * 省略 = 不限(仅宿主显式全量确认,如重启采纳盘上配置)
121
+ */
122
+ allowedChanged?: string[];
123
+ }): {
124
+ previousFingerprint: string;
125
+ fingerprint: string;
126
+ changed: string[];
127
+ };
128
+ }
129
+ /**
130
+ * 基于配置文件的可重锚定守卫。
131
+ *
132
+ * @param options.configPath - 配置文件绝对路径
133
+ * @returns 守卫(锚定与复核同口径:都取 raw 文件安全切面)
134
+ * @throws 启动期文件读不到/解析失败(fail-fast,与锚定即拒绝启动的既有语义一致)
135
+ */
136
+ export declare function createSecurityIntegrityGuard(options: {
137
+ configPath: string;
138
+ }): SecurityIntegrityGuard;
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import { readFileSync } from 'node:fs';
11
11
  import { createHash } from 'node:crypto';
12
+ import { computeConfigHash } from '../../config-admin/patch.js';
12
13
  /**
13
14
  * 参与指纹的安全字段(§8.4:jail / escalation / effects / 审计开关 + 作用域面)。
14
15
  * 键序无关;值走稳定序列化。
@@ -33,6 +34,32 @@ const EFFECT_POLICY_SECURITY_KEYS = [
33
34
  'dangerousCommands',
34
35
  ];
35
36
  const SECURITY_CONFIG_SECURITY_KEYS = ['enforce', 'injectionSensitivity', 'allowedPaths'];
37
+ /**
38
+ * effectPolicy 中**不进热应用**的子字段(§4.3.1:需重启 + 宿主确认)。
39
+ *
40
+ * 判据是 §4.3.1 **明列**的安全闸 + 注释明确「须重启 + 宿主署名」的字段,**不是**整个
41
+ * 指纹范围(EFFECT_POLICY_SECURITY_KEYS)——指纹范围只回答「哪些字段变化算漂移」,
42
+ * 热应用禁区回答「哪些字段改了必须重启确认」,两者不可混用(把 shellEscape 等一并
43
+ * 划入禁区会误拒 WebUI 的合法合并编辑)。
44
+ *
45
+ * `mode` 允许热改(WebUI「安全组」四选一);`shellEscape` / `untrustedAdmission` /
46
+ * `pathContainment` / `toolIsolation` / `network` 是普通配置旋钮,允许热改(仍在指纹内,
47
+ * 改了会重锚)。ApplyEngine 据此拒绝禁区字段(评审 M2 补全此前缺失的拒绝逻辑)。
48
+ */
49
+ export const EFFECT_POLICY_HOT_BLOCKED_KEYS = [
50
+ // §4.3.1 明列
51
+ 'jail',
52
+ 'onJailUnavailable',
53
+ 'privilegedAck',
54
+ 'effects',
55
+ 'escalation',
56
+ // §4.3.1「审计开关」;P5 审计外送 = 换见证人
57
+ 'opsAudit',
58
+ 'opsAuditPath',
59
+ 'opsAuditExportPath',
60
+ // ops P4 注释明说「危险命令减速带…须重启 + 宿主署名」
61
+ 'dangerousCommands',
62
+ ];
36
63
  function pickFields(source, keys, prefix) {
37
64
  const out = {};
38
65
  for (const key of keys) {
@@ -144,3 +171,65 @@ export function createFileSecurityIntegrity(options) {
144
171
  return diffSecurityConfigFingerprint(options.anchor, computeSecurityConfigFingerprint(slice));
145
172
  };
146
173
  }
174
+ /**
175
+ * 基于配置文件的可重锚定守卫。
176
+ *
177
+ * @param options.configPath - 配置文件绝对路径
178
+ * @returns 守卫(锚定与复核同口径:都取 raw 文件安全切面)
179
+ * @throws 启动期文件读不到/解析失败(fail-fast,与锚定即拒绝启动的既有语义一致)
180
+ */
181
+ export function createSecurityIntegrityGuard(options) {
182
+ const readSlice = () => {
183
+ const text = readFileSync(options.configPath, 'utf8');
184
+ return { text, slice: extractSecurityConfigSlice(text) };
185
+ };
186
+ let anchor = computeSecurityConfigFingerprint(readSlice().slice);
187
+ return {
188
+ get fingerprint() {
189
+ return anchor.fingerprint;
190
+ },
191
+ recheck() {
192
+ let slice;
193
+ try {
194
+ slice = extractSecurityConfigSlice(readFileSync(options.configPath, 'utf8'));
195
+ }
196
+ catch (err) {
197
+ // 读不到/解析不了 = 无法证明未被篡改,按漂移对待(fail-closed)
198
+ return {
199
+ ok: false,
200
+ changed: [`<config unreadable: ${err instanceof Error ? err.message : String(err)}>`],
201
+ currentFingerprint: '<unreadable>',
202
+ };
203
+ }
204
+ return diffSecurityConfigFingerprint(anchor, computeSecurityConfigFingerprint(slice));
205
+ },
206
+ reattest(reattestOptions) {
207
+ // 刚写盘的文件读不到/解析不了 = 内部异常:抛给调用方降级处理(锚不换,fail-closed 保持)
208
+ const { text, slice } = readSlice();
209
+ // 校验一(TOCTOU):写后 hash 与盘上现状不符 = 重锚前有第三方写入
210
+ if (reattestOptions?.expectHash !== undefined) {
211
+ const actualHash = computeConfigHash(text);
212
+ if (actualHash !== reattestOptions.expectHash) {
213
+ throw new Error(`security re-attest refused: config changed on disk since the console write (expected ${reattestOptions.expectHash.slice(0, 8)}, got ${actualHash.slice(0, 8)}); host restart attests instead`);
214
+ }
215
+ }
216
+ const current = computeSecurityConfigFingerprint(slice);
217
+ const diff = diffSecurityConfigFingerprint(anchor, current);
218
+ // 校验二(防白洗):本次写只应改变它声明的字段;其余安全字段变化 = 既存篡改/越权
219
+ if (reattestOptions?.allowedChanged) {
220
+ const allowed = new Set(reattestOptions.allowedChanged);
221
+ const unexpected = diff.changed.filter((field) => !allowed.has(field.split('.')[0] ?? ''));
222
+ if (unexpected.length > 0) {
223
+ throw new Error(`security re-attest refused: security fields outside this write's scope changed (${unexpected.join(', ')}); refusing to attest them — host restart required`);
224
+ }
225
+ }
226
+ const previous = anchor;
227
+ anchor = current;
228
+ return {
229
+ previousFingerprint: previous.fingerprint,
230
+ fingerprint: current.fingerprint,
231
+ changed: diff.changed,
232
+ };
233
+ },
234
+ };
235
+ }
@@ -18,6 +18,7 @@ import { getOctopiHome } from '../../paths.js';
18
18
  import { DefaultRunGuard, } from '../run/run-guard/default-run-guard.js';
19
19
  import { DefaultContextEngine } from '../context/default-context-engine.js';
20
20
  import { DefaultBudgetAllocator } from '../context/budget-allocator.js';
21
+ import { initShellParser } from '../governance/security/shell-parser.js';
21
22
  // ── 配置解析(唯一实现;供 wire 与公开导出共用) ──
22
23
  /**
23
24
  * 解析子系统审计目录(docs/autonomous-subsystem.md §10)
@@ -123,6 +124,8 @@ export function resolveRunGuard(config, providers) {
123
124
  * @param spec - 标准组装输入
124
125
  */
125
126
  export async function wireAgentBuilder(builder, spec) {
127
+ // ── Shell 解析引擎(安全风险评估依赖;失败自动降级 legacy,不阻断组装) ──
128
+ await initShellParser();
126
129
  // ── Model ──
127
130
  builder.model(spec.model);
128
131
  // ── Model call watchdog ──
@@ -346,6 +349,8 @@ async function wireContextStores(builder, input) {
346
349
  const wis = input.wisdomConfig;
347
350
  if (wis?.enabled !== false) {
348
351
  builder.wisdomStore(new SqliteWisdomStore(db, { hardCap: wis?.capacity?.hardCap }));
352
+ if (wis?.injection)
353
+ builder.wisdomInjection(wis.injection);
349
354
  }
350
355
  const cog = input.cognitionConfig;
351
356
  if (cog?.enabled !== false) {
@@ -16,8 +16,8 @@ export type { SharedDeps, SubsystemRuntimeConfig, SubsystemTriggerResult, Subsys
16
16
  export { SenseEngine, MetricsStore, SessionLifecycleBridge } from './sense/index.js';
17
17
  export { buildAgentInput } from './sense/input-builder.js';
18
18
  export { ThinkExecutor, ModelResolver } from './think/index.js';
19
- export { createSubsystemLLMPort, shouldFallbackModel, DEP_LLM_PORT, DEP_SUBSYSTEM_PROMPT, DEP_RESOLVED_MODEL, DEP_RESOLVED_MODELS, } from './think/index.js';
20
- export type { SubsystemLLMPort, SubsystemLLMPortChatRequest, CreateSubsystemLLMPortOptions, } from './think/index.js';
19
+ export { createSubsystemLLMPort, shouldFallbackModel, DEP_LLM_PORT, DEP_SUBSYSTEM_PROMPT, DEP_RESOLVED_MODEL, DEP_RESOLVED_MODELS, chatForCompleteOutput, } from './think/index.js';
20
+ export type { SubsystemLLMPort, SubsystemLLMPortChatRequest, CreateSubsystemLLMPortOptions, CompletionGuardFailure, CompletionGuardRequest, CompletionGuardResult, } from './think/index.js';
21
21
  export { SignalBus } from './signal/index.js';
22
22
  export { SubsystemSessionManager, parseTTL } from './session/index.js';
23
23
  export { AuditWriter, AuditReader } from './audit/index.js';
@@ -17,7 +17,7 @@ export { SenseEngine, MetricsStore, SessionLifecycleBridge } from './sense/index
17
17
  export { buildAgentInput } from './sense/input-builder.js';
18
18
  // ── Think ──
19
19
  export { ThinkExecutor, ModelResolver } from './think/index.js';
20
- export { createSubsystemLLMPort, shouldFallbackModel, DEP_LLM_PORT, DEP_SUBSYSTEM_PROMPT, DEP_RESOLVED_MODEL, DEP_RESOLVED_MODELS, } from './think/index.js';
20
+ export { createSubsystemLLMPort, shouldFallbackModel, DEP_LLM_PORT, DEP_SUBSYSTEM_PROMPT, DEP_RESOLVED_MODEL, DEP_RESOLVED_MODELS, chatForCompleteOutput, } from './think/index.js';
21
21
  // ── Signal ──
22
22
  export { SignalBus } from './signal/index.js';
23
23
  // ── Session ──
@@ -277,9 +277,12 @@ async function buildSpec(config, systemPrompt, source, dirPath) {
277
277
  events: filterRaw.events,
278
278
  condition: filterRaw.condition,
279
279
  conditionRef: filterRaw.conditionRef,
280
+ minEvents: filterRaw.minEvents,
280
281
  emits: filterRaw.emits,
281
282
  } : undefined,
282
283
  interval: senseRaw.interval,
284
+ runOnStart: senseRaw.runOnStart,
285
+ cooldownMs: senseRaw.cooldownMs,
283
286
  isolation: (senseRaw.isolation ?? 'structured'),
284
287
  fields: senseRaw.fields,
285
288
  },
@@ -59,6 +59,9 @@ export class SenseEngine {
59
59
  const entry = {
60
60
  spec,
61
61
  cooldown: { until: 0 },
62
+ cooldownMs: spec.sense.cooldownMs,
63
+ minEvents: spec.sense.filter?.minEvents ?? 1,
64
+ eventCount: 0,
62
65
  evaluator,
63
66
  disposables: [],
64
67
  };
@@ -92,6 +95,14 @@ export class SenseEngine {
92
95
  entry.scheduleTimer.unref?.();
93
96
  }
94
97
  }
98
+ // 启动首跳:注册完成后补一次 tick(长 interval 首跳跨不过进程生命周期时的保底脉搏;
99
+ // setTimeout(0) 保证 builder 同步注册/依赖注入全部完成后才跑)
100
+ if (spec.sense.runOnStart) {
101
+ const starter = setTimeout(() => {
102
+ void this.onScheduleTick(spec.id, onTrigger);
103
+ }, 0);
104
+ starter.unref?.();
105
+ }
95
106
  }
96
107
  }
97
108
  /**
@@ -283,6 +294,11 @@ export class SenseEngine {
283
294
  const entry = this.subsystems.get(subsystemId);
284
295
  if (!entry)
285
296
  return;
297
+ // 累积计数先于冷却检查:冷却期只是不触发,增量照样攒(攒够 minEvents 才放行)
298
+ entry.eventCount += 1;
299
+ if (entry.eventCount < entry.minEvents) {
300
+ return;
301
+ }
286
302
  const now = Date.now();
287
303
  if (now < entry.cooldown.until || entry.inFlight) {
288
304
  return;
@@ -312,7 +328,8 @@ export class SenseEngine {
312
328
  }
313
329
  }
314
330
  this.depthTracker.depth++;
315
- entry.cooldown.until = Date.now() + this.defaultCooldownMs;
331
+ entry.cooldown.until = Date.now() + (entry.cooldownMs ?? this.defaultCooldownMs);
332
+ entry.eventCount = 0;
316
333
  try {
317
334
  onTrigger(ctx);
318
335
  }
@@ -350,7 +367,7 @@ export class SenseEngine {
350
367
  }
351
368
  }
352
369
  this.depthTracker.depth++;
353
- entry.cooldown.until = Date.now() + this.defaultCooldownMs;
370
+ entry.cooldown.until = Date.now() + (entry.cooldownMs ?? this.defaultCooldownMs);
354
371
  try {
355
372
  onTrigger(ctx);
356
373
  }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * LLM 输出完整性保障 —— maxTokens 只是发给 provider 的生成配额,不是业务截断边界。
3
+ *
4
+ * 语义(2026-10-30 拍板):`finish=length`(配额截断)或 parse 失败的输出都**不得**当业务
5
+ * 结果收下(禁止静默半截结果);先放大配额重试一次,仍失败则返回显式失败原因,由调用方
6
+ * 决定如何上报。业务完整性优先于调用成本。
7
+ *
8
+ * @module harness/collaboration/autonomous-subsystem/think/completion-guard
9
+ */
10
+ import type { LLMMessage } from '@octopi-agent/core/interfaces/model-provider.js';
11
+ import type { SubsystemLLMPort } from './llm-port.js';
12
+ /** 完整性调用的失败原因 */
13
+ export type CompletionGuardFailure = 'llm_error' | 'llm_empty' | 'truncated_output' | 'parse_failed';
14
+ /** 完整性调用结果:成功带解析后的业务结构,失败带显式原因 */
15
+ export type CompletionGuardResult<T> = {
16
+ ok: true;
17
+ parsed: T;
18
+ raw: string;
19
+ } | {
20
+ ok: false;
21
+ reason: CompletionGuardFailure;
22
+ message: string;
23
+ };
24
+ export interface CompletionGuardRequest {
25
+ /** 覆盖认知 prompt;默认使用 port 绑定的 SUBSYSTEM.md 正文 */
26
+ systemPrompt?: string;
27
+ /** 对话消息(不含 system) */
28
+ messages: LLMMessage[];
29
+ /** 生成配额(LLM 传参);截断时重试放大 2 倍,硬上限 {@link RETRY_MAX_TOKENS_CAP} */
30
+ maxTokens: number;
31
+ }
32
+ /**
33
+ * 带输出完整性保障的单轮 LLM 调用:截断或解析失败时放大配额重试一次。
34
+ *
35
+ * @param llmPort - subsystem LLM 端口
36
+ * @param req - systemPrompt / messages / maxTokens(生成配额,非业务截断)
37
+ * @param parse - 从 LLM 文本解析业务结构;失败返回 null
38
+ * @returns 成功返回 parsed;失败返回 llm_error / truncated_output / parse_failed(至多 2 次 LLM 调用)
39
+ */
40
+ export declare function chatForCompleteOutput<T>(llmPort: SubsystemLLMPort, req: CompletionGuardRequest, parse: (text: string) => T | null): Promise<CompletionGuardResult<T>>;