Skip to content

Commit f250087

Browse files
author
linyuan.yang
committed
shutdown
1 parent e994ef5 commit f250087

13 files changed

Lines changed: 153 additions & 15 deletions

File tree

‎packages/admin/src/i18n/en.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,10 @@ export default {
235235
http_url: 'HTTP URL',
236236
port_changed: 'Port changed. Restart the service for the change to take effect.',
237237
service: 'Service',
238+
shutdown: 'Stop Service',
239+
shutdown_hint: 'Stops new tasks, then exits after active agent, memory, and agenda work has completed.',
240+
shutdown_confirm: 'Stop the service? Active tasks will finish before it exits.',
241+
shutdown_started: 'Service is stopping and will exit after active tasks complete.',
238242
max_image_size: 'Max Image Size (px)',
239243
max_image_size_hint: 'Images exceeding this size will be proportionally resized. Leave empty to disable.',
240244
version_updates: 'Version Updates',

‎packages/admin/src/i18n/zh.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,10 @@ export default {
235235
http_url: 'HTTP URL',
236236
port_changed: '端口已变更,修改将在重启服务后生效',
237237
service: '服务',
238+
shutdown: '停止服务',
239+
shutdown_hint: '停止接收新任务,等待正在执行的智能体、记忆和事项任务完成后退出。',
240+
shutdown_confirm: '确定停止服务?正在执行的任务会先完成,然后服务退出。',
241+
shutdown_started: '服务正在停止,当前任务完成后将退出。',
238242
max_image_size: '图片最大尺寸 (px)',
239243
max_image_size_hint: '图片宽高超过此值时按比例缩小,不设置则不压缩',
240244
version_updates: '版本更新',

‎packages/admin/src/views/SettingsView.vue‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ const autoApproveToolsText = ref('')
1717
const startupCommands = ref<string[]>([])
1818
const autoCheckUpdate = ref(true)
1919
const contextFileNames = ref<string[]>([])
20+
const shutdownLoading = ref(false)
2021
2122
watch(() => store.settings, (s) => {
2223
httpPort.value = s.httpPort ?? ''
@@ -106,6 +107,18 @@ async function save() {
106107
}
107108
}
108109
110+
async function shutdown() {
111+
if (!await confirm(t('settings.shutdown_confirm'), { danger: true })) return
112+
shutdownLoading.value = true
113+
try {
114+
await apiFetch('/api/shutdown', 'POST')
115+
show(t('settings.shutdown_started'))
116+
} catch (e: any) {
117+
show(e.message, 'error')
118+
shutdownLoading.value = false
119+
}
120+
}
121+
109122
// ── Scan invalid data ───────────────────────────────────────────
110123
111124
interface InvalidRef { source: string; field: string; badValue: string }
@@ -241,6 +254,12 @@ function fmtItem(category: string, item: any): string {
241254
<SInput v-model.number="maxImageSize" type="number" placeholder="1024" min="0" />
242255
</SFormItem>
243256
</div>
257+
<div class="service-actions">
258+
<div class="form-hint">{{ t('settings.shutdown_hint') }}</div>
259+
<SButton type="danger" size="sm" :disabled="shutdownLoading" @click="shutdown">
260+
{{ t('settings.shutdown') }}
261+
</SButton>
262+
</div>
244263
</SCard>
245264
<SCard :title="t('settings.version_updates')">
246265
<SCheckCard v-model="autoCheckUpdate">
@@ -397,9 +416,20 @@ function fmtItem(category: string, item: any): string {
397416
398417
.inline-form { display: flex; gap: var(--sui-sp-7); flex-wrap: wrap; }
399418
.inline-form > * { flex: 1; min-width: 200px; }
419+
.service-actions {
420+
display: flex;
421+
align-items: center;
422+
justify-content: space-between;
423+
gap: var(--sui-sp-4);
424+
margin-top: var(--sui-sp-4);
425+
padding-top: var(--sui-sp-4);
426+
border-top: 1px solid var(--sui-border);
427+
}
428+
.service-actions .form-hint { margin-bottom: 0; }
400429
401430
@media (max-width: 768px) {
402431
.inline-form { flex-direction: column; }
432+
.service-actions { align-items: flex-start; flex-direction: column; }
403433
}
404434
405435
.cleanup-actions {

‎packages/sbot/src/Agent/AgentRunner.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
T_ChannelSessionId,
2424
TimeUtils,
2525
type MessageContent,
26+
runtimeActivity,
2627
} from "scorpio.ai";
2728
import { loadPrompt } from "../Core/PromptLoader";
2829
import { config } from "../Core/Config";
@@ -76,6 +77,13 @@ export interface AgentRunOptions {
7677

7778
export class AgentRunner {
7879
static async run(options: AgentRunOptions): Promise<void> {
80+
if (runtimeActivity.isStopping) {
81+
throw new Error("Service is shutting down; new agent tasks are not accepted");
82+
}
83+
return runtimeActivity.track(this.runInternal(options));
84+
}
85+
86+
private static async runInternal(options: AgentRunOptions): Promise<void> {
7987
const { query, callbacks, agentId, saverId, threadId, dbSessionId, extraInfo, channelPrompt, notes, wikis, agentTools } = options;
8088
if (!agentId.trim()) throw new Error("agent not specified");
8189
if (!saverId.trim()) throw new Error("saver not specified");

‎packages/sbot/src/Server/HttpServer.ts‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import { AgentStoreService } from '../AgentStore';
88
import { LoggerService, log4js } from '../Core/LoggerService';
99
import { database } from '../Core/Database';
1010
import { agendaStorePool, agendaTriggerEnginePool } from '../Agenda';
11+
import { heartbeatService } from '../Heartbeat/HeartbeatService';
12+
import { runtimeActivity } from 'scorpio.ai';
1113
import { channelManager } from '../Channel/ChannelManager';
1214
import { tunnelService } from '../Tunnel';
1315
import { WEB_CHANNEL_ID } from 'sbot.commons';
@@ -39,23 +41,32 @@ class HttpServer {
3941
private readonly skillHubService = new SkillHubService();
4042
private readonly agentStoreService = new AgentStoreService();
4143
private server?: http.Server;
44+
private shutdownPromise?: Promise<void>;
4245

4346
async shutdown(): Promise<void> {
44-
logger.info('Shutting down services...');
47+
if (!this.shutdownPromise) this.shutdownPromise = this.shutdownInternal();
48+
return this.shutdownPromise;
49+
}
50+
51+
private async shutdownInternal(): Promise<void> {
52+
runtimeActivity.beginShutdown();
53+
logger.info(`Shutting down services: stopped accepting new work; waiting for ${runtimeActivity.active} active task(s)...`);
4554
try {
4655
agendaTriggerEnginePool.stopAll();
56+
heartbeatService.stopAll();
57+
// 立即停止接收新连接;已建立的 HTTP / WebSocket 连接会保留到现有任务排空。
58+
const closeServer = this.server
59+
? new Promise<void>((resolve, reject) => this.server!.close(err => err ? reject(err) : resolve()))
60+
: Promise.resolve();
61+
await runtimeActivity.waitForIdle();
4762
agendaStorePool.disposeAll();
4863
await ACPAgentPool.getInstance().disposeAll();
4964
await channelManager.dispose();
5065
ptyService.dispose();
5166
try { await tunnelService.stopAll(); } catch (e: any) {
5267
logger.warn(`tunnel stop error: ${e?.message ?? e}`);
5368
}
54-
if (this.server) {
55-
await new Promise<void>((resolve, reject) =>
56-
this.server!.close(err => err ? reject(err) : resolve()),
57-
);
58-
}
69+
await closeServer;
5970
await database.sequelize.close();
6071
logger.info('All services stopped');
6172
} catch (e: any) {

‎packages/sbot/src/Server/routes/system.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,9 +97,9 @@ export class SystemRoutes {
9797

9898
app.post('/api/shutdown', api(async () => {
9999
logger.info('Shutdown requested via API');
100-
// 先返回响应,再异步关闭服务
101-
setTimeout(() => ctx.shutdown(), 500);
102-
return { message: 'Shutting down...' };
100+
// 进入排空状态后拒绝新任务;现有 Agent / memory / agenda 工作完成后再退出。
101+
void ctx.shutdown();
102+
return { message: 'Shutdown initiated; waiting for active work to finish...' };
103103
}));
104104

105105
// 清理跨表引用孤儿数据。默认 dryRun:只返回报告不删,?apply=1 才真正清。

‎packages/sbot/src/Session/SessionManager.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import "reflect-metadata";
2-
import { ICommand, MessageType, MessageRole, MessageKind, type MessageContent, trimContent, isEmptyContent } from "scorpio.ai";
2+
import { ICommand, MessageType, MessageRole, MessageKind, type MessageContent, trimContent, isEmptyContent, runtimeActivity } from "scorpio.ai";
33
import { SessionManager, SessionService, ChannelMessageArgs, ChannelSessionHandler } from "channel.base";
44
import { type StructuredToolInterface } from "@langchain/core/tools";
55
import { config } from "../Core/Config";
@@ -189,6 +189,7 @@ export class SbotSessionManager extends SessionManager {
189189
// ── Channel entry points ──
190190

191191
async onReceiveChannelMessage(query: MessageContent, args: ChannelRouteArgs): Promise<void> {
192+
if (runtimeActivity.isStopping) return;
192193
query = trimContent(query);
193194
if (isEmptyContent(query)) return;
194195

@@ -231,6 +232,7 @@ export class SbotSessionManager extends SessionManager {
231232
}
232233

233234
private async dispatchToSession(threadId: string, query: MessageContent, args: ChannelRouteArgs): Promise<void> {
235+
if (runtimeActivity.isStopping) return;
234236
const ctx: MessageContext = { query, args, threadId, filtered: false };
235237
await this.messagePipeline.execute(ctx, async (c) => {
236238
if (c.filtered) return;

‎packages/scorpio.ai/src/Agenda/Service/AgendaService.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { inject } from "scorpio.di";
2-
import { T_AgendaToolDescs, formatError } from "../../Core";
2+
import { T_AgendaToolDescs, formatError, runtimeActivity } from "../../Core";
33
import { ILoggerService, type ILogger } from "../../Logger";
44
import type { ChatMessage } from "../../Saver";
55
import {
@@ -374,6 +374,7 @@ export class AgendaService implements IAgendaService {
374374
if (this.isRunning) return;
375375
this.isRunning = true;
376376
this.refCount++;
377+
const releaseActivity = runtimeActivity.retain();
377378
try {
378379
while (true) {
379380
let next: PendingAgendaJobRow | null;
@@ -396,6 +397,7 @@ export class AgendaService implements IAgendaService {
396397
} finally {
397398
this.isRunning = false;
398399
this.release(); // 配对开头 refCount++;归零自动 evict
400+
releaseActivity();
399401
}
400402
}
401403

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* 进程内运行引用计数。
3+
*
4+
* Agent 整轮执行、Memory/Agenda 后台 drain 和每次模型调用都持有同一个引用;
5+
* 宿主关闭时只需停止新工作并等待计数归零。
6+
*/
7+
class RuntimeActivity {
8+
private refCount = 0;
9+
private stopping = false;
10+
private idleWaiters = new Set<() => void>();
11+
12+
get active(): number {
13+
return this.refCount;
14+
}
15+
16+
get isStopping(): boolean {
17+
return this.stopping;
18+
}
19+
20+
beginShutdown(): void {
21+
this.stopping = true;
22+
}
23+
24+
retain(): () => void {
25+
this.refCount++;
26+
let released = false;
27+
return () => {
28+
if (released) return;
29+
released = true;
30+
this.refCount--;
31+
if (this.refCount !== 0) return;
32+
for (const resolve of this.idleWaiters) resolve();
33+
this.idleWaiters.clear();
34+
};
35+
}
36+
37+
track<T>(operation: Promise<T>): Promise<T> {
38+
const release = this.retain();
39+
return operation.finally(release);
40+
}
41+
42+
async trackStream<T>(operation: Promise<AsyncIterable<T>>): Promise<AsyncIterable<T>> {
43+
const release = this.retain();
44+
try {
45+
const stream = await operation;
46+
return (async function* () {
47+
try {
48+
yield* stream;
49+
} finally {
50+
release();
51+
}
52+
})();
53+
} catch (error) {
54+
release();
55+
throw error;
56+
}
57+
}
58+
59+
async waitForIdle(): Promise<void> {
60+
while (this.refCount > 0) {
61+
await new Promise<void>(resolve => this.idleWaiters.add(resolve));
62+
}
63+
}
64+
}
65+
66+
export const runtimeActivity = new RuntimeActivity();

‎packages/scorpio.ai/src/Core/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@ export { T_StaticSystemPrompts, T_DynamicSystemPrompts, T_DBPath, T_DBUrl, T_DBT
1212

1313
// 工具函数
1414
export { parseJson, truncate, listThreadIds, listSubDirs, formatError } from "./utils";
15+
export { runtimeActivity } from "./RuntimeActivity";

0 commit comments

Comments
 (0)