@tothemax/tasking 0.0.0-stage → 0.6.16
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/LICENSE +21 -0
- package/README.md +121 -2
- package/README.zh-CN.md +122 -0
- package/assets/skills/install-glab/SKILL.md +70 -0
- package/assets/skills/land/SKILL.md +63 -0
- package/assets/skills/land/land_watch.py +312 -0
- package/assets/skills/openspec-archive-change/SKILL.md +114 -0
- package/assets/skills/opsx-grill-with-docs/SKILL.md +193 -0
- package/assets/skills/opsx-implement/SKILL.md +258 -0
- package/assets/skills/opsx-propose-with-tdd/SKILL.md +271 -0
- package/assets/workflows/WORKFLOW.code-mr.en.md.example +345 -0
- package/assets/workflows/WORKFLOW.code-mr.md.example +339 -0
- package/assets/workflows/WORKFLOW.feishu-direct.en.md.example +267 -0
- package/assets/workflows/WORKFLOW.feishu-direct.md.example +258 -0
- package/assets/workflows/WORKFLOW.grill-openspec.en.md.example +362 -0
- package/assets/workflows/WORKFLOW.grill-openspec.md.example +356 -0
- package/assets/workflows/WORKFLOW.minimal.en.md.example +296 -0
- package/assets/workflows/WORKFLOW.minimal.md.example +289 -0
- package/dist/adapters/feishu/events.d.ts +55 -0
- package/dist/adapters/feishu/events.d.ts.map +1 -0
- package/dist/adapters/feishu/events.js +184 -0
- package/dist/adapters/feishu/events.js.map +1 -0
- package/dist/adapters/feishu/index.d.ts +2 -0
- package/dist/adapters/feishu/index.d.ts.map +1 -0
- package/dist/adapters/feishu/index.js +2 -0
- package/dist/adapters/feishu/index.js.map +1 -0
- package/dist/adapters/feishu/probe.d.ts +31 -0
- package/dist/adapters/feishu/probe.d.ts.map +1 -0
- package/dist/adapters/feishu/probe.js +179 -0
- package/dist/adapters/feishu/probe.js.map +1 -0
- package/dist/adapters/feishu/source.d.ts +124 -0
- package/dist/adapters/feishu/source.d.ts.map +1 -0
- package/dist/adapters/feishu/source.js +715 -0
- package/dist/adapters/feishu/source.js.map +1 -0
- package/dist/adapters/jira/index.d.ts +2 -0
- package/dist/adapters/jira/index.d.ts.map +1 -0
- package/dist/adapters/jira/index.js +2 -0
- package/dist/adapters/jira/index.js.map +1 -0
- package/dist/adapters/jira/tracker.d.ts +63 -0
- package/dist/adapters/jira/tracker.d.ts.map +1 -0
- package/dist/adapters/jira/tracker.js +402 -0
- package/dist/adapters/jira/tracker.js.map +1 -0
- package/dist/bridge/binding-store.d.ts +93 -0
- package/dist/bridge/binding-store.d.ts.map +1 -0
- package/dist/bridge/binding-store.js +365 -0
- package/dist/bridge/binding-store.js.map +1 -0
- package/dist/bridge/commands.d.ts +45 -0
- package/dist/bridge/commands.d.ts.map +1 -0
- package/dist/bridge/commands.js +197 -0
- package/dist/bridge/commands.js.map +1 -0
- package/dist/bridge/comment-bridge.d.ts +116 -0
- package/dist/bridge/comment-bridge.d.ts.map +1 -0
- package/dist/bridge/comment-bridge.js +1473 -0
- package/dist/bridge/comment-bridge.js.map +1 -0
- package/dist/cli/daemon-info.d.ts +17 -0
- package/dist/cli/daemon-info.d.ts.map +1 -0
- package/dist/cli/daemon-info.js +64 -0
- package/dist/cli/daemon-info.js.map +1 -0
- package/dist/cli/daemon.d.ts +27 -0
- package/dist/cli/daemon.d.ts.map +1 -0
- package/dist/cli/daemon.js +77 -0
- package/dist/cli/daemon.js.map +1 -0
- package/dist/cli/doctor.d.ts +7 -0
- package/dist/cli/doctor.d.ts.map +1 -0
- package/dist/cli/doctor.js +156 -0
- package/dist/cli/doctor.js.map +1 -0
- package/dist/cli/event-channel.d.ts +16 -0
- package/dist/cli/event-channel.d.ts.map +1 -0
- package/dist/cli/event-channel.js +51 -0
- package/dist/cli/event-channel.js.map +1 -0
- package/dist/cli/help.d.ts +3 -0
- package/dist/cli/help.d.ts.map +1 -0
- package/dist/cli/help.js +155 -0
- package/dist/cli/help.js.map +1 -0
- package/dist/cli/index.d.ts +3 -0
- package/dist/cli/index.d.ts.map +1 -0
- package/dist/cli/index.js +774 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/cli/init.d.ts +64 -0
- package/dist/cli/init.d.ts.map +1 -0
- package/dist/cli/init.js +1296 -0
- package/dist/cli/init.js.map +1 -0
- package/dist/cli/instance-lock.d.ts +13 -0
- package/dist/cli/instance-lock.d.ts.map +1 -0
- package/dist/cli/instance-lock.js +53 -0
- package/dist/cli/instance-lock.js.map +1 -0
- package/dist/cli/prompts.d.ts +13 -0
- package/dist/cli/prompts.d.ts.map +1 -0
- package/dist/cli/prompts.js +26 -0
- package/dist/cli/prompts.js.map +1 -0
- package/dist/cli/style.d.ts +26 -0
- package/dist/cli/style.d.ts.map +1 -0
- package/dist/cli/style.js +58 -0
- package/dist/cli/style.js.map +1 -0
- package/dist/cli/tui-helpers.d.ts +5 -0
- package/dist/cli/tui-helpers.d.ts.map +1 -0
- package/dist/cli/tui-helpers.js +124 -0
- package/dist/cli/tui-helpers.js.map +1 -0
- package/dist/cli/workflow-path.d.ts +12 -0
- package/dist/cli/workflow-path.d.ts.map +1 -0
- package/dist/cli/workflow-path.js +37 -0
- package/dist/cli/workflow-path.js.map +1 -0
- package/dist/config/config-types.d.ts +180 -0
- package/dist/config/config-types.d.ts.map +1 -0
- package/dist/config/config-types.js +71 -0
- package/dist/config/config-types.js.map +1 -0
- package/dist/config/dotenv.d.ts +2 -0
- package/dist/config/dotenv.d.ts.map +1 -0
- package/dist/config/dotenv.js +10 -0
- package/dist/config/dotenv.js.map +1 -0
- package/dist/config/index.d.ts +6 -0
- package/dist/config/index.d.ts.map +1 -0
- package/dist/config/index.js +6 -0
- package/dist/config/index.js.map +1 -0
- package/dist/config/loader.d.ts +5 -0
- package/dist/config/loader.d.ts.map +1 -0
- package/dist/config/loader.js +304 -0
- package/dist/config/loader.js.map +1 -0
- package/dist/config/manager.d.ts +31 -0
- package/dist/config/manager.d.ts.map +1 -0
- package/dist/config/manager.js +110 -0
- package/dist/config/manager.js.map +1 -0
- package/dist/config/resolver.d.ts +6 -0
- package/dist/config/resolver.d.ts.map +1 -0
- package/dist/config/resolver.js +267 -0
- package/dist/config/resolver.js.map +1 -0
- package/dist/config/validator.d.ts +9 -0
- package/dist/config/validator.d.ts.map +1 -0
- package/dist/config/validator.js +70 -0
- package/dist/config/validator.js.map +1 -0
- package/dist/direct/card.d.ts +49 -0
- package/dist/direct/card.d.ts.map +1 -0
- package/dist/direct/card.js +274 -0
- package/dist/direct/card.js.map +1 -0
- package/dist/direct/command.d.ts +12 -0
- package/dist/direct/command.d.ts.map +1 -0
- package/dist/direct/command.js +23 -0
- package/dist/direct/command.js.map +1 -0
- package/dist/direct/manager.d.ts +159 -0
- package/dist/direct/manager.d.ts.map +1 -0
- package/dist/direct/manager.js +1862 -0
- package/dist/direct/manager.js.map +1 -0
- package/dist/mcp/inject.d.ts +5 -0
- package/dist/mcp/inject.d.ts.map +1 -0
- package/dist/mcp/inject.js +51 -0
- package/dist/mcp/inject.js.map +1 -0
- package/dist/mcp/jira-server.d.ts +29 -0
- package/dist/mcp/jira-server.d.ts.map +1 -0
- package/dist/mcp/jira-server.js +288 -0
- package/dist/mcp/jira-server.js.map +1 -0
- package/dist/observability/activity-store.d.ts +29 -0
- package/dist/observability/activity-store.d.ts.map +1 -0
- package/dist/observability/activity-store.js +32 -0
- package/dist/observability/activity-store.js.map +1 -0
- package/dist/observability/config-view.d.ts +19 -0
- package/dist/observability/config-view.d.ts.map +1 -0
- package/dist/observability/config-view.js +61 -0
- package/dist/observability/config-view.js.map +1 -0
- package/dist/observability/http-dashboard.d.ts +36 -0
- package/dist/observability/http-dashboard.d.ts.map +1 -0
- package/dist/observability/http-dashboard.js +297 -0
- package/dist/observability/http-dashboard.js.map +1 -0
- package/dist/observability/log-buffer.d.ts +21 -0
- package/dist/observability/log-buffer.d.ts.map +1 -0
- package/dist/observability/log-buffer.js +69 -0
- package/dist/observability/log-buffer.js.map +1 -0
- package/dist/observability/logger.d.ts +37 -0
- package/dist/observability/logger.d.ts.map +1 -0
- package/dist/observability/logger.js +114 -0
- package/dist/observability/logger.js.map +1 -0
- package/dist/observability/snapshot.d.ts +11 -0
- package/dist/observability/snapshot.d.ts.map +1 -0
- package/dist/observability/snapshot.js +59 -0
- package/dist/observability/snapshot.js.map +1 -0
- package/dist/observability/terminal-dashboard.d.ts +155 -0
- package/dist/observability/terminal-dashboard.d.ts.map +1 -0
- package/dist/observability/terminal-dashboard.js +1598 -0
- package/dist/observability/terminal-dashboard.js.map +1 -0
- package/dist/observability/wrap.d.ts +4 -0
- package/dist/observability/wrap.d.ts.map +1 -0
- package/dist/observability/wrap.js +80 -0
- package/dist/observability/wrap.js.map +1 -0
- package/dist/scheduler/index.d.ts +2 -0
- package/dist/scheduler/index.d.ts.map +1 -0
- package/dist/scheduler/index.js +2 -0
- package/dist/scheduler/index.js.map +1 -0
- package/dist/scheduler/scheduler.d.ts +52 -0
- package/dist/scheduler/scheduler.d.ts.map +1 -0
- package/dist/scheduler/scheduler.js +535 -0
- package/dist/scheduler/scheduler.js.map +1 -0
- package/dist/shared/agent-resolver.d.ts +11 -0
- package/dist/shared/agent-resolver.d.ts.map +1 -0
- package/dist/shared/agent-resolver.js +20 -0
- package/dist/shared/agent-resolver.js.map +1 -0
- package/dist/shared/errors.d.ts +14 -0
- package/dist/shared/errors.d.ts.map +1 -0
- package/dist/shared/errors.js +24 -0
- package/dist/shared/errors.js.map +1 -0
- package/dist/shared/index.d.ts +4 -0
- package/dist/shared/index.d.ts.map +1 -0
- package/dist/shared/index.js +4 -0
- package/dist/shared/index.js.map +1 -0
- package/dist/shared/info-card.d.ts +24 -0
- package/dist/shared/info-card.d.ts.map +1 -0
- package/dist/shared/info-card.js +46 -0
- package/dist/shared/info-card.js.map +1 -0
- package/dist/shared/types.d.ts +148 -0
- package/dist/shared/types.d.ts.map +1 -0
- package/dist/shared/types.js +15 -0
- package/dist/shared/types.js.map +1 -0
- package/dist/translate/card.d.ts +2 -0
- package/dist/translate/card.d.ts.map +1 -0
- package/dist/translate/card.js +17 -0
- package/dist/translate/card.js.map +1 -0
- package/dist/translate/dict.d.ts +7 -0
- package/dist/translate/dict.d.ts.map +1 -0
- package/dist/translate/dict.js +895 -0
- package/dist/translate/dict.js.map +1 -0
- package/dist/translate/locale.d.ts +8 -0
- package/dist/translate/locale.d.ts.map +1 -0
- package/dist/translate/locale.js +75 -0
- package/dist/translate/locale.js.map +1 -0
- package/dist/translate/normalize.d.ts +4 -0
- package/dist/translate/normalize.d.ts.map +1 -0
- package/dist/translate/normalize.js +38 -0
- package/dist/translate/normalize.js.map +1 -0
- package/dist/translate/output.d.ts +3 -0
- package/dist/translate/output.d.ts.map +1 -0
- package/dist/translate/output.js +16 -0
- package/dist/translate/output.js.map +1 -0
- package/dist/worker/prompt.d.ts +11 -0
- package/dist/worker/prompt.d.ts.map +1 -0
- package/dist/worker/prompt.js +153 -0
- package/dist/worker/prompt.js.map +1 -0
- package/dist/worker/runner.d.ts +101 -0
- package/dist/worker/runner.d.ts.map +1 -0
- package/dist/worker/runner.js +448 -0
- package/dist/worker/runner.js.map +1 -0
- package/dist/workspace/index.d.ts +2 -0
- package/dist/workspace/index.d.ts.map +1 -0
- package/dist/workspace/index.js +2 -0
- package/dist/workspace/index.js.map +1 -0
- package/dist/workspace/manager.d.ts +37 -0
- package/dist/workspace/manager.d.ts.map +1 -0
- package/dist/workspace/manager.js +157 -0
- package/dist/workspace/manager.js.map +1 -0
- package/package.json +70 -4
|
@@ -0,0 +1,1862 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { basename, extname, join } from "node:path";
|
|
3
|
+
import { toSecondsStr, } from "../adapters/feishu/source.js";
|
|
4
|
+
import { parseChat } from "../bridge/commands.js";
|
|
5
|
+
import { toTaskingError } from "../shared/errors.js";
|
|
6
|
+
import { runDefaultSubprocess, } from "../worker/runner.js";
|
|
7
|
+
import { CARD_BUDGET_BYTES, buildCompletionCard, buildInfoCard, buildTurnCard, formatTokens, isFailed, toolSummary, } from "./card.js";
|
|
8
|
+
import { buildDirectCommand } from "./command.js";
|
|
9
|
+
const MAX_MESSAGE_CHARS = 3500;
|
|
10
|
+
const TTL_SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
|
11
|
+
const CARD_UPDATE_INTERVAL_MS = 1500;
|
|
12
|
+
const CARD_ACTION_DEDUP_MS = 2 * 60 * 1000;
|
|
13
|
+
const MEMBER_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
14
|
+
const CARD_HEARTBEAT_MS = 5000;
|
|
15
|
+
const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
|
|
16
|
+
const COLLECT_IDLE_TIMEOUT_MS = 10 * 60 * 1000;
|
|
17
|
+
const FULL_DETAIL_MAX_BYTES = 1_000_000;
|
|
18
|
+
const FULL_TEXT_LIMIT_BYTES = 140_000;
|
|
19
|
+
import { translate } from "../translate/locale.js";
|
|
20
|
+
export function isDirectEnabled(config) {
|
|
21
|
+
return config.feishu.enabled && config.feishu.direct.enabled;
|
|
22
|
+
}
|
|
23
|
+
const defaultSpawn = (cmd, cwd, timeout, inactivityTimeout, signal, onEvent) => runDefaultSubprocess(cmd, cwd, timeout, inactivityTimeout, signal, undefined, onEvent);
|
|
24
|
+
export class DirectSessionManager {
|
|
25
|
+
deps;
|
|
26
|
+
runtime = new Map();
|
|
27
|
+
aggregate = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
|
|
28
|
+
terminalHintedRoots = new Set();
|
|
29
|
+
cardActionSeen = new Map();
|
|
30
|
+
memberCache = new Map();
|
|
31
|
+
pendingWork = 0;
|
|
32
|
+
dirSlots = new Map();
|
|
33
|
+
running = false;
|
|
34
|
+
halted = false;
|
|
35
|
+
ttlTimer = null;
|
|
36
|
+
activeTurns = 0;
|
|
37
|
+
waiters = [];
|
|
38
|
+
constructor(deps) {
|
|
39
|
+
this.deps = deps;
|
|
40
|
+
}
|
|
41
|
+
start() {
|
|
42
|
+
if (this.running)
|
|
43
|
+
return;
|
|
44
|
+
this.running = true;
|
|
45
|
+
this.halted = false;
|
|
46
|
+
this.ttlTimer = setInterval(() => this.expireIdle(), TTL_SWEEP_INTERVAL_MS);
|
|
47
|
+
this.ttlTimer.unref?.();
|
|
48
|
+
}
|
|
49
|
+
stop() {
|
|
50
|
+
this.running = false;
|
|
51
|
+
this.halted = true;
|
|
52
|
+
if (this.ttlTimer) {
|
|
53
|
+
clearInterval(this.ttlTimer);
|
|
54
|
+
this.ttlTimer = null;
|
|
55
|
+
}
|
|
56
|
+
for (const rt of this.runtime.values()) {
|
|
57
|
+
this.stopHeartbeat(rt);
|
|
58
|
+
if (rt.collectTimer) {
|
|
59
|
+
clearTimeout(rt.collectTimer);
|
|
60
|
+
rt.collectTimer = null;
|
|
61
|
+
}
|
|
62
|
+
if (rt.flushTimer) {
|
|
63
|
+
clearTimeout(rt.flushTimer);
|
|
64
|
+
rt.flushTimer = null;
|
|
65
|
+
}
|
|
66
|
+
rt.queue = [];
|
|
67
|
+
rt.collect = null;
|
|
68
|
+
if (rt.turnInFlight) {
|
|
69
|
+
rt.stopRequested = true;
|
|
70
|
+
rt.abort?.abort();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
get isRunning() {
|
|
75
|
+
return this.running;
|
|
76
|
+
}
|
|
77
|
+
async whenIdle() {
|
|
78
|
+
for (;;) {
|
|
79
|
+
const busy = this.activeTurns > 0 || this.hasQueuedWork();
|
|
80
|
+
if (!busy)
|
|
81
|
+
return;
|
|
82
|
+
await new Promise((r) => setImmediate(r));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
hasQueuedWork() {
|
|
86
|
+
if (this.pendingWork > 0)
|
|
87
|
+
return true;
|
|
88
|
+
for (const rt of this.runtime.values()) {
|
|
89
|
+
if (rt.turnInFlight || rt.queue.length > 0 || rt.flushTimer !== null)
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
async handleCardAction(action) {
|
|
95
|
+
const value = (action.value ?? {});
|
|
96
|
+
const rootId = typeof value.root_id === "string" ? value.root_id : "";
|
|
97
|
+
const name = typeof value.action === "string" ? value.action : "";
|
|
98
|
+
const turn = typeof value.turn === "number" ? value.turn : null;
|
|
99
|
+
if (rootId === "" || name === "")
|
|
100
|
+
return undefined;
|
|
101
|
+
const idempotent = name.startsWith("auto_") || name.startsWith("collect_");
|
|
102
|
+
if (!idempotent && !this.claimCardAction(action)) {
|
|
103
|
+
this.deps.logger.debug("direct card action deduplicated", {
|
|
104
|
+
root_id: rootId,
|
|
105
|
+
action: name,
|
|
106
|
+
turn,
|
|
107
|
+
});
|
|
108
|
+
return { toast: { type: "info", content: "该操作已处理" } };
|
|
109
|
+
}
|
|
110
|
+
const session = this.deps.store.getDirectSession(rootId);
|
|
111
|
+
if (!session)
|
|
112
|
+
return { toast: { type: "error", content: "会话不存在或已清理" } };
|
|
113
|
+
const rt = this.runtimeFor(rootId);
|
|
114
|
+
const currentTurn = rt.turn?.turn ?? session.turns;
|
|
115
|
+
this.deps.logger.debug("direct card action received", {
|
|
116
|
+
root_id: rootId,
|
|
117
|
+
action: name,
|
|
118
|
+
turn,
|
|
119
|
+
operator: action.operatorName ?? action.operatorOpenId ?? null,
|
|
120
|
+
message_id: action.messageId,
|
|
121
|
+
});
|
|
122
|
+
if (name === "done" || name === "done_confirm" || name === "cancel") {
|
|
123
|
+
return this.handleLifecycleAction(name, session, rt, action);
|
|
124
|
+
}
|
|
125
|
+
if (name === "perm" || name === "perm_on" || name === "perm_once" || name === "perm_cancel") {
|
|
126
|
+
return this.handlePermissionAction(name, session, rt);
|
|
127
|
+
}
|
|
128
|
+
if (name.startsWith("auto_") || name.startsWith("collect_")) {
|
|
129
|
+
return this.handleInfoAction(name, session, rt, action);
|
|
130
|
+
}
|
|
131
|
+
if (turn !== null && turn !== currentTurn) {
|
|
132
|
+
return { toast: { type: "info", content: "该轮已结束" } };
|
|
133
|
+
}
|
|
134
|
+
if (name === "stop") {
|
|
135
|
+
if (!rt.turnInFlight || !rt.abort) {
|
|
136
|
+
return { toast: { type: "info", content: "该轮已结束" } };
|
|
137
|
+
}
|
|
138
|
+
const queued = this.beginInterrupt(session, rt);
|
|
139
|
+
const interrupted = rt.turn ? { ...rt.turn, phase: "interrupted" } : null;
|
|
140
|
+
this.deferAction(async () => {
|
|
141
|
+
await this.finalizeCardPhase(session.root_id, "interrupted");
|
|
142
|
+
await this.announceInterrupt(session.root_id, queued, await this.operatorLabel(action));
|
|
143
|
+
});
|
|
144
|
+
return {
|
|
145
|
+
toast: { type: "success", content: "已中断当前任务" },
|
|
146
|
+
...(interrupted ? { card: buildTurnCard(interrupted) } : {}),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
if (name === "retry") {
|
|
150
|
+
const prompt = session.last_prompt;
|
|
151
|
+
if (!prompt)
|
|
152
|
+
return { toast: { type: "error", content: "没有可重试的上一轮" } };
|
|
153
|
+
this.deferAction(() => this.enqueueRetry(session.root_id, prompt, currentTurn));
|
|
154
|
+
return { toast: { type: "success", content: "已重试上一轮" } };
|
|
155
|
+
}
|
|
156
|
+
if (session.status === "done" || session.status === "expired") {
|
|
157
|
+
return { toast: { type: "info", content: "会话已结束" } };
|
|
158
|
+
}
|
|
159
|
+
if (name === "full") {
|
|
160
|
+
this.deferAction(() => this.sendFullDetail(session, rt));
|
|
161
|
+
return { toast: { type: "info", content: "正在整理完整输出…" } };
|
|
162
|
+
}
|
|
163
|
+
return { toast: { type: "warning", content: "未知操作" } };
|
|
164
|
+
}
|
|
165
|
+
handlePermissionAction(name, session, rt) {
|
|
166
|
+
const card = (confirm) => {
|
|
167
|
+
const built = this.permissionCard(session, rt, confirm);
|
|
168
|
+
return built === null ? {} : { card: built };
|
|
169
|
+
};
|
|
170
|
+
if (name === "perm_cancel") {
|
|
171
|
+
return { toast: { type: "info", content: "已取消" }, ...card(false) };
|
|
172
|
+
}
|
|
173
|
+
const fresh = this.deps.store.getDirectSession(session.root_id) ?? session;
|
|
174
|
+
if (name === "perm") {
|
|
175
|
+
if (fresh.auto_approve_override === "on" || rt.autoOnce || rt.turnUsedOnce) {
|
|
176
|
+
rt.autoOnce = false;
|
|
177
|
+
rt.turnUsedOnce = false;
|
|
178
|
+
this.deps.store.updateDirectSession(session.root_id, { auto_approve_override: null });
|
|
179
|
+
return { toast: { type: "success", content: "已收回权限放开" }, ...card(false) };
|
|
180
|
+
}
|
|
181
|
+
return { toast: { type: "warning", content: "请确认是否放开权限" }, ...card(true) };
|
|
182
|
+
}
|
|
183
|
+
if (name === "perm_once") {
|
|
184
|
+
rt.autoOnce = true;
|
|
185
|
+
return { toast: { type: "success", content: "已设置为仅下一轮放开" }, ...card(false) };
|
|
186
|
+
}
|
|
187
|
+
this.deps.store.updateDirectSession(session.root_id, { auto_approve_override: "on" });
|
|
188
|
+
return {
|
|
189
|
+
toast: { type: "success", content: "已放开本会话权限(下一轮生效)" },
|
|
190
|
+
...card(false),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
permissionCard(session, rt, confirm) {
|
|
194
|
+
if (!rt.turn)
|
|
195
|
+
return null;
|
|
196
|
+
const fresh = this.deps.store.getDirectSession(session.root_id) ?? session;
|
|
197
|
+
const state = {
|
|
198
|
+
...rt.turn,
|
|
199
|
+
autoPosture: this.turnAutoPosture(fresh, rt),
|
|
200
|
+
agentOverride: fresh.agent_override,
|
|
201
|
+
};
|
|
202
|
+
if (confirm)
|
|
203
|
+
state.confirmPermission = true;
|
|
204
|
+
return buildTurnCard(state);
|
|
205
|
+
}
|
|
206
|
+
handleInfoAction(name, session, rt, action) {
|
|
207
|
+
if (name.startsWith("auto_")) {
|
|
208
|
+
const arg = name.slice("auto_".length);
|
|
209
|
+
const result = this.applyAutoArg(session, rt, arg);
|
|
210
|
+
this.refreshInfoCard(action.messageId, () => this.autoCard(this.freshSession(session), rt));
|
|
211
|
+
return { toast: { type: result.toast, content: result.toastText } };
|
|
212
|
+
}
|
|
213
|
+
if (name === "collect_start") {
|
|
214
|
+
if (rt.collect !== null) {
|
|
215
|
+
return { toast: { type: "info", content: "已在收集模式" } };
|
|
216
|
+
}
|
|
217
|
+
rt.collect = [];
|
|
218
|
+
this.armCollectTimer(session.root_id);
|
|
219
|
+
this.refreshInfoCard(action.messageId, () => this.collectCard(rt, session.root_id));
|
|
220
|
+
return { toast: { type: "success", content: "已进入收集模式" } };
|
|
221
|
+
}
|
|
222
|
+
if (name === "collect_cancel") {
|
|
223
|
+
if (rt.collect === null) {
|
|
224
|
+
return { toast: { type: "info", content: "当前不在收集模式" } };
|
|
225
|
+
}
|
|
226
|
+
const dropped = rt.collect.length;
|
|
227
|
+
this.clearCollect(session.root_id);
|
|
228
|
+
this.refreshInfoCard(action.messageId, () => this.collectCard(rt, session.root_id));
|
|
229
|
+
return {
|
|
230
|
+
toast: {
|
|
231
|
+
type: "success",
|
|
232
|
+
content: dropped === 0 ? "已退出收集模式" : `已退出收集模式,丢弃 ${dropped} 条`,
|
|
233
|
+
},
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
if (rt.collect === null) {
|
|
237
|
+
return { toast: { type: "info", content: "当前不在收集模式" } };
|
|
238
|
+
}
|
|
239
|
+
const buffered = rt.collect;
|
|
240
|
+
this.clearCollect(session.root_id);
|
|
241
|
+
if (buffered.length === 0) {
|
|
242
|
+
this.refreshInfoCard(action.messageId, () => this.collectCard(rt, session.root_id));
|
|
243
|
+
return { toast: { type: "info", content: "没有待提交内容" } };
|
|
244
|
+
}
|
|
245
|
+
this.enqueueTurn(session.root_id, buffered.join("\n---\n"));
|
|
246
|
+
this.refreshInfoCard(action.messageId, () => this.collectCard(rt, session.root_id));
|
|
247
|
+
return { toast: { type: "success", content: `已提交 ${buffered.length} 条为一轮` } };
|
|
248
|
+
}
|
|
249
|
+
freshSession(session) {
|
|
250
|
+
return this.deps.store.getDirectSession(session.root_id) ?? session;
|
|
251
|
+
}
|
|
252
|
+
refreshInfoCard(messageId, build) {
|
|
253
|
+
const updateCard = this.deps.feishu.updateCard;
|
|
254
|
+
if (!updateCard || messageId === "")
|
|
255
|
+
return;
|
|
256
|
+
this.deferAction(async () => {
|
|
257
|
+
try {
|
|
258
|
+
await updateCard.call(this.deps.feishu, messageId, build());
|
|
259
|
+
}
|
|
260
|
+
catch (e) {
|
|
261
|
+
this.deps.logger.debug("direct info card refresh failed", {
|
|
262
|
+
message_id: messageId,
|
|
263
|
+
error: toTaskingError(e).message,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
async replyInfoCard(session, card, fallbackText) {
|
|
269
|
+
const replyCard = this.deps.feishu.replyCardInThread;
|
|
270
|
+
if (replyCard) {
|
|
271
|
+
try {
|
|
272
|
+
await replyCard.call(this.deps.feishu, session.root_id, card);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
catch (e) {
|
|
276
|
+
this.deps.logger.warn("direct info card failed; falling back to text", {
|
|
277
|
+
root_id: session.root_id,
|
|
278
|
+
error: toTaskingError(e).message,
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
await this.replySafe(session.root_id, fallbackText);
|
|
283
|
+
}
|
|
284
|
+
helpCard() {
|
|
285
|
+
return buildInfoCard({
|
|
286
|
+
title: "📖 直连会话帮助",
|
|
287
|
+
lines: [
|
|
288
|
+
"**续聊**:直接回复本话题 → 与 agent 对话(排队串行执行)",
|
|
289
|
+
"**富输入**:直接发图片/文件 → 下载到工作区并把路径交给 agent",
|
|
290
|
+
"",
|
|
291
|
+
"**命令**",
|
|
292
|
+
"`/collect` → 收集多条消息;`/send` 提交为一轮;`/cancel` 丢弃",
|
|
293
|
+
"`/auto [on|once|off|reset]` → 本会话权限姿态(下一轮生效)",
|
|
294
|
+
"`/name <文本>` → 会话改名(卡片头部与 TUI)",
|
|
295
|
+
"`/agent <name>` · `/model <name>` → 切换 agent/model(`reset` 恢复)",
|
|
296
|
+
"`/new` → 清空上下文开启新会话",
|
|
297
|
+
"`/status` → 查看会话状态",
|
|
298
|
+
"`/stop` → 中断当前任务(含清空排队)",
|
|
299
|
+
"`/done` → 结束会话",
|
|
300
|
+
"",
|
|
301
|
+
"新建会话 → 在群里发 `/chat <项目|路径> <消息>`",
|
|
302
|
+
],
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
autoPostureOf(session, rt) {
|
|
306
|
+
if (session.auto_approve_override === "on")
|
|
307
|
+
return "on";
|
|
308
|
+
if (rt.autoOnce)
|
|
309
|
+
return "once";
|
|
310
|
+
return "off";
|
|
311
|
+
}
|
|
312
|
+
autoCard(session, rt) {
|
|
313
|
+
const current = this.autoPostureOf(session, rt);
|
|
314
|
+
const label = current === "on"
|
|
315
|
+
? translate("🔓 本会话放开")
|
|
316
|
+
: current === "once"
|
|
317
|
+
? translate("⚡ 仅下一轮放开")
|
|
318
|
+
: translate("🔒 默认(不传 --auto)");
|
|
319
|
+
return buildInfoCard({
|
|
320
|
+
title: "🔐 权限姿态",
|
|
321
|
+
rootId: session.root_id,
|
|
322
|
+
lines: [
|
|
323
|
+
`当前:${label}`,
|
|
324
|
+
this.autoSourceLabel(session),
|
|
325
|
+
"",
|
|
326
|
+
"放开后本会话后续轮次不再询问权限;目标仓库自身的 deny 规则仍然生效。",
|
|
327
|
+
],
|
|
328
|
+
buttons: [
|
|
329
|
+
{
|
|
330
|
+
label: "🔓 本会话放开",
|
|
331
|
+
action: "auto_on",
|
|
332
|
+
type: current === "on" ? "primary" : "default",
|
|
333
|
+
},
|
|
334
|
+
{
|
|
335
|
+
label: "⚡ 仅下一轮",
|
|
336
|
+
action: "auto_once",
|
|
337
|
+
type: current === "once" ? "primary" : "default",
|
|
338
|
+
},
|
|
339
|
+
{
|
|
340
|
+
label: "🔒 恢复默认",
|
|
341
|
+
action: "auto_off",
|
|
342
|
+
type: current === "off" ? "primary" : "default",
|
|
343
|
+
},
|
|
344
|
+
],
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
collectCard(rt, rootId) {
|
|
348
|
+
const buffered = rt.collect;
|
|
349
|
+
if (buffered === null) {
|
|
350
|
+
return buildInfoCard({
|
|
351
|
+
title: "📥 收集模式",
|
|
352
|
+
lines: [
|
|
353
|
+
"把接下来的多条消息(含图片/文件)攒成**一轮**再执行。",
|
|
354
|
+
"点下方按钮开始,或直接发 `/collect`。",
|
|
355
|
+
],
|
|
356
|
+
buttons: [{ label: "📥 开始收集", action: "collect_start", type: "primary" }],
|
|
357
|
+
rootId,
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
const idleMinutes = Math.round(COLLECT_IDLE_TIMEOUT_MS / 60000);
|
|
361
|
+
return buildInfoCard({
|
|
362
|
+
title: "📥 收集模式",
|
|
363
|
+
lines: [
|
|
364
|
+
`📥 收集中:已收集 **${buffered.length}** 条待提交。`,
|
|
365
|
+
"后续消息(含图片/文件)都会先收集,不立即执行。",
|
|
366
|
+
`发完点下方按钮提交为一轮(或发 \`/send\`);${idleMinutes} 分钟无新消息会自动提交。`,
|
|
367
|
+
"(缓冲仅在内存,daemon 重启会丢失。)",
|
|
368
|
+
],
|
|
369
|
+
buttons: [
|
|
370
|
+
{ label: "📤 提交为一轮", action: "collect_send", type: "primary" },
|
|
371
|
+
{ label: "🗑 丢弃", action: "collect_cancel", type: "danger" },
|
|
372
|
+
],
|
|
373
|
+
rootId,
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
applyAutoArg(session, rt, arg) {
|
|
377
|
+
if (arg === "on") {
|
|
378
|
+
this.deps.store.updateDirectSession(session.root_id, { auto_approve_override: "on" });
|
|
379
|
+
return {
|
|
380
|
+
text: "🔓 已放开本会话权限(下一轮生效)。目标仓库自身的 deny 规则仍然生效;/auto reset 可恢复。",
|
|
381
|
+
toast: "success",
|
|
382
|
+
toastText: "已放开本会话权限",
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
if (arg === "once") {
|
|
386
|
+
rt.autoOnce = true;
|
|
387
|
+
return {
|
|
388
|
+
text: "⚡ 仅下一轮放开权限(用完自动恢复默认)。",
|
|
389
|
+
toast: "success",
|
|
390
|
+
toastText: "仅下一轮放开权限",
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
if (arg === "off" || arg === "reset") {
|
|
394
|
+
rt.autoOnce = false;
|
|
395
|
+
this.deps.store.updateDirectSession(session.root_id, { auto_approve_override: null });
|
|
396
|
+
return {
|
|
397
|
+
text: `🔒 已恢复默认权限姿态(下一轮生效)。${this.autoSourceLabel(session)}`,
|
|
398
|
+
toast: "success",
|
|
399
|
+
toastText: "已恢复默认权限姿态",
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
return {
|
|
403
|
+
text: "用法:/auto(查看)|/auto on|/auto once|/auto off|/auto reset",
|
|
404
|
+
toast: "warning",
|
|
405
|
+
toastText: "未知的 /auto 参数",
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
handleLifecycleAction(name, session, rt, action) {
|
|
409
|
+
if (name === "cancel") {
|
|
410
|
+
const restored = rt.turn
|
|
411
|
+
? { ...rt.turn, phase: rt.turnInFlight ? "running" : rt.turn.phase }
|
|
412
|
+
: null;
|
|
413
|
+
return {
|
|
414
|
+
toast: { type: "info", content: "已取消" },
|
|
415
|
+
...(restored ? { card: buildTurnCard(restored) } : {}),
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
if (name === "done") {
|
|
419
|
+
const confirming = rt.turn ? { ...rt.turn, phase: "confirm" } : null;
|
|
420
|
+
return {
|
|
421
|
+
toast: { type: "warning", content: "请确认是否结束会话" },
|
|
422
|
+
...(confirming ? { card: buildTurnCard(confirming) } : {}),
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
this.deferAction(async () => this.executeDone(session, await this.operatorLabel(action)));
|
|
426
|
+
const ended = rt.turn ? { ...rt.turn, sealed: true } : null;
|
|
427
|
+
return {
|
|
428
|
+
toast: { type: "success", content: "会话已结束" },
|
|
429
|
+
...(ended ? { card: buildTurnCard(ended) } : {}),
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
async operatorLabel(action) {
|
|
433
|
+
if (action.operatorName !== null && action.operatorName !== "")
|
|
434
|
+
return action.operatorName;
|
|
435
|
+
const openId = action.operatorOpenId;
|
|
436
|
+
if (openId === null || openId === "")
|
|
437
|
+
return "未知";
|
|
438
|
+
const cached = this.memberCache.get(action.chatId);
|
|
439
|
+
if (cached && Date.now() - cached.at < MEMBER_CACHE_TTL_MS) {
|
|
440
|
+
const hit = cached.names.get(openId);
|
|
441
|
+
if (hit !== undefined && hit !== "")
|
|
442
|
+
return hit;
|
|
443
|
+
}
|
|
444
|
+
const names = await this.fetchMemberNames(action.chatId);
|
|
445
|
+
const name = names?.get(openId);
|
|
446
|
+
return name !== undefined && name !== "" ? name : openId;
|
|
447
|
+
}
|
|
448
|
+
async fetchMemberNames(chatId) {
|
|
449
|
+
const list = this.deps.feishu.listChatMembers;
|
|
450
|
+
if (!list || chatId === "")
|
|
451
|
+
return null;
|
|
452
|
+
try {
|
|
453
|
+
const members = await list.call(this.deps.feishu, chatId);
|
|
454
|
+
const names = new Map(members.map((m) => [m.open_id, m.name]));
|
|
455
|
+
this.memberCache.set(chatId, { at: Date.now(), names });
|
|
456
|
+
return names;
|
|
457
|
+
}
|
|
458
|
+
catch (e) {
|
|
459
|
+
this.deps.logger.debug("direct member lookup failed", {
|
|
460
|
+
chat_id: chatId,
|
|
461
|
+
error: toTaskingError(e).message,
|
|
462
|
+
});
|
|
463
|
+
return this.memberCache.get(chatId)?.names ?? null;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
deferAction(work) {
|
|
467
|
+
this.pendingWork++;
|
|
468
|
+
setImmediate(() => {
|
|
469
|
+
void work()
|
|
470
|
+
.catch((e) => this.deps.logger.warn("direct card action failed", {
|
|
471
|
+
error: toTaskingError(e).message,
|
|
472
|
+
}))
|
|
473
|
+
.finally(() => {
|
|
474
|
+
this.pendingWork = Math.max(0, this.pendingWork - 1);
|
|
475
|
+
});
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
claimCardAction(action) {
|
|
479
|
+
const key = `${action.messageId}:${action.operatorOpenId ?? ""}:${JSON.stringify(action.value ?? null)}`;
|
|
480
|
+
const now = Date.now();
|
|
481
|
+
for (const [seen, ts] of this.cardActionSeen) {
|
|
482
|
+
if (now - ts > CARD_ACTION_DEDUP_MS)
|
|
483
|
+
this.cardActionSeen.delete(seen);
|
|
484
|
+
}
|
|
485
|
+
if (this.cardActionSeen.has(key))
|
|
486
|
+
return false;
|
|
487
|
+
this.cardActionSeen.set(key, now);
|
|
488
|
+
return true;
|
|
489
|
+
}
|
|
490
|
+
async enqueueRetry(rootId, prompt, fromTurn) {
|
|
491
|
+
const rt = this.runtimeFor(rootId);
|
|
492
|
+
if (rt.turnInFlight) {
|
|
493
|
+
rt.queue.push(prompt);
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
void this.runTurnLoop(rootId, prompt, fromTurn).catch((e) => this.deps.logger.error("direct retry turn failed", {
|
|
497
|
+
root_id: rootId,
|
|
498
|
+
error: toTaskingError(e).message,
|
|
499
|
+
}));
|
|
500
|
+
}
|
|
501
|
+
async handleIntakeMessage(m) {
|
|
502
|
+
const config = this.deps.config();
|
|
503
|
+
if (!isDirectEnabled(config))
|
|
504
|
+
return false;
|
|
505
|
+
const parsed = parseChat(m.text);
|
|
506
|
+
if (!parsed)
|
|
507
|
+
return false;
|
|
508
|
+
try {
|
|
509
|
+
if (parsed.kind === "list") {
|
|
510
|
+
await this.deps.feishu.replyFlat(m.message_id, this.renderProjectList(config.feishu.direct));
|
|
511
|
+
return true;
|
|
512
|
+
}
|
|
513
|
+
if (parsed.kind === "help") {
|
|
514
|
+
await this.deps.feishu.replyFlat(m.message_id, renderChatHelp("intake"));
|
|
515
|
+
return true;
|
|
516
|
+
}
|
|
517
|
+
if (parsed.message.trim() === "") {
|
|
518
|
+
await this.deps.feishu.replyFlat(m.message_id, "请在 /chat 命令后带上首条消息,例如 `/chat tasking 帮我跑下测试`");
|
|
519
|
+
return true;
|
|
520
|
+
}
|
|
521
|
+
const existing = this.deps.store.getDirectSession(m.message_id);
|
|
522
|
+
if (existing) {
|
|
523
|
+
this.deps.logger.debug("direct chat root re-delivered; skipping silently", {
|
|
524
|
+
root_id: m.message_id,
|
|
525
|
+
status: existing.status,
|
|
526
|
+
});
|
|
527
|
+
return true;
|
|
528
|
+
}
|
|
529
|
+
const target = this.resolveTarget(parsed.target ?? "", parsed.isPath, config.feishu.direct);
|
|
530
|
+
if ("error" in target) {
|
|
531
|
+
await this.deps.feishu.replyFlat(m.message_id, target.error);
|
|
532
|
+
return true;
|
|
533
|
+
}
|
|
534
|
+
const dir = target.path;
|
|
535
|
+
this.deps.store.upsertDirectSession({
|
|
536
|
+
root_id: m.message_id,
|
|
537
|
+
chat_id: m.chat_id,
|
|
538
|
+
project: parsed.isPath ? null : (parsed.target ?? "").toLowerCase(),
|
|
539
|
+
name: sessionName(parsed.message),
|
|
540
|
+
path: dir,
|
|
541
|
+
session_id: null,
|
|
542
|
+
status: "idle",
|
|
543
|
+
});
|
|
544
|
+
const detailedCards = config.feishu.direct.verbosity === "detailed" &&
|
|
545
|
+
typeof this.deps.feishu.replyCardInThread === "function";
|
|
546
|
+
if (!detailedCards) {
|
|
547
|
+
const label = parsed.isPath
|
|
548
|
+
? translate(`目录 ${basename(dir)}`)
|
|
549
|
+
: translate(`项目 ${parsed.target}`);
|
|
550
|
+
await this.replySafe(m.message_id, `✅ 会话已创建(${label}),正在开始…`);
|
|
551
|
+
}
|
|
552
|
+
void this.fetchMemberNames(m.chat_id);
|
|
553
|
+
this.enqueueTurn(m.message_id, parsed.message);
|
|
554
|
+
return true;
|
|
555
|
+
}
|
|
556
|
+
catch (e) {
|
|
557
|
+
this.deps.logger.warn("direct chat intake failed", {
|
|
558
|
+
msg_id: m.message_id,
|
|
559
|
+
error: toTaskingError(e).message,
|
|
560
|
+
});
|
|
561
|
+
await this.deps.feishu
|
|
562
|
+
.replyFlat(m.message_id, `⚠️ /chat 处理失败:${toTaskingError(e).message}`)
|
|
563
|
+
.catch(() => { });
|
|
564
|
+
return true;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
async handleThreadMessage(m) {
|
|
568
|
+
const config = this.deps.config();
|
|
569
|
+
if (!isDirectEnabled(config))
|
|
570
|
+
return false;
|
|
571
|
+
if (m.root_id === null)
|
|
572
|
+
return false;
|
|
573
|
+
const session = this.deps.store.getDirectSession(m.root_id);
|
|
574
|
+
if (!session)
|
|
575
|
+
return false;
|
|
576
|
+
const curSec = toSecondsStr(session.last_msg_id ?? "");
|
|
577
|
+
if (curSec !== "") {
|
|
578
|
+
const t = Number(m.create_time);
|
|
579
|
+
if (t < Number(curSec))
|
|
580
|
+
return true;
|
|
581
|
+
if (t === Number(curSec) && session.seen_ids.includes(m.message_id))
|
|
582
|
+
return true;
|
|
583
|
+
}
|
|
584
|
+
this.deps.store.advanceDirectCursor(m.root_id, m.message_id, m.create_time);
|
|
585
|
+
if (m.sender_type === "app")
|
|
586
|
+
return true;
|
|
587
|
+
if (session.status === "done" || session.status === "expired") {
|
|
588
|
+
if (!this.terminalHintedRoots.has(m.root_id)) {
|
|
589
|
+
this.terminalHintedRoots.add(m.root_id);
|
|
590
|
+
await this.replySafe(m.root_id, session.status === "done"
|
|
591
|
+
? "ℹ️ 此会话已结束(/done)。重新发起请 /chat 创建新会话。"
|
|
592
|
+
: "ℹ️ 此会话已过期。重新发起请 /chat 创建新会话。");
|
|
593
|
+
}
|
|
594
|
+
return true;
|
|
595
|
+
}
|
|
596
|
+
const trimmed = m.text.trim();
|
|
597
|
+
if (trimmed === "/done") {
|
|
598
|
+
await this.executeDone(session);
|
|
599
|
+
return true;
|
|
600
|
+
}
|
|
601
|
+
if (trimmed === "/stop") {
|
|
602
|
+
await this.executeStop(session);
|
|
603
|
+
return true;
|
|
604
|
+
}
|
|
605
|
+
if (trimmed === "/help" || trimmed === "/?") {
|
|
606
|
+
await this.replyInfoCard(session, this.helpCard(), renderChatHelp("thread"));
|
|
607
|
+
return true;
|
|
608
|
+
}
|
|
609
|
+
if (trimmed === "/collect") {
|
|
610
|
+
await this.executeCollect(session);
|
|
611
|
+
return true;
|
|
612
|
+
}
|
|
613
|
+
if (trimmed === "/send") {
|
|
614
|
+
await this.executeSend(session);
|
|
615
|
+
return true;
|
|
616
|
+
}
|
|
617
|
+
if (trimmed === "/cancel") {
|
|
618
|
+
await this.executeCancel(session);
|
|
619
|
+
return true;
|
|
620
|
+
}
|
|
621
|
+
if (trimmed === "/name" || trimmed.startsWith("/name ")) {
|
|
622
|
+
await this.executeName(session, trimmed);
|
|
623
|
+
return true;
|
|
624
|
+
}
|
|
625
|
+
if (trimmed === "/status") {
|
|
626
|
+
await this.replyStatus(session);
|
|
627
|
+
return true;
|
|
628
|
+
}
|
|
629
|
+
if (trimmed === "/new") {
|
|
630
|
+
await this.executeNew(session);
|
|
631
|
+
return true;
|
|
632
|
+
}
|
|
633
|
+
if (trimmed === "/auto" || trimmed.startsWith("/auto ")) {
|
|
634
|
+
await this.executeAuto(session, trimmed);
|
|
635
|
+
return true;
|
|
636
|
+
}
|
|
637
|
+
if (trimmed === "/agent" || trimmed.startsWith("/agent ")) {
|
|
638
|
+
await this.executeAgent(session, trimmed);
|
|
639
|
+
return true;
|
|
640
|
+
}
|
|
641
|
+
if (trimmed === "/model" || trimmed.startsWith("/model ")) {
|
|
642
|
+
await this.executeModel(session, trimmed);
|
|
643
|
+
return true;
|
|
644
|
+
}
|
|
645
|
+
if (trimmed.startsWith("/")) {
|
|
646
|
+
await this.replySafe(m.root_id, "未知命令。直连会话支持:直接回复续聊、/collect、/send、/cancel、/auto、/agent、/model、/new、/name、/status、/stop、/done、/help");
|
|
647
|
+
return true;
|
|
648
|
+
}
|
|
649
|
+
const attachments = m.attachments ?? [];
|
|
650
|
+
if (trimmed === "" && attachments.length === 0) {
|
|
651
|
+
await this.replySafe(m.root_id, "⚠️ 暂仅支持文本消息,图片/文件请用文字描述~");
|
|
652
|
+
return true;
|
|
653
|
+
}
|
|
654
|
+
const prompt = await this.composePromptWithAttachments(session, m, trimmed);
|
|
655
|
+
if (prompt === null) {
|
|
656
|
+
await this.replySafe(m.root_id, "⚠️ 附件未能读取,本轮未执行;请重发,或把文件放到工作目录后把路径发给我。");
|
|
657
|
+
return true;
|
|
658
|
+
}
|
|
659
|
+
const rt = this.runtimeFor(m.root_id);
|
|
660
|
+
if (rt.collect !== null) {
|
|
661
|
+
rt.collect.push(prompt);
|
|
662
|
+
this.armCollectTimer(session.root_id);
|
|
663
|
+
await this.replySafe(m.root_id, `📥 已收集 ${rt.collect.length} 条(/send 提交为一轮,/cancel 丢弃)`);
|
|
664
|
+
return true;
|
|
665
|
+
}
|
|
666
|
+
this.enqueueTurn(m.root_id, prompt);
|
|
667
|
+
return true;
|
|
668
|
+
}
|
|
669
|
+
async recover() {
|
|
670
|
+
const running = this.deps.store.listDirectSessionsByStatus("running");
|
|
671
|
+
for (const s of running) {
|
|
672
|
+
this.deps.store.markDirectSessionStatus(s.root_id, "idle");
|
|
673
|
+
await this.finalizeStoredCard(s, "interrupted", "idle", true, "daemon 重启,上一轮已中断;工具明细未保留,可点「重试」重跑上一轮。");
|
|
674
|
+
await this.replySafe(s.root_id, "⚠️ 上次运行被中断(daemon 重启),请重发消息继续;若当时是第一轮对话,此前内容不会保留。");
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
async finalizeStoredCard(session, phase, sessionStatus, hideFullDetail, note = "", sealed = false) {
|
|
678
|
+
const cardId = session.card_message_id;
|
|
679
|
+
const updateCard = this.deps.feishu.updateCard;
|
|
680
|
+
if (!cardId || !updateCard)
|
|
681
|
+
return;
|
|
682
|
+
const state = {
|
|
683
|
+
rootId: session.root_id,
|
|
684
|
+
sessionName: session.name ?? sessionName(session.path),
|
|
685
|
+
sessionStatus,
|
|
686
|
+
turns: session.turns,
|
|
687
|
+
totalTokens: session.total_tokens,
|
|
688
|
+
queued: 0,
|
|
689
|
+
turn: session.turns,
|
|
690
|
+
phase,
|
|
691
|
+
toolCalls: 0,
|
|
692
|
+
durationSec: 0,
|
|
693
|
+
turnTokens: 0,
|
|
694
|
+
texts: note === "" ? [] : [note],
|
|
695
|
+
tools: [],
|
|
696
|
+
};
|
|
697
|
+
if (hideFullDetail)
|
|
698
|
+
state.hideFullDetail = true;
|
|
699
|
+
if (sealed)
|
|
700
|
+
state.sealed = true;
|
|
701
|
+
this.runtimeFor(session.root_id).turn = state;
|
|
702
|
+
try {
|
|
703
|
+
await updateCard.call(this.deps.feishu, cardId, buildTurnCard(state));
|
|
704
|
+
}
|
|
705
|
+
catch (e) {
|
|
706
|
+
this.deps.logger.warn("direct card finalize failed", {
|
|
707
|
+
root_id: session.root_id,
|
|
708
|
+
error: toTaskingError(e).message,
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
listActive() {
|
|
713
|
+
const sessions = this.deps.store.listActiveDirectSessions();
|
|
714
|
+
const config = this.deps.config();
|
|
715
|
+
return sessions.map((s) => {
|
|
716
|
+
const rt = this.runtime.get(s.root_id);
|
|
717
|
+
return {
|
|
718
|
+
id: `direct:${s.root_id}`,
|
|
719
|
+
root_id: s.root_id,
|
|
720
|
+
name: s.name,
|
|
721
|
+
project: s.project,
|
|
722
|
+
path: s.path,
|
|
723
|
+
status: s.status === "running" ? "running" : "idle",
|
|
724
|
+
session_id: s.session_id,
|
|
725
|
+
queued: rt?.queue.length ?? 0,
|
|
726
|
+
updated_at: s.updated_at,
|
|
727
|
+
agent: config.opencode.agent,
|
|
728
|
+
model: config.opencode.model,
|
|
729
|
+
variant: config.opencode.variant,
|
|
730
|
+
turns: s.turns,
|
|
731
|
+
input_tokens: s.input_tokens,
|
|
732
|
+
output_tokens: s.output_tokens,
|
|
733
|
+
total_tokens: s.total_tokens,
|
|
734
|
+
};
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
aggregateTotals() {
|
|
738
|
+
return {
|
|
739
|
+
input_tokens: this.aggregate.inputTokens,
|
|
740
|
+
output_tokens: this.aggregate.outputTokens,
|
|
741
|
+
total_tokens: this.aggregate.totalTokens,
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
async cleanupSession(session) {
|
|
745
|
+
this.clearCollect(session.root_id);
|
|
746
|
+
this.runtime.delete(session.root_id);
|
|
747
|
+
rmSync(join(this.deps.config().workspace.root, "direct-inbox", session.root_id), {
|
|
748
|
+
recursive: true,
|
|
749
|
+
force: true,
|
|
750
|
+
});
|
|
751
|
+
this.deps.clearActivity?.(`direct:${session.root_id}`);
|
|
752
|
+
const remove = this.deps.deleteSession;
|
|
753
|
+
const sessionId = session.session_id;
|
|
754
|
+
if (!remove || !sessionId)
|
|
755
|
+
return;
|
|
756
|
+
try {
|
|
757
|
+
await remove(sessionId);
|
|
758
|
+
}
|
|
759
|
+
catch (e) {
|
|
760
|
+
this.deps.logger.warn("direct session delete failed", {
|
|
761
|
+
root_id: session.root_id,
|
|
762
|
+
error: toTaskingError(e).message,
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
expireIdle(now = Date.now()) {
|
|
767
|
+
const ttl = this.deps.config().feishu.direct.idle_ttl_ms;
|
|
768
|
+
const expired = this.deps.store.listExpiredDirectSessions(now - ttl);
|
|
769
|
+
for (const s of expired) {
|
|
770
|
+
this.deps.store.markDirectSessionStatus(s.root_id, "expired");
|
|
771
|
+
this.terminalHintedRoots.add(s.root_id);
|
|
772
|
+
this.pendingWork++;
|
|
773
|
+
void this.finalizeStoredCard(s, "expired", "expired", true, "", true).finally(() => {
|
|
774
|
+
this.pendingWork = Math.max(0, this.pendingWork - 1);
|
|
775
|
+
});
|
|
776
|
+
void this.replySafe(s.root_id, "ℹ️ 会话空闲超时已过期。重新发起请 /chat 创建新会话。");
|
|
777
|
+
void this.cleanupSession(s).catch((e) => this.deps.logger.warn("direct session expiry cleanup failed", {
|
|
778
|
+
root_id: s.root_id,
|
|
779
|
+
error: toTaskingError(e).message,
|
|
780
|
+
}));
|
|
781
|
+
}
|
|
782
|
+
return expired.length;
|
|
783
|
+
}
|
|
784
|
+
renderProjectList(direct) {
|
|
785
|
+
const names = Object.keys(direct.projects);
|
|
786
|
+
const lines = ["可用项目:"];
|
|
787
|
+
if (names.length === 0) {
|
|
788
|
+
lines.push("(未配置 — 可用 /chat /绝对路径 <消息> 直接在目录创建会话)");
|
|
789
|
+
}
|
|
790
|
+
else {
|
|
791
|
+
for (const name of names) {
|
|
792
|
+
lines.push(` ${name} → ${direct.projects[name]?.path ?? ""}`);
|
|
793
|
+
}
|
|
794
|
+
lines.push("用法: /chat <项目名> <消息>");
|
|
795
|
+
}
|
|
796
|
+
lines.push("或: /chat /绝对路径 <消息> 在任意目录创建会话");
|
|
797
|
+
return lines.join("\n");
|
|
798
|
+
}
|
|
799
|
+
resolveTarget(target, isPath, direct) {
|
|
800
|
+
let candidate;
|
|
801
|
+
if (isPath) {
|
|
802
|
+
candidate = target;
|
|
803
|
+
}
|
|
804
|
+
else {
|
|
805
|
+
const entry = direct.projects[target.toLowerCase()];
|
|
806
|
+
if (!entry) {
|
|
807
|
+
return { error: `⚠️ 未找到项目 "${target}"。\n${this.renderProjectList(direct)}` };
|
|
808
|
+
}
|
|
809
|
+
candidate = entry.path;
|
|
810
|
+
}
|
|
811
|
+
if (!existsSync(candidate)) {
|
|
812
|
+
return { error: `⚠️ 路径不存在: ${candidate}` };
|
|
813
|
+
}
|
|
814
|
+
let real;
|
|
815
|
+
try {
|
|
816
|
+
real = realpathSync(candidate);
|
|
817
|
+
}
|
|
818
|
+
catch {
|
|
819
|
+
return { error: `⚠️ 无法解析路径: ${candidate}` };
|
|
820
|
+
}
|
|
821
|
+
if (isPath &&
|
|
822
|
+
direct.path_roots.length > 0 &&
|
|
823
|
+
!direct.path_roots.some((root) => real === root || real.startsWith(`${root}/`))) {
|
|
824
|
+
return {
|
|
825
|
+
error: `⚠️ ${target} 不在允许的路径范围内(path_roots)。\n${this.renderProjectList(direct)}`,
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
if (!statSync(real).isDirectory()) {
|
|
829
|
+
return { error: `⚠️ 不是目录: ${candidate}` };
|
|
830
|
+
}
|
|
831
|
+
return { path: real };
|
|
832
|
+
}
|
|
833
|
+
turnAutoPosture(session, rt) {
|
|
834
|
+
const posture = this.autoPostureOf(session, rt);
|
|
835
|
+
if (posture === "on")
|
|
836
|
+
return "on";
|
|
837
|
+
return rt.autoOnce || rt.turnUsedOnce ? "once" : "off";
|
|
838
|
+
}
|
|
839
|
+
resolveTurnAutoApprove(session, rt) {
|
|
840
|
+
const once = rt.autoOnce;
|
|
841
|
+
rt.autoOnce = false;
|
|
842
|
+
rt.turnUsedOnce = once;
|
|
843
|
+
if (once || session.auto_approve_override === "on")
|
|
844
|
+
return true;
|
|
845
|
+
return this.resolveAutoApprove(session.project ?? "", false, this.deps.config().feishu.direct);
|
|
846
|
+
}
|
|
847
|
+
resolveAutoApprove(target, isPath, direct) {
|
|
848
|
+
if (!isPath) {
|
|
849
|
+
const entry = direct.projects[target.toLowerCase()];
|
|
850
|
+
if (entry && entry.auto_approve !== null)
|
|
851
|
+
return entry.auto_approve;
|
|
852
|
+
}
|
|
853
|
+
return direct.auto_approve;
|
|
854
|
+
}
|
|
855
|
+
runtimeFor(rootId) {
|
|
856
|
+
let rt = this.runtime.get(rootId);
|
|
857
|
+
if (!rt) {
|
|
858
|
+
rt = {
|
|
859
|
+
queue: [],
|
|
860
|
+
turnInFlight: false,
|
|
861
|
+
abort: null,
|
|
862
|
+
stopRequested: false,
|
|
863
|
+
cardId: null,
|
|
864
|
+
cardsAvailable: true,
|
|
865
|
+
turn: null,
|
|
866
|
+
turnStartedAt: 0,
|
|
867
|
+
flushedTools: 0,
|
|
868
|
+
autoOnce: false,
|
|
869
|
+
turnUsedOnce: false,
|
|
870
|
+
heartbeatTimer: null,
|
|
871
|
+
collect: null,
|
|
872
|
+
collectTimer: null,
|
|
873
|
+
fullDetail: [],
|
|
874
|
+
fullDetailBytes: 0,
|
|
875
|
+
fullDetailDropped: 0,
|
|
876
|
+
cardUpdateFailures: 0,
|
|
877
|
+
flushTimer: null,
|
|
878
|
+
};
|
|
879
|
+
this.runtime.set(rootId, rt);
|
|
880
|
+
}
|
|
881
|
+
return rt;
|
|
882
|
+
}
|
|
883
|
+
enqueueTurn(rootId, message) {
|
|
884
|
+
const rt = this.runtimeFor(rootId);
|
|
885
|
+
if (rt.turnInFlight) {
|
|
886
|
+
rt.queue.push(message);
|
|
887
|
+
if (this.cardsLive(rt)) {
|
|
888
|
+
this.flushTurnCardSafe(rootId);
|
|
889
|
+
}
|
|
890
|
+
else {
|
|
891
|
+
const mergeNote = rt.queue.length >= 2 ? translate("(多条排队消息将合并为一轮执行)") : "";
|
|
892
|
+
void this.replySafe(rootId, `⏳ 已排队,当前任务完成后自动继续。${mergeNote}`);
|
|
893
|
+
}
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
void this.runTurnLoop(rootId, message).catch((e) => this.deps.logger.error("direct turn loop failed", {
|
|
897
|
+
root_id: rootId,
|
|
898
|
+
error: toTaskingError(e).message,
|
|
899
|
+
}));
|
|
900
|
+
}
|
|
901
|
+
async runTurnLoop(rootId, firstMessage, retryFromTurn) {
|
|
902
|
+
const rt = this.runtimeFor(rootId);
|
|
903
|
+
rt.turnInFlight = true;
|
|
904
|
+
rt.stopRequested = false;
|
|
905
|
+
try {
|
|
906
|
+
let prompt = firstMessage;
|
|
907
|
+
let retriedFrom = retryFromTurn;
|
|
908
|
+
for (;;) {
|
|
909
|
+
const session = this.deps.store.getDirectSession(rootId);
|
|
910
|
+
if (!session || session.status === "done" || session.status === "expired")
|
|
911
|
+
break;
|
|
912
|
+
if (this.halted || rt.stopRequested)
|
|
913
|
+
break;
|
|
914
|
+
await this.sealTurnCard(rt);
|
|
915
|
+
const max = this.deps.config().feishu.direct.max_concurrent;
|
|
916
|
+
const busy = this.activeTurns >= max || this.dirSlotFor(session.path).busy;
|
|
917
|
+
await this.startTurnCard(session, rt, busy, retriedFrom);
|
|
918
|
+
if (busy && !this.cardsLive(rt)) {
|
|
919
|
+
await this.replySafe(rootId, "⏳ 目标目录或并发额度正被占用,排队等待中,空闲后自动开始…");
|
|
920
|
+
}
|
|
921
|
+
await this.acquireDir(session.path);
|
|
922
|
+
try {
|
|
923
|
+
await this.acquireSlot();
|
|
924
|
+
try {
|
|
925
|
+
if (this.halted || rt.stopRequested)
|
|
926
|
+
break;
|
|
927
|
+
await this.executeTurn(session, prompt, rt);
|
|
928
|
+
}
|
|
929
|
+
finally {
|
|
930
|
+
this.releaseSlot();
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
finally {
|
|
934
|
+
this.releaseDir(session.path);
|
|
935
|
+
}
|
|
936
|
+
if (rt.queue.length === 0)
|
|
937
|
+
break;
|
|
938
|
+
prompt = rt.queue.join("\n---\n");
|
|
939
|
+
rt.queue = [];
|
|
940
|
+
retriedFrom = undefined;
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
finally {
|
|
944
|
+
rt.turnInFlight = false;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
cardsLive(rt) {
|
|
948
|
+
return rt.cardsAvailable && rt.cardId !== null && rt.turn !== null;
|
|
949
|
+
}
|
|
950
|
+
async startTurnCard(session, rt, busy, retryFromTurn) {
|
|
951
|
+
const fresh = this.deps.store.getDirectSession(session.root_id) ?? session;
|
|
952
|
+
const state = {
|
|
953
|
+
rootId: session.root_id,
|
|
954
|
+
sessionName: fresh.name ?? sessionName(fresh.path),
|
|
955
|
+
sessionStatus: busy ? "queued" : fresh.status,
|
|
956
|
+
turns: fresh.turns,
|
|
957
|
+
totalTokens: fresh.total_tokens,
|
|
958
|
+
queued: rt.queue.length,
|
|
959
|
+
turn: fresh.turns + 1,
|
|
960
|
+
phase: "running",
|
|
961
|
+
toolCalls: 0,
|
|
962
|
+
durationSec: 0,
|
|
963
|
+
turnTokens: 0,
|
|
964
|
+
texts: [],
|
|
965
|
+
tools: [],
|
|
966
|
+
};
|
|
967
|
+
if (retryFromTurn !== undefined)
|
|
968
|
+
state.retryFromTurn = retryFromTurn;
|
|
969
|
+
rt.turn = state;
|
|
970
|
+
rt.turnUsedOnce = false;
|
|
971
|
+
rt.turnStartedAt = 0;
|
|
972
|
+
rt.flushedTools = 0;
|
|
973
|
+
rt.fullDetail = [];
|
|
974
|
+
rt.fullDetailBytes = 0;
|
|
975
|
+
rt.fullDetailDropped = 0;
|
|
976
|
+
const detailed = this.deps.config().feishu.direct.verbosity === "detailed";
|
|
977
|
+
const replyCard = this.deps.feishu.replyCardInThread;
|
|
978
|
+
if (!detailed || !rt.cardsAvailable || !replyCard) {
|
|
979
|
+
rt.cardsAvailable = false;
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
try {
|
|
983
|
+
const created = await replyCard.call(this.deps.feishu, session.root_id, buildTurnCard(state));
|
|
984
|
+
rt.cardId = created.message_id;
|
|
985
|
+
this.deps.store.updateDirectSession(session.root_id, { card_message_id: created.message_id });
|
|
986
|
+
if (created.thread_id) {
|
|
987
|
+
this.deps.store.updateDirectSession(session.root_id, { thread_id: created.thread_id });
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
catch (e) {
|
|
991
|
+
rt.cardsAvailable = false;
|
|
992
|
+
rt.cardId = null;
|
|
993
|
+
this.deps.logger.warn("direct card create failed; falling back to text", {
|
|
994
|
+
root_id: session.root_id,
|
|
995
|
+
error: toTaskingError(e).message,
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
async sealTurnCard(rt) {
|
|
1000
|
+
if (!rt.turn || rt.cardId === null)
|
|
1001
|
+
return;
|
|
1002
|
+
const updateCard = this.deps.feishu.updateCard;
|
|
1003
|
+
const cardId = rt.cardId;
|
|
1004
|
+
const sealed = { ...rt.turn, sealed: true };
|
|
1005
|
+
rt.cardId = null;
|
|
1006
|
+
if (!updateCard)
|
|
1007
|
+
return;
|
|
1008
|
+
try {
|
|
1009
|
+
await updateCard.call(this.deps.feishu, cardId, buildTurnCard(sealed));
|
|
1010
|
+
}
|
|
1011
|
+
catch (e) {
|
|
1012
|
+
this.deps.logger.warn("direct card seal failed", {
|
|
1013
|
+
root_id: rt.turn.rootId,
|
|
1014
|
+
error: toTaskingError(e).message,
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
scheduleFlush(rootId) {
|
|
1019
|
+
const rt = this.runtimeFor(rootId);
|
|
1020
|
+
if (!rt.turn)
|
|
1021
|
+
return;
|
|
1022
|
+
if (rt.flushTimer)
|
|
1023
|
+
return;
|
|
1024
|
+
rt.flushTimer = setTimeout(() => {
|
|
1025
|
+
rt.flushTimer = null;
|
|
1026
|
+
this.flushTurnCardSafe(rootId);
|
|
1027
|
+
}, CARD_UPDATE_INTERVAL_MS);
|
|
1028
|
+
rt.flushTimer.unref?.();
|
|
1029
|
+
}
|
|
1030
|
+
flushSoon(rootId) {
|
|
1031
|
+
const rt = this.runtimeFor(rootId);
|
|
1032
|
+
if (rt.flushTimer) {
|
|
1033
|
+
clearTimeout(rt.flushTimer);
|
|
1034
|
+
rt.flushTimer = null;
|
|
1035
|
+
}
|
|
1036
|
+
this.flushTurnCardSafe(rootId);
|
|
1037
|
+
}
|
|
1038
|
+
flushTurnCardSafe(rootId) {
|
|
1039
|
+
void this.flushTurnCard(rootId).catch((e) => this.deps.logger.debug("direct card flush failed", {
|
|
1040
|
+
root_id: rootId,
|
|
1041
|
+
error: toTaskingError(e).message,
|
|
1042
|
+
}));
|
|
1043
|
+
}
|
|
1044
|
+
async flushTurnCard(rootId) {
|
|
1045
|
+
const rt = this.runtimeFor(rootId);
|
|
1046
|
+
const turn = rt.turn;
|
|
1047
|
+
if (!turn)
|
|
1048
|
+
return;
|
|
1049
|
+
if (rt.flushTimer) {
|
|
1050
|
+
clearTimeout(rt.flushTimer);
|
|
1051
|
+
rt.flushTimer = null;
|
|
1052
|
+
}
|
|
1053
|
+
const fresh = this.deps.store.getDirectSession(rootId);
|
|
1054
|
+
if (fresh) {
|
|
1055
|
+
turn.sessionName = fresh.name ?? sessionName(fresh.path);
|
|
1056
|
+
turn.autoPosture = this.turnAutoPosture(fresh, rt);
|
|
1057
|
+
turn.agentOverride = fresh.agent_override;
|
|
1058
|
+
if (rt.turnStartedAt > 0) {
|
|
1059
|
+
turn.sessionStatus = fresh.status;
|
|
1060
|
+
turn.turns = fresh.turns;
|
|
1061
|
+
turn.totalTokens = fresh.total_tokens;
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
turn.queued = rt.queue.length;
|
|
1065
|
+
if (turn.phase === "running" && rt.turnStartedAt > 0) {
|
|
1066
|
+
turn.durationSec = Math.max(1, Math.round((Date.now() - rt.turnStartedAt) / 1000));
|
|
1067
|
+
}
|
|
1068
|
+
const updateCard = this.deps.feishu.updateCard;
|
|
1069
|
+
if (rt.cardsAvailable && rt.cardId !== null && updateCard) {
|
|
1070
|
+
try {
|
|
1071
|
+
await updateCard.call(this.deps.feishu, rt.cardId, buildTurnCard(turn));
|
|
1072
|
+
rt.cardUpdateFailures = 0;
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
catch (e) {
|
|
1076
|
+
rt.cardUpdateFailures++;
|
|
1077
|
+
this.deps.logger.warn("direct card update failed", {
|
|
1078
|
+
root_id: rootId,
|
|
1079
|
+
error: toTaskingError(e).message,
|
|
1080
|
+
});
|
|
1081
|
+
if (rt.cardUpdateFailures < 2 && rt.cardId !== null) {
|
|
1082
|
+
try {
|
|
1083
|
+
await updateCard.call(this.deps.feishu, rt.cardId, buildTurnCard(turn));
|
|
1084
|
+
rt.cardUpdateFailures = 0;
|
|
1085
|
+
return;
|
|
1086
|
+
}
|
|
1087
|
+
catch (retryError) {
|
|
1088
|
+
rt.cardUpdateFailures++;
|
|
1089
|
+
this.deps.logger.warn("direct card update retry failed; falling back to text", {
|
|
1090
|
+
root_id: rootId,
|
|
1091
|
+
error: toTaskingError(retryError).message,
|
|
1092
|
+
});
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
rt.cardsAvailable = false;
|
|
1096
|
+
rt.cardId = null;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
if (this.deps.config().feishu.direct.verbosity !== "detailed")
|
|
1100
|
+
return;
|
|
1101
|
+
const pending = turn.tools.slice(rt.flushedTools);
|
|
1102
|
+
rt.flushedTools = turn.tools.length;
|
|
1103
|
+
if (pending.length === 0)
|
|
1104
|
+
return;
|
|
1105
|
+
const lines = pending.map((t) => {
|
|
1106
|
+
const summary = toolSummary(t);
|
|
1107
|
+
const exit = t.exit !== undefined && t.exit !== 0 ? ` (exit ${t.exit})` : "";
|
|
1108
|
+
return `🔧 ${t.tool}${summary === "" ? "" : ` · ${summary}`}${exit}`;
|
|
1109
|
+
});
|
|
1110
|
+
await this.replySafe(rootId, truncate(lines.join("\n"), 2000));
|
|
1111
|
+
}
|
|
1112
|
+
accumulateTool(rt, evt) {
|
|
1113
|
+
const panel = { tool: evt.tool ?? "tool" };
|
|
1114
|
+
if (evt.title !== undefined)
|
|
1115
|
+
panel.title = evt.title;
|
|
1116
|
+
if (evt.status !== undefined)
|
|
1117
|
+
panel.status = evt.status;
|
|
1118
|
+
if (evt.exit !== undefined)
|
|
1119
|
+
panel.exit = evt.exit;
|
|
1120
|
+
if (evt.durationMs !== undefined)
|
|
1121
|
+
panel.durationMs = evt.durationMs;
|
|
1122
|
+
if (evt.input !== undefined)
|
|
1123
|
+
panel.input = evt.input;
|
|
1124
|
+
if (evt.output !== undefined)
|
|
1125
|
+
panel.output = evt.output;
|
|
1126
|
+
if (evt.error !== undefined)
|
|
1127
|
+
panel.error = evt.error;
|
|
1128
|
+
if (evt.truncated !== undefined)
|
|
1129
|
+
panel.truncated = evt.truncated;
|
|
1130
|
+
rt.fullDetail.push(panel);
|
|
1131
|
+
rt.fullDetailBytes += fullDetailBytes(panel);
|
|
1132
|
+
while (rt.fullDetailBytes > FULL_DETAIL_MAX_BYTES && rt.fullDetail.length > 1) {
|
|
1133
|
+
const dropped = rt.fullDetail.shift();
|
|
1134
|
+
if (dropped)
|
|
1135
|
+
rt.fullDetailBytes -= fullDetailBytes(dropped);
|
|
1136
|
+
rt.fullDetailDropped++;
|
|
1137
|
+
}
|
|
1138
|
+
rt.turn?.tools.push(panel);
|
|
1139
|
+
}
|
|
1140
|
+
async sendCompletion(session, delivery) {
|
|
1141
|
+
const verbosity = this.deps.config().feishu.direct.verbosity;
|
|
1142
|
+
const replyCard = this.deps.feishu.replyCardInThread;
|
|
1143
|
+
if (verbosity !== "detailed" || !replyCard) {
|
|
1144
|
+
await this.replySafe(session.root_id, delivery.body);
|
|
1145
|
+
return;
|
|
1146
|
+
}
|
|
1147
|
+
const card = buildCompletionCard({
|
|
1148
|
+
answer: delivery.answer,
|
|
1149
|
+
statsLine: delivery.statsLine,
|
|
1150
|
+
note: delivery.note,
|
|
1151
|
+
});
|
|
1152
|
+
if (JSON.stringify(card).length <= CARD_BUDGET_BYTES) {
|
|
1153
|
+
try {
|
|
1154
|
+
await replyCard.call(this.deps.feishu, session.root_id, card);
|
|
1155
|
+
return;
|
|
1156
|
+
}
|
|
1157
|
+
catch (e) {
|
|
1158
|
+
this.deps.logger.warn("direct completion card failed; falling back to text", {
|
|
1159
|
+
root_id: session.root_id,
|
|
1160
|
+
error: toTaskingError(e).message,
|
|
1161
|
+
});
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
const markdown = `${delivery.answer}\n\n${[delivery.statsLine, delivery.note]
|
|
1165
|
+
.filter((part) => part !== "")
|
|
1166
|
+
.join("\n")}`.trim();
|
|
1167
|
+
await this.deliverLongContent(session.root_id, markdown, `direct-answer-${session.turns}.md`, "回答过长,无法作为消息发送;请在 TUI 活动视图查看该会话的完整回答。", "(回答过长,文件上传不可用,已改为文本投递;完整内容亦可在 TUI 活动视图查看)");
|
|
1168
|
+
}
|
|
1169
|
+
async deliverLongContent(rootId, markdown, fileName, oversizeNote, unavailableNote) {
|
|
1170
|
+
const bytes = Buffer.from(markdown, "utf8");
|
|
1171
|
+
const upload = this.deps.feishu.uploadFile;
|
|
1172
|
+
const sendFile = this.deps.feishu.sendFileMessage;
|
|
1173
|
+
if (!upload || !sendFile) {
|
|
1174
|
+
this.deps.logger.warn("direct file upload unavailable; sending text", { root_id: rootId });
|
|
1175
|
+
}
|
|
1176
|
+
if (upload && sendFile) {
|
|
1177
|
+
try {
|
|
1178
|
+
const key = await upload.call(this.deps.feishu, bytes, fileName);
|
|
1179
|
+
if (key !== "") {
|
|
1180
|
+
await sendFile.call(this.deps.feishu, rootId, key);
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
catch (e) {
|
|
1185
|
+
this.deps.logger.warn("direct file delivery failed; falling back to text", {
|
|
1186
|
+
root_id: rootId,
|
|
1187
|
+
error: toTaskingError(e).message,
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
if (bytes.length > FULL_TEXT_LIMIT_BYTES) {
|
|
1192
|
+
await this.replySafe(rootId, oversizeNote);
|
|
1193
|
+
return;
|
|
1194
|
+
}
|
|
1195
|
+
await this.replySafe(rootId, `${markdown}\n\n${unavailableNote}`);
|
|
1196
|
+
}
|
|
1197
|
+
async sendFullDetail(session, rt) {
|
|
1198
|
+
if (rt.fullDetail.length === 0) {
|
|
1199
|
+
await this.replySafe(session.root_id, "该轮没有可导出的完整明细(可能因 daemon 重启,明细已不在内存中)。");
|
|
1200
|
+
return;
|
|
1201
|
+
}
|
|
1202
|
+
const markdown = renderFullDetail(session, rt.turn, rt.fullDetail, rt.fullDetailDropped);
|
|
1203
|
+
await this.deliverLongContent(session.root_id, markdown, fullDetailFileName(rt.turn?.turn ?? 0), "完整输出过大,无法作为消息发送;请在 TUI 活动视图查看该会话的完整明细。", "(文件上传不可用,已改为文本投递;完整明细亦可在 TUI 活动视图查看)");
|
|
1204
|
+
}
|
|
1205
|
+
async finalizeTurnCard(rootId, phase, stats, durationSec, dropFinalText = false) {
|
|
1206
|
+
const rt = this.runtimeFor(rootId);
|
|
1207
|
+
if (!rt.turn)
|
|
1208
|
+
return;
|
|
1209
|
+
rt.turn.toolCalls = stats.toolCalls;
|
|
1210
|
+
rt.turn.turnTokens = stats.totalTokens;
|
|
1211
|
+
if (dropFinalText)
|
|
1212
|
+
rt.turn.finalized = true;
|
|
1213
|
+
await this.finalizeCardPhase(rootId, phase, durationSec);
|
|
1214
|
+
}
|
|
1215
|
+
beginInterrupt(session, rt) {
|
|
1216
|
+
const queued = rt.queue.length;
|
|
1217
|
+
rt.queue = [];
|
|
1218
|
+
rt.stopRequested = true;
|
|
1219
|
+
rt.abort?.abort();
|
|
1220
|
+
this.deps.store.markDirectSessionStatus(session.root_id, "idle");
|
|
1221
|
+
return queued;
|
|
1222
|
+
}
|
|
1223
|
+
async announceInterrupt(rootId, queued, operator) {
|
|
1224
|
+
const who = operator ? translate(`(操作人:${operator})`) : "";
|
|
1225
|
+
await this.replySafe(rootId, queued > 0
|
|
1226
|
+
? `🛑 已中断当前任务${who},并清空 ${queued} 条排队消息。可直接回复重新继续。`
|
|
1227
|
+
: `🛑 已中断当前任务${who}。可直接回复重新继续。`);
|
|
1228
|
+
}
|
|
1229
|
+
async sealCurrentCard(rootId) {
|
|
1230
|
+
const rt = this.runtimeFor(rootId);
|
|
1231
|
+
if (!rt.turn)
|
|
1232
|
+
return;
|
|
1233
|
+
rt.turn.sealed = true;
|
|
1234
|
+
await this.flushTurnCard(rootId);
|
|
1235
|
+
}
|
|
1236
|
+
stopHeartbeat(rt) {
|
|
1237
|
+
if (rt.heartbeatTimer) {
|
|
1238
|
+
clearInterval(rt.heartbeatTimer);
|
|
1239
|
+
rt.heartbeatTimer = null;
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
async finalizeCardPhase(rootId, phase, durationSec) {
|
|
1243
|
+
const rt = this.runtimeFor(rootId);
|
|
1244
|
+
if (!rt.turn)
|
|
1245
|
+
return;
|
|
1246
|
+
rt.turn.phase = phase;
|
|
1247
|
+
if (durationSec !== undefined)
|
|
1248
|
+
rt.turn.durationSec = durationSec;
|
|
1249
|
+
await this.flushTurnCard(rootId);
|
|
1250
|
+
}
|
|
1251
|
+
async acquireSlot() {
|
|
1252
|
+
const max = this.deps.config().feishu.direct.max_concurrent;
|
|
1253
|
+
if (this.activeTurns < max) {
|
|
1254
|
+
this.activeTurns++;
|
|
1255
|
+
return;
|
|
1256
|
+
}
|
|
1257
|
+
await new Promise((resolve) => this.waiters.push(resolve));
|
|
1258
|
+
}
|
|
1259
|
+
releaseSlot() {
|
|
1260
|
+
const next = this.waiters.shift();
|
|
1261
|
+
if (next) {
|
|
1262
|
+
next();
|
|
1263
|
+
return;
|
|
1264
|
+
}
|
|
1265
|
+
this.activeTurns = Math.max(0, this.activeTurns - 1);
|
|
1266
|
+
}
|
|
1267
|
+
async executeTurn(session, prompt, rt) {
|
|
1268
|
+
const config = this.deps.config();
|
|
1269
|
+
const sessionId = session.session_id;
|
|
1270
|
+
const isFirstTurn = sessionId === null;
|
|
1271
|
+
const autoApprove = this.resolveTurnAutoApprove(session, rt);
|
|
1272
|
+
const cmd = buildDirectCommand({
|
|
1273
|
+
opencodeCommand: config.opencode.command,
|
|
1274
|
+
dir: session.path,
|
|
1275
|
+
message: prompt,
|
|
1276
|
+
sessionId,
|
|
1277
|
+
autoApprove,
|
|
1278
|
+
agent: session.agent_override ?? config.opencode.agent,
|
|
1279
|
+
model: session.model_override ?? config.opencode.model,
|
|
1280
|
+
variant: config.opencode.variant,
|
|
1281
|
+
});
|
|
1282
|
+
this.deps.logger.info("direct turn starting", {
|
|
1283
|
+
root_id: session.root_id,
|
|
1284
|
+
dir: session.path,
|
|
1285
|
+
agent: session.agent_override ?? config.opencode.agent,
|
|
1286
|
+
model: session.model_override ?? config.opencode.model ?? null,
|
|
1287
|
+
auto_approve: autoApprove,
|
|
1288
|
+
continuation: !isFirstTurn,
|
|
1289
|
+
cmd: cmd.slice(0, -1).join(" "),
|
|
1290
|
+
message: truncate(prompt, 60),
|
|
1291
|
+
});
|
|
1292
|
+
this.deps.store.updateDirectSession(session.root_id, { status: "running" });
|
|
1293
|
+
this.deps.store.updateDirectSession(session.root_id, { last_prompt: prompt });
|
|
1294
|
+
rt.stopRequested = false;
|
|
1295
|
+
rt.turnStartedAt = Date.now();
|
|
1296
|
+
const startedAt = rt.turnStartedAt;
|
|
1297
|
+
this.stopHeartbeat(rt);
|
|
1298
|
+
rt.heartbeatTimer = setInterval(() => {
|
|
1299
|
+
this.flushTurnCardSafe(session.root_id);
|
|
1300
|
+
}, CARD_HEARTBEAT_MS);
|
|
1301
|
+
rt.heartbeatTimer.unref?.();
|
|
1302
|
+
const turnNo = session.turns + 1;
|
|
1303
|
+
this.deps.store.addDirectSessionUsage(session.root_id, { input_tokens: 0, output_tokens: 0, total_tokens: 0 }, 1);
|
|
1304
|
+
const stats = {
|
|
1305
|
+
toolCalls: 0,
|
|
1306
|
+
permissionRejections: 0,
|
|
1307
|
+
inputTokens: 0,
|
|
1308
|
+
outputTokens: 0,
|
|
1309
|
+
totalTokens: 0,
|
|
1310
|
+
lastText: "",
|
|
1311
|
+
};
|
|
1312
|
+
const abort = new AbortController();
|
|
1313
|
+
rt.abort = abort;
|
|
1314
|
+
const onEvent = (evt) => {
|
|
1315
|
+
if (evt.type === "tool_use") {
|
|
1316
|
+
stats.toolCalls++;
|
|
1317
|
+
if (evt.status === "error" &&
|
|
1318
|
+
typeof evt.error === "string" &&
|
|
1319
|
+
/permission/i.test(evt.error)) {
|
|
1320
|
+
stats.permissionRejections++;
|
|
1321
|
+
}
|
|
1322
|
+
this.accumulateTool(rt, evt);
|
|
1323
|
+
if (rt.turn)
|
|
1324
|
+
rt.turn.toolCalls = stats.toolCalls;
|
|
1325
|
+
const panel = rt.fullDetail[rt.fullDetail.length - 1];
|
|
1326
|
+
if (panel !== undefined && isFailed(panel))
|
|
1327
|
+
this.flushSoon(session.root_id);
|
|
1328
|
+
else
|
|
1329
|
+
this.scheduleFlush(session.root_id);
|
|
1330
|
+
}
|
|
1331
|
+
if (evt.type === "text" && typeof evt.text === "string" && evt.text.trim() !== "") {
|
|
1332
|
+
stats.lastText = evt.text;
|
|
1333
|
+
if (rt.turn)
|
|
1334
|
+
rt.turn.texts.push(evt.text);
|
|
1335
|
+
this.scheduleFlush(session.root_id);
|
|
1336
|
+
}
|
|
1337
|
+
if (this.deps.activity) {
|
|
1338
|
+
const activity = { ts: Date.now(), turn: turnNo, type: evt.type };
|
|
1339
|
+
if (evt.text !== undefined)
|
|
1340
|
+
activity.text = evt.text;
|
|
1341
|
+
if (evt.tool !== undefined)
|
|
1342
|
+
activity.tool = evt.tool;
|
|
1343
|
+
if (evt.tokens !== undefined)
|
|
1344
|
+
activity.tokens = evt.tokens;
|
|
1345
|
+
if (evt.title !== undefined)
|
|
1346
|
+
activity.title = evt.title;
|
|
1347
|
+
if (evt.input !== undefined)
|
|
1348
|
+
activity.input = evt.input;
|
|
1349
|
+
if (evt.output !== undefined)
|
|
1350
|
+
activity.output = evt.output;
|
|
1351
|
+
if (evt.error !== undefined)
|
|
1352
|
+
activity.error = evt.error;
|
|
1353
|
+
if (evt.exit !== undefined)
|
|
1354
|
+
activity.exit = evt.exit;
|
|
1355
|
+
if (evt.status !== undefined)
|
|
1356
|
+
activity.status = evt.status;
|
|
1357
|
+
if (evt.durationMs !== undefined)
|
|
1358
|
+
activity.durationMs = evt.durationMs;
|
|
1359
|
+
if (evt.truncated !== undefined)
|
|
1360
|
+
activity.truncated = evt.truncated;
|
|
1361
|
+
this.deps.activity(`direct:${session.root_id}`, activity);
|
|
1362
|
+
}
|
|
1363
|
+
};
|
|
1364
|
+
let result;
|
|
1365
|
+
try {
|
|
1366
|
+
result = await (this.deps.spawn ?? defaultSpawn)(cmd, session.path, config.opencode.turn_timeout_ms, config.opencode.inactivity_timeout_ms, abort.signal, onEvent);
|
|
1367
|
+
}
|
|
1368
|
+
catch (e) {
|
|
1369
|
+
rt.abort = null;
|
|
1370
|
+
rt.queue = [];
|
|
1371
|
+
this.deps.store.markDirectSessionStatus(session.root_id, "idle");
|
|
1372
|
+
this.deps.logger.error("direct turn spawn failed", {
|
|
1373
|
+
root_id: session.root_id,
|
|
1374
|
+
error: toTaskingError(e).message,
|
|
1375
|
+
});
|
|
1376
|
+
await this.finalizeTurnCard(session.root_id, "failed", stats, 0);
|
|
1377
|
+
await this.replySafe(session.root_id, `⚠️ 本轮未能启动(${toTaskingError(e).message})。请重发消息重试。`);
|
|
1378
|
+
return;
|
|
1379
|
+
}
|
|
1380
|
+
finally {
|
|
1381
|
+
rt.abort = null;
|
|
1382
|
+
this.stopHeartbeat(rt);
|
|
1383
|
+
}
|
|
1384
|
+
const durationSec = Math.max(1, Math.round((Date.now() - startedAt) / 1000));
|
|
1385
|
+
const fresh = this.deps.store.getDirectSession(session.root_id);
|
|
1386
|
+
if (!fresh || fresh.status === "done" || fresh.status === "expired")
|
|
1387
|
+
return;
|
|
1388
|
+
const extracted = result.sessionAndUsage;
|
|
1389
|
+
if (extracted) {
|
|
1390
|
+
stats.inputTokens = extracted.usage.input_tokens;
|
|
1391
|
+
stats.outputTokens = extracted.usage.output_tokens;
|
|
1392
|
+
stats.totalTokens = extracted.usage.total_tokens;
|
|
1393
|
+
this.aggregate.inputTokens += extracted.usage.input_tokens;
|
|
1394
|
+
this.aggregate.outputTokens += extracted.usage.output_tokens;
|
|
1395
|
+
this.aggregate.totalTokens += extracted.usage.total_tokens;
|
|
1396
|
+
this.deps.store.addDirectSessionUsage(session.root_id, extracted.usage, 0);
|
|
1397
|
+
}
|
|
1398
|
+
if (extracted?.session_id) {
|
|
1399
|
+
this.deps.store.updateDirectSession(session.root_id, { session_id: extracted.session_id });
|
|
1400
|
+
}
|
|
1401
|
+
if (rt.stopRequested) {
|
|
1402
|
+
this.deps.store.markDirectSessionStatus(session.root_id, "idle");
|
|
1403
|
+
await this.finalizeTurnCard(session.root_id, "interrupted", stats, durationSec);
|
|
1404
|
+
return;
|
|
1405
|
+
}
|
|
1406
|
+
if (result.timedOut) {
|
|
1407
|
+
const reason = result.timedOutReason === "inactivity" ? translate("无输出超时") : translate("整体超时");
|
|
1408
|
+
this.deps.store.markDirectSessionStatus(session.root_id, "idle");
|
|
1409
|
+
await this.finalizeTurnCard(session.root_id, "failed", stats, durationSec);
|
|
1410
|
+
await this.replySafe(session.root_id, `⚠️ 本轮${reason}被中止(${durationSec}s)。可用更小的任务描述重试。`);
|
|
1411
|
+
return;
|
|
1412
|
+
}
|
|
1413
|
+
if (result.exitCode !== 0) {
|
|
1414
|
+
this.deps.store.markDirectSessionStatus(session.root_id, "idle");
|
|
1415
|
+
await this.finalizeTurnCard(session.root_id, "failed", stats, durationSec, true);
|
|
1416
|
+
await this.replySafe(session.root_id, `⚠️ 本轮未完成(退出码 ${result.exitCode},${durationSec}s)。${stats.lastText ? `\n\n${truncate(stats.lastText)}` : ""}`.trim());
|
|
1417
|
+
return;
|
|
1418
|
+
}
|
|
1419
|
+
this.deps.store.markDirectSessionStatus(session.root_id, "idle");
|
|
1420
|
+
await this.finalizeTurnCard(session.root_id, "completed", stats, durationSec, true);
|
|
1421
|
+
const verbosity = config.feishu.direct.verbosity;
|
|
1422
|
+
const statsLine = verbosity === "quiet"
|
|
1423
|
+
? ""
|
|
1424
|
+
: `\n\n⏱ ${durationSec}s · 🔧 ${stats.toolCalls} · ≈${formatTokens(stats.totalTokens)} tokens`;
|
|
1425
|
+
const rejectionNote = stats.permissionRejections > 0
|
|
1426
|
+
? translate(`\n⚠️ ${stats.permissionRejections} 个操作被权限拒绝(可在项目 .opencode 配置放行,或对该项目开 auto_approve)`)
|
|
1427
|
+
: "";
|
|
1428
|
+
const answer = stats.lastText ? stats.lastText : translate("(本轮无文本回复)");
|
|
1429
|
+
const body = stats.lastText
|
|
1430
|
+
? `${truncate(stats.lastText)}${statsLine}${rejectionNote}`
|
|
1431
|
+
: `(本轮无文本回复)${statsLine}${rejectionNote}`;
|
|
1432
|
+
await this.sendCompletion(session, {
|
|
1433
|
+
answer,
|
|
1434
|
+
body,
|
|
1435
|
+
statsLine: statsLine.trim(),
|
|
1436
|
+
note: rejectionNote.trim(),
|
|
1437
|
+
});
|
|
1438
|
+
}
|
|
1439
|
+
dirSlotFor(dir) {
|
|
1440
|
+
let s = this.dirSlots.get(dir);
|
|
1441
|
+
if (!s) {
|
|
1442
|
+
s = { busy: false, waiters: [] };
|
|
1443
|
+
this.dirSlots.set(dir, s);
|
|
1444
|
+
}
|
|
1445
|
+
return s;
|
|
1446
|
+
}
|
|
1447
|
+
async acquireDir(dir) {
|
|
1448
|
+
const s = this.dirSlotFor(dir);
|
|
1449
|
+
if (!s.busy) {
|
|
1450
|
+
s.busy = true;
|
|
1451
|
+
return;
|
|
1452
|
+
}
|
|
1453
|
+
await new Promise((resolve) => s.waiters.push(resolve));
|
|
1454
|
+
}
|
|
1455
|
+
releaseDir(dir) {
|
|
1456
|
+
const s = this.dirSlotFor(dir);
|
|
1457
|
+
const next = s.waiters.shift();
|
|
1458
|
+
if (next) {
|
|
1459
|
+
next();
|
|
1460
|
+
return;
|
|
1461
|
+
}
|
|
1462
|
+
s.busy = false;
|
|
1463
|
+
}
|
|
1464
|
+
async composePromptWithAttachments(session, m, text) {
|
|
1465
|
+
const attachments = m.attachments ?? [];
|
|
1466
|
+
if (attachments.length === 0)
|
|
1467
|
+
return text;
|
|
1468
|
+
const download = this.deps.feishu.downloadMessageResource;
|
|
1469
|
+
const lines = [];
|
|
1470
|
+
for (const [index, attachment] of attachments.entries()) {
|
|
1471
|
+
if (!download) {
|
|
1472
|
+
lines.push(`[附件不可用] ${attachment.name}(当前未接下载能力)`);
|
|
1473
|
+
continue;
|
|
1474
|
+
}
|
|
1475
|
+
try {
|
|
1476
|
+
const resource = await download.call(this.deps.feishu, m.message_id, attachment.key, attachment.kind);
|
|
1477
|
+
if (resource.data.byteLength > MAX_ATTACHMENT_BYTES) {
|
|
1478
|
+
await this.replySafe(session.root_id, `⚠️ 附件 ${attachment.name} 超过 20MB,已跳过;可放到工作目录后把路径发给我。`);
|
|
1479
|
+
continue;
|
|
1480
|
+
}
|
|
1481
|
+
lines.push(`[附件] ${this.writeInboxFile(session.root_id, m.message_id, index, attachment, resource.data, resource.contentType)}`);
|
|
1482
|
+
}
|
|
1483
|
+
catch (e) {
|
|
1484
|
+
await this.replySafe(session.root_id, `⚠️ 附件 ${attachment.name} 下载失败:${toTaskingError(e).message}`);
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
if (lines.length === 0)
|
|
1488
|
+
return text === "" ? null : text;
|
|
1489
|
+
const head = text === "" ? "(用户发来附件,请读取下列文件后回答)" : text;
|
|
1490
|
+
return `${head}\n${lines.join("\n")}`;
|
|
1491
|
+
}
|
|
1492
|
+
writeInboxFile(rootId, messageId, index, attachment, data, contentType) {
|
|
1493
|
+
const dir = join(this.deps.config().workspace.root, "direct-inbox", rootId);
|
|
1494
|
+
mkdirSync(dir, { recursive: true });
|
|
1495
|
+
const named = extname(attachment.name) !== "" ? attachment.name : "";
|
|
1496
|
+
const ext = named === "" ? extensionFor(contentType, attachment.kind) : extname(named);
|
|
1497
|
+
const safe = named === "" ? "" : `-${basename(named).replace(/[^A-Za-z0-9._-]/g, "_")}`;
|
|
1498
|
+
const file = join(dir, `${messageId}-${index}${safe === "" ? ext : safe}`);
|
|
1499
|
+
writeFileSync(file, Buffer.from(data));
|
|
1500
|
+
return file;
|
|
1501
|
+
}
|
|
1502
|
+
async executeCollect(session) {
|
|
1503
|
+
const rt = this.runtimeFor(session.root_id);
|
|
1504
|
+
if (rt.collect === null) {
|
|
1505
|
+
rt.collect = [];
|
|
1506
|
+
this.armCollectTimer(session.root_id);
|
|
1507
|
+
}
|
|
1508
|
+
await this.replyInfoCard(session, this.collectCard(rt, session.root_id), "📥 已进入多消息收集模式:接下来的消息(含图片/文件)都会先收集,不立即执行。发完用 /send 合并提交为一轮;/cancel 丢弃;10 分钟无新消息会自动提交。");
|
|
1509
|
+
}
|
|
1510
|
+
async executeSend(session) {
|
|
1511
|
+
const rt = this.runtimeFor(session.root_id);
|
|
1512
|
+
const buffered = rt.collect;
|
|
1513
|
+
if (buffered === null) {
|
|
1514
|
+
await this.replyInfoCard(session, this.collectCard(rt, session.root_id), "当前不在收集模式。用 /collect 开始收集多条消息。");
|
|
1515
|
+
return;
|
|
1516
|
+
}
|
|
1517
|
+
this.clearCollect(session.root_id);
|
|
1518
|
+
if (buffered.length === 0) {
|
|
1519
|
+
await this.replySafe(session.root_id, "收集模式已关闭:没有待提交内容。");
|
|
1520
|
+
return;
|
|
1521
|
+
}
|
|
1522
|
+
await this.replySafe(session.root_id, `🚀 已提交 ${buffered.length} 条,合并为一轮执行。`);
|
|
1523
|
+
this.enqueueTurn(session.root_id, buffered.join("\n---\n"));
|
|
1524
|
+
}
|
|
1525
|
+
async executeCancel(session) {
|
|
1526
|
+
const rt = this.runtimeFor(session.root_id);
|
|
1527
|
+
const dropped = rt.collect;
|
|
1528
|
+
if (dropped === null) {
|
|
1529
|
+
await this.replyInfoCard(session, this.collectCard(rt, session.root_id), "当前不在收集模式。");
|
|
1530
|
+
return;
|
|
1531
|
+
}
|
|
1532
|
+
this.clearCollect(session.root_id);
|
|
1533
|
+
await this.replySafe(session.root_id, dropped.length === 0
|
|
1534
|
+
? "已退出收集模式。"
|
|
1535
|
+
: `🗑 已退出收集模式,丢弃 ${dropped.length} 条未提交消息。`);
|
|
1536
|
+
}
|
|
1537
|
+
armCollectTimer(rootId) {
|
|
1538
|
+
const rt = this.runtimeFor(rootId);
|
|
1539
|
+
if (rt.collectTimer)
|
|
1540
|
+
clearTimeout(rt.collectTimer);
|
|
1541
|
+
rt.collectTimer = setTimeout(() => {
|
|
1542
|
+
rt.collectTimer = null;
|
|
1543
|
+
void this.flushCollectOnTimeout(rootId);
|
|
1544
|
+
}, COLLECT_IDLE_TIMEOUT_MS);
|
|
1545
|
+
rt.collectTimer.unref?.();
|
|
1546
|
+
}
|
|
1547
|
+
clearCollect(rootId) {
|
|
1548
|
+
const rt = this.runtimeFor(rootId);
|
|
1549
|
+
rt.collect = null;
|
|
1550
|
+
if (rt.collectTimer) {
|
|
1551
|
+
clearTimeout(rt.collectTimer);
|
|
1552
|
+
rt.collectTimer = null;
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
async flushCollectOnTimeout(rootId) {
|
|
1556
|
+
const rt = this.runtimeFor(rootId);
|
|
1557
|
+
if (rt.collect === null)
|
|
1558
|
+
return;
|
|
1559
|
+
const buffered = rt.collect;
|
|
1560
|
+
this.clearCollect(rootId);
|
|
1561
|
+
if (buffered.length === 0)
|
|
1562
|
+
return;
|
|
1563
|
+
await this.replySafe(rootId, `⏰ 收集超时,已自动提交 ${buffered.length} 条为一轮。`);
|
|
1564
|
+
this.enqueueTurn(rootId, buffered.join("\n---\n"));
|
|
1565
|
+
}
|
|
1566
|
+
async executeName(session, text) {
|
|
1567
|
+
const name = text.slice("/name".length).trim().replace(/\s+/g, " ");
|
|
1568
|
+
if (name === "") {
|
|
1569
|
+
await this.replySafe(session.root_id, `当前会话名:${session.name ?? translate("(未设置)")}\n用法:/name <文本>(同时用于卡片头部与 TUI 区块)`);
|
|
1570
|
+
return;
|
|
1571
|
+
}
|
|
1572
|
+
const trimmed = name.slice(0, 80);
|
|
1573
|
+
this.deps.store.updateDirectSession(session.root_id, { name: trimmed });
|
|
1574
|
+
await this.replySafe(session.root_id, `已将会话名改为「${trimmed}」。`);
|
|
1575
|
+
}
|
|
1576
|
+
async executeNew(session) {
|
|
1577
|
+
this.deps.store.updateDirectSession(session.root_id, { session_id: null, last_prompt: null });
|
|
1578
|
+
await this.cleanupSession(session);
|
|
1579
|
+
await this.replySafe(session.root_id, "🆕 已开启新会话:上下文已清空(话题、目录与名称不变),旧 opencode 会话已删除。");
|
|
1580
|
+
}
|
|
1581
|
+
async executeAuto(session, text) {
|
|
1582
|
+
const rt = this.runtimeFor(session.root_id);
|
|
1583
|
+
const arg = text.slice("/auto".length).trim().toLowerCase();
|
|
1584
|
+
if (arg === "") {
|
|
1585
|
+
await this.replyInfoCard(session, this.autoCard(session, rt), this.renderAutoStatus(session, rt));
|
|
1586
|
+
return;
|
|
1587
|
+
}
|
|
1588
|
+
const result = this.applyAutoArg(session, rt, arg);
|
|
1589
|
+
await this.replySafe(session.root_id, result.text);
|
|
1590
|
+
}
|
|
1591
|
+
renderAutoStatus(session, rt) {
|
|
1592
|
+
const postureNow = this.autoPostureOf(session, rt);
|
|
1593
|
+
const current = postureNow === "on"
|
|
1594
|
+
? "🔓 本会话放开"
|
|
1595
|
+
: postureNow === "once"
|
|
1596
|
+
? "⚡ 仅下一轮放开"
|
|
1597
|
+
: "🔒 默认(不传 --auto)";
|
|
1598
|
+
return [
|
|
1599
|
+
`当前权限姿态:${current}`,
|
|
1600
|
+
this.autoSourceLabel(session),
|
|
1601
|
+
"用法:/auto on|/auto once|/auto off|/auto reset",
|
|
1602
|
+
].join("\n");
|
|
1603
|
+
}
|
|
1604
|
+
autoSourceLabel(session) {
|
|
1605
|
+
const direct = this.deps.config().feishu.direct;
|
|
1606
|
+
const entry = session.project === null ? null : direct.projects[session.project];
|
|
1607
|
+
const projectValue = entry?.auto_approve ?? null;
|
|
1608
|
+
const source = projectValue !== null ? translate(`项目条目「${session.project}」`) : translate("全局配置");
|
|
1609
|
+
const effective = this.resolveAutoApprove(session.project ?? "", false, direct);
|
|
1610
|
+
return `(会话未覆盖时按${source}:${effective ? translate("放开") : translate("默认")})`;
|
|
1611
|
+
}
|
|
1612
|
+
async executeAgent(session, text) {
|
|
1613
|
+
const config = this.deps.config();
|
|
1614
|
+
const arg = text.slice("/agent".length).trim();
|
|
1615
|
+
if (arg === "") {
|
|
1616
|
+
const catalog = config.opencode.agents ?? [];
|
|
1617
|
+
const lines = [
|
|
1618
|
+
`当前 agent:${session.agent_override ?? config.opencode.agent}${session.agent_override === null ? translate("(配置默认)") : translate("(会话覆盖)")}`,
|
|
1619
|
+
];
|
|
1620
|
+
if (catalog.length > 0)
|
|
1621
|
+
lines.push(`可用:${catalog.join(", ")}`);
|
|
1622
|
+
lines.push("用法:/agent <name>|/agent reset");
|
|
1623
|
+
await this.replyInfoCard(session, buildInfoCard({ title: "🧠 Agent", lines }), lines.join("\n"));
|
|
1624
|
+
return;
|
|
1625
|
+
}
|
|
1626
|
+
if (arg === "reset") {
|
|
1627
|
+
this.deps.store.updateDirectSession(session.root_id, { agent_override: null });
|
|
1628
|
+
await this.replySafe(session.root_id, `已恢复配置默认 agent:${config.opencode.agent}(下一轮生效)。`);
|
|
1629
|
+
return;
|
|
1630
|
+
}
|
|
1631
|
+
const name = arg.split(/\s+/)[0] ?? "";
|
|
1632
|
+
const catalog = config.opencode.agents ?? [];
|
|
1633
|
+
if (catalog.length > 0 && !catalog.includes(name)) {
|
|
1634
|
+
await this.replySafe(session.root_id, `⚠️ 未知 agent "${name}"。可用:${catalog.join(", ")}`);
|
|
1635
|
+
return;
|
|
1636
|
+
}
|
|
1637
|
+
this.deps.store.updateDirectSession(session.root_id, { agent_override: name });
|
|
1638
|
+
await this.replySafe(session.root_id, `已切换 agent 为 ${name}(下一轮生效)。/agent reset 恢复默认。`);
|
|
1639
|
+
}
|
|
1640
|
+
async executeModel(session, text) {
|
|
1641
|
+
const config = this.deps.config();
|
|
1642
|
+
const arg = text.slice("/model".length).trim();
|
|
1643
|
+
if (arg === "") {
|
|
1644
|
+
const lines = [
|
|
1645
|
+
`当前 model:${session.model_override ?? config.opencode.model ?? translate("(未设置)")}${session.model_override === null ? translate("(配置默认)") : translate("(会话覆盖)")}`,
|
|
1646
|
+
"用法:/model <name>|/model reset",
|
|
1647
|
+
];
|
|
1648
|
+
await this.replyInfoCard(session, buildInfoCard({ title: "🤖 Model", lines }), lines.join("\n"));
|
|
1649
|
+
return;
|
|
1650
|
+
}
|
|
1651
|
+
if (arg === "reset") {
|
|
1652
|
+
this.deps.store.updateDirectSession(session.root_id, { model_override: null });
|
|
1653
|
+
await this.replySafe(session.root_id, `已恢复配置默认 model:${config.opencode.model ?? translate("(未设置)")}(下一轮生效)。`);
|
|
1654
|
+
return;
|
|
1655
|
+
}
|
|
1656
|
+
this.deps.store.updateDirectSession(session.root_id, { model_override: arg });
|
|
1657
|
+
await this.replySafe(session.root_id, `已切换 model 为 ${arg}(下一轮生效)。/model reset 恢复默认。`);
|
|
1658
|
+
}
|
|
1659
|
+
async replyStatus(session) {
|
|
1660
|
+
const config = this.deps.config();
|
|
1661
|
+
const rt = this.runtimeFor(session.root_id);
|
|
1662
|
+
const postureNow = this.autoPostureOf(session, rt);
|
|
1663
|
+
const posture = postureNow === "on"
|
|
1664
|
+
? translate("🔓 本会话放开")
|
|
1665
|
+
: postureNow === "once"
|
|
1666
|
+
? translate("⚡ 仅下一轮放开")
|
|
1667
|
+
: translate("🔒 默认");
|
|
1668
|
+
const idleSec = Math.max(0, Math.round((Date.now() - session.updated_at) / 1000));
|
|
1669
|
+
const answer = [
|
|
1670
|
+
"**会话状态**",
|
|
1671
|
+
`- 目录:\`${session.path}\``,
|
|
1672
|
+
`- session:${session.session_id ?? translate("(未开始)")}`,
|
|
1673
|
+
`- agent:${session.agent_override ?? config.opencode.agent}${session.agent_override === null ? "" : translate("(会话覆盖)")}`,
|
|
1674
|
+
`- model:${session.model_override ?? config.opencode.model ?? translate("(未设置)")}${session.agent_override === null ? "" : translate("(会话覆盖)")}`,
|
|
1675
|
+
`- 权限姿态:${posture}`,
|
|
1676
|
+
`- turns:${session.turns} · tokens:≈${formatTokens(session.total_tokens)}`,
|
|
1677
|
+
`- 排队:${rt.queue.length}${rt.turnInFlight ? translate(" · 运行中") : ""} · 距上次活动:${idleSec}s`,
|
|
1678
|
+
...(rt.collect === null ? [] : [`- 收集模式:📥 ${rt.collect.length} 条待提交`]),
|
|
1679
|
+
].join("\n");
|
|
1680
|
+
const replyCard = this.deps.feishu.replyCardInThread;
|
|
1681
|
+
if (replyCard) {
|
|
1682
|
+
try {
|
|
1683
|
+
await replyCard.call(this.deps.feishu, session.root_id, buildCompletionCard({ answer, statsLine: "", note: "" }));
|
|
1684
|
+
return;
|
|
1685
|
+
}
|
|
1686
|
+
catch (e) {
|
|
1687
|
+
this.deps.logger.warn("direct status card failed; falling back to text", {
|
|
1688
|
+
root_id: session.root_id,
|
|
1689
|
+
error: toTaskingError(e).message,
|
|
1690
|
+
});
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
await this.replySafe(session.root_id, answer);
|
|
1694
|
+
}
|
|
1695
|
+
async executeDone(session, operator) {
|
|
1696
|
+
const rt = this.runtimeFor(session.root_id);
|
|
1697
|
+
const queued = rt.queue.length;
|
|
1698
|
+
rt.queue = [];
|
|
1699
|
+
if (rt.abort) {
|
|
1700
|
+
rt.stopRequested = true;
|
|
1701
|
+
rt.abort.abort();
|
|
1702
|
+
}
|
|
1703
|
+
this.deps.store.markDirectSessionStatus(session.root_id, "done");
|
|
1704
|
+
await this.sealCurrentCard(session.root_id);
|
|
1705
|
+
const statsLine = session.turns > 0
|
|
1706
|
+
? translate(`(本次运行统计:${session.turns} turn${session.turns === 1 ? "" : "s"} · ≈${formatTokens(session.total_tokens)} tokens)`)
|
|
1707
|
+
: "";
|
|
1708
|
+
const who = operator ? translate(`(操作人:${operator})`) : "";
|
|
1709
|
+
const discardNote = queued > 0 ? translate(`(已丢弃 ${queued} 条排队消息)`) : "";
|
|
1710
|
+
await this.replySafe(session.root_id, `✅ 会话已结束。${statsLine}${who}${discardNote}重新发起请 /chat <项目|路径> <消息>`);
|
|
1711
|
+
await this.cleanupSession(session);
|
|
1712
|
+
}
|
|
1713
|
+
async executeStop(session, operator) {
|
|
1714
|
+
const rt = this.runtimeFor(session.root_id);
|
|
1715
|
+
const queued = rt.queue.length;
|
|
1716
|
+
rt.queue = [];
|
|
1717
|
+
if (rt.turnInFlight && rt.abort) {
|
|
1718
|
+
this.beginInterrupt(session, rt);
|
|
1719
|
+
await this.finalizeCardPhase(session.root_id, "interrupted");
|
|
1720
|
+
await this.announceInterrupt(session.root_id, queued, operator);
|
|
1721
|
+
return;
|
|
1722
|
+
}
|
|
1723
|
+
if (queued > 0) {
|
|
1724
|
+
this.deps.store.markDirectSessionStatus(session.root_id, "idle");
|
|
1725
|
+
await this.replySafe(session.root_id, `🛑 已清空 ${queued} 条排队消息(当前无运行中任务)。`);
|
|
1726
|
+
return;
|
|
1727
|
+
}
|
|
1728
|
+
await this.replySafe(session.root_id, "ℹ️ 当前没有运行中的任务。");
|
|
1729
|
+
}
|
|
1730
|
+
async sweepThreads() {
|
|
1731
|
+
if (!this.running)
|
|
1732
|
+
return;
|
|
1733
|
+
const listFn = this.deps.feishu.listThreadReplies;
|
|
1734
|
+
if (!listFn)
|
|
1735
|
+
return;
|
|
1736
|
+
const active = this.deps.store.listActiveDirectSessions();
|
|
1737
|
+
for (const s of active) {
|
|
1738
|
+
if (!this.running)
|
|
1739
|
+
return;
|
|
1740
|
+
if (!s.thread_id)
|
|
1741
|
+
continue;
|
|
1742
|
+
let messages;
|
|
1743
|
+
try {
|
|
1744
|
+
messages = await listFn.call(this.deps.feishu, s.thread_id, s.last_msg_id);
|
|
1745
|
+
}
|
|
1746
|
+
catch (e) {
|
|
1747
|
+
this.deps.logger.debug("direct sweep thread fetch failed", {
|
|
1748
|
+
root_id: s.root_id,
|
|
1749
|
+
error: toTaskingError(e).message,
|
|
1750
|
+
});
|
|
1751
|
+
continue;
|
|
1752
|
+
}
|
|
1753
|
+
for (const m of messages) {
|
|
1754
|
+
if (!this.running)
|
|
1755
|
+
return;
|
|
1756
|
+
if (m.root_id !== s.root_id)
|
|
1757
|
+
continue;
|
|
1758
|
+
if (m.message_id === s.root_id)
|
|
1759
|
+
continue;
|
|
1760
|
+
await this.handleThreadMessage(m);
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
async replySafe(rootId, text) {
|
|
1765
|
+
try {
|
|
1766
|
+
const r = await this.deps.feishu.replyInThread(rootId, text);
|
|
1767
|
+
if (r.thread_id) {
|
|
1768
|
+
this.deps.store.updateDirectSession(rootId, { thread_id: r.thread_id });
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
catch (e) {
|
|
1772
|
+
this.deps.logger.warn("direct reply failed", {
|
|
1773
|
+
root_id: rootId,
|
|
1774
|
+
error: toTaskingError(e).message,
|
|
1775
|
+
});
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
function fullDetailBytes(detail) {
|
|
1780
|
+
return (Buffer.byteLength(detail.output ?? "", "utf8") +
|
|
1781
|
+
Buffer.byteLength(detail.title ?? "", "utf8") +
|
|
1782
|
+
Buffer.byteLength(detail.input === undefined ? "" : JSON.stringify(detail.input), "utf8"));
|
|
1783
|
+
}
|
|
1784
|
+
function fullDetailFileName(turn) {
|
|
1785
|
+
return `direct-turn-${turn}.md`;
|
|
1786
|
+
}
|
|
1787
|
+
function renderFullDetail(session, turn, details, dropped) {
|
|
1788
|
+
const lines = [
|
|
1789
|
+
`# ${session.name ?? session.path} · Turn ${turn?.turn ?? "?"}`,
|
|
1790
|
+
"",
|
|
1791
|
+
`- directory: \`${session.path}\``,
|
|
1792
|
+
`- tools: ${turn?.toolCalls ?? details.length}`,
|
|
1793
|
+
];
|
|
1794
|
+
if (dropped > 0)
|
|
1795
|
+
lines.push(`- ${dropped} 个更早的工具调用明细因体积过大未包含`);
|
|
1796
|
+
for (const [index, detail] of details.entries()) {
|
|
1797
|
+
const failed = detail.exit !== undefined && detail.exit !== 0;
|
|
1798
|
+
const heading = `## ${index + 1}. ${failed ? "✗" : "🔧"} ${detail.tool}${detail.title === undefined ? "" : ` · ${detail.title}`}`;
|
|
1799
|
+
lines.push("", heading);
|
|
1800
|
+
const status = detail.status ?? "completed";
|
|
1801
|
+
const exit = detail.exit !== undefined ? ` (exit ${detail.exit})` : "";
|
|
1802
|
+
const duration = detail.durationMs !== undefined ? ` · ${detail.durationMs}ms` : "";
|
|
1803
|
+
lines.push(`Status: ${status}${exit}${duration}`);
|
|
1804
|
+
if (typeof detail.input?.command === "string") {
|
|
1805
|
+
lines.push("", "```bash", detail.input.command, "```");
|
|
1806
|
+
}
|
|
1807
|
+
else if (detail.input !== undefined) {
|
|
1808
|
+
lines.push("", "```json", JSON.stringify(detail.input, null, 2), "```");
|
|
1809
|
+
}
|
|
1810
|
+
if (detail.output !== undefined) {
|
|
1811
|
+
lines.push("", "```", detail.output.trim() === "" ? "(no output)" : detail.output, "```");
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
return lines.join("\n");
|
|
1815
|
+
}
|
|
1816
|
+
function extensionFor(contentType, kind) {
|
|
1817
|
+
const type = (contentType ?? "").split(";")[0]?.trim() ?? "";
|
|
1818
|
+
const map = {
|
|
1819
|
+
"image/png": ".png",
|
|
1820
|
+
"image/jpeg": ".jpg",
|
|
1821
|
+
"image/gif": ".gif",
|
|
1822
|
+
"image/webp": ".webp",
|
|
1823
|
+
"application/pdf": ".pdf",
|
|
1824
|
+
"text/plain": ".txt",
|
|
1825
|
+
"application/zip": ".zip",
|
|
1826
|
+
};
|
|
1827
|
+
return map[type] ?? (kind === "image" ? ".png" : ".bin");
|
|
1828
|
+
}
|
|
1829
|
+
function sessionName(message) {
|
|
1830
|
+
return message.replace(/\s+/g, " ").trim().slice(0, 80);
|
|
1831
|
+
}
|
|
1832
|
+
function truncate(text, max = MAX_MESSAGE_CHARS) {
|
|
1833
|
+
if (text.length <= max)
|
|
1834
|
+
return text;
|
|
1835
|
+
return `${text.slice(0, max)}\n…(已截断)`;
|
|
1836
|
+
}
|
|
1837
|
+
function renderChatHelp(scope) {
|
|
1838
|
+
if (scope === "intake") {
|
|
1839
|
+
return [
|
|
1840
|
+
"直连会话用法:",
|
|
1841
|
+
"/chat <项目名|绝对路径> <消息> 在指定目录创建 opencode 会话",
|
|
1842
|
+
"/chat 列出可用项目",
|
|
1843
|
+
"会话创建后:在本话题内直接回复即续聊;/stop 中断当前任务;/done 结束会话",
|
|
1844
|
+
].join("\n");
|
|
1845
|
+
}
|
|
1846
|
+
return [
|
|
1847
|
+
"直连会话用法:",
|
|
1848
|
+
"直接回复本话题 → 继续与 agent 对话(排队串行执行)",
|
|
1849
|
+
"直接发图片/文件 → 下载到工作区并把路径交给 agent",
|
|
1850
|
+
"/collect → 进入多消息收集模式(发完用 /send 提交为一轮,/cancel 丢弃)",
|
|
1851
|
+
"/auto [on|once|off] → 查看/切换本会话权限姿态(下一轮生效)",
|
|
1852
|
+
"/name <文本> → 给本会话改名(卡片头部与 TUI 显示)",
|
|
1853
|
+
"/agent <name> → 切换本会话 agent(/agent reset 恢复)",
|
|
1854
|
+
"/model <name> → 切换本会话 model(/model reset 恢复)",
|
|
1855
|
+
"/new → 清空上下文开启新会话",
|
|
1856
|
+
"/status → 查看会话状态",
|
|
1857
|
+
"/stop → 中断当前任务(含清空排队消息)",
|
|
1858
|
+
"/done → 结束会话",
|
|
1859
|
+
"新建其他会话 → 在群里 /chat <项目|路径> <消息>",
|
|
1860
|
+
].join("\n");
|
|
1861
|
+
}
|
|
1862
|
+
//# sourceMappingURL=manager.js.map
|