@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
@@ -0,0 +1,59 @@
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
+ /** 重试放大配额的硬上限(防 provider 400;超过此值仍截断按显式失败处理) */
11
+ const RETRY_MAX_TOKENS_CAP = 32768;
12
+ /**
13
+ * 带输出完整性保障的单轮 LLM 调用:截断或解析失败时放大配额重试一次。
14
+ *
15
+ * @param llmPort - subsystem LLM 端口
16
+ * @param req - systemPrompt / messages / maxTokens(生成配额,非业务截断)
17
+ * @param parse - 从 LLM 文本解析业务结构;失败返回 null
18
+ * @returns 成功返回 parsed;失败返回 llm_error / truncated_output / parse_failed(至多 2 次 LLM 调用)
19
+ */
20
+ export async function chatForCompleteOutput(llmPort, req, parse) {
21
+ let lastFailure = 'parse_failed';
22
+ let lastMessage = 'parse_failed';
23
+ for (let attempt = 0; attempt < 2; attempt++) {
24
+ const maxTokens = attempt === 0 ? req.maxTokens : Math.min(req.maxTokens * 2, RETRY_MAX_TOKENS_CAP);
25
+ let res;
26
+ try {
27
+ res = await llmPort.chat({
28
+ systemPrompt: req.systemPrompt,
29
+ messages: req.messages,
30
+ // 温度留空:由模型配置(ModelInfo.temperature)或服务端默认决定
31
+ maxTokens,
32
+ });
33
+ }
34
+ catch (err) {
35
+ return { ok: false, reason: 'llm_error', message: err instanceof Error ? err.message : String(err) };
36
+ }
37
+ if (res.finishReason === 'error') {
38
+ return { ok: false, reason: 'llm_error', message: res.content || 'llm chat error' };
39
+ }
40
+ // 配额截断:半截输出不是业务结果,放大配额重试
41
+ if (res.finishReason === 'length') {
42
+ lastFailure = 'truncated_output';
43
+ lastMessage = `truncated_output: completion hit maxTokens=${maxTokens}`;
44
+ continue;
45
+ }
46
+ const raw = res.content ?? '';
47
+ if (!raw.trim()) {
48
+ lastFailure = 'llm_empty';
49
+ lastMessage = 'llm_empty: empty completion content';
50
+ continue;
51
+ }
52
+ const parsed = parse(raw);
53
+ if (parsed !== null)
54
+ return { ok: true, parsed, raw };
55
+ lastFailure = 'parse_failed';
56
+ lastMessage = 'parse_failed';
57
+ }
58
+ return { ok: false, reason: lastFailure, message: lastMessage };
59
+ }
@@ -4,3 +4,5 @@ export { ModelResolver, resolveProviderInstance } from './model-resolver.js';
4
4
  export type { ModelResolverConfig, ResolvedModel, ResolvedModelWithFallback } from './model-resolver.js';
5
5
  export { createSubsystemLLMPort, shouldFallbackModel, DEP_LLM_PORT, DEP_SUBSYSTEM_PROMPT, DEP_RESOLVED_MODEL, DEP_RESOLVED_MODELS, } from './llm-port.js';
6
6
  export type { SubsystemLLMPort, SubsystemLLMPortChatRequest, CreateSubsystemLLMPortOptions, } from './llm-port.js';
7
+ export { chatForCompleteOutput } from './completion-guard.js';
8
+ export type { CompletionGuardFailure, CompletionGuardRequest, CompletionGuardResult, } from './completion-guard.js';
@@ -1,3 +1,4 @@
1
1
  export { ThinkExecutor } from './executor.js';
2
2
  export { ModelResolver, resolveProviderInstance } from './model-resolver.js';
3
3
  export { createSubsystemLLMPort, shouldFallbackModel, DEP_LLM_PORT, DEP_SUBSYSTEM_PROMPT, DEP_RESOLVED_MODEL, DEP_RESOLVED_MODELS, } from './llm-port.js';
4
+ export { chatForCompleteOutput } from './completion-guard.js';
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * @module autonomous-subsystem/think/model-resolver
14
14
  */
