"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildNoToolsNotice = buildNoToolsNotice;
exports.buildShellPolicyPrompt = buildShellPolicyPrompt;
exports.buildMemorySystemPrompt = buildMemorySystemPrompt;
exports.buildIntrinsicToolUsageText = buildIntrinsicToolUsageText;
const inter_dialog_format_1 = require("../runtime/inter-dialog-format");
const minds_i18n_1 = require("./minds-i18n");
function buildNoToolsNotice(language) {
    return language === 'zh'
        ? '无工具：不能调用任何工具，也不能访问 rtws / 文件 / 浏览器 / shell。'
        : 'No tools: do not call any tools, and do not access the rtws, files, browser, or shell.';
}
function getShellPolicyCopy(language) {
    if (language === 'zh') {
        return {
            title: '### Shell 执行策略（重要）',
            noSpecialistsText: '（未配置 shell 专员）',
            specialistRoleReady: '你是本队的 shell 专员，具备 shell 执行能力（高风险）。使用前必须先做风险识别与最小化：',
            specialistRiskBullets: [
                '- 说明目的、预期输出/验证方式、预期工作目录与影响面。',
                '- 优先选择只读命令；写入/删除/网络/权限相关操作必须解释理由与安全边界。',
                '- 如果不确定命令后果，先提出更安全的替代方案或向人类/队友确认。',
            ],
            specialistExecutionReceipt: '当队友请求你执行命令时：请先复述你将执行的命令与风险边界，再执行，并按结构化格式回传 command/exit_code/stdout/stderr。',
            specialistConfiguredNoTools: '你被配置为 shell 专员，但当前没有可用的 shell 工具（团队配置错误）。',
            specialistFixConfig: '在未修复配置前：不要声称自己执行过命令；如需验证，请让人类修复 team.yaml 或把 shell 能力授予正确的成员。',
            noHighRiskTools: '你不具备高权限 shell 工具（shell_cmd/stop_daemon/get_daemon_output）。',
            readonlyAuthorized: '你仅被授权使用 `readonly_shell` 做只读检查（仅允许白名单命令前缀；不得写入/删除/联网/进程管理）：符合只读目的时请直接调用。',
            readonlyDelegateWhenNeeded: (value) => `边界规则：除只读目的外，其它一切 shell 需求都不得自行执行。凡是不在白名单内，或涉及写入/删除/网络/长时间运行/进程管理，必须诉请以下 shell 专员之一执行：${value}。并提供充分理由与可审查的命令提案：`,
            noShellTools: (value) => `你不具备 shell 工具（本环境仅 shell 专员可执行 shell）：可直接诉请以下 shell 专员执行：${value}。不要尝试“编造/假设”命令输出。`,
            delegateWhenNeeded: (value) => `当你确实需要 shell 执行时：直接诉请以下 shell 专员之一执行：${value}。提供充分理由与可审查的命令提案：`,
            delegationProposalBullets: [
                '- 你要达成的目标（why）',
                '- 建议命令（what）+ 预期工作目录（cwd）+ 预期输出/验证方式（how to verify）',
                '- 风险评估与安全边界（risk & guardrails）',
            ],
            specialistListLine: (value) => `本队 shell 专员列表：${value}`,
            delegationSpecialistsLine: (value) => `可诉请的 shell 专员：${value}`,
            tellaskFunctionReminder: (examples) => `重要：如果你打算让队友执行命令，请在同一回复中直接发起 tellask-special 函数调用。可用函数调用示例：${examples}。不要只说“我会请某人运行”。`,
            claimAfterReceiptReminder: '重要：在你看到 shell 专员的回执（command/exit_code/stdout/stderr）之前，不要声称“已运行/已通过/无错”。',
            includeDevopsPolicyForSpecialist: false,
        };
    }
    return {
        title: '### Shell Execution Policy (Important)',
        noSpecialistsText: '(no shell specialists configured)',
        specialistRoleReady: 'You are a designated shell specialist and have shell execution capability (high-risk). Before using it, do risk identification and minimize blast radius:',
        specialistRiskBullets: [
            '- State intent, expected output/verification, expected working directory, and scope of impact.',
            '- Prefer read-only commands; for writes/deletes/network/privilege-related actions, justify and state safety boundaries.',
            '- If unsure about consequences, propose a safer alternative or confirm with a human/teammate first.',
        ],
        specialistExecutionReceipt: 'When teammates ask you to run commands: restate the exact command and guardrails, then execute, and report back with a structured receipt: command/exit_code/stdout/stderr.',
        specialistConfiguredNoTools: 'You are configured as a shell specialist, but you do not currently have shell tools available (team configuration error).',
        specialistFixConfig: 'Until it is fixed: do not claim you ran any command; ask a human to fix team.yaml or grant shell tools to the correct specialist member.',
        noHighRiskTools: 'You do not have high-risk shell tools (shell_cmd/stop_daemon/get_daemon_output).',
        readonlyAuthorized: 'You are authorized to use `readonly_shell` only for read-only inspection (small allowlist only; no writes/deletes/network/process management). When it is truly read-only, call it directly.',
        readonlyDelegateWhenNeeded: (value) => `Boundary rule: anything beyond read-only must not be executed by you. If it is outside the allowlist, or involves writes/deletes/network/long-running jobs/process management, you must tellask one of these shell specialists to execute it: ${value}. Provide a justified, reviewable proposal:`,
        noShellTools: (value) => `You do not have shell tools (only shell specialists can execute shell in this environment): directly tellask one of these shell specialists: ${value}. Do not attempt to "fabricate/assume" command outputs.`,
        delegateWhenNeeded: (value) => `When you genuinely need shell execution, directly tellask one of these shell specialists: ${value}. Provide sufficient rationale and a reviewable command proposal:`,
        delegationProposalBullets: [
            '- Goal (why)',
            '- Proposed command (what) + expected working directory (cwd) + expected output/verification (how to verify)',
            '- Risk assessment and guardrails (risk & guardrails)',
        ],
        specialistListLine: (value) => `Shell specialists in this team: ${value}`,
        delegationSpecialistsLine: (value) => `Shell specialists you can tellask: ${value}`,
        tellaskFunctionReminder: (examples) => `Important: if you intend to delegate, invoke tellask-special functions directly in the same response. Example function calls: ${examples}. Do not just say “I will ask someone to run it”.`,
        claimAfterReceiptReminder: 'Important: do not claim “ran/passed/no errors” until you see the shell specialist’s receipt (command/exit_code/stdout/stderr).',
        includeDevopsPolicyForSpecialist: true,
    };
}
function buildShellPolicyPrompt(ctx) {
    const { language, agentIsShellSpecialist, agentHasShellTools, agentHasReadonlyShell, shellSpecialistMemberIds, } = ctx;
    const copy = getShellPolicyCopy(language);
    const devopsScriptPolicy = language === 'zh'
        ? 'DevOps 场景：忌讳临时脚本。不要用临时脚本完成工作；如需工具脚本，请与队友和人类讨论并在 rtws 中正式设计/命名/规范化后使用。'
        : 'DevOps context: ad-hoc temp scripts are a taboo. Do not rely on temp scripts; if a tool script is needed, align with teammates and the human and formalize it in the rtws before use.';
    const shellSpecialists = shellSpecialistMemberIds.length > 0
        ? shellSpecialistMemberIds.map((id) => `@${id}`).join(', ')
        : copy.noSpecialistsText;
    const specialistListLine = copy.specialistListLine(shellSpecialists);
    const specialistDelegationLine = copy.delegationSpecialistsLine(shellSpecialists);
    const tellaskFunctionExamples = shellSpecialistMemberIds.length > 0
        ? shellSpecialistMemberIds
            .map((id) => `\`${language === 'zh' ? 'tellaskSessionless' : 'tellaskSessionless'}({ targetAgentId: "${id}", tellaskContent: "..." })\``)
            .join(language === 'zh' ? ' / ' : ' / ')
        : language === 'zh'
            ? '（当前无可用 shell 专员）'
            : '(no available shell specialists)';
    const buildDelegationBlock = (introLine) => [
        introLine,
        ...copy.delegationProposalBullets,
        specialistDelegationLine,
        '',
        devopsScriptPolicy,
        '',
        copy.tellaskFunctionReminder(tellaskFunctionExamples),
        copy.claimAfterReceiptReminder,
    ];
    if (agentIsShellSpecialist && agentHasShellTools) {
        const bodyLines = [
            copy.specialistRoleReady,
            ...copy.specialistRiskBullets,
            '',
            copy.specialistExecutionReceipt,
            '',
            specialistListLine,
            ...(copy.includeDevopsPolicyForSpecialist ? ['', devopsScriptPolicy] : []),
        ];
        return `${copy.title}\n\n${bodyLines.join('\n')}`.trim();
    }
    if (agentIsShellSpecialist && !agentHasShellTools) {
        const bodyLines = [
            copy.specialistConfiguredNoTools,
            copy.specialistFixConfig,
            '',
            specialistListLine,
            ...(copy.includeDevopsPolicyForSpecialist ? ['', devopsScriptPolicy] : []),
        ];
        return `${copy.title}\n\n${bodyLines.join('\n')}`.trim();
    }
    const bodyLines = agentHasReadonlyShell
        ? [
            copy.noHighRiskTools,
            copy.readonlyAuthorized,
            '',
            ...buildDelegationBlock(copy.readonlyDelegateWhenNeeded(shellSpecialists)),
        ]
        : [
            copy.noShellTools(shellSpecialists),
            ...buildDelegationBlock(copy.delegateWhenNeeded(shellSpecialists)),
        ];
    return `${copy.title}\n\n${bodyLines.join('\n')}`.trim();
}
function getMemoryPromptCopy(ctx) {
    const runtimeMarkers = (0, inter_dialog_format_1.getRuntimeTransferMarkers)(ctx.language);
    const contextHealthLineZh = ctx.contextHealthPromptMode === 'critical'
        ? ctx.isSideDialog
            ? 'Dominds 已提醒上下文告急：立即停止继续大实现/大阅读。你当前处于支线对话；本程不维护差遣牒，也不整理差遣牒更新提案，只维护足够详尽的当前对话范围（scope=dialog）接续包提醒项并写明本路任务目标，然后 `clear_mind`。提醒项没有固定长度限制。'
            : 'Dominds 已提醒上下文告急：立即停止继续大实现/大阅读。本程只做保信息：先用当前对话范围（scope=dialog）接续包提醒项写明本路任务目标，再把确需共享给同一差遣牒其它对话的讨论事实落到差遣牒合适章节，最后提炼恢复本路对话容易丢的接续包提醒项并 `clear_mind`。'
        : ctx.contextHealthPromptMode === 'caution'
            ? ctx.isSideDialog
                ? 'Dominds 已提醒上下文吃紧：不要继续扩张上下文。你当前处于支线对话；本程不维护差遣牒，也不整理差遣牒更新提案，优先维护足够详尽的当前对话范围（scope=dialog）接续包提醒项并写明本路任务目标，然后尽快 `clear_mind`。提醒项没有固定长度限制。'
                : 'Dominds 已提醒上下文吃紧：不要继续扩张上下文。本程优先用当前对话范围（scope=dialog）接续包提醒项写明本路任务目标，再把确需共享给同一差遣牒其它对话的讨论事实落到差遣牒合适章节，最后提炼恢复本路对话容易丢的提醒项并尽快 `clear_mind`，不要继续大实现/大阅读。'
            : '当前没有生效中的上下文保全提示，按正常工作流推进。';
    const taskdocLogLineZh = ctx.contextHealthPromptMode === 'critical'
        ? ctx.isSideDialog
            ? 'Dominds 已提醒上下文告急：支线对话不要维护差遣牒，也不要整理差遣牒更新提案；把当前这一路支线对话的任务目标、讨论细节、下一步、关键定位、运行/验证信息、临时路径/ID/样例输入和恢复依据写入当前对话范围（scope=dialog）接续包提醒项。提醒项没有固定长度限制，宁可完整一些；允许多条粗略提醒项求稳，但不要在当前程提前做“新一程清醒复核”。Dominds 真正开启新一程后，第一步按 scope=dialog 提醒项里的本路任务目标继续，再复核整理：删除冗余、纠正偏激/失真思路，收敛成高质量提醒项。'
            : '不要把长日志/大段 tool output 直接塞进差遣牒；差遣牒只写结论+下一步。Dominds 已提醒上下文告急：先确保当前对话范围（scope=dialog）接续包提醒项写明本路任务目标；再检查当前对话历史里尚未落文档的讨论细节，只有确需同一差遣牒其它对话/队友共享的状态/决策/约束/目标，主线才优先用 `do_mind` 新增章节保存；只有在确实需要改写已有章节、已完成合并并先调用 `recall_taskdoc` 取得当前 `content_hash` 作为 `previous_content_hash` 时，才用 `change_mind`。接续包提醒项只留差遣牒仍未覆盖、但恢复本路对话容易丢的细节；本程允许先保留多条粗略提醒项求稳，但不要在当前程提前做“新一程清醒复核”。Dominds 真正开启新一程后，第一步按 scope=dialog 提醒项里的本路任务目标继续，再复核整理：删除冗余、纠正偏激/失真思路，收敛成高质量提醒项。'
        : ctx.contextHealthPromptMode === 'caution'
            ? ctx.isSideDialog
                ? 'Dominds 已提醒上下文吃紧：支线对话不要维护差遣牒，也不要整理差遣牒更新提案；把当前这一路支线对话的任务目标、讨论细节、下一步、关键定位、运行/验证信息、临时路径/ID/样例输入和恢复依据写入当前对话范围（scope=dialog）接续包提醒项。提醒项没有固定长度限制，宁可完整一些；若一时来不及，可先保留多条粗略提醒项过桥，但不要在当前程提前做“新一程清醒复核”。Dominds 真正开启新一程后，第一步按 scope=dialog 提醒项里的本路任务目标继续，再复核整理：删除冗余、纠正偏激/失真思路，收敛成高质量提醒项。'
                : '不要把长日志/大段 tool output 直接塞进差遣牒；差遣牒只写结论+下一步。Dominds 已提醒上下文吃紧：先确保当前对话范围（scope=dialog）接续包提醒项写明本路任务目标；再检查当前对话历史里尚未落文档的讨论细节，只有确需同一差遣牒其它对话/队友共享的状态/决策/约束/目标，主线才优先用 `do_mind` 新增章节保存；只有在确实需要改写已有章节、已完成合并并先调用 `recall_taskdoc` 取得当前 `content_hash` 作为 `previous_content_hash` 时，才用 `change_mind`。接续包提醒项只留差遣牒仍未覆盖、但恢复本路对话容易丢的细节；若一时来不及，可先保留多条粗略提醒项过桥，但不要在当前程提前做“新一程清醒复核”。Dominds 真正开启新一程后，第一步按 scope=dialog 提醒项里的本路任务目标继续，再复核整理：删除冗余、纠正偏激/失真思路，收敛成高质量提醒项。'
            : '不要把长日志/大段 tool output 直接塞进差遣牒；差遣牒只写结论+下一步；提醒项也只留可扫读摘录。准备 `clear_mind` 的接续包提醒项必须是当前对话范围（scope=dialog），写明本路任务目标，并保持结构化、便于快速恢复。';
    const contextHealthLineEn = ctx.contextHealthPromptMode === 'critical'
        ? ctx.isSideDialog
            ? 'Dominds has warned that context is critical: stop large implementations/reads immediately. You are in a Side Dialog; in this course, do not maintain Taskdoc and do not draft Taskdoc update proposals. Only maintain sufficiently detailed current-dialog scoped (scope=dialog) continuation-package reminders, state this dialog task goal, then `clear_mind`. Reminders have no fixed length limit.'
            : 'Dominds has warned that context is critical: stop large implementations/reads immediately. In this course, only preserve information: first state this dialog task goal in a current-dialog scoped (scope=dialog) continuation-package reminder, then record only discussion facts that other dialogs/teammates sharing the same Taskdoc truly need to know, then distill details easy to lose when resuming this dialog into continuation-package reminders and `clear_mind`.'
        : ctx.contextHealthPromptMode === 'caution'
            ? ctx.isSideDialog
                ? 'Dominds has warned that context is tight: do not keep expanding context. You are in a Side Dialog; in this course, do not maintain Taskdoc and do not draft Taskdoc update proposals. Prioritize sufficiently detailed current-dialog scoped (scope=dialog) continuation-package reminders, state this dialog task goal, then `clear_mind`. Reminders have no fixed length limit.'
                : 'Dominds has warned that context is tight: do not keep expanding context. In this course, first state this dialog task goal in a current-dialog scoped (scope=dialog) continuation-package reminder, then record only discussion facts that other dialogs/teammates sharing the same Taskdoc truly need to know, then distill details easy to lose when resuming this dialog into reminders and `clear_mind`; do not continue large implementations/reads.'
            : 'There is no active context-preservation notice in effect right now; proceed with the normal workflow.';
    const taskdocLogLineEn = ctx.contextHealthPromptMode === 'critical'
        ? ctx.isSideDialog
            ? 'Dominds has warned that context is critical: in a Side Dialog, do not maintain Taskdoc and do not draft Taskdoc update proposals. Put this specific Side Dialog task goal, discussion details, next actions, key pointers, run/verify info, volatile paths/IDs/sample inputs, and resume reasoning into current-dialog scoped (scope=dialog) continuation-package reminders. Reminders have no fixed length limit, so prefer being complete. Rough multi-reminder bridge notes are acceptable in this course, but do not perform the new-course “clear-headed review” early. Once Dominds actually starts the new course, first continue from the task goal in scope=dialog reminders, then review/rewrite them: remove redundancy, correct biased or distorted bridge notes, and compress them into high-quality reminders.'
            : 'Do not paste long logs/tool outputs into Taskdoc; Taskdoc should record decisions + next steps. Dominds has warned that context is critical: first make sure a current-dialog scoped (scope=dialog) continuation-package reminder states this dialog task goal. Then review current-dialog discussion details not yet written into documentation; only if they truly need to be shared with other dialogs/teammates on the same Taskdoc, prefer creating a new section with `do_mind`; use `change_mind` only when an existing section truly needs rewriting, you have merged against the current content, and you have first called `recall_taskdoc` to get the current `content_hash` as `previous_content_hash`. Continuation-package reminders should keep only details still not covered by Taskdoc but easy to lose when resuming this dialog. Rough multi-reminder bridge notes are acceptable in this course, but do not perform the new-course “clear-headed review” early. Once Dominds actually starts the new course, first continue from the task goal in scope=dialog reminders, then review/rewrite them: remove redundancy, correct biased or distorted bridge notes, and compress them into high-quality reminders.'
        : ctx.contextHealthPromptMode === 'caution'
            ? ctx.isSideDialog
                ? 'Dominds has warned that context is tight: in a Side Dialog, do not maintain Taskdoc and do not draft Taskdoc update proposals. Put this specific Side Dialog task goal, discussion details, next actions, key pointers, run/verify info, volatile paths/IDs/sample inputs, and resume reasoning into current-dialog scoped (scope=dialog) continuation-package reminders. Reminders have no fixed length limit, so prefer being complete. If needed, rough multi-reminder bridge notes are acceptable, but do not perform the new-course “clear-headed review” early. Once Dominds actually starts the new course, first continue from the task goal in scope=dialog reminders, then review/rewrite them: remove redundancy, correct biased or distorted bridge notes, and compress them into high-quality reminders.'
                : 'Do not paste long logs/tool outputs into Taskdoc; Taskdoc should record decisions + next steps. Dominds has warned that context is tight: first make sure a current-dialog scoped (scope=dialog) continuation-package reminder states this dialog task goal. Then review current-dialog discussion details not yet written into documentation; only if they truly need to be shared with other dialogs/teammates on the same Taskdoc, prefer creating a new section with `do_mind`; use `change_mind` only when an existing section truly needs rewriting, you have merged against the current content, and you have first called `recall_taskdoc` to get the current `content_hash` as `previous_content_hash`. Continuation-package reminders should keep only details still not covered by Taskdoc but easy to lose when resuming this dialog. If needed, rough multi-reminder bridge notes are acceptable, but do not perform the new-course “clear-headed review” early. Once Dominds actually starts the new course, first continue from the task goal in scope=dialog reminders, then review/rewrite them: remove redundancy, correct biased or distorted bridge notes, and compress them into high-quality reminders.'
            : 'Do not paste long logs/tool outputs into Taskdoc; Taskdoc should record decisions + next steps; reminders should also keep only scannable excerpts. Continuation-package reminders before `clear_mind` must be current-dialog scoped (scope=dialog), state this dialog task goal, and stay structured for fast resume.';
    if (ctx.language === 'zh') {
        return {
            title: '### 记忆系统（重要）',
            temporaryInfoLine: '你的聊天记录与工具输出是临时信息：会快速累积、很快过时，并增加你的认知负担。在同一轮对话中，除了 `clear_mind` 以外你无法真正丢弃这些历史。',
            clearMindLine: '`clear_mind` 会开启新一程对话（保留差遣牒、提醒项与记忆层），从而卸掉这部分认知负载并继续推进。因此你必须先把关键信息提炼到高价值载体：',
            taskdocContractLine: '- 差遣牒（`*.tsk/`）：全队共享的任务契约（goals/constraints/progress）；不是个人笔记，保持足够短，每轮都应可通读。',
            taskdocSemanticsLine: '- 章节语义约定：`progress` 是全队共享、准实时、可扫读的任务公告牌，用来记录当前有效状态、关键决策、下一步与仍成立阻塞；不是流水账，也不是个人工作记录。`goals` / `constraints` 是较稳定的任务契约；每次更新都必须保留仍然有效的他人条目。',
            taskdocSectionReplaceLine: ctx.isSideDialog && ctx.contextHealthPromptMode !== 'normal'
                ? '- Dominds 已提醒当前上下文吃紧/告急，且你处于支线对话：本程不要维护差遣牒，也不要整理差遣牒更新提案；把本路任务目标和下一程需要恢复的细节写入足够详尽的当前对话范围（scope=dialog）接续包提醒项。'
                : `- 更新差遣牒时：少量新增条目可用 \`mind_more\` 追加（默认 progress）；缺失章节用 \`do_mind\` 创建；需要删除陈旧项、重排结构或压缩时，先对照上下文中注入的当前内容完成合并，再调用 \`recall_taskdoc\` 取得当前 \`content_hash\`，然后用带 \`previous_content_hash\` 的 \`change_mind\` 整章替换；需要删除整章文件时用 \`never_mind\`；禁止覆盖/抹掉他人条目；自己负责维护的条目必须标注责任人（例如 \`- [owner:@${ctx.agentId}] ...\` 或用 \`### @${ctx.agentId}\` 分块）。`,
            progressLine: ctx.isSideDialog && ctx.contextHealthPromptMode !== 'normal'
                ? '- Dominds 已提醒当前上下文吃紧/告急，且你处于支线对话：本程不更新 `progress`；只把本路任务目标和下一程接续所需信息写入当前对话范围（scope=dialog）提醒项。'
                : '- 更新 `progress` 时：它必须始终是可供全队扫读的完整当前快照，而不是只追加自己这一轮的零散笔记。',
            injectedTaskdocLine: '- 重要：差遣牒内容会被系统以内联形式注入到上下文中（本轮生成视角下即为最新；注入内容不包括全局约束）。需要回顾时请直接基于上下文里的差遣牒内容回顾与决策，不要试图用通用文件工具读取 `*.tsk/` 下的文件（会被拒绝）。',
            constraintsLine: '- 约定：`constraints` 只写任务特有的硬要求，不得写入系统提示/工具文档里已明确且由系统强制执行的通用规则（例如 `*.tsk/` 封装禁止通用文件工具）。一经发现重复，必须删除并告知用户。',
            remindersLine: ctx.isSideDialog
                ? '- 提醒项（以 `reminder_id` 标识，手头工作）：当前对话的高频工作记录/关键细节（偏私有，不作为全队公告）；默认保持少量（常见 1–3 条），优先 `update_reminder` 压缩/合并，不再需要就 `delete_reminder`。准备 `clear_mind` 开启新一程对话时，整理当前对话范围（scope=dialog）的“结构化接续包提醒项”，必须写明本路任务目标，并保留恢复工作容易丢的细节（如第一步、关键定位、运行/验证信息、临时 ids/路径）。若 Dominds 已提醒当前程吃紧/告急，支线对话不要维护差遣牒，也不要整理差遣牒更新提案；只维护足够详尽的 scope=dialog 接续包提醒项，提醒项没有固定长度限制，允许先保留多条粗略提醒项把信息带过桥；当前程只做保信息 + clear_mind；只有 Dominds 实际开启新一程后，第一步才是按 scope=dialog 提醒项里的本路任务目标继续，再复核整理这些接续包/粗略提醒项：删除冗余、纠正偏激或失真的过桥思路、压缩成高质量提醒项。'
                : '- 提醒项（以 `reminder_id` 标识，手头工作）：当前对话的高频工作记录/关键细节（偏私有，不作为全队公告）；默认保持少量（常见 1–3 条），优先 `update_reminder` 压缩/合并，不再需要就 `delete_reminder`。准备 `clear_mind` 开启新一程对话时，先用当前对话范围（scope=dialog）结构化接续包提醒项写明本路任务目标，再把尚未落实到文档、且下一程需要同一差遣牒其它对话/队友知会的讨论细节落到差遣牒合适章节；提醒项只保留差遣牒仍未覆盖、但恢复本路对话容易丢的细节（如第一步、关键定位、运行/验证信息、临时 ids/路径）。若 Dominds 已提醒当前程吃紧/告急，则允许先保留多条粗略 scope=dialog 提醒项把信息带过桥；当前程只做落文档、保信息 + clear_mind；只有 Dominds 实际开启新一程后，第一步才是按 scope=dialog 提醒项里的本路任务目标继续，再复核整理这些接续包/粗略提醒项：删除冗余、纠正偏激或失真的过桥思路、压缩成高质量提醒项。',
            teamMemoryLine: '- 团队记忆：稳定的团队约定/工程规约（跨任务共享）。',
            personalMemoryLine: '- 个人记忆：稳定的个人习惯/偏好与职责域知识；记忆会在每次生成时自动注入上下文，应保持少量且准确（关键文档/代码的精确路径 + 最小必要事实）。不要记录具体任务状态。',
            skillsLine: '- Skills：可复用操作指引/检查清单/触发条件与边界。工作区关联强的事实、路径、局部契约进 memory/env；独立于工作区内容的“怎么做”进 skill。skill 不授予工具权限；需要脚本/MCP/外部能力时应配套 app/toolset/权限配置。',
            sideDialogDutyLine: ctx.contextHealthPromptMode === 'normal'
                ? `你当前处于支线对话：此处不允许 \`do_mind\` / \`mind_more\` / \`change_mind\` / \`never_mind\`。当你判断需要更新差遣牒（尤其是 progress 公告牌）时，请在合适时机直接诉请差遣牒维护人 \`@${ctx.taskdocMaintainerId}\` 执行更新，并给出要新增的章节、要追加的条目、已合并好的“新全文/替换稿”，或要删除的章节。不要声称已更新，除非看到回执。`
                : '你当前处于支线对话，且 Dominds 已提醒上下文吃紧/告急：本程不要维护差遣牒，也不要整理差遣牒更新提案。请把本路任务目标、下一程需要恢复的讨论细节、定位、验证方式和临时信息写入足够详尽的当前对话范围（scope=dialog）接续包提醒项。',
            mainDialogDutyLine: '你当前处于主线对话：你负责综合维护全队共享差遣牒（尤其是 progress 公告牌）。当队友/支线对话提出更新建议时，及时合并、压缩并保持清晰。',
            teammateTellaskRoundDoneLine: `队友诉请重要语义：当你在诉请者上下文中收到带${runtimeMarkers.finalCompleted}标记的回贴，表示该轮诉请已经结束；对方不会继续执行同一轮诉请。此时如果目标未达成，“等待”是错误的：必须显式发起新一轮 tellask 才能继续推进。并行语义：不要把智能体队友当成真人同事；祂不会因为你又发一条诉请而被打扰。同一个队友 + 同一个 sessionSlug = 接着同一件事说，并更新那件正在做的事；tellaskSessionless 或不同 sessionSlug = 另一件独立任务。`,
            teamMemoryHintLine: '提示：你具备团队记忆工具（`add_team_memory` / `replace_team_memory` / `drop_team_memory` / `clear_team_memory`），可在必要时维护团队记忆（谨慎、少量、只写稳定约定）。',
            personalMemoryHintLine: `提示：你具备个人记忆工具（\`add_personal_memory\` / \`replace_personal_memory\` / \`drop_personal_memory\` / \`clear_personal_memory\`）。个人记忆仅对当前智能体可见，且系统会自动按成员隔离到 \`.minds/memory/individual/<member-id>/...\`；因此 \`path\` 不应包含你的成员 id（不要写 \`${ctx.agentId}/...\`）。首次创建时直接用 \`add_personal_memory\` 即可，目录会由系统自动创建。记忆会在每次生成时自动注入上下文：保持少量、保持准确、按“未来会一起更新的内容”合并；写稳定事实（关键路径 + 最小必要约定），不要写任务进度/当天状态；一旦你修改了相关文件或发现记忆过期/冲突，立刻用 \`replace_personal_memory\` 更新。`,
            sideDialogWorkflowLine: ctx.contextHealthPromptMode === 'normal'
                ? `工作流：先做事 → 再提炼（\`update_reminder\`；必要时整理差遣牒追加条目/更新提案并诉请 \`@${ctx.taskdocMaintainerId}\` 合并写入）→ 然后 \`clear_mind\` 清空噪音。`
                : '工作流：停止扩张上下文 → 维护足够详尽的当前对话范围（scope=dialog）接续包提醒项（`add_reminder` 或 `update_reminder`，必须写明本路任务目标，没有固定长度限制）→ 然后 `clear_mind` 开启新一程。',
            mainDialogWorkflowLine: '工作流：先做事 -> 再提炼（`update_reminder` + `mind_more(progress)`；需要压缩/删旧时先 `recall_taskdoc` 取得 `content_hash`，再用带 `previous_content_hash` 的 `change_mind`；要删除整章文件时用 `never_mind`）-> 然后 `clear_mind` 清空噪音。',
            ...(ctx.isSideDialog
                ? {}
                : {
                    progressVcsOrderLine: '硬性顺序：先补 `progress`，再动 git。只要这次代码/文档改动准备进 git（add / commit / push），先确认 `progress` 已经写清当前状态、决策、阻塞和下一步；如果还没写清，就先补写。简单判断：改动会进仓库 + `progress` 还没跟上 = 先别动 git。`git status` 只用来确认，不是提交动作。不要把“提交了某个 commit”“push 了”写进 `progress`。',
                }),
            contextHealthLine: contextHealthLineZh,
            taskdocLogLine: taskdocLogLineZh,
        };
    }
    return {
        title: '### Memory System (Important)',
        temporaryInfoLine: 'Dialog history and tool outputs are temporary: they accumulate quickly, become stale, and increase cognitive load. Within a course, you cannot truly drop that history except via `clear_mind`.',
        clearMindLine: '`clear_mind` starts a new course while preserving Taskdoc, reminders, and memory layers. Therefore, before clearing, distill key information into durable layers:',
        taskdocContractLine: '- Taskdoc (`*.tsk/`): the team-shared task contract (goals/constraints/progress). It is not a personal notebook; keep it small enough to read every course.',
        taskdocSemanticsLine: '- Section semantics: `progress` is the team-shared, quasi-real-time, scannable task bulletin board for current effective state, key decisions, next steps, and still-active blockers; it is not a raw log or personal work record. `goals` / `constraints` are the more stable task contract; every update must preserve still-valid entries from others.',
        taskdocSectionReplaceLine: ctx.isSideDialog && ctx.contextHealthPromptMode !== 'normal'
            ? '- Dominds has warned that context is tight/critical in this Side Dialog: do not maintain Taskdoc and do not draft Taskdoc update proposals in this course; put this dialog task goal and resume-critical details into sufficiently detailed current-dialog scoped (scope=dialog) continuation-package reminders.'
            : `- When updating Taskdoc: use \`mind_more\` for small append-only additions (defaults to progress); create missing sections with \`do_mind\`; when stale entries must be removed, reordered, or compressed, first merge against the current injected content, then call \`recall_taskdoc\` to get the current \`content_hash\`, then use \`change_mind\` for a full-section replacement with that value as \`previous_content_hash\`; when a whole section file should be removed, use \`never_mind\`; do not overwrite other contributors; add an explicit owner tag for entries you maintain (e.g., \`- [owner:@${ctx.agentId}] ...\` or a \`### @${ctx.agentId}\` block).`,
        progressLine: ctx.isSideDialog && ctx.contextHealthPromptMode !== 'normal'
            ? '- Dominds has warned that context is tight/critical in this Side Dialog: do not update `progress` in this course; put this dialog task goal and resume-critical information into current-dialog scoped (scope=dialog) reminders only.'
            : '- When updating `progress`, keep it as a complete, team-scannable current snapshot instead of appending only your own latest notes.',
        injectedTaskdocLine: '- Important: the Taskdoc content is injected inline into the context (the latest as of this generation; injected content excludes global constraints). Review the injected Taskdoc instead of trying to read files under `*.tsk/` via general file tools (they will be rejected).',
        constraintsLine: '- Convention: Taskdoc `constraints` must contain task-specific requirements only; do not include global, system-enforced rules already stated in system prompt/tool docs (e.g. `.tsk/` encapsulation bans general file tools). If duplication is found, you MUST remove it and notify the user.',
        remindersLine: ctx.isSideDialog
            ? '- Reminders (addressed by `reminder_id`, current work): your high-frequency per-dialog worklog + critical details (not a team bulletin board); keep it small by default (often 1–3 items), prefer `update_reminder` to compress/merge, and delete when obsolete. When preparing `clear_mind` to start a new course, create a current-dialog scoped (scope=dialog) structured continuation-package reminder, state this dialog task goal, and preserve details easy to lose during resume (first step, key pointers, run/verify info, volatile ids/paths). If Dominds has warned that the current course is tight/critical, you are in a Side Dialog: do not maintain Taskdoc and do not draft Taskdoc update proposals; only maintain sufficiently detailed scope=dialog continuation-package reminders. Reminders have no fixed length limit, rough multi-reminder bridge notes are acceptable, and in the current course you should only preserve volatile information and clear_mind. Only after Dominds actually starts the new course does the mandatory first step become continuing this dialog from the task goal in scope=dialog reminders, then reviewing and rewriting those continuation/rough reminders with a clear head: remove redundancy, correct biased or distorted bridge notes, and compress them into high-quality reminders.'
            : '- Reminders (addressed by `reminder_id`, current work): your high-frequency per-dialog worklog + critical details (not a team bulletin board); keep it small by default (often 1–3 items), prefer `update_reminder` to compress/merge, and delete when obsolete. When preparing `clear_mind` to start a new course, first state this dialog task goal in a current-dialog scoped (scope=dialog) structured continuation-package reminder, then record undocumented discussion details that other dialogs/teammates sharing the same Taskdoc truly need to know into the appropriate Taskdoc sections. Reminders should keep only details still not covered by Taskdoc but easy to lose when resuming this dialog (first step, key pointers, run/verify info, volatile ids/paths). If Dominds has warned that the current course is tight/critical, rough multi-reminder scope=dialog bridge notes are acceptable; in the current course, only document missing details, preserve volatile information, and clear_mind. Only after Dominds actually starts the new course does the mandatory first step become continuing this dialog from the task goal in scope=dialog reminders, then reviewing and rewriting those continuation/rough reminders with a clear head: remove redundancy, correct biased or distorted bridge notes, and compress them into high-quality reminders.',
        teamMemoryLine: '- Team memory: stable shared conventions (cross-task).',
        personalMemoryLine: '- Personal memory: stable personal habits/preferences and responsibility-scope knowledge. Memory is automatically injected into context on each generation: keep it small and accurate (exact key doc/code paths + minimal key facts); do not store per-task state.',
        skillsLine: '- Skills: reusable operating guidance, checklists, triggers, and boundaries. Workspace-coupled facts, paths, and local contracts belong in memory/env; workspace-independent “how to do it” procedures belong in skills. Skills do not grant tool permissions; pair scripts/MCP/external capabilities with apps/toolsets/permission configuration.',
        sideDialogDutyLine: ctx.contextHealthPromptMode === 'normal'
            ? `You are currently in a Side Dialog: \`do_mind\` / \`mind_more\` / \`change_mind\` / \`never_mind\` are not allowed here. When Taskdoc should be updated (especially the shared progress bulletin board), tellask the Taskdoc maintainer \`@${ctx.taskdocMaintainerId}\` with the new section to create, entries to append, a fully merged replacement draft, or the section to delete. Do not claim it is updated until you see a receipt.`
            : 'You are currently in a Side Dialog, and Dominds has warned that context is tight/critical: do not maintain Taskdoc and do not draft Taskdoc update proposals in this course. Put this dialog task goal, discussion details, pointers, verification method, and volatile resume information into sufficiently detailed current-dialog scoped (scope=dialog) continuation-package reminders.',
        mainDialogDutyLine: 'You are currently in the Main Dialog: you are responsible for keeping the team-shared Taskdoc coherent and up to date (especially the progress bulletin board). Merge proposals from teammates/Side Dialogs promptly and keep it concise.',
        teammateTellaskRoundDoneLine: `Teammate Tellask semantics: when you receive a tellasker reply with the ${runtimeMarkers.finalCompleted} marker, that Tellask round is finished; the tellaskee will not keep executing the same call in the background. If the objective is not met, “waiting” is wrong: you must explicitly start a new Tellask round to continue. Parallel semantics: do not treat an agent teammate like a human coworker who can only handle one conversation at a time. Same teammate + same sessionSlug = continue the same task and update that task; tellaskSessionless or a different sessionSlug = another independent task.`,
        teamMemoryHintLine: 'Hint: you have team-memory tools (`add_team_memory` / `replace_team_memory` / `drop_team_memory` / `clear_team_memory`) and may maintain team memory when it is truly stable and worth sharing.',
        personalMemoryHintLine: `Hint: you have personal-memory tools (\`add_personal_memory\` / \`replace_personal_memory\` / \`drop_personal_memory\` / \`clear_personal_memory\`). Personal memory is private to the current agent and is automatically isolated under \`.minds/memory/individual/<member-id>/...\`; therefore \`path\` MUST NOT include your member id (do not write \`${ctx.agentId}/...\`). For first-time setup, just call \`add_personal_memory\`—the directory will be created automatically. Memory is automatically injected into context on each generation: keep it small, keep it accurate, and group facts that are updated together. Store stable facts (exact key paths + minimal contracts), not daily state/progress. If you changed those files or detect staleness/conflicts, immediately \`replace_personal_memory\` to keep it accurate.`,
        sideDialogWorkflowLine: ctx.contextHealthPromptMode === 'normal'
            ? `Workflow: do work → distill (\`update_reminder\`; when Taskdoc needs updates, draft append entries, a merged replacement, or a section deletion and ask \`@${ctx.taskdocMaintainerId}\`) → then \`clear_mind\` to drop noise.`
            : 'Workflow: stop expanding context → maintain sufficiently detailed current-dialog scoped (scope=dialog) continuation-package reminders (`add_reminder` or `update_reminder`, must state this dialog task goal, with no fixed length limit) → then `clear_mind` to start a new course.',
        mainDialogWorkflowLine: 'Workflow: do work -> distill (`update_reminder` + `mind_more(progress)`; when compression/deletion is needed, first use `recall_taskdoc` to get `content_hash`, then use `change_mind` with `previous_content_hash`; use `never_mind` when removing a whole section file) -> then `clear_mind` to drop noise.',
        ...(ctx.isSideDialog
            ? {}
            : {
                progressVcsOrderLine: 'Hard order: update `progress` first, then use git. If this code/docs change is going into git (add / commit / push), make sure `progress` already says the current state, decisions, blockers, and next step; if not, write it first. Simple check: change will enter the repo + `progress` is behind = stop and update `progress` first. `git status` is only for checking, not a commit step. Do not write git events like “committed X” or “ran git push” into progress.',
            }),
        contextHealthLine: contextHealthLineEn,
        taskdocLogLine: taskdocLogLineEn,
    };
}
function buildMemorySystemPrompt(ctx) {
    const copy = getMemoryPromptCopy(ctx);
    const body = [
        copy.temporaryInfoLine,
        copy.clearMindLine,
        copy.taskdocContractLine,
        copy.taskdocSemanticsLine,
        copy.taskdocSectionReplaceLine,
        copy.progressLine,
        copy.injectedTaskdocLine,
        copy.constraintsLine,
        copy.remindersLine,
        copy.teamMemoryLine,
        copy.personalMemoryLine,
        copy.skillsLine,
        '',
        ctx.isSideDialog ? copy.sideDialogDutyLine : copy.mainDialogDutyLine,
        copy.teammateTellaskRoundDoneLine,
        ...(ctx.agentHasTeamMemoryTools ? [copy.teamMemoryHintLine] : []),
        ...(ctx.agentHasPersonalMemoryTools ? [copy.personalMemoryHintLine] : []),
        ctx.isSideDialog ? copy.sideDialogWorkflowLine : copy.mainDialogWorkflowLine,
        ...(copy.progressVcsOrderLine === undefined ? [] : [copy.progressVcsOrderLine]),
        copy.contextHealthLine,
        copy.taskdocLogLine,
    ].join('\n');
    return `${copy.title}\n\n${body}`.trim();
}
function buildFuncToolUsageText(language, funcTools) {
    if (funcTools.length === 0) {
        return language === 'zh' ? '没有可用的函数工具。' : 'No function tools available.';
    }
    return funcTools
        .map((tool) => {
        const schema = tool.parameters;
        const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
        const requiredValue = schema['required'];
        const required = Array.isArray(requiredValue) && requiredValue.every((v) => typeof v === 'string')
            ? requiredValue
            : [];
        const req = required.length > 0 ? required.join(', ') : (0, minds_i18n_1.noneRequiredFieldsText)(language);
        const propsValue = schema['properties'];
        const propsRecord = isRecord(propsValue) ? propsValue : {};
        const props = Object.entries(propsRecord)
            .map(([k, v]) => {
            const desc = isRecord(v) && 'description' in v && typeof v.description === 'string'
                ? v.description
                : 'parameter';
            return `- ${k}: ${desc}`;
        })
            .join('\n');
        const labels = (0, minds_i18n_1.funcToolUsageLabels)(language);
        const toolDesc = tool.descriptionI18n
            ? (tool.descriptionI18n[language] ?? tool.descriptionI18n.en ?? tool.description)
            : (tool.description ?? '');
        return `#### ${labels.toolLabel}: ${tool.name}\n\n${toolDesc}\n\n- ${labels.invocationLabel}: ${labels.invocationBody}\n- ${labels.requiredLabel}: ${req}\n- ${labels.parametersLabel}:\n${props}`.trim();
    })
        .join('\n\n');
}
function buildIntrinsicToolUsageText(language, funcTools) {
    const usage = buildFuncToolUsageText(language, funcTools).trim();
    if (usage === '')
        return language === 'zh' ? '（无）' : '(none)';
    return usage;
}
