@octopi-agent/engine 0.86.38 → 0.90.11

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 (83) hide show
  1. package/dist/config-schema/agent.js +12 -5
  2. package/dist/config-schema/context.d.ts +1 -1
  3. package/dist/config-schema/engine.d.ts +4 -4
  4. package/dist/config-schema/governance.js +3 -2
  5. package/dist/config-schema/models.d.ts +2 -2
  6. package/dist/config-schema/shared.d.ts +3 -0
  7. package/dist/config-schema/shared.js +12 -0
  8. package/dist/config-schema/substrate.d.ts +1 -1
  9. package/dist/config.d.ts +31 -9
  10. package/dist/config.js +66 -74
  11. package/dist/harness/agent/builder.d.ts +3 -2
  12. package/dist/harness/agent/builder.js +11 -7
  13. package/dist/harness/agent/config-bridge.js +4 -1
  14. package/dist/harness/agent/tool-purpose.d.ts +9 -1
  15. package/dist/harness/agent/tool-purpose.js +11 -2
  16. package/dist/harness/agent/wire-agent-builder.js +9 -2
  17. package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.d.ts +11 -1
  18. package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.js +11 -1
  19. package/dist/harness/collaboration/autonomous-subsystem/loader.d.ts +13 -0
  20. package/dist/harness/collaboration/autonomous-subsystem/loader.js +16 -1
  21. package/dist/harness/collaboration/autonomous-subsystem/runtime.d.ts +4 -0
  22. package/dist/harness/collaboration/autonomous-subsystem/runtime.js +3 -1
  23. package/dist/harness/context/default-context-engine.js +4 -4
  24. package/dist/harness/context/layer-types.d.ts +36 -0
  25. package/dist/harness/context/layer-types.js +38 -0
  26. package/dist/harness/context/root-instructions.js +1 -1
  27. package/dist/harness/context/system-prompt-assembler.js +10 -4
  28. package/dist/harness/context/tool-result-aging.js +2 -2
  29. package/dist/harness/context/turn-envelope.d.ts +1 -1
  30. package/dist/harness/context/turn-envelope.js +1 -1
  31. package/dist/harness/extension/execution-environment/effect-policy.d.ts +11 -1
  32. package/dist/harness/extension/execution-environment/effect-policy.js +24 -0
  33. package/dist/harness/extension/execution-environment/index.d.ts +1 -1
  34. package/dist/harness/extension/execution-environment/index.js +1 -1
  35. package/dist/harness/extension/execution-environment/isolation.js +5 -1
  36. package/dist/harness/extension/execution-environment/sandbox.js +36 -8
  37. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.d.ts +6 -0
  38. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.js +17 -0
  39. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +10 -17
  40. package/dist/harness/extension/plugin-ecosystem/tools/git-runner.d.ts +31 -0
  41. package/dist/harness/extension/plugin-ecosystem/tools/git-runner.js +104 -0
  42. package/dist/harness/extension/plugin-ecosystem/tools/git-status-snapshot.d.ts +111 -0
  43. package/dist/harness/extension/plugin-ecosystem/tools/git-status-snapshot.js +197 -0
  44. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.d.ts +8 -8
  45. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +9 -100
  46. package/dist/harness/extension/plugin-ecosystem/tools/index.d.ts +4 -0
  47. package/dist/harness/extension/plugin-ecosystem/tools/index.js +2 -0
  48. package/dist/harness/index.d.ts +2 -0
  49. package/dist/harness/index.js +1 -0
  50. package/dist/harness/knowledge/file-identity.d.ts +8 -0
  51. package/dist/harness/knowledge/file-identity.js +26 -1
  52. package/dist/harness/knowledge/grounding.js +5 -5
  53. package/dist/harness/knowledge/index-store.d.ts +31 -4
  54. package/dist/harness/knowledge/index-store.js +121 -39
  55. package/dist/harness/knowledge/ingest.d.ts +115 -115
  56. package/dist/harness/knowledge/ingest.js +150 -150
  57. package/dist/harness/knowledge/knowledge-serve-child.js +1 -1
  58. package/dist/harness/knowledge/purge.js +4 -1
  59. package/dist/harness/memory/backfill-coverage.js +3 -1
  60. package/dist/harness/observability/observer/hub.js +30 -1
  61. package/dist/harness/observability/observer/types.d.ts +23 -0
  62. package/dist/harness/run/runner.d.ts +16 -0
  63. package/dist/harness/run/runner.js +139 -26
  64. package/dist/harness/session/history/port.js +15 -5
  65. package/dist/harness/session/in-memory-store.d.ts +5 -0
  66. package/dist/harness/session/in-memory-store.js +33 -2
  67. package/dist/harness/session/title.js +25 -9
  68. package/dist/harness/shared/events/agent-event-map.d.ts +26 -0
  69. package/dist/harness/shared/events/agent-event-map.js +2 -0
  70. package/dist/index.d.ts +4 -2
  71. package/dist/index.js +3 -2
  72. package/dist/integration/observability/run-telemetry.d.ts +8 -0
  73. package/dist/integration/observability/run-telemetry.js +31 -8
  74. package/dist/integration/observability/trace-collector.js +26 -4
  75. package/dist/integration/observability/trace-events.d.ts +1 -0
  76. package/dist/integration/observability/trace-events.js +2 -0
  77. package/dist/integration/observability/trace-logger.js +27 -17
  78. package/dist/integration/storage/jsonl.d.ts +19 -1
  79. package/dist/integration/storage/jsonl.js +96 -3
  80. package/dist/paths.d.ts +19 -0
  81. package/dist/paths.js +38 -1
  82. package/dist/subsystems/safety-guard/config.yaml +3 -1
  83. package/package.json +2 -2
