Skip to content

Commit 013995f

Browse files
author
hzq
committed
Coordinate tool-free reasoning workspace lifetime
Share directory creation per session and drain allocations and active turns before cleanup. Keep workspace identity checks for ACP and native resumes across worker shutdown.
1 parent 952b3ea commit 013995f

5 files changed

Lines changed: 347 additions & 54 deletions

File tree

‎docs/protocol.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,8 @@ Worker retry delays grow exponentially with jitter and are capped at five second
390390

391391
Workers keep up to 128 parsed bundle manifests warm, with a 16 MiB budget measured on their compact JSON representation. Installed files are not retained in this cache. Before evicting a manifest, the worker seals it in private temporary storage using a key held only by that runtime. An already installed digest can be read back during the same worker lifetime without resending or repeating an execution. Closing the worker removes its temporary index, not the installed files.
392392

393+
Tool-free native turns in the same session share one worker-owned working directory. Worker shutdown waits for those turns and pending directory creation before reclaiming it. A checkpoint tied to an old workspace identity is not silently resumed in a different directory.
394+
393395
If `welcome.features` includes `artifact-chunks-v1`, a worker may deliver an output over its existing execution lease. Each `artifact_chunk` carries the RPC `id`, `leaseId`, zero-based artifact `index`, byte `offset`, total `bytes`, `name`, SHA-256 `sha256` and base64 `data` (up to 128 KiB decoded). Wait for `artifact_ack` with the matching lease, index and offset before the next chunk. The final result references the matching manifest entry with `transferIndex` and empty `content`; a worker path is never a wire reference. An interrupted transfer is discarded, not automatically replayed.
394396

395397
### Node lifecycle control

‎docs/zh-CN/protocol.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,8 @@ worker 的重试等待按指数增长,并加随机抖动,最长 5 秒。只
410410

411411
worker 最多保留 128 份已解析的热清单,按精简后的 JSON 大小计量,预算为 16 MiB。缓存不保留已安装文件的正文。淘汰清单前,worker 用仅当前运行时持有的密钥将它加密存入私有临时目录。同一个 worker 运行期间可按摘要读回已安装清单,不重发或重做任务。worker 关闭时只移除自己的临时索引,不删除已安装文件。
412412

413+
同一会话的无工具原生调用复用同一个由 worker 创建的工作目录。worker 关闭时先等在途调用和目录创建结束,再回收该目录。绑定了旧工作区身份的检查点不会在别的目录里静默恢复。
414+
413415
若 `welcome.features` 含 `artifact-chunks-v1`,节点可通过当前执行租约回传文件。`artifact_chunk` 包含 RPC 的 `id`、`leaseId`、从零开始的产物序号 `index`、字节偏移 `offset`、总大小 `bytes`、`name`、`sha256` 和 Base64 编码的 `data`(解码后最多 128 KiB)。收到相同租约、序号和偏移的 `artifact_ack` 后才发送下一块。最终结果用 `transferIndex` 与空 `content` 引用对应文件,不传节点本机路径。传输中断将丢弃未确认数据,不自动重放任务。
414416

415417
<a id="node-lifecycle-control"></a>

