@amaranthic/hernex 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +66 -2
- package/dist/ai.d.ts +11 -0
- package/dist/ai.d.ts.map +1 -0
- package/dist/ai.js +11 -0
- package/dist/ai.js.map +1 -0
- package/dist/checkpoints/FileCheckpointStore.d.ts +95 -0
- package/dist/checkpoints/FileCheckpointStore.d.ts.map +1 -0
- package/dist/checkpoints/FileCheckpointStore.js +412 -0
- package/dist/checkpoints/FileCheckpointStore.js.map +1 -0
- package/dist/checkpoints/index.d.ts +7 -0
- package/dist/checkpoints/index.d.ts.map +1 -0
- package/dist/checkpoints/index.js +7 -0
- package/dist/checkpoints/index.js.map +1 -0
- package/dist/checkpoints/types.d.ts +157 -0
- package/dist/checkpoints/types.d.ts.map +1 -0
- package/dist/checkpoints/types.js +6 -0
- package/dist/checkpoints/types.js.map +1 -0
- package/dist/engine/AgentEngine.d.ts +156 -0
- package/dist/engine/AgentEngine.d.ts.map +1 -0
- package/dist/engine/AgentEngine.js +288 -0
- package/dist/engine/AgentEngine.js.map +1 -0
- package/dist/engine/engineConfig.d.ts +138 -0
- package/dist/engine/engineConfig.d.ts.map +1 -0
- package/dist/engine/engineConfig.js +6 -0
- package/dist/engine/engineConfig.js.map +1 -0
- package/dist/engine/eventQueue.d.ts +42 -0
- package/dist/engine/eventQueue.d.ts.map +1 -0
- package/dist/engine/eventQueue.js +93 -0
- package/dist/engine/eventQueue.js.map +1 -0
- package/dist/engine/index.d.ts +7 -0
- package/dist/engine/index.d.ts.map +1 -0
- package/dist/engine/index.js +6 -0
- package/dist/engine/index.js.map +1 -0
- package/dist/engine/runTurn.d.ts +17 -0
- package/dist/engine/runTurn.d.ts.map +1 -0
- package/dist/engine/runTurn.js +684 -0
- package/dist/engine/runTurn.js.map +1 -0
- package/dist/errors.d.ts +142 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +174 -0
- package/dist/errors.js.map +1 -0
- package/dist/events/checkpointEvents.d.ts +20 -0
- package/dist/events/checkpointEvents.d.ts.map +1 -0
- package/dist/events/checkpointEvents.js +6 -0
- package/dist/events/checkpointEvents.js.map +1 -0
- package/dist/events/errorEvents.d.ts +23 -0
- package/dist/events/errorEvents.d.ts.map +1 -0
- package/dist/events/errorEvents.js +6 -0
- package/dist/events/errorEvents.js.map +1 -0
- package/dist/events/index.d.ts +11 -0
- package/dist/events/index.d.ts.map +1 -0
- package/dist/events/index.js +6 -0
- package/dist/events/index.js.map +1 -0
- package/dist/events/stepEvents.d.ts +68 -0
- package/dist/events/stepEvents.d.ts.map +1 -0
- package/dist/events/stepEvents.js +6 -0
- package/dist/events/stepEvents.js.map +1 -0
- package/dist/events/streamEvents.d.ts +41 -0
- package/dist/events/streamEvents.d.ts.map +1 -0
- package/dist/events/streamEvents.js +6 -0
- package/dist/events/streamEvents.js.map +1 -0
- package/dist/events/toolEvents.d.ts +62 -0
- package/dist/events/toolEvents.d.ts.map +1 -0
- package/dist/events/toolEvents.js +6 -0
- package/dist/events/toolEvents.js.map +1 -0
- package/dist/events/types.d.ts +37 -0
- package/dist/events/types.d.ts.map +1 -0
- package/dist/events/types.js +6 -0
- package/dist/events/types.js.map +1 -0
- package/dist/hooks/composeAgentHooks.d.ts +14 -0
- package/dist/hooks/composeAgentHooks.d.ts.map +1 -0
- package/dist/hooks/composeAgentHooks.js +142 -0
- package/dist/hooks/composeAgentHooks.js.map +1 -0
- package/dist/hooks/index.d.ts +7 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/index.js +6 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/hooks/types.d.ts +133 -0
- package/dist/hooks/types.d.ts.map +1 -0
- package/dist/hooks/types.js +6 -0
- package/dist/hooks/types.js.map +1 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -0
- package/dist/index.js.map +1 -0
- package/dist/model/ProviderRegistry.d.ts +62 -0
- package/dist/model/ProviderRegistry.d.ts.map +1 -0
- package/dist/model/ProviderRegistry.js +114 -0
- package/dist/model/ProviderRegistry.js.map +1 -0
- package/dist/model/providers/alibaba.d.ts +11 -0
- package/dist/model/providers/alibaba.d.ts.map +1 -0
- package/dist/model/providers/alibaba.js +16 -0
- package/dist/model/providers/alibaba.js.map +1 -0
- package/dist/model/providers/anthropic.d.ts +11 -0
- package/dist/model/providers/anthropic.d.ts.map +1 -0
- package/dist/model/providers/anthropic.js +16 -0
- package/dist/model/providers/anthropic.js.map +1 -0
- package/dist/model/providers/cohere.d.ts +11 -0
- package/dist/model/providers/cohere.d.ts.map +1 -0
- package/dist/model/providers/cohere.js +16 -0
- package/dist/model/providers/cohere.js.map +1 -0
- package/dist/model/providers/compatible.d.ts +11 -0
- package/dist/model/providers/compatible.d.ts.map +1 -0
- package/dist/model/providers/compatible.js +17 -0
- package/dist/model/providers/compatible.js.map +1 -0
- package/dist/model/providers/deepseek.d.ts +11 -0
- package/dist/model/providers/deepseek.d.ts.map +1 -0
- package/dist/model/providers/deepseek.js +16 -0
- package/dist/model/providers/deepseek.js.map +1 -0
- package/dist/model/providers/google.d.ts +11 -0
- package/dist/model/providers/google.d.ts.map +1 -0
- package/dist/model/providers/google.js +16 -0
- package/dist/model/providers/google.js.map +1 -0
- package/dist/model/providers/groq.d.ts +11 -0
- package/dist/model/providers/groq.d.ts.map +1 -0
- package/dist/model/providers/groq.js +16 -0
- package/dist/model/providers/groq.js.map +1 -0
- package/dist/model/providers/mistral.d.ts +11 -0
- package/dist/model/providers/mistral.d.ts.map +1 -0
- package/dist/model/providers/mistral.js +16 -0
- package/dist/model/providers/mistral.js.map +1 -0
- package/dist/model/providers/openai.d.ts +11 -0
- package/dist/model/providers/openai.d.ts.map +1 -0
- package/dist/model/providers/openai.js +16 -0
- package/dist/model/providers/openai.js.map +1 -0
- package/dist/model/providers/openrouter.d.ts +14 -0
- package/dist/model/providers/openrouter.d.ts.map +1 -0
- package/dist/model/providers/openrouter.js +20 -0
- package/dist/model/providers/openrouter.js.map +1 -0
- package/dist/model/providers/togetherai.d.ts +11 -0
- package/dist/model/providers/togetherai.d.ts.map +1 -0
- package/dist/model/providers/togetherai.js +16 -0
- package/dist/model/providers/togetherai.js.map +1 -0
- package/dist/model/providers/vercelGateway.d.ts +14 -0
- package/dist/model/providers/vercelGateway.d.ts.map +1 -0
- package/dist/model/providers/vercelGateway.js +19 -0
- package/dist/model/providers/vercelGateway.js.map +1 -0
- package/dist/model/providers/xai.d.ts +11 -0
- package/dist/model/providers/xai.d.ts.map +1 -0
- package/dist/model/providers/xai.js +16 -0
- package/dist/model/providers/xai.js.map +1 -0
- package/dist/model/resolveModel.d.ts +45 -0
- package/dist/model/resolveModel.d.ts.map +1 -0
- package/dist/model/resolveModel.js +109 -0
- package/dist/model/resolveModel.js.map +1 -0
- package/dist/model/types.d.ts +98 -0
- package/dist/model/types.d.ts.map +1 -0
- package/dist/model/types.js +6 -0
- package/dist/model/types.js.map +1 -0
- package/dist/runtime.d.ts +74 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +41 -0
- package/dist/runtime.js.map +1 -0
- package/dist/storage/atomicFile.d.ts +28 -0
- package/dist/storage/atomicFile.d.ts.map +1 -0
- package/dist/storage/atomicFile.js +56 -0
- package/dist/storage/atomicFile.js.map +1 -0
- package/dist/storage/homeDirectory.d.ts +21 -0
- package/dist/storage/homeDirectory.d.ts.map +1 -0
- package/dist/storage/homeDirectory.js +36 -0
- package/dist/storage/homeDirectory.js.map +1 -0
- package/dist/storage/index.d.ts +10 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/index.js +10 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/storage/jsonl.d.ts +46 -0
- package/dist/storage/jsonl.d.ts.map +1 -0
- package/dist/storage/jsonl.js +121 -0
- package/dist/storage/jsonl.js.map +1 -0
- package/dist/storage/lock.d.ts +47 -0
- package/dist/storage/lock.d.ts.map +1 -0
- package/dist/storage/lock.js +126 -0
- package/dist/storage/lock.js.map +1 -0
- package/dist/storage/valueCodec.d.ts +68 -0
- package/dist/storage/valueCodec.d.ts.map +1 -0
- package/dist/storage/valueCodec.js +140 -0
- package/dist/storage/valueCodec.js.map +1 -0
- package/dist/tasks/TaskManager.d.ts +155 -0
- package/dist/tasks/TaskManager.d.ts.map +1 -0
- package/dist/tasks/TaskManager.js +774 -0
- package/dist/tasks/TaskManager.js.map +1 -0
- package/dist/tasks/index.d.ts +7 -0
- package/dist/tasks/index.d.ts.map +1 -0
- package/dist/tasks/index.js +6 -0
- package/dist/tasks/index.js.map +1 -0
- package/dist/tasks/types.d.ts +160 -0
- package/dist/tasks/types.d.ts.map +1 -0
- package/dist/tasks/types.js +8 -0
- package/dist/tasks/types.js.map +1 -0
- package/dist/threads/FileThreadStore.d.ts +118 -0
- package/dist/threads/FileThreadStore.d.ts.map +1 -0
- package/dist/threads/FileThreadStore.js +320 -0
- package/dist/threads/FileThreadStore.js.map +1 -0
- package/dist/threads/index.d.ts +7 -0
- package/dist/threads/index.d.ts.map +1 -0
- package/dist/threads/index.js +7 -0
- package/dist/threads/index.js.map +1 -0
- package/dist/threads/types.d.ts +230 -0
- package/dist/threads/types.d.ts.map +1 -0
- package/dist/threads/types.js +6 -0
- package/dist/threads/types.js.map +1 -0
- package/dist/tools/AgentTool.d.ts +38 -0
- package/dist/tools/AgentTool.d.ts.map +1 -0
- package/dist/tools/AgentTool.js +6 -0
- package/dist/tools/AgentTool.js.map +1 -0
- package/dist/tools/BashTool.d.ts +61 -0
- package/dist/tools/BashTool.d.ts.map +1 -0
- package/dist/tools/BashTool.js +142 -0
- package/dist/tools/BashTool.js.map +1 -0
- package/dist/tools/EditFileTool.d.ts +49 -0
- package/dist/tools/EditFileTool.d.ts.map +1 -0
- package/dist/tools/EditFileTool.js +114 -0
- package/dist/tools/EditFileTool.js.map +1 -0
- package/dist/tools/GlobTool.d.ts +48 -0
- package/dist/tools/GlobTool.d.ts.map +1 -0
- package/dist/tools/GlobTool.js +117 -0
- package/dist/tools/GlobTool.js.map +1 -0
- package/dist/tools/GrepTool.d.ts +73 -0
- package/dist/tools/GrepTool.d.ts.map +1 -0
- package/dist/tools/GrepTool.js +250 -0
- package/dist/tools/GrepTool.js.map +1 -0
- package/dist/tools/ReadFileTool.d.ts +51 -0
- package/dist/tools/ReadFileTool.d.ts.map +1 -0
- package/dist/tools/ReadFileTool.js +153 -0
- package/dist/tools/ReadFileTool.js.map +1 -0
- package/dist/tools/TaskManagerTool.d.ts +102 -0
- package/dist/tools/TaskManagerTool.d.ts.map +1 -0
- package/dist/tools/TaskManagerTool.js +130 -0
- package/dist/tools/TaskManagerTool.js.map +1 -0
- package/dist/tools/ToolExecutionContext.d.ts +61 -0
- package/dist/tools/ToolExecutionContext.d.ts.map +1 -0
- package/dist/tools/ToolExecutionContext.js +8 -0
- package/dist/tools/ToolExecutionContext.js.map +1 -0
- package/dist/tools/ToolRegistry.d.ts +82 -0
- package/dist/tools/ToolRegistry.d.ts.map +1 -0
- package/dist/tools/ToolRegistry.js +116 -0
- package/dist/tools/ToolRegistry.js.map +1 -0
- package/dist/tools/WriteFileTool.d.ts +46 -0
- package/dist/tools/WriteFileTool.d.ts.map +1 -0
- package/dist/tools/WriteFileTool.js +87 -0
- package/dist/tools/WriteFileTool.js.map +1 -0
- package/dist/tools/index.d.ts +17 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +17 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/internal/bashEnvironment.d.ts +20 -0
- package/dist/tools/internal/bashEnvironment.d.ts.map +1 -0
- package/dist/tools/internal/bashEnvironment.js +65 -0
- package/dist/tools/internal/bashEnvironment.js.map +1 -0
- package/dist/tools/internal/pathGuard.d.ts +27 -0
- package/dist/tools/internal/pathGuard.d.ts.map +1 -0
- package/dist/tools/internal/pathGuard.js +99 -0
- package/dist/tools/internal/pathGuard.js.map +1 -0
- package/dist/tools/prompts.d.ts +33 -0
- package/dist/tools/prompts.d.ts.map +1 -0
- package/dist/tools/prompts.js +48 -0
- package/dist/tools/prompts.js.map +1 -0
- package/package.json +64 -4
|
@@ -0,0 +1,774 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Subprocess task manager handling live disk output streaming,
|
|
3
|
+
* line-paged inspection, stdin interaction, and process group lifecycle controls.
|
|
4
|
+
* Single owner of subprocess spawning, signalling, waiting, and deletion.
|
|
5
|
+
* @packageDocumentation
|
|
6
|
+
*/
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import { randomUUID } from "node:crypto";
|
|
9
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, createReadStream, } from "node:fs";
|
|
10
|
+
import os from "node:os";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { createInterface } from "node:readline";
|
|
13
|
+
import { StringDecoder } from "node:string_decoder";
|
|
14
|
+
import { atomicWriteFile } from "../storage/atomicFile.js";
|
|
15
|
+
import { resolveHomeDirectory } from "../storage/homeDirectory.js";
|
|
16
|
+
import { getSafeBashEnvironment } from "../tools/internal/bashEnvironment.js";
|
|
17
|
+
/** Default retention time for terminated tasks (10 minutes). */
|
|
18
|
+
export const defaultRetentionTtlMs = 10 * 60 * 1000;
|
|
19
|
+
/** Default capacity limit for completed tasks before pruning (50 tasks). */
|
|
20
|
+
export const defaultMaxRetainedTasks = 50;
|
|
21
|
+
/** Default maximum output bytes persisted to disk log before truncation (1MB). */
|
|
22
|
+
export const defaultMaxOutputBytes = 1_000_000;
|
|
23
|
+
/** Default termination grace period before escalating from SIGTERM to SIGKILL (3000ms). */
|
|
24
|
+
export const defaultTerminationGraceMs = 3000;
|
|
25
|
+
/** Safe identifier regex pattern matching thread and task identifiers. */
|
|
26
|
+
const safeIdPattern = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
27
|
+
/**
|
|
28
|
+
* Manages background shell executions, live logging, and line-paged retrieval.
|
|
29
|
+
* Sole owner of process spawning, signalling, output persistence, and termination.
|
|
30
|
+
*/
|
|
31
|
+
export class TaskManager {
|
|
32
|
+
rootDir;
|
|
33
|
+
threadId;
|
|
34
|
+
workingDirectory;
|
|
35
|
+
isPersist;
|
|
36
|
+
retentionTtlMs;
|
|
37
|
+
maxRetainedTasks;
|
|
38
|
+
maxOutputBytes;
|
|
39
|
+
terminationGraceMs;
|
|
40
|
+
tasks = new Map();
|
|
41
|
+
evictedReasons = new Map();
|
|
42
|
+
isDisposed = false;
|
|
43
|
+
/**
|
|
44
|
+
* Initializes a new TaskManager instance.
|
|
45
|
+
*
|
|
46
|
+
* @param options - Configuration options for directory resolution, retention, and thread identity.
|
|
47
|
+
* @throws Error if threadId is provided and fails safe identifier validation.
|
|
48
|
+
*/
|
|
49
|
+
constructor(options) {
|
|
50
|
+
this.threadId = options.threadId;
|
|
51
|
+
if (!safeIdPattern.test(this.threadId)) {
|
|
52
|
+
throw new Error(`Invalid threadId "${this.threadId}". Thread IDs must match ${safeIdPattern.source}`);
|
|
53
|
+
}
|
|
54
|
+
this.workingDirectory = options.workingDirectory || process.cwd();
|
|
55
|
+
this.rootDir = resolveHomeDirectory(options.homeDirectory !== undefined
|
|
56
|
+
? { homeDirectory: options.homeDirectory }
|
|
57
|
+
: undefined);
|
|
58
|
+
this.isPersist = options.persist ?? false;
|
|
59
|
+
this.retentionTtlMs = options.retentionTtlMs ?? defaultRetentionTtlMs;
|
|
60
|
+
this.maxRetainedTasks = options.maxRetainedTasks ?? defaultMaxRetainedTasks;
|
|
61
|
+
this.maxOutputBytes = options.maxOutputBytes ?? defaultMaxOutputBytes;
|
|
62
|
+
this.terminationGraceMs =
|
|
63
|
+
options.terminationGraceMs ?? defaultTerminationGraceMs;
|
|
64
|
+
this.loadPersistedTasks();
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Validates that a task identifier conforms to the safe identifier specification.
|
|
68
|
+
*
|
|
69
|
+
* @param taskId - The task identifier to validate.
|
|
70
|
+
* @throws Error if the identifier is malformed.
|
|
71
|
+
*/
|
|
72
|
+
assertValidTaskId(taskId) {
|
|
73
|
+
if (!taskId || !safeIdPattern.test(taskId)) {
|
|
74
|
+
throw new Error(`Invalid taskId "${taskId}". Task IDs must match ${safeIdPattern.source}`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Generates a unique task identifier using UUIDv4.
|
|
79
|
+
*
|
|
80
|
+
* @returns Formatted task identifier string.
|
|
81
|
+
*/
|
|
82
|
+
createUniqueTaskId() {
|
|
83
|
+
return `task_${randomUUID()}`;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Resolves the on-disk storage directory for a specific task.
|
|
87
|
+
*
|
|
88
|
+
* @param taskId - The validated task identifier.
|
|
89
|
+
* @returns Fully resolved directory path.
|
|
90
|
+
*/
|
|
91
|
+
getTaskDirectory(taskId) {
|
|
92
|
+
this.assertValidTaskId(taskId);
|
|
93
|
+
if (this.isPersist) {
|
|
94
|
+
return path.join(this.rootDir, "threads", this.threadId, "tasks", taskId);
|
|
95
|
+
}
|
|
96
|
+
return path.join(os.tmpdir(), "hernex", "tasks", this.threadId, taskId);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Spawns and registers a new shell process as a managed task.
|
|
100
|
+
* This is the sole execution owner for subprocess spawning across Harnex.
|
|
101
|
+
*
|
|
102
|
+
* @param input - Process parameters including command string, cwd, timeout, and environment allowlist.
|
|
103
|
+
* @param options - Optional observers such as streaming onOutput callback.
|
|
104
|
+
* @returns Snapshot metadata of the newly created task.
|
|
105
|
+
* @throws Error if the task manager has been shut down or command is invalid.
|
|
106
|
+
*/
|
|
107
|
+
async createTask(input, options) {
|
|
108
|
+
if (this.isDisposed) {
|
|
109
|
+
throw new Error("Cannot create task: TaskManager has been shut down.");
|
|
110
|
+
}
|
|
111
|
+
if (!input.command || typeof input.command !== "string" || input.command.trim().length === 0) {
|
|
112
|
+
throw new Error("Command must be a non-empty string.");
|
|
113
|
+
}
|
|
114
|
+
this.evictExpiredTasks();
|
|
115
|
+
const taskId = this.createUniqueTaskId();
|
|
116
|
+
const taskDir = this.getTaskDirectory(taskId);
|
|
117
|
+
if (!existsSync(taskDir)) {
|
|
118
|
+
mkdirSync(taskDir, { recursive: true });
|
|
119
|
+
}
|
|
120
|
+
const logPath = path.join(taskDir, "output.log");
|
|
121
|
+
appendFileSync(logPath, "");
|
|
122
|
+
const cwd = input.cwd ?? this.workingDirectory;
|
|
123
|
+
const env = getSafeBashEnvironment(input.envAllowlist);
|
|
124
|
+
const child = spawn(input.command, {
|
|
125
|
+
shell: true,
|
|
126
|
+
cwd,
|
|
127
|
+
env,
|
|
128
|
+
detached: true,
|
|
129
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
130
|
+
});
|
|
131
|
+
const now = Date.now();
|
|
132
|
+
const initialMetadata = {
|
|
133
|
+
id: taskId,
|
|
134
|
+
command: input.command,
|
|
135
|
+
pid: child.pid,
|
|
136
|
+
cwd,
|
|
137
|
+
status: "running",
|
|
138
|
+
startedAt: now,
|
|
139
|
+
exitCode: null,
|
|
140
|
+
signal: null,
|
|
141
|
+
totalLines: 0,
|
|
142
|
+
outputBytes: 0,
|
|
143
|
+
outputTruncated: false,
|
|
144
|
+
logPath,
|
|
145
|
+
};
|
|
146
|
+
const record = {
|
|
147
|
+
metadata: initialMetadata,
|
|
148
|
+
child,
|
|
149
|
+
logPath,
|
|
150
|
+
persistedBytes: 0,
|
|
151
|
+
newlineCount: 0,
|
|
152
|
+
pendingBuffer: "",
|
|
153
|
+
statusWasFailed: false,
|
|
154
|
+
stdinClosed: false,
|
|
155
|
+
waiters: new Set(),
|
|
156
|
+
};
|
|
157
|
+
const stdoutDecoder = new StringDecoder("utf-8");
|
|
158
|
+
const stderrDecoder = new StringDecoder("utf-8");
|
|
159
|
+
const appendChunk = (text) => {
|
|
160
|
+
if (text.length === 0)
|
|
161
|
+
return;
|
|
162
|
+
const chunkBytes = Buffer.byteLength(text, "utf-8");
|
|
163
|
+
record.metadata = {
|
|
164
|
+
...record.metadata,
|
|
165
|
+
outputBytes: record.metadata.outputBytes + chunkBytes,
|
|
166
|
+
};
|
|
167
|
+
for (let i = 0; i < text.length; i++) {
|
|
168
|
+
if (text[i] === "\n") {
|
|
169
|
+
record.newlineCount += 1;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
record.pendingBuffer += text;
|
|
173
|
+
const hasTrailingNewline = text.endsWith("\n");
|
|
174
|
+
const currentTotalLines = record.newlineCount + (hasTrailingNewline || record.pendingBuffer.length === 0 ? 0 : 1);
|
|
175
|
+
record.metadata = {
|
|
176
|
+
...record.metadata,
|
|
177
|
+
totalLines: currentTotalLines,
|
|
178
|
+
};
|
|
179
|
+
if (record.persistedBytes < this.maxOutputBytes) {
|
|
180
|
+
const available = this.maxOutputBytes - record.persistedBytes;
|
|
181
|
+
if (chunkBytes <= available) {
|
|
182
|
+
appendFileSync(logPath, text, "utf-8");
|
|
183
|
+
record.persistedBytes += chunkBytes;
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
const slice = Buffer.from(text, "utf-8").subarray(0, available).toString("utf-8");
|
|
187
|
+
if (slice.length > 0) {
|
|
188
|
+
appendFileSync(logPath, slice, "utf-8");
|
|
189
|
+
record.persistedBytes += Buffer.byteLength(slice, "utf-8");
|
|
190
|
+
}
|
|
191
|
+
record.metadata = {
|
|
192
|
+
...record.metadata,
|
|
193
|
+
outputTruncated: true,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
record.metadata = {
|
|
199
|
+
...record.metadata,
|
|
200
|
+
outputTruncated: true,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
child.stdout?.on("data", (chunk) => {
|
|
205
|
+
const text = stdoutDecoder.write(chunk);
|
|
206
|
+
if (text.length > 0) {
|
|
207
|
+
if (options?.onOutput) {
|
|
208
|
+
try {
|
|
209
|
+
options.onOutput(text);
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
// Live observer errors must not interrupt process output draining
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
appendChunk(text);
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
child.stderr?.on("data", (chunk) => {
|
|
219
|
+
const text = stderrDecoder.write(chunk);
|
|
220
|
+
if (text.length > 0) {
|
|
221
|
+
if (options?.onOutput) {
|
|
222
|
+
try {
|
|
223
|
+
options.onOutput(text);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
// Live observer errors must not interrupt process output draining
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
appendChunk(text);
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
child.stdin?.on("error", () => {
|
|
233
|
+
record.stdinClosed = true;
|
|
234
|
+
});
|
|
235
|
+
child.on("error", () => {
|
|
236
|
+
record.statusWasFailed = true;
|
|
237
|
+
record.metadata = {
|
|
238
|
+
...record.metadata,
|
|
239
|
+
status: "failed",
|
|
240
|
+
};
|
|
241
|
+
});
|
|
242
|
+
if (input.timeoutMs && input.timeoutMs > 0) {
|
|
243
|
+
record.killTimer = setTimeout(() => {
|
|
244
|
+
this.stopTask(taskId, { signal: "SIGTERM" }).catch(() => { });
|
|
245
|
+
}, input.timeoutMs);
|
|
246
|
+
record.killTimer.unref();
|
|
247
|
+
}
|
|
248
|
+
child.once("close", (code, signal) => {
|
|
249
|
+
const restOut = stdoutDecoder.end();
|
|
250
|
+
if (restOut.length > 0) {
|
|
251
|
+
if (options?.onOutput) {
|
|
252
|
+
try {
|
|
253
|
+
options.onOutput(restOut);
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
// Live observer errors must not interrupt process output draining
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
appendChunk(restOut);
|
|
260
|
+
}
|
|
261
|
+
const restErr = stderrDecoder.end();
|
|
262
|
+
if (restErr.length > 0) {
|
|
263
|
+
if (options?.onOutput) {
|
|
264
|
+
try {
|
|
265
|
+
options.onOutput(restErr);
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
// Live observer errors must not interrupt process output draining
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
appendChunk(restErr);
|
|
272
|
+
}
|
|
273
|
+
record.stdinClosed = true;
|
|
274
|
+
if (record.killTimer) {
|
|
275
|
+
clearTimeout(record.killTimer);
|
|
276
|
+
record.killTimer = undefined;
|
|
277
|
+
}
|
|
278
|
+
if (record.escalationTimer) {
|
|
279
|
+
clearTimeout(record.escalationTimer);
|
|
280
|
+
record.escalationTimer = undefined;
|
|
281
|
+
}
|
|
282
|
+
const endedAt = Date.now();
|
|
283
|
+
let finalStatus = "exited";
|
|
284
|
+
if (record.statusWasFailed) {
|
|
285
|
+
finalStatus = "failed";
|
|
286
|
+
}
|
|
287
|
+
else if (record.metadata.status === "stopping" ||
|
|
288
|
+
record.metadata.status === "killed" ||
|
|
289
|
+
signal !== null) {
|
|
290
|
+
finalStatus = "killed";
|
|
291
|
+
}
|
|
292
|
+
record.metadata = {
|
|
293
|
+
...record.metadata,
|
|
294
|
+
status: finalStatus,
|
|
295
|
+
endedAt,
|
|
296
|
+
exitCode: code,
|
|
297
|
+
signal,
|
|
298
|
+
};
|
|
299
|
+
record.terminalTimestamp = endedAt;
|
|
300
|
+
const metaPath = path.join(taskDir, "meta.json");
|
|
301
|
+
atomicWriteFile(metaPath, JSON.stringify(record.metadata, null, 2)).catch(() => { });
|
|
302
|
+
for (const waiter of record.waiters) {
|
|
303
|
+
waiter(record.metadata);
|
|
304
|
+
}
|
|
305
|
+
record.waiters.clear();
|
|
306
|
+
});
|
|
307
|
+
this.tasks.set(taskId, record);
|
|
308
|
+
return record.metadata;
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Retrieves current metadata for a task, or undefined if unknown or expired.
|
|
312
|
+
*
|
|
313
|
+
* @param taskId - Unique task identifier.
|
|
314
|
+
* @returns Snapshot metadata of the task, or undefined if not found.
|
|
315
|
+
*/
|
|
316
|
+
getTask(taskId) {
|
|
317
|
+
this.assertValidTaskId(taskId);
|
|
318
|
+
this.evictExpiredTasks();
|
|
319
|
+
return this.tasks.get(taskId)?.metadata;
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Lists lightweight summaries of all active and recently completed tasks.
|
|
323
|
+
*
|
|
324
|
+
* @returns Readonly array of task summaries.
|
|
325
|
+
*/
|
|
326
|
+
listTasks() {
|
|
327
|
+
this.evictExpiredTasks();
|
|
328
|
+
const now = Date.now();
|
|
329
|
+
const summaries = [];
|
|
330
|
+
for (const record of this.tasks.values()) {
|
|
331
|
+
const meta = record.metadata;
|
|
332
|
+
const runtimeMs = (meta.endedAt ?? now) - meta.startedAt;
|
|
333
|
+
summaries.push({
|
|
334
|
+
id: meta.id,
|
|
335
|
+
command: meta.command,
|
|
336
|
+
status: meta.status,
|
|
337
|
+
runtimeMs,
|
|
338
|
+
exitCode: meta.exitCode,
|
|
339
|
+
totalLines: meta.totalLines,
|
|
340
|
+
outputBytes: meta.outputBytes,
|
|
341
|
+
outputTruncated: meta.outputTruncated,
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
return summaries;
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Reads a line-paged slice from a task's log output file on disk.
|
|
348
|
+
*
|
|
349
|
+
* @param taskId - The unique task identifier.
|
|
350
|
+
* @param offset - 1-based starting line number (required).
|
|
351
|
+
* @param limit - Maximum lines to read in this slice (capped at 500).
|
|
352
|
+
* @returns Promise resolving to the paged task log slice.
|
|
353
|
+
* @throws Error if the task is not found, expired, or parameters are out of range.
|
|
354
|
+
*/
|
|
355
|
+
async readTask(taskId, offset, limit) {
|
|
356
|
+
this.assertValidTaskId(taskId);
|
|
357
|
+
this.evictExpiredTasks();
|
|
358
|
+
const record = this.tasks.get(taskId);
|
|
359
|
+
if (!record) {
|
|
360
|
+
const reason = this.evictedReasons.get(taskId);
|
|
361
|
+
if (reason) {
|
|
362
|
+
throw new Error(`Task "${taskId}" was ${reason}.`);
|
|
363
|
+
}
|
|
364
|
+
throw new Error(`Task "${taskId}" not found.`);
|
|
365
|
+
}
|
|
366
|
+
if (offset < 1) {
|
|
367
|
+
throw new Error(`Invalid offset: ${offset}. Offset must be >= 1.`);
|
|
368
|
+
}
|
|
369
|
+
const clampedLimit = Math.min(Math.max(1, limit), 500);
|
|
370
|
+
const logPath = record.metadata.logPath;
|
|
371
|
+
if (!existsSync(logPath)) {
|
|
372
|
+
return {
|
|
373
|
+
taskId,
|
|
374
|
+
status: record.metadata.status,
|
|
375
|
+
exitCode: record.metadata.exitCode,
|
|
376
|
+
offset,
|
|
377
|
+
limit: clampedLimit,
|
|
378
|
+
totalLines: 0,
|
|
379
|
+
hasMore: false,
|
|
380
|
+
lines: [],
|
|
381
|
+
outputTruncated: record.metadata.outputTruncated,
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
const lines = [];
|
|
385
|
+
let currentLineIndex = 0;
|
|
386
|
+
const targetStart = offset;
|
|
387
|
+
const targetEnd = offset + clampedLimit - 1;
|
|
388
|
+
const fileStream = createReadStream(logPath, { encoding: "utf-8" });
|
|
389
|
+
const readlineInterface = createInterface({
|
|
390
|
+
input: fileStream,
|
|
391
|
+
crlfDelay: Infinity,
|
|
392
|
+
});
|
|
393
|
+
for await (const line of readlineInterface) {
|
|
394
|
+
currentLineIndex += 1;
|
|
395
|
+
if (currentLineIndex >= targetStart && currentLineIndex <= targetEnd) {
|
|
396
|
+
lines.push(line);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
const totalLines = Math.max(record.metadata.totalLines, currentLineIndex);
|
|
400
|
+
const hasMore = totalLines > targetEnd;
|
|
401
|
+
return {
|
|
402
|
+
taskId,
|
|
403
|
+
status: record.metadata.status,
|
|
404
|
+
exitCode: record.metadata.exitCode,
|
|
405
|
+
offset,
|
|
406
|
+
limit: clampedLimit,
|
|
407
|
+
totalLines,
|
|
408
|
+
hasMore,
|
|
409
|
+
lines,
|
|
410
|
+
outputTruncated: record.metadata.outputTruncated,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Delivers text into a running task's standard input stream.
|
|
415
|
+
*
|
|
416
|
+
* @param taskId - The unique task identifier.
|
|
417
|
+
* @param input - Text payload to write.
|
|
418
|
+
* @param options - Optional parameters, such as appending a newline.
|
|
419
|
+
* @returns Promise resolving to input delivery confirmation.
|
|
420
|
+
* @throws Error if the task is not found, not running, or stdin is closed.
|
|
421
|
+
*/
|
|
422
|
+
async sendTaskInput(taskId, input, options) {
|
|
423
|
+
this.assertValidTaskId(taskId);
|
|
424
|
+
this.evictExpiredTasks();
|
|
425
|
+
const record = this.tasks.get(taskId);
|
|
426
|
+
if (!record) {
|
|
427
|
+
throw new Error(`Task "${taskId}" not found.`);
|
|
428
|
+
}
|
|
429
|
+
if (record.metadata.status !== "running" ||
|
|
430
|
+
record.stdinClosed ||
|
|
431
|
+
!record.child?.stdin ||
|
|
432
|
+
record.child.stdin.destroyed) {
|
|
433
|
+
throw new Error(`Cannot write to task "${taskId}": process has ${record.metadata.status} or stdin is closed.`);
|
|
434
|
+
}
|
|
435
|
+
const payload = (options?.newline ?? true) ? `${input}\n` : input;
|
|
436
|
+
const bytesWritten = Buffer.byteLength(payload, "utf-8");
|
|
437
|
+
await new Promise((resolve, reject) => {
|
|
438
|
+
record.child.stdin.write(payload, "utf-8", (err) => {
|
|
439
|
+
if (err) {
|
|
440
|
+
record.stdinClosed = true;
|
|
441
|
+
reject(err);
|
|
442
|
+
}
|
|
443
|
+
else {
|
|
444
|
+
resolve();
|
|
445
|
+
}
|
|
446
|
+
});
|
|
447
|
+
});
|
|
448
|
+
return {
|
|
449
|
+
taskId,
|
|
450
|
+
status: "running",
|
|
451
|
+
bytesWritten,
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Terminates a task process gracefully with SIGTERM, escalating to SIGKILL after grace period.
|
|
456
|
+
* Blocks until child close is observed to guarantee complete termination.
|
|
457
|
+
*
|
|
458
|
+
* @param taskId - The unique task identifier to terminate.
|
|
459
|
+
* @param options - Signal to dispatch and termination grace timeout before escalating to SIGKILL.
|
|
460
|
+
* @returns Promise resolving to final termination details.
|
|
461
|
+
* @throws Error if the task is not found.
|
|
462
|
+
*/
|
|
463
|
+
async stopTask(taskId, options) {
|
|
464
|
+
this.assertValidTaskId(taskId);
|
|
465
|
+
this.evictExpiredTasks();
|
|
466
|
+
const record = this.tasks.get(taskId);
|
|
467
|
+
if (!record) {
|
|
468
|
+
throw new Error(`Task "${taskId}" not found.`);
|
|
469
|
+
}
|
|
470
|
+
if (record.metadata.status !== "running" &&
|
|
471
|
+
record.metadata.status !== "stopping") {
|
|
472
|
+
return {
|
|
473
|
+
taskId,
|
|
474
|
+
status: (record.metadata.status === "orphaned"
|
|
475
|
+
? "exited"
|
|
476
|
+
: record.metadata.status),
|
|
477
|
+
exitCode: record.metadata.exitCode,
|
|
478
|
+
signal: record.metadata.signal,
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
record.metadata = {
|
|
482
|
+
...record.metadata,
|
|
483
|
+
status: "stopping",
|
|
484
|
+
};
|
|
485
|
+
const signal = options?.signal ?? "SIGTERM";
|
|
486
|
+
const pid = record.child?.pid;
|
|
487
|
+
if (pid) {
|
|
488
|
+
try {
|
|
489
|
+
process.kill(-pid, signal);
|
|
490
|
+
}
|
|
491
|
+
catch {
|
|
492
|
+
try {
|
|
493
|
+
record.child.kill(signal);
|
|
494
|
+
}
|
|
495
|
+
catch {
|
|
496
|
+
// Process already terminated or signal rejected
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
const graceMs = options?.graceMs ?? this.terminationGraceMs;
|
|
500
|
+
record.escalationTimer = setTimeout(() => {
|
|
501
|
+
if (record.metadata.status === "stopping" ||
|
|
502
|
+
record.metadata.status === "running") {
|
|
503
|
+
try {
|
|
504
|
+
process.kill(-pid, "SIGKILL");
|
|
505
|
+
}
|
|
506
|
+
catch {
|
|
507
|
+
try {
|
|
508
|
+
record.child.kill("SIGKILL");
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
// Process already terminated or signal rejected
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}, graceMs);
|
|
516
|
+
record.escalationTimer.unref();
|
|
517
|
+
}
|
|
518
|
+
await new Promise((resolve) => {
|
|
519
|
+
if (record.metadata.status !== "running" &&
|
|
520
|
+
record.metadata.status !== "stopping") {
|
|
521
|
+
resolve();
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
const onTerm = () => resolve();
|
|
525
|
+
record.waiters.add(onTerm);
|
|
526
|
+
});
|
|
527
|
+
if (record.escalationTimer) {
|
|
528
|
+
clearTimeout(record.escalationTimer);
|
|
529
|
+
record.escalationTimer = undefined;
|
|
530
|
+
}
|
|
531
|
+
const finalStatus = record.metadata.status === "stopping"
|
|
532
|
+
? "killed"
|
|
533
|
+
: record.metadata.status;
|
|
534
|
+
return {
|
|
535
|
+
taskId,
|
|
536
|
+
status: finalStatus,
|
|
537
|
+
exitCode: record.metadata.exitCode,
|
|
538
|
+
signal: record.metadata.signal,
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Waits for a task to terminate or for the specified wait timeout to expire.
|
|
543
|
+
*
|
|
544
|
+
* @param taskId - The unique task identifier.
|
|
545
|
+
* @param options - Timeout in milliseconds and optional abort signal.
|
|
546
|
+
* @returns Snapshot metadata and whether the wait timed out.
|
|
547
|
+
* @throws Error if the task is not found or abort signal triggers.
|
|
548
|
+
*/
|
|
549
|
+
async waitForTask(taskId, options) {
|
|
550
|
+
this.assertValidTaskId(taskId);
|
|
551
|
+
this.evictExpiredTasks();
|
|
552
|
+
const record = this.tasks.get(taskId);
|
|
553
|
+
if (!record) {
|
|
554
|
+
throw new Error(`Task "${taskId}" not found.`);
|
|
555
|
+
}
|
|
556
|
+
if (record.metadata.status !== "running" &&
|
|
557
|
+
record.metadata.status !== "stopping") {
|
|
558
|
+
return {
|
|
559
|
+
task: record.metadata,
|
|
560
|
+
timedOut: false,
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
return new Promise((resolve, reject) => {
|
|
564
|
+
let timer;
|
|
565
|
+
let abortHandler;
|
|
566
|
+
const cleanup = () => {
|
|
567
|
+
if (timer)
|
|
568
|
+
clearTimeout(timer);
|
|
569
|
+
if (abortHandler && options?.signal) {
|
|
570
|
+
options.signal.removeEventListener("abort", abortHandler);
|
|
571
|
+
}
|
|
572
|
+
record.waiters.delete(onClose);
|
|
573
|
+
};
|
|
574
|
+
const onClose = (meta) => {
|
|
575
|
+
cleanup();
|
|
576
|
+
resolve({
|
|
577
|
+
task: meta,
|
|
578
|
+
timedOut: false,
|
|
579
|
+
});
|
|
580
|
+
};
|
|
581
|
+
record.waiters.add(onClose);
|
|
582
|
+
if (options?.timeoutMs && options.timeoutMs > 0) {
|
|
583
|
+
timer = setTimeout(() => {
|
|
584
|
+
cleanup();
|
|
585
|
+
resolve({
|
|
586
|
+
task: this.getTask(taskId),
|
|
587
|
+
timedOut: true,
|
|
588
|
+
});
|
|
589
|
+
}, options.timeoutMs);
|
|
590
|
+
timer.unref();
|
|
591
|
+
}
|
|
592
|
+
if (options?.signal) {
|
|
593
|
+
if (options.signal.aborted) {
|
|
594
|
+
cleanup();
|
|
595
|
+
reject(new Error(`waitForTask aborted: ${options.signal.reason ?? "Aborted by signal"}`));
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
abortHandler = () => {
|
|
599
|
+
cleanup();
|
|
600
|
+
reject(new Error(`waitForTask aborted: ${options.signal?.reason ?? "Aborted by signal"}`));
|
|
601
|
+
};
|
|
602
|
+
options.signal.addEventListener("abort", abortHandler, { once: true });
|
|
603
|
+
}
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Deletes a terminal task record and cleans up its directory and log assets.
|
|
608
|
+
*
|
|
609
|
+
* @param taskId - The unique task identifier to remove.
|
|
610
|
+
* @returns True if deleted, false if task was not found.
|
|
611
|
+
* @throws Error if the task is still running or stopping.
|
|
612
|
+
*/
|
|
613
|
+
async deleteTask(taskId) {
|
|
614
|
+
this.assertValidTaskId(taskId);
|
|
615
|
+
this.evictExpiredTasks();
|
|
616
|
+
const record = this.tasks.get(taskId);
|
|
617
|
+
if (!record) {
|
|
618
|
+
return false;
|
|
619
|
+
}
|
|
620
|
+
if (record.metadata.status === "running" ||
|
|
621
|
+
record.metadata.status === "stopping") {
|
|
622
|
+
throw new Error(`Cannot delete task "${taskId}" because it is still ${record.metadata.status}. Only terminal tasks may be deleted.`);
|
|
623
|
+
}
|
|
624
|
+
const taskDir = this.getTaskDirectory(taskId);
|
|
625
|
+
if (existsSync(taskDir)) {
|
|
626
|
+
rmSync(taskDir, { recursive: true, force: true });
|
|
627
|
+
}
|
|
628
|
+
this.tasks.delete(taskId);
|
|
629
|
+
return true;
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* Scans and loads persisted tasks from the persistent thread storage root.
|
|
633
|
+
* Any previously active task is marked as orphaned without signalling stale PIDs.
|
|
634
|
+
*/
|
|
635
|
+
loadPersistedTasks() {
|
|
636
|
+
if (!this.isPersist)
|
|
637
|
+
return;
|
|
638
|
+
const tasksBaseDir = path.join(this.rootDir, "threads", this.threadId, "tasks");
|
|
639
|
+
if (!existsSync(tasksBaseDir))
|
|
640
|
+
return;
|
|
641
|
+
try {
|
|
642
|
+
const entries = readdirSync(tasksBaseDir, { withFileTypes: true });
|
|
643
|
+
for (const entry of entries) {
|
|
644
|
+
if (!entry.isDirectory())
|
|
645
|
+
continue;
|
|
646
|
+
const taskId = entry.name;
|
|
647
|
+
if (!safeIdPattern.test(taskId))
|
|
648
|
+
continue;
|
|
649
|
+
const taskDir = path.join(tasksBaseDir, taskId);
|
|
650
|
+
const metaPath = path.join(taskDir, "meta.json");
|
|
651
|
+
if (!existsSync(metaPath))
|
|
652
|
+
continue;
|
|
653
|
+
try {
|
|
654
|
+
const raw = readFileSync(metaPath, "utf-8");
|
|
655
|
+
const parsed = JSON.parse(raw);
|
|
656
|
+
const status = parsed.status === "running" || parsed.status === "stopping"
|
|
657
|
+
? "orphaned"
|
|
658
|
+
: parsed.status;
|
|
659
|
+
const updatedMeta = {
|
|
660
|
+
...parsed,
|
|
661
|
+
status,
|
|
662
|
+
};
|
|
663
|
+
if (status === "orphaned" && parsed.status !== "orphaned") {
|
|
664
|
+
atomicWriteFile(metaPath, JSON.stringify(updatedMeta, null, 2)).catch(() => { });
|
|
665
|
+
}
|
|
666
|
+
const logPath = path.join(taskDir, "output.log");
|
|
667
|
+
this.tasks.set(taskId, {
|
|
668
|
+
metadata: updatedMeta,
|
|
669
|
+
child: undefined,
|
|
670
|
+
logPath,
|
|
671
|
+
persistedBytes: updatedMeta.outputBytes,
|
|
672
|
+
newlineCount: updatedMeta.totalLines,
|
|
673
|
+
pendingBuffer: "",
|
|
674
|
+
statusWasFailed: updatedMeta.status === "failed",
|
|
675
|
+
stdinClosed: true,
|
|
676
|
+
waiters: new Set(),
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
catch {
|
|
680
|
+
// Skip corrupt task record
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
catch {
|
|
685
|
+
// Ignore directory scan error
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* Evicts completed tasks that exceed retention TTL or capacity limits.
|
|
690
|
+
*/
|
|
691
|
+
evictExpiredTasks() {
|
|
692
|
+
const now = Date.now();
|
|
693
|
+
const terminalEntries = [];
|
|
694
|
+
for (const [id, record] of this.tasks.entries()) {
|
|
695
|
+
if (record.metadata.status !== "running" &&
|
|
696
|
+
record.metadata.status !== "stopping") {
|
|
697
|
+
terminalEntries.push([id, record]);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
for (const [id, record] of terminalEntries) {
|
|
701
|
+
const finishedAt = record.terminalTimestamp ?? record.metadata.endedAt ?? now;
|
|
702
|
+
if (now - finishedAt > this.retentionTtlMs) {
|
|
703
|
+
this.pruneTask(id, `evicted due to ${Math.round(this.retentionTtlMs / 60000)}-minute retention TTL`);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
const remaining = Array.from(this.tasks.entries())
|
|
707
|
+
.filter(([, r]) => r.metadata.status !== "running" && r.metadata.status !== "stopping")
|
|
708
|
+
.sort((a, b) => (a[1].terminalTimestamp ?? 0) - (b[1].terminalTimestamp ?? 0));
|
|
709
|
+
while (remaining.length > this.maxRetainedTasks) {
|
|
710
|
+
const [oldestId] = remaining.shift();
|
|
711
|
+
this.pruneTask(oldestId, `evicted due to task capacity limit (${this.maxRetainedTasks} tasks max)`);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* Prunes a single task from memory and cleans up on-disk assets.
|
|
716
|
+
*/
|
|
717
|
+
pruneTask(taskId, reason) {
|
|
718
|
+
const record = this.tasks.get(taskId);
|
|
719
|
+
if (!record)
|
|
720
|
+
return;
|
|
721
|
+
if (!this.isPersist) {
|
|
722
|
+
try {
|
|
723
|
+
const dir = this.getTaskDirectory(taskId);
|
|
724
|
+
if (existsSync(dir)) {
|
|
725
|
+
rmSync(dir, { recursive: true, force: true });
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
catch {
|
|
729
|
+
// Ignore directory cleanup error
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
this.tasks.delete(taskId);
|
|
733
|
+
if (this.evictedReasons.size >= 100) {
|
|
734
|
+
const oldestKey = this.evictedReasons.keys().next().value;
|
|
735
|
+
if (oldestKey) {
|
|
736
|
+
this.evictedReasons.delete(oldestKey);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
this.evictedReasons.set(taskId, reason);
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* Terminates all active running tasks and frees resources on engine shutdown.
|
|
743
|
+
*/
|
|
744
|
+
async shutdown() {
|
|
745
|
+
if (this.isDisposed)
|
|
746
|
+
return;
|
|
747
|
+
this.isDisposed = true;
|
|
748
|
+
for (const [taskId, record] of this.tasks.entries()) {
|
|
749
|
+
if (record.killTimer) {
|
|
750
|
+
clearTimeout(record.killTimer);
|
|
751
|
+
}
|
|
752
|
+
if (record.escalationTimer) {
|
|
753
|
+
clearTimeout(record.escalationTimer);
|
|
754
|
+
}
|
|
755
|
+
if (record.metadata.status === "running" ||
|
|
756
|
+
record.metadata.status === "stopping") {
|
|
757
|
+
await this.stopTask(taskId, { signal: "SIGKILL", graceMs: 500 }).catch(() => { });
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
if (!this.isPersist) {
|
|
761
|
+
try {
|
|
762
|
+
const baseTempDir = path.join(os.tmpdir(), "hernex", "tasks", this.threadId);
|
|
763
|
+
if (existsSync(baseTempDir)) {
|
|
764
|
+
rmSync(baseTempDir, { recursive: true, force: true });
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
catch {
|
|
768
|
+
// Ephemeral task directory cleanup error ignored on shutdown
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
this.tasks.clear();
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
//# sourceMappingURL=TaskManager.js.map
|