@botlearn-course/daemon 0.0.32-beta.6 → 0.0.32-beta.7
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-service-sandbox.d.ts +27 -0
- package/dist/agent-service-sandbox.js +184 -3
- package/dist/agent-service-ws-protocol.d.ts +3 -1
- package/dist/agent-service-ws-protocol.js +6 -0
- package/dist/runtimes/deepseek-tui.d.ts +44 -5
- package/dist/runtimes/deepseek-tui.js +186 -70
- package/dist/runtimes/engine.d.ts +5 -0
- package/dist/runtimes/engine.js +12 -0
- package/package.json +1 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type Logger } from "./log.js";
|
|
2
2
|
import type { WorkspaceScanMeasurement } from "./file-candidates.js";
|
|
3
|
+
import { type NativeCompactionReport } from "./runtimes/deepseek-tui.js";
|
|
3
4
|
import { type RuntimeSkillProviderFactory } from "./runtime-skills.js";
|
|
4
5
|
import { type PersistentSessionExecution, type PreparedPersistentTurn, type RunReportingClient } from "./run-dispatcher.js";
|
|
5
6
|
import type { CourseRuntime, RunEvent, RunEventReceipt, RunFileCandidate, RunFileRecord, RunStartPayload } from "./types.js";
|
|
@@ -21,7 +22,21 @@ export interface AgentServiceSandboxOptions {
|
|
|
21
22
|
prepareSkillProvider?: RuntimeSkillProviderFactory;
|
|
22
23
|
/** Cold-start stage timer; its payload is sent once with the first `sandbox.ready`. */
|
|
23
24
|
startupTimer?: StartupTimer;
|
|
25
|
+
/** Test injection; production compacts on the live Codewhale process of the session. */
|
|
26
|
+
compactNativeThread?: NativeThreadCompactor;
|
|
24
27
|
}
|
|
28
|
+
export type NativeThreadCompactor = (args: {
|
|
29
|
+
compactionId: string;
|
|
30
|
+
runtimeSessionKey: string;
|
|
31
|
+
threadId: string;
|
|
32
|
+
signal: AbortSignal;
|
|
33
|
+
queueWaitMs: number;
|
|
34
|
+
}) => Promise<NativeCompactionReport>;
|
|
35
|
+
/**
|
|
36
|
+
* A learner turn that arrives during a background compaction waits at most this long, then
|
|
37
|
+
* the compaction is interrupted. Compaction is an optimization; the learner turn never fails.
|
|
38
|
+
*/
|
|
39
|
+
export declare const NATIVE_COMPACTION_YIELD_MS = 30000;
|
|
25
40
|
/**
|
|
26
41
|
* Long-running daemon client for one user-scoped managed sandbox (ADR-015).
|
|
27
42
|
*
|
|
@@ -74,6 +89,8 @@ export declare class AgentServiceSandboxClient implements RunReportingClient, Pe
|
|
|
74
89
|
private runtimeLogSuppressedBytes;
|
|
75
90
|
private runtimeLogSendChain;
|
|
76
91
|
private workspaceFileReadInFlight;
|
|
92
|
+
private nativeCompaction;
|
|
93
|
+
private readonly compactNativeThread;
|
|
77
94
|
private readonly removeOperationalLogSink;
|
|
78
95
|
constructor(options: AgentServiceSandboxOptions);
|
|
79
96
|
prepareTurn(payload: RunStartPayload): PreparedPersistentTurn;
|
|
@@ -140,6 +157,16 @@ export declare class AgentServiceSandboxClient implements RunReportingClient, Pe
|
|
|
140
157
|
private replaySpool;
|
|
141
158
|
private sendHeartbeat;
|
|
142
159
|
private sendCommandAck;
|
|
160
|
+
/**
|
|
161
|
+
* `session.compact`: compact the course native thread of an idle, active RuntimeSession on
|
|
162
|
+
* its live Codewhale process. The frame lends a short maintenance grant that only the relay
|
|
163
|
+
* holds, and only while this compaction runs. Every rejection is a result, never an error:
|
|
164
|
+
* compaction is optional and the platform has a "compact before the next turn" fallback.
|
|
165
|
+
*/
|
|
166
|
+
private handleSessionCompact;
|
|
167
|
+
/** Lets a running compaction finish within the learner budget, then interrupts it. */
|
|
168
|
+
private yieldNativeCompaction;
|
|
169
|
+
private abortNativeCompaction;
|
|
143
170
|
private handleWorkspaceFilesList;
|
|
144
171
|
private handleWorkspaceFileRead;
|
|
145
172
|
private sendWorkspaceFileResult;
|
|
@@ -4,12 +4,12 @@ import { randomUUID } from "node:crypto";
|
|
|
4
4
|
import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { ensureDaemonHome } from "./auth-store.js";
|
|
7
|
-
import { AGENT_SERVICE_WS_SCHEMA, AGENT_SERVICE_WS_SUBPROTOCOL, createSandboxFrame, createWorkspaceFileChunk, parseSandboxFrame, serializeSandboxFrame, UnsupportedSandboxProtocolError, WORKSPACE_FILE_READ_BINARY_CAPABILITY, WORKSPACE_FILES_LIST_CAPABILITY, } from "./agent-service-ws-protocol.js";
|
|
7
|
+
import { AGENT_SERVICE_WS_SCHEMA, AGENT_SERVICE_WS_SUBPROTOCOL, createSandboxFrame, createWorkspaceFileChunk, parseSandboxFrame, serializeSandboxFrame, UnsupportedSandboxProtocolError, WORKSPACE_FILE_READ_BINARY_CAPABILITY, WORKSPACE_FILES_LIST_CAPABILITY, NATIVE_COMPACTION_CAPABILITY, } from "./agent-service-ws-protocol.js";
|
|
8
8
|
import { log as defaultLog, setOperationalLogSink, } from "./log.js";
|
|
9
9
|
import { availableRunCapabilities, runtimeSupportsCourseSkills, } from "./runtime-capabilities.js";
|
|
10
10
|
import { activationRuntimeEnv, runtimeChildEnv } from "./runtime-env.js";
|
|
11
11
|
import { ModelCredentialRelay } from "./model-credential-relay.js";
|
|
12
|
-
import { reapPreviousDeepseekRuntime, releaseDeepseekRuntime } from "./runtimes/deepseek-tui.js";
|
|
12
|
+
import { DeepseekTuiAdapter, reapPreviousDeepseekRuntime, releaseDeepseekRuntime, } from "./runtimes/deepseek-tui.js";
|
|
13
13
|
import { redactSecretString } from "./redaction.js";
|
|
14
14
|
import { parseRuntimeSkillProviderGrantSet, prepareRuntimeSkillProvider, RuntimeSkillProviderError, } from "./runtime-skills.js";
|
|
15
15
|
import { RunDispatcher, } from "./run-dispatcher.js";
|
|
@@ -362,6 +362,15 @@ function saveState(sandboxId, state) {
|
|
|
362
362
|
// Windows best effort.
|
|
363
363
|
}
|
|
364
364
|
}
|
|
365
|
+
/**
|
|
366
|
+
* A learner turn that arrives during a background compaction waits at most this long, then
|
|
367
|
+
* the compaction is interrupted. Compaction is an optimization; the learner turn never fails.
|
|
368
|
+
*/
|
|
369
|
+
export const NATIVE_COMPACTION_YIELD_MS = 30_000;
|
|
370
|
+
/** Bounded wait for the runtime turn queue; a learner turn is never queued behind it. */
|
|
371
|
+
const NATIVE_COMPACTION_QUEUE_WAIT_MS = 5_000;
|
|
372
|
+
const NATIVE_COMPACTION_MAX_DEADLINE_MS = 15 * 60_000;
|
|
373
|
+
const NATIVE_COMPACTION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
|
|
365
374
|
/**
|
|
366
375
|
* Long-running daemon client for one user-scoped managed sandbox (ADR-015).
|
|
367
376
|
*
|
|
@@ -414,6 +423,8 @@ export class AgentServiceSandboxClient {
|
|
|
414
423
|
runtimeLogSuppressedBytes = 0;
|
|
415
424
|
runtimeLogSendChain = Promise.resolve();
|
|
416
425
|
workspaceFileReadInFlight = false;
|
|
426
|
+
nativeCompaction = null;
|
|
427
|
+
compactNativeThread;
|
|
417
428
|
removeOperationalLogSink;
|
|
418
429
|
constructor(options) {
|
|
419
430
|
this.options = options;
|
|
@@ -424,6 +435,8 @@ export class AgentServiceSandboxClient {
|
|
|
424
435
|
options.prepareSkillProvider ?? ((raw) => prepareRuntimeSkillProvider(raw));
|
|
425
436
|
this.state = loadState(options.sandboxId, options.sandboxToken);
|
|
426
437
|
this.modelRelay = new ModelCredentialRelay({ log: this.log });
|
|
438
|
+
this.compactNativeThread = options.compactNativeThread
|
|
439
|
+
?? ((args) => new DeepseekTuiAdapter().compactNativeThread(args));
|
|
427
440
|
this.dispatcher = new RunDispatcher(this, options.runtimes, {
|
|
428
441
|
persistentSession: this,
|
|
429
442
|
});
|
|
@@ -649,6 +662,7 @@ export class AgentServiceSandboxClient {
|
|
|
649
662
|
}
|
|
650
663
|
stop() {
|
|
651
664
|
this.stopped = true;
|
|
665
|
+
this.nativeCompaction?.abort.abort();
|
|
652
666
|
this.dispatcher.cancelAll();
|
|
653
667
|
for (const [sessionId, session] of Object.entries(this.state.sessions)) {
|
|
654
668
|
session.activationId = null;
|
|
@@ -671,6 +685,7 @@ export class AgentServiceSandboxClient {
|
|
|
671
685
|
this.stop();
|
|
672
686
|
}
|
|
673
687
|
async drainWorkspace(fence) {
|
|
688
|
+
await this.abortNativeCompaction("sandbox_drain");
|
|
674
689
|
if (!(await this.dispatcher.drain(10_000)) || !this.isCurrentDrainFence(fence)) {
|
|
675
690
|
return;
|
|
676
691
|
}
|
|
@@ -981,6 +996,7 @@ export class AgentServiceSandboxClient {
|
|
|
981
996
|
capabilities: [
|
|
982
997
|
WORKSPACE_FILE_READ_BINARY_CAPABILITY,
|
|
983
998
|
WORKSPACE_FILES_LIST_CAPABILITY,
|
|
999
|
+
...(this.options.runtimes.has("deepseek-tui") ? [NATIVE_COMPACTION_CAPABILITY] : []),
|
|
984
1000
|
RUNTIME_PROMPT_CAPABILITY,
|
|
985
1001
|
NATIVE_SESSION_KEY_CAPABILITY,
|
|
986
1002
|
...workspaceDurabilityCapabilities(),
|
|
@@ -1172,7 +1188,17 @@ export class AgentServiceSandboxClient {
|
|
|
1172
1188
|
});
|
|
1173
1189
|
});
|
|
1174
1190
|
return;
|
|
1191
|
+
case "session.compact":
|
|
1192
|
+
void this.handleSessionCompact(frame).catch((error) => {
|
|
1193
|
+
this.log.warn("native compaction response failed", {
|
|
1194
|
+
sandboxId: this.options.sandboxId,
|
|
1195
|
+
runtimeSessionId: frame.runtime_session_id,
|
|
1196
|
+
error: error instanceof Error ? redactSecretString(error.message) : "unexpected",
|
|
1197
|
+
});
|
|
1198
|
+
});
|
|
1199
|
+
return;
|
|
1175
1200
|
case "sandbox.shutdown":
|
|
1201
|
+
await this.abortNativeCompaction("sandbox_shutdown");
|
|
1176
1202
|
await this.stopGracefully();
|
|
1177
1203
|
return;
|
|
1178
1204
|
case "sandbox.drain":
|
|
@@ -1504,7 +1530,10 @@ export class AgentServiceSandboxClient {
|
|
|
1504
1530
|
}
|
|
1505
1531
|
this.inflightCommands.add(commandId);
|
|
1506
1532
|
await this.sendCommandAck(frame, "ok");
|
|
1507
|
-
|
|
1533
|
+
// A background compaction holds this session's relay grant; let it finish briefly, then
|
|
1534
|
+
// interrupt it, before prepareTurn installs the learner activation.
|
|
1535
|
+
void this.yieldNativeCompaction()
|
|
1536
|
+
.then(() => this.dispatcher.dispatch(payload))
|
|
1508
1537
|
.then(() => {
|
|
1509
1538
|
if (!session.completedCommands.includes(commandId)) {
|
|
1510
1539
|
session.completedCommands.push(commandId);
|
|
@@ -1582,6 +1611,9 @@ export class AgentServiceSandboxClient {
|
|
|
1582
1611
|
async closeSession(sessionId, reason, sourceFrame, fence, reportClosed = true) {
|
|
1583
1612
|
const session = this.state.sessions[sessionId];
|
|
1584
1613
|
if (session) {
|
|
1614
|
+
if (this.nativeCompaction?.sessionId === sessionId) {
|
|
1615
|
+
await this.abortNativeCompaction("session_close");
|
|
1616
|
+
}
|
|
1585
1617
|
const runIds = this.runIdsForSession(sessionId);
|
|
1586
1618
|
this.resolvePendingEventAcksForSession(sessionId);
|
|
1587
1619
|
this.rejectPendingFilesForSession(sessionId, new Error("Agent Service runtime session was closed"));
|
|
@@ -1946,6 +1978,155 @@ export class AgentServiceSandboxClient {
|
|
|
1946
1978
|
...(retryable !== undefined ? { retryable } : {}),
|
|
1947
1979
|
});
|
|
1948
1980
|
}
|
|
1981
|
+
/**
|
|
1982
|
+
* `session.compact`: compact the course native thread of an idle, active RuntimeSession on
|
|
1983
|
+
* its live Codewhale process. The frame lends a short maintenance grant that only the relay
|
|
1984
|
+
* holds, and only while this compaction runs. Every rejection is a result, never an error:
|
|
1985
|
+
* compaction is optional and the platform has a "compact before the next turn" fallback.
|
|
1986
|
+
*/
|
|
1987
|
+
async handleSessionCompact(frame) {
|
|
1988
|
+
const sessionId = frame.runtime_session_id;
|
|
1989
|
+
const payload = frame.payload;
|
|
1990
|
+
const compactionId = typeof payload.compaction_id === "string" ? payload.compaction_id : "";
|
|
1991
|
+
if (!NATIVE_COMPACTION_ID.test(compactionId))
|
|
1992
|
+
return;
|
|
1993
|
+
const respond = async (report) => {
|
|
1994
|
+
this.log[report.outcome === "failed" ? "warn" : "info"]("native compaction finished", {
|
|
1995
|
+
sandboxId: this.options.sandboxId,
|
|
1996
|
+
runtimeSessionId: sessionId,
|
|
1997
|
+
compactionId,
|
|
1998
|
+
outcome: report.outcome,
|
|
1999
|
+
reasonCode: report.reasonCode,
|
|
2000
|
+
durationMs: report.durationMs,
|
|
2001
|
+
messagesBefore: report.messagesBefore,
|
|
2002
|
+
messagesAfter: report.messagesAfter,
|
|
2003
|
+
});
|
|
2004
|
+
if (frame.sandbox_generation !== this.sandboxGeneration ||
|
|
2005
|
+
frame.connection_epoch !== this.connectionEpoch)
|
|
2006
|
+
return;
|
|
2007
|
+
await this.sendFrame(createSandboxFrame({
|
|
2008
|
+
type: "session.compact.result",
|
|
2009
|
+
sandboxId: this.options.sandboxId,
|
|
2010
|
+
sandboxGeneration: this.sandboxGeneration,
|
|
2011
|
+
connectionEpoch: this.connectionEpoch,
|
|
2012
|
+
seq: this.nextOutboundSeq(),
|
|
2013
|
+
runtimeSessionId: sessionId,
|
|
2014
|
+
payload: {
|
|
2015
|
+
compaction_id: compactionId,
|
|
2016
|
+
outcome: report.outcome,
|
|
2017
|
+
...(report.reasonCode ? { reason_code: report.reasonCode } : {}),
|
|
2018
|
+
duration_ms: Math.max(0, Math.round(report.durationMs)),
|
|
2019
|
+
...(report.messagesBefore !== undefined ? { messages_before: report.messagesBefore } : {}),
|
|
2020
|
+
...(report.messagesAfter !== undefined ? { messages_after: report.messagesAfter } : {}),
|
|
2021
|
+
},
|
|
2022
|
+
}));
|
|
2023
|
+
};
|
|
2024
|
+
const skip = (reasonCode) => respond({ outcome: "skipped", reasonCode, durationMs: 0 });
|
|
2025
|
+
const baseUrl = payload.model_proxy_base_url;
|
|
2026
|
+
const grant = payload.model_proxy_grant;
|
|
2027
|
+
const deadlineMs = payload.deadline_ms;
|
|
2028
|
+
if (typeof baseUrl !== "string" || !baseUrl
|
|
2029
|
+
|| typeof grant !== "string" || !grant
|
|
2030
|
+
|| typeof deadlineMs !== "number" || !Number.isInteger(deadlineMs)
|
|
2031
|
+
|| deadlineMs < 1_000 || deadlineMs > NATIVE_COMPACTION_MAX_DEADLINE_MS) {
|
|
2032
|
+
await skip("invalid_request");
|
|
2033
|
+
return;
|
|
2034
|
+
}
|
|
2035
|
+
const session = this.state.sessions[sessionId];
|
|
2036
|
+
if (!session) {
|
|
2037
|
+
await skip("session_not_open");
|
|
2038
|
+
return;
|
|
2039
|
+
}
|
|
2040
|
+
if (session.runtimeId !== "deepseek-tui") {
|
|
2041
|
+
await skip("runtime_unsupported");
|
|
2042
|
+
return;
|
|
2043
|
+
}
|
|
2044
|
+
// The reused server process belongs to the active session only.
|
|
2045
|
+
if (this.activeSessionId !== sessionId) {
|
|
2046
|
+
await skip("session_not_active");
|
|
2047
|
+
return;
|
|
2048
|
+
}
|
|
2049
|
+
const threadId = session.nativeSessions[COURSE_NATIVE_SESSION_KEY];
|
|
2050
|
+
if (!threadId) {
|
|
2051
|
+
await skip("native_thread_missing");
|
|
2052
|
+
return;
|
|
2053
|
+
}
|
|
2054
|
+
// Checked synchronously with the relay activation below: a learner turn accepted from
|
|
2055
|
+
// here on waits in yieldNativeCompaction before it installs its own activation.
|
|
2056
|
+
if (this.inflightCommands.size > 0 || this.currentTurnSessionId !== null) {
|
|
2057
|
+
await skip("learner_turn_active");
|
|
2058
|
+
return;
|
|
2059
|
+
}
|
|
2060
|
+
if (this.nativeCompaction) {
|
|
2061
|
+
await skip("compaction_in_progress");
|
|
2062
|
+
return;
|
|
2063
|
+
}
|
|
2064
|
+
const relayActivationId = `compaction:${compactionId}`;
|
|
2065
|
+
const sessionKey = runtimeSessionKey(sessionId, this.sandboxGeneration);
|
|
2066
|
+
const abort = new AbortController();
|
|
2067
|
+
const deadline = setTimeout(() => abort.abort(), deadlineMs);
|
|
2068
|
+
let report = {
|
|
2069
|
+
outcome: "failed", reasonCode: "compaction_request_failed", durationMs: 0,
|
|
2070
|
+
};
|
|
2071
|
+
const done = (async () => {
|
|
2072
|
+
try {
|
|
2073
|
+
await this.modelRelay.start();
|
|
2074
|
+
this.modelRelay.activate(sessionKey, relayActivationId, baseUrl, grant);
|
|
2075
|
+
report = await this.compactNativeThread({
|
|
2076
|
+
compactionId,
|
|
2077
|
+
runtimeSessionKey: sessionKey,
|
|
2078
|
+
threadId,
|
|
2079
|
+
signal: abort.signal,
|
|
2080
|
+
queueWaitMs: NATIVE_COMPACTION_QUEUE_WAIT_MS,
|
|
2081
|
+
});
|
|
2082
|
+
}
|
|
2083
|
+
catch {
|
|
2084
|
+
// The report above stays "failed"; details never include the grant.
|
|
2085
|
+
}
|
|
2086
|
+
finally {
|
|
2087
|
+
clearTimeout(deadline);
|
|
2088
|
+
this.modelRelay.deactivate(relayActivationId);
|
|
2089
|
+
}
|
|
2090
|
+
})();
|
|
2091
|
+
this.nativeCompaction = { sessionId, compactionId, abort, done };
|
|
2092
|
+
try {
|
|
2093
|
+
await done;
|
|
2094
|
+
}
|
|
2095
|
+
finally {
|
|
2096
|
+
if (this.nativeCompaction?.compactionId === compactionId)
|
|
2097
|
+
this.nativeCompaction = null;
|
|
2098
|
+
}
|
|
2099
|
+
await respond(report);
|
|
2100
|
+
}
|
|
2101
|
+
/** Lets a running compaction finish within the learner budget, then interrupts it. */
|
|
2102
|
+
async yieldNativeCompaction() {
|
|
2103
|
+
const running = this.nativeCompaction;
|
|
2104
|
+
if (!running)
|
|
2105
|
+
return;
|
|
2106
|
+
let timer;
|
|
2107
|
+
const finished = await Promise.race([
|
|
2108
|
+
running.done.then(() => true),
|
|
2109
|
+
new Promise((resolve) => {
|
|
2110
|
+
timer = setTimeout(() => resolve(false), NATIVE_COMPACTION_YIELD_MS);
|
|
2111
|
+
}),
|
|
2112
|
+
]);
|
|
2113
|
+
clearTimeout(timer);
|
|
2114
|
+
if (!finished)
|
|
2115
|
+
await this.abortNativeCompaction("learner_turn");
|
|
2116
|
+
}
|
|
2117
|
+
async abortNativeCompaction(reason) {
|
|
2118
|
+
const running = this.nativeCompaction;
|
|
2119
|
+
if (!running)
|
|
2120
|
+
return;
|
|
2121
|
+
this.log.info("native compaction interrupted", {
|
|
2122
|
+
sandboxId: this.options.sandboxId,
|
|
2123
|
+
runtimeSessionId: running.sessionId,
|
|
2124
|
+
compactionId: running.compactionId,
|
|
2125
|
+
reason,
|
|
2126
|
+
});
|
|
2127
|
+
running.abort.abort();
|
|
2128
|
+
await running.done;
|
|
2129
|
+
}
|
|
1949
2130
|
async handleWorkspaceFilesList(frame) {
|
|
1950
2131
|
const session = this.state.sessions[frame.runtime_session_id];
|
|
1951
2132
|
const requestId = frame.payload.request_id;
|
|
@@ -2,9 +2,11 @@ export declare const AGENT_SERVICE_WS_SCHEMA: "botlearn-agent-sandbox-ws/0.4";
|
|
|
2
2
|
export declare const AGENT_SERVICE_WS_SUBPROTOCOL: "botlearn-agent-sandbox.v4";
|
|
3
3
|
export declare const WORKSPACE_FILE_READ_BINARY_CAPABILITY: "workspace_file_read_binary_v1";
|
|
4
4
|
export declare const WORKSPACE_FILES_LIST_CAPABILITY: "workspace_files_list_v1";
|
|
5
|
+
/** Daemon accepts `session.compact` (background native-thread compaction after a passed task). */
|
|
6
|
+
export declare const NATIVE_COMPACTION_CAPABILITY: "native_compaction_v1";
|
|
5
7
|
export declare const WORKSPACE_FILE_CHUNK_BYTES: number;
|
|
6
8
|
export declare const WORKSPACE_FILE_CHUNK_HEADER_BYTES = 29;
|
|
7
|
-
export type SandboxFrameType = "sandbox.hello" | "sandbox.sync" | "session.open" | "session.activate" | "turn.start" | "turn.cancel" | "session.close" | "sandbox.drain" | "sandbox.shutdown" | "event.ack" | "auth.rotate" | "workspace.file.read" | "workspace.files.list" | "ping" | "sandbox.ready" | "sandbox.heartbeat" | "command.ack" | "session.opened" | "session.open_failed" | "session.closed" | "activation.cleaned" | "turn.event" | "turn.files.report" | "workspace.file.result" | "workspace.files.result" | "sandbox.drained" | "sandbox.log" | "pong" | "protocol.error";
|
|
9
|
+
export type SandboxFrameType = "sandbox.hello" | "sandbox.sync" | "session.open" | "session.activate" | "turn.start" | "turn.cancel" | "session.close" | "sandbox.drain" | "sandbox.shutdown" | "event.ack" | "auth.rotate" | "workspace.file.read" | "workspace.files.list" | "session.compact" | "ping" | "sandbox.ready" | "sandbox.heartbeat" | "command.ack" | "session.opened" | "session.open_failed" | "session.closed" | "activation.cleaned" | "turn.event" | "turn.files.report" | "workspace.file.result" | "workspace.files.result" | "session.compact.result" | "sandbox.drained" | "sandbox.log" | "pong" | "protocol.error";
|
|
8
10
|
export declare class UnsupportedSandboxProtocolError extends Error {
|
|
9
11
|
readonly schemaVersion: unknown;
|
|
10
12
|
constructor(schemaVersion: unknown);
|
|
@@ -3,6 +3,8 @@ export const AGENT_SERVICE_WS_SCHEMA = "botlearn-agent-sandbox-ws/0.4";
|
|
|
3
3
|
export const AGENT_SERVICE_WS_SUBPROTOCOL = "botlearn-agent-sandbox.v4";
|
|
4
4
|
export const WORKSPACE_FILE_READ_BINARY_CAPABILITY = "workspace_file_read_binary_v1";
|
|
5
5
|
export const WORKSPACE_FILES_LIST_CAPABILITY = "workspace_files_list_v1";
|
|
6
|
+
/** Daemon accepts `session.compact` (background native-thread compaction after a passed task). */
|
|
7
|
+
export const NATIVE_COMPACTION_CAPABILITY = "native_compaction_v1";
|
|
6
8
|
export const WORKSPACE_FILE_CHUNK_BYTES = 64 * 1024;
|
|
7
9
|
export const WORKSPACE_FILE_CHUNK_HEADER_BYTES = 29;
|
|
8
10
|
const WORKSPACE_FILE_CHUNK_MAGIC = Buffer.from("BLWF", "ascii");
|
|
@@ -20,6 +22,7 @@ const FRAME_TYPES = new Set([
|
|
|
20
22
|
"auth.rotate",
|
|
21
23
|
"workspace.file.read",
|
|
22
24
|
"workspace.files.list",
|
|
25
|
+
"session.compact",
|
|
23
26
|
"ping",
|
|
24
27
|
"sandbox.ready",
|
|
25
28
|
"sandbox.heartbeat",
|
|
@@ -32,6 +35,7 @@ const FRAME_TYPES = new Set([
|
|
|
32
35
|
"turn.files.report",
|
|
33
36
|
"workspace.file.result",
|
|
34
37
|
"workspace.files.result",
|
|
38
|
+
"session.compact.result",
|
|
35
39
|
"sandbox.drained",
|
|
36
40
|
"sandbox.log",
|
|
37
41
|
"pong",
|
|
@@ -49,6 +53,8 @@ const SESSION_TYPES = new Set([
|
|
|
49
53
|
"workspace.files.list",
|
|
50
54
|
"workspace.file.result",
|
|
51
55
|
"workspace.files.result",
|
|
56
|
+
"session.compact",
|
|
57
|
+
"session.compact.result",
|
|
52
58
|
]);
|
|
53
59
|
/** TURN 帧:必须带 runtime_session_id + agent_run_id + worker_attempt + activation_id 四元组。 */
|
|
54
60
|
const TURN_TYPES = new Set([
|
|
@@ -1,7 +1,21 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { type ProbeDeps } from "./probe.js";
|
|
3
3
|
import { type EngineAdapter, type EngineRunOptions, type EngineRunResult } from "./engine.js";
|
|
4
|
-
import type { RuntimeModule, RuntimeProbe, RuntimeUsage } from "../types.js";
|
|
4
|
+
import type { RuntimeCompletionSummary, RuntimeModule, RuntimeProbe, RuntimeProgressDispositions, RuntimeUsage } from "../types.js";
|
|
5
|
+
interface DeepseekTurnResult {
|
|
6
|
+
text: string;
|
|
7
|
+
model?: string;
|
|
8
|
+
completion?: RuntimeCompletionSummary;
|
|
9
|
+
error?: string;
|
|
10
|
+
progressDispositions?: RuntimeProgressDispositions;
|
|
11
|
+
usage?: RuntimeUsage;
|
|
12
|
+
userInputHandoff?: boolean;
|
|
13
|
+
/** Last `context_compaction` item of this turn: Codewhale's own one-line receipt. */
|
|
14
|
+
compaction?: {
|
|
15
|
+
status: string;
|
|
16
|
+
detail: string;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
5
19
|
export interface DeepseekAdapterDeps {
|
|
6
20
|
binary?: string;
|
|
7
21
|
/** 测试注入:使用现成的兼容 server,不 spawn `deepseek`。 */
|
|
@@ -49,6 +63,21 @@ export declare class DeepseekTuiAdapter implements EngineAdapter {
|
|
|
49
63
|
private readonly runtimeVersions;
|
|
50
64
|
constructor(deps?: DeepseekAdapterDeps);
|
|
51
65
|
run(opts: EngineRunOptions): Promise<EngineRunResult>;
|
|
66
|
+
/**
|
|
67
|
+
* Background maintenance after a passed task: compact the RuntimeSession's native thread
|
|
68
|
+
* on its live server process, between learner turns. Never spawns a process: without the
|
|
69
|
+
* reused process of this RuntimeSession there is nothing warm to compact, and the platform
|
|
70
|
+
* keeps its "compact before the next turn" fallback. The caller owns the relay activation
|
|
71
|
+
* that lends this request a short maintenance grant.
|
|
72
|
+
*/
|
|
73
|
+
compactNativeThread(args: {
|
|
74
|
+
compactionId: string;
|
|
75
|
+
runtimeSessionKey: string;
|
|
76
|
+
threadId: string;
|
|
77
|
+
signal: AbortSignal;
|
|
78
|
+
/** Longest wait for a learner turn that is already running on this daemon. */
|
|
79
|
+
queueWaitMs: number;
|
|
80
|
+
}): Promise<NativeCompactionReport>;
|
|
52
81
|
private resolveBinary;
|
|
53
82
|
private acquireHandle;
|
|
54
83
|
private spawnHandle;
|
|
@@ -62,10 +91,6 @@ export declare class DeepseekTuiAdapter implements EngineAdapter {
|
|
|
62
91
|
private spawnEnv;
|
|
63
92
|
private managedRuntimeDirPath;
|
|
64
93
|
private prepareManagedRuntimeDir;
|
|
65
|
-
private compactionMarkerPath;
|
|
66
|
-
private compactionRequired;
|
|
67
|
-
private markCompactionRequired;
|
|
68
|
-
private clearCompactionRequired;
|
|
69
94
|
private managedActivationId;
|
|
70
95
|
private createThread;
|
|
71
96
|
/**
|
|
@@ -106,4 +131,18 @@ export declare function __setProcessStartTimeForTests(fn: ((pid: number) => stri
|
|
|
106
131
|
export declare function __resetDeepseekTuiPoolForTests(): void;
|
|
107
132
|
/** Accept both OpenAI-compatible and canonical usage fields from terminal SSE frames. */
|
|
108
133
|
export declare function extractDeepseekUsage(payload: any): RuntimeUsage | undefined;
|
|
134
|
+
export type NativeCompactionOutcome = "summarized" | "pruned" | "unchanged" | "failed";
|
|
135
|
+
export interface NativeCompactionReport {
|
|
136
|
+
outcome: NativeCompactionOutcome | "skipped";
|
|
137
|
+
reasonCode?: string;
|
|
138
|
+
durationMs: number;
|
|
139
|
+
messagesBefore?: number;
|
|
140
|
+
messagesAfter?: number;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Classifies Codewhale's own receipt ("Made room: 13 → 9 messages …(summary; …)" in 0.10.4,
|
|
144
|
+
* "Compaction complete: …" in 0.9.12). Pruning old tool output first needs no model call.
|
|
145
|
+
*/
|
|
146
|
+
export declare function classifyNativeCompaction(result: Pick<DeepseekTurnResult, "compaction" | "error">): Omit<NativeCompactionReport, "durationMs">;
|
|
109
147
|
export declare const deepseekTuiModule: RuntimeModule;
|
|
148
|
+
export {};
|
|
@@ -84,11 +84,13 @@ const RUNTIME_PROCESS_RECORD = "deepseek-runtime-process.json";
|
|
|
84
84
|
const SSE_TEXT_CAP = 1 * 1024 * 1024;
|
|
85
85
|
const VISION_MODEL_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,159}$/;
|
|
86
86
|
const MANAGED_RUNTIME_DIR_NAME = ".botlearn-deepseek-runtime";
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
87
|
+
/**
|
|
88
|
+
* Platform-requested compactions already attempted by this daemon (deferred turn flag or
|
|
89
|
+
* background maintenance). One attempt per id: candidate retries of the same AgentRun and
|
|
90
|
+
* replayed maintenance commands never summarize the thread twice. Bounded, process-local.
|
|
91
|
+
*/
|
|
92
|
+
const ATTEMPTED_NATIVE_COMPACTIONS = new Set();
|
|
93
|
+
const ATTEMPTED_NATIVE_COMPACTIONS_LIMIT = 256;
|
|
92
94
|
const REQUEST_USER_INPUT_TOOL_NAME = "request_user_input";
|
|
93
95
|
const USER_INPUT_HANDOFF_MAX_CHARS = 8_000;
|
|
94
96
|
const DEEPSEEK_COURSE_SKILL_TOOL_ALIASES = new Set([
|
|
@@ -312,7 +314,7 @@ export class DeepseekTuiAdapter {
|
|
|
312
314
|
clearTimeout(handle.idleTimer);
|
|
313
315
|
// Failure diagnostics describe this run only, also on a reused process.
|
|
314
316
|
handle.stderrTail = "";
|
|
315
|
-
|
|
317
|
+
let headers = authHeaders(handle.token);
|
|
316
318
|
if (threadId && !isValidThreadId(threadId)) {
|
|
317
319
|
return {
|
|
318
320
|
text: "",
|
|
@@ -351,23 +353,50 @@ export class DeepseekTuiAdapter {
|
|
|
351
353
|
// submit windows. Codewhale 0.9.12 keeps the prompt of an already loaded
|
|
352
354
|
// engine, so loading before PATCH would serve the previous system prompt.
|
|
353
355
|
await this.prewarmThread(handle, headers, threadId, turnAbort.signal);
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
356
|
+
const compactionId = opts.nativeCompactionId?.trim();
|
|
357
|
+
if (managedActivationId && compactionId && markNativeCompactionAttempt(compactionId)) {
|
|
358
|
+
// Deferred platform request (the sandbox was paused when the previous task
|
|
359
|
+
// passed). Mid-turn context growth is Codewhale's own auto-compaction; this
|
|
360
|
+
// only trims the finished task. A failure never fails the learner turn.
|
|
361
|
+
const startedAt = Date.now();
|
|
362
|
+
try {
|
|
363
|
+
const compacted = await this.compactThread({
|
|
364
|
+
baseUrl: handle.baseUrl,
|
|
365
|
+
headers,
|
|
366
|
+
threadId,
|
|
367
|
+
opts,
|
|
368
|
+
signal: turnAbort.signal,
|
|
369
|
+
handle,
|
|
370
|
+
});
|
|
371
|
+
maintenanceUsage = compacted.usage;
|
|
372
|
+
log.info("deepseek-tui.native-compaction", {
|
|
373
|
+
compactionId,
|
|
374
|
+
trigger: "before_turn",
|
|
375
|
+
...nativeCompactionLogFields(compacted, Date.now() - startedAt),
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
catch (error) {
|
|
379
|
+
if (turnAbort.signal.aborted)
|
|
380
|
+
throw error;
|
|
381
|
+
log.warn("deepseek-tui.native-compaction", {
|
|
382
|
+
compactionId,
|
|
383
|
+
trigger: "before_turn",
|
|
384
|
+
outcome: "failed",
|
|
385
|
+
reasonCode: "compaction_request_failed",
|
|
386
|
+
durationMs: Date.now() - startedAt,
|
|
387
|
+
});
|
|
388
|
+
// A timed-out submission may still be running in the old process, which the
|
|
389
|
+
// adapter has stopped. Continue this turn on a fresh process instead.
|
|
390
|
+
if (handle.closed) {
|
|
391
|
+
handle.inFlight = Math.max(0, handle.inFlight - 1);
|
|
392
|
+
handle = await this.acquireHandle(opts, turnAbort.signal);
|
|
393
|
+
handle.inFlight += 1;
|
|
394
|
+
handle.runsServed += 1;
|
|
395
|
+
handle.stderrTail = "";
|
|
396
|
+
headers = authHeaders(handle.token);
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
366
399
|
}
|
|
367
|
-
// The marker arms exactly one compaction. Disarm it here so later turns
|
|
368
|
-
// start work directly; the post-turn threshold check re-arms when the
|
|
369
|
-
// compacted thread grows past the limit again.
|
|
370
|
-
this.clearCompactionRequired(opts);
|
|
371
400
|
}
|
|
372
401
|
}
|
|
373
402
|
runResult = await this.startTurnAndReadEvents({
|
|
@@ -391,8 +420,6 @@ export class DeepseekTuiAdapter {
|
|
|
391
420
|
fallbackUsed = true;
|
|
392
421
|
threadId = "";
|
|
393
422
|
maintenanceUsage = undefined;
|
|
394
|
-
if (managedActivationId)
|
|
395
|
-
this.clearCompactionRequired(opts);
|
|
396
423
|
turnOpts = {
|
|
397
424
|
...opts,
|
|
398
425
|
text: opts.recoveryText ?? opts.text,
|
|
@@ -402,10 +429,12 @@ export class DeepseekTuiAdapter {
|
|
|
402
429
|
throw error;
|
|
403
430
|
}
|
|
404
431
|
}
|
|
405
|
-
if (
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
432
|
+
if (runResult.compaction) {
|
|
433
|
+
// Codewhale compacted on its own before a model request (latest request size).
|
|
434
|
+
log.info("deepseek-tui.native-compaction", {
|
|
435
|
+
trigger: "auto",
|
|
436
|
+
...classifyNativeCompaction(runResult),
|
|
437
|
+
});
|
|
409
438
|
}
|
|
410
439
|
const text = runResult.text;
|
|
411
440
|
const usage = mergeRuntimeUsage(maintenanceUsage, runResult.usage);
|
|
@@ -479,6 +508,74 @@ export class DeepseekTuiAdapter {
|
|
|
479
508
|
}
|
|
480
509
|
}
|
|
481
510
|
}
|
|
511
|
+
/**
|
|
512
|
+
* Background maintenance after a passed task: compact the RuntimeSession's native thread
|
|
513
|
+
* on its live server process, between learner turns. Never spawns a process: without the
|
|
514
|
+
* reused process of this RuntimeSession there is nothing warm to compact, and the platform
|
|
515
|
+
* keeps its "compact before the next turn" fallback. The caller owns the relay activation
|
|
516
|
+
* that lends this request a short maintenance grant.
|
|
517
|
+
*/
|
|
518
|
+
async compactNativeThread(args) {
|
|
519
|
+
const startedAt = Date.now();
|
|
520
|
+
const skipped = (reasonCode) => ({
|
|
521
|
+
outcome: "skipped", reasonCode, durationMs: Date.now() - startedAt,
|
|
522
|
+
});
|
|
523
|
+
if (this.explicitServerUrl)
|
|
524
|
+
return skipped("runtime_external_server");
|
|
525
|
+
if (!isValidThreadId(args.threadId))
|
|
526
|
+
return skipped("native_thread_missing");
|
|
527
|
+
if (!markNativeCompactionAttempt(args.compactionId))
|
|
528
|
+
return skipped("already_attempted");
|
|
529
|
+
const queueAbort = AbortSignal.any([args.signal, AbortSignal.timeout(args.queueWaitMs)]);
|
|
530
|
+
let release;
|
|
531
|
+
try {
|
|
532
|
+
try {
|
|
533
|
+
release = await acquireDeepseekTurn(POOL_KEY, queueAbort);
|
|
534
|
+
}
|
|
535
|
+
catch {
|
|
536
|
+
return skipped(args.signal.aborted ? "preempted" : "turn_queue_busy");
|
|
537
|
+
}
|
|
538
|
+
const handle = PROCESS_POOL.get(POOL_KEY);
|
|
539
|
+
if (!handle || handle.closed || !handle.managed || handle.sessionKey !== args.runtimeSessionKey) {
|
|
540
|
+
return skipped("runtime_process_unavailable");
|
|
541
|
+
}
|
|
542
|
+
const headers = authHeaders(handle.token);
|
|
543
|
+
handle.inFlight += 1;
|
|
544
|
+
try {
|
|
545
|
+
await this.prewarmThread(handle, headers, args.threadId, args.signal);
|
|
546
|
+
const result = await this.compactThread({
|
|
547
|
+
baseUrl: handle.baseUrl,
|
|
548
|
+
headers,
|
|
549
|
+
threadId: args.threadId,
|
|
550
|
+
opts: {
|
|
551
|
+
text: "",
|
|
552
|
+
sessionId: args.threadId,
|
|
553
|
+
cwd: "",
|
|
554
|
+
runtimeSessionKey: args.runtimeSessionKey,
|
|
555
|
+
signal: args.signal,
|
|
556
|
+
},
|
|
557
|
+
signal: args.signal,
|
|
558
|
+
handle,
|
|
559
|
+
});
|
|
560
|
+
return { ...classifyNativeCompaction(result), durationMs: Date.now() - startedAt };
|
|
561
|
+
}
|
|
562
|
+
catch (error) {
|
|
563
|
+
return {
|
|
564
|
+
outcome: "failed",
|
|
565
|
+
reasonCode: args.signal.aborted
|
|
566
|
+
? "preempted"
|
|
567
|
+
: isMissingThreadHttpError(error) ? "native_thread_missing" : "compaction_request_failed",
|
|
568
|
+
durationMs: Date.now() - startedAt,
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
finally {
|
|
572
|
+
handle.inFlight = Math.max(0, handle.inFlight - 1);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
finally {
|
|
576
|
+
release?.();
|
|
577
|
+
}
|
|
578
|
+
}
|
|
482
579
|
resolveBinary() {
|
|
483
580
|
if (this.explicitBinary)
|
|
484
581
|
return this.explicitBinary;
|
|
@@ -785,24 +882,6 @@ export class DeepseekTuiAdapter {
|
|
|
785
882
|
chmodSync(runtimeDir, 0o770);
|
|
786
883
|
return runtimeDir;
|
|
787
884
|
}
|
|
788
|
-
compactionMarkerPath(opts) {
|
|
789
|
-
if (!opts.runtimeStateDir) {
|
|
790
|
-
throw new Error("deepseek-tui: managed RuntimeSession state directory is unavailable");
|
|
791
|
-
}
|
|
792
|
-
return path.join(opts.runtimeStateDir, COMPACTION_REQUIRED_MARKER);
|
|
793
|
-
}
|
|
794
|
-
compactionRequired(opts) {
|
|
795
|
-
return existsSync(this.compactionMarkerPath(opts));
|
|
796
|
-
}
|
|
797
|
-
markCompactionRequired(opts) {
|
|
798
|
-
writeFileSync(this.compactionMarkerPath(opts), "required\n", {
|
|
799
|
-
encoding: "utf8",
|
|
800
|
-
mode: 0o600,
|
|
801
|
-
});
|
|
802
|
-
}
|
|
803
|
-
clearCompactionRequired(opts) {
|
|
804
|
-
rmSync(this.compactionMarkerPath(opts), { force: true });
|
|
805
|
-
}
|
|
806
885
|
managedActivationId(opts) {
|
|
807
886
|
if (this.explicitServerUrl)
|
|
808
887
|
return null;
|
|
@@ -950,7 +1029,7 @@ export class DeepseekTuiAdapter {
|
|
|
950
1029
|
method: "POST",
|
|
951
1030
|
headers,
|
|
952
1031
|
body: JSON.stringify({
|
|
953
|
-
reason: "BotLearn
|
|
1032
|
+
reason: "BotLearn compaction after a completed task",
|
|
954
1033
|
}),
|
|
955
1034
|
});
|
|
956
1035
|
turnId = stringField(started?.turn, "id") ?? stringField(started, "turn_id") ?? "";
|
|
@@ -1132,6 +1211,7 @@ export class DeepseekTuiAdapter {
|
|
|
1132
1211
|
let turnStatus;
|
|
1133
1212
|
let finishReason;
|
|
1134
1213
|
let userInputHandoff = false;
|
|
1214
|
+
let compaction;
|
|
1135
1215
|
let capped = false;
|
|
1136
1216
|
const progressState = createDeepseekProgressState();
|
|
1137
1217
|
const courseSkillCallIds = new Set();
|
|
@@ -1250,6 +1330,9 @@ export class DeepseekTuiAdapter {
|
|
|
1250
1330
|
opts.onStatus?.({ kind: "thinking", phase: "stopped" });
|
|
1251
1331
|
return true;
|
|
1252
1332
|
}
|
|
1333
|
+
const compactionItem = deepseekCompactionItem(eventName, payload);
|
|
1334
|
+
if (compactionItem)
|
|
1335
|
+
compaction = compactionItem;
|
|
1253
1336
|
if (eventName === "message.delta") {
|
|
1254
1337
|
const chunk = stringField(payload, "content") ?? "";
|
|
1255
1338
|
if (chunk.trim()) {
|
|
@@ -1321,6 +1404,7 @@ export class DeepseekTuiAdapter {
|
|
|
1321
1404
|
...(finishReason ? { finish_reason: finishReason } : {}),
|
|
1322
1405
|
},
|
|
1323
1406
|
...(userInputHandoff ? { userInputHandoff: true } : {}),
|
|
1407
|
+
...(compaction ? { compaction } : {}),
|
|
1324
1408
|
};
|
|
1325
1409
|
}
|
|
1326
1410
|
}
|
|
@@ -1346,6 +1430,7 @@ export class DeepseekTuiAdapter {
|
|
|
1346
1430
|
...(finishReason ? { finish_reason: finishReason } : {}),
|
|
1347
1431
|
},
|
|
1348
1432
|
...(userInputHandoff ? { userInputHandoff: true } : {}),
|
|
1433
|
+
...(compaction ? { compaction } : {}),
|
|
1349
1434
|
};
|
|
1350
1435
|
};
|
|
1351
1436
|
}
|
|
@@ -1496,6 +1581,7 @@ export function __resetDeepseekTuiPoolForTests() {
|
|
|
1496
1581
|
}
|
|
1497
1582
|
RELEASING.clear();
|
|
1498
1583
|
DEEPSEEK_TURN_QUEUES.clear();
|
|
1584
|
+
ATTEMPTED_NATIVE_COMPACTIONS.clear();
|
|
1499
1585
|
}
|
|
1500
1586
|
function normalizeDeepseekEvent(eventName, payload, seq) {
|
|
1501
1587
|
if (eventName === "message.delta") {
|
|
@@ -1617,30 +1703,60 @@ export function extractDeepseekUsage(payload) {
|
|
|
1617
1703
|
...(requestId ? { provider_request_ids: [requestId] } : {}),
|
|
1618
1704
|
};
|
|
1619
1705
|
}
|
|
1620
|
-
/**
|
|
1621
|
-
function
|
|
1622
|
-
if (
|
|
1623
|
-
return
|
|
1624
|
-
const
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1706
|
+
/** The `context_compaction` item of a terminal item event; Codewhale 0.9.12 and 0.10.4 shape. */
|
|
1707
|
+
function deepseekCompactionItem(eventName, payload) {
|
|
1708
|
+
if (eventName !== "item.completed" && eventName !== "item.failed")
|
|
1709
|
+
return undefined;
|
|
1710
|
+
const item = payload?.payload?.item ?? payload?.item;
|
|
1711
|
+
if (!item || typeof item !== "object" || item.kind !== "context_compaction")
|
|
1712
|
+
return undefined;
|
|
1713
|
+
const detail = stringField(item, "detail") ?? stringField(item, "summary") ?? "";
|
|
1714
|
+
return {
|
|
1715
|
+
status: eventName === "item.failed" ? "failed" : (stringField(item, "status") ?? "completed"),
|
|
1716
|
+
detail: detail.slice(0, 500),
|
|
1717
|
+
};
|
|
1718
|
+
}
|
|
1719
|
+
/**
|
|
1720
|
+
* Classifies Codewhale's own receipt ("Made room: 13 → 9 messages …(summary; …)" in 0.10.4,
|
|
1721
|
+
* "Compaction complete: …" in 0.9.12). Pruning old tool output first needs no model call.
|
|
1722
|
+
*/
|
|
1723
|
+
export function classifyNativeCompaction(result) {
|
|
1724
|
+
const item = result.compaction;
|
|
1725
|
+
if (!item) {
|
|
1726
|
+
return { outcome: "failed", reasonCode: "compaction_receipt_missing" };
|
|
1727
|
+
}
|
|
1728
|
+
const counts = /(\d+)\s*(?:→|->)\s*(\d+)\s+messages/u.exec(item.detail);
|
|
1729
|
+
const messages = counts
|
|
1730
|
+
? { messagesBefore: Number(counts[1]), messagesAfter: Number(counts[2]) }
|
|
1731
|
+
: {};
|
|
1732
|
+
if (item.status === "failed" || result.error) {
|
|
1733
|
+
return { outcome: "failed", reasonCode: "compaction_refused", ...messages };
|
|
1734
|
+
}
|
|
1735
|
+
const outcome = /\bsummary\b/iu.test(item.detail)
|
|
1736
|
+
? "summarized"
|
|
1737
|
+
: /prun/iu.test(item.detail)
|
|
1738
|
+
? "pruned"
|
|
1739
|
+
: "unchanged";
|
|
1740
|
+
return { outcome, ...messages };
|
|
1741
|
+
}
|
|
1742
|
+
function nativeCompactionLogFields(result, durationMs) {
|
|
1743
|
+
const report = classifyNativeCompaction(result);
|
|
1744
|
+
return {
|
|
1745
|
+
...report,
|
|
1746
|
+
durationMs,
|
|
1747
|
+
...(result.usage?.input_tokens !== undefined ? { inputTokens: result.usage.input_tokens } : {}),
|
|
1748
|
+
};
|
|
1749
|
+
}
|
|
1750
|
+
function markNativeCompactionAttempt(id) {
|
|
1751
|
+
if (ATTEMPTED_NATIVE_COMPACTIONS.has(id))
|
|
1752
|
+
return false;
|
|
1753
|
+
ATTEMPTED_NATIVE_COMPACTIONS.add(id);
|
|
1754
|
+
if (ATTEMPTED_NATIVE_COMPACTIONS.size > ATTEMPTED_NATIVE_COMPACTIONS_LIMIT) {
|
|
1755
|
+
const oldest = ATTEMPTED_NATIVE_COMPACTIONS.values().next().value;
|
|
1756
|
+
if (oldest !== undefined)
|
|
1757
|
+
ATTEMPTED_NATIVE_COMPACTIONS.delete(oldest);
|
|
1640
1758
|
}
|
|
1641
|
-
|
|
1642
|
-
return UNKNOWN_MODEL_COMPACTION_THRESHOLD_TOKENS;
|
|
1643
|
-
return Math.floor((contextWindow * COMPACTION_THRESHOLD_PERCENT) / 100);
|
|
1759
|
+
return true;
|
|
1644
1760
|
}
|
|
1645
1761
|
function mergeRuntimeUsage(first, second) {
|
|
1646
1762
|
if (!first)
|
|
@@ -43,6 +43,11 @@ export interface EngineRunOptions {
|
|
|
43
43
|
locale?: string;
|
|
44
44
|
/** Full durable conversation bootstrap, used only if a resumed native thread is missing. */
|
|
45
45
|
recoveryText?: string;
|
|
46
|
+
/**
|
|
47
|
+
* Platform request to compact the resumed native thread before this turn (the previous
|
|
48
|
+
* task passed while the sandbox was paused). Attempted once per id; failure is ignored.
|
|
49
|
+
*/
|
|
50
|
+
nativeCompactionId?: string;
|
|
46
51
|
/** runtime 原生会话 id(resume 用);null 表示新会话。 */
|
|
47
52
|
sessionId: string | null;
|
|
48
53
|
cwd: string;
|
package/dist/runtimes/engine.js
CHANGED
|
@@ -117,6 +117,15 @@ export const consoleLogger = {
|
|
|
117
117
|
writeConsoleLine("debug", msg, fields);
|
|
118
118
|
},
|
|
119
119
|
};
|
|
120
|
+
const NATIVE_COMPACTION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
|
|
121
|
+
/** `runtime.native_compaction.id` set by Course on the first run after a deferred request. */
|
|
122
|
+
function nativeCompactionId(payload) {
|
|
123
|
+
const request = payload.runtime.native_compaction;
|
|
124
|
+
const id = request && typeof request === "object"
|
|
125
|
+
? request.id
|
|
126
|
+
: undefined;
|
|
127
|
+
return typeof id === "string" && NATIVE_COMPACTION_ID.test(id) ? id : undefined;
|
|
128
|
+
}
|
|
120
129
|
const BLOCK_KIND_MAP = {
|
|
121
130
|
assistant_text: "text_delta",
|
|
122
131
|
tool_use: "tool_call",
|
|
@@ -197,6 +206,9 @@ export function wrapEngineAdapter(id, engine, opts) {
|
|
|
197
206
|
...(payload.runtime.model_contract ? { modelContract: payload.runtime.model_contract } : {}),
|
|
198
207
|
...(payload.input.locale ? { locale: payload.input.locale } : {}),
|
|
199
208
|
...(recoveryText !== undefined ? { recoveryText } : {}),
|
|
209
|
+
...(resumesNativeSession && nativeCompactionId(payload)
|
|
210
|
+
? { nativeCompactionId: nativeCompactionId(payload) }
|
|
211
|
+
: {}),
|
|
200
212
|
sessionId: run.nativeSessionId ?? null,
|
|
201
213
|
cwd: run.workspaceDir,
|
|
202
214
|
...(run.runtimeStateDir ? { runtimeStateDir: run.runtimeStateDir } : {}),
|