‎src/fabric/reasoning-workspaces.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { mkdtemp, rm } from 'node:fs/promises';
2+
import os from 'node:os';
3+
import path from 'node:path';
4+
import { AbortableWait } from '../core/abortable-wait.js';
5+
import { checkAbort, Fault } from '../core/util.js';
6+
7+
type Workspace = { created: Promise<string>; ready: AbortableWait<string> };
8+
9+
/** Runtime-owned directories for tool-free native turns, stable across resumes in one session. */
10+
export class ReasoningWorkspaces {
11+
private readonly sessions = new Map<string, Workspace>();
12+
private readonly active = new Set<Promise<unknown>>();
13+
private closing?: Promise<void>;
14+
15+
constructor(private readonly create = () => mkdtemp(path.join(os.tmpdir(), 'oaa-reasoning-'))) {}
16+
17+
async use<T>(sessionId: string, signal: AbortSignal, run: (directory: string) => Promise<T>) {
18+
checkAbort(signal);
19+
if (this.closing) throw new Fault('shutting_down', 'Worker is shutting down.', 503);
20+
const task = this.directory(sessionId)
21+
.wait(signal)
22+
.then((directory) => {
23+
checkAbort(signal);
24+
return run(directory);
25+
});
26+
this.active.add(task);
27+
try {
28+
return await task;
29+
} finally {
30+
this.active.delete(task);
31+
}
32+
}
33+
34+
private directory(sessionId: string): AbortableWait<string> {
35+
const existing = this.sessions.get(sessionId);
36+
if (existing) return existing.ready;
37+
const created = Promise.resolve()
38+
.then(this.create)
39+
.catch((error) => {
40+
this.sessions.delete(sessionId);
41+
throw error;
42+
});
43+
const ready = new AbortableWait(created);
44+
this.sessions.set(sessionId, { created, ready });
45+
return ready;
46+
}
47+
48+
close(): Promise<void> {
49+
return (this.closing ??= this.drain());
50+
}
51+
52+
private async drain(): Promise<void> {
53+
await Promise.allSettled(this.active);
54+
// A cancelled waiter may have left its shared allocation running with no observers.
55+
const roots = await Promise.allSettled(
56+
[...this.sessions.values()].map(({ created }) => created),
57+
);
58+
this.sessions.clear();
59+
let failure: unknown;
60+
for (const root of roots) {
61+
if (root.status === 'fulfilled') {
62+
try {
63+
await rm(root.value, { recursive: true, force: true });
64+
} catch (error) {
65+
failure ??= error;
66+
}
67+
}
68+
}
69+
if (failure) throw failure;
70+
}
71+
}

‎src/fabric/worker.ts‎

