ai_co_discuss 0.4.13 → 0.4.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/.agents/skills/discuss-host/SKILL.md +42 -42
- package/.agents/skills/workflow-creator/SKILL.md +155 -155
- package/.agents/skills/workflow-creator/references/model-selection.md +24 -23
- package/backend/free_room.py +15 -8
- package/backend/schema.sql +3 -1
- package/backend/server.py +146 -17
- package/docs/THIRD_PARTY_NOTICES.md +721 -1
- package/docs/runner.md +4 -2
- package/docs/workflow.md +1 -1
- package/package.json +10 -3
- package/runner/adapters/api.mjs +33 -7
- package/runner/adapters/api_files.mjs +21 -0
- package/runner/adapters/api_images.mjs +245 -0
- package/runner/adapters/index.mjs +186 -186
- package/runner/adapters/profiles.mjs +152 -139
- package/runner/discussion_launch.mjs +49 -11
- package/runner/free_runner.mjs +1286 -1281
- package/runner/project_files.mjs +390 -330
- package/runner/relay_channel.mjs +326 -325
- package/runner/remote_launch.mjs +2 -2
- package/runner/stt.mjs +135 -111
- package/runner/tts.mjs +180 -172
- package/runner/tts_providers.mjs +479 -435
- package/runner/workflows.mjs +606 -606
- package/web/app.js +82 -12
- package/web/backup.js +1 -1
- package/web/markdown.css +1 -1
- package/web/modern.css +1 -1
- package/web/modern.js +663 -40
- package/web/office/assets/pptx-source-worker-559Vl2R3.mjs +446 -0
- package/web/office/assets/pptx_parser_bg-DON650C_.wasm +0 -0
- package/web/office/assets/render-worker-Ck21oePL-D_L2C4am.js +16 -0
- package/web/office/chunks/comment-ui-runtime-Bp37ytDC-CEDIeFBy.js +125 -0
- package/web/office/chunks/emf--QWY-UlT-D7lCNost.js +1 -0
- package/web/office/chunks/font-preload-demand-NqcVKIpX-_QhVEaPJ.js +1 -0
- package/web/office/chunks/plot-area-frame-DNYMd9Pf-B0ScWz_J.js +2 -0
- package/web/office/chunks/pptx-DbjWegUB-CU8ZIJEP.js +4 -0
- package/web/office/chunks/presentation-model-source-DLNioq7T-Demo5cCW.js +1 -0
- package/web/office/chunks/render-worker-host-CVr53kg0-DUcW76F6.js +1 -0
- package/web/office/chunks/slide-pull-client-3g6TxaKa-BohMnKOC.js +12 -0
- package/web/office/chunks/worker-source-ZQE9C1j6-B31UTbq3.js +1 -0
- package/web/office/docx.js +21 -0
- package/web/office/pptx.js +1 -0
- package/web/office/xlsx.js +64 -0
package/runner/free_runner.mjs
CHANGED
|
@@ -1,1281 +1,1286 @@
|
|
|
1
|
-
/** Free-room delivery: one live execution per member, carrying all of that member's open requests. */
|
|
2
|
-
import { spawnSync } from 'node:child_process';
|
|
3
|
-
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
-
import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from 'node:fs';
|
|
5
|
-
import { basename, join, resolve } from 'node:path';
|
|
6
|
-
import { adapter_of, BRANCHABLE_ADAPTERS, branch_session, capabilities_of, cleanup_room, deliver_task, delivery_receipt, session_exists, stored_delivery } from './adapters/index.mjs';
|
|
7
|
-
import { api, overlapping_directories, read_rule } from './discussion_runner.mjs';
|
|
8
|
-
import { SegmentLog } from './execution_progress.mjs';
|
|
9
|
-
import { free_task_text, TASK_SUBCOMMANDS, with_expert_prompt } from './expert_prompts.mjs';
|
|
10
|
-
import { atomic_json } from './files.mjs';
|
|
11
|
-
import { outside_directory, room_directories } from './project_files.mjs';
|
|
12
|
-
import { SessionDriver } from './session_driver.mjs';
|
|
13
|
-
import { effective_profile, load_room_workflow, workflow_in_use, workflow_task_field } from './workflows.mjs';
|
|
14
|
-
import { DEFAULT_SCHEDULER_MODE, GOAL_PROMPT_VERSION, decide_goal_wake, decide_sequence_checkpoint, REVIEW_CONFIDENCE, REVIEW_PROMPT_VERSION, SEQUENCE_CONFIDENCE, SEQUENCE_PROMPT_VERSION, ROUTE_CONFIDENCE, ROUTE_CONTEXT_MESSAGES, decide_review_completion, route_free_message, route_prompt_version, scheduler_thresholds, some_members } from './scheduler.mjs';
|
|
15
|
-
|
|
16
|
-
const PACKAGE_VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
17
|
-
const RENEW_MS = 30_000;
|
|
18
|
-
/** A changed phase is reported early, but no more often than this, since each report refreshes open pages. */
|
|
19
|
-
const ACTIVITY_REPORT_MS = 10_000;
|
|
20
|
-
/** Segments and progress notes are reported quietly, waking no page, so they may go every tick. */
|
|
21
|
-
const PROGRESS_REPORT_MS = 2_000;
|
|
22
|
-
const MAX_DELIVERY_ATTEMPTS = 3;
|
|
23
|
-
// An idle room under an active goal waits this long before the host is woken, leaving the owner time to speak first.
|
|
24
|
-
// Fallback when the room's goal does not carry its own idle wait (older website).
|
|
25
|
-
export const GOAL_IDLE_MS = 120_000;
|
|
26
|
-
// A goal waiting on the owner reaches their Weixin only after this long: right after the question they may be typing.
|
|
27
|
-
export const PENDING_NOTICE_MS = 5 * 60_000;
|
|
28
|
-
// A failed Weixin notice is tried again after this long instead of on every tick.
|
|
29
|
-
const NOTICE_RETRY_MS = 60_000;
|
|
30
|
-
// Without the host's note, the notice quotes the room's latest message, up to this many characters.
|
|
31
|
-
const NOTICE_EXCERPT = 300;
|
|
32
|
-
// A manual member's session that refuses a delivery is retried in the same execution, after a wait the owner can cut short.
|
|
33
|
-
const MAX_DELIVERY_RETRIES = 3;
|
|
34
|
-
const RETRY_DELAY_SECONDS = 60;
|
|
35
|
-
// The cause is gone once the restarted runner is back, so its retry needs no long wait.
|
|
36
|
-
const RESTART_RETRY_DELAY_SECONDS = 5;
|
|
37
|
-
// The retry reason the site keeps for an execution a runner restart cut off; its redelivery asks to continue.
|
|
38
|
-
const RESTART_REASON = '本机接入程序重启或异常退出,这次执行的软件进程已结束,未提交回答';
|
|
39
|
-
const MAX_RETRY_REASON = 500;
|
|
40
|
-
const LIVE = ['reserving', 'delivering', 'sidecar_pending', 'running', 'retry_wait'];
|
|
41
|
-
// The longest private chat reply the site keeps.
|
|
42
|
-
const CHAT_REPLY_LIMIT = 20000;
|
|
43
|
-
const MAX_HASHED_BYTES = 5 * 1024 * 1024;
|
|
44
|
-
const GIT_TIMEOUT_MS = 15_000;
|
|
45
|
-
|
|
46
|
-
/** Fingerprint configurations whose adapter can enforce project read-only access; no local paths leave this function. */
|
|
47
|
-
export function review_capability_version(profile, member, config) {
|
|
48
|
-
if (!profile || profile.project_access !== 'read' || member.access !== 'runner' || member.session_mode !== 'new'
|
|
49
|
-
|| !capabilities_of(profile.adapter).enforces_read_only || profile.adapter !== member.adapter
|
|
50
|
-
|| !profile.cwd || profile.allowed_tools?.length) return '';
|
|
51
|
-
const project = cwd_key(profile.cwd), drafts = cwd_key(config.draft_directory || `${config.directory}-drafts`);
|
|
52
|
-
if (drafts === project || drafts.startsWith(`${project}/`)) return '';
|
|
53
|
-
const facts = [1, profile.adapter, profile.executable || '', cwd_key(profile.cwd), cwd_key(profile.workdir),
|
|
54
|
-
profile.project_id || '', profile.project_name || '', profile.session_id || '', drafts,
|
|
55
|
-
cwd_key(config.directory)];
|
|
56
|
-
return createHash('sha256').update(JSON.stringify(facts)).digest('hex');
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/** Whether a process with this pid exists; signal 0 only checks, and EPERM means it exists under another user. */
|
|
60
|
-
function process_alive(pid) {
|
|
61
|
-
try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/** Identify a working directory consistently, so executions in the same cwd can be compared. */
|
|
65
|
-
export function cwd_key(directory) {
|
|
66
|
-
if (!directory) return '';
|
|
67
|
-
const path = resolve(directory).replaceAll('\\', '/');
|
|
68
|
-
return process.platform === 'win32' ? path.toLowerCase() : path;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Record each changed or untracked file's Git status and content hash in a Git working tree.
|
|
73
|
-
* Returns null outside Git: free rooms then provide no automatic overlap detection.
|
|
74
|
-
*/
|
|
75
|
-
export function workspace_snapshot(directory) {
|
|
76
|
-
if (!directory) return null;
|
|
77
|
-
const result = spawnSync('git', ['-C', directory, 'status', '--porcelain=v1', '-z', '--untracked-files=all'],
|
|
78
|
-
{ encoding: 'utf8', windowsHide: true, timeout: GIT_TIMEOUT_MS });
|
|
79
|
-
if (result.status !== 0) return null;
|
|
80
|
-
const entries = new Map();
|
|
81
|
-
const fields = result.stdout.split('\0').filter(Boolean);
|
|
82
|
-
for (let index = 0; index < fields.length; index++) {
|
|
83
|
-
const status = fields[index].slice(0, 2), path = fields[index].slice(3);
|
|
84
|
-
if (status[0] === 'R' || status[0] === 'C') index++; // The original path of a rename follows.
|
|
85
|
-
let content = 'missing';
|
|
86
|
-
try {
|
|
87
|
-
const file = join(directory, path);
|
|
88
|
-
const size = statSync(file).size;
|
|
89
|
-
content = size > MAX_HASHED_BYTES ? `size:${size}` : createHash('sha256').update(readFileSync(file)).digest('hex');
|
|
90
|
-
} catch { /* Deleted files keep the marker. */ }
|
|
91
|
-
entries.set(path, `${status}:${content}`);
|
|
92
|
-
}
|
|
93
|
-
return entries;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/** Paths whose status or content differ between two snapshots of one working tree. */
|
|
97
|
-
export function changed_between(before, after) {
|
|
98
|
-
const paths = new Set([...before.keys(), ...after.keys()]);
|
|
99
|
-
return [...paths].filter(path => before.get(path) !== after.get(path)).sort();
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* The changed paths (relative, as git lists them) that the agent edited with its own tools, given the paths those tools
|
|
104
|
-
* named (absolute or relative to the working directory). Matched by path suffix, so a working directory below the
|
|
105
|
-
* repository root still matches; Windows paths compare case-insensitively.
|
|
106
|
-
*/
|
|
107
|
-
export function edited_changes(changes, claimed, platform = process.platform) {
|
|
108
|
-
const normal = path => {
|
|
109
|
-
const text = `/${String(path).replaceAll('\\', '/').replace(/^\.\//, '')}`;
|
|
110
|
-
return platform === 'win32' ? text.toLowerCase() : text;
|
|
111
|
-
};
|
|
112
|
-
const named = [...claimed].map(normal);
|
|
113
|
-
return changes.filter(path => named.some(item => item.endsWith(normal(path))));
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* The room's project directories a member works with besides its own cwd, each `{path, access}`: a member working in
|
|
118
|
-
* the room's project gets the others at its own project access (read or write); a member working outside them gets
|
|
119
|
-
* them all read-only. Software without project files gets none, and a folder gone from this computer is left out.
|
|
120
|
-
*/
|
|
121
|
-
export function member_extra_directories(config, profile) {
|
|
122
|
-
if (!profile || !capabilities_of(profile.adapter).project) return [];
|
|
123
|
-
// '' marks a member that joined before the room had a project: it reaches every room directory at its own access.
|
|
124
|
-
const cwd = profile.cwd ?? config.cwd;
|
|
125
|
-
const access = outside_directory(config, profile) || profile.project_access === 'read' ? 'read' : 'write';
|
|
126
|
-
return room_directories(config).filter(path => !(cwd && overlapping_directories(path, cwd)) && existsSync(path))
|
|
127
|
-
.map(path => ({ path, access }));
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
/** A changed path in an extra directory, reported in full so it cannot be mistaken for one in the main directory. */
|
|
131
|
-
function extra_change(directory, path) {
|
|
132
|
-
return `${cwd_key(directory)}/${path}`;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/** Write a non-secret task and a member-only credential file for one execution. */
|
|
136
|
-
export function free_task_files(config, member, execution, binding, { session = null, suggestions = [], reviews = [], stopped = [], process_access = true,
|
|
137
|
-
workflow = null, room_members = [], goal = null } = {}) {
|
|
138
|
-
const id = `free-${execution.id}`;
|
|
139
|
-
const draft_directory = config.draft_directory || `${config.directory}-drafts`;
|
|
140
|
-
mkdirSync(draft_directory, { recursive: true });
|
|
141
|
-
const access_path = join(config.directory, `${id}.access.json`);
|
|
142
|
-
const task_path = join(config.directory, `${id}.task.json`);
|
|
143
|
-
// A workflow member's prompt is read from its card for this execution; everything else stays the room's setting.
|
|
144
|
-
const profile = effective_profile(config.participants[member.name], member.name, workflow);
|
|
145
|
-
// The host sees the workflow only while its members are here: sending them away ends it.
|
|
146
|
-
const host_workflow = member.role === 'host' && workflow && !workflow.error && workflow_in_use(workflow, room_members) ? workflow : null;
|
|
147
|
-
atomic_json(access_path, { site: config.site, room: config.room, member: member.name, token: config.members[member.name].token,
|
|
148
|
-
session_id: binding.session_id || '', execution_id: execution.id });
|
|
149
|
-
const adapter = adapter_of(profile.adapter);
|
|
150
|
-
const extra_directories = member_extra_directories(config, profile);
|
|
151
|
-
const cli = process.platform === 'win32' ? adapter?.windows_command || 'codiscuss.cmd' : 'codiscuss';
|
|
152
|
-
const inbox = Boolean(adapter?.into_window?.(profile, binding));
|
|
153
|
-
const bound_access = process_access && !inbox && Boolean(adapter?.capabilities.access_env);
|
|
154
|
-
const messages = execution.requests.map(item => `#${item.message_id}`).join('、');
|
|
155
|
-
const requests = execution.requests || [];
|
|
156
|
-
const discussion_request = requests.find(item => item.session_request_id && ['discuss', 'discuss_host'].includes(item.purpose)) || null;
|
|
157
|
-
const direct_question = Boolean(session?.status === 'active' && requests.some(item => item.purpose === 'ask'));
|
|
158
|
-
const { instructions, prompt } = free_task_text({ name: member.label || member.name, role: member.role, discussion: direct_question,
|
|
159
|
-
discussion_request, profile, cli,
|
|
160
|
-
room: config.room, messages, read_after: execution.read_until, execution_id: execution.id, task_path,
|
|
161
|
-
access_file: bound_access ? '' : access_path, read_rule: read_rule(profile.adapter), inbox, extra_directories });
|
|
162
|
-
const skills = discussion_request || direct_question
|
|
163
|
-
? ['discuss-participant/SKILL.md', 'discuss-session/SKILL.md',
|
|
164
|
-
...member.role === 'host' ? ['discuss-host/SKILL.md', 'discuss-session/references/host.md'] : [],
|
|
165
|
-
...direct_question ? ['discuss-participant/references/room.md'] : []]
|
|
166
|
-
: ['discuss-participant/SKILL.md', 'discuss-participant/references/room.md',
|
|
167
|
-
...member.role === 'host' ? ['discuss-host/SKILL.md', 'discuss-host/references/room.md'] : []];
|
|
168
|
-
// The host works a goal while it is open, and also handles the request that opens it or the wrap-up after it ends.
|
|
169
|
-
const goal_task = member.role === 'host' && (['active', 'paused'].includes(goal?.status)
|
|
170
|
-
|| requests.some(item => ['goal_start', 'goal_continue'].includes(item.purpose)));
|
|
171
|
-
if (goal_task) skills.push('discuss-goal/SKILL.md');
|
|
172
|
-
const goal_field = goal_task && goal ? { id: goal.id, objective: goal.objective, status: goal.status, continues: goal.continues,
|
|
173
|
-
max_continues: goal.max_continues, elapsed_seconds: goal.elapsed_seconds, max_minutes: goal.max_minutes,
|
|
174
|
-
phase: goal.phase ?? 'doing', ...(goal.phase_note ? { phase_note: goal.phase_note } : {}) } : null;
|
|
175
|
-
const skills_directory = join(config.project, '.agents', 'skills');
|
|
176
|
-
const workflow_field = host_workflow ? workflow_task_field(host_workflow, room_members, config.participants) : null;
|
|
177
|
-
atomic_json(task_path, { site: config.site, room: config.room, mode: 'free', member: member.name,
|
|
178
|
-
execution_id: execution.id, requests, request_messages: execution.requests.map(item => item.message_id),
|
|
179
|
-
request_purposes: execution.requests.map(item => item.purpose || 'ask'),
|
|
180
|
-
...(discussion_request ? { discussion_request } : {}),
|
|
181
|
-
...(session ? { session: { id: session.id, status: session.status, phase: session.phase,
|
|
182
|
-
goal: session.goal, named_followup: session.named_followup } } : {}),
|
|
183
|
-
...(suggestions.length ? { scheduler_suggestions: suggestions } : {}),
|
|
184
|
-
...(reviews.length ? { review_handoffs: reviews } : {}),
|
|
185
|
-
...(goal_field ? { goal: goal_field } : {}),
|
|
186
|
-
...(stopped.length ? { stopped_executions: stopped } : {}),
|
|
187
|
-
role: member.role || 'member',
|
|
188
|
-
read_after: execution.read_until, cwd: profile.cwd || null, project_access: profile.project_access, draft_directory,
|
|
189
|
-
...(extra_directories.length ? { extra_directories } : {}),
|
|
190
|
-
skills: skills.map(file => join(config.project, '.agents/skills', file)),
|
|
191
|
-
// The workflow's SKILL.md is not a skill read on every task: the host opens it when a request fits its description.
|
|
192
|
-
...(workflow_field ? { workflow: { ...workflow_field, skill_path: host_workflow.skill_path } } : {}),
|
|
193
|
-
...(member.role === 'host' && config.host_workflows ? { host_workflows: true } : {}),
|
|
194
|
-
cli, subcommands: TASK_SUBCOMMANDS,
|
|
195
|
-
...(bound_access ? { access_env: 'DISCUSS_ACCESS_FILE' } : { access_file: access_path }), instructions });
|
|
196
|
-
return { id, participant: member.name, directory: config.directory, draft_directory, extra_directories, ...(goal_field ? { goal: goal_field } : {}),
|
|
197
|
-
skill_directories: [skills_directory, ...(host_workflow ? [host_workflow.directory] : [])], access_path, prompt: with_expert_prompt(prompt, profile), inbox,
|
|
198
|
-
profile, ...(workflow_field ? { workflow: { ...workflow_field, skill: host_workflow.skill } } : {}) };
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/**
|
|
202
|
-
* The prompt that resumes an execution the owner paused from the private chat: the same task goes on in the same
|
|
203
|
-
* session, steered by what the owner added. The task file and credentials are written again as at its first delivery.
|
|
204
|
-
*/
|
|
205
|
-
export function resume_prompt(execution_id, texts) {
|
|
206
|
-
return `房主在私聊窗口暂停了你正在做的这次房间任务(执行 #${execution_id},仍在进行,没有结束),并补充了下面的话。`
|
|
207
|
-
+ `按补充调整后接着完成原任务,已经做完的部分不必重做;完成后照常用 codiscuss 提交这次执行的回答。\n\n${texts.join('\n\n')}`;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
/**
|
|
211
|
-
* The preface of a task delivered again after the runner restarted mid-execution: the member's session usually still
|
|
212
|
-
* holds the work done so far, so it continues instead of starting over. The original task follows, for a session that
|
|
213
|
-
* never received it.
|
|
214
|
-
*/
|
|
215
|
-
export function restart_notice(execution_id) {
|
|
216
|
-
return `本机接入程序重启或异常退出,中断了你正在做的这次房间任务(执行 #${execution_id},仍在进行,没有结束)。`
|
|
217
|
-
+ '如果本会话里已经开始了它,接着完成,已经做完的部分不必重做;完成后照常用 codiscuss 提交这次执行的回答。原任务如下。\n\n';
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// The fixed opening of a private chat turn: where the words come from and how to answer them; the owner's text follows.
|
|
221
|
-
const CHAT_PREAMBLE = '房主在私聊窗口直接对你说(不在房间消息流里,其他成员看不到)。像在终端里对话一样直接用文字回答,不要用 codiscuss 提交到房间,除非房主明确要求;可以照常按你的权限读写项目文件。';
|
|
222
|
-
|
|
223
|
-
/**
|
|
224
|
-
* Write the member-only credential file for one private chat turn and describe it as a task: the member's own session,
|
|
225
|
-
* profile and directories, with the owner's words as the prompt. No task file: the prompt is all the turn needs.
|
|
226
|
-
*/
|
|
227
|
-
export function chat_task_files(config, member, chat, binding) {
|
|
228
|
-
const id = `chat-${chat.id}`;
|
|
229
|
-
const draft_directory = config.draft_directory || `${config.directory}-drafts`;
|
|
230
|
-
mkdirSync(draft_directory, { recursive: true });
|
|
231
|
-
const access_path = join(config.directory, `${id}.access.json`);
|
|
232
|
-
const profile = effective_profile(config.participants[member.name], member.name, null);
|
|
233
|
-
atomic_json(access_path, { site: config.site, room: config.room, member: member.name, token: config.members[member.name].token,
|
|
234
|
-
session_id: binding.session_id || '' });
|
|
235
|
-
return { id, participant: member.name, directory: config.directory, draft_directory, extra_directories: member_extra_directories(config, profile),
|
|
236
|
-
skill_directories: [join(config.project, '.agents', 'skills')], access_path, prompt: `${CHAT_PREAMBLE}\n\n${chat.text}`, inbox: false, profile };
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/** What a scheduler can know about a member without a role field: its software, project access and the messages it is on. */
|
|
240
|
-
function member_description(name, profile, work) {
|
|
241
|
-
const project = profile.project_name || (profile.cwd ? basename(profile.cwd) : '');
|
|
242
|
-
const access = !capabilities_of(profile.adapter).project ? ',只能读写房间消息' : profile.project_access === 'own' ? ',权限沿用其会话设置' : !profile.cwd ? ',未指定项目目录'
|
|
243
|
-
: profile.project_access === 'read' ? `,项目 ${project} 只读`
|
|
244
|
-
: `,可修改项目 ${project} 的文件${capabilities_of(profile.adapter).file_tools ? '(不能运行命令)' : '并运行命令'}`;
|
|
245
|
-
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
const
|
|
252
|
-
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
const
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
this.
|
|
269
|
-
this.
|
|
270
|
-
this.
|
|
271
|
-
this.
|
|
272
|
-
this.
|
|
273
|
-
this.
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
this.
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
this.
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
this.
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
this.
|
|
290
|
-
|
|
291
|
-
this
|
|
292
|
-
|
|
293
|
-
this
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
this.
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
this.
|
|
306
|
-
this.
|
|
307
|
-
this.
|
|
308
|
-
this.
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
const
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
.
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
*
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
const
|
|
332
|
-
const
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
this.
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
*
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
const
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
//
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
if (!inbox.archived) await this.
|
|
365
|
-
if (!inbox.archived
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
if (this.config.scheduler && !inbox.archived) this.
|
|
374
|
-
if (!inbox.archived) this.
|
|
375
|
-
|
|
376
|
-
this.
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
const
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
await this.
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
const
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
&& !
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
const
|
|
443
|
-
const
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
const
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
{
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
const
|
|
534
|
-
if (
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
this.
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
this.
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
const
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
const
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
.
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
}
|
|
673
|
-
/**
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
return
|
|
697
|
-
}
|
|
698
|
-
/**
|
|
699
|
-
|
|
700
|
-
const
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
const
|
|
712
|
-
const
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
.
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
if (
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
// A
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
this.
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
const
|
|
802
|
-
|
|
803
|
-
const
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
const
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
});
|
|
813
|
-
|
|
814
|
-
this.
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
if (
|
|
841
|
-
if (
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
}
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
if (
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
this.
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
await api(this.config, `/
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
this.
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
this.
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
this.
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
if (this.
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
const
|
|
1035
|
-
|
|
1036
|
-
if (
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
.
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
.
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
}
|
|
1105
|
-
/**
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
}
|
|
1118
|
-
/**
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
this.
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
this.
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
this.
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
this.
|
|
1162
|
-
this.
|
|
1163
|
-
this.
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
const
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
})
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
}
|
|
1260
|
-
/**
|
|
1261
|
-
|
|
1262
|
-
this.
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1
|
+
/** Free-room delivery: one live execution per member, carrying all of that member's open requests. */
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from 'node:fs';
|
|
5
|
+
import { basename, join, resolve } from 'node:path';
|
|
6
|
+
import { adapter_of, BRANCHABLE_ADAPTERS, branch_session, capabilities_of, cleanup_room, deliver_task, delivery_receipt, image_model_of, session_exists, stored_delivery } from './adapters/index.mjs';
|
|
7
|
+
import { api, overlapping_directories, read_rule } from './discussion_runner.mjs';
|
|
8
|
+
import { SegmentLog } from './execution_progress.mjs';
|
|
9
|
+
import { free_task_text, TASK_SUBCOMMANDS, with_expert_prompt } from './expert_prompts.mjs';
|
|
10
|
+
import { atomic_json } from './files.mjs';
|
|
11
|
+
import { outside_directory, room_directories } from './project_files.mjs';
|
|
12
|
+
import { SessionDriver } from './session_driver.mjs';
|
|
13
|
+
import { effective_profile, load_room_workflow, workflow_in_use, workflow_task_field } from './workflows.mjs';
|
|
14
|
+
import { DEFAULT_SCHEDULER_MODE, GOAL_PROMPT_VERSION, decide_goal_wake, decide_sequence_checkpoint, REVIEW_CONFIDENCE, REVIEW_PROMPT_VERSION, SEQUENCE_CONFIDENCE, SEQUENCE_PROMPT_VERSION, ROUTE_CONFIDENCE, ROUTE_CONTEXT_MESSAGES, decide_review_completion, route_free_message, route_prompt_version, scheduler_thresholds, some_members } from './scheduler.mjs';
|
|
15
|
+
|
|
16
|
+
const PACKAGE_VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
17
|
+
const RENEW_MS = 30_000;
|
|
18
|
+
/** A changed phase is reported early, but no more often than this, since each report refreshes open pages. */
|
|
19
|
+
const ACTIVITY_REPORT_MS = 10_000;
|
|
20
|
+
/** Segments and progress notes are reported quietly, waking no page, so they may go every tick. */
|
|
21
|
+
const PROGRESS_REPORT_MS = 2_000;
|
|
22
|
+
const MAX_DELIVERY_ATTEMPTS = 3;
|
|
23
|
+
// An idle room under an active goal waits this long before the host is woken, leaving the owner time to speak first.
|
|
24
|
+
// Fallback when the room's goal does not carry its own idle wait (older website).
|
|
25
|
+
export const GOAL_IDLE_MS = 120_000;
|
|
26
|
+
// A goal waiting on the owner reaches their Weixin only after this long: right after the question they may be typing.
|
|
27
|
+
export const PENDING_NOTICE_MS = 5 * 60_000;
|
|
28
|
+
// A failed Weixin notice is tried again after this long instead of on every tick.
|
|
29
|
+
const NOTICE_RETRY_MS = 60_000;
|
|
30
|
+
// Without the host's note, the notice quotes the room's latest message, up to this many characters.
|
|
31
|
+
const NOTICE_EXCERPT = 300;
|
|
32
|
+
// A manual member's session that refuses a delivery is retried in the same execution, after a wait the owner can cut short.
|
|
33
|
+
const MAX_DELIVERY_RETRIES = 3;
|
|
34
|
+
const RETRY_DELAY_SECONDS = 60;
|
|
35
|
+
// The cause is gone once the restarted runner is back, so its retry needs no long wait.
|
|
36
|
+
const RESTART_RETRY_DELAY_SECONDS = 5;
|
|
37
|
+
// The retry reason the site keeps for an execution a runner restart cut off; its redelivery asks to continue.
|
|
38
|
+
const RESTART_REASON = '本机接入程序重启或异常退出,这次执行的软件进程已结束,未提交回答';
|
|
39
|
+
const MAX_RETRY_REASON = 500;
|
|
40
|
+
const LIVE = ['reserving', 'delivering', 'sidecar_pending', 'running', 'retry_wait'];
|
|
41
|
+
// The longest private chat reply the site keeps.
|
|
42
|
+
const CHAT_REPLY_LIMIT = 20000;
|
|
43
|
+
const MAX_HASHED_BYTES = 5 * 1024 * 1024;
|
|
44
|
+
const GIT_TIMEOUT_MS = 15_000;
|
|
45
|
+
|
|
46
|
+
/** Fingerprint configurations whose adapter can enforce project read-only access; no local paths leave this function. */
|
|
47
|
+
export function review_capability_version(profile, member, config) {
|
|
48
|
+
if (!profile || profile.project_access !== 'read' || member.access !== 'runner' || member.session_mode !== 'new'
|
|
49
|
+
|| !capabilities_of(profile.adapter).enforces_read_only || profile.adapter !== member.adapter
|
|
50
|
+
|| !profile.cwd || profile.allowed_tools?.length) return '';
|
|
51
|
+
const project = cwd_key(profile.cwd), drafts = cwd_key(config.draft_directory || `${config.directory}-drafts`);
|
|
52
|
+
if (drafts === project || drafts.startsWith(`${project}/`)) return '';
|
|
53
|
+
const facts = [1, profile.adapter, profile.executable || '', cwd_key(profile.cwd), cwd_key(profile.workdir),
|
|
54
|
+
profile.project_id || '', profile.project_name || '', profile.session_id || '', drafts,
|
|
55
|
+
cwd_key(config.directory)];
|
|
56
|
+
return createHash('sha256').update(JSON.stringify(facts)).digest('hex');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Whether a process with this pid exists; signal 0 only checks, and EPERM means it exists under another user. */
|
|
60
|
+
function process_alive(pid) {
|
|
61
|
+
try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Identify a working directory consistently, so executions in the same cwd can be compared. */
|
|
65
|
+
export function cwd_key(directory) {
|
|
66
|
+
if (!directory) return '';
|
|
67
|
+
const path = resolve(directory).replaceAll('\\', '/');
|
|
68
|
+
return process.platform === 'win32' ? path.toLowerCase() : path;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Record each changed or untracked file's Git status and content hash in a Git working tree.
|
|
73
|
+
* Returns null outside Git: free rooms then provide no automatic overlap detection.
|
|
74
|
+
*/
|
|
75
|
+
export function workspace_snapshot(directory) {
|
|
76
|
+
if (!directory) return null;
|
|
77
|
+
const result = spawnSync('git', ['-C', directory, 'status', '--porcelain=v1', '-z', '--untracked-files=all'],
|
|
78
|
+
{ encoding: 'utf8', windowsHide: true, timeout: GIT_TIMEOUT_MS });
|
|
79
|
+
if (result.status !== 0) return null;
|
|
80
|
+
const entries = new Map();
|
|
81
|
+
const fields = result.stdout.split('\0').filter(Boolean);
|
|
82
|
+
for (let index = 0; index < fields.length; index++) {
|
|
83
|
+
const status = fields[index].slice(0, 2), path = fields[index].slice(3);
|
|
84
|
+
if (status[0] === 'R' || status[0] === 'C') index++; // The original path of a rename follows.
|
|
85
|
+
let content = 'missing';
|
|
86
|
+
try {
|
|
87
|
+
const file = join(directory, path);
|
|
88
|
+
const size = statSync(file).size;
|
|
89
|
+
content = size > MAX_HASHED_BYTES ? `size:${size}` : createHash('sha256').update(readFileSync(file)).digest('hex');
|
|
90
|
+
} catch { /* Deleted files keep the marker. */ }
|
|
91
|
+
entries.set(path, `${status}:${content}`);
|
|
92
|
+
}
|
|
93
|
+
return entries;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Paths whose status or content differ between two snapshots of one working tree. */
|
|
97
|
+
export function changed_between(before, after) {
|
|
98
|
+
const paths = new Set([...before.keys(), ...after.keys()]);
|
|
99
|
+
return [...paths].filter(path => before.get(path) !== after.get(path)).sort();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The changed paths (relative, as git lists them) that the agent edited with its own tools, given the paths those tools
|
|
104
|
+
* named (absolute or relative to the working directory). Matched by path suffix, so a working directory below the
|
|
105
|
+
* repository root still matches; Windows paths compare case-insensitively.
|
|
106
|
+
*/
|
|
107
|
+
export function edited_changes(changes, claimed, platform = process.platform) {
|
|
108
|
+
const normal = path => {
|
|
109
|
+
const text = `/${String(path).replaceAll('\\', '/').replace(/^\.\//, '')}`;
|
|
110
|
+
return platform === 'win32' ? text.toLowerCase() : text;
|
|
111
|
+
};
|
|
112
|
+
const named = [...claimed].map(normal);
|
|
113
|
+
return changes.filter(path => named.some(item => item.endsWith(normal(path))));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The room's project directories a member works with besides its own cwd, each `{path, access}`: a member working in
|
|
118
|
+
* the room's project gets the others at its own project access (read or write); a member working outside them gets
|
|
119
|
+
* them all read-only. Software without project files gets none, and a folder gone from this computer is left out.
|
|
120
|
+
*/
|
|
121
|
+
export function member_extra_directories(config, profile) {
|
|
122
|
+
if (!profile || !capabilities_of(profile.adapter).project) return [];
|
|
123
|
+
// '' marks a member that joined before the room had a project: it reaches every room directory at its own access.
|
|
124
|
+
const cwd = profile.cwd ?? config.cwd;
|
|
125
|
+
const access = outside_directory(config, profile) || profile.project_access === 'read' ? 'read' : 'write';
|
|
126
|
+
return room_directories(config).filter(path => !(cwd && overlapping_directories(path, cwd)) && existsSync(path))
|
|
127
|
+
.map(path => ({ path, access }));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** A changed path in an extra directory, reported in full so it cannot be mistaken for one in the main directory. */
|
|
131
|
+
function extra_change(directory, path) {
|
|
132
|
+
return `${cwd_key(directory)}/${path}`;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Write a non-secret task and a member-only credential file for one execution. */
|
|
136
|
+
export function free_task_files(config, member, execution, binding, { session = null, suggestions = [], reviews = [], stopped = [], process_access = true,
|
|
137
|
+
workflow = null, room_members = [], goal = null } = {}) {
|
|
138
|
+
const id = `free-${execution.id}`;
|
|
139
|
+
const draft_directory = config.draft_directory || `${config.directory}-drafts`;
|
|
140
|
+
mkdirSync(draft_directory, { recursive: true });
|
|
141
|
+
const access_path = join(config.directory, `${id}.access.json`);
|
|
142
|
+
const task_path = join(config.directory, `${id}.task.json`);
|
|
143
|
+
// A workflow member's prompt is read from its card for this execution; everything else stays the room's setting.
|
|
144
|
+
const profile = effective_profile(config.participants[member.name], member.name, workflow);
|
|
145
|
+
// The host sees the workflow only while its members are here: sending them away ends it.
|
|
146
|
+
const host_workflow = member.role === 'host' && workflow && !workflow.error && workflow_in_use(workflow, room_members) ? workflow : null;
|
|
147
|
+
atomic_json(access_path, { site: config.site, room: config.room, member: member.name, token: config.members[member.name].token,
|
|
148
|
+
session_id: binding.session_id || '', execution_id: execution.id });
|
|
149
|
+
const adapter = adapter_of(profile.adapter);
|
|
150
|
+
const extra_directories = member_extra_directories(config, profile);
|
|
151
|
+
const cli = process.platform === 'win32' ? adapter?.windows_command || 'codiscuss.cmd' : 'codiscuss';
|
|
152
|
+
const inbox = Boolean(adapter?.into_window?.(profile, binding));
|
|
153
|
+
const bound_access = process_access && !inbox && Boolean(adapter?.capabilities.access_env);
|
|
154
|
+
const messages = execution.requests.map(item => `#${item.message_id}`).join('、');
|
|
155
|
+
const requests = execution.requests || [];
|
|
156
|
+
const discussion_request = requests.find(item => item.session_request_id && ['discuss', 'discuss_host'].includes(item.purpose)) || null;
|
|
157
|
+
const direct_question = Boolean(session?.status === 'active' && requests.some(item => item.purpose === 'ask'));
|
|
158
|
+
const { instructions, prompt } = free_task_text({ name: member.label || member.name, role: member.role, discussion: direct_question,
|
|
159
|
+
discussion_request, profile, cli,
|
|
160
|
+
room: config.room, messages, read_after: execution.read_until, execution_id: execution.id, task_path,
|
|
161
|
+
access_file: bound_access ? '' : access_path, read_rule: read_rule(profile.adapter), inbox, extra_directories });
|
|
162
|
+
const skills = discussion_request || direct_question
|
|
163
|
+
? ['discuss-participant/SKILL.md', 'discuss-session/SKILL.md',
|
|
164
|
+
...member.role === 'host' ? ['discuss-host/SKILL.md', 'discuss-session/references/host.md'] : [],
|
|
165
|
+
...direct_question ? ['discuss-participant/references/room.md'] : []]
|
|
166
|
+
: ['discuss-participant/SKILL.md', 'discuss-participant/references/room.md',
|
|
167
|
+
...member.role === 'host' ? ['discuss-host/SKILL.md', 'discuss-host/references/room.md'] : []];
|
|
168
|
+
// The host works a goal while it is open, and also handles the request that opens it or the wrap-up after it ends.
|
|
169
|
+
const goal_task = member.role === 'host' && (['active', 'paused'].includes(goal?.status)
|
|
170
|
+
|| requests.some(item => ['goal_start', 'goal_continue'].includes(item.purpose)));
|
|
171
|
+
if (goal_task) skills.push('discuss-goal/SKILL.md');
|
|
172
|
+
const goal_field = goal_task && goal ? { id: goal.id, objective: goal.objective, status: goal.status, continues: goal.continues,
|
|
173
|
+
max_continues: goal.max_continues, elapsed_seconds: goal.elapsed_seconds, max_minutes: goal.max_minutes,
|
|
174
|
+
phase: goal.phase ?? 'doing', ...(goal.phase_note ? { phase_note: goal.phase_note } : {}) } : null;
|
|
175
|
+
const skills_directory = join(config.project, '.agents', 'skills');
|
|
176
|
+
const workflow_field = host_workflow ? workflow_task_field(host_workflow, room_members, config.participants) : null;
|
|
177
|
+
atomic_json(task_path, { site: config.site, room: config.room, mode: 'free', member: member.name,
|
|
178
|
+
execution_id: execution.id, requests, request_messages: execution.requests.map(item => item.message_id),
|
|
179
|
+
request_purposes: execution.requests.map(item => item.purpose || 'ask'),
|
|
180
|
+
...(discussion_request ? { discussion_request } : {}),
|
|
181
|
+
...(session ? { session: { id: session.id, status: session.status, phase: session.phase,
|
|
182
|
+
goal: session.goal, named_followup: session.named_followup } } : {}),
|
|
183
|
+
...(suggestions.length ? { scheduler_suggestions: suggestions } : {}),
|
|
184
|
+
...(reviews.length ? { review_handoffs: reviews } : {}),
|
|
185
|
+
...(goal_field ? { goal: goal_field } : {}),
|
|
186
|
+
...(stopped.length ? { stopped_executions: stopped } : {}),
|
|
187
|
+
role: member.role || 'member',
|
|
188
|
+
read_after: execution.read_until, cwd: profile.cwd || null, project_access: profile.project_access, draft_directory,
|
|
189
|
+
...(extra_directories.length ? { extra_directories } : {}),
|
|
190
|
+
skills: skills.map(file => join(config.project, '.agents/skills', file)),
|
|
191
|
+
// The workflow's SKILL.md is not a skill read on every task: the host opens it when a request fits its description.
|
|
192
|
+
...(workflow_field ? { workflow: { ...workflow_field, skill_path: host_workflow.skill_path } } : {}),
|
|
193
|
+
...(member.role === 'host' && config.host_workflows ? { host_workflows: true } : {}),
|
|
194
|
+
cli, subcommands: TASK_SUBCOMMANDS,
|
|
195
|
+
...(bound_access ? { access_env: 'DISCUSS_ACCESS_FILE' } : { access_file: access_path }), instructions });
|
|
196
|
+
return { id, participant: member.name, directory: config.directory, draft_directory, extra_directories, ...(goal_field ? { goal: goal_field } : {}),
|
|
197
|
+
skill_directories: [skills_directory, ...(host_workflow ? [host_workflow.directory] : [])], access_path, prompt: with_expert_prompt(prompt, profile), inbox,
|
|
198
|
+
profile, ...(workflow_field ? { workflow: { ...workflow_field, skill: host_workflow.skill } } : {}) };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The prompt that resumes an execution the owner paused from the private chat: the same task goes on in the same
|
|
203
|
+
* session, steered by what the owner added. The task file and credentials are written again as at its first delivery.
|
|
204
|
+
*/
|
|
205
|
+
export function resume_prompt(execution_id, texts) {
|
|
206
|
+
return `房主在私聊窗口暂停了你正在做的这次房间任务(执行 #${execution_id},仍在进行,没有结束),并补充了下面的话。`
|
|
207
|
+
+ `按补充调整后接着完成原任务,已经做完的部分不必重做;完成后照常用 codiscuss 提交这次执行的回答。\n\n${texts.join('\n\n')}`;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* The preface of a task delivered again after the runner restarted mid-execution: the member's session usually still
|
|
212
|
+
* holds the work done so far, so it continues instead of starting over. The original task follows, for a session that
|
|
213
|
+
* never received it.
|
|
214
|
+
*/
|
|
215
|
+
export function restart_notice(execution_id) {
|
|
216
|
+
return `本机接入程序重启或异常退出,中断了你正在做的这次房间任务(执行 #${execution_id},仍在进行,没有结束)。`
|
|
217
|
+
+ '如果本会话里已经开始了它,接着完成,已经做完的部分不必重做;完成后照常用 codiscuss 提交这次执行的回答。原任务如下。\n\n';
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// The fixed opening of a private chat turn: where the words come from and how to answer them; the owner's text follows.
|
|
221
|
+
const CHAT_PREAMBLE = '房主在私聊窗口直接对你说(不在房间消息流里,其他成员看不到)。像在终端里对话一样直接用文字回答,不要用 codiscuss 提交到房间,除非房主明确要求;可以照常按你的权限读写项目文件。';
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Write the member-only credential file for one private chat turn and describe it as a task: the member's own session,
|
|
225
|
+
* profile and directories, with the owner's words as the prompt. No task file: the prompt is all the turn needs.
|
|
226
|
+
*/
|
|
227
|
+
export function chat_task_files(config, member, chat, binding) {
|
|
228
|
+
const id = `chat-${chat.id}`;
|
|
229
|
+
const draft_directory = config.draft_directory || `${config.directory}-drafts`;
|
|
230
|
+
mkdirSync(draft_directory, { recursive: true });
|
|
231
|
+
const access_path = join(config.directory, `${id}.access.json`);
|
|
232
|
+
const profile = effective_profile(config.participants[member.name], member.name, null);
|
|
233
|
+
atomic_json(access_path, { site: config.site, room: config.room, member: member.name, token: config.members[member.name].token,
|
|
234
|
+
session_id: binding.session_id || '' });
|
|
235
|
+
return { id, participant: member.name, directory: config.directory, draft_directory, extra_directories: member_extra_directories(config, profile),
|
|
236
|
+
skill_directories: [join(config.project, '.agents', 'skills')], access_path, prompt: `${CHAT_PREAMBLE}\n\n${chat.text}`, inbox: false, profile };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** What a scheduler can know about a member without a role field: its software, project access and the messages it is on. */
|
|
240
|
+
function member_description(name, profile, work) {
|
|
241
|
+
const project = profile.project_name || (profile.cwd ? basename(profile.cwd) : '');
|
|
242
|
+
const access = !capabilities_of(profile.adapter).project ? ',只能读写房间消息' : profile.project_access === 'own' ? ',权限沿用其会话设置' : !profile.cwd ? ',未指定项目目录'
|
|
243
|
+
: profile.project_access === 'read' ? `,项目 ${project} 只读`
|
|
244
|
+
: `,可修改项目 ${project} 的文件${capabilities_of(profile.adapter).file_tools ? '(不能运行命令)' : '并运行命令'}`;
|
|
245
|
+
const images = image_model_of(profile) ? `,可生成和修改图片(${image_model_of(profile)})` : '';
|
|
246
|
+
return `${name}(${adapter_of(profile.adapter)?.label || profile.adapter}${access}${images}${work})`;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** The other messages a member is answering or has queued, so a correction can follow the message it corrects. */
|
|
250
|
+
function member_work(requests, name, message_id) {
|
|
251
|
+
const open = requests.filter(item => item.member === name && item.message_id !== message_id);
|
|
252
|
+
const ids = status => [...new Set(open.filter(item => item.status === status).map(item => `#${item.message_id}`))].join('、');
|
|
253
|
+
return [ids('delivering') && `;正在处理 ${ids('delivering')}`, ids('pending') && `;待处理 ${ids('pending')}`].filter(Boolean).join('');
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Why a message stayed with the host: the scheduler chose the host, or leaned elsewhere without enough certainty. */
|
|
257
|
+
function route_host_label(decision, host, members) {
|
|
258
|
+
if (decision.choice === '__host__' || decision.confidence === null) return `交给主持人 ${host}`;
|
|
259
|
+
const group = some_members(decision.choice);
|
|
260
|
+
const lean = decision.choice === '__all__' ? '全体各自回应' : decision.choice === '__all_seq__' ? '全体依次回应' : decision.choice === '__none__' ? '无需回应' : group ? `请 ${group.join('、')} 各自回应`
|
|
261
|
+
: members.some(member => member.name === decision.choice) ? `请 ${decision.choice} 回答` : '';
|
|
262
|
+
return lean ? `倾向${lean},把握不足,交给主持人 ${host}` : `交给主持人 ${host}`;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Delivers free-room requests through the same software adapters as discussions. */
|
|
266
|
+
export class FreeRoomRunner {
|
|
267
|
+
constructor(config, store, deliver = deliver_task, log = () => {}, fetch_impl = fetch, session_driver = null) {
|
|
268
|
+
this.config = config;
|
|
269
|
+
this.store = store;
|
|
270
|
+
this.deliver = deliver;
|
|
271
|
+
this.log = log;
|
|
272
|
+
this.fetch = fetch_impl;
|
|
273
|
+
this.session_driver = session_driver || new SessionDriver(config, log, fetch_impl, store);
|
|
274
|
+
this.routed = new Set();
|
|
275
|
+
// Group requests (@全体成员) being arranged; a failed arrangement leaves the set so the next tick retries.
|
|
276
|
+
this.grouped = new Set();
|
|
277
|
+
this.decisions = new Set();
|
|
278
|
+
// Called when a scheduling decision settles; the service checks the room at once instead of waiting for the next poll.
|
|
279
|
+
this.on_decided = () => {};
|
|
280
|
+
// Set by the service when it can reach the owner's Weixin: { ready(), sent(key), send(notice) }.
|
|
281
|
+
this.notifier = null;
|
|
282
|
+
// Routed requests whose decision is still pending: their host waits, so one pick replaces the host's start.
|
|
283
|
+
this.routing = new Set();
|
|
284
|
+
this.children = new Set();
|
|
285
|
+
// Per live execution, how to pass an interjection to its running software; and interjections already handed over.
|
|
286
|
+
this.steers = new Map();
|
|
287
|
+
this.interjecting = new Map();
|
|
288
|
+
// Per member, the private chat turn running in its session.
|
|
289
|
+
this.chat_turns = new Map();
|
|
290
|
+
this.members = new Map();
|
|
291
|
+
// An empty set proves every tracked handle for this execution closed; a missing set proves nothing after restart.
|
|
292
|
+
this.execution_processes = new Map();
|
|
293
|
+
// Marks the handles this runner process tracks (`owner:ID` in metadata), so a later runner can tell inherited executions.
|
|
294
|
+
this.instance = randomUUID();
|
|
295
|
+
// Execution id -> why its session ended on its own, such as a command refused in unattended mode ('' when unknown).
|
|
296
|
+
this.exited = new Map();
|
|
297
|
+
// Per execution, which delivery is current: a turn stopped by a pause may report its exit after the resumed one began.
|
|
298
|
+
this.generations = new Map();
|
|
299
|
+
// Executions whose software failed before any turn ran, as its adapter reported; safe to deliver again.
|
|
300
|
+
this.not_started = new Set();
|
|
301
|
+
// Executions whose software failed in a way a retry meets again (a used-up limit, a lost login), as its adapter reported.
|
|
302
|
+
this.not_retryable = new Set();
|
|
303
|
+
this.snapshots = new Map();
|
|
304
|
+
// Execution id -> { phase, at, sent_phase, sent_at }: what the member's software last showed it doing.
|
|
305
|
+
this.activity = new Map();
|
|
306
|
+
this.segments = new SegmentLog();
|
|
307
|
+
this.context_errors = new Map();
|
|
308
|
+
this.adopt(config);
|
|
309
|
+
this.store.db.exec(`CREATE TABLE IF NOT EXISTS free_deliveries(member TEXT PRIMARY KEY, client_id TEXT NOT NULL,
|
|
310
|
+
execution_id INTEGER NOT NULL DEFAULT 0, status TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,
|
|
311
|
+
started INTEGER NOT NULL DEFAULT 0, last_renew INTEGER NOT NULL DEFAULT 0, error TEXT NOT NULL DEFAULT '')`);
|
|
312
|
+
}
|
|
313
|
+
/** Read this member's current local delivery record. */
|
|
314
|
+
row(name) { return this.store.db.prepare('SELECT * FROM free_deliveries WHERE member=?').get(name); }
|
|
315
|
+
/** Persist one member's delivery state; the client id makes a lost reserve response recoverable. */
|
|
316
|
+
save(name, fields) {
|
|
317
|
+
const current = this.row(name) || { member: name, client_id: '', execution_id: 0, status: 'idle', attempts: 0, started: 0, last_renew: 0, error: '' };
|
|
318
|
+
const next = { ...current, ...fields };
|
|
319
|
+
this.store.db.prepare(`INSERT INTO free_deliveries VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(member) DO UPDATE SET
|
|
320
|
+
client_id=excluded.client_id,execution_id=excluded.execution_id,status=excluded.status,attempts=excluded.attempts,
|
|
321
|
+
started=excluded.started,last_renew=excluded.last_renew,error=excluded.error`)
|
|
322
|
+
.run(name, next.client_id, next.execution_id, next.status, next.attempts, next.started, next.last_renew, next.error);
|
|
323
|
+
return next;
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Take a changed configuration while running: new members are added, but a member whose
|
|
327
|
+
* project, cwd or bound session changed is blocked instead of silently reusing its conversation.
|
|
328
|
+
*/
|
|
329
|
+
adopt(config) {
|
|
330
|
+
for (const [name, item] of Object.entries(config.participants)) {
|
|
331
|
+
const context = JSON.stringify([item.adapter, item.project_id || '', item.project_name || '', cwd_key(item.cwd), cwd_key(item.workdir), item.session_id || '']);
|
|
332
|
+
const key = `member-context:${name}`;
|
|
333
|
+
const previous = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(key)?.value;
|
|
334
|
+
if (previous && !this.same_context(name, previous, context)) this.context_errors.set(name, `${name} 已绑定会话的项目、cwd 或接入方式发生变化;请移除后重新邀请`);
|
|
335
|
+
else this.store.db.prepare('INSERT INTO metadata VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key, context);
|
|
336
|
+
}
|
|
337
|
+
this.config = { ...this.config, ...config, participants: config.participants, members: config.members };
|
|
338
|
+
this.session_driver.config = this.config;
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* A Codex member switched between App and CLI keeps its conversation: the two entries count as one, and the App's
|
|
342
|
+
* session may be filled in from the conversation this member is already bound to.
|
|
343
|
+
*/
|
|
344
|
+
same_context(name, previous, current) {
|
|
345
|
+
const [before, after] = [JSON.parse(previous), JSON.parse(current)];
|
|
346
|
+
for (const context of [before, after]) context[0] = adapter_of(context[0])?.session_family || context[0];
|
|
347
|
+
const bound = this.store.binding(name).session_id;
|
|
348
|
+
if (before[5] !== after[5] && [before[5], after[5]].includes('') && [before[5], after[5]].includes(bound)) after[5] = before[5];
|
|
349
|
+
return JSON.stringify(before) === JSON.stringify(after);
|
|
350
|
+
}
|
|
351
|
+
/** One bounded iteration: reconcile live executions, then deliver idle members with open requests. */
|
|
352
|
+
async tick() {
|
|
353
|
+
let inbox; let room;
|
|
354
|
+
// Read one after another: Node's fetch keeps one warm connection per site, and a second parallel request would pay a new
|
|
355
|
+
// TLS handshake (measured 2 s against 0.4 s through a proxy to a hosted site).
|
|
356
|
+
try {
|
|
357
|
+
inbox = await api(this.config, '/inbox');
|
|
358
|
+
room = await api(this.config, '');
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
if (error.message === 'HTTP 404: 房间不存在') cleanup_room(this.config.directory);
|
|
362
|
+
throw error;
|
|
363
|
+
}
|
|
364
|
+
if (!inbox.archived) await this.sync_review_capabilities(inbox);
|
|
365
|
+
if (!inbox.archived) await this.sync_member_capabilities(inbox);
|
|
366
|
+
if (!inbox.archived && room.session?.status === 'active'
|
|
367
|
+
&& await this.session_driver.tick(room, inbox)) {
|
|
368
|
+
// A scheduled plan completes the pending host request and creates a speaker request.
|
|
369
|
+
inbox = await api(this.config, '/inbox');
|
|
370
|
+
room = await api(this.config, '');
|
|
371
|
+
}
|
|
372
|
+
// Smart scheduling runs beside delivery: the host waits for its answer (or failure) before starting, see `routing`.
|
|
373
|
+
if (this.config.scheduler && !inbox.archived) this.recommend_unnamed(inbox, room);
|
|
374
|
+
if (this.config.scheduler && !inbox.archived) this.schedule_handoffs(inbox);
|
|
375
|
+
if (!inbox.archived) this.arrange_groups(inbox);
|
|
376
|
+
this.room_title = room.title;
|
|
377
|
+
this.room = room;
|
|
378
|
+
if (!inbox.archived) await this.continue_goal(room);
|
|
379
|
+
this.inbox = inbox;
|
|
380
|
+
const active = new Map(inbox.executions.map(item => [item.id, item]));
|
|
381
|
+
const present = new Set(inbox.members.map(member => member.name));
|
|
382
|
+
// A member sent away or removed no longer appears; its live work was already voided on the website.
|
|
383
|
+
for (const row of this.store.db.prepare('SELECT * FROM free_deliveries').all()) {
|
|
384
|
+
if (LIVE.includes(row.status) && !present.has(row.member)) { this.stop_member(row.member); this.save(row.member, { status: 'idle' }); }
|
|
385
|
+
}
|
|
386
|
+
await this.report_finished(active);
|
|
387
|
+
await this.deliver_interjections(inbox.executions);
|
|
388
|
+
const pending_stops = await this.report_stops(active);
|
|
389
|
+
// Start in the room's speaking order: execution ids follow it, and the website lays out working cards by them.
|
|
390
|
+
const rank = (room.speaking_order?.items || []).map(item => item.name);
|
|
391
|
+
const place = name => rank.includes(name) ? rank.indexOf(name) : rank.length;
|
|
392
|
+
for (const member of [...inbox.members].sort((left, right) => place(left.name) - place(right.name))) {
|
|
393
|
+
const row = this.row(member.name);
|
|
394
|
+
if (row && LIVE.includes(row.status)) await this.reconcile(member, row, active);
|
|
395
|
+
// A member voided in a window or App the runner could not stop waits until that turn ends (`held_until`).
|
|
396
|
+
else if (!inbox.archived && member.pending.some(request => request.purpose !== 'group') && !this.members.get(member.name)?.size
|
|
397
|
+
&& !pending_stops.has(member.name)
|
|
398
|
+
&& !member.pending.some(request => this.routing.has(request.id)) && !(member.held_until * 1000 > Date.now())) await this.start(member, row);
|
|
399
|
+
}
|
|
400
|
+
// Room work starts first; a private chat line waits until its member is idle.
|
|
401
|
+
if (!inbox.archived) await this.run_chats(inbox.members);
|
|
402
|
+
}
|
|
403
|
+
/** Publish only changed local facts, using member revisions supplied by the owner's inbox. */
|
|
404
|
+
async sync_review_capabilities(inbox) {
|
|
405
|
+
for (const member of inbox.members) {
|
|
406
|
+
const current = member.review_capability;
|
|
407
|
+
if (!current) continue; // Older sites have no review protocol.
|
|
408
|
+
const version = this.context_errors.has(member.name) ? ''
|
|
409
|
+
: review_capability_version(this.config.participants[member.name], member, this.config);
|
|
410
|
+
if ((current.capability?.config_version || '') === version) continue;
|
|
411
|
+
try {
|
|
412
|
+
member.review_capability = await api(this.config, `/members/${member.id}/review-capability`, {
|
|
413
|
+
revision: current.revision, read_only: Boolean(version), ...(version ? { config_version: version } : {}),
|
|
414
|
+
});
|
|
415
|
+
} catch (error) { this.log(`只读评审能力未同步:${member.name}:${error.message}`); }
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Tell the site what each member can do, as its adapter says: what a rewind does to its session, and the image model
|
|
420
|
+
* it can draw with, so the host and every reader of the room see it. Only a change is sent.
|
|
421
|
+
*/
|
|
422
|
+
async sync_member_capabilities(inbox) {
|
|
423
|
+
for (const member of inbox.members) {
|
|
424
|
+
const profile = this.config.participants[member.name];
|
|
425
|
+
// An older site lists no effect and takes no report; one without image_model takes only the rewind effect.
|
|
426
|
+
if (member.rewind === undefined || !profile) continue;
|
|
427
|
+
const rewind = capabilities_of(profile.adapter).rewind;
|
|
428
|
+
const report = { rewind, ...(member.image_model === undefined ? {} : { image_model: image_model_of(profile) }) };
|
|
429
|
+
if (member.rewind === rewind && (report.image_model === undefined || member.image_model === report.image_model)) continue;
|
|
430
|
+
try { await api(this.config, `/members/${member.id}/capabilities`, report); Object.assign(member, report); }
|
|
431
|
+
catch (error) { this.log(`成员能力未同步:${member.name}:${error.message}`); }
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
/** Hold only pending hand-backs with a declared next step while it is judged: a preauthorized review, or a loop's next pass. */
|
|
435
|
+
schedule_handoffs(inbox) {
|
|
436
|
+
const host = inbox.members.find(member => member.role === 'host');
|
|
437
|
+
if (!host || !this.config.members[host.name]?.token || inbox.executions.some(item => item.member_id === host.id)
|
|
438
|
+
|| LIVE.includes(this.row(host.name)?.status)) return;
|
|
439
|
+
for (const request of host.pending) {
|
|
440
|
+
const scene = request.review?.phase === 'handoff' ? 'review' : request.sequence?.phase === 'checkpoint' ? 'sequence' : '';
|
|
441
|
+
if (!scene) continue;
|
|
442
|
+
const key = `${scene}-decision:${request.id}`;
|
|
443
|
+
const saved = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(key)?.value;
|
|
444
|
+
if (this.routed.has(request.id) || (saved && JSON.parse(saved).done)) continue;
|
|
445
|
+
this.routed.add(request.id);
|
|
446
|
+
this.routing.add(request.id);
|
|
447
|
+
const judge = scene === 'review' ? () => this.judge_review(host, request) : () => this.judge_sequence(host, request);
|
|
448
|
+
const pending = this.mark_routing(request.message_id, true).then(judge)
|
|
449
|
+
.catch(error => {
|
|
450
|
+
this.save_suggestion(request, { action: 'host', actual_action: 'host', applied: false,
|
|
451
|
+
model_judgment: false, reason: `没有模型判断:${error.message}` });
|
|
452
|
+
this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(key, JSON.stringify({ done: true }));
|
|
453
|
+
this.log(`${scene === 'review' ? '评审交接' : '循环检查点'} #${request.message_id} 交给主持人:${error.message}`);
|
|
454
|
+
}).finally(() => { this.routing.delete(request.id); return this.mark_routing(request.message_id, false); });
|
|
455
|
+
this.decisions.add(pending);
|
|
456
|
+
pending.finally(() => { this.decisions.delete(pending); this.on_decided(); });
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
/** Persist the complete judgment and submission before any write, so restart recovery cannot double-dispatch. */
|
|
460
|
+
async judge_review(host, request) {
|
|
461
|
+
const key = `review-decision:${request.id}`;
|
|
462
|
+
const cached = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(key)?.value;
|
|
463
|
+
let job = cached ? JSON.parse(cached) : null;
|
|
464
|
+
if (!job) {
|
|
465
|
+
const ready = await api(this.config, `/reviews/${request.review.batch_id}/ready`);
|
|
466
|
+
const decision = await decide_review_completion(this.config.api_home, this.config.scheduler, ready, this.fetch);
|
|
467
|
+
job = { decision, revision: ready.revision, submission_id: randomUUID(), profiles: JSON.stringify(this.config.participants) };
|
|
468
|
+
this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(key, JSON.stringify(job));
|
|
469
|
+
}
|
|
470
|
+
const { decision } = job;
|
|
471
|
+
this.save_suggestion(request, { action: decision.action, actual_action: 'unverified', applied: false,
|
|
472
|
+
model_judgment: Boolean(decision.detail), reason: '自动评审交接结果尚未核验' });
|
|
473
|
+
const outcome = decision.action === 'review' ? await this.apply_review(host, request, job)
|
|
474
|
+
: { applied: false, actual_action: 'host', reason: decision.label };
|
|
475
|
+
const label = outcome.applied ? decision.label : outcome.reason;
|
|
476
|
+
const record = decision.detail ? await this.record_decision(request.message_id, decision, label, outcome.applied,
|
|
477
|
+
{ scene: 'review', prompt: REVIEW_PROMPT_VERSION, threshold: REVIEW_CONFIDENCE }) : null;
|
|
478
|
+
this.save_suggestion(request, { action: decision.action, actual_action: outcome.actual_action, applied: outcome.applied,
|
|
479
|
+
model_judgment: Boolean(decision.detail), ...(record?.id ? { decision_id: record.id } : {}), reason: label });
|
|
480
|
+
this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(key, JSON.stringify({ ...job, done: true }));
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* At a loop's checkpoint, persist the judgment before writing; continuing is bound to the one checkpoint request, so a
|
|
484
|
+
* restart that repeats it gets the same pass back instead of a second one.
|
|
485
|
+
*/
|
|
486
|
+
async judge_sequence(host, request) {
|
|
487
|
+
const key = `sequence-decision:${request.id}`;
|
|
488
|
+
const cached = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(key)?.value;
|
|
489
|
+
let job = cached ? JSON.parse(cached) : null;
|
|
490
|
+
if (!job) {
|
|
491
|
+
const sequence = await api(this.config, `/sequences/${request.sequence.id}`);
|
|
492
|
+
job = { decision: await decide_sequence_checkpoint(this.config.api_home, this.config.scheduler, sequence, this.fetch) };
|
|
493
|
+
this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(key, JSON.stringify(job));
|
|
494
|
+
}
|
|
495
|
+
const { decision } = job;
|
|
496
|
+
let outcome = { applied: false, actual_action: 'host', reason: decision.label };
|
|
497
|
+
if (decision.action === 'continue') {
|
|
498
|
+
try {
|
|
499
|
+
await api({ ...this.config, token: this.config.members[host.name].token }, '/sequences/continue', { actor: host.name, request_id: request.id });
|
|
500
|
+
outcome = { applied: true, actual_action: 'continue' };
|
|
501
|
+
} catch (error) { outcome = { applied: false, actual_action: 'host', reason: `未自动开始下一圈:${error.message}` }; }
|
|
502
|
+
}
|
|
503
|
+
const label = outcome.applied ? decision.label : outcome.reason;
|
|
504
|
+
// The decision sits under the answer it read: the last one of the pass.
|
|
505
|
+
const record = decision.detail ? await this.record_decision(request.sequence.answer_id || request.message_id, decision, label, outcome.applied,
|
|
506
|
+
{ scene: 'sequence', prompt: SEQUENCE_PROMPT_VERSION, threshold: SEQUENCE_CONFIDENCE }) : null;
|
|
507
|
+
this.save_suggestion(request, { action: decision.action, actual_action: outcome.actual_action, applied: outcome.applied,
|
|
508
|
+
model_judgment: Boolean(decision.detail), ...(record?.id ? { decision_id: record.id } : {}), reason: label });
|
|
509
|
+
this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(key, JSON.stringify({ ...job, done: true }));
|
|
510
|
+
}
|
|
511
|
+
/** Advance only the judged revision; inspect an uncertain write using its persisted submission id. */
|
|
512
|
+
async apply_review(host, request, job) {
|
|
513
|
+
if (job.profiles !== JSON.stringify(this.config.participants)) return { applied: false, actual_action: 'host', reason: '本机成员配置已变化,未自动交评审' };
|
|
514
|
+
try {
|
|
515
|
+
await api({ ...this.config, token: this.config.members[host.name].token }, '/reviews/advance', {
|
|
516
|
+
actor: host.name, batch_id: request.review.batch_id, revision: job.revision, submission_id: job.submission_id,
|
|
517
|
+
});
|
|
518
|
+
return { applied: true, actual_action: 'review' };
|
|
519
|
+
} catch (error) {
|
|
520
|
+
try {
|
|
521
|
+
const state = await api(this.config, `/reviews/${request.review.batch_id}/ready`);
|
|
522
|
+
if (state.plan.advance_submission === job.submission_id) return { applied: true, actual_action: 'review' };
|
|
523
|
+
return { applied: false, actual_action: 'host', reason: `未自动交评审:${error.message}` };
|
|
524
|
+
} catch { return { applied: false, actual_action: 'unverified', reason: `评审交接写入结果未核验:${error.message}` }; }
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Whether the last tick left nothing in progress: no live delivery or process, no open request for a member this
|
|
529
|
+
* runner delivers to, no pending scheduling judgement and no running discussion. An idle room changes only through its
|
|
530
|
+
* website, so the service may wait for the website to report a change before ticking it again.
|
|
531
|
+
*/
|
|
532
|
+
idle() {
|
|
533
|
+
const inbox = this.inbox;
|
|
534
|
+
if (!inbox || this.routing.size || [...this.members.values()].some(children => children.size)) return false;
|
|
535
|
+
// A goal waiting out its idle grace still needs ticks to wake the host when it ends, and one waiting on the owner
|
|
536
|
+
// needs them to send its Weixin notice on time.
|
|
537
|
+
if (this.room?.goal_state?.goal?.idle) return false;
|
|
538
|
+
const notice = this.pending_notice(this.room);
|
|
539
|
+
if (notice && this.notifier.ready() && !this.notifier.sent(notice.key)) return false;
|
|
540
|
+
if (this.room?.session?.status === 'active' || inbox.executions.length || inbox.members.some(member => member.pending.length)) return false;
|
|
541
|
+
return !this.store.db.prepare('SELECT status FROM free_deliveries').all().some(row => LIVE.includes(row.status));
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Goal mode: once the room has stayed idle with the same revision for the grace period, wake the host through the
|
|
545
|
+
* website, which re-checks idleness and the revision and decides between a wake-up, a wrap-up or stopping. With a
|
|
546
|
+
* decision model, a room judged to be waiting for the user stands down instead (`wait`); any doubt wakes the host.
|
|
547
|
+
*/
|
|
548
|
+
async continue_goal(room) {
|
|
549
|
+
const view = room.goal_state;
|
|
550
|
+
await this.notify_pending(room);
|
|
551
|
+
if (!view?.goal?.idle) { this.goal_idle = null; return; }
|
|
552
|
+
if (this.goal_idle?.revision !== view.revision) { this.goal_idle = { revision: view.revision, since: Date.now() }; return; }
|
|
553
|
+
const grace = this.config.goal_idle_ms ?? (view.goal.idle_seconds ? view.goal.idle_seconds * 1000 : GOAL_IDLE_MS);
|
|
554
|
+
if (this.goal_idle.busy || Date.now() - this.goal_idle.since < grace) return;
|
|
555
|
+
this.goal_idle.busy = true;
|
|
556
|
+
let decision = null;
|
|
557
|
+
// A phase the host declared (waiting, pending) is its own judgement; the decision model only weighs a plain idle room.
|
|
558
|
+
if (this.config.scheduler && view.goal.armed && (view.goal.phase ?? 'doing') === 'doing') {
|
|
559
|
+
try { decision = await this.judge_goal(room, view.goal); }
|
|
560
|
+
catch (error) { this.log(`Goal 空闲判断失败,照常唤醒主持人:${error.message}`); }
|
|
561
|
+
}
|
|
562
|
+
const action = decision?.action === 'wait' ? 'wait' : 'continue';
|
|
563
|
+
let applied = false;
|
|
564
|
+
try {
|
|
565
|
+
const result = await api(this.config, '/goal', { action, revision: view.revision });
|
|
566
|
+
this.room = { ...room, goal_state: result };
|
|
567
|
+
applied = true;
|
|
568
|
+
this.log(action === 'wait' ? 'Goal:房间在等用户,不唤醒主持人'
|
|
569
|
+
: `Goal 续跑:${result.goal?.status === 'active' ? `第 ${result.goal.continues} 次` : result.goal?.status}`);
|
|
570
|
+
this.on_decided();
|
|
571
|
+
} catch (error) { this.log(`Goal ${action === 'wait' ? '等待' : '续跑'}未生效:${error.message}`); }
|
|
572
|
+
finally { this.goal_idle = null; }
|
|
573
|
+
if (decision?.detail) await this.record_decision(decision.after_message_id, decision, decision.label, applied,
|
|
574
|
+
{ prompt: GOAL_PROMPT_VERSION, threshold: ROUTE_CONFIDENCE, wide_threshold: ROUTE_CONFIDENCE, scene: 'goal' });
|
|
575
|
+
}
|
|
576
|
+
/** The Weixin notice an active goal waiting on the owner calls for, or null. */
|
|
577
|
+
pending_notice(room) {
|
|
578
|
+
const goal = room?.goal_state?.goal;
|
|
579
|
+
if (!this.notifier || goal?.status !== 'active' || goal.phase !== 'pending') return null;
|
|
580
|
+
return { key: `${this.config.site}/${this.config.room}/goal-${goal.id}-pending-${goal.phase_since}`,
|
|
581
|
+
due: goal.phase_since * 1000 + PENDING_NOTICE_MS, goal };
|
|
582
|
+
}
|
|
583
|
+
/** Tell the owner on Weixin once the goal has waited on them a while; their reply comes back to this room. */
|
|
584
|
+
async notify_pending(room) {
|
|
585
|
+
const notice = this.pending_notice(room);
|
|
586
|
+
if (!notice || Date.now() < notice.due || Date.now() - (this.notice_failed_at ?? 0) < NOTICE_RETRY_MS) return;
|
|
587
|
+
if (!this.notifier.ready() || this.notifier.sent(notice.key)) return;
|
|
588
|
+
try {
|
|
589
|
+
// Weixin folds single line breaks, so each part is its own paragraph.
|
|
590
|
+
const question = notice.goal.phase_note ? ['主持人在等你确认:', notice.goal.phase_note] : await this.latest_excerpt(room);
|
|
591
|
+
const paragraphs = [...question, `目标:${notice.goal.objective}`, '直接回复这条消息,会作为你的发言发回这个房间。'];
|
|
592
|
+
const result = await this.notifier.send({ key: notice.key, room: { site: this.config.site, room: this.config.room, title: room.title }, paragraphs });
|
|
593
|
+
if (result.status === 'sent') this.log(`Goal 待确认已发微信通知 #${result.number}`);
|
|
594
|
+
} catch (error) {
|
|
595
|
+
this.notice_failed_at = Date.now();
|
|
596
|
+
this.log(`Goal 待确认微信通知失败:${error.message}`);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
/** The room's latest message from a person or member, for a pending goal nobody wrote a note for. */
|
|
600
|
+
async latest_excerpt(room) {
|
|
601
|
+
const page = await api(this.config, `/messages?after=${Math.max(0, (room.latest_id || 0) - 5)}`);
|
|
602
|
+
const latest = (page.messages || []).filter(message => message.author !== '系统').at(-1);
|
|
603
|
+
if (!latest) return ['房间在等你的决定或补充信息,详情见房间。'];
|
|
604
|
+
const text = latest.text.length > NOTICE_EXCERPT ? `${latest.text.slice(0, NOTICE_EXCERPT)}…` : latest.text;
|
|
605
|
+
return [`房间在等你回复。最近一条是 ${latest.author} 说:`, text];
|
|
606
|
+
}
|
|
607
|
+
/** Ask the decision model whether the idle goal room needs its host, from the latest messages and who is in it. */
|
|
608
|
+
async judge_goal(room, goal) {
|
|
609
|
+
const page = await api(this.config, `/messages?after=${Math.max(0, (room.latest_id || 0) - ROUTE_CONTEXT_MESSAGES)}`);
|
|
610
|
+
const context = page.messages || [];
|
|
611
|
+
const everyone = [...(this.inbox?.members || []), ...(this.inbox?.observers || [])];
|
|
612
|
+
const described = this.route_members(everyone, room, (context.at(-1)?.id || 0) + 1);
|
|
613
|
+
const host = described.find(member => member.role === 'host');
|
|
614
|
+
const decision = await decide_goal_wake(this.config.api_home, this.config.scheduler,
|
|
615
|
+
{ title: room.title, objective: goal.objective, context, host: host?.name || '主持人', members: described }, this.fetch);
|
|
616
|
+
return { ...decision, after_message_id: context.at(-1)?.id || 0 };
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Smart scheduling: for each new unnamed message routed to the host, ask the provider whether another woken
|
|
620
|
+
* member suits it better and apply a confident pick. The host waits for the answer (or its failure) before starting.
|
|
621
|
+
*/
|
|
622
|
+
recommend_unnamed(inbox, room) {
|
|
623
|
+
// Manual members are listed apart; they are never delivered to but may host or be recommended.
|
|
624
|
+
const everyone = [...inbox.members, ...(inbox.observers || [])];
|
|
625
|
+
const host = everyone.find(member => member.role === 'host');
|
|
626
|
+
const waiting = host?.pending.filter(request => request.purpose === 'route' && !request.group_action
|
|
627
|
+
&& !this.routed.has(request.id) && !this.saved_suggestion(request.id)) || [];
|
|
628
|
+
for (const request of waiting) {
|
|
629
|
+
this.routed.add(request.id);
|
|
630
|
+
if (everyone.length < 2) continue;
|
|
631
|
+
this.routing.add(request.id);
|
|
632
|
+
const decision = this.mark_routing(request.message_id, true)
|
|
633
|
+
.then(() => this.recommend(request, room, everyone))
|
|
634
|
+
.catch(error => {
|
|
635
|
+
if (!this.saved_suggestion(request.id)) this.save_suggestion(request, { action: 'host', actual_action: 'host',
|
|
636
|
+
applied: false, model_judgment: false, reason: `没有模型判断:${error.message}` });
|
|
637
|
+
this.log(`智能调度 #${request.message_id} 未给出推荐:${error.message}`);
|
|
638
|
+
})
|
|
639
|
+
.finally(() => { this.routing.delete(request.id); return this.mark_routing(request.message_id, false); });
|
|
640
|
+
this.decisions.add(decision);
|
|
641
|
+
decision.finally(() => { this.decisions.delete(decision); this.on_decided(); });
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* For each message naming everyone, have them all answer at once. @全体成员 is the user's explicit choice, so smart
|
|
646
|
+
* scheduling never judges it; answering one after another has its own entry (@全体依次).
|
|
647
|
+
*/
|
|
648
|
+
arrange_groups(inbox) {
|
|
649
|
+
const everyone = [...inbox.members, ...(inbox.observers || [])];
|
|
650
|
+
for (const request of everyone.flatMap(member => member.pending).filter(item => item.purpose === 'group' && !this.grouped.has(item.id))) {
|
|
651
|
+
this.grouped.add(request.id);
|
|
652
|
+
const arranged = this.order_group(request)
|
|
653
|
+
.catch(error => { this.grouped.delete(request.id); this.log(`全体成员 #${request.message_id} 未能安排:${error.message}`); });
|
|
654
|
+
this.decisions.add(arranged);
|
|
655
|
+
arranged.finally(() => { this.decisions.delete(arranged); this.on_decided(); });
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
async order_group(request) {
|
|
659
|
+
const plan = await api(this.config, `/recommendations/${request.message_id}`);
|
|
660
|
+
const result = await this.apply_group(request.message_id, { action: 'all' }, plan.revision);
|
|
661
|
+
if (!result.applied) throw new Error(result.error);
|
|
662
|
+
}
|
|
663
|
+
/** Apply once with the state that was judged; distinguish conflicts from failed writes and actual success. */
|
|
664
|
+
async apply_group(message_id, decision, revision) {
|
|
665
|
+
try {
|
|
666
|
+
await api(this.config, `/recommendations/${message_id}`, { action: decision.action, ...(revision ? { revision } : {}) });
|
|
667
|
+
this.log(`全体成员 #${message_id}:${{ all: '同时回答', sequential: '依次回答', host: '交给主持人' }[decision.action]}`);
|
|
668
|
+
return { status: 'applied', applied: true };
|
|
669
|
+
} catch (error) {
|
|
670
|
+
return { status: /HTTP (404|409)/.test(error.message) ? 'changed' : 'failed', applied: false, error: error.message };
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
/** Tell the website a message is being analysed so it can show the card; a failed mark never blocks routing. */
|
|
674
|
+
async mark_routing(message_id, active) {
|
|
675
|
+
try { await api(this.config, '/scheduler-routing', { message_id, active }); }
|
|
676
|
+
catch (error) { this.log(`智能调度 #${message_id} 分析状态未上报:${error.message}`); }
|
|
677
|
+
}
|
|
678
|
+
/** Describe each member as the scheduler sees it: software, project access and the other messages it is on. */
|
|
679
|
+
route_members(everyone, room, message_id) {
|
|
680
|
+
const requests = (room.free?.requests || []).filter(item => ['pending', 'delivering'].includes(item.status));
|
|
681
|
+
return everyone.map(member => {
|
|
682
|
+
const work = member_work(requests, member.name, message_id);
|
|
683
|
+
const profile = this.config.participants[member.name];
|
|
684
|
+
const described = room.descriptions?.[member.name] ? `;用户描述:${room.descriptions[member.name]}` : '';
|
|
685
|
+
// The model and the last finished message are only read by the guided wording.
|
|
686
|
+
const finished = (room.free?.requests || []).filter(item => item.member === member.name && item.status === 'completed' && item.message_id !== message_id).at(-1);
|
|
687
|
+
return { id: member.id, name: member.name, role: member.role, model: profile?.model || '', finished: finished ? `#${finished.message_id}` : '',
|
|
688
|
+
description: profile ? member_description(member.name, profile, `${work}${described}`)
|
|
689
|
+
: `${member.name}(手动接入,由用户代为触发${work}${described})` };
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
/** Retain a request-bound handoff across retries and service restarts; never inline model probabilities. */
|
|
693
|
+
save_suggestion(request, suggestion) {
|
|
694
|
+
const entry = { request_id: request.id, message_id: request.source_message_id || request.message_id, ...suggestion };
|
|
695
|
+
this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(`scheduler-suggestion:${request.id}`, JSON.stringify(entry));
|
|
696
|
+
return entry;
|
|
697
|
+
}
|
|
698
|
+
/** Recover the handoff for one exact request, independent of the room's recent decision window. */
|
|
699
|
+
saved_suggestion(request_id) {
|
|
700
|
+
const value = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(`scheduler-suggestion:${request_id}`)?.value;
|
|
701
|
+
return value ? JSON.parse(value) : null;
|
|
702
|
+
}
|
|
703
|
+
/** Save the website record id only after it is returned; failed logging never invents one. */
|
|
704
|
+
async record_route(request, decision, label, applied) {
|
|
705
|
+
const record = await this.record_decision(request.message_id, decision, label, applied);
|
|
706
|
+
this.save_suggestion(request, { action: decision.action, actual_action: applied ? decision.action : 'host', applied,
|
|
707
|
+
model_judgment: true, ...(record?.id ? { decision_id: record.id } : {}), reason: label });
|
|
708
|
+
}
|
|
709
|
+
/** Decide one message and apply a confident pick: one member, everyone, or no one; otherwise the host keeps it. */
|
|
710
|
+
async recommend(request, room, everyone) {
|
|
711
|
+
const page = await api(this.config, `/messages?after=${Math.max(0, request.message_id - ROUTE_CONTEXT_MESSAGES)}`);
|
|
712
|
+
const message = page.messages.find(item => item.id === request.message_id);
|
|
713
|
+
if (!message) throw new Error('读取不到这条消息');
|
|
714
|
+
const described = this.route_members(everyone, room, message.id);
|
|
715
|
+
const host = described.find(member => member.role === 'host');
|
|
716
|
+
const members = described.filter(member => member !== host);
|
|
717
|
+
const decision = await route_free_message(this.config.api_home, this.config.scheduler,
|
|
718
|
+
{ title: room.title, goal: room.goal, context: page.messages, message, host, members }, this.fetch);
|
|
719
|
+
this.save_suggestion(request, { action: decision.action, actual_action: 'unverified', applied: false,
|
|
720
|
+
model_judgment: true, reason: '判断已产生,自动动作结果尚未核验' });
|
|
721
|
+
this.log(`智能调度 #${message.id}:${decision.action}${decision.member ? ` ${decision.member}` : ''}(选择 ${decision.choice ?? '-'},置信度 ${decision.confidence ?? '-'})`);
|
|
722
|
+
if (decision.action === 'host') return this.record_route(request, decision, route_host_label(decision, host.name, members), false);
|
|
723
|
+
if (decision.action !== 'member') {
|
|
724
|
+
// Everyone, the named few or no one replaces the host's request in one step; a host that already started keeps the message.
|
|
725
|
+
const applied = await api(this.config, `/recommendations/${message.id}`, { action: decision.action, ...(decision.members ? { members: decision.members } : {}) })
|
|
726
|
+
.then(() => true, error => { this.log(`智能调度 #${message.id} 未能改派:${error.message}`); return false; });
|
|
727
|
+
const names = described.map(member => member.name).join('、');
|
|
728
|
+
const label = decision.action === 'all' ? `请全体各自回应(${names})` : decision.action === 'sequential' ? '请全体按发言顺序依次回应' : decision.action === 'some' ? `请 ${decision.members.join('、')} 各自回应` : '无需回应,未唤醒任何成员';
|
|
729
|
+
return this.record_route(request, decision, applied ? label : `${label}(未生效,仍由主持人处理)`, applied);
|
|
730
|
+
}
|
|
731
|
+
try {
|
|
732
|
+
await api(this.config, '/recommendations', { message_id: message.id, member_id: members.find(member => member.name === decision.member).id,
|
|
733
|
+
provider: this.config.scheduler.provider, confidence: decision.confidence });
|
|
734
|
+
} catch (error) {
|
|
735
|
+
await this.record_route(request, decision, `建议让 ${decision.member} 回答(推荐写入失败,未自动生效)`, false);
|
|
736
|
+
throw error;
|
|
737
|
+
}
|
|
738
|
+
// A confident pick is applied at once, interrupting the host; if that fails the recommendation stays for the user to adopt.
|
|
739
|
+
const adopted = await api(this.config, `/recommendations/${message.id}`, { action: 'adopt', mode: 'interrupt' })
|
|
740
|
+
.then(() => true, error => { this.log(`智能调度 #${message.id} 自动改派失败,保留推荐:${error.message}`); return false; });
|
|
741
|
+
await this.record_route(request, decision, adopted ? `改由 ${decision.member} 回答` : `建议让 ${decision.member} 回答(未能自动改派)`, adopted);
|
|
742
|
+
}
|
|
743
|
+
/** Show each judgment under its message so the user can rate it; a failed record never affects delivery. */
|
|
744
|
+
async record_decision(message_id, decision, label, applied, context = {}) {
|
|
745
|
+
const limits = scheduler_thresholds(this.config.scheduler.mode || DEFAULT_SCHEDULER_MODE);
|
|
746
|
+
try {
|
|
747
|
+
return await api(this.config, '/scheduler-decisions', { kind: 'interjection', label, confidence: decision.confidence ?? null,
|
|
748
|
+
applied, provider: this.config.scheduler.provider, after_message_id: message_id, detail: decision.detail, input: decision.input,
|
|
749
|
+
context: { model: this.config.scheduler.model, threshold: limits.member, wide_threshold: limits.wide,
|
|
750
|
+
mode: this.config.scheduler.mode || DEFAULT_SCHEDULER_MODE, prompt: route_prompt_version(this.config.scheduler.mode || DEFAULT_SCHEDULER_MODE), package: PACKAGE_VERSION, ...context } });
|
|
751
|
+
} catch (error) { this.log(`智能调度 #${message_id} 决策记录未保存:${error.message}`); }
|
|
752
|
+
}
|
|
753
|
+
/** Reserve with a persisted client id before invoking any software. */
|
|
754
|
+
async start(member, row) {
|
|
755
|
+
const record = this.save(member.name, { client_id: randomUUID(), execution_id: 0, status: 'reserving', error: '',
|
|
756
|
+
attempts: row?.attempts || 0 });
|
|
757
|
+
await this.reserve(member, record);
|
|
758
|
+
}
|
|
759
|
+
/** A retried client id returns the original execution; a finished or refused one just goes idle. */
|
|
760
|
+
async reserve(member, record) {
|
|
761
|
+
let execution;
|
|
762
|
+
const profile = this.config.participants[member.name];
|
|
763
|
+
const cwd = profile && !capabilities_of(profile.adapter).project ? '' : cwd_key(profile?.cwd ?? this.config.cwd);
|
|
764
|
+
try { execution = await api(this.config, '/executions', { member_id: member.id, client_id: record.client_id, cwd }); }
|
|
765
|
+
catch (error) {
|
|
766
|
+
if (/HTTP (404|409)/.test(error.message)) return this.save(member.name, { status: 'idle', error: '' });
|
|
767
|
+
throw error;
|
|
768
|
+
}
|
|
769
|
+
if (!['dispatched', 'started'].includes(execution.status)) return this.save(member.name, { status: 'idle' });
|
|
770
|
+
this.save(member.name, { execution_id: execution.id, status: 'delivering', started: Date.now(), last_renew: Date.now() });
|
|
771
|
+
await this.invoke(member, execution);
|
|
772
|
+
}
|
|
773
|
+
/** Hand the execution to the member's software; only proven non-delivery is released for retry. */
|
|
774
|
+
async invoke(member, execution, { resume = '', preface = '' } = {}) {
|
|
775
|
+
const adapter = this.config.participants[member.name];
|
|
776
|
+
const review_request = execution.requests?.find(request => request.review?.phase === 'review');
|
|
777
|
+
if (review_request) {
|
|
778
|
+
try { await this.check_review_delivery(member, review_request); }
|
|
779
|
+
catch (error) { return this.reject_review(member, execution, error.message); }
|
|
780
|
+
}
|
|
781
|
+
if (!adapter) return this.fail(member.name, execution.id, `未配置 ${member.name} 的本机接入`);
|
|
782
|
+
if (this.context_errors.has(member.name)) return this.fail(member.name, execution.id, this.context_errors.get(member.name));
|
|
783
|
+
const directory = capabilities_of(adapter.adapter).project ? adapter.cwd ?? this.config.cwd : undefined;
|
|
784
|
+
// A read-only member's software cannot write the project, so files changing meanwhile were written by someone else.
|
|
785
|
+
const before = adapter.project_access === 'read' ? null : workspace_snapshot(directory);
|
|
786
|
+
// The room's other directories this member may write are watched as well; their changes are reported with full paths.
|
|
787
|
+
const extras = member_extra_directories(this.config, adapter).filter(item => item.access === 'write')
|
|
788
|
+
.map(item => ({ directory: item.path, before: workspace_snapshot(item.path) })).filter(item => item.before);
|
|
789
|
+
// A resumed execution keeps the snapshot of its first delivery, so changes made before the pause are reported too.
|
|
790
|
+
if ((before || extras.length) && !this.snapshots.has(execution.id)) this.snapshots.set(execution.id, { member: member.name, directory, before, extras });
|
|
791
|
+
const generation = (this.generations.get(execution.id) || 0) + 1;
|
|
792
|
+
this.generations.set(execution.id, generation);
|
|
793
|
+
const current = () => this.generations.get(execution.id) === generation;
|
|
794
|
+
const binding = this.store.binding(member.name);
|
|
795
|
+
// A member whose session a rewind restarted is bound to '' and must not fall back to the session it was invited with.
|
|
796
|
+
if (binding.session_id === undefined && adapter.session_id) binding.session_id = adapter.session_id;
|
|
797
|
+
let invoked = false;
|
|
798
|
+
try {
|
|
799
|
+
// A resumed execution's session was already cut at its first delivery.
|
|
800
|
+
const warning = resume ? '' : await this.cut_rewound(member.name, adapter, binding, execution);
|
|
801
|
+
const session_request = execution.requests?.find(item => item.session_request_id && ['discuss', 'discuss_host'].includes(item.purpose));
|
|
802
|
+
const session = this.room?.session ? { ...this.room.session } : null;
|
|
803
|
+
const scheduler_suggestions = !this.config.scheduler || member.role !== 'host' ? []
|
|
804
|
+
: session_request?.purpose === 'discuss_host' ? this.session_driver.take_suggestions(session_request.id)
|
|
805
|
+
: execution.requests.map(request => this.saved_suggestion(request.id)).filter(Boolean);
|
|
806
|
+
const review_handoffs = await this.review_handoffs(execution);
|
|
807
|
+
// Executions the user stopped that this session may still hold; a rewind already cut its own out, and a new session holds none.
|
|
808
|
+
const rewound = new Set(execution.rewound_executions || []);
|
|
809
|
+
const stopped = binding.session_id ? this.stopped_executions(member.name).filter(id => !rewound.has(id)) : [];
|
|
810
|
+
const workflow = load_room_workflow(this.config);
|
|
811
|
+
// An unreadable workflow leaves members on their room settings; it is logged once per error, not every execution.
|
|
812
|
+
if (workflow?.error && this.workflow_error !== workflow.error) this.log(`工作流 ${workflow.id} 不可用:${workflow.error}`);
|
|
813
|
+
this.workflow_error = workflow?.error || '';
|
|
814
|
+
const task = free_task_files(this.config, member, execution, binding, {
|
|
815
|
+
session, suggestions: scheduler_suggestions, reviews: review_handoffs, stopped, workflow, room_members: this.room?.members,
|
|
816
|
+
goal: this.room?.goal_state?.goal || null,
|
|
817
|
+
});
|
|
818
|
+
invoked = true;
|
|
819
|
+
this.segments.start(execution.id);
|
|
820
|
+
if (warning) this.note(execution.id, warning);
|
|
821
|
+
const result = await this.deliver(review_request ? structuredClone(task.profile) : task.profile, binding, { ...task, ...(resume ? { prompt: resume } : preface ? { prompt: preface + task.prompt } : {}), room_title: this.room_title,
|
|
822
|
+
...(review_request ? { before_model_start: () => this.check_review_delivery(member, review_request) } : {}),
|
|
823
|
+
api_context: { site: this.config.site, room: this.config.room, token: this.config.members[member.name].token,
|
|
824
|
+
home: this.config.api_home, mode: 'free', role: member.role || 'member', execution_id: execution.id,
|
|
825
|
+
cwd: directory, project_access: adapter.project_access, extra_directories: task.extra_directories,
|
|
826
|
+
requests: execution.requests, read_after: execution.read_until, session, discussion_request: session_request,
|
|
827
|
+
scheduler_suggestions, review_handoffs, ...(task.workflow ? { workflow: task.workflow } : {}),
|
|
828
|
+
// Commands the enabled workflow registers; software with its own command line ignores them.
|
|
829
|
+
...(workflow?.commands?.length ? { commands: { directory: workflow.directory, list: workflow.commands } } : {}),
|
|
830
|
+
...(Number.isInteger(this.config.api_max_requests) ? { max_requests: this.config.api_max_requests } : {}),
|
|
831
|
+
...(task.goal ? { goal: task.goal } : {}) },
|
|
832
|
+
on_binding: session => this.store.bind(member.name, session),
|
|
833
|
+
on_process: child => this.track(member.name, child, execution.id),
|
|
834
|
+
on_output: (path, chunk) => { appendFileSync(path, chunk, { mode: 0o600 }); this.touch(execution.id); this.segments.mark(execution.id); },
|
|
835
|
+
on_activity: (phase, tool) => { this.touch(execution.id, phase); this.segments.mark(execution.id, phase, tool); },
|
|
836
|
+
on_note: text => this.note(execution.id, text),
|
|
837
|
+
// Files the agent edited with its own tools, read from its events; an empty call says the list is tracked.
|
|
838
|
+
on_edits: paths => {
|
|
839
|
+
const snapshot = this.snapshots.get(execution.id);
|
|
840
|
+
if (snapshot) paths.forEach(path => (snapshot.edited ||= new Set()).add(path));
|
|
841
|
+
if (snapshot && !paths.length) snapshot.edited ||= new Set();
|
|
842
|
+
},
|
|
843
|
+
// A stopped process may report after the next execution started; only its own execution takes the result.
|
|
844
|
+
on_failure: (error, { not_started = false, retryable = true } = {}) => {
|
|
845
|
+
if (!current()) return;
|
|
846
|
+
if (not_started) this.not_started.add(execution.id);
|
|
847
|
+
if (!retryable) this.not_retryable.add(execution.id);
|
|
848
|
+
try { if (this.row(member.name)?.execution_id === execution.id) this.save(member.name, { error }); } catch { /* Store may already be closed at shutdown. */ }
|
|
849
|
+
},
|
|
850
|
+
on_exit: denial => { if (current()) this.exited.set(execution.id, denial || ''); },
|
|
851
|
+
// Shown beside the answer or failure so the owner can allow them; a lost report only hides the list.
|
|
852
|
+
on_denials: denials => api(this.config, `/executions/${execution.id}`, { action: 'denials', denials }).catch(() => {}),
|
|
853
|
+
});
|
|
854
|
+
if (result.session_id) this.store.bind(member.name, result.session_id);
|
|
855
|
+
this.clear_stopped(member.name);
|
|
856
|
+
this.save(member.name, { status: result.status === 'sidecar_pending' ? 'sidecar_pending' : 'running', attempts: 0 });
|
|
857
|
+
if (result.steer) this.steers.set(execution.id, result.steer);
|
|
858
|
+
const delivery = result.capabilities || capabilities_of(adapter.adapter).delivery;
|
|
859
|
+
await this.report_delivery(execution.id, { ...delivery, steer: Boolean(result.steer),
|
|
860
|
+
resume: Boolean(capabilities_of(adapter.adapter).resume && delivery.stoppable) }, member.name);
|
|
861
|
+
} catch (error) {
|
|
862
|
+
if (review_request && error.delivery_status === 'not_sent') return this.reject_review(member, execution, error.message);
|
|
863
|
+
if (adapter.project_access === 'own') return this.retry_or_fail(member.name, execution, `投递失败:${error.message}`);
|
|
864
|
+
const attempts = (this.row(member.name)?.attempts || 0) + 1;
|
|
865
|
+
if ((invoked && error.delivery_status !== 'not_sent') || attempts >= MAX_DELIVERY_ATTEMPTS) {
|
|
866
|
+
return this.fail(member.name, execution.id, `投递失败:${error.message}`);
|
|
867
|
+
}
|
|
868
|
+
await api(this.config, `/executions/${execution.id}`, { action: 'release', reason: `确认未送达:${error.message}` });
|
|
869
|
+
this.save(member.name, { status: 'idle', attempts, error: error.message });
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
/** Recheck local configuration and the site's identity binding before a review starts. */
|
|
873
|
+
async check_review_delivery(member, request) {
|
|
874
|
+
const proof = request.review;
|
|
875
|
+
const version = review_capability_version(this.config.participants[member.name], member, this.config);
|
|
876
|
+
if (!version || version !== proof.config_version || this.context_errors.has(member.name)) throw new Error('没有可核验只读的评审成员:本机配置与预授权能力版本不符');
|
|
877
|
+
const current = await api(this.config, `/members/${member.id}/review-capability`);
|
|
878
|
+
if (current.revision !== proof.member_revision || current.capability?.config_version !== version) throw new Error('评审者资格或能力版本已改变');
|
|
879
|
+
}
|
|
880
|
+
/** Cancel only this isolated review execution and leave a durable reason for its host. */
|
|
881
|
+
async reject_review(member, execution, reason) {
|
|
882
|
+
await api(this.config, `/executions/${execution.id}`, { action: 'reject_review', reason });
|
|
883
|
+
this.save(member.name, { status: 'idle', error: reason });
|
|
884
|
+
this.stop_member(member.name);
|
|
885
|
+
}
|
|
886
|
+
/** Attach status and read entry points, never inline the implementation context into a wake-up. */
|
|
887
|
+
async review_handoffs(execution) {
|
|
888
|
+
const reviews = [];
|
|
889
|
+
for (const request of execution.requests || []) {
|
|
890
|
+
if (request.review?.phase !== 'handoff') continue;
|
|
891
|
+
const batch_id = request.review.batch_id;
|
|
892
|
+
try {
|
|
893
|
+
const state = await api(this.config, `/reviews/${batch_id}/ready`);
|
|
894
|
+
reviews.push({ batch_id, request_id: request.id, ready: state.ready, reason: state.reason,
|
|
895
|
+
reviewer: state.plan.reviewer_name, scope: state.plan.scope });
|
|
896
|
+
} catch (error) { reviews.push({ batch_id, request_id: request.id, ready: false, reason: `无法读取评审推进状态:${error.message}` }); }
|
|
897
|
+
}
|
|
898
|
+
return reviews;
|
|
899
|
+
}
|
|
900
|
+
/**
|
|
901
|
+
* Before a member works again after a rewind, branch its session before the executions the rewind took back.
|
|
902
|
+
* A Claude fork happens on its next turn, so it stays pending until that session exists. Returns a warning when the
|
|
903
|
+
* session could not be cut and the member continues in the old one.
|
|
904
|
+
*/
|
|
905
|
+
async cut_rewound(name, adapter, binding, execution) {
|
|
906
|
+
const key = `session-fork:${name}`;
|
|
907
|
+
const pending = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(key)?.value;
|
|
908
|
+
if (pending && !session_exists(adapter.adapter, binding.session_id)) { binding.fork = JSON.parse(pending); return ''; }
|
|
909
|
+
if (pending) this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(key);
|
|
910
|
+
if (!binding.session_id || !execution.rewound_executions?.length || !BRANCHABLE_ADAPTERS.includes(adapter.adapter)) return '';
|
|
911
|
+
try {
|
|
912
|
+
const cut = await branch_session(adapter, binding.session_id, execution.rewound_executions);
|
|
913
|
+
if (!cut) return '';
|
|
914
|
+
if (cut.fork) this.store.db.prepare('INSERT INTO metadata VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key, JSON.stringify(cut.fork));
|
|
915
|
+
this.store.bind(name, cut.session_id);
|
|
916
|
+
Object.assign(binding, cut);
|
|
917
|
+
return '';
|
|
918
|
+
} catch (error) { return `会话未能回退(${error.message}),本次沿用原会话,它可能仍记得已回退的内容`; }
|
|
919
|
+
}
|
|
920
|
+
/** Follow the website's verdict; stop only this member's processes when its execution ends. */
|
|
921
|
+
async reconcile(member, row, active) {
|
|
922
|
+
if (row.status === 'reserving') return this.reserve(member, row);
|
|
923
|
+
if (row.status === 'sidecar_pending') {
|
|
924
|
+
const receipt = delivery_receipt(this.config.participants[member.name], `free-${row.execution_id}`);
|
|
925
|
+
if (receipt?.status === 'accepted' && receipt.session_id) {
|
|
926
|
+
this.store.bind(member.name, receipt.session_id);
|
|
927
|
+
this.save(member.name, { status: 'running' });
|
|
928
|
+
} else if (receipt && active.has(row.execution_id)) return this.retry_or_fail(member.name, active.get(row.execution_id), receipt.error || 'Sidecar 投递结果不明,请核对原会话');
|
|
929
|
+
}
|
|
930
|
+
const execution = active.get(row.execution_id);
|
|
931
|
+
if (!execution) {
|
|
932
|
+
this.forget_owner(row.execution_id);
|
|
933
|
+
this.activity.delete(row.execution_id);
|
|
934
|
+
await this.report_segments(row.execution_id, true);
|
|
935
|
+
this.stop_member(member.name);
|
|
936
|
+
return this.save(member.name, { status: 'idle', error: '' });
|
|
937
|
+
}
|
|
938
|
+
if (row.status === 'retry_wait') {
|
|
939
|
+
const retry = execution.retry;
|
|
940
|
+
if (retry?.stopped) return this.fail(member.name, execution.id, `${retry.reason}(已停止自动重试)`);
|
|
941
|
+
if (retry?.retry_at && Date.now() >= retry.retry_at * 1000) {
|
|
942
|
+
await api(this.config, `/executions/${execution.id}`, { action: 'retry_start' });
|
|
943
|
+
this.save(member.name, { status: 'delivering' });
|
|
944
|
+
// Read from the site's retry record, so a second restart during the wait still delivers it as a continuation.
|
|
945
|
+
const preface = retry?.reason === RESTART_REASON ? restart_notice(execution.id) : '';
|
|
946
|
+
return this.invoke(member, await api(this.config, `/executions/${execution.id}`), { preface });
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
// A restart between persisting and invoking cannot prove non-delivery, so it never resends.
|
|
950
|
+
if (row.status === 'delivering') return this.fail(member.name, execution.id, '上次投递结果不明,未自动重发;请核对原会话后重新发送');
|
|
951
|
+
if (execution.paused_at) {
|
|
952
|
+
// A paused turn ending is not a failure: the execution waits, renewed, for the owner's words.
|
|
953
|
+
if (await this.hold_paused(member, row, execution)) return;
|
|
954
|
+
} else {
|
|
955
|
+
// Inherited from a runner that stopped or crashed: once its software processes are gone, no answer can come, so the
|
|
956
|
+
// same execution is delivered again after the retry wait instead of handing the failure to the host.
|
|
957
|
+
if (row.status === 'running' && this.orphan(execution.id)?.alive === false) {
|
|
958
|
+
return this.retry_or_fail(member.name, execution, RESTART_REASON, { restarted: true });
|
|
959
|
+
}
|
|
960
|
+
if (row.error) return this.retry_or_fail(member.name, execution, row.error);
|
|
961
|
+
if (this.exited.has(execution.id)) {
|
|
962
|
+
const latest = await api(this.config, `/executions/${execution.id}`);
|
|
963
|
+
const denial = this.exited.get(execution.id);
|
|
964
|
+
if (['dispatched', 'started'].includes(latest.status)) return this.fail(member.name, execution.id, denial
|
|
965
|
+
? `${member.name} ${denial},未提交本次回答`
|
|
966
|
+
: `${member.name} 会话已结束,但未提交本次回答;请核对原会话确认是否已有内容`);
|
|
967
|
+
return this.save(member.name, { status: 'idle' });
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
// Segments and notes go first, quietly and often, so a renewal in the same tick already shows the notes it announces.
|
|
971
|
+
if (this.segments.due(execution.id, PROGRESS_REPORT_MS)) await this.report_segments(execution.id);
|
|
972
|
+
const activity = this.activity.get(execution.id);
|
|
973
|
+
const changed = activity && (activity.phase !== activity.sent_phase || activity.at !== activity.sent_at);
|
|
974
|
+
const elapsed = Date.now() - row.last_renew;
|
|
975
|
+
if (elapsed >= RENEW_MS || (changed && elapsed >= ACTIVITY_REPORT_MS)) {
|
|
976
|
+
await api(this.config, `/executions/${execution.id}`, { action: 'renew',
|
|
977
|
+
...(activity ? { activity: activity.phase, activity_at: Math.floor(activity.at / 1000) } : {}) });
|
|
978
|
+
if (activity) Object.assign(activity, { sent_phase: activity.phase, sent_at: activity.at });
|
|
979
|
+
this.save(member.name, { last_renew: Date.now() });
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* An execution the owner paused from the private chat, or that takes an interjection only by a pause: stop its
|
|
984
|
+
* software turn and keep the execution live; once that turn has ended and the owner's words wait, resume the same
|
|
985
|
+
* execution in the same session with them. Returns true when it resumed, so the caller does nothing more this tick.
|
|
986
|
+
*/
|
|
987
|
+
async hold_paused(member, row, execution) {
|
|
988
|
+
this.steers.delete(execution.id);
|
|
989
|
+
const processes = this.execution_processes.get(execution.id);
|
|
990
|
+
for (const child of processes || []) this.request_stop(child);
|
|
991
|
+
this.exited.delete(execution.id);
|
|
992
|
+
this.not_started.delete(execution.id);
|
|
993
|
+
this.not_retryable.delete(execution.id);
|
|
994
|
+
if (row.error) this.save(member.name, { error: '' });
|
|
995
|
+
if (processes?.size || !execution.interjections?.length) return false;
|
|
996
|
+
this.save(member.name, { status: 'delivering', error: '' });
|
|
997
|
+
await api(this.config, `/executions/${execution.id}`, { action: 'resume' });
|
|
998
|
+
await this.invoke(member, execution, { resume: resume_prompt(execution.id, execution.interjections.map(item => item.text)) });
|
|
999
|
+
if (this.row(member.name)?.status !== 'running') return true;
|
|
1000
|
+
for (const interjection of execution.interjections) {
|
|
1001
|
+
this.interjecting.set(interjection.id, { status: 'delivered' });
|
|
1002
|
+
await api(this.config, `/executions/${execution.id}`, { action: 'interjection', interjection_id: interjection.id, status: 'delivered' })
|
|
1003
|
+
.catch(error => this.log(`插话 #${interjection.id} 的结果未能上报:${error.message}`));
|
|
1004
|
+
}
|
|
1005
|
+
return true;
|
|
1006
|
+
}
|
|
1007
|
+
/**
|
|
1008
|
+
* Tell the site what this delivery can do, as the adapter reported it: whether the runner can stop it and see its
|
|
1009
|
+
* progress. Kept locally until the execution ends so a restarted runner still knows whether it could stop it.
|
|
1010
|
+
* A lost report is retained for the final stop result; sites and runners must use the same capability protocol.
|
|
1011
|
+
*/
|
|
1012
|
+
async report_delivery(execution_id, { stoppable, progress, steer = false, resume = false }, member) {
|
|
1013
|
+
this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(`delivery:${execution_id}`, JSON.stringify({ stoppable, progress, member }));
|
|
1014
|
+
await api(this.config, `/executions/${execution_id}`, { action: 'delivery', stoppable, progress, steer, resume })
|
|
1015
|
+
.catch(error => this.log(`执行 #${execution_id} 的投递能力未能上报:${error.message}`));
|
|
1016
|
+
}
|
|
1017
|
+
/** Retry durable stop reports even after the member went idle, left, or started a later execution. */
|
|
1018
|
+
async report_stops(active) {
|
|
1019
|
+
const pending = new Set();
|
|
1020
|
+
for (const { key, value } of this.store.db.prepare("SELECT key,value FROM metadata WHERE key LIKE 'delivery:%'").all()) {
|
|
1021
|
+
const execution_id = Number(key.slice('delivery:'.length));
|
|
1022
|
+
if (active.has(execution_id)) continue;
|
|
1023
|
+
const delivery = stored_delivery(value);
|
|
1024
|
+
const name = delivery.member || this.store.db.prepare('SELECT member FROM free_deliveries WHERE execution_id=?').get(execution_id)?.member;
|
|
1025
|
+
if (!name) continue;
|
|
1026
|
+
for (const child of this.execution_processes.get(execution_id) || []) this.request_stop(child);
|
|
1027
|
+
try { await this.report_stop(name, execution_id); }
|
|
1028
|
+
catch (error) { pending.add(name); this.log(`执行 #${execution_id} 的停止结果未能上报:${error.message}`); }
|
|
1029
|
+
}
|
|
1030
|
+
return pending;
|
|
1031
|
+
}
|
|
1032
|
+
/** Report observed termination, never infer it from a capability or a successfully sent kill signal. */
|
|
1033
|
+
async report_stop(name, execution_id) {
|
|
1034
|
+
const key = `delivery:${execution_id}`;
|
|
1035
|
+
const value = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(key)?.value;
|
|
1036
|
+
if (!value) return;
|
|
1037
|
+
const delivery = stored_delivery(value), processes = this.execution_processes.get(execution_id);
|
|
1038
|
+
const ended = processes ? processes.size === 0 : this.exited.has(execution_id) || this.orphan(execution_id)?.alive === false;
|
|
1039
|
+
const result = delivery.pending_result && delivery.pending_result !== 'unconfirmed' ? delivery.pending_result
|
|
1040
|
+
: !delivery.stoppable ? 'unstoppable' : ended ? 'stopped' : 'unconfirmed';
|
|
1041
|
+
if (delivery.stop_result === result) return;
|
|
1042
|
+
// An execution that left the inbox by finishing normally has no stop to report; only a voided one does.
|
|
1043
|
+
if (['completed', 'failed'].includes((await api(this.config, `/executions/${execution_id}`)).status)) {
|
|
1044
|
+
this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(key);
|
|
1045
|
+
this.execution_processes.delete(execution_id);
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
// Keep the observed outcome before sending: a restart after a lost response must retry the same fact.
|
|
1049
|
+
this.store.db.prepare('UPDATE metadata SET value=? WHERE key=?')
|
|
1050
|
+
.run(JSON.stringify({ ...delivery, member: name, pending_result: result }), key);
|
|
1051
|
+
try { await api(this.config, `/executions/${execution_id}`, { action: 'stopped', result }); }
|
|
1052
|
+
catch (error) {
|
|
1053
|
+
if (!/HTTP 409:/.test(error.message)) throw error;
|
|
1054
|
+
const latest = await api(this.config, `/executions/${execution_id}`);
|
|
1055
|
+
// A conflict is not necessarily normal completion: keep cancelled reports until an idempotent receipt arrives.
|
|
1056
|
+
if (!['completed', 'failed'].includes(latest.status)) throw error;
|
|
1057
|
+
this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(key);
|
|
1058
|
+
this.execution_processes.delete(execution_id);
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)')
|
|
1062
|
+
.run(`stopped:${name}`, JSON.stringify([...new Set([...this.stopped_executions(name), execution_id])]));
|
|
1063
|
+
if (result === 'unconfirmed') {
|
|
1064
|
+
this.store.db.prepare('UPDATE metadata SET value=? WHERE key=?')
|
|
1065
|
+
.run(JSON.stringify({ ...delivery, member: name, pending_result: result, stop_result: result }), key);
|
|
1066
|
+
// The site's bounded hold now controls the next delivery; retain handles to observe and retry termination.
|
|
1067
|
+
for (const child of processes || []) this.members.get(name)?.delete(child);
|
|
1068
|
+
}
|
|
1069
|
+
else { this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(key); this.execution_processes.delete(execution_id); this.forget_owner(execution_id); }
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* An execution whose handles an earlier runner process tracked and this one does not: `{alive}` says whether any of its
|
|
1073
|
+
* recorded software processes still runs. A handle without a pid lived inside that runner, so it ended with it.
|
|
1074
|
+
*/
|
|
1075
|
+
orphan(execution_id) {
|
|
1076
|
+
if (this.execution_processes.has(execution_id)) return null;
|
|
1077
|
+
const saved = JSON.parse(this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(`owner:${execution_id}`)?.value || 'null');
|
|
1078
|
+
if (!saved || saved.instance === this.instance) return null;
|
|
1079
|
+
return { alive: saved.pids.some(process_alive) };
|
|
1080
|
+
}
|
|
1081
|
+
/** Record that this runner process tracks a handle of the execution, with its pid when it is a separate process. */
|
|
1082
|
+
record_owner(execution_id, pid) {
|
|
1083
|
+
const key = `owner:${execution_id}`;
|
|
1084
|
+
const saved = JSON.parse(this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(key)?.value || 'null');
|
|
1085
|
+
const pids = saved?.instance === this.instance ? saved.pids : [];
|
|
1086
|
+
if (Number.isInteger(pid) && !pids.includes(pid)) pids.push(pid);
|
|
1087
|
+
this.store.db.prepare('INSERT OR REPLACE INTO metadata VALUES (?,?)').run(key, JSON.stringify({ instance: this.instance, pids }));
|
|
1088
|
+
}
|
|
1089
|
+
forget_owner(execution_id) { this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(`owner:${execution_id}`); }
|
|
1090
|
+
/** Once a new task received the stop reminders, retire acknowledged unconfirmed reports for its old turns. */
|
|
1091
|
+
clear_stopped(name) {
|
|
1092
|
+
for (const id of this.stopped_executions(name)) {
|
|
1093
|
+
const key = `delivery:${id}`, value = this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(key)?.value;
|
|
1094
|
+
if (value && stored_delivery(value).stop_result === 'unconfirmed') {
|
|
1095
|
+
this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(key);
|
|
1096
|
+
this.execution_processes.delete(id);
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
this.store.db.prepare('DELETE FROM metadata WHERE key=?').run(`stopped:${name}`);
|
|
1100
|
+
}
|
|
1101
|
+
/** Executions the user stopped since this member's last delivered task. */
|
|
1102
|
+
stopped_executions(name) {
|
|
1103
|
+
return JSON.parse(this.store.db.prepare('SELECT value FROM metadata WHERE key=?').get(`stopped:${name}`)?.value || '[]');
|
|
1104
|
+
}
|
|
1105
|
+
/** Send the execution's recorded segments and progress notes; `final` sends the rest once it has ended. */
|
|
1106
|
+
report_segments(execution_id, final = false) {
|
|
1107
|
+
return this.segments.report(execution_id, final, ({ segments, notes }) =>
|
|
1108
|
+
api(this.config, `/executions/${execution_id}`, { action: 'segments', segments, ...(notes.length ? { notes } : {}) }));
|
|
1109
|
+
}
|
|
1110
|
+
/** Note that the software produced output now, and its phase when the output names one. */
|
|
1111
|
+
touch(execution_id, phase) {
|
|
1112
|
+
// Updated in place: a renewal in flight marks what it sent on this same record.
|
|
1113
|
+
if (!this.activity.has(execution_id)) this.activity.set(execution_id, { phase: '' });
|
|
1114
|
+
const current = this.activity.get(execution_id);
|
|
1115
|
+
if (phase) current.phase = phase;
|
|
1116
|
+
current.at = Date.now();
|
|
1117
|
+
}
|
|
1118
|
+
/** Queue one progress note for the next progress report; numbering makes a retried report harmless. */
|
|
1119
|
+
note(execution_id, text) {
|
|
1120
|
+
this.touch(execution_id);
|
|
1121
|
+
this.segments.note(execution_id, text);
|
|
1122
|
+
}
|
|
1123
|
+
/** Report observed file changes once an execution has ended and its member's processes have exited. */
|
|
1124
|
+
async report_finished(active) {
|
|
1125
|
+
for (const [execution_id, snapshot] of this.snapshots) {
|
|
1126
|
+
if (active.has(execution_id) || this.execution_processes.get(execution_id)?.size) continue;
|
|
1127
|
+
this.snapshots.delete(execution_id);
|
|
1128
|
+
const after = snapshot.before ? workspace_snapshot(snapshot.directory) : null;
|
|
1129
|
+
if (!after && !snapshot.extras?.length) continue;
|
|
1130
|
+
const extra = (snapshot.extras || []).flatMap(item => {
|
|
1131
|
+
const current = workspace_snapshot(item.directory);
|
|
1132
|
+
return current ? changed_between(item.before, current).map(path => extra_change(item.directory, path)) : [];
|
|
1133
|
+
});
|
|
1134
|
+
const changes = [...(after ? changed_between(snapshot.before, after) : []), ...extra].slice(0, 200);
|
|
1135
|
+
// `edited` is sent only when the adapter tracked edits; without it the site cannot tell who wrote a shared file.
|
|
1136
|
+
const edited = snapshot.edited ? { edited: edited_changes(changes, snapshot.edited) } : {};
|
|
1137
|
+
try { await api(this.config, `/executions/${execution_id}`, { action: 'report', changes, ...edited }); }
|
|
1138
|
+
catch (error) { if (!/HTTP (404|409)/.test(error.message)) throw error; }
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
/**
|
|
1142
|
+
* A manual member's session refused the delivery, or the software failed before any turn ran: keep the execution and
|
|
1143
|
+
* deliver again after a wait shown on the website, up to MAX_DELIVERY_RETRIES times; so is an execution whose software
|
|
1144
|
+
* ended with the previous runner process (`restarted`). Anything else, or the last attempt, fails as before.
|
|
1145
|
+
*/
|
|
1146
|
+
async retry_or_fail(name, execution, reason, { restarted = false } = {}) {
|
|
1147
|
+
const attempt = (execution.retry?.attempt || 0) + 1;
|
|
1148
|
+
const not_started = this.not_started.delete(execution.id);
|
|
1149
|
+
if (this.not_retryable.delete(execution.id)) return this.fail(name, execution.id, reason);
|
|
1150
|
+
if (!restarted && this.config.participants[name]?.project_access !== 'own' && !not_started) return this.fail(name, execution.id, reason);
|
|
1151
|
+
if (attempt > MAX_DELIVERY_RETRIES) return this.fail(name, execution.id, `${reason}(已自动重试 ${MAX_DELIVERY_RETRIES} 次)`);
|
|
1152
|
+
this.stop_member(name);
|
|
1153
|
+
this.exited.delete(execution.id);
|
|
1154
|
+
await api(this.config, `/executions/${execution.id}`, { action: 'retry_wait', attempt,
|
|
1155
|
+
retry_at: Math.floor(Date.now() / 1000) + (restarted ? RESTART_RETRY_DELAY_SECONDS : RETRY_DELAY_SECONDS), reason: reason.slice(0, MAX_RETRY_REASON) });
|
|
1156
|
+
this.save(name, { status: 'retry_wait', error: '' });
|
|
1157
|
+
}
|
|
1158
|
+
/** Record the cause on the website, then stop this member's own processes. */
|
|
1159
|
+
async fail(name, execution_id, reason) {
|
|
1160
|
+
this.activity.delete(execution_id);
|
|
1161
|
+
this.not_started.delete(execution_id);
|
|
1162
|
+
this.not_retryable.delete(execution_id);
|
|
1163
|
+
await this.report_segments(execution_id, true);
|
|
1164
|
+
try { await api(this.config, `/executions/${execution_id}`, { action: 'fail', reason }); }
|
|
1165
|
+
catch (error) { if (!/HTTP 409/.test(error.message)) throw error; }
|
|
1166
|
+
this.save(name, { status: 'idle', error: reason });
|
|
1167
|
+
this.stop_member(name);
|
|
1168
|
+
this.forget_owner(execution_id);
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Hand the owner's pending interjections to the software running each execution, in order, through the steer handle
|
|
1172
|
+
* its delivery returned; report each as delivered or failed. A handle is dropped once its execution is no longer live.
|
|
1173
|
+
*/
|
|
1174
|
+
async deliver_interjections(executions) {
|
|
1175
|
+
const live = new Set(executions.map(item => item.id));
|
|
1176
|
+
for (const id of this.steers.keys()) if (!live.has(id)) this.steers.delete(id);
|
|
1177
|
+
for (const execution of executions) {
|
|
1178
|
+
// A paused execution hears its interjections when it resumes (hold_paused).
|
|
1179
|
+
if (execution.paused_at) continue;
|
|
1180
|
+
for (const interjection of execution.interjections || []) {
|
|
1181
|
+
// An interjection is handed over once; a lost report is sent again with the same outcome.
|
|
1182
|
+
let report = this.interjecting.get(interjection.id);
|
|
1183
|
+
if (!report) {
|
|
1184
|
+
const steer = this.steers.get(execution.id);
|
|
1185
|
+
report = { status: 'failed', reason: '本次投递不支持执行中插话' };
|
|
1186
|
+
if (steer) {
|
|
1187
|
+
try { report = await steer(interjection.text) ? { status: 'delivered' } : { status: 'failed', reason: '它已结束本轮,插话未送达' }; }
|
|
1188
|
+
catch (error) { report = { status: 'failed', reason: String(error.message).slice(0, 400) }; }
|
|
1189
|
+
}
|
|
1190
|
+
this.interjecting.set(interjection.id, report);
|
|
1191
|
+
}
|
|
1192
|
+
try { await api(this.config, `/executions/${execution.id}`, { action: 'interjection', interjection_id: interjection.id, ...report }); }
|
|
1193
|
+
catch (error) { this.log(`插话 #${interjection.id} 的结果未能上报:${error.message}`); }
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
/**
|
|
1198
|
+
* The owner's private chat lines (backend/private_chat.py), each run as a turn of its member's own session once the
|
|
1199
|
+
* member is idle, the reply taken from the software's last remark. A line sent while a chat turn runs goes into it
|
|
1200
|
+
* as an interjection; a running line the owner stopped ends its process; one the runner lost at a restart fails.
|
|
1201
|
+
*/
|
|
1202
|
+
async run_chats(members) {
|
|
1203
|
+
for (const member of members) {
|
|
1204
|
+
const chats = member.chats || [];
|
|
1205
|
+
const live = this.chat_turns.get(member.name);
|
|
1206
|
+
if (live && !chats.some(chat => chat.id === live.id && chat.status === 'running')) {
|
|
1207
|
+
if (live.child) this.request_stop(live.child);
|
|
1208
|
+
continue;
|
|
1209
|
+
}
|
|
1210
|
+
for (const chat of chats) {
|
|
1211
|
+
if (chat.status === 'running' && chat.id !== live?.id) await this.chat_report(chat.id, { action: 'fail', reason: '本机服务重启,这轮私聊已中断' });
|
|
1212
|
+
else if (chat.status === 'pending' && live?.steer && !live.steered.has(chat.id)) {
|
|
1213
|
+
live.steered.add(chat.id);
|
|
1214
|
+
if (await live.steer(chat.text)) await this.chat_report(chat.id, { action: 'steered' });
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
const next = chats.find(chat => chat.status === 'pending' && !live?.steered.has(chat.id));
|
|
1218
|
+
const row = this.row(member.name);
|
|
1219
|
+
if (next && !live && !this.members.get(member.name)?.size && !(row && LIVE.includes(row.status))) await this.start_chat(member, next);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
/** Start one chat line as its own turn; the turn reports its reply or failure when it ends, without holding the tick. */
|
|
1223
|
+
async start_chat(member, chat) {
|
|
1224
|
+
const profile = this.config.participants[member.name];
|
|
1225
|
+
const binding = this.store.binding(member.name) || {};
|
|
1226
|
+
const adapter = profile && adapter_of(profile.adapter);
|
|
1227
|
+
if (!adapter || !capabilities_of(profile.adapter).chat || (!adapter.chat && adapter.into_window?.(profile, binding))) {
|
|
1228
|
+
return this.chat_report(chat.id, { action: 'fail', reason: '这位成员的接入方式看不到它的输出,暂不支持私聊窗;可在它自己的窗口里对话' });
|
|
1229
|
+
}
|
|
1230
|
+
if (!await this.chat_report(chat.id, { action: 'start' })) return;
|
|
1231
|
+
const turn = { id: chat.id, child: null, steer: null, steered: new Set() };
|
|
1232
|
+
this.chat_turns.set(member.name, turn);
|
|
1233
|
+
const notes = [];
|
|
1234
|
+
let settle;
|
|
1235
|
+
const ended = new Promise(resolve => { settle = resolve; });
|
|
1236
|
+
try {
|
|
1237
|
+
const task = chat_task_files(this.config, member, chat, binding);
|
|
1238
|
+
// Software without its own session (the model API) takes the earlier lines as its context.
|
|
1239
|
+
const history = (await api(this.config, `/members/${member.id}/chat`).catch(() => ({ chats: [] }))).chats
|
|
1240
|
+
.filter(item => item.id !== chat.id && item.status === 'answered').map(item => ({ text: item.text, reply: item.reply }));
|
|
1241
|
+
const result = await this.deliver(task.profile, binding, { ...task, room_title: this.room_title, chat: true, chat_history: history,
|
|
1242
|
+
api_context: { site: this.config.site, room: this.config.room, token: this.config.members[member.name].token,
|
|
1243
|
+
home: this.config.api_home, mode: 'free', role: member.role || 'member', cwd: task.profile.cwd || this.config.cwd,
|
|
1244
|
+
project_access: task.profile.project_access, ...(Number.isInteger(this.config.api_max_requests) ? { max_requests: this.config.api_max_requests } : {}) },
|
|
1245
|
+
on_binding: session => this.store.bind(member.name, session),
|
|
1246
|
+
on_process: child => { turn.child = child; this.track(member.name, child, `chat-${chat.id}`); },
|
|
1247
|
+
on_output: (path, chunk) => appendFileSync(path, chunk, { mode: 0o600 }),
|
|
1248
|
+
on_activity: () => {}, on_note: text => notes.push(text), on_edits: () => {},
|
|
1249
|
+
on_failure: error => settle({ error }), on_exit: () => settle({}), on_denials: () => {} });
|
|
1250
|
+
if (result.session_id) this.store.bind(member.name, result.session_id);
|
|
1251
|
+
turn.steer = result.steer || null;
|
|
1252
|
+
} catch (error) { settle({ error: error.message }); }
|
|
1253
|
+
ended.then(async ({ error }) => {
|
|
1254
|
+
this.chat_turns.delete(member.name);
|
|
1255
|
+
const reply = notes.at(-1);
|
|
1256
|
+
await this.chat_report(chat.id, !error && reply ? { action: 'reply', text: reply.slice(0, CHAT_REPLY_LIMIT) }
|
|
1257
|
+
: { action: 'fail', reason: String(error || '它没有给出文字回复').slice(0, 400) });
|
|
1258
|
+
});
|
|
1259
|
+
}
|
|
1260
|
+
/** Tell the site how one chat line went; false when the site refused it (the owner already stopped it). */
|
|
1261
|
+
async chat_report(chat_id, payload) {
|
|
1262
|
+
try { await api(this.config, `/chats/${chat_id}`, payload); return true; }
|
|
1263
|
+
catch (error) { this.log(`私聊 #${chat_id} ${payload.action} 未能上报:${error.message}`); return false; }
|
|
1264
|
+
}
|
|
1265
|
+
/** Count live processes per member so one session never has two writers. */
|
|
1266
|
+
track(name, child, execution_id = this.row(name)?.execution_id) {
|
|
1267
|
+
this.children.add(child);
|
|
1268
|
+
if (!this.members.has(name)) this.members.set(name, new Set());
|
|
1269
|
+
this.members.get(name).add(child);
|
|
1270
|
+
if (!this.execution_processes.has(execution_id)) this.execution_processes.set(execution_id, new Set());
|
|
1271
|
+
const processes = this.execution_processes.get(execution_id);
|
|
1272
|
+
processes.add(child);
|
|
1273
|
+
// A handle only the owner may stop keeps running in the user's software, so a later runner must not fail it.
|
|
1274
|
+
if (Number.isInteger(execution_id) && child.stop_on_shutdown !== false) this.record_owner(execution_id, child.pid);
|
|
1275
|
+
child.once('close', () => { processes.delete(child); this.children.delete(child); this.members.get(name).delete(child); });
|
|
1276
|
+
}
|
|
1277
|
+
/** Request termination; only a later close event proves it happened. */
|
|
1278
|
+
request_stop(child) { try { child.kill(); } catch { /* The stop report remains unconfirmed. */ } }
|
|
1279
|
+
/** Stop one member's processes without touching other members or desktop apps. */
|
|
1280
|
+
stop_member(name) { for (const child of this.members.get(name) || []) this.request_stop(child); }
|
|
1281
|
+
/**
|
|
1282
|
+
* Stop every process this runner created, except a handle whose stop only the owner asks for (`stop_on_shutdown:
|
|
1283
|
+
* false`, e.g. a stop that changes the user's App): that turn runs on in the software and is not reported.
|
|
1284
|
+
*/
|
|
1285
|
+
stop_children() { for (const child of this.children) if (child.stop_on_shutdown !== false) this.request_stop(child); }
|
|
1286
|
+
}
|