lemma-agent 0.0.0-stage → 1.0.0
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/README.md +121 -2
- package/bin/lemma.mjs +42 -0
- package/dist/acceptance.js +63 -0
- package/dist/admin.js +1482 -0
- package/dist/agents.js +245 -0
- package/dist/api-member.js +537 -0
- package/dist/app.js +161 -0
- package/dist/board.js +185 -0
- package/dist/business-tools.js +153 -0
- package/dist/change-ops.js +91 -0
- package/dist/changes.js +46 -0
- package/dist/cli-runner.js +106 -0
- package/dist/code-tools.js +396 -0
- package/dist/coding-benchmark-fixtures.js +1049 -0
- package/dist/coding-benchmark-suite.js +1252 -0
- package/dist/collaboration-benchmark.js +349 -0
- package/dist/config.js +392 -0
- package/dist/context-benchmark.js +91 -0
- package/dist/conventions.js +282 -0
- package/dist/conversation.js +39 -0
- package/dist/credentials.js +44 -0
- package/dist/deliverables.js +43 -0
- package/dist/digest.js +129 -0
- package/dist/dispatch.js +801 -0
- package/dist/execution-settings.js +24 -0
- package/dist/git-workbench.js +800 -0
- package/dist/git.js +149 -0
- package/dist/integration-git.js +108 -0
- package/dist/integrations.js +557 -0
- package/dist/jobs.js +100 -0
- package/dist/lead.js +263 -0
- package/dist/learning.js +36 -0
- package/dist/main.js +1402 -0
- package/dist/mcp-settings.js +45 -0
- package/dist/mcp-tools.js +102 -0
- package/dist/member-settings.js +245 -0
- package/dist/model-selection.js +48 -0
- package/dist/models.js +145 -0
- package/dist/native-selectors.js +45 -0
- package/dist/native-terminal-components.js +100 -0
- package/dist/ood-benchmark.js +660 -0
- package/dist/operations.js +21 -0
- package/dist/printer.js +113 -0
- package/dist/repair.js +102 -0
- package/dist/resources.js +31 -0
- package/dist/result-summary.js +8 -0
- package/dist/results.js +41 -0
- package/dist/scope.js +114 -0
- package/dist/sessions.js +95 -0
- package/dist/settings.js +30 -0
- package/dist/task-commands.js +37 -0
- package/dist/task-lifecycle.js +49 -0
- package/dist/task-readiness.js +22 -0
- package/dist/task-recovery.js +116 -0
- package/dist/task-review.js +70 -0
- package/dist/task-workflow.js +424 -0
- package/dist/terminal-layout.js +27 -0
- package/dist/terminal-state.js +145 -0
- package/dist/terminal.js +800 -0
- package/dist/tool-settings.js +111 -0
- package/dist/tools.js +1043 -0
- package/dist/ux-telemetry.js +127 -0
- package/dist/view.js +114 -0
- package/package.json +79 -6
- package/web/index.html +136 -0
- package/web/js/conversations.js +312 -0
- package/web/js/dag.js +495 -0
- package/web/js/drawer.js +139 -0
- package/web/js/editors.js +424 -0
- package/web/js/gitlens.js +844 -0
- package/web/js/main.js +152 -0
- package/web/js/sankey.js +476 -0
- package/web/js/store.js +291 -0
- package/web/js/ticket.js +151 -0
- package/web/js/timeline.js +183 -0
- package/web/js/topology.js +454 -0
- package/web/js/util.js +232 -0
- package/web/js/views.js +1496 -0
- package/web/style.css +5299 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { discoverMcp, validateMcpGrants } from "./mcp-tools.js";
|
|
2
|
+
import { editSettings } from "./settings.js";
|
|
3
|
+
import { saveCredential } from "./credentials.js";
|
|
4
|
+
export const MCP_HELP = "/mcp add|refresh|remove|list <成员ID> [连接ID] 发现并明确授权 MCP Streamable HTTP 只读工具(可选本机 Bearer 凭据)";
|
|
5
|
+
export async function mcpSettingsCommand(line, host) {
|
|
6
|
+
const [, action, memberId, id, ...extra] = line.trim().split(/\s+/), current = host.config();
|
|
7
|
+
if (!action) {
|
|
8
|
+
host.log(MCP_HELP);
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
const member = memberId && Object.hasOwn(current.agents, memberId) ? current.agents[memberId] : undefined;
|
|
12
|
+
if (!member?.api || extra.length)
|
|
13
|
+
throw new Error(MCP_HELP);
|
|
14
|
+
const grants = structuredClone(member.api.mcpServers ?? []);
|
|
15
|
+
if (action === "list") {
|
|
16
|
+
host.log(JSON.stringify(grants.map(({ credential, ...grant }) => ({ ...grant, localCredential: !!credential })), null, 2));
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
if (!id || !["add", "refresh", "remove"].includes(action))
|
|
20
|
+
throw new Error(MCP_HELP);
|
|
21
|
+
await host.assertIdle();
|
|
22
|
+
const draft = editSettings(host.path), old = grants.find((grant) => grant.id === id);
|
|
23
|
+
if (action === "add" ? !!old : !old)
|
|
24
|
+
throw new Error("连接已存在或找不到连接,请检查 ID。");
|
|
25
|
+
let nextGrant = old;
|
|
26
|
+
if (action !== "remove") {
|
|
27
|
+
const url = old?.url ?? (await host.question({ title: "MCP Streamable HTTP 地址" })).trim();
|
|
28
|
+
const secret = await host.question({ title: "MCP Bearer 密钥(隐藏输入;留空保留或无认证)", secret: true });
|
|
29
|
+
const credential = secret.trim() ? saveCredential(secret) : old?.credential;
|
|
30
|
+
const candidate = { id, url, ...(credential ? { credential } : {}), tools: [{ name: "validation", inputSchema: { type: "object", properties: {} } }] };
|
|
31
|
+
validateMcpGrants([candidate]);
|
|
32
|
+
const catalog = await discoverMcp(candidate);
|
|
33
|
+
host.log(catalog.map((tool) => `${tool.name} · ${tool.readOnly ? "只读" : "未声明只读,当前不支持授权"} · ${tool.description ?? ""}`).join("\n"));
|
|
34
|
+
const selected = (await host.question({ title: "授权工具名(逗号分隔;仅选择可信的只读工具)", value: old?.tools.map((tool) => tool.name).join(",") })).trim() || old?.tools.map((tool) => tool.name).join(",") || "";
|
|
35
|
+
const names = [...new Set(selected.split(",").map((name) => name.trim()).filter(Boolean))];
|
|
36
|
+
const tools = names.map((name) => { const tool = catalog.find((tool) => tool.name === name); if (!tool?.readOnly)
|
|
37
|
+
throw new Error("只能授权目录中明确声明只读的工具;声明本身不替代对服务的信任。"); const { readOnly, ...definition } = tool; return definition; });
|
|
38
|
+
nextGrant = { id, url, ...(credential ? { credential } : {}), tools };
|
|
39
|
+
validateMcpGrants([nextGrant]);
|
|
40
|
+
}
|
|
41
|
+
const next = draft.apply((raw) => { raw.agents = { ...raw.agents, [memberId]: { ...member, api: { ...member.api, mcpServers: [...grants.filter((grant) => grant.id !== id), ...(action === "remove" ? [] : [nextGrant])] } } }; });
|
|
42
|
+
await host.commit(draft, next, false);
|
|
43
|
+
host.log("MCP 成员授权已保存并生效,历史保持。");
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
2
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
3
|
+
import { defineTool } from "@earendil-works/pi-durable";
|
|
4
|
+
import { compile, unsafe } from "@earendil-works/pi-schema";
|
|
5
|
+
import { readCredential } from "./credentials.js";
|
|
6
|
+
export function validateMcpGrants(grants) {
|
|
7
|
+
if (grants === undefined)
|
|
8
|
+
return;
|
|
9
|
+
if (!Array.isArray(grants) || grants.length > 16)
|
|
10
|
+
throw new Error("mcpServers 需要数组,最多 16 个。");
|
|
11
|
+
const ids = new Set();
|
|
12
|
+
for (const grant of grants) {
|
|
13
|
+
if (!grant || !/^[a-z][a-z0-9_]{0,15}$/.test(grant.id) || ids.has(grant.id))
|
|
14
|
+
throw new Error("MCP 连接 ID 无效或重复。");
|
|
15
|
+
ids.add(grant.id);
|
|
16
|
+
let url;
|
|
17
|
+
try {
|
|
18
|
+
url = new URL(grant.url);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
throw new Error("MCP 地址无效。");
|
|
22
|
+
}
|
|
23
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash)
|
|
24
|
+
throw new Error("MCP 需要固定 HTTP(S) 地址,不含凭据或查询参数。");
|
|
25
|
+
if (grant.credential !== undefined && !/^local-[a-f0-9-]{36}$/.test(grant.credential))
|
|
26
|
+
throw new Error("MCP 凭据引用无效。");
|
|
27
|
+
if (!Array.isArray(grant.tools) || !grant.tools.length || grant.tools.length > 40)
|
|
28
|
+
throw new Error("每个 MCP 连接需明确选择 1–40 个只读工具。");
|
|
29
|
+
const names = new Set();
|
|
30
|
+
for (const tool of grant.tools) {
|
|
31
|
+
if (!/^[a-zA-Z][a-zA-Z0-9_]{0,39}$/.test(tool.name) || names.has(tool.name) || tool.inputSchema?.type !== "object")
|
|
32
|
+
throw new Error("MCP 工具名重复或参数无效。");
|
|
33
|
+
names.add(tool.name);
|
|
34
|
+
compile(tool.inputSchema);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
async function withClient(grant, signal, operation) {
|
|
39
|
+
const secret = readCredential(grant.credential);
|
|
40
|
+
if (grant.credential && !secret)
|
|
41
|
+
throw new Error("MCP 凭据不存在。");
|
|
42
|
+
const client = new Client({ name: "lemma", version: "1.0.0" }, { capabilities: {} });
|
|
43
|
+
const transport = new StreamableHTTPClientTransport(new URL(grant.url), { requestInit: { ...(secret ? { headers: { Authorization: `Bearer ${secret}` } } : {}), redirect: "error" }, fetch: (input, init) => fetch(input, { ...init, redirect: "error", signal: AbortSignal.any([signal, ...(init?.signal ? [init.signal] : [])]) }), reconnectionOptions: { maxRetries: 0, initialReconnectionDelay: 1000, maxReconnectionDelay: 1000, reconnectionDelayGrowFactor: 1 } });
|
|
44
|
+
try {
|
|
45
|
+
await client.connect(transport, { signal, timeout: 20000 });
|
|
46
|
+
return await operation(client);
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
await client.close().catch(() => { });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async function listMcpTools(client, signal) {
|
|
53
|
+
const tools = [];
|
|
54
|
+
let cursor;
|
|
55
|
+
const seen = new Set();
|
|
56
|
+
for (let page = 0; page < 10; page++) {
|
|
57
|
+
const result = await client.listTools(cursor ? { cursor } : {}, { signal, timeout: 20000 });
|
|
58
|
+
for (const tool of result.tools)
|
|
59
|
+
tools.push({ name: tool.name, ...(tool.description ? { description: tool.description } : {}), inputSchema: tool.inputSchema, readOnly: tool.annotations?.readOnlyHint === true });
|
|
60
|
+
if (!result.nextCursor) {
|
|
61
|
+
if (new Set(tools.map((tool) => tool.name)).size !== tools.length)
|
|
62
|
+
throw new Error("MCP 工具目录包含重复名称。");
|
|
63
|
+
return tools;
|
|
64
|
+
}
|
|
65
|
+
if (seen.has(result.nextCursor))
|
|
66
|
+
throw new Error("MCP 工具分页游标重复。");
|
|
67
|
+
seen.add(result.nextCursor);
|
|
68
|
+
cursor = result.nextCursor;
|
|
69
|
+
}
|
|
70
|
+
throw new Error("工具目录过大,请缩小服务范围。");
|
|
71
|
+
}
|
|
72
|
+
export async function discoverMcp(grant, signal = AbortSignal.timeout(30000)) {
|
|
73
|
+
return withClient(grant, signal, (client) => listMcpTools(client, signal));
|
|
74
|
+
}
|
|
75
|
+
const canonicalSchema = (value) => Array.isArray(value) ? value.map(canonicalSchema) : value && typeof value === "object" ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonicalSchema(value[key])])) : value;
|
|
76
|
+
export const mcpToolName = (grant, name) => `mcp_${grant.id}_${name}`;
|
|
77
|
+
export function createMcpTools(grants = []) {
|
|
78
|
+
return grants.flatMap((grant) => grant.tools.map((tool) => defineTool({
|
|
79
|
+
name: mcpToolName(grant, tool.name), description: `${tool.description ?? tool.name}(已授权的 MCP 只读工具;外部返回为资料)`, parameters: unsafe(tool.inputSchema), replay: "safe",
|
|
80
|
+
execute: async (args, _api, context) => {
|
|
81
|
+
const signal = AbortSignal.any([AbortSignal.timeout(30000), ...(context.abortSignal ? [context.abortSignal] : [])]);
|
|
82
|
+
try {
|
|
83
|
+
const result = await withClient(grant, signal, async (client) => {
|
|
84
|
+
const catalog = await listMcpTools(client, signal);
|
|
85
|
+
const actual = catalog.find((entry) => entry.name === tool.name);
|
|
86
|
+
if (!actual?.readOnly || JSON.stringify(canonicalSchema(actual.inputSchema)) !== JSON.stringify(canonicalSchema(tool.inputSchema)))
|
|
87
|
+
throw new Error("MCP 工具定义变化,需要 /mcp refresh 重新授权。");
|
|
88
|
+
return client.callTool({ name: tool.name, arguments: args }, undefined, { signal, timeout: 20000 });
|
|
89
|
+
});
|
|
90
|
+
const content = Array.isArray(result.content) ? result.content : [];
|
|
91
|
+
let text = result.structuredContent ? JSON.stringify(result.structuredContent) : content.filter((block) => block.type === "text").map((block) => block.text ?? "").join("\n");
|
|
92
|
+
const secret = readCredential(grant.credential);
|
|
93
|
+
if (secret)
|
|
94
|
+
text = text.split(secret).join("[REDACTED]");
|
|
95
|
+
return { output: [{ type: "text", text: JSON.stringify({ body: text.slice(0, 8000), truncated: text.length > 8000 }) }], isError: !!result.isError };
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return { output: [{ type: "text", text: "MCP 调用失败、取消、定义变更或超时;请检查连接和 /mcp refresh,未自动重试。" }], isError: true };
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
})));
|
|
102
|
+
}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { normalizeAutonomy, normalizeConfig } from "./config.js";
|
|
2
|
+
import { editSettings } from "./settings.js";
|
|
3
|
+
import { saveCredential } from "./credentials.js";
|
|
4
|
+
import { memberToolNames } from "./api-member.js";
|
|
5
|
+
import { toolSettingsCommand, TOOL_HELP } from "./tool-settings.js";
|
|
6
|
+
import { executionSettingsCommand, EXECUTION_HELP } from "./execution-settings.js";
|
|
7
|
+
import { mcpSettingsCommand, MCP_HELP } from "./mcp-settings.js";
|
|
8
|
+
export const MEMBER_HELP = [
|
|
9
|
+
"/agent add [ID] 添加 API 成员(引导配置)",
|
|
10
|
+
"/agent edit <ID> 修改名称、职责、接口、模型与权限",
|
|
11
|
+
"/agent show <ID> 查看配置与状态(不显示密钥)",
|
|
12
|
+
"/agent enable|disable <ID> 启用或停用成员",
|
|
13
|
+
"/agent model <ID> [模型ID] 修改默认模型",
|
|
14
|
+
"/agent key <ID> 隐藏输入并保存本机凭据",
|
|
15
|
+
"/setup 配置总控模型、API 地址与本机凭据",
|
|
16
|
+
"/agents 查看全部成员;/members 查看已运行的成员会话",
|
|
17
|
+
TOOL_HELP,
|
|
18
|
+
EXECUTION_HELP,
|
|
19
|
+
MCP_HELP,
|
|
20
|
+
].join("\n");
|
|
21
|
+
const RESERVED_IDS = new Set(["constructor", "prototype", "lead", "all", "orchestrator"]);
|
|
22
|
+
export function validateMemberId(id) {
|
|
23
|
+
const trimmed = id.trim();
|
|
24
|
+
if (!/^[a-z][a-z0-9_]{0,47}$/.test(trimmed) || RESERVED_IDS.has(trimmed)) {
|
|
25
|
+
throw new Error("成员 ID 需要小写字母开头,只含小写字母、数字或下划线,且不是系统保留名。");
|
|
26
|
+
}
|
|
27
|
+
return trimmed;
|
|
28
|
+
}
|
|
29
|
+
export function validateApiEndpoint(type, baseUrl) {
|
|
30
|
+
if (type !== "openai-compatible" && type !== "anthropic-compatible")
|
|
31
|
+
throw new Error("协议需要 openai-compatible 或 anthropic-compatible。");
|
|
32
|
+
let url;
|
|
33
|
+
try {
|
|
34
|
+
url = new URL(baseUrl.trim());
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
throw new Error("需要有效的 API 服务地址。");
|
|
38
|
+
}
|
|
39
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password)
|
|
40
|
+
throw new Error("API 地址需要 HTTP(S),且不包含凭据。");
|
|
41
|
+
return { type, baseUrl: baseUrl.trim() };
|
|
42
|
+
}
|
|
43
|
+
export function applyLimitsDraft(draft, current, input) {
|
|
44
|
+
const execution = {
|
|
45
|
+
maxConcurrent: input.maxConcurrent ?? current.execution?.maxConcurrent ?? 8,
|
|
46
|
+
perMember: input.perMember ?? current.execution?.perMember ?? 4,
|
|
47
|
+
perService: input.perService ?? current.execution?.perService ?? 8,
|
|
48
|
+
};
|
|
49
|
+
const perRunUsd = input.perRunUsd === undefined ? current.budget.perRunUsd : input.perRunUsd;
|
|
50
|
+
const reservePerDispatchUsd = input.reservePerDispatchUsd ?? current.budget.reservePerDispatchUsd ?? 0;
|
|
51
|
+
return draft.apply((raw) => {
|
|
52
|
+
raw.execution = execution;
|
|
53
|
+
raw.budget = { ...current.budget, perRunUsd, reservePerDispatchUsd };
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
export function applyOrchestratorDraft(draft, current, input) {
|
|
57
|
+
const api = validateApiEndpoint(input.type, input.baseUrl);
|
|
58
|
+
const modelId = input.modelId.trim();
|
|
59
|
+
if (!modelId)
|
|
60
|
+
throw new Error("模型 ID 不能为空。");
|
|
61
|
+
const secret = input.secret?.trim();
|
|
62
|
+
const local = secret ? saveCredential(secret) : current.orchestrator.credential;
|
|
63
|
+
return draft.apply((raw) => {
|
|
64
|
+
raw.orchestrator = { ...current.orchestrator, ...api, modelId, credential: local, ...(local ? { apiKeyFromClaudeSettings: false, apiKeyEnv: [] } : {}) };
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
export function applyAutonomyDraft(draft, current, input) {
|
|
68
|
+
const autonomy = normalizeAutonomy({
|
|
69
|
+
enabled: input.enabled ?? current.autonomy.enabled,
|
|
70
|
+
maxRepairAttempts: input.maxRepairAttempts ?? current.autonomy.maxRepairAttempts,
|
|
71
|
+
resultMaxChars: input.resultMaxChars ?? current.autonomy.resultMaxChars,
|
|
72
|
+
checks: input.checks ?? current.autonomy.checks,
|
|
73
|
+
});
|
|
74
|
+
return draft.apply((raw) => {
|
|
75
|
+
raw.autonomy = autonomy;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
export function applyApiMemberDraft(draft, path, current, input) {
|
|
79
|
+
const id = validateMemberId(input.id);
|
|
80
|
+
const exists = Object.hasOwn(current.agents, id);
|
|
81
|
+
if (input.mode === "add" && exists)
|
|
82
|
+
throw new Error(`成员 ${id} 已存在,请使用 /agent edit ${id}。`);
|
|
83
|
+
if (input.mode === "edit" && !exists)
|
|
84
|
+
throw new Error(`没有成员 ${id};/agents 查看成员。`);
|
|
85
|
+
const previous = exists ? current.agents[id] : undefined;
|
|
86
|
+
if (previous && !previous.api)
|
|
87
|
+
throw new Error("CLI 成员可用 enable / disable / model 管理;edit 向导用于 API 成员。");
|
|
88
|
+
const name = (input.name ?? previous?.name ?? id).trim() || id;
|
|
89
|
+
const description = (input.description ?? previous?.description ?? name).trim() || name;
|
|
90
|
+
const rawInstructions = input.instructions ?? previous?.instructions ?? "";
|
|
91
|
+
const instructions = rawInstructions === "-" ? "" : rawInstructions;
|
|
92
|
+
const api = validateApiEndpoint(input.type ?? (previous?.api?.type ?? "openai-compatible"), input.baseUrl ?? (previous?.api?.baseUrl ?? ""));
|
|
93
|
+
const modelId = (input.defaultModel ?? previous?.defaultModel ?? "").trim();
|
|
94
|
+
if (!modelId)
|
|
95
|
+
throw new Error("模型 ID 不能为空。");
|
|
96
|
+
const workspace = (input.workspace ?? previous?.workspace ?? "none");
|
|
97
|
+
const rawTools = input.tools ?? (previous?.api ? memberToolNames(previous.api) : []);
|
|
98
|
+
const tools = rawTools.map((value) => value.trim()).filter((value) => value && value !== "none");
|
|
99
|
+
if (tools.some((tool) => !["read", "write", "edit", "bash"].includes(tool)))
|
|
100
|
+
throw new Error("工具权限无效。");
|
|
101
|
+
const bash = tools.includes("bash") ? "allowlist" : "off";
|
|
102
|
+
const bashAllow = bash === "allowlist" ? (input.bashAllow ?? previous?.api?.bashAllow ?? []).map((value) => value.trim()).filter(Boolean) : [];
|
|
103
|
+
const member = {
|
|
104
|
+
enabled: input.enabled ?? previous?.enabled ?? true,
|
|
105
|
+
extraArgs: [],
|
|
106
|
+
timeoutMinutes: 30,
|
|
107
|
+
maxOutputChars: 4000,
|
|
108
|
+
...previous,
|
|
109
|
+
name,
|
|
110
|
+
description,
|
|
111
|
+
instructions,
|
|
112
|
+
workspace,
|
|
113
|
+
defaultModel: modelId,
|
|
114
|
+
models: previous?.models.some((model) => model.id === modelId) ? previous.models : [...previous?.models ?? [], { id: modelId, tier: "standard" }],
|
|
115
|
+
api: { apiKeyEnv: [], ...previous?.api, ...api, tools: tools, bash, bashAllow },
|
|
116
|
+
};
|
|
117
|
+
// Validate everything except optional credentials before writing a local secret.
|
|
118
|
+
normalizeConfig({ ...current, agents: { ...current.agents, [id]: member } }, path);
|
|
119
|
+
const secret = input.secret?.trim();
|
|
120
|
+
member.api.credential = secret ? saveCredential(secret) : previous?.api?.credential;
|
|
121
|
+
if (member.api.credential && secret)
|
|
122
|
+
member.api.apiKeyEnv = [];
|
|
123
|
+
const next = draft.apply((raw) => { raw.agents = { ...raw.agents, [id]: member }; });
|
|
124
|
+
return { next, member, id };
|
|
125
|
+
}
|
|
126
|
+
export function applyQuickMemberDraft(draft, current, id, patch) {
|
|
127
|
+
validateMemberId(id);
|
|
128
|
+
if (!Object.hasOwn(current.agents, id))
|
|
129
|
+
throw new Error(`没有成员 ${id};/agents 查看成员。`);
|
|
130
|
+
const member = structuredClone(current.agents[id]);
|
|
131
|
+
if (patch.enabled !== undefined)
|
|
132
|
+
member.enabled = patch.enabled;
|
|
133
|
+
if (patch.defaultModel !== undefined) {
|
|
134
|
+
const modelId = patch.defaultModel.trim();
|
|
135
|
+
if (!modelId)
|
|
136
|
+
throw new Error("模型 ID 不能为空。");
|
|
137
|
+
member.defaultModel = modelId;
|
|
138
|
+
if (!member.models.some((model) => model.id === modelId))
|
|
139
|
+
member.models.push({ id: modelId, tier: "standard" });
|
|
140
|
+
}
|
|
141
|
+
if (patch.secret !== undefined && patch.secret.trim()) {
|
|
142
|
+
if (!member.api)
|
|
143
|
+
throw new Error("CLI 成员使用自己的登录;密钥配置仅用于 API 成员。");
|
|
144
|
+
member.api.credential = saveCredential(patch.secret.trim());
|
|
145
|
+
member.api.apiKeyEnv = [];
|
|
146
|
+
}
|
|
147
|
+
const next = draft.apply((raw) => { raw.agents = { ...raw.agents, [id]: member }; });
|
|
148
|
+
return { next, member };
|
|
149
|
+
}
|
|
150
|
+
export async function memberSettingsCommand(line, host) {
|
|
151
|
+
if (/^\/mcp(?:\s|$)/.test(line))
|
|
152
|
+
return mcpSettingsCommand(line, host);
|
|
153
|
+
if (/^\/limits(?:\s|$)/.test(line))
|
|
154
|
+
return executionSettingsCommand(line, host);
|
|
155
|
+
if (/^\/tool(?:\s|$)/.test(line))
|
|
156
|
+
return toolSettingsCommand(line, host);
|
|
157
|
+
if (!/^\/(?:agent|setup)(?:\s|$)/.test(line))
|
|
158
|
+
return false;
|
|
159
|
+
const [command, action = "help", suppliedId, ...extra] = line.trim().split(/\s+/);
|
|
160
|
+
if (command === "/agent" && ["help", "list"].includes(action)) {
|
|
161
|
+
host.log(MEMBER_HELP);
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
if (command === "/setup" && line.trim() !== "/setup")
|
|
165
|
+
throw new Error("用法:/setup(按引导配置总控)");
|
|
166
|
+
const current = host.config();
|
|
167
|
+
const exists = (id) => {
|
|
168
|
+
if (!Object.hasOwn(current.agents, id))
|
|
169
|
+
throw new Error(`没有成员 ${id};/agents 查看成员。`);
|
|
170
|
+
return current.agents[id];
|
|
171
|
+
};
|
|
172
|
+
if (command === "/agent" && action === "show") {
|
|
173
|
+
if (!suppliedId || extra.length)
|
|
174
|
+
throw new Error("用法:/agent show <ID>");
|
|
175
|
+
const member = exists(suppliedId);
|
|
176
|
+
host.log(JSON.stringify({ id: suppliedId, name: member.name ?? suppliedId, enabled: member.enabled, description: member.description, instructions: member.instructions, workspace: member.workspace, model: member.defaultModel, models: member.models, api: member.api ? { type: member.api.type, baseUrl: member.api.baseUrl, tools: member.api.tools, apiKeyEnv: member.api.apiKeyEnv, localCredential: !!member.api.credential } : undefined }, null, 2));
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
if (command === "/agent" && !["add", "edit", "enable", "disable", "model", "key"].includes(action))
|
|
180
|
+
throw new Error(MEMBER_HELP);
|
|
181
|
+
await host.assertIdle();
|
|
182
|
+
const draft = editSettings(host.path);
|
|
183
|
+
const ask = async (title, value, secret = false) => {
|
|
184
|
+
const result = await host.question({ title, value, secret });
|
|
185
|
+
return result.trim() || value || "";
|
|
186
|
+
};
|
|
187
|
+
const askEndpoint = async (previous) => validateApiEndpoint(await ask("API 协议:openai-compatible / anthropic-compatible", previous?.type === "builtin" ? "openai-compatible" : previous?.type ?? "openai-compatible"), await ask("API 服务地址", previous?.baseUrl));
|
|
188
|
+
const askSecret = async (hasExisting) => (await host.question({ title: hasExisting ? "API 密钥(隐藏输入;留空保留)" : "API 密钥(隐藏输入;留空使用环境变量)", secret: true })).trim();
|
|
189
|
+
if (command === "/setup") {
|
|
190
|
+
const api = await askEndpoint(current.orchestrator);
|
|
191
|
+
const modelId = await ask("总控模型 ID", current.orchestrator.modelId);
|
|
192
|
+
if (!modelId)
|
|
193
|
+
throw new Error("模型 ID 不能为空。");
|
|
194
|
+
const secret = await askSecret(!!current.orchestrator.credential);
|
|
195
|
+
const next = applyOrchestratorDraft(draft, current, { ...api, modelId, secret });
|
|
196
|
+
await host.commit(draft, next, true);
|
|
197
|
+
host.log("总控配置已保存并生效,历史会话保留。");
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
if (!suppliedId && action !== "add")
|
|
201
|
+
throw new Error(`/agent ${action} 需要成员 ID。`);
|
|
202
|
+
const id = validateMemberId(suppliedId ?? await ask("成员 ID(小写字母、数字、下划线)"));
|
|
203
|
+
if (extra.length && !(action === "model" && extra.length === 1))
|
|
204
|
+
throw new Error("参数过多;密钥请通过 /agent key <ID> 隐藏输入。");
|
|
205
|
+
if (action === "add" && Object.hasOwn(current.agents, id))
|
|
206
|
+
throw new Error(`成员 ${id} 已存在,请使用 /agent edit ${id}。`);
|
|
207
|
+
const previous = action === "add" ? undefined : exists(id);
|
|
208
|
+
let result;
|
|
209
|
+
if (action === "add" || action === "edit") {
|
|
210
|
+
if (previous && !previous.api)
|
|
211
|
+
throw new Error("CLI 成员可用 enable / disable / model 管理;edit 向导用于 API 成员。");
|
|
212
|
+
const name = await ask("成员名称", previous?.name ?? id);
|
|
213
|
+
const description = await ask("成员职责", previous?.description ?? name);
|
|
214
|
+
const instructions = await ask("专属指令(- 清空)", previous?.instructions ?? "");
|
|
215
|
+
const api = await askEndpoint(previous?.api);
|
|
216
|
+
const modelId = await ask("默认模型 ID", previous?.defaultModel);
|
|
217
|
+
if (!modelId)
|
|
218
|
+
throw new Error("模型 ID 不能为空。");
|
|
219
|
+
const workspace = await ask("工作区:none / code", previous?.workspace ?? "none");
|
|
220
|
+
const tools = (await ask("工具权限:none 或 read,write,edit,bash", previous?.api ? memberToolNames(previous.api).join(",") || "none" : "none")).split(",").map((value) => value.trim()).filter((value) => value && value !== "none");
|
|
221
|
+
if (tools.some((tool) => !["read", "write", "edit", "bash"].includes(tool)))
|
|
222
|
+
throw new Error("工具权限无效。");
|
|
223
|
+
const bashAllow = tools.includes("bash") ? (await ask("允许的命令前缀(逗号分隔)", previous?.api?.bashAllow.join(","))).split(",").map((value) => value.trim()).filter(Boolean) : [];
|
|
224
|
+
// Validate everything before asking optional credential so invalid settings fail early.
|
|
225
|
+
const probe = editSettings(host.path);
|
|
226
|
+
applyApiMemberDraft(probe, host.path, current, { mode: action, id, name, description, instructions, workspace, ...api, defaultModel: modelId, tools, bashAllow });
|
|
227
|
+
const secret = await askSecret(!!previous?.api?.credential);
|
|
228
|
+
result = applyApiMemberDraft(draft, host.path, current, { mode: action, id, name, description, instructions, workspace, ...api, defaultModel: modelId, tools, bashAllow, secret });
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
if (action === "key" && !previous.api)
|
|
232
|
+
throw new Error("CLI 成员使用自己的登录;此命令用于 API 成员。");
|
|
233
|
+
const patch = {};
|
|
234
|
+
if (action === "enable" || action === "disable")
|
|
235
|
+
patch.enabled = action === "enable";
|
|
236
|
+
if (action === "model")
|
|
237
|
+
patch.defaultModel = extra[0] ?? await ask("默认模型 ID", previous.defaultModel);
|
|
238
|
+
if (action === "key")
|
|
239
|
+
patch.secret = await askSecret(!!previous.api?.credential);
|
|
240
|
+
result = applyQuickMemberDraft(draft, current, id, patch);
|
|
241
|
+
}
|
|
242
|
+
await host.commit(draft, result.next, false);
|
|
243
|
+
host.log(`成员 ${result.member.name ?? id}(${id})配置已保存并生效;已有会话和结果保留。`);
|
|
244
|
+
return true;
|
|
245
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { AgentDoc, configure, defineDoc, LiveDoc } from "@earendil-works/pi-durable";
|
|
2
|
+
/** Tracks configuration changes only. The chosen model itself lives in Durable's pi.agent. */
|
|
3
|
+
export const ModelSelection = defineDoc({
|
|
4
|
+
kind: "lemma.model-selection", version: 1, scope: "session", initial: () => ({}), checkpointWhen: () => false,
|
|
5
|
+
});
|
|
6
|
+
export function controllerModels(models, provider) {
|
|
7
|
+
return models.getModels(provider);
|
|
8
|
+
}
|
|
9
|
+
export async function selectControllerModel(harness, conversation, models, provider, selected, context) {
|
|
10
|
+
if (selected.provider !== provider || !models.getModel(provider, selected.id))
|
|
11
|
+
throw new Error("模型不在当前总控配置的目录中。");
|
|
12
|
+
await harness.commit(async (tx) => {
|
|
13
|
+
const record = await tx.conversation(conversation.id);
|
|
14
|
+
const live = await tx.doc(LiveDoc, conversation.id);
|
|
15
|
+
if (record?.owner)
|
|
16
|
+
throw new Error("成员子对话由原任务管理,不能在终端切换模型。");
|
|
17
|
+
if (live.run)
|
|
18
|
+
throw new Error("总控运行中,请等待本轮结束再切换模型。");
|
|
19
|
+
await configure(tx, conversation.id, { model: { provider, modelId: selected.id } });
|
|
20
|
+
}, context);
|
|
21
|
+
}
|
|
22
|
+
export async function restoreControllerModel(harness, root, models, configured, context) {
|
|
23
|
+
await harness.commit(async (tx) => {
|
|
24
|
+
const preference = await tx.doc(ModelSelection);
|
|
25
|
+
const agent = await tx.doc(AgentDoc, root.id);
|
|
26
|
+
const signature = `${configured.provider}/${configured.modelId}`;
|
|
27
|
+
const stored = agent.model;
|
|
28
|
+
if (preference.configuredDefault !== signature || !stored || stored.provider !== configured.provider || !models.getModel(stored.provider, stored.modelId))
|
|
29
|
+
await configure(tx, root.id, { model: configured });
|
|
30
|
+
preference.configuredDefault = signature;
|
|
31
|
+
}, context);
|
|
32
|
+
}
|
|
33
|
+
/** Adapter for the four public catalog methods consumed by the pinned upstream selector.
|
|
34
|
+
* It delegates to the same pi-ai Models that Harness uses. No credentials, execution or second runtime. */
|
|
35
|
+
export async function nativeModelCatalog(models, provider, allowNetwork = false) {
|
|
36
|
+
let snapshot = await models.getAvailable(provider);
|
|
37
|
+
return {
|
|
38
|
+
getAvailableSnapshot: () => snapshot,
|
|
39
|
+
getModel: (owner, id) => owner === provider ? models.getModel(owner, id) : undefined,
|
|
40
|
+
getError: () => undefined,
|
|
41
|
+
async refresh(options) {
|
|
42
|
+
const result = await models.refresh({ ...options, allowNetwork, providers: [provider] });
|
|
43
|
+
if (!result.aborted)
|
|
44
|
+
snapshot = await models.getAvailable(provider, { signal: options?.signal });
|
|
45
|
+
return result;
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
package/dist/models.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// 总调度自己用的"大脑"模型。CLI agent 走各自的登录;总调度需要一个 API 模型来做拆解和汇总。
|
|
2
|
+
import { createModels, createProvider } from "@earendil-works/pi-ai";
|
|
3
|
+
import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messages.lazy";
|
|
4
|
+
import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
|
|
5
|
+
import { builtinModels } from "@earendil-works/pi-ai/providers/all";
|
|
6
|
+
import { claudeSettingsEnv } from "./config.js";
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { readFileSync, mkdirSync, writeFileSync, renameSync } from "node:fs";
|
|
9
|
+
import { dirname } from "node:path";
|
|
10
|
+
import { readCredential } from "./credentials.js";
|
|
11
|
+
export function resolveOrchestratorKey(config) {
|
|
12
|
+
for (const name of config.apiKeyEnv ?? []) {
|
|
13
|
+
const value = process.env[name];
|
|
14
|
+
if (value)
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
const local = readCredential(config.credential);
|
|
18
|
+
if (local)
|
|
19
|
+
return local;
|
|
20
|
+
if (config.apiKeyFromClaudeSettings)
|
|
21
|
+
return claudeSettingsEnv().token;
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
/** 密钥从哪里来(不返回密钥) */
|
|
25
|
+
function keySource(config) {
|
|
26
|
+
if (config.type === "builtin")
|
|
27
|
+
return `${config.provider ?? "?"} 的标准环境变量`;
|
|
28
|
+
for (const name of config.apiKeyEnv ?? [])
|
|
29
|
+
if (process.env[name])
|
|
30
|
+
return `环境变量 ${name}`;
|
|
31
|
+
if (readCredential(config.credential))
|
|
32
|
+
return "本机凭据文件";
|
|
33
|
+
if (config.apiKeyFromClaudeSettings) {
|
|
34
|
+
const claude = claudeSettingsEnv();
|
|
35
|
+
if (claude.token)
|
|
36
|
+
return "~/.claude/settings.json(与 Claude CLI 共用)";
|
|
37
|
+
if (claude.error)
|
|
38
|
+
return `~/.claude/settings.json 解析失败:${claude.error}`;
|
|
39
|
+
}
|
|
40
|
+
return "未找到密钥";
|
|
41
|
+
}
|
|
42
|
+
export function orchestratorKeyWarning(config) {
|
|
43
|
+
if (config.type === "builtin" || resolveOrchestratorKey(config))
|
|
44
|
+
return undefined;
|
|
45
|
+
if (config.apiKeyFromClaudeSettings) {
|
|
46
|
+
const claude = claudeSettingsEnv();
|
|
47
|
+
if (claude.error)
|
|
48
|
+
return `总控无法从 ~/.claude/settings.json 读取密钥(JSON 语法错误:${claude.error});请修复该文件或运行 /setup 配置总控凭据。`;
|
|
49
|
+
}
|
|
50
|
+
return "总控模型尚未配置 API 密钥,发消息会报 Provider is not configured;请运行 /setup 或在网页「配置 → 编辑总控」填写。";
|
|
51
|
+
}
|
|
52
|
+
export function createOrchestratorModel(config, catalogPath) {
|
|
53
|
+
if (config.type === "builtin") {
|
|
54
|
+
if (!config.provider)
|
|
55
|
+
throw new Error("orchestrator.type=builtin 时必须填写 orchestrator.provider(例如 anthropic、openai、google)");
|
|
56
|
+
const models = builtinModels();
|
|
57
|
+
return {
|
|
58
|
+
models,
|
|
59
|
+
ref: { provider: config.provider, modelId: config.modelId },
|
|
60
|
+
describe: `${config.provider}/${config.modelId}`,
|
|
61
|
+
info: { type: config.type, modelId: config.modelId, keySource: keySource(config) },
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const id = "orchestrator";
|
|
65
|
+
const api = config.type === "anthropic-compatible" ? "anthropic-messages" : "openai-completions";
|
|
66
|
+
const baseUrl = config.baseUrl ??
|
|
67
|
+
(config.type === "anthropic-compatible" ? (claudeSettingsEnv().baseUrl ?? "https://api.anthropic.com") : undefined);
|
|
68
|
+
if (!baseUrl)
|
|
69
|
+
throw new Error("orchestrator.type=openai-compatible 时必须填写 orchestrator.baseUrl");
|
|
70
|
+
const source = createHash("sha256").update(`${config.type}:${baseUrl}`).digest("hex");
|
|
71
|
+
let cached = [];
|
|
72
|
+
if (config.discoverModels && catalogPath)
|
|
73
|
+
try {
|
|
74
|
+
const data = JSON.parse(readFileSync(catalogPath, "utf8"));
|
|
75
|
+
if (data.source === source && Array.isArray(data.ids))
|
|
76
|
+
cached = data.ids.filter((id) => typeof id === "string" && !!id.trim() && id.length <= 200).slice(0, 1000);
|
|
77
|
+
}
|
|
78
|
+
catch { /* 初次发现或缓存损坏时使用显式配置。 */ }
|
|
79
|
+
const model = {
|
|
80
|
+
id: config.modelId,
|
|
81
|
+
name: config.modelId,
|
|
82
|
+
api,
|
|
83
|
+
provider: id,
|
|
84
|
+
baseUrl,
|
|
85
|
+
reasoning: false,
|
|
86
|
+
input: ["text"],
|
|
87
|
+
// 中转站模型没有内置定价:配了 orchestrator.price 才能算出总调度的花费
|
|
88
|
+
cost: {
|
|
89
|
+
input: config.price?.input ?? 0,
|
|
90
|
+
output: config.price?.output ?? 0,
|
|
91
|
+
cacheRead: config.price?.cacheRead ?? config.price?.input ?? 0,
|
|
92
|
+
cacheWrite: config.price?.input ?? 0,
|
|
93
|
+
},
|
|
94
|
+
contextWindow: config.contextWindow ?? 200_000,
|
|
95
|
+
maxTokens: config.maxTokens ?? 16_000,
|
|
96
|
+
};
|
|
97
|
+
const provider = createProvider({
|
|
98
|
+
id,
|
|
99
|
+
name: "Orchestrator",
|
|
100
|
+
baseUrl,
|
|
101
|
+
auth: {
|
|
102
|
+
apiKey: {
|
|
103
|
+
name: "Orchestrator API key",
|
|
104
|
+
resolve: async () => {
|
|
105
|
+
const key = resolveOrchestratorKey(config);
|
|
106
|
+
return key ? { auth: { apiKey: key }, source: "Lemma config" } : undefined;
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
models: [...new Set([config.modelId, ...(config.modelIds ?? []), ...cached])].map((id) => ({ ...model, id, name: id })),
|
|
111
|
+
fetchModels: config.discoverModels ? async (context) => {
|
|
112
|
+
const key = resolveOrchestratorKey(config);
|
|
113
|
+
const endpoint = new URL(baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`);
|
|
114
|
+
const prefix = endpoint.pathname.endsWith("/") ? endpoint.pathname.slice(0, -1) : endpoint.pathname;
|
|
115
|
+
endpoint.pathname = `${prefix}${prefix.endsWith("/v1") ? "" : "/v1"}/models`;
|
|
116
|
+
const response = await fetch(endpoint, { redirect: "error", signal: AbortSignal.any([context.signal, AbortSignal.timeout(8000)]),
|
|
117
|
+
headers: config.type === "anthropic-compatible" ? { "x-api-key": key ?? "", "anthropic-version": "2023-06-01" } : { Authorization: `Bearer ${key ?? ""}` },
|
|
118
|
+
});
|
|
119
|
+
if (!response.ok)
|
|
120
|
+
throw new Error(`模型目录返回 HTTP ${response.status};继续使用已配置模型。`);
|
|
121
|
+
const body = await response.json();
|
|
122
|
+
if (!Array.isArray(body.data))
|
|
123
|
+
throw new Error("服务未返回标准模型目录;继续使用已配置模型。");
|
|
124
|
+
const discovered = body.data.filter((item) => item && typeof item.id === "string" && item.id.trim() && item.id.length <= 200).slice(0, 1000);
|
|
125
|
+
if (catalogPath) {
|
|
126
|
+
mkdirSync(dirname(catalogPath), { recursive: true });
|
|
127
|
+
writeFileSync(`${catalogPath}.tmp`, JSON.stringify({ source, checkedAt: Date.now(), ids: discovered.map((item) => item.id) }, null, 2));
|
|
128
|
+
renameSync(`${catalogPath}.tmp`, catalogPath);
|
|
129
|
+
}
|
|
130
|
+
return discovered.map((item) => ({
|
|
131
|
+
...model, id: item.id, name: typeof item.display_name === "string" ? item.display_name : item.id,
|
|
132
|
+
}));
|
|
133
|
+
} : undefined,
|
|
134
|
+
api: config.type === "anthropic-compatible" ? anthropicMessagesApi() : openAICompletionsApi(),
|
|
135
|
+
});
|
|
136
|
+
const models = createModels();
|
|
137
|
+
models.setProvider(provider);
|
|
138
|
+
const host = new URL(baseUrl).host;
|
|
139
|
+
return {
|
|
140
|
+
models,
|
|
141
|
+
ref: { provider: id, modelId: config.modelId },
|
|
142
|
+
describe: `${config.type} ${host} / ${config.modelId}`,
|
|
143
|
+
info: { type: config.type, modelId: config.modelId, host, keySource: keySource(config) },
|
|
144
|
+
};
|
|
145
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// UI-only projections. Never create a coding-agent SessionManager or AgentSession.
|
|
2
|
+
import { SessionSelectorComponent, TreeSelectorComponent } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { getKeybindings } from "@earendil-works/pi-tui";
|
|
4
|
+
import { cleanText, safeNativeComponent } from "./native-terminal-components.js";
|
|
5
|
+
export function nativeSessions(items, select, cancel, render) {
|
|
6
|
+
const project = () => items.map((item) => ({
|
|
7
|
+
path: item.id, id: item.id, cwd: cleanText(item.workdir ?? ""), name: cleanText(item.title),
|
|
8
|
+
created: new Date(item.createdAt ?? item.lastAt ?? 0), modified: new Date(item.lastAt ?? item.createdAt ?? 0), messageCount: item.messageCount ?? 0,
|
|
9
|
+
firstMessage: cleanText(`${item.id} ${item.detail ?? ""}`), allMessagesText: cleanText(`${item.id} ${item.detail ?? ""} ${item.searchText ?? ""}`),
|
|
10
|
+
parentSessionPath: item.parentId,
|
|
11
|
+
}));
|
|
12
|
+
// Upstream only needs matches() here; use the application's existing key map.
|
|
13
|
+
const keybindings = getKeybindings();
|
|
14
|
+
const selector = safeNativeComponent(new SessionSelectorComponent(async () => project(), async () => project(), select, cancel, cancel, render, { keybindings, showRenameHint: false }, items.find((item) => item.current)?.id), true);
|
|
15
|
+
// The upstream default deletes JSONL files. Lemma selectors are navigation-only.
|
|
16
|
+
selector.getSessionList().onDeleteSession = undefined;
|
|
17
|
+
return selector;
|
|
18
|
+
}
|
|
19
|
+
export function conversationTree(items) {
|
|
20
|
+
const parents = new Map(items.map((item) => [item.id, item.parentId]));
|
|
21
|
+
const nodes = new Map(items.map((item) => [item.id, {
|
|
22
|
+
entry: { type: "session_info", id: item.id, parentId: item.parentId ?? null, timestamp: new Date(item.createdAt ?? 0).toISOString(), name: cleanText(`${item.title} · ${item.id}`) },
|
|
23
|
+
label: cleanText(item.detail ?? ""), children: [],
|
|
24
|
+
}]));
|
|
25
|
+
const roots = [];
|
|
26
|
+
for (const item of items) {
|
|
27
|
+
const node = nodes.get(item.id);
|
|
28
|
+
const seen = new Set([item.id]);
|
|
29
|
+
let parent = item.parentId;
|
|
30
|
+
while (parent && !seen.has(parent)) {
|
|
31
|
+
seen.add(parent);
|
|
32
|
+
parent = parents.get(parent);
|
|
33
|
+
}
|
|
34
|
+
if (item.parentId && nodes.has(item.parentId) && !parent)
|
|
35
|
+
nodes.get(item.parentId).children.push(node);
|
|
36
|
+
else {
|
|
37
|
+
node.entry.parentId = null;
|
|
38
|
+
roots.push(node);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return roots;
|
|
42
|
+
}
|
|
43
|
+
export function nativeConversationTree(items, height, select, cancel) {
|
|
44
|
+
return safeNativeComponent(new TreeSelectorComponent(conversationTree(items), items.find((item) => item.current)?.id ?? null, height, select, cancel, undefined, undefined, "all"), true);
|
|
45
|
+
}
|