@@ -4,18 +4,25 @@
4
4
  * @module
5
5
  */
6
6
  import { z } from 'zod';
7
- import { InlinePersonaSchema, ModelConfigSchema, NetworkHostSchema, SessionRightsSchema, ToolPolicySchema, } from './shared.js';
7
+ import { ConfigPathSchema, InlinePersonaSchema, ModelConfigSchema, NetworkHostSchema, SessionRightsSchema, ToolPolicySchema, } from './shared.js';
8
8
  import { EffectPolicyConfigSchema } from './governance.js';
9
9
  export const AgentConfigSchema = z.object({
10
10
  id: z.string({ error: 'Agent must have an id' }).min(1, 'Agent id cannot be empty'),
11
- home: z.string().optional(),
12
- workspace: z.string().optional(),
11
+ /**
12
+ * agent 文件态 home(persona / skills / agent.db 基线)。与 `workspace` 同规:
13
+ * 绝对路径或 `~` 形态——相对路径加载即拒,杜绝隐式 resolve 到进程 cwd。
14
+ */
15
+ home: ConfigPathSchema.optional(),
16
+ /** 工具基路径:绝对路径或 ~ 形态(相对路径加载即拒,杜绝隐式 resolve 到进程 cwd) */
17
+ workspace: ConfigPathSchema.optional(),
13
18
  /** ToolEffectPolicy 运行模式(P3);与 tools allow/deny 无关 */
14
19
  effectPolicy: EffectPolicyConfigSchema.optional(),
15
- persona: z.union([z.string(), InlinePersonaSchema]).optional(),
20
+ /** 文件式 persona 目录,或内联 systemPrompt。legacy string 形态等价 home(同路径契约) */
21
+ persona: z.union([ConfigPathSchema, InlinePersonaSchema]).optional(),
16
22
  model: z.union([z.string().min(1), ModelConfigSchema]),
17
23
  tools: ToolPolicySchema.optional(),
18
- skillDirectory: z.string().optional(),
24
+ /** Skill 目录(缺省 `home/skills`):与 `workspace`/`home` 同规(绝对或 `~` 形态,拒相对) */
25
+ skillDirectory: ConfigPathSchema.optional(),
19
26
  skills: z.array(z.string()).optional(),
20
27
  channelBindings: z.record(z.string(), z.string()).optional(),
21
28
  /** Session ACL 天花板(E6 L1);与角色 max / 绑定取交集 */
@@ -172,8 +172,8 @@ export declare const DocumentsConfigSchema: z.ZodObject<{
172
172
  export declare const ConstitutionConfigSchema: z.ZodObject<{
173
173
  mode: z.ZodEnum<{
174
174
  off: "off";
175
- custom: "custom";
176
175
  product: "product";
176
+ custom: "custom";
177
177
  }>;
178
178
  path: z.ZodOptional<z.ZodNullable<z.ZodString>>;
179
179
  }, z.core.$strip>;
@@ -185,9 +185,9 @@ export declare const engineConfigSchema: z.ZodObject<{
185
185
  enabled: z.ZodOptional<z.ZodBoolean>;
186
186
  type: z.ZodOptional<z.ZodEnum<{
187
187
  openai: "openai";
188
+ http: "http";
188
189
  custom: "custom";
189
190
  ollama: "ollama";
190
- http: "http";
191
191
  }>>;
192
192
  provider: z.ZodOptional<z.ZodString>;
193
193
  model: z.ZodString;
@@ -494,8 +494,8 @@ export declare const engineConfigSchema: z.ZodObject<{
494
494
  hybridKeyword: z.ZodOptional<z.ZodBoolean>;
495
495
  embedSecretPolicy: z.ZodOptional<z.ZodEnum<{
496
496
  allow: "allow";
497
- redact: "redact";
498
497
  skip: "skip";
498
+ redact: "redact";
499
499
  }>>;
500
500
  phaseA: z.ZodOptional<z.ZodObject<{
501
501
  concurrency: z.ZodOptional<z.ZodNumber>;
@@ -578,8 +578,8 @@ export declare const engineConfigSchema: z.ZodObject<{
578
578
  constitution: z.ZodOptional<z.ZodObject<{
579
579
  mode: z.ZodEnum<{
580
580
  off: "off";
581
- custom: "custom";
582
581
  product: "product";
582
+ custom: "custom";
583
583
  }>;
584
584
  path: z.ZodOptional<z.ZodNullable<z.ZodString>>;
585
585
  }, z.core.$strip>>;
@@ -605,8 +605,8 @@ export declare const engineConfigSchema: z.ZodObject<{
605
605
  constitution: z.ZodOptional<z.ZodObject<{
606
606
  mode: z.ZodEnum<{
607
607
  off: "off";
608
- custom: "custom";
609
608
  product: "product";
609
+ custom: "custom";
610
610
  }>;
611
611
  path: z.ZodOptional<z.ZodNullable<z.ZodString>>;
612
612
  }, z.core.$strip>>;
@@ -4,7 +4,7 @@
4
4
  * @module
5
5
  */
6
6
  import { z } from 'zod';
7
- import { SessionRightsSchema } from './shared.js';
7
+ import { ConfigPathSchema, SessionRightsSchema } from './shared.js';
8
8
  export const SecurityConfigSchema = z.object({
9
9
  enforce: z.enum(['block', 'audit']).optional(),
10
10
  injectionSensitivity: z.enum(['low', 'medium', 'high']).optional(),
@@ -56,7 +56,8 @@ export const EffectPolicyConfigSchema = z.object({
56
56
  * degrade 降 effectiveMode + toolSurface=reduced + securityDegraded。
57
57
  */
58
58
  untrustedAdmission: z.enum(['refuse', 'degrade']).optional(),
59
- transactionRoots: z.array(z.string()).optional(),
59
+ /** 额外事务 root(绝对路径或 ~ 形态);并入 allowRoots */
60
+ transactionRoots: z.array(ConfigPathSchema).optional(),
60
61
  pathContainment: z.enum(['strict', 'soft', 'none']).optional(),
61
62
  shellEscape: z.enum(['deny', 'confirm', 'allow']).optional(),
62
63
  processLimits: z.boolean().optional(),
@@ -39,9 +39,9 @@ export declare const ModelsConfigSchema: z.ZodObject<{
39
39
  enabled: z.ZodOptional<z.ZodBoolean>;
40
40
  type: z.ZodOptional<z.ZodEnum<{
41
41
  openai: "openai";
42
+ http: "http";
42
43
  custom: "custom";
43
44
  ollama: "ollama";
44
- http: "http";
45
45
  }>>;
46
46
  provider: z.ZodOptional<z.ZodString>;
47
47
  model: z.ZodString;
@@ -92,9 +92,9 @@ export declare const EmbeddingModelConfigSchemaExport: z.ZodObject<{
92
92
  enabled: z.ZodOptional<z.ZodBoolean>;
93
93
  type: z.ZodOptional<z.ZodEnum<{
94
94
  openai: "openai";
95
+ http: "http";
95
96
  custom: "custom";
96
97
  ollama: "ollama";
97
- http: "http";
98
98
  }>>;
99
99
  provider: z.ZodOptional<z.ZodString>;
100
100
  model: z.ZodString;
@@ -4,6 +4,9 @@
4
4
  * @module
5
5
  */
6
6
  import { z } from 'zod';
7
+ export { expandHomePath, isConfigPathShape } from '../paths.js';
8
+ /** 配置路径字段(workspace / transactionRoots 等):绝对路径或 ~ 形态 */
9
+ export declare const ConfigPathSchema: z.ZodString;
7
10
  /** 监听 host:local(默认仅本机)| lan(局域网)| 具体 IP/主机名 */
8
11
  export declare const NetworkHostSchema: z.ZodUnion<readonly [z.ZodEnum<{
9
12
  local: "local";
@@ -4,6 +4,18 @@
4
4
  * @module
5
5
  */
6
6
  import { z } from 'zod';
7
+ import { isConfigPathShape } from '../paths.js';
8
+ // 路径语义的唯一实现在 zod-free 的 paths.ts(harness 运行时同样引用);此处转出
9
+ // 保持 schema 消费方的导入面不变。
10
+ export { expandHomePath, isConfigPathShape } from '../paths.js';
11
+ /** 配置路径字段(workspace / transactionRoots 等):绝对路径或 ~ 形态 */
12
+ export const ConfigPathSchema = z
13
+ .string()
14
+ .min(1)
15
+ .refine(isConfigPathShape, {
16
+ message: 'must be an absolute path or ~-prefixed (~/…, ~\\…, or bare ~)',
17
+ })
18
+ .describe('Absolute path or ~-prefixed (~/…, ~\\…, bare ~); ~user is not supported');
7
19
  /** 监听 host:local(默认仅本机)| lan(局域网)| 具体 IP/主机名 */
8
20
  export const NetworkHostSchema = z.union([
9
21
  z.enum(['local', 'lan']),
@@ -52,8 +52,8 @@ export declare const KnowledgeConfigSchema: z.ZodObject<{
52
52
  hybridKeyword: z.ZodOptional<z.ZodBoolean>;
53
53
  embedSecretPolicy: z.ZodOptional<z.ZodEnum<{
54
54
  allow: "allow";
55
- redact: "redact";
56
55
  skip: "skip";
56
+ redact: "redact";
57
57
  }>>;
58
58
  phaseA: z.ZodOptional<z.ZodObject<{
59
59
  concurrency: z.ZodOptional<z.ZodNumber>;
package/dist/config.d.ts CHANGED
@@ -20,7 +20,7 @@ export interface AgentConfig {
20
20
  id: string;
21
21
  /** Agent home 目录:persona、skills 的根目录(session 在 OCTOPI_HOME/sessions;memory/wisdom 走 AgentDatabase SQLite) */
22
22
  home?: string;
23
- /** 沙箱工作目录:agent 工具操作的 cwd,默认为 home 下的 workspace 子目录 */
23
+ /** 沙箱工作目录:agent 工具操作的 cwd,默认为 home 下的 workspace 子目录;支持 ~ 形态(使用点展开) */
24
24
  workspace?: string;
25
25
  /** ToolEffectPolicy(P3) */
26
26
  effectPolicy?: import('./harness/extension/execution-environment/effect-policy.js').EffectPolicyConfig;
@@ -1121,13 +1121,6 @@ export interface NormalizedModelInfo {
1121
1121
  contextWindow?: number;
1122
1122
  maxTokens?: number;
1123
1123
  }
1124
- /**
1125
- * 包一层计时探针:llm_start / llm_first_token(TTFT)/ llm_end
1126
- *
1127
- * @param inner - 真实 provider
1128
- * @returns 透传装饰器
1129
- */
1130
- export declare function withTimingProbe(inner: ModelProvider): ModelProvider;
1131
1124
  /**
1132
1125
  * 按 `observability.llmRequestDump` 配置构造 wire dump sink
1133
1126
  *
@@ -1148,8 +1141,37 @@ export declare function createWireDumpSinkFromConfig(cfg?: import('./integration
1148
1141
  * @param name - provider 名称
1149
1142
  * @param pc - provider 配置
1150
1143
  * @param options - 可选:wire dump sink(诊断用,见 `observability.llmRequestDump`)
1151
- * @returns provider 实例(计时探针 → wire dump → 原生 provider 的装饰链)
1144
+ * @returns provider 实例(wire dump → 原生 provider 的装饰链;LLM 计时已 observability 化进 model.call.*)
1152
1145
  */
1153
1146
  export declare function createProviderFromConfig(name: string, pc: ModelProviderConfig, options?: {
1154
1147
  wireDump?: import('./integration/providers/wire-dump.js').WireDumpSink;
1155
1148
  }): Promise<ModelProvider>;
1149
+ /**
1150
+ * 按 `observability` 配置构造 RunTelemetry 工厂(F3/D5 接线,组合根)
1151
+ *
1152
+ * TraceCollector → TraceLogger 按 `outputDir` 逐条同步落 JSONL(即 `traceDir`,无缓冲丢失风险);
1153
+ * `level` / `consoleLevel` 与配置的 0–5 数值同构(FATAL=0 … TRACE=5,schema 已校验范围)。
1154
+ * `consoleLevel` 缺省 null:trace 走文件通道,不向 gateway.log 混入控制台副本(要副本显式配置)。
1155
+ *
1156
+ * @param cfg - `observability` 配置段(level / consoleLevel / traceDir / capture*)
1157
+ * @param options - 可选:trace 文件名前缀(多 agent 归属标识)
1158
+ * @returns RunTelemetry 工厂(供 `AgentBuilder.telemetryFactory()` 注入)
1159
+ */
1160
+ export declare function createTelemetryFactoryFromConfig(cfg: NonNullable<HarnessConfig['observability']>, options?: {
1161
+ filePrefix?: string;
1162
+ }): Promise<import('./harness/observability/run-telemetry.js').RunTelemetryFactory>;
1163
+ /**
1164
+ * 按 `observability` 配置接线 AgentBuilder 观测装配(F3/D5)
1165
+ *
1166
+ * - 落盘:`traceDir / level / consoleLevel` → TraceCollector → JSONL
1167
+ * - 采集意图:`captureStreamDeltas / captureModelRequest` → `AgentBuilder.trace()`
1168
+ * - 工厂显式注入,不依赖包入口 `setRunTelemetryFactory` 副作用
1169
+ * (serve / 子路径 import 时该副作用未必执行过,不能拿它当接线)
1170
+ *
1171
+ * @param builder - 目标 builder(`build()` 之前调用)
1172
+ * @param cfg - `observability` 配置段;缺省时不做任何事
1173
+ * @param options - 可选:trace 文件名前缀(一般传 agentId)
1174
+ */
1175
+ export declare function wireObservability(builder: import('./harness/agent/builder.js').AgentBuilder, cfg: HarnessConfig['observability'] | undefined, options?: {
1176
+ filePrefix?: string;
1177
+ }): Promise<void>;
package/dist/config.js CHANGED
@@ -143,76 +143,7 @@ function resolveFallbackModels(fallbacks, models, defaults, depth = 0) {
143
143
  });
144
144
  }
145
145
  // ── Provider 工厂 ──
146
- // [timing probe] 长 session 首 run 延迟定位:LLM 调用计时装饰器(诊断后移除或转正)
147
- /**
148
- * 估算请求规模(字符近似值,仅用于计时日志)
149
- *
150
- * @param request - LLM 请求
151
- * @returns msgs/chars/toolChars 计数串
152
- */
153
- function timingReqSize(request) {
154
- let chars = 0;
155
- for (const m of request.messages ?? []) {
156
- const c = m.content;
157
- chars += typeof c === 'string' ? c.length : JSON.stringify(c ?? '').length;
158
- }
159
- const toolChars = request.tools ? JSON.stringify(request.tools).length : 0;
160
- return `msgs=${request.messages?.length ?? 0} chars=${chars} toolChars=${toolChars}`;
161
- }
162
- /**
163
- * 包一层计时探针:llm_start / llm_first_token(TTFT)/ llm_end
164
- *
165
- * @param inner - 真实 provider
166
- * @returns 透传装饰器
167
- */
168
- // [timing probe] 临时导出供 CLI daemon 的第二处 provider 工厂复用(诊断后随探针一起收)
169
- export function withTimingProbe(inner) {
170
- return {
171
- name: inner.name,
172
- defaultModel: inner.defaultModel,
173
- models: inner.models,
174
- isAvailable: () => inner.isAvailable(),
175
- getModelInfo: (modelName) => inner.getModelInfo(modelName),
176
- getModelInfos: () => inner.getModelInfos(),
177
- chat: async (request) => {
178
- const t0 = Date.now();
179
- console.log(`[timing] stage=llm_start ms=${t0} provider=${inner.name} mode=chat model=${request.model ?? inner.defaultModel ?? '?'} ${timingReqSize(request)}`);
180
- try {
181
- const res = await inner.chat(request);
182
- console.log(`[timing] stage=llm_end ms=${Date.now()} dur=${Date.now() - t0} provider=${inner.name} mode=chat outcome=ok finish=${res.finishReason ?? '?'} outChars=${(res.content ?? '').length}`);
183
- return res;
184
- }
185
- catch (err) {
186
- console.log(`[timing] stage=llm_end ms=${Date.now()} dur=${Date.now() - t0} provider=${inner.name} mode=chat outcome=error`);
187
- throw err;
188
- }
189
- },
190
- stream: async function* (request) {
191
- const t0 = Date.now();
192
- const model = request.model ?? inner.defaultModel ?? '?';
193
- console.log(`[timing] stage=llm_start ms=${t0} provider=${inner.name} mode=stream model=${model} ${timingReqSize(request)}`);
194
- let first = true;
195
- let outcome = 'abandoned';
196
- try {
197
- for await (const chunk of inner.stream(request)) {
198
- if (first) {
199
- first = false;
200
- console.log(`[timing] stage=llm_first_token ms=${Date.now()} ttft=${Date.now() - t0} provider=${inner.name} model=${model}`);
201
- }
202
- yield chunk;
203
- }
204
- outcome = 'ok';
205
- }
206
- catch (err) {
207
- outcome = 'error';
208
- throw err;
209
- }
210
- finally {
211
- console.log(`[timing] stage=llm_end ms=${Date.now()} dur=${Date.now() - t0} provider=${inner.name} mode=stream outcome=${outcome}`);
212
- }
213
- },
214
- };
215
- }
146
+ // ── 观测装配(F3/D5)──
216
147
  /**
217
148
  * 按 `observability.llmRequestDump` 配置构造 wire dump sink
218
149
  *
@@ -249,18 +180,19 @@ export async function createWireDumpSinkFromConfig(cfg) {
249
180
  * @param name - provider 名称
250
181
  * @param pc - provider 配置
251
182
  * @param options - 可选:wire dump sink(诊断用,见 `observability.llmRequestDump`)
252
- * @returns provider 实例(计时探针 → wire dump → 原生 provider 的装饰链)
183
+ * @returns provider 实例(wire dump → 原生 provider 的装饰链;LLM 计时已 observability 化进 model.call.*)
253
184
  */
254
185
  export async function createProviderFromConfig(name, pc, options) {
255
186
  const apiType = pc.api === 'anthropic-messages' ? 'anthropic' : 'openai';
256
187
  const models = pc.models.map(m => ({ name: m.name ?? m.id, contextWindow: m.contextWindow, maxOutputTokens: m.maxTokens }));
257
188
  const defaultModel = pc.models[0]?.name ?? pc.models[0]?.id;
258
- let decorate = withTimingProbe;
189
+ let decorate = (inner) => inner;
259
190
  if (options?.wireDump) {
260
- // 仅诊断路径才加载 wire dump(fs/crypto 不进入常规 provider 创建)
191
+ // 仅诊断路径才加载 wire dump(fs/crypto 不进入常规 provider 创建)。
192
+ // dump 必须贴在真实 provider 上才能拿到 `wireBodyFor`。
261
193
  const { withWireDump } = await import('./integration/providers/wire-dump.js');
262
194
  const sink = options.wireDump;
263
- decorate = (inner) => withTimingProbe(withWireDump(inner, sink));
195
+ decorate = (inner) => withWireDump(inner, sink);
264
196
  }
265
197
  if (apiType === 'anthropic') {
266
198
  const { AnthropicProvider } = await import('./integration/providers/anthropic.js');
@@ -269,3 +201,63 @@ export async function createProviderFromConfig(name, pc, options) {
269
201
  const { OpenAIProvider } = await import('./integration/providers/openai.js');
270
202
  return decorate(new OpenAIProvider({ name, apiKey: pc.apiKey, baseUrl: pc.baseUrl, models, defaultModel, timeoutMs: pc.timeoutSeconds ? pc.timeoutSeconds * 1000 : undefined }));
271
203
  }
204
+ /**
205
+ * 按 `observability` 配置构造 RunTelemetry 工厂(F3/D5 接线,组合根)
206
+ *
207
+ * TraceCollector → TraceLogger 按 `outputDir` 逐条同步落 JSONL(即 `traceDir`,无缓冲丢失风险);
208
+ * `level` / `consoleLevel` 与配置的 0–5 数值同构(FATAL=0 … TRACE=5,schema 已校验范围)。
209
+ * `consoleLevel` 缺省 null:trace 走文件通道,不向 gateway.log 混入控制台副本(要副本显式配置)。
210
+ *
211
+ * @param cfg - `observability` 配置段(level / consoleLevel / traceDir / capture*)
212
+ * @param options - 可选:trace 文件名前缀(多 agent 归属标识)
213
+ * @returns RunTelemetry 工厂(供 `AgentBuilder.telemetryFactory()` 注入)
214
+ */
215
+ export async function createTelemetryFactoryFromConfig(cfg, options) {
216
+ const { createRunTelemetry } = await import('./integration/observability/run-telemetry.js');
217
+ const { TraceCollector } = await import('./integration/observability/trace-collector.js');
218
+ const { getRunScope } = await import('./harness/run/run-scope.js');
219
+ // 配置 0–5 与 TraceLevel 数值同构;schema 保证 0-5 整数
220
+ const level = (cfg.level ?? 3);
221
+ const consoleLevel = (cfg.consoleLevel ?? null);
222
+ // 前缀进文件名:非法字符替换,防 agentId 越界成路径
223
+ const filePrefix = options?.filePrefix?.replace(/[^\w.-]/g, '_');
224
+ return (traceOptions) => createRunTelemetry({
225
+ ...traceOptions,
226
+ // model.call.* 归因:LoopObserver 路径经 RunScope ALS 取 sessionId/agentId(与 wire dump 同法)
227
+ resolveContext: () => {
228
+ const scope = getRunScope();
229
+ return scope ? { sessionId: scope.sessionId, agentId: scope.agentId } : {};
230
+ },
231
+ collector: new TraceCollector({
232
+ ...traceOptions,
233
+ level,
234
+ consoleLevel,
235
+ outputDir: cfg.traceDir ?? null,
236
+ ...(filePrefix ? { filePrefix } : {}),
237
+ }),
238
+ });
239
+ }
240
+ /**
241
+ * 按 `observability` 配置接线 AgentBuilder 观测装配(F3/D5)
242
+ *
243
+ * - 落盘:`traceDir / level / consoleLevel` → TraceCollector → JSONL
244
+ * - 采集意图:`captureStreamDeltas / captureModelRequest` → `AgentBuilder.trace()`
245
+ * - 工厂显式注入,不依赖包入口 `setRunTelemetryFactory` 副作用
246
+ * (serve / 子路径 import 时该副作用未必执行过,不能拿它当接线)
247
+ *
248
+ * @param builder - 目标 builder(`build()` 之前调用)
249
+ * @param cfg - `observability` 配置段;缺省时不做任何事
250
+ * @param options - 可选:trace 文件名前缀(一般传 agentId)
251
+ */
252
+ export async function wireObservability(builder, cfg, options) {
253
+ if (!cfg)
254
+ return;
255
+ builder.telemetryFactory(await createTelemetryFactoryFromConfig(cfg, options));
256
+ builder.trace({
257
+ captureStreamDeltas: cfg.captureStreamDeltas,
258
+ captureModelRequest: cfg.captureModelRequest,
259
+ // metrics 读取口未暴露(Builder 无 getTelemetry)且 LatencyTracker 无界:
260
+ // 暴露读取口前不启用,避免长驻 serve 只写不读的内存增长
261
+ enableMetrics: false,
262
+ });
263
+ }
@@ -287,6 +287,7 @@ export declare class AgentBuilder {
287
287
  * 设置 Skill 目录(子目录内含 SKILL.md)
288
288
  *
289
289
  * build 时 discover,每轮以索引形式注入 system prompt(formatForPrompt)。
290
+ * `~` 形态在此展开(与 workspace / agentHome 同规,幂等)。
290
291
  */
291
292
  skillDirectory(dir: string): this;
292
293
  /** 直接注入 SkillManager(跳过目录 discover) */
@@ -421,9 +422,9 @@ export declare class AgentBuilder {
421
422
  /** 加载 persona 目录 */
422
423
  persona(workspace: string): this;
423
424
  persona(...workspaces: string[]): this;
424
- /** 设置 Agent 沙箱工作目录(注入到内置工具的 cwd) */
425
+ /** 设置 Agent 沙箱工作目录(注入到内置工具的 cwd);`~` 形态在此展开(trim → expand) */
425
426
  workspace(dir: string): this;
426
- /** agent 文件态 home:extract 落盘、与 persona 目录解耦 */
427
+ /** agent 文件态 home:extract 落盘、与 persona 目录解耦;`~` 形态在此展开(与 workspace 同规) */
427
428
  agentHome(dir: string): this;
428
429
  /** 逻辑 agentId(extract pending 扫描 / 观测) */
429
430
  agentId(id: string): this;
@@ -14,6 +14,7 @@
14
14
  * ```
15
15
  */
16
16
  import { DefaultToolBus } from '../extension/plugin-ecosystem/tools/tool-bus.js';
17
+ import { expandHomePath } from '../../paths.js';
17
18
  import { createUnconfiguredFileEffects, createUnconfiguredMemoryEffects, } from '../extension/execution-environment/undo-log.js';
18
19
  import { JournaledMemoryStore } from '../extension/execution-environment/memory-undo.js';
19
20
  import { buildToolLlmParameters, prepareHandlerArgs, resolveToolCallPurpose, sanitizeToolJsonSchema, } from './tool-purpose.js';
@@ -545,9 +546,10 @@ export class AgentBuilder {
545
546
  * 设置 Skill 目录(子目录内含 SKILL.md)
546
547
  *
547
548
  * build 时 discover,每轮以索引形式注入 system prompt(formatForPrompt)。
549
+ * `~` 形态在此展开(与 workspace / agentHome 同规,幂等)。
548
550
  */
549
551
  skillDirectory(dir) {
550
- this._skillDirectory = dir;
552
+ this._skillDirectory = expandHomePath(dir.trim());
551
553
  return this;
552
554
  }
553
555
  /** 直接注入 SkillManager(跳过目录 discover) */
@@ -762,14 +764,14 @@ export class AgentBuilder {
762
764
  this._personaWorkspaces.push(...workspaces);
763
765
  return this;
764
766
  }
765
- /** 设置 Agent 沙箱工作目录(注入到内置工具的 cwd) */
767
+ /** 设置 Agent 沙箱工作目录(注入到内置工具的 cwd);`~` 形态在此展开(trim → expand) */
766
768
  workspace(dir) {
767
- this._workspace = dir;
769
+ this._workspace = expandHomePath(dir.trim());
768
770
  return this;
769
771
  }
770
- /** agent 文件态 home:extract 落盘、与 persona 目录解耦 */
772
+ /** agent 文件态 home:extract 落盘、与 persona 目录解耦;`~` 形态在此展开(与 workspace 同规) */
771
773
  agentHome(dir) {
772
- this._agentHome = dir;
774
+ this._agentHome = expandHomePath(dir.trim());
773
775
  return this;
774
776
  }
775
777
  /** 逻辑 agentId(extract pending 扫描 / 观测) */
@@ -1062,6 +1064,9 @@ export class AgentBuilder {
1062
1064
  let subsystemRuntime;
1063
1065
  if (candidateSpecs.length > 0 || this._subsystemDir) {
1064
1066
  const { SubsystemRuntime } = await import('../collaboration/autonomous-subsystem/runtime.js');
1067
+ const { probeProcessIsolation, assessL4ProcessMinimum } = await import('../extension/execution-environment/process-isolation.js');
1068
+ const isolationProfile = await probeProcessIsolation();
1069
+ const securityEnforcement = { l4Available: assessL4ProcessMinimum(isolationProfile).ok };
1065
1070
  subsystemRuntime = new SubsystemRuntime({
1066
1071
  deps: {
1067
1072
  model: agent.model,
@@ -1073,6 +1078,7 @@ export class AgentBuilder {
1073
1078
  },
1074
1079
  auditDir: this._subsystemAuditDir,
1075
1080
  agentId: this._agentId,
1081
+ securityEnforcement,
1076
1082
  });
1077
1083
  const registeredIds = new Set();
1078
1084
  const tryRegister = (spec) => {
@@ -1530,8 +1536,6 @@ export class AgentBuilder {
1530
1536
 
1531
1537
  ${toolList}
1532
1538
 
1533
- Every tool call must include a short honest purpose field (verb + object + goal, e.g. "read package.json to find test script") — humans and approvers see it as the call title.
1534
-
1535
1539
  Tool selection (strict):
1536
1540
  1. Prefer a dedicated tool when one covers the job (file_read / file_list / file_write / file_edit / file_delete / file_mkdir / file_rename / file_copy / file_stat / file_rmdir / file_search / env_info, and any task-specific tool).
1537
1541
  2. If a dedicated-tool call fails because your arguments were wrong (bad path, bad params), fix the call and retry that tool — do not switch to shell for a call you can fix.
@@ -13,7 +13,7 @@
13
13
  * // agents.get('assistant') → { engine, runner }
14
14
  * ```
15
15
  */
16
- import { createProviderFromConfig, createWireDumpSinkFromConfig, resolveModelConfig } from '../../config.js';
16
+ import { createProviderFromConfig, createWireDumpSinkFromConfig, resolveModelConfig, wireObservability } from '../../config.js';
17
17
  import { SubsystemLoader } from '../collaboration/autonomous-subsystem/loader.js';
18
18
  import { homedir } from 'node:os';
19
19
  import { resolve, join } from 'node:path';
@@ -130,6 +130,7 @@ export async function buildFromConfig(config, options) {
130
130
  sessionIdleExpiryMs: config.session?.idleExpiryMs,
131
131
  modelCallConfig: config.modelCall,
132
132
  concurrencyConfig: config.concurrency,
133
+ observabilityConfig: config.observability,
133
134
  });
134
135
  agents.set(agentConfig.id, built);
135
136
  }
@@ -210,6 +211,8 @@ async function buildAgent(agentConfig, shared) {
210
211
  subsystemDenylist: shared.subsystemDenylist,
211
212
  concurrencyConfig: shared.concurrencyConfig,
212
213
  });
214
+ // ── 观测装配(F3/D5):observability 配置 → trace 落盘 + 采集意图 ──
215
+ await wireObservability(builder, shared.observabilityConfig, { filePrefix: agentConfig.id });
213
216
  // ── Build ──
214
217
  const built = await builder.build({
215
218
  autoLoadSubsystems: shouldAutoLoadSubsystems(shared),
@@ -5,11 +5,19 @@
5
5
  * 禁止 builder / gateway / tool-bus 各自拼一套(否则模型看到的 required 不一致)。
6
6
  */
7
7
  import type { ToolDefinition, ToolParameter } from '@octopi-agent/core/types.js';
8
- /** 统一注入的行动简述参数 */
8
+ /**
9
+ * 统一注入的行动简述参数。
10
+ *
11
+ * description 只留极短 stub(schema 自解释兜底);详版+示例在 TOOL_PURPOSE_SYSTEM_NOTE
12
+ * 全局说明(system prompt 稳定块)只写一次——55 个工具不再重复同一段 157 字符文案
13
+ * (方案 S,arch/tool-call-purpose.md「演进」)。
14
+ */
9
15
  export declare const TOOL_PURPOSE_PARAM: {
10
16
  type: "string";
11
17
  description: string;
12
18
  };
19
+ /** purpose 填法的全局说明(详版与示例唯一来源;system prompt 稳定块,缓存无损) */
20
+ export declare const TOOL_PURPOSE_SYSTEM_NOTE = "### Tool call purpose\nEvery tool call MUST include a `purpose` argument: one short honest line for humans and approvers \u2014 what the call does and why (verb + object + goal, max 120 chars). Example: \"overwrite src/a.ts to fix timeout\". Never leave it empty.";
13
21
  /** 仅保留 OpenAI function calling 可识别的 JSON Schema 关键字 */
14
22
  export declare function sanitizeToolJsonSchema(node: unknown): unknown;
15
23
  /**
@@ -1,8 +1,17 @@
1
- /** 统一注入的行动简述参数 */
1
+ /**
2
+ * 统一注入的行动简述参数。
3
+ *
4
+ * description 只留极短 stub(schema 自解释兜底);详版+示例在 TOOL_PURPOSE_SYSTEM_NOTE
5
+ * 全局说明(system prompt 稳定块)只写一次——55 个工具不再重复同一段 157 字符文案
6
+ * (方案 S,arch/tool-call-purpose.md「演进」)。
7
+ */
2
8
  export const TOOL_PURPOSE_PARAM = {
3
9
  type: 'string',
4
- description: 'One short honest line for humans and approvers: what this call does and why (verb + object + goal, max 120 chars). Example: "overwrite src/a.ts to fix timeout".',
10
+ description: 'Call purpose: what + why, ≤120 chars',
5
11
  };
12
+ /** purpose 填法的全局说明(详版与示例唯一来源;system prompt 稳定块,缓存无损) */
13
+ export const TOOL_PURPOSE_SYSTEM_NOTE = `### Tool call purpose
14
+ Every tool call MUST include a \`purpose\` argument: one short honest line for humans and approvers — what the call does and why (verb + object + goal, max 120 chars). Example: "overwrite src/a.ts to fix timeout". Never leave it empty.`;
6
15
  /** 仅保留 OpenAI function calling 可识别的 JSON Schema 关键字 */
7
16
  export function sanitizeToolJsonSchema(node) {
8
17
  if (Array.isArray(node))
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import { existsSync } from 'node:fs';
15
15
  import { join } from 'node:path';
16
+ import { expandHomePath } from '../../paths.js';
16
17
  import { getOctopiHome } from '../../paths.js';
17
18
  import { DefaultRunGuard, } from '../run/run-guard/default-run-guard.js';
18
19
  import { DefaultContextEngine } from '../context/default-context-engine.js';
@@ -166,7 +167,9 @@ export async function wireAgentBuilder(builder, spec) {
166
167
  // ── Home / Persona / Skills ──
167
168
  // stores 只跟显式 home 走;string persona 只作 prompt 目录,不隐式开 agent.db
168
169
  //(config-bridge 需要 legacy persona-as-home 时应显式传 home)。
169
- const agentHome = spec.home;
170
+ // home/skillDirectory 在库边界展开 `~`(幂等):`join()` 与 agent.db 路径都以它为基,
171
+ // 留一个未展开的 `~` 就会在进程 cwd 下建出字面 `~/…` 目录。
172
+ const agentHome = spec.home ? expandHomePath(spec.home.trim()) : undefined;
170
173
  // agentId 无条件接线(审计分区 / 工具域对称);home 只决定 agent 文件态目录
171
174
  builder.agentId(spec.agentId);
172
175
  if (spec.home) {
@@ -181,7 +184,11 @@ export async function wireAgentBuilder(builder, spec) {
181
184
  else if (agentHome) {
182
185
  builder.persona(agentHome);
183
186
  }
184
- const skillDir = spec.skillDirectory ?? (agentHome ? join(agentHome, 'skills') : undefined);
187
+ const skillDir = spec.skillDirectory
188
+ ? expandHomePath(spec.skillDirectory.trim())
189
+ : agentHome
190
+ ? join(agentHome, 'skills')
191
+ : undefined;
185
192
  let skillManager;
186
193
  if (skillDir && existsSync(skillDir)) {
187
194
  try {
@@ -6,6 +6,15 @@
6
6
  * @module autonomous-subsystem/boundary/validator
7
7
  */
8
8
  import type { SubsystemSpec } from '../types.js';
9
+ /**
10
+ * SEC-6 执行上下文:声明必须可兑现。
11
+ * `sandboxed` 是加载器的硬承诺(环境须满足 L4 process 最低线);
12
+ * `trusted | privileged` 是作者承诺(advisory,见 docs/autonomous-subsystem.md)。
13
+ */
14
+ export interface SecurityEnforcementContext {
15
+ /** 环境是否满足 L4 process 最低线(`assessL4ProcessMinimum`) */
16
+ l4Available: boolean;
17
+ }
9
18
  /**
10
19
  * 校验错误
11
20
  */
@@ -19,6 +28,7 @@ export interface ValidationError {
19
28
  * 校验 SubsystemSpec 的内部一致性
20
29
  *
21
30
  * @param spec - 子系统规格
31
+ * @param enforcement - SEC-6 执行上下文(宿主能力声明,必填:校验器不替调用方猜环境)
22
32
  * @returns 校验错误数组,空数组表示通过
23
33
  */
24
- export declare function validateSubsystemSpec(spec: SubsystemSpec): ValidationError[];
34
+ export declare function validateSubsystemSpec(spec: SubsystemSpec, enforcement: SecurityEnforcementContext): ValidationError[];
@@ -18,9 +18,10 @@ const AUTHORITY_ACT_MAP = {
18
18
  * 校验 SubsystemSpec 的内部一致性
19
19
  *
20
20
  * @param spec - 子系统规格
21
+ * @param enforcement - SEC-6 执行上下文(宿主能力声明,必填:校验器不替调用方猜环境)
21
22
  * @returns 校验错误数组,空数组表示通过
22
23
  */
23
- export function validateSubsystemSpec(spec) {
24
+ export function validateSubsystemSpec(spec, enforcement) {
24
25
  const errors = [];
25
26
  if (!spec.boundary)
26
27
  errors.push({ field: 'boundary', message: 'boundary is required' });
@@ -30,6 +31,15 @@ export function validateSubsystemSpec(spec) {
30
31
  errors.push({ field: 'act', message: 'act is required' });
31
32
  if (!spec.boundary || !spec.signal || !spec.act)
32
33
  return errors;
34
+ // ── SEC-6:`sandboxed` 声明必须可兑现(fail-closed)──
35
+ // `sandboxed` 是加载器的硬承诺:环境达不到 L4 process 最低线就拒绝加载,
36
+ // 绝不允许「看起来已沙箱」。`trusted | privileged` 是作者承诺(advisory),不在此拦截。
37
+ if (spec.boundary.security === 'sandboxed' && !enforcement.l4Available) {
38
+ errors.push({
39
+ field: 'boundary.security',
40
+ message: 'security "sandboxed" requires L4 process isolation (bwrap/Seatbelt/Job) in this environment; declare trusted/privileged explicitly or run where L4 exists',
41
+ });
42
+ }
33
43
  // ── act.mode 与 boundary.authority 交叉校验 ──
34
44
  const allowedModes = AUTHORITY_ACT_MAP[spec.boundary.authority];
35
45
  if (!allowedModes.has(spec.act.mode)) {