15
- /** 产品约定的级别名(init/example/docs 均定义):未配置时给可操作错误,而不是把别名当模型名打给 provider */
15
+ /** 产品约定的级别名(init/example/docs 均定义 mini/standard/pro;summary 为保留别名——历史上曾是摘要档,保留只为把误写的档位名 fail-loud,而不是当模型名发给 provider) */
16
16
  const WELLKNOWN_LEVEL_ALIASES = new Set(['summary', 'mini', 'standard', 'pro']);
17
17
  /**
18
18
  * 按解析结果选择 provider 实例
@@ -79,6 +79,11 @@ export interface SenseFilter {
79
79
  condition?: string;
80
80
  /** 代码引用(如 "./handler.ts:shouldExtract"),与 condition 互斥 */
81
81
  conditionRef?: string;
82
+ /**
83
+ * 事件累积触发阈值:每收到一个匹配事件计数 +1,累计达到阈值才评估/触发,
84
+ * 触发后清零(缺省 1 = 来一件发一件)。用于「增量 N 条才跑一次」的节流。
85
+ */
86
+ minEvents?: number;
82
87
  /** 该子系统可能产生的事件类型(用于静态循环检测,LLM 子系统建议声明 ['*']) */
83
88
  emits?: string[];
84
89
  }
@@ -90,6 +95,10 @@ export interface SenseConfig {
90
95
  filter?: SenseFilter;
91
96
  /** schedule 模式:轮询间隔(毫秒) */
92
97
  interval?: number;
98
+ /** schedule 模式:注册后立即补一次首跳(长 interval 跨不过进程生命周期时的保底脉搏) */
99
+ runOnStart?: boolean;
100
+ /** 本子系统的触发冷却(毫秒);缺省用 SenseEngine 全局 defaultCooldownMs */
101
+ cooldownMs?: number;
93
102
  isolation: IsolationLevel;
94
103
  /** isolation=partial 时,可见的字段列表 */
95
104
  fields?: ContextField[];
@@ -27,7 +27,7 @@ export declare function resolvePolicyForUnit(unit: ContentUnit, registry: Record
27
27
  */
28
28
  export declare function buildPolicyRegistry(overrides?: Record<string, SummaryPolicy>): Record<string, SummaryPolicy>;
29
29
  /**
30
- * 解析摘要用 ModelProvider(priority: policy.model → policy.modelLevel → explicit → level.summary → legacy → mini → standard → fallback)
30
+ * 解析摘要用 ModelProvider(priority: policy.model → policy.modelLevel → explicit → level(缺省 mini) → legacy → mini → standard → fallback)
31
31
  *
32
32
  * @param input - providers / levelMap / 显式与兼容配置
33
33
  * @returns 解析结果
@@ -76,7 +76,7 @@ function parseProviderModel(ref) {
76
76
  return { provider: ref.slice(0, slash), model: ref.slice(slash + 1) };
77
77
  }
78
78
  /**
79
- * 解析摘要用 ModelProvider(priority: policy.model → policy.modelLevel → explicit → level.summary → legacy → mini → standard → fallback)
79
+ * 解析摘要用 ModelProvider(priority: policy.model → policy.modelLevel → explicit → level(缺省 mini) → legacy → mini → standard → fallback)
80
80
  *
81
81
  * @param input - providers / levelMap / 显式与兼容配置
82
82
  * @returns 解析结果
@@ -92,7 +92,7 @@ export function resolveSummaryModel(input) {
92
92
  const provider = input.providers.get(parsed.provider);
93
93
  if (!provider)
94
94
  return null;
95
- return { provider, model: parsed.model, from: levelName === 'summary' ? 'level.summary' : levelName };
95
+ return { provider, model: parsed.model, from: 'level' };
96
96
  };
97
97
  const tryModelRef = (ref, from) => {
98
98
  const parsed = parseProviderModel(ref);
@@ -122,10 +122,10 @@ export function resolveSummaryModel(input) {
122
122
  if (r)
123
123
  return r;
124
124
  }
125
- const levelName = input.modelLevel ?? 'summary';
125
+ const levelName = input.modelLevel ?? 'mini';
126
126
  const summaryLevel = pickLevel(levelName);
127
127
  if (summaryLevel)
128
- return { ...summaryLevel, from: 'level.summary' };
128
+ return { ...summaryLevel, from: 'level' };
129
129
  if (input.legacySummaryModel) {
130
130
  const r = tryModelRef(input.legacySummaryModel, 'legacy');
131
131
  if (r)
@@ -133,7 +133,7 @@ export interface ResolveSummaryModelInput {
133
133
  legacySummaryModel?: string;
134
134
  /** config.summary.model 显式 */
135
135
  explicitModel?: string;
136
- /** config.summary.modelLevel,默认 'summary' */
136
+ /** config.summary.modelLevel,默认 'mini' */
137
137
  modelLevel?: string;
138
138
  /** policy.modelLevel / policy.model */
139
139
  policyModelLevel?: string;
@@ -142,7 +142,7 @@ export interface ResolveSummaryModelInput {
142
142
  export interface ResolvedSummaryModel {
143
143
  provider: ModelProvider;
144
144
  model?: string;
145
- from: 'policy.model' | 'policy.modelLevel' | 'explicit' | 'level.summary' | 'legacy' | 'mini' | 'standard' | 'fallback';
145
+ from: 'policy.model' | 'policy.modelLevel' | 'explicit' | 'level' | 'legacy' | 'mini' | 'standard' | 'fallback';
146
146
  }
147
147
  export interface CreateSummaryPortOptions {
148
148
  providers: Map<string, ModelProvider>;
@@ -116,8 +116,6 @@ export declare class CognitionLayer extends BaseLayer {
116
116
  export declare class WisdomLayer extends BaseLayer {
117
117
  private readonly select;
118
118
  private readonly onInjected?;
119
- private readonly coreMaxItems?;
120
- private readonly scenarioMaxItems?;
121
119
  constructor(options: {
122
120
  select: (query: string) => Promise<Array<{
123
121
  entry: {
@@ -136,8 +134,6 @@ export declare class WisdomLayer extends BaseLayer {
136
134
  }>>;
137
135
  /** S1 applied 入账(注入命中) */
138
136
  onInjected?: (ids: string[]) => void | Promise<void>;
139
- coreMaxItems?: number;
140
- scenarioMaxItems?: number;
141
137
  order?: number;
142
138
  });
143
139
  assemble(ctx: LayerAssembleContext): Promise<LayerContent | null>;
@@ -155,6 +151,8 @@ export interface CreateDefaultLayersOptions {
155
151
  wisdomStore?: import('../memory/types.js').WisdomStore;
156
152
  wisdomCoreMaxItems?: number;
157
153
  wisdomScenarioMaxItems?: number;
154
+ /** trial 可见性(wisdom.injection.trialVisible;缺省 true——trial 的意义就是被试用) */
155
+ wisdomIncludeTrial?: boolean;
158
156
  }
159
157
  /**
160
158
  * 按可用依赖创建启用层列表
@@ -328,14 +328,10 @@ export class CognitionLayer extends BaseLayer {
328
328
  export class WisdomLayer extends BaseLayer {
329
329
  select;
330
330
  onInjected;
331
- coreMaxItems;
332
- scenarioMaxItems;
333
331
  constructor(options) {
334
332
  super('wisdom', { order: options.order, placement: 'snapshot' });
335
333
  this.select = options.select;
336
334
  this.onInjected = options.onInjected;
337
- this.coreMaxItems = options.coreMaxItems;
338
- this.scenarioMaxItems = options.scenarioMaxItems;
339
335
  }
340
336
  async assemble(ctx) {
341
337
  const picks = await this.select(ctx.query ?? '');
@@ -346,11 +342,14 @@ export class WisdomLayer extends BaseLayer {
346
342
  return null;
347
343
  const text = `# 思维框架\n\n${body}`;
348
344
  const { text: truncated, dropped } = this.truncateToBudget(text, ctx.tokenBudget);
349
- const sources = picks.map((p) => p.entry.id);
350
- // S1:实际进入 system 的条目记 applied(轻量,不跑 confidence)
351
- if (this.onInjected && sources.length) {
345
+ // S1:只对实际留在文本里的条目记 applied / 报 sources——
346
+ // truncate 粗滤会裁掉尾部条目,被裁掉的不入账(applied 是归因环地基,宁缺勿滥)
347
+ const keptIds = picks
348
+ .filter((p) => truncated.includes(p.entry.statement))
349
+ .map((p) => p.entry.id);
350
+ if (this.onInjected && keptIds.length) {
352
351
  try {
353
- await this.onInjected(sources);
352
+ await this.onInjected(keptIds);
354
353
  }
355
354
  catch {
356
355
  // 入账失败不拖垮装配;结局环可由 evaluate 兜
@@ -358,7 +357,7 @@ export class WisdomLayer extends BaseLayer {
358
357
  }
359
358
  return this.content(truncated, {
360
359
  dropped,
361
- sources,
360
+ sources: keptIds,
362
361
  });
363
362
  }
364
363
  }
@@ -378,12 +377,11 @@ export function createDefaultLayers(options) {
378
377
  text: query,
379
378
  coreMaxItems: options.wisdomCoreMaxItems,
380
379
  scenarioMaxItems: options.wisdomScenarioMaxItems,
380
+ includeTrial: options.wisdomIncludeTrial,
381
381
  });
382
382
  return picks.map((p) => ({ entry: p.entry, bucket: p.bucket }));
383
383
  },
384
384
  onInjected: (ids) => store.touchApplied(ids),
385
- coreMaxItems: options.wisdomCoreMaxItems,
386
- scenarioMaxItems: options.wisdomScenarioMaxItems,
387
385
  }));
388
386
  }
389
387
  if (options.personaText) {
@@ -25,7 +25,7 @@ export declare function createProviderSummarize(provider: ModelProvider, options
25
25
  /**
26
26
  * 从 model level 映射中挑摘要用 provider
27
27
  *
28
- * 优先级:summary → mini → standard → 传入的 fallbackProvider(通常是主模型)
28
+ * 优先级:mini → standard → 传入的 fallbackProvider(通常是主模型)
29
29
  *
30
30
  * @param providers - 可用 provider 映射
31
31
  * @param levelMap - models.level 配置(primary 为 provider/model)
@@ -30,7 +30,7 @@ export function createProviderSummarize(provider, options) {
30
30
  /**
31
31
  * 从 model level 映射中挑摘要用 provider
32
32
  *
33
- * 优先级:summary → mini → standard → 传入的 fallbackProvider(通常是主模型)
33
+ * 优先级:mini → standard → 传入的 fallbackProvider(通常是主模型)
34
34
  *
35
35
  * @param providers - 可用 provider 映射
36
36
  * @param levelMap - models.level 配置(primary 为 provider/model)
@@ -38,7 +38,7 @@ export function createProviderSummarize(provider, options) {
38
38
  * @returns 选中的 provider + 建议模型名
39
39
  */
40
40
  export function pickSummarizeProvider(providers, levelMap, fallbackProvider) {
41
- for (const levelName of ['summary', 'mini', 'standard']) {
41
+ for (const levelName of ['mini', 'standard']) {
42
42
  const primary = levelMap?.[levelName]?.primary;
43
43
  if (!primary)
44
44
  continue;
@@ -78,6 +78,8 @@ export declare function createDefaultSystemPromptAssembler(options?: {
78
78
  /** Wisdom 注入条数硬顶 */
79
79
  wisdomCoreMaxItems?: number;
80
80
  wisdomScenarioMaxItems?: number;
81
+ /** trial 可见性(wisdom.injection.trialVisible;缺省 true——trial 的意义就是被试用) */
82
+ wisdomIncludeTrial?: boolean;
81
83
  cognitionStore?: ConceptGraphStore;
82
84
  memoryLimit?: number;
83
85
  knowledgeMaxEntries?: number;
@@ -115,6 +115,7 @@ export function createDefaultSystemPromptAssembler(options) {
115
115
  text: query,
116
116
  coreMaxItems: options?.wisdomCoreMaxItems,
117
117
  scenarioMaxItems: options?.wisdomScenarioMaxItems,
118
+ includeTrial: options?.wisdomIncludeTrial,
118
119
  });
119
120
  return picks.map((p) => ({ entry: p.entry, bucket: p.bucket }));
120
121
  },
@@ -112,6 +112,23 @@ export interface EffectPolicyConfig {
112
112
  /** 额外事务 root(绝对路径或 ~ 形态,入口 trim → expand);并入 allowRoots */
113
113
  transactionRoots?: string[];
114
114
  pathContainment?: PathContainment;
115
+ /**
116
+ * 拒绝最终组件为符号链接的文件读写(缺省 `false`)。
117
+ *
118
+ * 包含判定已把路径解析为真实路径,正常情况下最终组件不是链接;若打开时它
119
+ * 仍是链接,说明检查与使用之间被替换。开启后以 `O_NOFOLLOW` / `lstat`
120
+ * 拒绝,而不是跟随。`untrusted` 模式强制开启,不受配置放松。
121
+ *
122
+ * 代价:`pathContainment: 'none'` 下根内合法链接的读写会被拒。
123
+ */
124
+ refuseFinalSymlink?: boolean;
125
+ /**
126
+ * 拒绝匹配这些 glob 的路径(相对允许根匹配,同时匹配文件名)。
127
+ *
128
+ * 默认空 = 不拒绝任何路径;「agent 读写自己 workspace 里的 `.env`」是合法
129
+ * 用法,本字段是部署策略而非引擎世界观。声明即拒绝,任何 containment 级别都生效。
130
+ */
131
+ pathDenylist?: string[];
115
132
  shellEscape?: ShellEscapePolicy;
116
133
  /**
117
134
  * Jail network posture (D4-c). Omitted = mode default:
@@ -142,8 +159,9 @@ export interface EffectPolicyConfig {
142
159
  jail?: JailIntent;
143
160
  /** jail≠none 且笼不可用时:`refuse` 拒绝执行 | `degrade`(缺省)记 securityDegraded + 告警 */
144
161
  onJailUnavailable?: OnJailUnavailable;
145
- /** `jail: "none"` 时必填的显式表态(缺省拒绝启动;§8.1 二级确认)。root/elevated
146
- * 部署同样要求此声明(§5 P4 root 部署语义,启动期断言)。 */
162
+ /** `jail: "none"` / `escalation: "full"` 时按块必填的显式表态(缺省拒绝启动;§8.1 二级确认)。
163
+ * root/elevated 部署声明是另一回事:只认**顶层** effectPolicy 的本字段(§5 P4,启动期断言);
164
+ * agent 块内的本字段只声明该块自己的 jail=none/full,不参与 elevated 启动声明。 */
147
165
  privilegedAck?: string;
148
166
  /** 提权策略(§4/§5 P3/P4):`allowlist` 按 cmd+args 全等放行;`full` 全量档
149
167
  * (需 `jail: "none"` + `privilegedAck` + `mode: "host"`);缺省 `none` */
@@ -188,6 +206,10 @@ export interface EffectiveEffectPolicy {
188
206
  securityDegraded: SecurityDegradation[];
189
207
  toolIsolation: ToolIsolationMode;
190
208
  pathContainment: PathContainment;
209
+ /** 拒绝最终组件为符号链接的文件读写(`untrusted` 强制 true) */
210
+ refuseFinalSymlink: boolean;
211
+ /** 拒绝清单(glob);空数组 = 不拒绝 */
212
+ pathDenylist: readonly string[];
191
213
  shellEscape: ShellEscapePolicy;
192
214
  /** Resolved jail network posture */
193
215
  network: 'open' | 'deny' | 'allowlist';
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { isAbsolute, resolve } from 'node:path';
8
8
  import { expandHomePath } from '../../../paths.js';
9
+ import { globToPathRegex, normalizeDenyPattern, validateDenyPattern } from '../../shared/paths/glob.js';
9
10
  import { checkEscalationBinary, escalationRuleTargets, escalationWritableRoots, } from './privileged-exec.js';
10
11
  import { deniesReducedSurface, resolveToolCapabilities, } from './tool-capabilities.js';
11
12
  import { assessL4ProcessMinimum, } from './process-isolation.js';
@@ -23,6 +24,10 @@ const MODE_DEFAULTS = {
23
24
  mode: 'workspace',
24
25
  toolIsolation: 'session-subdir',
25
26
  pathContainment: 'strict',
27
+ // containment 已把路径解析为真实路径,合法链接不受影响;需要闭合
28
+ // 「检查后、落盘前被换成链接」窗口的部署再显式开启。
29
+ refuseFinalSymlink: false,
30
+ pathDenylist: [],
26
31
  // 无 L4 时无法「只禁越界」:deny = 拒绝 shell 工具(fail-closed)
27
32
  shellEscape: 'deny',
28
33
  network: 'deny',
@@ -36,6 +41,8 @@ const MODE_DEFAULTS = {
36
41
  mode: 'project',
37
42
  toolIsolation: 'session-subdir',
38
43
  pathContainment: 'strict',
44
+ refuseFinalSymlink: false,
45
+ pathDenylist: [],
39
46
  // 编码 agent 必须有 shell;文件侧靠 L2,shell FS 越界待 L4
40
47
  shellEscape: 'allow',
41
48
  network: 'open',
@@ -49,6 +56,9 @@ const MODE_DEFAULTS = {
49
56
  mode: 'host',
50
57
  toolIsolation: 'none',
51
58
  pathContainment: 'none',
59
+ // containment 关闭时不做 realpath,开启会拒掉根内合法链接,故保持关闭
60
+ refuseFinalSymlink: false,
61
+ pathDenylist: [],
52
62
  shellEscape: 'allow',
53
63
  network: 'open',
54
64
  processLimits: true,
@@ -61,6 +71,9 @@ const MODE_DEFAULTS = {
61
71
  mode: 'untrusted',
62
72
  toolIsolation: 'session-subdir',
63
73
  pathContainment: 'strict',
74
+ // 不可信输入下强制开启:硬化为不可放松的产品承诺
75
+ refuseFinalSymlink: true,
76
+ pathDenylist: [],
64
77
  shellEscape: 'deny',
65
78
  network: 'deny',
66
79
  processLimits: true,
@@ -306,6 +319,21 @@ export function resolveEffectiveEffectPolicy(config, baseWorkspace, isolation) {
306
319
  const pathContainment = requestedMode === 'untrusted'
307
320
  ? 'strict'
308
321
  : (config.pathContainment ?? d.pathContainment);
322
+ // Final-symlink refusal is a hardening, so the untrusted promise turns it on
323
+ // and config cannot loosen it back off. Elsewhere it stays opt-in: with
324
+ // containment off, in-root links are a legitimate workflow.
325
+ const refuseFinalSymlink = requestedMode === 'untrusted' ? true : (config.refuseFinalSymlink ?? d.refuseFinalSymlink);
326
+ // Union, not replace: a preset may only *add* denied patterns, so a deployment
327
+ // cannot loosen a built-in deny list by supplying its own.
328
+ const pathDenylist = [...new Set([...(d.pathDenylist ?? []), ...(config.pathDenylist ?? [])])]
329
+ .map(normalizeDenyPattern);
330
+ // Two gates, deliberately: the config schema rejects these shapes at load time
331
+ // (so a daemon never starts believing it is protected), and this loop covers
332
+ // callers that hand-build a config object instead of going through the schema.
333
+ for (const pattern of pathDenylist) {
334
+ validateDenyPattern(pattern);
335
+ globToPathRegex(pattern);
336
+ }
309
337
  // untrusted intent residue: keep discard-on-close even when effectiveMode renames
310
338
  const onClose = config.onClose ??
311
339
  (requestedMode === 'untrusted' ? MODE_DEFAULTS.untrusted.onClose : d.onClose);
@@ -319,6 +347,8 @@ export function resolveEffectiveEffectPolicy(config, baseWorkspace, isolation) {
319
347
  securityDegraded,
320
348
  toolIsolation: config.toolIsolation ?? d.toolIsolation,
321
349
  pathContainment,
350
+ refuseFinalSymlink,
351
+ pathDenylist,
322
352
  // degraded untrusted must not leave shell allow as a hole
323
353
  shellEscape: toolSurface === 'reduced' ? 'deny' : (config.shellEscape ?? d.shellEscape),
324
354
  // untrusted product promise: egress deny is not a config knob (like pathContainment)
@@ -184,9 +184,13 @@ export declare class OpsAuditedFileEffects implements ToolFileEffects {
184
184
  private underRoots;
185
185
  private noteWrite;
186
186
  /** @inheritdoc */
187
- writeFile(path: string, data: string | Uint8Array): Promise<void>;
187
+ writeFile(path: string, data: string | Uint8Array, options?: {
188
+ refuseFinalSymlink?: boolean;
189
+ }): Promise<void>;
188
190
  /** @inheritdoc */
189
- appendFile(path: string, data: string | Uint8Array): Promise<void>;
191
+ appendFile(path: string, data: string | Uint8Array, options?: {
192
+ refuseFinalSymlink?: boolean;
193
+ }): Promise<void>;
190
194
  /** @inheritdoc */
191
195
  recordDelete(path: string, before: string | Uint8Array): Promise<void>;
192
196
  /** @inheritdoc */
@@ -18,7 +18,8 @@
18
18
  */
19
19
  import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, writeSync } from 'node:fs';
20
20
  import { createHash } from 'node:crypto';
21
- import { dirname, resolve, sep } from 'node:path';
21
+ import { dirname } from 'node:path';
22
+ import { isPathUnderRoots } from '../../shared/paths/index.js';
22
23
  /** 链首哨兵 */
23
24
  export const GENESIS_HASH = '0'.repeat(64);
24
25
  /**
@@ -279,13 +280,11 @@ export class OpsAuditedFileEffects {
279
280
  this.record = options.record;
280
281
  }
281
282
  underRoots(path) {
282
- // resolve + sep 感知;win32 大小写不敏感卷按 toLowerCase 口径(对齐 isPathAllowed)
283
- const norm = (p) => process.platform === 'win32' ? resolve(p).toLowerCase() : resolve(p);
284
- const target = norm(path);
285
- return this.roots.some((root) => {
286
- const base = norm(root);
287
- return target === base || target.startsWith(base.endsWith(sep) ? base : `${base}${sep}`);
288
- });
283
+ // Containment in real coordinates: tools now hand back symlink-resolved
284
+ // paths while `roots` keeps the configured spelling. A lexical-only check
285
+ // would audit every in-root write as an out-of-root write under alias roots
286
+ // (macOS /var → /private/var, a symlinked HOME).
287
+ return isPathUnderRoots(path, this.roots);
289
288
  }
290
289
  noteWrite(op, path, fromPath) {
291
290
  // 经 fileEffects 写口的写入本身是 undo 账在管(before/after 都在 TurnFileUndoLog,
@@ -301,13 +300,13 @@ export class OpsAuditedFileEffects {
301
300
  });
302
301
  }
303
302
  /** @inheritdoc */
304
- async writeFile(path, data) {
305
- await this.inner.writeFile(path, data);
303
+ async writeFile(path, data, options) {
304
+ await this.inner.writeFile(path, data, options);
306
305
  this.noteWrite('writeFile', path);
307
306
  }
308
307
  /** @inheritdoc */
309
- async appendFile(path, data) {
310
- await this.inner.appendFile(path, data);
308
+ async appendFile(path, data, options) {
309
+ await this.inner.appendFile(path, data, options);
311
310
  this.noteWrite('appendFile', path);
312
311
  }
313
312
  /** @inheritdoc */
@@ -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
  }