/*
 * 文件定位：Agent 执行引擎 / 基础工具原语层 / 基础工具集合 / Shell 基础工具 / Shell 交互。
 * 核心目的：提供 Shell 基础工具 / Shell 交互 中的“写入 stdin”基础能力原语。
 * 能力要求1：需要定义该能力的输入、输出、错误、权限需求和可观测事件。
 * 能力要求2：这些基础工具是 Agent 成立的底层能力，不是 TAP 的最终高级工具库。
 * 能力要求3：后续 TAP 可以基于这些原语构建更强的工具编排、审批、替换和专业能力库。
 * 边界：保留 Agent 基础工具原语，不替代 TAP 的高级工具系统。
 * 对接：需要被 runtime.execEngine 拉起，并和 mainLoop、stateEngine、事件暴露、工具调用策略接通。
 * 实现提示：先补稳定类型契约、最小可测行为和清晰错误边界，再接入真实执行逻辑。
 */
import { jsonRecord, optionalStringArray, stringList, stringValue, trimmedString } from "../_shared/jsonBoundary.js";
export const shellStdinFeedingDescriptor = {
    toolId: "shell.stdinFeeding",
    capability: "shell-stdin-feeding",
    route: "agent_executionEngine.basic_toolLayer.baseTools.shellBase.shellInteraction",
    defaultDryRun: true,
    defaultMode: "text",
    defaultMaxBytes: 16_384,
    requiredPermission: "shell:stdin:feed",
    tapOwnsApproval: true,
    unsafeSideEffects: true,
};
const maxInputBytes = 262_144;
const stdinModes = new Set(["text", "control-sequence"]);
function cleanStringList(values) {
    return stringList(values);
}
function dryRunEnabled(context) {
    return context?.dryRun !== false;
}
function invocationId(context) {
    return trimmedString(jsonRecord(context)?.invocationId) ?? "shell.stdinFeeding:dry-run";
}
function auditEvent(type, context, sessionId, metadata) {
    return {
        type,
        toolId: shellStdinFeedingDescriptor.toolId,
        invocationId: invocationId(context),
        dryRun: dryRunEnabled(context),
        sessionId,
        metadata: {
            ...(context?.auditMetadata ?? {}),
            ...(metadata ?? {}),
        },
    };
}
function failure(code, message, boundary, context, sessionId) {
    return {
        ok: false,
        toolId: shellStdinFeedingDescriptor.toolId,
        error: { code, message, boundary, publicSafe: true, internalDetailExposed: false },
        audit: [auditEvent("agentCore.basicTool.shell.stdinFeeding.rejected", context, sessionId, { code })],
        events: ["basicTool.shell.stdinFeeding.rejected"],
    };
}
function ensureDryRunOnly(context, sessionId) {
    if (dryRunEnabled(context)) {
        return undefined;
    }
    return failure("REAL_STDIN_WRITE_BLOCKED", "shell.stdinFeeding only creates a guarded dry-run stdin write envelope in the first implementation", "contract", context, sessionId);
}
function ensurePermission(context, sessionId) {
    if (context?.grantedPermissions === undefined) {
        return undefined;
    }
    if (cleanStringList(context.grantedPermissions).includes(shellStdinFeedingDescriptor.requiredPermission)) {
        return undefined;
    }
    return failure("PERMISSION_DENIED", "shell.stdinFeeding is missing permission: shell:stdin:feed", "permission", context, sessionId);
}
function ensureScope(sessionId, context) {
    const allowedSessionIds = optionalStringArray(context?.allowedSessionIds, { trim: true });
    if (!allowedSessionIds.ok) {
        return failure("SCOPE_REJECTED", "shell.stdinFeeding allowedSessionIds must be a string array", "scope", context, sessionId);
    }
    if (context?.allowedSessionIds === undefined || allowedSessionIds.values.includes(sessionId)) {
        return undefined;
    }
    return failure("SCOPE_REJECTED", "shell.stdinFeeding sessionId is outside allowed stdin scope", "scope", context, sessionId);
}
function approvalRequired(target) {
    return target.sensitive === true || target.mode === "control-sequence";
}
function ensureApproval(requiresApproval, context, sessionId) {
    if (!requiresApproval) {
        return undefined;
    }
    if (context?.approval?.accepted === true) {
        return undefined;
    }
    if (context?.approval?.accepted === false) {
        return failure("APPROVAL_REJECTED", context.approval.reason ?? "shell.stdinFeeding approval was rejected by TAP governance", "approval", context, sessionId);
    }
    return failure("APPROVAL_REQUIRED", "shell.stdinFeeding sensitive or control-sequence input requires TAP approval", "approval", context, sessionId);
}
function previewInput(input, sensitive) {
    if (sensitive) {
        return "[redacted]";
    }
    return input.length > 80 ? `${input.slice(0, 80)}...` : input;
}
function normalizeTarget(target, context) {
    const targetRecord = jsonRecord(target);
    const sessionId = trimmedString(targetRecord?.sessionId);
    if (sessionId === undefined) {
        return failure("MISSING_SESSION_ID", "shell.stdinFeeding requires target.sessionId", "input", context);
    }
    const input = stringValue(targetRecord?.input);
    if (input === undefined || input.length === 0 || input.includes("\0")) {
        return failure("MISSING_INPUT", "shell.stdinFeeding requires non-empty safe input", "input", context, sessionId);
    }
    const mode = (stringValue(targetRecord?.mode) ?? shellStdinFeedingDescriptor.defaultMode);
    if (!stdinModes.has(mode)) {
        return failure("INVALID_MODE", "shell.stdinFeeding mode must be text or control-sequence", "input", context, sessionId);
    }
    const appendNewline = targetRecord?.appendNewline === true;
    const plannedInput = appendNewline ? `${input}\n` : input;
    const inputBytes = Buffer.byteLength(plannedInput, "utf8");
    const maxBytes = typeof context?.maxBytes === "number" ? context.maxBytes : shellStdinFeedingDescriptor.defaultMaxBytes;
    if (!Number.isInteger(maxBytes) || maxBytes <= 0 || maxBytes > maxInputBytes || inputBytes > maxBytes) {
        return failure("INPUT_TOO_LARGE", `shell.stdinFeeding input must fit within maxBytes (${maxBytes}) and absolute limit ${maxInputBytes}`, "resource", context, sessionId);
    }
    const requiresTapApproval = approvalRequired({ sensitive: targetRecord?.sensitive === true, mode });
    return {
        kind: "agentCore.basicTool.shell.stdinFeeding",
        sessionId,
        mode,
        appendNewline,
        inputPreview: previewInput(plannedInput, targetRecord?.sensitive === true),
        inputBytes,
        requiredPermission: shellStdinFeedingDescriptor.requiredPermission,
        requiresTapApproval,
        approvalId: trimmedString(jsonRecord(context?.approval)?.approvalId),
        dryRun: true,
        stdinWriteBlocked: true,
        unsafeSideEffects: true,
        resultEnvelope: {
            planned: true,
        },
    };
}
export function planShellStdinFeeding(request = {}) {
    const requestRecord = jsonRecord(request) ?? {};
    const context = jsonRecord(requestRecord.context);
    const targetRecord = jsonRecord(requestRecord.target);
    const sessionId = trimmedString(targetRecord?.sessionId);
    const dryRunFailure = ensureDryRunOnly(context, sessionId);
    if (dryRunFailure !== undefined) {
        return dryRunFailure;
    }
    const permissionFailure = ensurePermission(context, sessionId);
    if (permissionFailure !== undefined) {
        return permissionFailure;
    }
    const output = normalizeTarget(requestRecord.target, context);
    if ("ok" in output) {
        return output;
    }
    const scopeFailure = ensureScope(output.sessionId, context);
    if (scopeFailure !== undefined) {
        return scopeFailure;
    }
    const approvalFailure = ensureApproval(output.requiresTapApproval, context, output.sessionId);
    if (approvalFailure !== undefined) {
        return approvalFailure;
    }
    return {
        ok: true,
        toolId: shellStdinFeedingDescriptor.toolId,
        output,
        audit: [
            auditEvent("agentCore.basicTool.shell.stdinFeeding.dryRun", context, output.sessionId, {
                mode: output.mode,
                inputBytes: output.inputBytes,
                requiresTapApproval: output.requiresTapApproval,
            }),
        ],
        events: ["basicTool.shell.stdinFeeding.dryRun"],
    };
}
