@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
@@ -32,6 +32,8 @@ export interface AgentEventMap {
32
32
  stopped?: boolean;
33
33
  error?: boolean;
34
34
  usage?: import('@octopi-agent/core/types/turn.js').TokenUsage;
35
+ /** F3 LLM 计时摘要(loop turn_end 透传;Run 页签耗时区消费) */
36
+ llmTiming?: import('@octopi-agent/core/loop/types.js').LoopLLMTiming;
35
37
  contextTokens?: number;
36
38
  contextWindow?: number;
37
39
  };
@@ -61,6 +63,28 @@ export interface AgentEventMap {
61
63
  deleted?: string[];
62
64
  };
63
65
  };
66
+ /** Runner 收口计时(F3 `[timing]` 探针转正;wait/build/run_end 分段,事件旁路 eventSink) */
67
+ 'run.timing': {
68
+ stage: 'run_start' | 'context_ready' | 'run_end';
69
+ /** 排队/等锁耗时(stage=run_start) */
70
+ waitMs?: number;
71
+ /** 上下文组装耗时,从拿锁后起算(stage=context_ready) */
72
+ buildMs?: number;
73
+ /** 消息数(stage=context_ready) */
74
+ msgs?: number;
75
+ /** system prompt 稳定前缀字符数(E8 后不含易变快照) */
76
+ sysChars?: number;
77
+ /** grounding 估算 tokens(stage=context_ready) */
78
+ groundingTokens?: number;
79
+ /** run 总耗时(stage=run_end) */
80
+ durMs?: number;
81
+ /** 观测口径结束原因(stage=run_end) */
82
+ reason?: string;
83
+ /** 循环结束原因(stage=run_end) */
84
+ loopEnd?: string;
85
+ /** 停止闸门原因(stage=run_end) */
86
+ stopReason?: string;
87
+ };
64
88
  'budget.exceeded': {
65
89
  reason: 'wall_clock' | 'iteration' | 'tool_calls';
66
90
  report?: unknown;
@@ -253,6 +277,8 @@ export declare const AgentEvents: {
253
277
  readonly ENGINE_ERROR: "engine.error";
254
278
  readonly ITERATION_START: "iteration.start";
255
279
  readonly TURN_END: "turn.end";
280
+ /** Runner 收口计时(F3 转正) */
281
+ readonly RUN_TIMING: "run.timing";
256
282
  readonly TOOL_EXEC_START: "tool.exec.start";
257
283
  readonly TOOL_EXEC_END: "tool.exec.end";
258
284
  readonly INJECTION_DETECTED: "injection.detected";
@@ -20,6 +20,8 @@ export const AgentEvents = {
20
20
  ENGINE_ERROR: 'engine.error',
21
21
  ITERATION_START: 'iteration.start',
22
22
  TURN_END: 'turn.end',
23
+ /** Runner 收口计时(F3 转正) */
24
+ RUN_TIMING: 'run.timing',
23
25
  TOOL_EXEC_START: 'tool.exec.start',
24
26
  TOOL_EXEC_END: 'tool.exec.end',
25
27
  INJECTION_DETECTED: 'injection.detected',
package/dist/index.d.ts CHANGED
@@ -40,7 +40,7 @@ export { TurnFileUndoLog, commitSessionFileUndo, discardSessionFileUndo, resolve
40
40
  export { TurnMemoryJournal, JournaledMemoryStore, createMemoryRestorer, discardMemoryUndo, } from './harness/extension/execution-environment/memory-undo.js';
41
41
  export type { MemoryUndoEntry, MemoryEffectRestorer, DiscardMemoryEffectsResult, } from './harness/extension/execution-environment/memory-undo.js';
42
42
  export type { MemoryEffectJournal, MemoryEffectDomain } from '@octopi-agent/core/types/tools.js';
43
- export { resolveEffectiveEffectPolicy, isPathAllowed, isToolAllowedOnSurface, DEFAULT_EFFECT_RUN_MODE, readSessionEffectOverrides, normalizeTransactionRoots, mergeTransactionRoots, SESSION_EFFECT_OVERRIDES_KEY, } from './harness/extension/execution-environment/effect-policy.js';
43
+ export { resolveEffectiveEffectPolicy, requiresJail, isPathAllowed, isToolAllowedOnSurface, DEFAULT_EFFECT_RUN_MODE, readSessionEffectOverrides, normalizeTransactionRoots, mergeTransactionRoots, SESSION_EFFECT_OVERRIDES_KEY, } from './harness/extension/execution-environment/effect-policy.js';
44
44
  export { ProcessSandbox, createProcessSandbox, assessL4ProcessMinimum, probeProcessIsolation, scrubEnv, killProcessTree, supervisedSpawnProfile, } from './harness/extension/execution-environment/index.js';
45
45
  export type { ProcessIsolationProfile, IsolationBackend, L4ProcessAssessment, } from './harness/extension/execution-environment/process-isolation.js';
46
46
  export { runWithToolLimits, resolveToolTimeoutMs, ToolTimeoutError, } from './harness/extension/execution-environment/resource-limits.js';
@@ -83,11 +83,13 @@ export type { SkillDefinition, SkillManager } from './harness/extension/plugin-e
83
83
  /** 产品装配 DTO(非 Kernel);ModelInfo/ToolPolicy 仍从 core/types 导出 */
84
84
  export type { AgentPersona, ModelConfig, AgentDefinition } from './harness/shared/types/agent-definition.js';
85
85
  export { DefaultToolBus } from './harness/extension/plugin-ecosystem/tools/tool-bus.js';
86
- export { buildToolLlmParameters, prepareHandlerArgs, readToolCallPurpose, resolveToolCallPurpose, sanitizeToolJsonSchema, toolDeclaresPurpose, TOOL_PURPOSE_PARAM, } from './harness/agent/tool-purpose.js';
86
+ export { buildToolLlmParameters, prepareHandlerArgs, readToolCallPurpose, resolveToolCallPurpose, sanitizeToolJsonSchema, toolDeclaresPurpose, TOOL_PURPOSE_PARAM, TOOL_PURPOSE_SYSTEM_NOTE, } from './harness/agent/tool-purpose.js';
87
87
  export { createClientTool, makeClientToolCallId, ClientToolRegistry, DEFAULT_CLIENT_TOOL_TIMEOUT_MS, } from './harness/extension/plugin-ecosystem/client-tools/index.js';
88
88
  export type { ClientToolCall, ClientToolCallId, ClientToolCallOutcome, ClientToolDescriptor, ClientToolDeviceMeta, ClientToolErrorReason, ClientToolInvoker, ClientToolInteraction, ClientToolName, ClientToolProvider, ClientToolFileRef, ClientToolResult, ClientToolSensitivity, ClientToolRouteDecision, } from './harness/extension/plugin-ecosystem/client-tools/index.js';
89
89
  export { getBuiltinTools, createShellTool, createFileReadTool, createFileWriteTool, createFileListTool } from './harness/extension/plugin-ecosystem/tools/builtin.js';
90
90
  export { createToolSet } from './harness/extension/plugin-ecosystem/tools/tool-set.js';
91
+ export { readGitStatusSnapshot, parsePorcelainV2 } from './harness/extension/plugin-ecosystem/tools/git-status-snapshot.js';
92
+ export type { GitStatusSnapshot, GitStatusSnapshotBody, GitStatusSnapshotOptions, GitStatusEntry, GitStatusBranch, GitStatusCounts, GitStatusGroup, GitStatusKind, } from './harness/extension/plugin-ecosystem/tools/git-status-snapshot.js';
91
93
  export { createSummaryPort, applyToolOutputGate, createCompactEngine } from './harness/context/capabilities/index.js';
92
94
  export { createDefaultDocumentPort, createDocumentPortFromConfig, DocumentExtractError } from './harness/capabilities/document/index.js';
93
95
  export type { SummaryPort, SummaryPolicy, ContentUnit, ToolSummarySupport, CompactEngine } from './harness/context/capabilities/index.js';
package/dist/index.js CHANGED
@@ -27,7 +27,7 @@ export { SessionAwareRunner } from './harness/run/runner.js';
27
27
  export { DEFAULT_TOOL_ISOLATION, resolveToolIsolationCwd, } from './harness/extension/execution-environment/isolation.js';
28
28
  export { TurnFileUndoLog, commitSessionFileUndo, discardSessionFileUndo, resolveSessionUndoPaths, resolveSessionUndoOnClose, createUnconfiguredFileEffects, createUnconfiguredMemoryEffects, } from './harness/extension/execution-environment/undo-log.js';
29
29
  export { TurnMemoryJournal, JournaledMemoryStore, createMemoryRestorer, discardMemoryUndo, } from './harness/extension/execution-environment/memory-undo.js';
30
- export { resolveEffectiveEffectPolicy, isPathAllowed, isToolAllowedOnSurface, DEFAULT_EFFECT_RUN_MODE, readSessionEffectOverrides, normalizeTransactionRoots, mergeTransactionRoots, SESSION_EFFECT_OVERRIDES_KEY, } from './harness/extension/execution-environment/effect-policy.js';
30
+ export { resolveEffectiveEffectPolicy, requiresJail, isPathAllowed, isToolAllowedOnSurface, DEFAULT_EFFECT_RUN_MODE, readSessionEffectOverrides, normalizeTransactionRoots, mergeTransactionRoots, SESSION_EFFECT_OVERRIDES_KEY, } from './harness/extension/execution-environment/effect-policy.js';
31
31
  export { ProcessSandbox, createProcessSandbox, assessL4ProcessMinimum, probeProcessIsolation, scrubEnv, killProcessTree, supervisedSpawnProfile, } from './harness/extension/execution-environment/index.js';
32
32
  export { runWithToolLimits, resolveToolTimeoutMs, ToolTimeoutError, } from './harness/extension/execution-environment/resource-limits.js';
33
33
  export { scanOrphanSessionUndo, } from './harness/extension/execution-environment/undo-log.js';
@@ -51,10 +51,11 @@ export { CapabilityRegistry } from './harness/extension/plugin-ecosystem/plugins
51
51
  export { validateManifest, parseManifest } from './harness/extension/plugin-ecosystem/plugins/manifest.js';
52
52
  export { DefaultSkillManager, FileSystemSkillSource } from './harness/extension/plugin-ecosystem/skills/manager.js';
53
53
  export { DefaultToolBus } from './harness/extension/plugin-ecosystem/tools/tool-bus.js';
54
- export { buildToolLlmParameters, prepareHandlerArgs, readToolCallPurpose, resolveToolCallPurpose, sanitizeToolJsonSchema, toolDeclaresPurpose, TOOL_PURPOSE_PARAM, } from './harness/agent/tool-purpose.js';
54
+ export { buildToolLlmParameters, prepareHandlerArgs, readToolCallPurpose, resolveToolCallPurpose, sanitizeToolJsonSchema, toolDeclaresPurpose, TOOL_PURPOSE_PARAM, TOOL_PURPOSE_SYSTEM_NOTE, } from './harness/agent/tool-purpose.js';
55
55
  export { createClientTool, makeClientToolCallId, ClientToolRegistry, DEFAULT_CLIENT_TOOL_TIMEOUT_MS, } from './harness/extension/plugin-ecosystem/client-tools/index.js';
56
56
  export { getBuiltinTools, createShellTool, createFileReadTool, createFileWriteTool, createFileListTool } from './harness/extension/plugin-ecosystem/tools/builtin.js';
57
57
  export { createToolSet } from './harness/extension/plugin-ecosystem/tools/tool-set.js';
58
+ export { readGitStatusSnapshot, parsePorcelainV2 } from './harness/extension/plugin-ecosystem/tools/git-status-snapshot.js';
58
59
  export { createSummaryPort, applyToolOutputGate, createCompactEngine } from './harness/context/capabilities/index.js';
59
60
  export { createDefaultDocumentPort, createDocumentPortFromConfig, DocumentExtractError } from './harness/capabilities/document/index.js';
60
61
  export { createWebSearchTool } from './harness/extension/plugin-ecosystem/tools/web-search.js';
@@ -18,6 +18,14 @@ export interface CreateRunTelemetryOptions {
18
18
  /** 预创建实例(测试注入) */
19
19
  collector?: TraceCollector;
20
20
  metricsInstance?: MetricsAggregator;
21
+ /**
22
+ * 归因上下文解析(组合根注入,如 RunScope ALS)。
23
+ * LoopObserver 路径的 model.call.* 行靠它带 sessionId/agentId。
24
+ */
25
+ resolveContext?: () => {
26
+ sessionId?: string;
27
+ agentId?: string;
28
+ };
21
29
  }
22
30
  /**
23
31
  * 创建一套 RunTelemetry
@@ -45,31 +45,54 @@ export function createRunTelemetry(options = {}) {
45
45
  /**
46
46
  * 只补 LLM 调用生命周期(Runner 事件流无 model.call.*)。
47
47
  * 工具事件由 onEvent 接收 Runner 的 tool.exec.*,避免双计。
48
+ *
49
+ * 计时按 callId 隔离(同 agent 并发 run 共用本 observer,单变量会互相覆盖)。
48
50
  */
49
51
  createLoopObserver(traceOpts) {
50
52
  const c = ensureCollector(traceOpts);
51
- let llmStartTs = 0;
53
+ /** callId → 计时状态(onLLMEnd 清理,无泄漏) */
54
+ const calls = new Map();
55
+ const ctx = () => options.resolveContext?.() ?? {};
56
+ /** 无 callId 的旧调用方回退键(顺序调用沿用旧单变量语义;并发场景请传 callId) */
57
+ const keyOf = (callId) => callId ?? 'default';
52
58
  return {
53
59
  onLLMStart(params) {
54
- llmStartTs = Date.now();
60
+ const startTs = Date.now();
61
+ calls.set(keyOf(params.callId), { startTs });
55
62
  c.record({
56
63
  type: 'model.call.start',
57
- timestamp: llmStartTs,
58
- data: { model: params.model },
59
- }, {});
64
+ timestamp: startTs,
65
+ data: {
66
+ model: params.model,
67
+ callId: params.callId,
68
+ reqChars: params.reqChars,
69
+ toolChars: params.toolChars,
70
+ },
71
+ }, ctx());
72
+ },
73
+ onLLMFirstToken(params) {
74
+ const call = calls.get(keyOf(params.callId));
75
+ if (call)
76
+ call.ttftMs = params.ttftMs;
60
77
  },
61
78
  onLLMEnd(params) {
62
- const durationMs = llmStartTs ? Date.now() - llmStartTs : 0;
63
- llmStartTs = 0;
79
+ const call = calls.get(keyOf(params.callId));
80
+ calls.delete(keyOf(params.callId));
81
+ // 无 start 记录(异常调用序)时 duration 缺省,不伪造 0
82
+ const durationMs = call ? Date.now() - call.startTs : undefined;
64
83
  c.record({
65
84
  type: 'model.call.end',
66
85
  timestamp: Date.now(),
67
86
  data: {
68
87
  model: params.model,
88
+ callId: params.callId,
69
89
  usage: params.usage,
70
90
  durationMs,
91
+ ttftMs: params.ttftMs ?? call?.ttftMs,
92
+ outChars: params.outChars,
93
+ finishReason: params.finishReason,
71
94
  },
72
- }, {});
95
+ }, ctx());
73
96
  },
74
97
  };
75
98
  },
