@qlingzzy/qling 1.0.0 → 1.1.1
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.
- package/CHANGELOG.md +158 -0
- package/README.en.md +83 -18
- package/README.md +19 -9
- package/dist/agent/main-loop.d.ts +120 -0
- package/dist/agent/main-loop.d.ts.map +1 -0
- package/dist/agent/main-loop.js +279 -0
- package/dist/agent/subtask-parallel.d.ts +29 -0
- package/dist/agent/subtask-parallel.d.ts.map +1 -0
- package/dist/agent/subtask-parallel.js +107 -0
- package/dist/agent/subtask.d.ts +13 -0
- package/dist/agent/subtask.d.ts.map +1 -1
- package/dist/agent/subtask.js +79 -24
- package/dist/agent/system-prompt.d.ts +39 -0
- package/dist/agent/system-prompt.d.ts.map +1 -0
- package/dist/agent/system-prompt.js +89 -0
- package/dist/agent/tool-orchestrator.d.ts +66 -0
- package/dist/agent/tool-orchestrator.d.ts.map +1 -0
- package/dist/agent/tool-orchestrator.js +355 -0
- package/dist/agent-loop.d.ts +29 -16
- package/dist/agent-loop.d.ts.map +1 -1
- package/dist/agent-loop.js +262 -807
- package/dist/agents/roles.d.ts +57 -0
- package/dist/agents/roles.d.ts.map +1 -0
- package/dist/agents/roles.js +198 -0
- package/dist/commands/agents.d.ts.map +1 -1
- package/dist/commands/agents.js +17 -3
- package/dist/commands/claude-style.d.ts.map +1 -1
- package/dist/commands/claude-style.js +19 -10
- package/dist/commands/help.d.ts.map +1 -1
- package/dist/commands/help.js +3 -2
- package/dist/commands/index.d.ts.map +1 -1
- package/dist/commands/index.js +6 -0
- package/dist/commands/mode.d.ts +16 -0
- package/dist/commands/mode.d.ts.map +1 -0
- package/dist/commands/mode.js +67 -0
- package/dist/commands/recover.d.ts +3 -0
- package/dist/commands/recover.d.ts.map +1 -0
- package/dist/commands/recover.js +69 -0
- package/dist/commands/runtime.d.ts +2 -0
- package/dist/commands/runtime.d.ts.map +1 -1
- package/dist/commands/runtime.js +2 -0
- package/dist/commands/trace.d.ts +3 -0
- package/dist/commands/trace.d.ts.map +1 -0
- package/dist/commands/trace.js +45 -0
- package/dist/commands/verify.js +2 -2
- package/dist/config-report.d.ts +0 -1
- package/dist/config-report.d.ts.map +1 -1
- package/dist/config-report.js +1 -2
- package/dist/config.d.ts +0 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +0 -1
- package/dist/context-report.d.ts +13 -7
- package/dist/context-report.d.ts.map +1 -1
- package/dist/context-report.js +64 -61
- package/dist/context-tool-hygiene.d.ts +36 -0
- package/dist/context-tool-hygiene.d.ts.map +1 -0
- package/dist/context-tool-hygiene.js +125 -0
- package/dist/dashboard/client.d.ts +2 -0
- package/dist/dashboard/client.d.ts.map +1 -0
- package/dist/dashboard/client.js +305 -0
- package/dist/dashboard/model.d.ts +13 -0
- package/dist/dashboard/model.d.ts.map +1 -0
- package/dist/dashboard/model.js +112 -0
- package/dist/dashboard/page.d.ts +3 -0
- package/dist/dashboard/page.d.ts.map +1 -0
- package/dist/dashboard/page.js +204 -0
- package/dist/dashboard/types.d.ts +63 -0
- package/dist/dashboard/types.d.ts.map +1 -0
- package/dist/dashboard/types.js +1 -0
- package/dist/dashboard-server.d.ts +24 -4
- package/dist/dashboard-server.d.ts.map +1 -1
- package/dist/dashboard-server.js +397 -302
- package/dist/discovery-registry.d.ts +17 -3
- package/dist/discovery-registry.d.ts.map +1 -1
- package/dist/discovery-registry.js +78 -3
- package/dist/doctor.d.ts +8 -0
- package/dist/doctor.d.ts.map +1 -1
- package/dist/doctor.js +116 -0
- package/dist/eval/llm-tasks.d.ts +5 -0
- package/dist/eval/llm-tasks.d.ts.map +1 -0
- package/dist/eval/llm-tasks.js +125 -0
- package/dist/eval/repo-tasks.d.ts +12 -0
- package/dist/eval/repo-tasks.d.ts.map +1 -0
- package/dist/eval/repo-tasks.js +220 -0
- package/dist/eval/runner.d.ts +3 -1
- package/dist/eval/runner.d.ts.map +1 -1
- package/dist/eval/runner.js +23 -4
- package/dist/eval/tasks.d.ts.map +1 -1
- package/dist/eval/tasks.js +186 -0
- package/dist/eval/types.d.ts +8 -5
- package/dist/eval/types.d.ts.map +1 -1
- package/dist/execution/event-bus.d.ts +44 -0
- package/dist/execution/event-bus.d.ts.map +1 -0
- package/dist/execution/event-bus.js +76 -0
- package/dist/execution/failure-classifier.d.ts +11 -0
- package/dist/execution/failure-classifier.d.ts.map +1 -0
- package/dist/execution/failure-classifier.js +66 -0
- package/dist/execution/progress-detector.d.ts +3 -0
- package/dist/execution/progress-detector.d.ts.map +1 -0
- package/dist/execution/progress-detector.js +23 -0
- package/dist/execution/recovery-controller.d.ts +24 -0
- package/dist/execution/recovery-controller.d.ts.map +1 -0
- package/dist/execution/recovery-controller.js +114 -0
- package/dist/execution/recovery-messages.d.ts +24 -0
- package/dist/execution/recovery-messages.d.ts.map +1 -0
- package/dist/execution/recovery-messages.js +48 -0
- package/dist/execution/recovery-metrics.d.ts +16 -0
- package/dist/execution/recovery-metrics.d.ts.map +1 -0
- package/dist/execution/recovery-metrics.js +73 -0
- package/dist/execution/recovery-strategy-planner.d.ts +6 -0
- package/dist/execution/recovery-strategy-planner.d.ts.map +1 -0
- package/dist/execution/recovery-strategy-planner.js +24 -0
- package/dist/execution/run-trace-store.d.ts +29 -0
- package/dist/execution/run-trace-store.d.ts.map +1 -0
- package/dist/execution/run-trace-store.js +140 -0
- package/dist/execution/staged-verifier.d.ts +33 -0
- package/dist/execution/staged-verifier.d.ts.map +1 -0
- package/dist/execution/staged-verifier.js +39 -0
- package/dist/execution/types.d.ts +58 -0
- package/dist/execution/types.d.ts.map +1 -0
- package/dist/execution/types.js +1 -0
- package/dist/execution/verification-loop.d.ts +58 -0
- package/dist/execution/verification-loop.d.ts.map +1 -0
- package/dist/execution/verification-loop.js +195 -0
- package/dist/execution/verification-stages.d.ts +17 -0
- package/dist/execution/verification-stages.d.ts.map +1 -0
- package/dist/execution/verification-stages.js +102 -0
- package/dist/help-topics.d.ts.map +1 -1
- package/dist/help-topics.js +11 -0
- package/dist/index.js +0 -8
- package/dist/lsp/ts-service.d.ts +36 -0
- package/dist/lsp/ts-service.d.ts.map +1 -0
- package/dist/lsp/ts-service.js +291 -0
- package/dist/memory/lifecycle.d.ts +19 -0
- package/dist/memory/lifecycle.d.ts.map +1 -0
- package/dist/memory/lifecycle.js +53 -0
- package/dist/memory.d.ts +0 -16
- package/dist/memory.d.ts.map +1 -1
- package/dist/memory.js +0 -36
- package/dist/metrics/collector.d.ts +7 -0
- package/dist/metrics/collector.d.ts.map +1 -1
- package/dist/metrics/collector.js +60 -0
- package/dist/mission/manager.d.ts +1 -0
- package/dist/mission/manager.d.ts.map +1 -1
- package/dist/mission/manager.js +9 -0
- package/dist/mission/progress-notify.d.ts +39 -0
- package/dist/mission/progress-notify.d.ts.map +1 -0
- package/dist/mission/progress-notify.js +386 -0
- package/dist/pipeline/hooks.d.ts +1 -1
- package/dist/pipeline/hooks.d.ts.map +1 -1
- package/dist/pipeline/hooks.js +1 -0
- package/dist/pipeline/sections.d.ts +8 -4
- package/dist/pipeline/sections.d.ts.map +1 -1
- package/dist/pipeline/sections.js +70 -27
- package/dist/pipeline/verification.d.ts +1 -0
- package/dist/pipeline/verification.d.ts.map +1 -1
- package/dist/pipeline/verification.js +10 -7
- package/dist/providers/llm-client.d.ts +38 -0
- package/dist/providers/llm-client.d.ts.map +1 -0
- package/dist/providers/llm-client.js +105 -0
- package/dist/sdk.d.ts +1 -0
- package/dist/sdk.d.ts.map +1 -1
- package/dist/sdk.js +1 -0
- package/dist/session/durable-session-supervisor.d.ts.map +1 -1
- package/dist/session/durable-session-supervisor.js +13 -6
- package/dist/session/session-persistence.d.ts +29 -0
- package/dist/session/session-persistence.d.ts.map +1 -0
- package/dist/session/session-persistence.js +45 -0
- package/dist/session/session-scheduler.d.ts +8 -1
- package/dist/session/session-scheduler.d.ts.map +1 -1
- package/dist/session/session-scheduler.js +33 -4
- package/dist/session-task-report.d.ts +1 -0
- package/dist/session-task-report.d.ts.map +1 -1
- package/dist/session-task-report.js +2 -1
- package/dist/shortcuts.d.ts.map +1 -1
- package/dist/shortcuts.js +1 -0
- package/dist/skills/registry.d.ts.map +1 -1
- package/dist/skills/registry.js +10 -0
- package/dist/skills/security-scan.d.ts +15 -0
- package/dist/skills/security-scan.d.ts.map +1 -0
- package/dist/skills/security-scan.js +95 -0
- package/dist/skills/types.d.ts +2 -0
- package/dist/skills/types.d.ts.map +1 -1
- package/dist/statusline.d.ts +3 -3
- package/dist/statusline.d.ts.map +1 -1
- package/dist/statusline.js +9 -17
- package/dist/token-usage.d.ts +27 -0
- package/dist/token-usage.d.ts.map +1 -0
- package/dist/token-usage.js +107 -0
- package/dist/tools/bash.d.ts.map +1 -1
- package/dist/tools/bash.js +5 -3
- package/dist/tools/browser-act-session.d.ts +48 -0
- package/dist/tools/browser-act-session.d.ts.map +1 -0
- package/dist/tools/browser-act-session.js +168 -0
- package/dist/tools/browser-act.d.ts +14 -0
- package/dist/tools/browser-act.d.ts.map +1 -0
- package/dist/tools/browser-act.js +297 -0
- package/dist/tools/code-symbols.d.ts +35 -0
- package/dist/tools/code-symbols.d.ts.map +1 -0
- package/dist/tools/code-symbols.js +257 -0
- package/dist/tools/index.d.ts +4 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +22 -2
- package/dist/tools/lsp.d.ts +13 -0
- package/dist/tools/lsp.d.ts.map +1 -0
- package/dist/tools/lsp.js +136 -0
- package/dist/tools/patch.d.ts +5 -0
- package/dist/tools/patch.d.ts.map +1 -1
- package/dist/tools/patch.js +25 -4
- package/dist/tools/search.d.ts +7 -0
- package/dist/tools/search.d.ts.map +1 -1
- package/dist/tools/search.js +20 -3
- package/dist/tools/skill.d.ts +2 -0
- package/dist/tools/skill.d.ts.map +1 -1
- package/dist/tools/skill.js +47 -14
- package/dist/tools/subtask.d.ts +3 -1
- package/dist/tools/subtask.d.ts.map +1 -1
- package/dist/tools/subtask.js +151 -56
- package/dist/tui/shell.d.ts +12 -0
- package/dist/tui/shell.d.ts.map +1 -1
- package/dist/tui/shell.js +36 -3
- package/dist/tui/streaming-repl.d.ts +1 -0
- package/dist/tui/streaming-repl.d.ts.map +1 -1
- package/dist/tui/streaming-repl.js +27 -4
- package/dist/tui/streaming-tui.d.ts +10 -0
- package/dist/tui/streaming-tui.d.ts.map +1 -1
- package/dist/tui/streaming-tui.js +70 -12
- package/dist/types.d.ts +0 -8
- package/dist/types.d.ts.map +1 -1
- package/dist/workflow-runtime.d.ts.map +1 -1
- package/dist/workflow-runtime.js +10 -2
- package/dist/workflow-types.d.ts +2 -0
- package/dist/workflow-types.d.ts.map +1 -1
- package/docs/install.md +46 -12
- package/docs/skills.md +56 -7
- package/docs/web-routing.md +83 -0
- package/package.json +18 -4
- package/scripts/dep-layers.mjs +275 -0
- package/scripts/eval-llm.mjs +27 -0
- package/scripts/eval-recovery.mjs +101 -0
- package/scripts/eval-tasks.mjs +20 -0
- package/scripts/validate-packaging.mjs +57 -0
- package/skills/examples/README.md +23 -0
- package/skills/examples/add-function/SKILL.md +31 -0
- package/skills/examples/fix-failing-test/SKILL.md +32 -0
- package/skills/examples/pr-summary/SKILL.md +34 -0
- package/skills/lifecycle-build/SKILL.md +22 -0
- package/skills/lifecycle-plan/SKILL.md +32 -0
- package/skills/lifecycle-review/SKILL.md +25 -0
- package/skills/lifecycle-ship/SKILL.md +22 -0
- package/skills/lifecycle-spec/SKILL.md +24 -0
- package/skills/lifecycle-test/SKILL.md +21 -0
- package/skills/opencli/SKILL.md +222 -0
- package/skills/qling.md +14 -3
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// System prompt 组装 + 内省评估(从 AgentLoop 抽出)
|
|
3
|
+
// ============================================================
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { buildRepoMapSection, buildSystemPrompt, buildReflectionPrompt, } from "../pipeline/sections.js";
|
|
6
|
+
export function findLastUserMessageContent(messages) {
|
|
7
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
8
|
+
if (messages[index].role === "user")
|
|
9
|
+
return messages[index].content;
|
|
10
|
+
}
|
|
11
|
+
return "";
|
|
12
|
+
}
|
|
13
|
+
export function buildRuntimeMetaSection(options) {
|
|
14
|
+
const workspace = options.workspaceDir ?? "(disabled)";
|
|
15
|
+
const cache = options.fileCacheDir ?? path.join(options.runtimeRootDir, "cache");
|
|
16
|
+
const state = options.fileStateDir ?? options.runtimeRootDir;
|
|
17
|
+
return [
|
|
18
|
+
"【Runtime Meta】",
|
|
19
|
+
`provider=${options.provider ?? "default"}`,
|
|
20
|
+
`endpoint=${options.endpoint ?? "default"}`,
|
|
21
|
+
`workspace_dir=${workspace}`,
|
|
22
|
+
`file_cache_dir=${cache}`,
|
|
23
|
+
`file_state_dir=${state}`,
|
|
24
|
+
].join("\n");
|
|
25
|
+
}
|
|
26
|
+
export async function assembleSystemPrompt(options) {
|
|
27
|
+
const cognitiveIndex = options.memoryStore
|
|
28
|
+
.getCognitiveIndex?.();
|
|
29
|
+
if (cognitiveIndex) {
|
|
30
|
+
try {
|
|
31
|
+
const symbols = cognitiveIndex.getAllSymbols();
|
|
32
|
+
options.sectionRegistry.register(buildRepoMapSection(symbols));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// ignore repomap failures
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
let memoryStr = "";
|
|
39
|
+
if (options.messages.length > 0) {
|
|
40
|
+
const lastUserMsg = findLastUserMessageContent(options.messages);
|
|
41
|
+
const relevant = await options.memoryStore.getRelevant(lastUserMsg, 10);
|
|
42
|
+
if (relevant.length > 0) {
|
|
43
|
+
memoryStr = relevant.map((e) => "[" + e.source + "] " + e.content).join("\n");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const sectionPrompt = buildSystemPrompt(options.sectionRegistry, {
|
|
47
|
+
memory: memoryStr || undefined,
|
|
48
|
+
});
|
|
49
|
+
const parts = [
|
|
50
|
+
options.baseSystemPrompt.trim(),
|
|
51
|
+
buildRuntimeMetaSection({
|
|
52
|
+
provider: options.provider,
|
|
53
|
+
endpoint: options.endpoint,
|
|
54
|
+
workspaceDir: options.workspaceDir,
|
|
55
|
+
fileCacheDir: options.fileCacheDir,
|
|
56
|
+
fileStateDir: options.fileStateDir,
|
|
57
|
+
runtimeRootDir: options.runtimeRootDir,
|
|
58
|
+
}),
|
|
59
|
+
sectionPrompt,
|
|
60
|
+
].filter((p) => p && p.trim().length > 0);
|
|
61
|
+
return parts.join("\n\n");
|
|
62
|
+
}
|
|
63
|
+
export function heuristicReflect(tc) {
|
|
64
|
+
const args = tc.arguments;
|
|
65
|
+
const cmd = (args.cmd || args.command || "").toLowerCase();
|
|
66
|
+
if (cmd.includes("rm ") || cmd.includes("del ")) {
|
|
67
|
+
return { decision: "warn", reason: "启发式拦截:检测到可能的删除操作。" };
|
|
68
|
+
}
|
|
69
|
+
return { decision: "proceed", reason: "启发式通过。" };
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Self-reflective pre-check for high-risk tools.
|
|
73
|
+
* Uses optional chat callback; falls back to heuristics on failure.
|
|
74
|
+
*/
|
|
75
|
+
export async function reflectiveThink(tc, chat) {
|
|
76
|
+
const prompt = buildReflectionPrompt(tc.name, tc.arguments);
|
|
77
|
+
try {
|
|
78
|
+
const resp = await chat(prompt, { max_tokens: 200, temperature: 0 });
|
|
79
|
+
const jsonStr = resp.content.match(/\{[\s\S]*\}/)?.[0] || "{}";
|
|
80
|
+
const analysis = JSON.parse(jsonStr);
|
|
81
|
+
return {
|
|
82
|
+
decision: analysis.decision || "proceed",
|
|
83
|
+
reason: analysis.reason || "评估完成。",
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return heuristicReflect(tc);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { ToolPipeline } from "../pipeline/hooks.js";
|
|
2
|
+
import { ApprovalGate } from "../guard/approval.js";
|
|
3
|
+
import type { GuardConfig } from "../config.js";
|
|
4
|
+
import type { Channel } from "../channels/types.js";
|
|
5
|
+
import type { KnowledgeAgentAdapter } from "../knowledge-agent.js";
|
|
6
|
+
import type { MemoryStore } from "../memory.js";
|
|
7
|
+
import type { WorkflowRuntime } from "../workflow-runtime.js";
|
|
8
|
+
import type { ExecutionEventBus } from "../execution/event-bus.js";
|
|
9
|
+
import type { Message, RawToolCall, ToolCall, ToolDefinition, ToolResult } from "../types.js";
|
|
10
|
+
export type ParseToolArgsResult = {
|
|
11
|
+
ok: true;
|
|
12
|
+
value: Record<string, unknown>;
|
|
13
|
+
} | {
|
|
14
|
+
ok: false;
|
|
15
|
+
error: string;
|
|
16
|
+
};
|
|
17
|
+
export interface PreparedToolCall {
|
|
18
|
+
call: ToolCall;
|
|
19
|
+
immediateResult?: ToolResult;
|
|
20
|
+
}
|
|
21
|
+
export declare function repairToolArguments(source: string, attempt: number): string;
|
|
22
|
+
export declare function parseToolArguments(raw: string, parseRetries?: number): ParseToolArgsResult;
|
|
23
|
+
export declare function stableStringify(value: unknown): string;
|
|
24
|
+
export declare function buildToolSignature(name: string, args: Record<string, unknown>): string;
|
|
25
|
+
/**
|
|
26
|
+
* Parse raw tool calls, apply argument repair retries, and enforce per-signature
|
|
27
|
+
* repeat limits within the current run.
|
|
28
|
+
*/
|
|
29
|
+
export declare function prepareToolCalls(toolCalls: RawToolCall[], options?: {
|
|
30
|
+
parseRetries?: number;
|
|
31
|
+
toolRepeatLimit?: number;
|
|
32
|
+
signatureCounts?: Map<string, number>;
|
|
33
|
+
}): PreparedToolCall[];
|
|
34
|
+
export type ReflectionDecision = "proceed" | "ask" | "block" | "warn";
|
|
35
|
+
export interface ToolOrchestratorDeps {
|
|
36
|
+
pipeline: ToolPipeline;
|
|
37
|
+
tools: ToolDefinition[];
|
|
38
|
+
guardConfig: GuardConfig;
|
|
39
|
+
channel: Channel | null;
|
|
40
|
+
approvalGate: ApprovalGate;
|
|
41
|
+
knowledgeAdapter: KnowledgeAgentAdapter;
|
|
42
|
+
memoryStore: MemoryStore;
|
|
43
|
+
workspaceDir: string;
|
|
44
|
+
workflowRuntime: WorkflowRuntime;
|
|
45
|
+
executionEventBus: ExecutionEventBus;
|
|
46
|
+
emit: (event: string, ...args: unknown[]) => void;
|
|
47
|
+
reflectiveThink: (tc: ToolCall) => Promise<{
|
|
48
|
+
decision: ReflectionDecision;
|
|
49
|
+
reason: string;
|
|
50
|
+
}>;
|
|
51
|
+
}
|
|
52
|
+
export interface ExecuteToolsContext {
|
|
53
|
+
preparedCalls: PreparedToolCall[];
|
|
54
|
+
messages: Message[];
|
|
55
|
+
runId: string;
|
|
56
|
+
attemptId: string;
|
|
57
|
+
}
|
|
58
|
+
export interface ExecuteToolsResult {
|
|
59
|
+
turnToolCalls: number;
|
|
60
|
+
turnToolFailures: number;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Execute a prepared tool batch, appending tool messages onto `context.messages`.
|
|
64
|
+
*/
|
|
65
|
+
export declare function executePreparedTools(deps: ToolOrchestratorDeps, context: ExecuteToolsContext): Promise<ExecuteToolsResult>;
|
|
66
|
+
//# sourceMappingURL=tool-orchestrator.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-orchestrator.d.ts","sourceRoot":"","sources":["../../src/agent/tool-orchestrator.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,EAAE,YAAY,EAAyB,MAAM,sBAAsB,CAAC;AAG3E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,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C;IACvB,KAAK,EAAE,cAAc,EAAE,CAAC;IACxB,WAAW,EAAE,WAAW,CAAC;IACzB,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;IACxB,YAAY,EAAE,YAAY,CAAC;IAC3B,gBAAgB,EAAE,qBAAqB,CAAC;IACxC,WAAW,EAAE,WAAW,CAAC;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,eAAe,EAAE,eAAe,CAAC;IACjC,iBAAiB,EAAE,iBAAiB,CAAC;IACrC,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;IAClD,eAAe,EAAE,CAAC,EAAE,EAAE,QAAQ,KAAK,OAAO,CAAC;QAAE,QAAQ,EAAE,kBAAkB,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAC9F;AAED,MAAM,WAAW,mBAAmB;IAClC,aAAa,EAAE,gBAAgB,EAAE,CAAC;IAClC,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,kBAAkB;IACjC,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED;;GAEG;AACH,wBAAsB,oBAAoB,CACxC,IAAI,EAAE,oBAAoB,EAC1B,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,kBAAkB,CAAC,CAsO7B"}
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// 工具编排(从 AgentLoop 抽出)
|
|
3
|
+
// agent-runtime:解析参数、重复限制、pipeline 执行、结果卫生
|
|
4
|
+
// ============================================================
|
|
5
|
+
import { dispatch } from "../tools/index.js";
|
|
6
|
+
import { checkToolConsistency } from "../pipeline/consistency-checker.js";
|
|
7
|
+
import { ApprovalRequiredError } from "../guard/approval.js";
|
|
8
|
+
import { applyContentFilter } from "../guard/content-filter.js";
|
|
9
|
+
import { appendGuardAudit } from "../guard.js";
|
|
10
|
+
import { prepareToolResultContent, resolveToolResultMaxChars, } from "../context-tool-hygiene.js";
|
|
11
|
+
import { maybeAutoCommitAfterWrite } from "../git/auto-commit.js";
|
|
12
|
+
export function repairToolArguments(source, attempt) {
|
|
13
|
+
let out = source.trim();
|
|
14
|
+
if (attempt === 0) {
|
|
15
|
+
const fenced = out.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
|
|
16
|
+
if (fenced) {
|
|
17
|
+
out = fenced[1].trim();
|
|
18
|
+
}
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
if (attempt === 1) {
|
|
22
|
+
return out.replace(/,\s*([}\]])/g, "$1");
|
|
23
|
+
}
|
|
24
|
+
if (attempt === 2) {
|
|
25
|
+
return out
|
|
26
|
+
.replace(/[“”]/g, "\"")
|
|
27
|
+
.replace(/[‘’]/g, "'")
|
|
28
|
+
.replace(/([{,]\s*)'([^']+?)'\s*:/g, '$1"$2":')
|
|
29
|
+
.replace(/:\s*'([^']*?)'(\s*[,}])/g, ': "$1"$2');
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
export function parseToolArguments(raw, parseRetries = 0) {
|
|
34
|
+
const retries = Math.max(0, parseRetries);
|
|
35
|
+
let candidate = String(raw ?? "");
|
|
36
|
+
let lastError = "invalid arguments";
|
|
37
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
38
|
+
try {
|
|
39
|
+
const parsed = JSON.parse(candidate);
|
|
40
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
41
|
+
lastError = "arguments must be a JSON object";
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
return { ok: true, value: parsed };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
lastError = err instanceof Error ? err.message : String(err);
|
|
49
|
+
}
|
|
50
|
+
if (attempt < retries) {
|
|
51
|
+
candidate = repairToolArguments(candidate, attempt);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
ok: false,
|
|
56
|
+
error: `failed after ${retries + 1} attempt(s): ${lastError}`,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
export function stableStringify(value) {
|
|
60
|
+
const normalize = (input) => {
|
|
61
|
+
if (Array.isArray(input)) {
|
|
62
|
+
return input.map((item) => normalize(item));
|
|
63
|
+
}
|
|
64
|
+
if (input && typeof input === "object") {
|
|
65
|
+
const entries = Object.entries(input).sort(([a], [b]) => a.localeCompare(b));
|
|
66
|
+
const obj = {};
|
|
67
|
+
for (const [k, v] of entries) {
|
|
68
|
+
obj[k] = normalize(v);
|
|
69
|
+
}
|
|
70
|
+
return obj;
|
|
71
|
+
}
|
|
72
|
+
return input;
|
|
73
|
+
};
|
|
74
|
+
try {
|
|
75
|
+
return JSON.stringify(normalize(value));
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return "[unstringifiable]";
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export function buildToolSignature(name, args) {
|
|
82
|
+
return `${name}:${stableStringify(args)}`;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Parse raw tool calls, apply argument repair retries, and enforce per-signature
|
|
86
|
+
* repeat limits within the current run.
|
|
87
|
+
*/
|
|
88
|
+
export function prepareToolCalls(toolCalls, options = {}) {
|
|
89
|
+
const parseRetries = options.parseRetries ?? 0;
|
|
90
|
+
const toolRepeatLimit = Math.max(1, options.toolRepeatLimit ?? 6);
|
|
91
|
+
const signatureCounts = options.signatureCounts ?? new Map();
|
|
92
|
+
const prepared = [];
|
|
93
|
+
for (const tc of toolCalls) {
|
|
94
|
+
const parseResult = parseToolArguments(tc.function.arguments, parseRetries);
|
|
95
|
+
if (!parseResult.ok) {
|
|
96
|
+
prepared.push({
|
|
97
|
+
call: {
|
|
98
|
+
id: tc.id,
|
|
99
|
+
name: tc.function.name,
|
|
100
|
+
arguments: {},
|
|
101
|
+
},
|
|
102
|
+
immediateResult: {
|
|
103
|
+
tool_call_id: tc.id,
|
|
104
|
+
output: `Error: [TOOL_INVALID_ARGUMENTS] ${parseResult.error}`,
|
|
105
|
+
is_error: true,
|
|
106
|
+
error: {
|
|
107
|
+
code: "TOOL_INVALID_ARGUMENTS",
|
|
108
|
+
message: parseResult.error,
|
|
109
|
+
category: "runtime",
|
|
110
|
+
},
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const call = {
|
|
116
|
+
id: tc.id,
|
|
117
|
+
name: tc.function.name,
|
|
118
|
+
arguments: parseResult.value,
|
|
119
|
+
};
|
|
120
|
+
const signature = buildToolSignature(call.name, call.arguments);
|
|
121
|
+
const repeatCount = (signatureCounts.get(signature) ?? 0) + 1;
|
|
122
|
+
signatureCounts.set(signature, repeatCount);
|
|
123
|
+
if (repeatCount > toolRepeatLimit) {
|
|
124
|
+
prepared.push({
|
|
125
|
+
call,
|
|
126
|
+
immediateResult: {
|
|
127
|
+
tool_call_id: tc.id,
|
|
128
|
+
output: `Error: [TOOL_REPEAT_LIMIT_EXCEEDED] ` +
|
|
129
|
+
`tool '${call.name}' exceeded repeat limit (${toolRepeatLimit})`,
|
|
130
|
+
is_error: true,
|
|
131
|
+
error: {
|
|
132
|
+
code: "TOOL_REPEAT_LIMIT_EXCEEDED",
|
|
133
|
+
message: `tool '${call.name}' exceeded repeat limit (${toolRepeatLimit})`,
|
|
134
|
+
category: "guard",
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
});
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
prepared.push({ call });
|
|
141
|
+
}
|
|
142
|
+
return prepared;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Execute a prepared tool batch, appending tool messages onto `context.messages`.
|
|
146
|
+
*/
|
|
147
|
+
export async function executePreparedTools(deps, context) {
|
|
148
|
+
let turnToolCalls = 0;
|
|
149
|
+
let turnToolFailures = 0;
|
|
150
|
+
const { preparedCalls, messages, runId, attemptId } = context;
|
|
151
|
+
if (process.env.QLING_FEATURES_WORKFLOW_RUNTIME === "true") {
|
|
152
|
+
await deps.workflowRuntime.setPendingTools(preparedCalls.map((p) => p.call));
|
|
153
|
+
}
|
|
154
|
+
for (const prepared of preparedCalls) {
|
|
155
|
+
const tc = prepared.call;
|
|
156
|
+
turnToolCalls++;
|
|
157
|
+
if (tc.name === "write" || tc.name === "bash") {
|
|
158
|
+
const reflection = await deps.reflectiveThink(tc);
|
|
159
|
+
if (reflection.decision === "block") {
|
|
160
|
+
console.error(`🚨 [内省阻断] ${reflection.reason}`);
|
|
161
|
+
messages.push({
|
|
162
|
+
role: "tool",
|
|
163
|
+
content: JSON.stringify({
|
|
164
|
+
tool_call_id: tc.id,
|
|
165
|
+
output: `Error: [REFLECTION_BLOCKED] ${reflection.reason}. This action was deemed too risky.`,
|
|
166
|
+
is_error: true,
|
|
167
|
+
}),
|
|
168
|
+
tool_call_id: tc.id,
|
|
169
|
+
});
|
|
170
|
+
turnToolFailures++;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
else if (reflection.decision === "warn") {
|
|
174
|
+
console.error(`💭 [内省警告] ${reflection.reason}`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (process.env.QLING_FEATURES_TOOL_SPEC_BOOST === "true") {
|
|
178
|
+
const def = deps.tools.find((t) => t.name === tc.name);
|
|
179
|
+
if (def) {
|
|
180
|
+
const check = checkToolConsistency(tc, def);
|
|
181
|
+
if (!check.ok) {
|
|
182
|
+
console.error(`⚠️ [SpecBoost] 检查到幻觉风险: ${tc.name} - ${check.error}`);
|
|
183
|
+
messages.push({
|
|
184
|
+
role: "tool",
|
|
185
|
+
content: JSON.stringify({
|
|
186
|
+
tool_call_id: tc.id,
|
|
187
|
+
output: `Error: [TOOL_SPEC_VIOLATION] ${check.error}. Please correct your arguments based on the schema and examples.`,
|
|
188
|
+
is_error: true,
|
|
189
|
+
}),
|
|
190
|
+
tool_call_id: tc.id,
|
|
191
|
+
});
|
|
192
|
+
turnToolFailures++;
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
if (check.warnings.length > 0) {
|
|
196
|
+
console.warn(`[SpecBoost] 潜在警告: ${check.warnings.join("; ")}`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
deps.knowledgeAdapter.onToolCall(tc);
|
|
201
|
+
deps.executionEventBus.startTool({ runId, attemptId, toolCallId: tc.id, tool: tc.name });
|
|
202
|
+
deps.emit("tool_start", tc.name, tc.arguments);
|
|
203
|
+
let result = prepared.immediateResult ?? {
|
|
204
|
+
tool_call_id: tc.id,
|
|
205
|
+
output: "",
|
|
206
|
+
is_error: false,
|
|
207
|
+
};
|
|
208
|
+
if (!prepared.immediateResult) {
|
|
209
|
+
try {
|
|
210
|
+
result = await deps.pipeline.execute(tc, (t) => dispatch(t));
|
|
211
|
+
}
|
|
212
|
+
catch (err) {
|
|
213
|
+
if (err instanceof ApprovalRequiredError && deps.channel) {
|
|
214
|
+
if (process.env.QLING_FEATURES_WORKFLOW_RUNTIME === "true") {
|
|
215
|
+
await deps.workflowRuntime.awaitApproval();
|
|
216
|
+
}
|
|
217
|
+
const approvalResponse = await deps.approvalGate.requestApproval({
|
|
218
|
+
id: err.toolCallId,
|
|
219
|
+
toolName: err.toolName,
|
|
220
|
+
arguments: tc.arguments,
|
|
221
|
+
reason: err.reasons.join("; "),
|
|
222
|
+
timestamp: Date.now(),
|
|
223
|
+
}, deps.channel);
|
|
224
|
+
if (approvalResponse.decision === "allow") {
|
|
225
|
+
result = await dispatch(tc);
|
|
226
|
+
}
|
|
227
|
+
else {
|
|
228
|
+
result = {
|
|
229
|
+
tool_call_id: tc.id,
|
|
230
|
+
output: "[Approval Denied] " + err.reasons.join("; "),
|
|
231
|
+
is_error: true,
|
|
232
|
+
error: {
|
|
233
|
+
code: "APPROVAL_DENIED",
|
|
234
|
+
message: "User denied tool execution",
|
|
235
|
+
category: "permission",
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
turnToolFailures++;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
result = {
|
|
243
|
+
tool_call_id: tc.id,
|
|
244
|
+
output: err.message,
|
|
245
|
+
is_error: true,
|
|
246
|
+
error: {
|
|
247
|
+
code: "TOOL_ERROR",
|
|
248
|
+
message: err.message,
|
|
249
|
+
category: "runtime",
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
turnToolFailures++;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
else {
|
|
257
|
+
turnToolFailures++;
|
|
258
|
+
}
|
|
259
|
+
deps.knowledgeAdapter.onToolResult(result, tc.name);
|
|
260
|
+
deps.executionEventBus.completeTool({
|
|
261
|
+
runId,
|
|
262
|
+
attemptId,
|
|
263
|
+
toolCallId: tc.id,
|
|
264
|
+
tool: tc.name,
|
|
265
|
+
failed: result.is_error,
|
|
266
|
+
});
|
|
267
|
+
deps.emit("tool_result", tc.name, result.output, result.is_error ?? false);
|
|
268
|
+
if (!result.is_error && (tc.name === "bash" || tc.name === "write" || tc.name === "read")) {
|
|
269
|
+
let lastUserMsg = "";
|
|
270
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
271
|
+
if (messages[i].role === "user") {
|
|
272
|
+
lastUserMsg = messages[i].content;
|
|
273
|
+
break;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
const taskId = "task_" + Buffer.from(lastUserMsg.slice(0, 10)).toString("hex");
|
|
277
|
+
deps.memoryStore.link({ id: taskId, type: "task", label: lastUserMsg.slice(0, 50) }, "uses", { id: "tool_" + tc.name, type: "tool", label: tc.name });
|
|
278
|
+
const args = tc.arguments;
|
|
279
|
+
const targetFile = args.path || args.file || "";
|
|
280
|
+
if (targetFile) {
|
|
281
|
+
deps.memoryStore.link({ id: "tool_" + tc.name, type: "tool", label: tc.name }, tc.name === "read" ? "reads" : "writes", {
|
|
282
|
+
id: "file_" + Buffer.from(targetFile).toString("hex"),
|
|
283
|
+
type: "file",
|
|
284
|
+
label: targetFile,
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (!result.is_error &&
|
|
289
|
+
(tc.name === "write" || tc.name === "patch") &&
|
|
290
|
+
!tc.arguments?.dry_run) {
|
|
291
|
+
const args = tc.arguments;
|
|
292
|
+
const targetFile = String(args.path || args.file || "").trim();
|
|
293
|
+
if (targetFile) {
|
|
294
|
+
try {
|
|
295
|
+
const ac = await maybeAutoCommitAfterWrite({
|
|
296
|
+
workspaceDir: deps.workspaceDir || process.cwd(),
|
|
297
|
+
filePath: targetFile,
|
|
298
|
+
toolName: tc.name,
|
|
299
|
+
});
|
|
300
|
+
if (ac.mode !== "off") {
|
|
301
|
+
result = {
|
|
302
|
+
...result,
|
|
303
|
+
output: `${result.output}\n\n[${ac.message}]`,
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
// auto-commit 失败不影响工具成功语义
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (deps.guardConfig.enabled && deps.guardConfig.content_filter?.enabled) {
|
|
313
|
+
const cf = applyContentFilter(result.output, {
|
|
314
|
+
pii: deps.guardConfig.content_filter.pii_detection,
|
|
315
|
+
injection: deps.guardConfig.content_filter.injection_detection,
|
|
316
|
+
custom: deps.guardConfig.content_filter.custom_patterns.length > 0,
|
|
317
|
+
});
|
|
318
|
+
if (cf.blocked) {
|
|
319
|
+
await appendGuardAudit(deps.guardConfig, {
|
|
320
|
+
tool: tc.name,
|
|
321
|
+
action: "deny",
|
|
322
|
+
category: "content_filter",
|
|
323
|
+
reason: cf.reason,
|
|
324
|
+
});
|
|
325
|
+
result = {
|
|
326
|
+
...result,
|
|
327
|
+
output: `[内容过滤] ${cf.reason}: ${(cf.matches ?? []).join(", ")}`,
|
|
328
|
+
is_error: true,
|
|
329
|
+
error: {
|
|
330
|
+
code: "CONTENT_FILTERED",
|
|
331
|
+
message: cf.reason ?? "content filtered",
|
|
332
|
+
category: "guard",
|
|
333
|
+
},
|
|
334
|
+
};
|
|
335
|
+
turnToolFailures++;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
const preview = result.output.split("\n")[0].slice(0, 80);
|
|
339
|
+
const icon = result.is_error ? "❌" : "✅";
|
|
340
|
+
console.error(icon + " " + tc.name + ": " + preview + (result.output.length > 80 ? "..." : ""));
|
|
341
|
+
if (process.env.QLING_FEATURES_WORKFLOW_RUNTIME === "true") {
|
|
342
|
+
await deps.workflowRuntime.addToolResult(result);
|
|
343
|
+
}
|
|
344
|
+
const rawToolContent = JSON.stringify(result);
|
|
345
|
+
const hygienicContent = prepareToolResultContent(rawToolContent, {
|
|
346
|
+
maxChars: resolveToolResultMaxChars(),
|
|
347
|
+
});
|
|
348
|
+
messages.push({
|
|
349
|
+
role: "tool",
|
|
350
|
+
content: hygienicContent,
|
|
351
|
+
tool_call_id: tc.id,
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
return { turnToolCalls, turnToolFailures };
|
|
355
|
+
}
|
package/dist/agent-loop.d.ts
CHANGED
|
@@ -1,24 +1,26 @@
|
|
|
1
1
|
import { MemoryStore } from "./memory.js";
|
|
2
|
+
import type { TokenUsageSource } from "./token-usage.js";
|
|
2
3
|
import type { Channel } from "./channels/types.js";
|
|
3
4
|
import type { AgentConfig, Message } from "./types.js";
|
|
4
5
|
import { WorkflowRuntime } from "./workflow-runtime.js";
|
|
5
6
|
import { DiscoveryRegistry } from "./discovery-registry.js";
|
|
6
7
|
import { MissionManager } from "./mission/manager.js";
|
|
7
8
|
import { type SavedSessionSummary } from "./session/session-registry.js";
|
|
9
|
+
import type { ExecutionEvent, RecoveryState } from "./execution/types.js";
|
|
10
|
+
export declare function resolveMemoryDreamLlmEnabled(env?: NodeJS.ProcessEnv | Record<string, string | undefined>): boolean;
|
|
8
11
|
export interface LlmSessionPatch {
|
|
9
12
|
model?: string;
|
|
10
13
|
provider?: string;
|
|
11
14
|
endpoint?: string;
|
|
12
15
|
apiKey?: string;
|
|
13
16
|
}
|
|
14
|
-
type TokenUsageSource = "provider" | "estimate" | "unknown";
|
|
15
17
|
export declare class AgentEventEmitter {
|
|
16
18
|
private handlers;
|
|
17
19
|
on(event: string, handler: Function): () => void;
|
|
18
20
|
emit(event: string, ...args: unknown[]): void;
|
|
19
21
|
}
|
|
20
22
|
export declare class AgentLoop extends AgentEventEmitter {
|
|
21
|
-
private
|
|
23
|
+
private llmClient;
|
|
22
24
|
private messages;
|
|
23
25
|
private config;
|
|
24
26
|
private turnCount;
|
|
@@ -29,7 +31,6 @@ export declare class AgentLoop extends AgentEventEmitter {
|
|
|
29
31
|
private pipeline;
|
|
30
32
|
private sectionRegistry;
|
|
31
33
|
private memoryStore;
|
|
32
|
-
private tokenBudget;
|
|
33
34
|
private verifier;
|
|
34
35
|
private compactor;
|
|
35
36
|
private knowledgeAdapter;
|
|
@@ -53,6 +54,10 @@ export declare class AgentLoop extends AgentEventEmitter {
|
|
|
53
54
|
private sessionRegistry;
|
|
54
55
|
private guardConfig;
|
|
55
56
|
private verificationCommand;
|
|
57
|
+
private readonly executionEventBus;
|
|
58
|
+
private readonly recoveryController;
|
|
59
|
+
private runTraceStore;
|
|
60
|
+
private activeRun;
|
|
56
61
|
getWorkflowRuntime(): WorkflowRuntime;
|
|
57
62
|
getMemoryStore(): MemoryStore;
|
|
58
63
|
getDiscoveryRegistry(): DiscoveryRegistry;
|
|
@@ -61,11 +66,23 @@ export declare class AgentLoop extends AgentEventEmitter {
|
|
|
61
66
|
getWorkspaceDir(): string;
|
|
62
67
|
getMessagesSnapshot(): Message[];
|
|
63
68
|
getVerificationCommand(): string | null;
|
|
69
|
+
getActiveRun(): Readonly<typeof this.activeRun>;
|
|
70
|
+
getRecoveryState(): RecoveryState | null;
|
|
71
|
+
subscribeExecutionEvents(listener: (event: ExecutionEvent) => void): () => void;
|
|
72
|
+
applyRecoveryAction(action: "retry" | "next" | "edit" | "cancel"): {
|
|
73
|
+
state: RecoveryState;
|
|
74
|
+
prompt?: string;
|
|
75
|
+
};
|
|
76
|
+
listRunTraceIds(): Promise<string[]>;
|
|
77
|
+
readRunTrace(runId: string): Promise<ExecutionEvent[]>;
|
|
78
|
+
getRecentRunTrace(sessionId?: string, runId?: string): Promise<ExecutionEvent[]>;
|
|
64
79
|
setVerificationCommand(cmd: string | null): Promise<void>;
|
|
65
80
|
getSessionStats(): {
|
|
66
81
|
sessionId: string;
|
|
67
82
|
turnCount: number;
|
|
68
83
|
tokens: number;
|
|
84
|
+
promptTokens: number;
|
|
85
|
+
completionTokens: number;
|
|
69
86
|
tokenSource: TokenUsageSource;
|
|
70
87
|
compactions: number;
|
|
71
88
|
};
|
|
@@ -73,6 +90,8 @@ export declare class AgentLoop extends AgentEventEmitter {
|
|
|
73
90
|
/** 状态机恢复后的内部同步 */
|
|
74
91
|
syncWorkflowState(checkpoint: any): void;
|
|
75
92
|
private sessionTokens;
|
|
93
|
+
private sessionPromptTokens;
|
|
94
|
+
private sessionCompletionTokens;
|
|
76
95
|
private tokenUsageSource;
|
|
77
96
|
private initPromise;
|
|
78
97
|
private compactionCount;
|
|
@@ -84,6 +103,9 @@ export declare class AgentLoop extends AgentEventEmitter {
|
|
|
84
103
|
private init;
|
|
85
104
|
addUserMessage(content: string): void;
|
|
86
105
|
run(): Promise<string>;
|
|
106
|
+
private executeRunInternal;
|
|
107
|
+
private formatRecoveryPause;
|
|
108
|
+
private applyRecoveryStrategy;
|
|
87
109
|
getModel(): string;
|
|
88
110
|
getProvider(): string;
|
|
89
111
|
getEndpoint(): string;
|
|
@@ -120,15 +142,14 @@ export declare class AgentLoop extends AgentEventEmitter {
|
|
|
120
142
|
listSessionsDetailed(): Promise<SavedSessionSummary[]>;
|
|
121
143
|
restoreSession(nameOrSessionId: string): Promise<SavedSessionSummary | null>;
|
|
122
144
|
restoreLatestSession(): Promise<SavedSessionSummary | null>;
|
|
123
|
-
private
|
|
124
|
-
private
|
|
145
|
+
private captureSessionSnapshot;
|
|
146
|
+
private hydrateSessionSnapshot;
|
|
125
147
|
/** 自我反思循环 (v0.5 M2) */
|
|
126
148
|
private reflectiveThink;
|
|
127
149
|
private buildSystemPrompt;
|
|
128
150
|
private chat;
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
private verifyLastOperation;
|
|
151
|
+
/** Exposed for doctor / status: current staged verification plan. */
|
|
152
|
+
getVerificationStagesSummary(): string;
|
|
132
153
|
persistVerificationCommand(): Promise<void>;
|
|
133
154
|
loadVerificationCommand(): Promise<void>;
|
|
134
155
|
runVerificationCommand(cmd: string): Promise<{
|
|
@@ -137,15 +158,7 @@ export declare class AgentLoop extends AgentEventEmitter {
|
|
|
137
158
|
stderr: string;
|
|
138
159
|
}>;
|
|
139
160
|
private checkAutoDream;
|
|
140
|
-
private estimateTokens;
|
|
141
|
-
private logTurnTelemetry;
|
|
142
|
-
private buildRuntimeMetaSection;
|
|
143
161
|
private maybeDumpInspect;
|
|
144
162
|
private resolveLlmRequestTimeout;
|
|
145
|
-
private parseToolArguments;
|
|
146
|
-
private repairToolArguments;
|
|
147
|
-
private buildToolSignature;
|
|
148
|
-
private stableStringify;
|
|
149
163
|
}
|
|
150
|
-
export {};
|
|
151
164
|
//# sourceMappingURL=agent-loop.d.ts.map
|
package/dist/agent-loop.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,KAAK,E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