/*
 * 文件定位：Agent 执行引擎 / 执行核心逻辑。
 * 核心目的：把工具和临时过程执行结果整理成 PromptPack 可消费的 observation material。
 * 边界：只做观测摘要和引用，不重放工具语义，不写 TAP/CMP/MP/multiagent 策略。
 * 对接：连接 BaseTool/Procedure 执行结果、PromptPack assembly 和下一轮 mainLoop。
 * 实现提示：保持 provider-neutral material，不在这里生成 provider payload 或最终输出。
 */
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
export const DEFAULT_TOOL_RESULT_SIZE_POLICY = {
    maxInlineBytes: 32 * 1024,
    overflowMode: "artifactRef",
};
export const DEFAULT_OBSERVATION_TURN_INLINE_BUDGET_BYTES = 128 * 1024;
export const DEFAULT_OBSERVATION_SUMMARY_DELEGATION_POLICY = {
    mode: "summaryAgent",
    summaryAgentRef: "summaryAgent.default",
    allowCurrentAgentSelfSummary: false,
    compressionRatio: 0.05,
    metadata: {},
};
export const DEFAULT_OBSERVATION_COMPRESSION_POLICY = {
    enabled: true,
    compressionRatio: 0.05,
    primitive: "compressObservation",
    owner: "summaryAgent",
    metadata: {},
};
export const DEFAULT_SUMMARY_AGENT_REF = {
    agentRef: "summaryAgent.default",
    role: "observationSummary",
    compressionRatio: 0.05,
    publicSafe: true,
};
export function createFallbackMemoryRef(sessionId, storageHint = ".rax_workspace") {
    return {
        memoryId: `${sessionId.trim() || "session"}:memory:fallback-md-index`,
        kind: "sessionLocalMarkdownIndex",
        storageHint,
        takeoverReadyForMp: true,
        publicSafe: true,
    };
}
function safeStringify(value) {
    if (value === undefined) {
        return "";
    }
    if (typeof value === "string") {
        return value;
    }
    try {
        return JSON.stringify(value);
    }
    catch {
        return "[unserializable observation payload]";
    }
}
function byteLength(value) {
    return Buffer.byteLength(value, "utf8");
}
function safePathSegment(value) {
    const normalized = value.trim().replace(/[^a-zA-Z0-9._-]+/gu, "-").replace(/^-+|-+$/gu, "");
    return normalized.slice(0, 120) || "observation";
}
function defaultTrustLevel(input) {
    if (input.trustLevel !== undefined)
        return input.trustLevel;
    if (input.source === "baseTool" || input.source === "ephemeralProcedure")
        return "toolOutput";
    if (input.source === "model")
        return "modelInterpretation";
    return "runtimeFact";
}
function persistedArtifact(input, payloadText) {
    if (input.artifactStore === undefined)
        return undefined;
    const workspaceRoot = resolve(input.artifactStore.workspaceRoot);
    const sessionId = safePathSegment(input.artifactStore.sessionId);
    const observationId = safePathSegment(input.observationId);
    const artifactPath = join(workspaceRoot, ".rax_workspace", "observations", sessionId, `${observationId}.json`);
    mkdirSync(dirname(artifactPath), { recursive: true });
    writeFileSync(artifactPath, `${payloadText}\n`, "utf8");
    return {
        uri: pathToFileURL(artifactPath).href,
        path: artifactPath,
    };
}
function artifactRefFor(input, payloadText) {
    const artifactId = `${input.observationId}:artifact:payload`;
    const persisted = persistedArtifact(input, payloadText);
    return {
        artifactId,
        uri: input.artifactUri ?? persisted?.uri ?? `artifact://${artifactId}`,
        ...(persisted?.path === undefined ? {} : { path: persisted.path }),
        byteLength: byteLength(payloadText),
        reason: "toolResultTooLarge",
        metadata: {
            observationId: input.observationId,
            source: input.source,
            ...(persisted?.path === undefined ? {} : { artifactPath: persisted.path }),
        },
    };
}
function resolveSummaryDelegation(input) {
    const override = input.summaryDelegation ?? {};
    return {
        ...DEFAULT_OBSERVATION_SUMMARY_DELEGATION_POLICY,
        ...override,
        metadata: override.metadata ?? {},
    };
}
function resolveCompression(input, summaryDelegation) {
    const override = input.compression ?? {};
    return {
        ...DEFAULT_OBSERVATION_COMPRESSION_POLICY,
        owner: summaryDelegation.mode === "cmp" ? "cmp" : summaryDelegation.mode === "summaryAgent" ? "summaryAgent" : "runtimeFallback",
        compressionRatio: summaryDelegation.compressionRatio ?? DEFAULT_OBSERVATION_COMPRESSION_POLICY.compressionRatio,
        ...override,
        metadata: override.metadata ?? {},
    };
}
export function createObservationMaterial(input) {
    const payloadText = safeStringify(input.payload);
    const sizePolicy = {
        ...DEFAULT_TOOL_RESULT_SIZE_POLICY,
        ...(input.sizePolicy ?? {}),
    };
    const trustLevel = defaultTrustLevel(input);
    const payloadBytes = byteLength(payloadText);
    const shouldArtifact = payloadBytes > sizePolicy.maxInlineBytes;
    const artifactRef = shouldArtifact ? artifactRefFor(input, payloadText) : undefined;
    const summaryDelegation = resolveSummaryDelegation(input);
    const compression = resolveCompression(input, summaryDelegation);
    const selectionFlow = artifactRef === undefined ? undefined : {
        kind: "largeObservationSelection",
        artifactRef,
        modelInstruction: "The full observation payload is stored as an artifact. Select only the relevant byte range or excerpt before using it as prompt context.",
        selectionBudgetBytes: Math.min(sizePolicy.maxInlineBytes, 1024 * 1024),
        publicSafe: true,
    };
    const text = [
        `${input.title}: ${input.summary}`,
        artifactRef === undefined && payloadText.length > 0 ? `payload: ${payloadText}` : "",
        artifactRef === undefined ? "" : `payloadArtifact: ${artifactRef.uri}`,
        artifactRef === undefined ? "" : `payloadBytes: ${artifactRef.byteLength}`,
        artifactRef === undefined ? "" : `summaryAgent: ${summaryDelegation.summaryAgentRef ?? "disabled"}`,
        artifactRef === undefined ? "" : `selectionBudgetBytes: ${selectionFlow?.selectionBudgetBytes ?? sizePolicy.maxInlineBytes}`,
    ].filter(Boolean).join("\n");
    return {
        observationId: input.observationId,
        refs: input.refs ?? [],
        payload: input.payload,
        trustLevel,
        summaryDelegation,
        compression,
        ...(artifactRef === undefined ? {} : { artifactRef }),
        ...(selectionFlow === undefined ? {} : { selectionFlow }),
        material: {
            id: input.observationId,
            kind: input.source === "baseTool" || input.source === "ephemeralProcedure" ? "tool-summary" : "runtime",
            text,
            source: `runtime.observation.${input.source}`,
            priority: input.status === "failed" ? 80 : 40,
            trusted: true,
            scope: "runtime.observation",
            metadata: {
                observationId: input.observationId,
                observationSource: input.source,
                observationStatus: input.status,
                observationTrustLevel: trustLevel,
                payloadBytes,
                artifactUri: artifactRef?.uri ?? "",
                artifactPath: artifactRef?.path ?? "",
                largeObservationSelection: artifactRef === undefined ? false : true,
                summaryDelegationMode: summaryDelegation.mode,
                summaryAgentRef: summaryDelegation.summaryAgentRef ?? "",
                allowCurrentAgentSelfSummary: summaryDelegation.allowCurrentAgentSelfSummary,
                compressionEnabled: compression.enabled,
                compressionRatio: compression.compressionRatio,
                compressionPrimitive: compression.primitive,
                compressionOwner: compression.owner,
                ...(input.metadata ?? {}),
            },
        },
    };
}