@@ -46,13 +46,20 @@ export class TraceCollector {
46
46
  const turnId = `turn_${++this.turnCount}`;
47
47
  this.currentTurnId = turnId;
48
48
  this.logger.info(TRACE_EVENTS.TURN_START, { turnId }, ctx);
49
+ let sawTurnEnd = false;
49
50
  for await (const event of events) {
51
+ if (event.type === 'turn.end')
52
+ sawTurnEnd = true;
50
53
  // 记录到 trace
51
54
  this.recordEvent(event, ctx, turnId);
52
55
  // 原样传递
53
56
  yield event;
54
57
  }
55
- this.logger.info(TRACE_EVENTS.TURN_END, { turnId }, ctx);
58
+ // 收口行仅在事件流自身无 turn.end 时补——recordEvent 已把 turn.end 映射为 TURN_END,
59
+ // 再补一行即双计(turn 统计翻倍)
60
+ if (!sawTurnEnd) {
61
+ this.logger.info(TRACE_EVENTS.TURN_END, { turnId }, ctx);
62
+ }
56
63
  }
57
64
  /**
58
65
  * 获取 MetricsAggregator 实例
@@ -92,29 +99,44 @@ export class TraceCollector {
92
99
  case 'turn.start':
93
100
  this.logger.info(TRACE_EVENTS.TURN_START, { turnId }, base);
94
101
  break;
95
- // Runner 词表:turn.end 携带 usage,映射为 model.call.end
102
+ // Runner 词表:turn.end 携带 usage。F3-c 起不再冒充 model.call.end
103
+ //(LoopObserver 的 model.call.end 才带 durationMs/ttft;两行各归各位,p50/p95 取数不双计。
104
+ // F3-d 起 turn.end 事件还带 llmTiming 供 UI timeline 展示,本白名单仍不落盘——trace 指标只认 model.call.*)
96
105
  case 'turn.end':
97
- this.logger.info(TRACE_EVENTS.MODEL_CALL_END, {
106
+ this.logger.info(TRACE_EVENTS.TURN_END, {
98
107
  contentLength: event.data?.content?.length ?? 0,
99
108
  usage: event.data?.usage,
100
109
  turnId,
101
110
  }, base);
102
- this.logger.info(TRACE_EVENTS.TURN_END, { turnId }, base);
103
111
  break;
104
112
  case 'model.call.start':
105
113
  this.logger.info(TRACE_EVENTS.MODEL_CALL_START, {
106
114
  model: event.data?.model,
115
+ callId: event.data?.callId,
116
+ reqChars: event.data?.reqChars,
117
+ toolChars: event.data?.toolChars,
107
118
  turnId,
108
119
  }, base);
109
120
  break;
110
121
  case 'model.call.end':
111
122
  this.logger.info(TRACE_EVENTS.MODEL_CALL_END, {
123
+ model: event.data?.model,
124
+ callId: event.data?.callId,
125
+ // durationMs/ttftMs/reqChars 是 F3 回归指标口径(long-session-latency §7):白名单漏掉即断档
126
+ durationMs: event.data?.durationMs,
127
+ ttftMs: event.data?.ttftMs,
128
+ outChars: event.data?.outChars,
129
+ finishReason: event.data?.finishReason,
112
130
  contentLength: event.data?.content?.length ?? 0,
113
131
  toolCallCount: event.data?.toolCallCount ?? 0,
114
132
  usage: event.data?.usage,
115
133
  turnId,
116
134
  }, base);
117
135
  break;
136
+ // Runner 收口计时(wait/build/run_end;`[timing]` 探针转正,F3)
137
+ case 'run.timing':
138
+ this.logger.info(TRACE_EVENTS.RUN_TIMING, event.data, base);
139
+ break;
118
140
  case 'model.call.error':
119
141
  this.logger.error(TRACE_EVENTS.MODEL_CALL_ERROR, {
120
142
  error: event.data?.error,
@@ -47,6 +47,7 @@ export declare const TRACE_EVENTS: {
47
47
  readonly TOOL_EXEC_END: "tool.exec.end";
48
48
  readonly SESSION_LOAD: "session.load";
49
49
  readonly SESSION_SAVE: "session.save";
50
+ readonly RUN_TIMING: "run.timing";
50
51
  readonly MODEL_RETRY: "model.retry";
51
52
  readonly MODEL_FALLBACK: "model.fallback";
52
53
  readonly EMPTY_RESPONSE: "empty.response";
@@ -42,6 +42,8 @@ export const TRACE_EVENTS = {
42
42
  TOOL_EXEC_END: 'tool.exec.end',
43
43
  SESSION_LOAD: 'session.load',
44
44
  SESSION_SAVE: 'session.save',
45
+ // Runner 收口计时(wait/build/run_end;F3 `[timing]` 探针转正)
46
+ RUN_TIMING: 'run.timing',
45
47
  // Level 2: WARN
46
48
  MODEL_RETRY: 'model.retry',
47
49
  MODEL_FALLBACK: 'model.fallback',
@@ -22,6 +22,8 @@ const DEFAULT_CONFIG = {
22
22
  filePrefix: 'trace',
23
23
  sync: false,
24
24
  };
25
+ /** 进程内 trace 文件序号(同毫秒多实例防撞) */
26
+ let fileSeq = 0;
25
27
  /**
26
28
  * TraceLogger
27
29
  */