Lines changed: 58 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@ import { AgentModelCatalogs } from './agent-models.js';
33
import { validateModelWork } from '../core/work-manifest.js';
44
import { executeNative, collectNativeArtifacts } from './native-executor.js';
55
import { ProjectWorkspaces } from './project-workspaces.js';
6-
import { mkdir, readdir, mkdtemp, rm } from 'node:fs/promises';
7-
import os from 'node:os';
6+
import { mkdir, readdir } from 'node:fs/promises';
87
import { existsSync } from 'node:fs';
98
import { JsonSchemas } from '../core/schemas.js';
109
import { McpConnections, mcpConfigured, descriptorDigest, findMcpTool } from './mcp-connections.js';
@@ -25,6 +24,7 @@ import {
2524
} from '../core/contracts.js';
2625
import { builtin } from '../lang/bundle.js';
2726
import { WorkerBundles } from './worker-bundles.js';
27+
import { ReasoningWorkspaces } from './reasoning-workspaces.js';
2828
import { createModelDriver, providerApiKey, type ModelDriver } from '../providers/models.js';
2929
import { validateProviderState } from '../providers/provider-state.js';
3030
import {
@@ -85,7 +85,8 @@ export function adapterReady(
8585
export class WorkerRuntime implements Executor {
8686
readonly modelCatalogs: AgentModelCatalogs;
8787
readonly projects: ProjectWorkspaces;
88-
private reasoningRoots = new Map<string, string>();
88+
private reasoningWorkspaces = new ReasoningWorkspaces();
89+
private closing?: Promise<void>;
8990
/** Protocol timing bounds for ACP agents; tests shorten them. */
9091
acpTimings: AcpTimings = {};
9192
private readonly bundles: WorkerBundles;
@@ -383,6 +384,8 @@ export class WorkerRuntime implements Executor {
383384
}
384385
async execute(work: Work, signal: AbortSignal, emit: Emit): Promise<WorkResult> {
385386
checkAbort(signal);
387+
const reasoning =
388+
work.kind === 'native' && work.toolsDisabled ? this.reasoningWorkspaces : undefined;
386389
const digest = work.context.digest;
387390
const bundle = this.bundles.cached(digest) ?? (await this.bundles.load(digest));
388391
checkAbort(signal);
@@ -392,50 +395,46 @@ export class WorkerRuntime implements Executor {
392395
if (work.kind === 'model' || work.kind === 'native') {
393396
const agent = validateModelWork(bundle, work, this.modelCatalogs.snapshot());
394397
if (work.kind === 'native') {
395-
let executionRoot = root;
396-
if (work.toolsDisabled) {
397-
executionRoot =
398-
this.reasoningRoots.get(work.context.sessionId) ??
399-
(await mkdtemp(path.join(os.tmpdir(), 'oaa-reasoning-')));
400-
this.reasoningRoots.set(work.context.sessionId, executionRoot);
401-
}
402-
const outputRoot = path.join(root, 'outputs');
403-
await mkdir(outputRoot, { recursive: true, mode: 0o700 });
404-
const project = !work.toolsDisabled && agent.access?.workspace === 'project';
405-
const lease = await this.projects.acquire(agent.id, executionRoot, project, signal);
406-
try {
407-
const identity = sha(lease.root);
408-
if (
409-
work.nativeState?.workspaceIdentity &&
410-
work.nativeState.workspaceIdentity !== identity
411-
)
412-
throw new Fault(
413-
'native_resume_unsupported',
414-
'The working directory changed. Use an explicit handoff instead of resuming the old native session.',
415-
409,
398+
const run = async (executionRoot: string) => {
399+
const outputRoot = path.join(root, 'outputs');
400+
await mkdir(outputRoot, { recursive: true, mode: 0o700 });
401+
const project = !work.toolsDisabled && agent.access?.workspace === 'project';
402+
const lease = await this.projects.acquire(agent.id, executionRoot, project, signal);
403+
try {
404+
const identity = sha(lease.root);
405+
if (
406+
work.nativeState?.workspaceIdentity &&
407+
work.nativeState.workspaceIdentity !== identity
408+
)
409+
throw new Fault(
410+
'native_resume_unsupported',
411+
'The working directory changed. Use an explicit handoff instead of resuming the old native session.',
412+
409,
413+
);
414+
const result = await executeNative(
415+
work,
416+
agent,
417+
this.config,
418+
executionRoot,
419+
signal,
420+
emit,
421+
this.acpTimings,
422+
this.nativeSandbox(work),
423+
this.modelCatalogs.snapshot()[agent.engine]?.clientTools === 'hybrid',
424+
project ? lease.root : undefined,
416425
);
417-
const result = await executeNative(
418-
work,
419-
agent,
420-
this.config,
421-
executionRoot,
422-
signal,
423-
emit,
424-
this.acpTimings,
425-
this.nativeSandbox(work),
426-
this.modelCatalogs.snapshot()[agent.engine]?.clientTools === 'hybrid',
427-
project ? lease.root : undefined,
428-
);
429-
return {
430-
...result,
431-
...(agent.access
432-
? { nativeState: { ...result.nativeState, workspaceIdentity: identity } }
433-
: {}),
434-
artifacts: await collectNativeArtifacts(outputRoot, this.config.maxArtifactBytes),
435-
};
436-
} finally {
437-
lease.release();
438-
}
426+
return {
427+
...result,
428+
...(agent.access
429+
? { nativeState: { ...result.nativeState, workspaceIdentity: identity } }
430+
: {}),
431+
artifacts: await collectNativeArtifacts(outputRoot, this.config.maxArtifactBytes),
432+
};
433+
} finally {
434+
lease.release();
435+
}
436+
};
437+
return reasoning ? reasoning.use(work.context.sessionId, signal, run) : run(root);
439438
}
440439
const callerKey = work.credential?.apiKey;
441440
let driver = callerKey === undefined ? this.drivers.get(agent.provider) : undefined;
@@ -725,15 +724,20 @@ export class WorkerRuntime implements Executor {
725724
boundedJson(result, 12 * 1024 * 1024);
726725
return result;
727726
}
728-
async close(): Promise<void> {
727+
close(): Promise<void> {
728+
return (this.closing ??= this.closeResources().finally(() => {
729+
this.reasoningWorkspaces = new ReasoningWorkspaces();
730+
this.closing = undefined;
731+
}));
732+
}
733+
private async closeResources(): Promise<void> {
729734
try {
730-
await this.modelCatalogs.close();
731-
await this.projects.ready;
732-
for (const root of this.reasoningRoots.values())
733-
await rm(root, { recursive: true, force: true });
734-
this.reasoningRoots.clear();
735-
await this.mcpConnections.close();
736-
await this.sandbox?.close();
735+
await this.reasoningWorkspaces.close().finally(async () => {
736+
await this.modelCatalogs.close();
737+
await this.projects.ready;
738+
await this.mcpConnections.close();
739+
await this.sandbox?.close();
740+
});
737741
} finally {
738742
await this.bundles.close();
739743
}

0 commit comments

Comments
 (0)