@oyasmi/pipiclaw 0.9.0 → 0.9.1-beta.1
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/dist/agent/channel-runner.d.ts +5 -0
- package/dist/agent/channel-runner.js +36 -0
- package/dist/agent/commands.js +3 -1
- package/dist/agent/types.d.ts +6 -0
- package/dist/memory/lifecycle.d.ts +15 -0
- package/dist/memory/lifecycle.js +60 -0
- package/dist/runtime/active-session-store.d.ts +12 -0
- package/dist/runtime/active-session-store.js +26 -0
- package/dist/runtime/bootstrap.js +74 -0
- package/dist/runtime/delivery.js +1 -1
- package/dist/runtime/dingtalk.d.ts +7 -0
- package/dist/runtime/dingtalk.js +22 -3
- package/package.json +1 -1
|
@@ -60,6 +60,8 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
60
60
|
* whichever turn started in the meantime.
|
|
61
61
|
*/
|
|
62
62
|
private abandonedTurns;
|
|
63
|
+
/** Set once transport-level `/new` replaces this generation. A retired runner is never reused. */
|
|
64
|
+
private retired;
|
|
63
65
|
/** When the primary model last failed and we switched to the backup. null = on primary. */
|
|
64
66
|
private primaryFailedAt;
|
|
65
67
|
private runState;
|
|
@@ -103,6 +105,9 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
103
105
|
getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
|
|
104
106
|
getStatusSnapshot(): RunnerStatusSnapshot;
|
|
105
107
|
abort(): Promise<void>;
|
|
108
|
+
isCompacting(): boolean;
|
|
109
|
+
interruptCompaction(): boolean;
|
|
110
|
+
retireForNewSession(): void;
|
|
106
111
|
/**
|
|
107
112
|
* `/context` — read-only prompt accounting, no LLM cost. Reports the section
|
|
108
113
|
* breakdown of the system prompt, the tool schemas (billed on top of it, and
|
|
@@ -96,6 +96,8 @@ export class ChannelRunner {
|
|
|
96
96
|
* whichever turn started in the meantime.
|
|
97
97
|
*/
|
|
98
98
|
this.abandonedTurns = 0;
|
|
99
|
+
/** Set once transport-level `/new` replaces this generation. A retired runner is never reused. */
|
|
100
|
+
this.retired = false;
|
|
99
101
|
/** When the primary model last failed and we switched to the backup. null = on primary. */
|
|
100
102
|
this.primaryFailedAt = null;
|
|
101
103
|
// --- Per run ---
|
|
@@ -700,6 +702,40 @@ export class ChannelRunner {
|
|
|
700
702
|
async abort() {
|
|
701
703
|
await this.session.abort();
|
|
702
704
|
}
|
|
705
|
+
isCompacting() {
|
|
706
|
+
return this.session?.isCompacting ?? false;
|
|
707
|
+
}
|
|
708
|
+
interruptCompaction() {
|
|
709
|
+
if (!this.session?.isCompacting)
|
|
710
|
+
return false;
|
|
711
|
+
this.session.abortCompaction();
|
|
712
|
+
return true;
|
|
713
|
+
}
|
|
714
|
+
retireForNewSession() {
|
|
715
|
+
if (this.retired)
|
|
716
|
+
return;
|
|
717
|
+
this.retired = true;
|
|
718
|
+
if (this.session) {
|
|
719
|
+
this.memoryLifecycle.noteNewSessionBoundary();
|
|
720
|
+
}
|
|
721
|
+
// close() marks the delivery context closed synchronously before awaiting its drain,
|
|
722
|
+
// so late events from the old provider cannot overwrite the new session's response.
|
|
723
|
+
void this.runState.ctx?.close().catch(() => undefined);
|
|
724
|
+
this.forceEndTurn("superseded by /new");
|
|
725
|
+
const retireLiveSession = () => {
|
|
726
|
+
this.sessionUnsubscribe?.();
|
|
727
|
+
this.sessionUnsubscribe = undefined;
|
|
728
|
+
this.session.dispose();
|
|
729
|
+
};
|
|
730
|
+
if (this.session) {
|
|
731
|
+
retireLiveSession();
|
|
732
|
+
}
|
|
733
|
+
else {
|
|
734
|
+
// A second message can issue `/new` while this generation is still initializing.
|
|
735
|
+
// Let construction settle in the background, then immediately tear it down.
|
|
736
|
+
void this.sessionReady.then(retireLiveSession, () => undefined);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
703
739
|
/**
|
|
704
740
|
* `/context` — read-only prompt accounting, no LLM cost. Reports the section
|
|
705
741
|
* breakdown of the system prompt, the tool schemas (billed on top of it, and
|
package/dist/agent/commands.js
CHANGED
|
@@ -141,6 +141,7 @@ export const SESSION_COMMANDS = [
|
|
|
141
141
|
name: "new",
|
|
142
142
|
description: "开启新会话",
|
|
143
143
|
examples: ["/new"],
|
|
144
|
+
availableWhileBusy: true,
|
|
144
145
|
},
|
|
145
146
|
{
|
|
146
147
|
name: "compact",
|
|
@@ -169,7 +170,8 @@ export function isRunnerBuiltInCommand(command) {
|
|
|
169
170
|
}
|
|
170
171
|
/** Comma-separated list of commands usable while a task is streaming (names only). */
|
|
171
172
|
export function formatBusyCommandList() {
|
|
172
|
-
return BUILT_IN_COMMANDS
|
|
173
|
+
return [...BUILT_IN_COMMANDS, ...SESSION_COMMANDS]
|
|
174
|
+
.filter((command) => command.availableWhileBusy)
|
|
173
175
|
.map((command) => `\`/${command.name}\``)
|
|
174
176
|
.join(", ");
|
|
175
177
|
}
|
package/dist/agent/types.d.ts
CHANGED
|
@@ -56,6 +56,12 @@ export interface AgentRunner {
|
|
|
56
56
|
* already discovered, without forcing a rescan. */
|
|
57
57
|
getSubAgentDiscoverySnapshot(): SubAgentDiscoveryResult;
|
|
58
58
|
abort(): Promise<void>;
|
|
59
|
+
/** True when the SDK is currently summarizing context. */
|
|
60
|
+
isCompacting?(): boolean;
|
|
61
|
+
/** Cancel context summarization synchronously; returns whether one was active. */
|
|
62
|
+
interruptCompaction?(): boolean;
|
|
63
|
+
/** Permanently retire this runner generation after an out-of-band `/new`. */
|
|
64
|
+
retireForNewSession?(): void;
|
|
59
65
|
/**
|
|
60
66
|
* Synchronously reserve the turn for a message. Transports MUST call this in
|
|
61
67
|
* the same tick they dequeue the message, before any await, so a concurrent
|
|
@@ -5,6 +5,19 @@ import type { PipiclawSessionMemorySettings } from "../settings.js";
|
|
|
5
5
|
import { type ChannelMemoryQueue } from "./channel-maintenance-queue.js";
|
|
6
6
|
import { type MemoryActivityEvent } from "./maintenance-state.js";
|
|
7
7
|
export type ConsolidationReason = "compaction" | "new-session" | "idle" | "shutdown";
|
|
8
|
+
/**
|
|
9
|
+
* Bound one standalone summarization request. Provider limits can be lower than a model's
|
|
10
|
+
* advertised context window; sending the whole pre-compaction transcript is therefore not safe.
|
|
11
|
+
* The head preserves the original goal and the larger tail preserves current work. Durable
|
|
12
|
+
* memory is refreshed before this runs, so the omitted middle is still available outside the
|
|
13
|
+
* provider request.
|
|
14
|
+
*/
|
|
15
|
+
export declare function boundCompactionMessages(messages: AgentMessage[], contextWindow: number, reserveTokens: number): {
|
|
16
|
+
messages: AgentMessage[];
|
|
17
|
+
truncated: boolean;
|
|
18
|
+
originalChars: number;
|
|
19
|
+
boundedChars: number;
|
|
20
|
+
};
|
|
8
21
|
export interface MemoryLifecycleOptions {
|
|
9
22
|
channelId: string;
|
|
10
23
|
channelDir: string;
|
|
@@ -46,6 +59,8 @@ export declare class MemoryLifecycle {
|
|
|
46
59
|
private handleSessionBeforeCompact;
|
|
47
60
|
private handleSessionCompact;
|
|
48
61
|
private handleSessionBeforeSwitch;
|
|
62
|
+
/** Snapshot the outgoing state for an out-of-band `/new` before its runner is retired. */
|
|
63
|
+
noteNewSessionBoundary(): void;
|
|
49
64
|
/** Await any in-flight detached new-session consolidation (shutdown/tests). */
|
|
50
65
|
whenNewSessionConsolidationSettled(): Promise<void>;
|
|
51
66
|
private handleSessionStart;
|
package/dist/memory/lifecycle.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { convertToLlm, serializeConversation } from "@earendil-works/pi-coding-agent";
|
|
1
2
|
import * as log from "../log.js";
|
|
2
3
|
import { formatLocalTime } from "../shared/local-time.js";
|
|
4
|
+
import { clipTextByPromptUnits } from "../shared/prompt-units.js";
|
|
3
5
|
import { errorMessage } from "../shared/text-utils.js";
|
|
4
6
|
import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
|
|
5
7
|
import { runInlineConsolidation, } from "./consolidation.js";
|
|
@@ -7,6 +9,51 @@ import { readMemoryMaintenanceState, updateMemoryMaintenanceState, } from "./mai
|
|
|
7
9
|
import { appendMemoryReviewLog } from "./review-log.js";
|
|
8
10
|
import { updateChannelSessionMemory } from "./session.js";
|
|
9
11
|
import { buildCompactionMemorySourceWindow, buildIncrementalMemorySourceWindow, } from "./source-window.js";
|
|
12
|
+
const COMPACTION_INPUT_MAX_UNITS = 48_000;
|
|
13
|
+
const COMPACTION_INPUT_MIN_UNITS = 4_000;
|
|
14
|
+
const COMPACTION_INPUT_CHARS_PER_TOKEN = 3;
|
|
15
|
+
const COMPACTION_INPUT_HEAD_RATIO = 0.35;
|
|
16
|
+
/**
|
|
17
|
+
* Bound one standalone summarization request. Provider limits can be lower than a model's
|
|
18
|
+
* advertised context window; sending the whole pre-compaction transcript is therefore not safe.
|
|
19
|
+
* The head preserves the original goal and the larger tail preserves current work. Durable
|
|
20
|
+
* memory is refreshed before this runs, so the omitted middle is still available outside the
|
|
21
|
+
* provider request.
|
|
22
|
+
*/
|
|
23
|
+
export function boundCompactionMessages(messages, contextWindow, reserveTokens) {
|
|
24
|
+
if (messages.length === 0) {
|
|
25
|
+
return { messages, truncated: false, originalChars: 0, boundedChars: 0 };
|
|
26
|
+
}
|
|
27
|
+
const safeWindow = Number.isFinite(contextWindow) && contextWindow > 0 ? Math.floor(contextWindow) : 128_000;
|
|
28
|
+
const safeReserve = Number.isFinite(reserveTokens) && reserveTokens > 0 ? Math.floor(reserveTokens) : 16_384;
|
|
29
|
+
const maxUnits = Math.min(COMPACTION_INPUT_MAX_UNITS, Math.max(COMPACTION_INPUT_MIN_UNITS, safeWindow - safeReserve - 8_192));
|
|
30
|
+
const serialized = serializeConversation(convertToLlm(messages));
|
|
31
|
+
const clipped = clipTextByPromptUnits(serialized, maxUnits, {
|
|
32
|
+
headRatio: COMPACTION_INPUT_HEAD_RATIO,
|
|
33
|
+
maxChars: maxUnits * COMPACTION_INPUT_CHARS_PER_TOKEN,
|
|
34
|
+
marker: "\n\n[... middle omitted from this compaction request; durable channel memory was refreshed before compaction ...]\n\n",
|
|
35
|
+
});
|
|
36
|
+
if (!clipped.truncated) {
|
|
37
|
+
return {
|
|
38
|
+
messages,
|
|
39
|
+
truncated: false,
|
|
40
|
+
originalChars: serialized.length,
|
|
41
|
+
boundedChars: serialized.length,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
messages: [
|
|
46
|
+
{
|
|
47
|
+
role: "user",
|
|
48
|
+
content: [{ type: "text", text: clipped.text }],
|
|
49
|
+
timestamp: Date.now(),
|
|
50
|
+
},
|
|
51
|
+
],
|
|
52
|
+
truncated: true,
|
|
53
|
+
originalChars: serialized.length,
|
|
54
|
+
boundedChars: clipped.text.length,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
10
57
|
export class MemoryLifecycle {
|
|
11
58
|
constructor(options) {
|
|
12
59
|
this.options = options;
|
|
@@ -243,6 +290,14 @@ export class MemoryLifecycle {
|
|
|
243
290
|
}
|
|
244
291
|
async handleSessionBeforeCompact(event) {
|
|
245
292
|
await this.runPreflightConsolidation("compaction", event.preparation.messagesToSummarize, this.options.getSessionEntries(), event.preparation.firstKeptEntryId);
|
|
293
|
+
const model = this.options.getModel();
|
|
294
|
+
for (const key of ["messagesToSummarize", "turnPrefixMessages"]) {
|
|
295
|
+
const bounded = boundCompactionMessages(event.preparation[key] ?? [], model.contextWindow, event.preparation.settings?.reserveTokens ?? 16_384);
|
|
296
|
+
if (!bounded.truncated)
|
|
297
|
+
continue;
|
|
298
|
+
event.preparation[key] = bounded.messages;
|
|
299
|
+
log.logWarning(`[${this.options.channelId}] Bounded oversized compaction input (${key})`, `${bounded.originalChars} -> ${bounded.boundedChars} chars; model=${model.provider}/${model.id}`);
|
|
300
|
+
}
|
|
246
301
|
}
|
|
247
302
|
handleSessionCompact(_event) {
|
|
248
303
|
this.recordActivity("boundary");
|
|
@@ -251,6 +306,10 @@ export class MemoryLifecycle {
|
|
|
251
306
|
if (event.reason !== "new") {
|
|
252
307
|
return;
|
|
253
308
|
}
|
|
309
|
+
this.noteNewSessionBoundary();
|
|
310
|
+
}
|
|
311
|
+
/** Snapshot the outgoing state for an out-of-band `/new` before its runner is retired. */
|
|
312
|
+
noteNewSessionBoundary() {
|
|
254
313
|
// Snapshot the outgoing session synchronously: the switch has not happened
|
|
255
314
|
// yet, so getMessages()/getSessionEntries() still reference the session that
|
|
256
315
|
// is about to be replaced. Once we yield, this.session is rebound to the new
|
|
@@ -265,6 +324,7 @@ export class MemoryLifecycle {
|
|
|
265
324
|
const message = errorMessage(error);
|
|
266
325
|
log.logWarning(`[${this.options.channelId}] Background new-session consolidation rejected`, message);
|
|
267
326
|
});
|
|
327
|
+
this.recordActivity("boundary");
|
|
268
328
|
}
|
|
269
329
|
/** Await any in-flight detached new-session consolidation (shutdown/tests). */
|
|
270
330
|
async whenNewSessionConsolidationSettled() {
|
|
@@ -40,3 +40,15 @@ export interface SessionFileHandle {
|
|
|
40
40
|
* the old session) remains authoritative.
|
|
41
41
|
*/
|
|
42
42
|
export declare function commitActiveSessionRef(channelDir: string, session: SessionFileHandle): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* Create a durable empty session and atomically make it active for a channel.
|
|
45
|
+
*
|
|
46
|
+
* This deliberately does not touch a live AgentSession. It is the transport-level `/new`
|
|
47
|
+
* primitive: a wedged provider request or compaction in the old runner cannot delay the
|
|
48
|
+
* commit. Materializing and reopening the file makes the SDK write the session header before
|
|
49
|
+
* the active ref points at it, preserving the same file-before-pointer ordering as normal SDK
|
|
50
|
+
* topology changes.
|
|
51
|
+
*/
|
|
52
|
+
export declare function createFreshActiveSession(channelDir: string, cwd: string): Promise<{
|
|
53
|
+
sessionId: string;
|
|
54
|
+
}>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { closeSync, existsSync, openSync, readFileSync } from "node:fs";
|
|
2
2
|
import { basename, dirname, join, resolve } from "node:path";
|
|
3
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
3
4
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
4
5
|
const REF_FILENAME = "active-session.json";
|
|
5
6
|
const DEFAULT_SESSION_FILENAME = "context.jsonl";
|
|
@@ -98,3 +99,28 @@ export async function commitActiveSessionRef(channelDir, session) {
|
|
|
98
99
|
};
|
|
99
100
|
await writeFileAtomically(getActiveSessionRefPath(channelDir), `${JSON.stringify(ref, null, 2)}\n`);
|
|
100
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* Create a durable empty session and atomically make it active for a channel.
|
|
104
|
+
*
|
|
105
|
+
* This deliberately does not touch a live AgentSession. It is the transport-level `/new`
|
|
106
|
+
* primitive: a wedged provider request or compaction in the old runner cannot delay the
|
|
107
|
+
* commit. Materializing and reopening the file makes the SDK write the session header before
|
|
108
|
+
* the active ref points at it, preserving the same file-before-pointer ordering as normal SDK
|
|
109
|
+
* topology changes.
|
|
110
|
+
*/
|
|
111
|
+
export async function createFreshActiveSession(channelDir, cwd) {
|
|
112
|
+
const provisional = SessionManager.create(cwd, channelDir);
|
|
113
|
+
const sessionFile = provisional.getSessionFile();
|
|
114
|
+
if (!sessionFile) {
|
|
115
|
+
throw new Error("Cannot create a new session: the SDK did not allocate a backing file.");
|
|
116
|
+
}
|
|
117
|
+
const resolvedDir = resolve(channelDir);
|
|
118
|
+
const resolvedFile = resolve(sessionFile);
|
|
119
|
+
if (dirname(resolvedFile) !== resolvedDir) {
|
|
120
|
+
throw new Error(`New session file must live directly under the channel directory: ${sessionFile}`);
|
|
121
|
+
}
|
|
122
|
+
materializeSessionFile(channelDir, basename(resolvedFile));
|
|
123
|
+
const durable = SessionManager.open(resolvedFile, channelDir, cwd);
|
|
124
|
+
await commitActiveSessionRef(channelDir, durable);
|
|
125
|
+
return { sessionId: durable.getSessionId() };
|
|
126
|
+
}
|
|
@@ -14,6 +14,7 @@ import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
|
|
|
14
14
|
import { defaultModel } from "../models/utils.js";
|
|
15
15
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
16
16
|
import { flushSecurityLogs } from "../security/logger.js";
|
|
17
|
+
import { resolveProjectAccessPolicy } from "../security/project-scope.js";
|
|
17
18
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
18
19
|
import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
|
|
19
20
|
import { fileStamp } from "../shared/file-stamp.js";
|
|
@@ -25,6 +26,7 @@ import { finishTaskAttempt } from "../tasks/store.js";
|
|
|
25
26
|
import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
26
27
|
import { getUsageLedger } from "../usage/ledger.js";
|
|
27
28
|
import { parseUsageMode, renderUsageReport } from "../usage/render.js";
|
|
29
|
+
import { createFreshActiveSession } from "./active-session-store.js";
|
|
28
30
|
import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, readCliVersion, } from "./app-home.js";
|
|
29
31
|
import { createChannelIndex } from "./channel-index.js";
|
|
30
32
|
import { ensureChannelDir, getChannelDir } from "./channel-paths.js";
|
|
@@ -34,6 +36,7 @@ import { DurableDispatchService } from "./durable-dispatch.js";
|
|
|
34
36
|
import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
|
|
35
37
|
import { createEventsWatcher } from "./events.js";
|
|
36
38
|
import { handleProjectCommand as runProjectCommand } from "./project-commands.js";
|
|
39
|
+
import { resolveProjectScope } from "./project-scope-store.js";
|
|
37
40
|
import { installLlmProxy } from "./proxy.js";
|
|
38
41
|
import { ChannelStore } from "./store.js";
|
|
39
42
|
import { handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
|
|
@@ -139,6 +142,7 @@ export async function createRuntimeContext(options) {
|
|
|
139
142
|
const startedAt = Date.now();
|
|
140
143
|
const cliVersion = readCliVersion();
|
|
141
144
|
const channelRunners = new Map();
|
|
145
|
+
const sessionResetChains = new Map();
|
|
142
146
|
const activeTasks = new Set();
|
|
143
147
|
/** Channels with a `/stop` watchdog in flight, so a burst of `/stop` starts only one. */
|
|
144
148
|
const stopWatchdogs = new Set();
|
|
@@ -251,6 +255,69 @@ export async function createRuntimeContext(options) {
|
|
|
251
255
|
}
|
|
252
256
|
return { pausedTaskId };
|
|
253
257
|
},
|
|
258
|
+
async handleNewSession(event, _bot) {
|
|
259
|
+
if (shuttingDown)
|
|
260
|
+
return;
|
|
261
|
+
const previous = sessionResetChains.get(event.channelId) ?? Promise.resolve();
|
|
262
|
+
const reset = previous
|
|
263
|
+
.catch(() => undefined)
|
|
264
|
+
.then(async () => {
|
|
265
|
+
try {
|
|
266
|
+
const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
|
|
267
|
+
ensureChannelMemoryFilesSync(channelDir);
|
|
268
|
+
const access = resolveProjectAccessPolicy(loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config, process.cwd());
|
|
269
|
+
const scope = resolveProjectScope(channelDir, access);
|
|
270
|
+
if (scope.kind === "blocked") {
|
|
271
|
+
throw new Error(scope.reason);
|
|
272
|
+
}
|
|
273
|
+
// The empty session file and active pointer are committed before the old
|
|
274
|
+
// generation is touched. A filesystem failure therefore leaves the live
|
|
275
|
+
// session authoritative and retryable.
|
|
276
|
+
const result = await createFreshActiveSession(channelDir, scope.scope.projectRoot);
|
|
277
|
+
const oldRunner = channelRunners.get(event.channelId);
|
|
278
|
+
if (oldRunner) {
|
|
279
|
+
channelRunners.delete(event.channelId);
|
|
280
|
+
try {
|
|
281
|
+
oldRunner.retireForNewSession?.();
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
// The active pointer already names the new session. Retirement is
|
|
285
|
+
// best-effort cleanup and must not misreport the committed reset as failed.
|
|
286
|
+
log.logWarning(`[${event.channelId}] Old runner retirement failed after /new`, errorMessage(error));
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
const dropped = _bot.resetChannelQueue(event.channelId);
|
|
290
|
+
if (dropped > 0) {
|
|
291
|
+
log.logInfo(`[${event.channelId}] /new discarded ${dropped} queued old-session message(s)`);
|
|
292
|
+
}
|
|
293
|
+
await _bot.sendPlain(event.channelId, `已开启新会话。\n\nSession ID: \`${result.sessionId}\``);
|
|
294
|
+
void archiveIncomingMessage(event.channelId, {
|
|
295
|
+
date: new Date().toISOString(),
|
|
296
|
+
ts: event.ts,
|
|
297
|
+
user: event.user,
|
|
298
|
+
userName: event.userName,
|
|
299
|
+
text: event.text,
|
|
300
|
+
isBot: false,
|
|
301
|
+
}, "/new command");
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
const message = errorMessage(error);
|
|
305
|
+
log.logWarning(`[${event.channelId}] Failed to create a fresh session`, message);
|
|
306
|
+
await _bot.sendPlain(event.channelId, `新会话创建失败:${message}\n\n旧会话仍保持不变;请重试 \`/new\`。`);
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
sessionResetChains.set(event.channelId, reset);
|
|
310
|
+
activeTasks.add(reset);
|
|
311
|
+
try {
|
|
312
|
+
await reset;
|
|
313
|
+
}
|
|
314
|
+
finally {
|
|
315
|
+
activeTasks.delete(reset);
|
|
316
|
+
if (sessionResetChains.get(event.channelId) === reset) {
|
|
317
|
+
sessionResetChains.delete(event.channelId);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
},
|
|
254
321
|
async runRuntimeCommand(event, name, args) {
|
|
255
322
|
switch (name) {
|
|
256
323
|
case "events":
|
|
@@ -345,6 +412,13 @@ export async function createRuntimeContext(options) {
|
|
|
345
412
|
await bot.sendPlain(event.channelId, `无法排队:/${commandName} 需要带上消息内容。`);
|
|
346
413
|
return { kind: "handled" };
|
|
347
414
|
}
|
|
415
|
+
// Compaction is maintenance, not user work. A new message cancels it and is
|
|
416
|
+
// kept as a normal queued turn instead of trying to steer an agent loop that
|
|
417
|
+
// is currently disconnected for summarization.
|
|
418
|
+
if (runner.interruptCompaction?.()) {
|
|
419
|
+
log.logInfo(`[${event.channelId}] Interrupted compaction for a new user message`);
|
|
420
|
+
return { kind: "requeue", text: trimmedQueueText };
|
|
421
|
+
}
|
|
348
422
|
if (mode === "followUp") {
|
|
349
423
|
log.logEvent("info", "agent.turn.followup_queued", "Follow-up queued", {
|
|
350
424
|
ctx: { channelId: event.channelId, userName: event.userName },
|
package/dist/runtime/delivery.js
CHANGED
|
@@ -63,7 +63,7 @@ class ChannelDeliveryController {
|
|
|
63
63
|
respondPlain: async (text, shouldLog = true) => this.sendFinal(text, shouldLog),
|
|
64
64
|
replaceMessage: async (text) => this.replaceWithFinal(text),
|
|
65
65
|
respondInThread: async (text) => {
|
|
66
|
-
if (!text.trim()) {
|
|
66
|
+
if (this.closed || !text.trim()) {
|
|
67
67
|
return;
|
|
68
68
|
}
|
|
69
69
|
const delivered = await this.bot.sendPlain(this.event.channelId, text);
|
|
@@ -60,6 +60,8 @@ export interface DingTalkHandler {
|
|
|
60
60
|
reserveEvent?(event: DingTalkEvent): void;
|
|
61
61
|
handleEvent(event: DingTalkEvent, bot: DingTalkBot, isEvent?: boolean): Promise<void>;
|
|
62
62
|
handleStop(channelId: string, bot: DingTalkBot): Promise<StopOutcome>;
|
|
63
|
+
/** `/new` bypasses the old per-channel queue and live SDK session. */
|
|
64
|
+
handleNewSession(event: DingTalkEvent, bot: DingTalkBot): Promise<void>;
|
|
63
65
|
/**
|
|
64
66
|
* Render one of the stateless report commands (events/tasks/status/usage/context/subagents) to
|
|
65
67
|
* text. Single dispatch point shared by the busy-turn switch below and bootstrap's idle-turn
|
|
@@ -185,6 +187,11 @@ export declare class DingTalkBot implements MediaSender {
|
|
|
185
187
|
* do not run after the user halts the current task. Returns dropped count.
|
|
186
188
|
*/
|
|
187
189
|
clearPendingMessages(channelId: string): number;
|
|
190
|
+
/**
|
|
191
|
+
* Detach all queued work from the previous session generation. The in-flight callback may
|
|
192
|
+
* still unwind on its old queue object, while subsequent messages get a fresh queue.
|
|
193
|
+
*/
|
|
194
|
+
resetChannelQueue(channelId: string): number;
|
|
188
195
|
private getQueue;
|
|
189
196
|
private getConversationMeta;
|
|
190
197
|
private setConversationMeta;
|
package/dist/runtime/dingtalk.js
CHANGED
|
@@ -11,7 +11,7 @@ import axios from "axios";
|
|
|
11
11
|
import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
|
|
12
12
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
13
13
|
import { dirname, join } from "path";
|
|
14
|
-
import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, } from "../agent/commands.js";
|
|
14
|
+
import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, slashCommandName, } from "../agent/commands.js";
|
|
15
15
|
import * as log from "../log.js";
|
|
16
16
|
import { errorMessage } from "../shared/text-utils.js";
|
|
17
17
|
import { isRecord } from "../shared/type-guards.js";
|
|
@@ -1069,6 +1069,13 @@ export class DingTalkBot {
|
|
|
1069
1069
|
};
|
|
1070
1070
|
const builtInCommand = parseBuiltInCommand(content);
|
|
1071
1071
|
const isSlashCommand = content.trim().startsWith("/");
|
|
1072
|
+
// `/new` is an emergency boundary as well as a session command. Route it before
|
|
1073
|
+
// busy checking and before the old channel queue, so a wedged compaction/provider
|
|
1074
|
+
// request cannot prevent recovery.
|
|
1075
|
+
if (slashCommandName(content) === "new") {
|
|
1076
|
+
await this.handler.handleNewSession(event, this);
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1072
1079
|
// Check if busy
|
|
1073
1080
|
if (this.handler.isRunning(channelId)) {
|
|
1074
1081
|
// All built-in transport commands are usable while a task streams.
|
|
@@ -1106,10 +1113,10 @@ export class DingTalkBot {
|
|
|
1106
1113
|
}
|
|
1107
1114
|
}
|
|
1108
1115
|
}
|
|
1109
|
-
//
|
|
1116
|
+
// Other session commands (/model, /compact, …) and unknown slash commands cannot
|
|
1110
1117
|
// run mid-turn: they would need the idle session layer.
|
|
1111
1118
|
if (isSlashCommand) {
|
|
1112
|
-
await this.sendPlain(channelId, `当前已有回合在运行。运行中可用:${formatBusyCommandList()}。会话命令(\`/model\`、\`/
|
|
1119
|
+
await this.sendPlain(channelId, `当前已有回合在运行。运行中可用:${formatBusyCommandList()}。会话命令(\`/model\`、\`/compact\`、\`/session\`)需要等空闲后再用。`);
|
|
1113
1120
|
return;
|
|
1114
1121
|
}
|
|
1115
1122
|
const result = await this.handler.handleBusyMessage(event, this, this.busyMessageDefault, content);
|
|
@@ -1129,6 +1136,18 @@ export class DingTalkBot {
|
|
|
1129
1136
|
const queue = this.queues.get(channelId);
|
|
1130
1137
|
return queue ? queue.clearPending() : 0;
|
|
1131
1138
|
}
|
|
1139
|
+
/**
|
|
1140
|
+
* Detach all queued work from the previous session generation. The in-flight callback may
|
|
1141
|
+
* still unwind on its old queue object, while subsequent messages get a fresh queue.
|
|
1142
|
+
*/
|
|
1143
|
+
resetChannelQueue(channelId) {
|
|
1144
|
+
const queue = this.queues.get(channelId);
|
|
1145
|
+
const dropped = queue?.clearPending() ?? 0;
|
|
1146
|
+
queue?.stop();
|
|
1147
|
+
this.queues.delete(channelId);
|
|
1148
|
+
this.discardCard(channelId);
|
|
1149
|
+
return dropped;
|
|
1150
|
+
}
|
|
1132
1151
|
getQueue(channelId) {
|
|
1133
1152
|
this.touchChannel(channelId);
|
|
1134
1153
|
let queue = this.queues.get(channelId);
|
package/package.json
CHANGED