@@ -35,26 +37,34 @@ export class TraceLogger {
35
37
  this.config = { ...DEFAULT_CONFIG, ...config };
36
38
  // 初始化导出器
37
39
  this.exporters = config?.exporters ?? [];
38
- // 初始化文件输出(兼容旧的 outputDir 模式)
40
+ // 初始化文件输出(兼容旧的 outputDir 模式)。失败 fail-open:观测绝不影响业务构建
39
41
  if (this.config.outputDir) {
40
42
  const dir = this.config.outputDir;
41
- if (!existsSync(dir)) {
42
- mkdirSync(dir, { recursive: true });
43
+ try {
44
+ if (!existsSync(dir)) {
45
+ mkdirSync(dir, { recursive: true });
46
+ }
47
+ // 文件名唯一化:毫秒时间戳 + pid + 进程内序号(同秒多 agent / 多实例不共写一个文件)
48
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
49
+ const prefix = this.config.filePrefix ?? 'trace';
50
+ this.filePath = join(dir, `${prefix}-${ts}-${process.pid}-${++fileSeq}.jsonl`);
51
+ // 写入 trace 头部
52
+ this.writeToFile({
53
+ ts: this.startTime,
54
+ level: TraceLevel.INFO,
55
+ type: 'trace.start',
56
+ data: {
57
+ level: TRACE_LEVEL_NAMES[this.config.level],
58
+ outputDir: this.config.outputDir,
59
+ filePath: this.filePath,
60
+ },
61
+ });
62
+ }
63
+ catch (err) {
64
+ // 目录不可用(非法路径/只读):禁用文件通道并告警一次;writeToFile 的空 catch 是写期瞬时失败兜底
65
+ this.filePath = undefined;
66
+ console.warn(`[observability] trace file output disabled (${dir}): ${err instanceof Error ? err.message : String(err)}`);
43
67
  }
44
- const ts = new Date().toISOString().replace(/[:.]/g, '-').substring(0, 19);
45
- const prefix = this.config.filePrefix ?? 'trace';
46
- this.filePath = join(dir, `${prefix}-${ts}.jsonl`);
47
- // 写入 trace 头部
48
- this.writeToFile({
49
- ts: this.startTime,
50
- level: TraceLevel.INFO,
51
- type: 'trace.start',
52
- data: {
53
- level: TRACE_LEVEL_NAMES[this.config.level],
54
- outputDir: this.config.outputDir,
55
- filePath: this.filePath,
56
- },
57
- });
58
68
  }
59
69
  }
60
70
  /**
@@ -26,8 +26,17 @@ export interface JsonlSessionStoreOptions {
26
26
  export declare class JsonlSessionStore implements SessionStore<SessionData> {
27
27
  private readonly sessionsDir;
28
28
  private readonly index?;
29
- /** 同 sessionId 读改写串行(save / updateMetadata / delete) */
29
+ /** 同 sessionId 读改写串行(save / updateMetadata / syncMessages / delete) */
30
30
  private readonly writeQueues;
31
+ /**
32
+ * syncMessages 增量判定缓存:本实例最近一次写下的消息文件状态。
33
+ * size(字节数)抓「旁路整包 save / 外部改动」造成的文件漂移;refs(消息对象
34
+ * 引用序列)抓「同一实例的序列分歧」。任一不符即整文件对齐重写,自愈。
35
+ * LRU 上限防长驻进程把全量转录引用常驻堆内存。
36
+ */
37
+ private readonly syncCaches;
38
+ /** 记录/刷新增量判定缓存(LRU:超限淘汰最旧条目) */
39
+ private noteSyncCache;
31
40
  /**
32
41
  * @param options - sessionsDir + 可选 index
33
42
  */
@@ -51,6 +60,15 @@ export declare class JsonlSessionStore implements SessionStore<SessionData> {
51
60
  * @param mutate - 原地修改 meta,或返回替换对象;返回 undefined 表示用原地结果
52
61
  */
53
62
  updateMetadata(sessionId: string, mutate: (meta: Record<string, unknown>) => void | Record<string, unknown>): Promise<void>;
63
+ /**
64
+ * 消息序列对齐(Run 进行中转录增量落盘)。契约见 SessionStore.syncMessages。
65
+ *
66
+ * 增量判定:文件字节数与上次本实例写入一致,且给定序列以已同步序列为
67
+ * 引用相等前缀 → 只追加尾差;任一不成立(旁路整包 save / 外部改动 /
68
+ * 前缀分歧 / 冷缓存)→ 整文件对齐重写。漂移不是错误路径:旁路写者
69
+ * 整包 save 是常态动作,对齐即自愈。
70
+ */
71
+ syncMessages(sessionId: string, messages: readonly unknown[]): Promise<void>;
54
72
  list(filter?: SessionListFilter): Promise<SessionMeta[]>;
55
73
  /**
56
74
  * 按会话事实 lifecycle 过滤(索引投影;缺省视为 active)。
@@ -11,10 +11,10 @@
11
11
  * 可选 `index`:可重建检索投影(失败不阻断权威写)。禁止把 index 当权威。
12
12
  * `sessions.json` parse 失败会拒绝写回,避免清空 meta。
13
13
  */
14
- import { access, mkdir, readFile, writeFile, unlink, rename } from 'node:fs/promises';
14
+ import { access, mkdir, readFile, writeFile, unlink, rename, appendFile, stat } from 'node:fs/promises';
15
15
  import { join } from 'node:path';
16
16
  import { toSessionFileName } from '@octopi-agent/core/session-filename.js';
17
- import { sessionMatchesAgent } from '@octopi-agent/core/types/session.js';
17
+ import { readTitleState, sessionMatchesAgent } from '@octopi-agent/core/types/session.js';
18
18
  async function fileExists(path) {
19
19
  try {
20
20
  await access(path);
@@ -28,6 +28,22 @@ async function fileExists(path) {
28
28
  function readPinnedAt(value) {
29
29
  return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
30
30
  }
31
+ /** 已同步序列上限(LRU):缓存只服务于增量判定,不得把全会话转录常驻钉在堆里 */
32
+ const MAX_SYNC_CACHES = 64;
33
+ /**
34
+ * 已同步序列是否为给定序列的引用相等前缀。
35
+ * 调用方契约:已同步消息不再原地修改(原地修改 = 视为新序列,须由调用方
36
+ * 保证不发生在首同步之前,如 turn_start 定形)。
37
+ */
38
+ function isRefPrefix(synced, incoming) {
39
+ if (incoming.length < synced.length)
40
+ return false;
41
+ for (let i = 0; i < synced.length; i++) {
42
+ if (synced[i] !== incoming[i])
43
+ return false;
44
+ }
45
+ return true;
46
+ }
31
47
  /**
32
48
  * 历史 state.json 的 turns[].input(全量历史快照)已废弃:读取即剥,
33
49
  * 下次 save 自然瘦身。输入正文的唯一权威是 messages JSONL(Discourse)。
@@ -48,8 +64,25 @@ function slimTurns(turns) {
48
64
  export class JsonlSessionStore {
49
65
  sessionsDir;
50
66
  index;
51
- /** 同 sessionId 读改写串行(save / updateMetadata / delete) */
67
+ /** 同 sessionId 读改写串行(save / updateMetadata / syncMessages / delete) */
52
68
  writeQueues = new Map();
69
+ /**
70
+ * syncMessages 增量判定缓存:本实例最近一次写下的消息文件状态。
71
+ * size(字节数)抓「旁路整包 save / 外部改动」造成的文件漂移;refs(消息对象
72
+ * 引用序列)抓「同一实例的序列分歧」。任一不符即整文件对齐重写,自愈。
73
+ * LRU 上限防长驻进程把全量转录引用常驻堆内存。
74
+ */
75
+ syncCaches = new Map();
76
+ /** 记录/刷新增量判定缓存(LRU:超限淘汰最旧条目) */
77
+ noteSyncCache(sessionId, size, refs) {
78
+ this.syncCaches.delete(sessionId);
79
+ if (this.syncCaches.size >= MAX_SYNC_CACHES) {
80
+ const oldest = this.syncCaches.keys().next().value;
81
+ if (oldest !== undefined)
82
+ this.syncCaches.delete(oldest);
83
+ }
84
+ this.syncCaches.set(sessionId, { size, refs });
85
+ }
53
86
  /**
54
87
  * @param options - sessionsDir + 可选 index
55
88
  */
@@ -120,6 +153,9 @@ export class JsonlSessionStore {
120
153
  // 置顶是用户数据:权威在 metadata.pinnedAt(受 save 浅合并保护,
121
154
  // 长驻 run 对象的整包 save 抹不掉);meta.pinnedAt 仅作旧数据回退
122
155
  pinnedAt: readPinnedAt(data.metadata?.pinnedAt) ?? readPinnedAt(data.meta.pinnedAt),
156
+ // 标题是用户数据:权威在 metadata 三键(同 pinnedAt 通道,save 按 titleUpdatedAt 仲裁);
157
+ // 投影必须覆盖 ...data.meta 展开带出的陈旧 meta.title,不做旧数据回退
158
+ ...readTitleState(data.metadata),
123
159
  };
124
160
  }
125
161
  async readSession(sessionId, resolved) {
@@ -231,6 +267,8 @@ export class JsonlSessionStore {
231
267
  // 不会出现索引有但数据没写完的不一致
232
268
  const jsonl = data.messages.map(msg => JSON.stringify(msg)).join('\n') + '\n';
233
269
  await writeFile(this.sessionFile(sessionId), jsonl);
270
+ // 全量重写后同步增量缓存(防止下一次 syncMessages 误判漂移)
271
+ this.noteSyncCache(sessionId, Buffer.byteLength(jsonl, 'utf-8'), data.messages.slice());
234
272
  // metadata 浅合并:长驻 run 对象上的陈旧/空 metadata 不得抹掉
235
273
  // 并发 updateMetadata 写入的键(clientToolCalls / fileReleases…)。
236
274
  // 删键必须走 updateMetadata。
@@ -239,6 +277,18 @@ export class JsonlSessionStore {
239
277
  ...(prevState?.metadata ?? {}),
240
278
  ...(data.metadata ?? {}),
241
279
  };
280
+ // 标题三键按 titleUpdatedAt 仲裁:浅合并只护「缺键」,不护「旧值」——
281
+ // 长驻 run 对象上 run 开始时的旧 trio 不得回滚运行期间 rename/标题生成写入的新 trio。
282
+ // incoming 缺时间戳视为陈旧(写端恒打三键;缺戳 = 半写/外来写),同样归磁盘胜
283
+ const fresh = readTitleState(prevState?.metadata);
284
+ const incomingTitle = readTitleState(data.metadata);
285
+ if (fresh.titleUpdatedAt !== undefined &&
286
+ (incomingTitle.titleUpdatedAt === undefined ||
287
+ incomingTitle.titleUpdatedAt < fresh.titleUpdatedAt)) {
288
+ metadata.title = fresh.title;
289
+ metadata.titleSource = fresh.titleSource;
290
+ metadata.titleUpdatedAt = fresh.titleUpdatedAt;
291
+ }
242
292
  await writeFile(this.sessionStateFile(sessionId), JSON.stringify({
243
293
  agentId: data.agentId,
244
294
  primaryAgentId: data.primaryAgentId ?? data.agentId,
@@ -309,6 +359,8 @@ export class JsonlSessionStore {
309
359
  ...entry,
310
360
  // pinnedAt 投影与 buildIndexEntry 同规则(置顶/取消即时可见于 list)
311
361
  pinnedAt: readPinnedAt(metadata.pinnedAt),
362
+ // 标题投影同规则(rename / 自动标题即时可见于 list)
363
+ ...readTitleState(metadata),
312
364
  updatedAt: Date.now(),
313
365
  };
314
366
  await this.writeMetaIndex(index);
@@ -319,6 +371,46 @@ export class JsonlSessionStore {
319
371
  }
320
372
  });
321
373
  }
374
+ /**
375
+ * 消息序列对齐(Run 进行中转录增量落盘)。契约见 SessionStore.syncMessages。
376
+ *
377
+ * 增量判定:文件字节数与上次本实例写入一致,且给定序列以已同步序列为
378
+ * 引用相等前缀 → 只追加尾差;任一不成立(旁路整包 save / 外部改动 /
379
+ * 前缀分歧 / 冷缓存)→ 整文件对齐重写。漂移不是错误路径:旁路写者
380
+ * 整包 save 是常态动作,对齐即自愈。
381
+ */
382
+ async syncMessages(sessionId, messages) {
383
+ return this.withWriteLock(sessionId, async () => {
384
+ await mkdir(this.sessionsDir, { recursive: true });
385
+ const path = this.sessionFile(sessionId);
386
+ const cache = this.syncCaches.get(sessionId);
387
+ let size = -1;
388
+ try {
389
+ size = (await stat(path)).size;
390
+ }
391
+ catch {
392
+ // 文件不存在 → 走整文件对齐
393
+ }
394
+ // 增量通道不是会话创建通道:会话完全不存在时跳过(创建/重建由 save 负责)
395
+ if (size < 0 && !(await fileExists(this.sessionStateFile(sessionId))))
396
+ return;
397
+ if (cache && size === cache.size && isRefPrefix(cache.refs, messages)) {
398
+ const added = messages.slice(cache.refs.length);
399
+ if (added.length === 0)
400
+ return;
401
+ const jsonl = added.map((m) => JSON.stringify(m)).join('\n') + '\n';
402
+ await appendFile(path, jsonl);
403
+ this.noteSyncCache(sessionId, size + Buffer.byteLength(jsonl, 'utf-8'), messages.slice());
404
+ return;
405
+ }
406
+ // 整文件对齐走 tmp+rename:读侧(浏览器刷新 load)不得撞见写半截的转录
407
+ const jsonl = messages.map((m) => JSON.stringify(m)).join('\n') + '\n';
408
+ const tmpPath = `${path}.${process.pid}.${Date.now()}.tmp`;
409
+ await writeFile(tmpPath, jsonl);
410
+ await rename(tmpPath, path);
411
+ this.noteSyncCache(sessionId, Buffer.byteLength(jsonl, 'utf-8'), messages.slice());
412
+ });
413
+ }
322
414
  async list(filter) {
323
415
  let entries = Object.values(await this.readMetaIndex());
324
416
  if (filter?.agentId) {
@@ -338,6 +430,7 @@ export class JsonlSessionStore {
338
430
  async delete(sessionId) {
339
431
  return this.withWriteLock(sessionId, async () => {
340
432
  await this.removeSessionFiles(sessionId);
433
+ this.syncCaches.delete(sessionId);
341
434
  if (this.index) {
342
435
  try {
343
436
  await this.index.remove(sessionId);
package/dist/paths.d.ts CHANGED
@@ -1,3 +1,22 @@
1
+ /**
2
+ * 展开 `~` 前缀为用户主目录(Windows/Linux/macOS 通用)。
3
+ * 接受 `~`、`~/rest`、`~\rest`(Windows 形态,剩余分隔符归一为 `/` 后按平台 join);
4
+ * `~user/…` 等其他形态不展开(无跨平台语义)。已是绝对路径的原样返回(幂等)。
5
+ *
6
+ * @param p - 配置原文路径
7
+ * @returns 展开后的路径
8
+ */
9
+ export declare function expandHomePath(p: string): string;
10
+ /**
11
+ * 配置路径合法形态:绝对路径,或 `~` / `~/…` / `~\…`。
12
+ * win32 上「绝对」要求盘符(`C:\`/`C:/`)或 UNC(`\\server\share`)——
13
+ * `\foo` 这类盘符相对路径会按当前盘隐式解析,属于要消灭的隐式行为。
14
+ * 相对路径直接拒绝:被 resolve 到进程 cwd 属于隐式行为,加载即报错。
15
+ *
16
+ * @param p - 配置原文路径
17
+ * @returns 形态合法与否
18
+ */
19
+ export declare function isConfigPathShape(p: string): boolean;
1
20
  /** 默认系统根目录 */
2
21
  export declare const DEFAULT_OCTOPI_HOME: string;
3
22
  /** 环境变量名 */
package/dist/paths.js CHANGED
@@ -1,9 +1,46 @@
1
1
  /**
2
2
  * Runtime home path helpers (OCTOPI_HOME).
3
3
  * Shared by gateway / suite so neither depends on the other for path resolution.
4
+ *
5
+ * This module must stay zod-free: harness runtime code imports it for path
6
+ * semantics without pulling in the config-schema layer.
4
7
  */
5
- import { join, resolve } from 'node:path';
8
+ import { isAbsolute, join, resolve } from 'node:path';
6
9
  import { homedir } from 'node:os';
10
+ /**
11
+ * 展开 `~` 前缀为用户主目录(Windows/Linux/macOS 通用)。
12
+ * 接受 `~`、`~/rest`、`~\rest`(Windows 形态,剩余分隔符归一为 `/` 后按平台 join);
13
+ * `~user/…` 等其他形态不展开(无跨平台语义)。已是绝对路径的原样返回(幂等)。
14
+ *
15
+ * @param p - 配置原文路径
16
+ * @returns 展开后的路径
17
+ */
18
+ export function expandHomePath(p) {
19
+ if (p === '~')
20
+ return homedir();
21
+ if (p.startsWith('~/') || p.startsWith('~\\')) {
22
+ // `~\a\b` 多段:把剩余的 `\` 归一为 `/`,避免 POSIX 上把 `\` 当文件名字符
23
+ return join(homedir(), p.slice(2).replace(/\\/g, '/'));
24
+ }
25
+ return p;
26
+ }
27
+ /**
28
+ * 配置路径合法形态:绝对路径,或 `~` / `~/…` / `~\…`。
29
+ * win32 上「绝对」要求盘符(`C:\`/`C:/`)或 UNC(`\\server\share`)——
30
+ * `\foo` 这类盘符相对路径会按当前盘隐式解析,属于要消灭的隐式行为。
31
+ * 相对路径直接拒绝:被 resolve 到进程 cwd 属于隐式行为,加载即报错。
32
+ *
33
+ * @param p - 配置原文路径
34
+ * @returns 形态合法与否
35
+ */
36
+ export function isConfigPathShape(p) {
37
+ if (p === '~' || p.startsWith('~/') || p.startsWith('~\\'))
38
+ return true;
39
+ if (process.platform === 'win32') {
40
+ return /^[A-Za-z]:[\\/]/.test(p) || p.startsWith('\\\\');
41
+ }
42
+ return isAbsolute(p);
43
+ }
7
44
  /** 默认系统根目录 */
8
45
  export const DEFAULT_OCTOPI_HOME = join(homedir(), '.octopi');
9
46
  /** 环境变量名 */
@@ -24,7 +24,9 @@ signal:
24
24
  boundary:
25
25
  visibility: structured
26
26
  authority: act
27
- security: sandboxed
27
+ # 第一方受审代码:显式声明 trusted(如实降级,不假装 sandboxed)。
28
+ # 缺省值仍是 sandboxed——第三方子系统必须显式声明(SEC-6 fail-closed)。
29
+ security: trusted
28
30
 
29
31
  tools:
30
32
  mode: none
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octopi-agent/engine",
3
- "version": "0.86.38",
3
+ "version": "0.90.11",
4
4
  "description": "Octopi Engine — Harness product domains, library integrations, and embeddable Agent.run()",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -80,7 +80,7 @@
80
80
  },
81
81
  "dependencies": {
82
82
  "@modelcontextprotocol/sdk": "^1.29.0",
83
- "@octopi-agent/core": "0.86.38",
83
+ "@octopi-agent/core": "0.90.11",
84
84
  "js-yaml": "^4.3.2",
85
85
  "zod": "^4.4.3"
86
86
  },