@evermore.work/adapter-utils 2026.509.0-canary.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/dist/billing.d.ts +2 -0
- package/dist/billing.d.ts.map +1 -0
- package/dist/billing.js +16 -0
- package/dist/billing.js.map +1 -0
- package/dist/billing.test.d.ts +2 -0
- package/dist/billing.test.d.ts.map +1 -0
- package/dist/billing.test.js +14 -0
- package/dist/billing.test.js.map +1 -0
- package/dist/command-managed-runtime.d.ts +45 -0
- package/dist/command-managed-runtime.d.ts.map +1 -0
- package/dist/command-managed-runtime.js +164 -0
- package/dist/command-managed-runtime.js.map +1 -0
- package/dist/command-managed-runtime.test.d.ts +2 -0
- package/dist/command-managed-runtime.test.d.ts.map +1 -0
- package/dist/command-managed-runtime.test.js +102 -0
- package/dist/command-managed-runtime.test.js.map +1 -0
- package/dist/command-redaction.d.ts +3 -0
- package/dist/command-redaction.d.ts.map +1 -0
- package/dist/command-redaction.js +17 -0
- package/dist/command-redaction.js.map +1 -0
- package/dist/execution-target-sandbox.test.d.ts +2 -0
- package/dist/execution-target-sandbox.test.d.ts.map +1 -0
- package/dist/execution-target-sandbox.test.js +392 -0
- package/dist/execution-target-sandbox.test.js.map +1 -0
- package/dist/execution-target.d.ts +150 -0
- package/dist/execution-target.d.ts.map +1 -0
- package/dist/execution-target.js +791 -0
- package/dist/execution-target.js.map +1 -0
- package/dist/execution-target.test.d.ts +2 -0
- package/dist/execution-target.test.d.ts.map +1 -0
- package/dist/execution-target.test.js +314 -0
- package/dist/execution-target.test.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/log-redaction.d.ts +9 -0
- package/dist/log-redaction.d.ts.map +1 -0
- package/dist/log-redaction.js +88 -0
- package/dist/log-redaction.js.map +1 -0
- package/dist/remote-execution-env.d.ts +2 -0
- package/dist/remote-execution-env.d.ts.map +1 -0
- package/dist/remote-execution-env.js +46 -0
- package/dist/remote-execution-env.js.map +1 -0
- package/dist/remote-managed-runtime.d.ts +31 -0
- package/dist/remote-managed-runtime.d.ts.map +1 -0
- package/dist/remote-managed-runtime.js +81 -0
- package/dist/remote-managed-runtime.js.map +1 -0
- package/dist/sandbox-callback-bridge.d.ts +132 -0
- package/dist/sandbox-callback-bridge.d.ts.map +1 -0
- package/dist/sandbox-callback-bridge.js +925 -0
- package/dist/sandbox-callback-bridge.js.map +1 -0
- package/dist/sandbox-callback-bridge.test.d.ts +2 -0
- package/dist/sandbox-callback-bridge.test.d.ts.map +1 -0
- package/dist/sandbox-callback-bridge.test.js +719 -0
- package/dist/sandbox-callback-bridge.test.js.map +1 -0
- package/dist/sandbox-managed-runtime.d.ts +54 -0
- package/dist/sandbox-managed-runtime.d.ts.map +1 -0
- package/dist/sandbox-managed-runtime.js +234 -0
- package/dist/sandbox-managed-runtime.js.map +1 -0
- package/dist/sandbox-managed-runtime.test.d.ts +2 -0
- package/dist/sandbox-managed-runtime.test.d.ts.map +1 -0
- package/dist/sandbox-managed-runtime.test.js +118 -0
- package/dist/sandbox-managed-runtime.test.js.map +1 -0
- package/dist/sandbox-shell.d.ts +2 -0
- package/dist/sandbox-shell.d.ts.map +1 -0
- package/dist/sandbox-shell.js +4 -0
- package/dist/sandbox-shell.js.map +1 -0
- package/dist/server-utils.d.ts +253 -0
- package/dist/server-utils.d.ts.map +1 -0
- package/dist/server-utils.js +1522 -0
- package/dist/server-utils.js.map +1 -0
- package/dist/server-utils.test.d.ts +2 -0
- package/dist/server-utils.test.d.ts.map +1 -0
- package/dist/server-utils.test.js +685 -0
- package/dist/server-utils.test.js.map +1 -0
- package/dist/session-compaction.d.ts +25 -0
- package/dist/session-compaction.d.ts.map +1 -0
- package/dist/session-compaction.js +154 -0
- package/dist/session-compaction.js.map +1 -0
- package/dist/ssh-fixture.test.d.ts +2 -0
- package/dist/ssh-fixture.test.d.ts.map +1 -0
- package/dist/ssh-fixture.test.js +214 -0
- package/dist/ssh-fixture.test.js.map +1 -0
- package/dist/ssh.d.ts +111 -0
- package/dist/ssh.d.ts.map +1 -0
- package/dist/ssh.js +1098 -0
- package/dist/ssh.js.map +1 -0
- package/dist/types.d.ts +465 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +5 -0
- package/dist/types.js.map +1 -0
- package/package.json +41 -0
|
@@ -0,0 +1,1522 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { constants as fsConstants, promises as fs } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { sanitizeRemoteExecutionEnv } from "./remote-execution-env.js";
|
|
6
|
+
import { buildSshSpawnTarget } from "./ssh.js";
|
|
7
|
+
import { redactCommandText } from "./command-redaction.js";
|
|
8
|
+
function resolveProcessGroupId(child) {
|
|
9
|
+
if (process.platform === "win32")
|
|
10
|
+
return null;
|
|
11
|
+
return typeof child.pid === "number" && child.pid > 0 ? child.pid : null;
|
|
12
|
+
}
|
|
13
|
+
function signalRunningProcess(running, signal) {
|
|
14
|
+
if (process.platform !== "win32" && running.processGroupId && running.processGroupId > 0) {
|
|
15
|
+
try {
|
|
16
|
+
process.kill(-running.processGroupId, signal);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
// Fall back to the direct child signal if group signaling fails.
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
if (!running.child.killed) {
|
|
24
|
+
running.child.kill(signal);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export const runningProcesses = new Map();
|
|
28
|
+
export const MAX_CAPTURE_BYTES = 4 * 1024 * 1024;
|
|
29
|
+
export const MAX_EXCERPT_BYTES = 32 * 1024;
|
|
30
|
+
const TERMINAL_RESULT_SCAN_OVERLAP_CHARS = 64 * 1024;
|
|
31
|
+
const SENSITIVE_ENV_KEY = /(key|token|secret|password|passwd|authorization|cookie)/i;
|
|
32
|
+
const REDACTED_LOG_VALUE = "***REDACTED***";
|
|
33
|
+
const EVERMORE_SKILL_ROOT_RELATIVE_CANDIDATES = [
|
|
34
|
+
"../../skills",
|
|
35
|
+
"../../../../../skills",
|
|
36
|
+
];
|
|
37
|
+
const MATERIALIZED_SKILL_SENTINEL = ".evermore-materialized-skill.json";
|
|
38
|
+
const MATERIALIZED_SKILL_LOCK_OWNER = "owner.json";
|
|
39
|
+
const MATERIALIZED_SKILL_LOCK_STALE_MS = 30_000;
|
|
40
|
+
export const DEFAULT_EVERMORE_AGENT_PROMPT_TEMPLATE = [
|
|
41
|
+
"You are agent {{agent.id}} ({{agent.name}}). Continue your Evermore work.",
|
|
42
|
+
"",
|
|
43
|
+
"Execution contract:",
|
|
44
|
+
"- Start actionable work in this heartbeat; do not stop at a plan unless the issue asks for planning.",
|
|
45
|
+
"- Leave durable progress in comments, documents, or work products, then update the issue to a clear final disposition before ending the heartbeat.",
|
|
46
|
+
"- Comments, documents, screenshots, work products, and `Remaining` bullets are evidence, not valid liveness paths by themselves.",
|
|
47
|
+
"- Final disposition checklist: mark `done` when complete; use `in_review` only with a real reviewer, approval, interaction, or monitor path; use `blocked` only with first-class blockers or a named unblock owner/action; create delegated follow-up issues with blockers when another agent owns the next step; keep `in_progress` only when a live continuation path exists.",
|
|
48
|
+
"- Prefer the smallest verification that proves the change; do not default to full workspace typecheck/build/test on every heartbeat unless the task scope warrants it.",
|
|
49
|
+
"- Use child issues for parallel or long delegated work instead of polling agents, sessions, or processes.",
|
|
50
|
+
"- If woken by a human comment on a dependency-blocked issue, respond or triage the comment without treating the blocked deliverable work as unblocked.",
|
|
51
|
+
"- Create child issues directly when you know what needs to be done; use issue-thread interactions when the board/user must choose suggested tasks, answer structured questions, or confirm a proposal.",
|
|
52
|
+
"- To ask for that input, create an interaction on the current issue with POST /api/issues/{issueId}/interactions using kind suggest_tasks, ask_user_questions, or request_confirmation. Use continuationPolicy wake_assignee when you need to resume after a response; for request_confirmation this resumes only after acceptance.",
|
|
53
|
+
"- When you intentionally restart follow-up work on a completed assigned issue, include structured `resume: true` with the POST /api/issues/{issueId}/comments or PATCH /api/issues/{issueId} comment payload. Generic agent comments on closed issues are inert by default.",
|
|
54
|
+
"- For plan approval, update the plan document first, then create request_confirmation targeting the latest plan revision with idempotencyKey confirmation:{issueId}:plan:{revisionId}. Wait for acceptance before creating implementation subtasks, and create a fresh confirmation after superseding board/user comments if approval is still needed.",
|
|
55
|
+
"- If blocked, mark the issue blocked and name the unblock owner and action.",
|
|
56
|
+
"- Respect budget, pause/cancel, approval gates, and company boundaries.",
|
|
57
|
+
].join("\n");
|
|
58
|
+
function normalizePathSlashes(value) {
|
|
59
|
+
return value.replaceAll("\\", "/");
|
|
60
|
+
}
|
|
61
|
+
function isMaintainerOnlySkillTarget(candidate) {
|
|
62
|
+
return normalizePathSlashes(candidate).includes("/.agents/skills/");
|
|
63
|
+
}
|
|
64
|
+
function skillLocationLabel(value) {
|
|
65
|
+
if (typeof value !== "string")
|
|
66
|
+
return null;
|
|
67
|
+
const trimmed = value.trim();
|
|
68
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
69
|
+
}
|
|
70
|
+
function buildManagedSkillOrigin(entry) {
|
|
71
|
+
if (entry.required) {
|
|
72
|
+
return {
|
|
73
|
+
origin: "evermore_required",
|
|
74
|
+
originLabel: "Required by Evermore",
|
|
75
|
+
readOnly: false,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
origin: "company_managed",
|
|
80
|
+
originLabel: "Managed by Evermore",
|
|
81
|
+
readOnly: false,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function resolveInstalledEntryTarget(skillsHome, entryName, dirent, linkedPath) {
|
|
85
|
+
const fullPath = path.join(skillsHome, entryName);
|
|
86
|
+
if (dirent.isSymbolicLink()) {
|
|
87
|
+
return {
|
|
88
|
+
targetPath: linkedPath ? path.resolve(path.dirname(fullPath), linkedPath) : null,
|
|
89
|
+
kind: "symlink",
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
if (dirent.isDirectory()) {
|
|
93
|
+
return { targetPath: fullPath, kind: "directory" };
|
|
94
|
+
}
|
|
95
|
+
return { targetPath: fullPath, kind: "file" };
|
|
96
|
+
}
|
|
97
|
+
export function parseObject(value) {
|
|
98
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
99
|
+
return {};
|
|
100
|
+
}
|
|
101
|
+
return value;
|
|
102
|
+
}
|
|
103
|
+
export function asString(value, fallback) {
|
|
104
|
+
return typeof value === "string" && value.length > 0 ? value : fallback;
|
|
105
|
+
}
|
|
106
|
+
export function asNumber(value, fallback) {
|
|
107
|
+
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
108
|
+
}
|
|
109
|
+
export function asBoolean(value, fallback) {
|
|
110
|
+
return typeof value === "boolean" ? value : fallback;
|
|
111
|
+
}
|
|
112
|
+
export function asStringArray(value) {
|
|
113
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
114
|
+
}
|
|
115
|
+
export function parseJson(value) {
|
|
116
|
+
try {
|
|
117
|
+
return JSON.parse(value);
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
export function appendWithCap(prev, chunk, cap = MAX_CAPTURE_BYTES) {
|
|
124
|
+
const combined = prev + chunk;
|
|
125
|
+
return combined.length > cap ? combined.slice(combined.length - cap) : combined;
|
|
126
|
+
}
|
|
127
|
+
export function appendWithByteCap(prev, chunk, cap = MAX_CAPTURE_BYTES) {
|
|
128
|
+
const combined = prev + chunk;
|
|
129
|
+
const bytes = Buffer.byteLength(combined, "utf8");
|
|
130
|
+
if (bytes <= cap)
|
|
131
|
+
return combined;
|
|
132
|
+
const buffer = Buffer.from(combined, "utf8");
|
|
133
|
+
let start = Math.max(0, bytes - cap);
|
|
134
|
+
while (start < buffer.length && (buffer[start] & 0xc0) === 0x80)
|
|
135
|
+
start += 1;
|
|
136
|
+
return buffer.subarray(start).toString("utf8");
|
|
137
|
+
}
|
|
138
|
+
function resumeReadable(readable) {
|
|
139
|
+
if (!readable || readable.destroyed)
|
|
140
|
+
return;
|
|
141
|
+
readable.resume();
|
|
142
|
+
}
|
|
143
|
+
export function resolvePathValue(obj, dottedPath) {
|
|
144
|
+
const parts = dottedPath.split(".");
|
|
145
|
+
let cursor = obj;
|
|
146
|
+
for (const part of parts) {
|
|
147
|
+
if (typeof cursor !== "object" || cursor === null || Array.isArray(cursor)) {
|
|
148
|
+
return "";
|
|
149
|
+
}
|
|
150
|
+
cursor = cursor[part];
|
|
151
|
+
}
|
|
152
|
+
if (cursor === null || cursor === undefined)
|
|
153
|
+
return "";
|
|
154
|
+
if (typeof cursor === "string")
|
|
155
|
+
return cursor;
|
|
156
|
+
if (typeof cursor === "number" || typeof cursor === "boolean")
|
|
157
|
+
return String(cursor);
|
|
158
|
+
try {
|
|
159
|
+
return JSON.stringify(cursor);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return "";
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
export function renderTemplate(template, data) {
|
|
166
|
+
return template.replace(/{{\s*([a-zA-Z0-9_.-]+)\s*}}/g, (_, path) => resolvePathValue(data, path));
|
|
167
|
+
}
|
|
168
|
+
export function joinPromptSections(sections, separator = "\n\n") {
|
|
169
|
+
return sections
|
|
170
|
+
.map((value) => (typeof value === "string" ? value.trim() : ""))
|
|
171
|
+
.filter(Boolean)
|
|
172
|
+
.join(separator);
|
|
173
|
+
}
|
|
174
|
+
function normalizeEvermoreWakeIssue(value) {
|
|
175
|
+
const issue = parseObject(value);
|
|
176
|
+
const id = asString(issue.id, "").trim() || null;
|
|
177
|
+
const identifier = asString(issue.identifier, "").trim() || null;
|
|
178
|
+
const title = asString(issue.title, "").trim() || null;
|
|
179
|
+
const status = asString(issue.status, "").trim() || null;
|
|
180
|
+
const workMode = asString(issue.workMode, "").trim() || null;
|
|
181
|
+
const priority = asString(issue.priority, "").trim() || null;
|
|
182
|
+
if (!id && !identifier && !title)
|
|
183
|
+
return null;
|
|
184
|
+
return {
|
|
185
|
+
id,
|
|
186
|
+
identifier,
|
|
187
|
+
title,
|
|
188
|
+
status,
|
|
189
|
+
workMode,
|
|
190
|
+
priority,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function normalizeEvermoreWakeComment(value) {
|
|
194
|
+
const comment = parseObject(value);
|
|
195
|
+
const author = parseObject(comment.author);
|
|
196
|
+
const body = asString(comment.body, "");
|
|
197
|
+
if (!body.trim())
|
|
198
|
+
return null;
|
|
199
|
+
return {
|
|
200
|
+
id: asString(comment.id, "").trim() || null,
|
|
201
|
+
issueId: asString(comment.issueId, "").trim() || null,
|
|
202
|
+
body,
|
|
203
|
+
bodyTruncated: asBoolean(comment.bodyTruncated, false),
|
|
204
|
+
createdAt: asString(comment.createdAt, "").trim() || null,
|
|
205
|
+
authorType: asString(author.type, "").trim() || null,
|
|
206
|
+
authorId: asString(author.id, "").trim() || null,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
function normalizeEvermoreWakeContinuationSummary(value) {
|
|
210
|
+
const summary = parseObject(value);
|
|
211
|
+
const body = asString(summary.body, "").trim();
|
|
212
|
+
if (!body)
|
|
213
|
+
return null;
|
|
214
|
+
return {
|
|
215
|
+
key: asString(summary.key, "").trim() || null,
|
|
216
|
+
title: asString(summary.title, "").trim() || null,
|
|
217
|
+
body,
|
|
218
|
+
bodyTruncated: asBoolean(summary.bodyTruncated, false),
|
|
219
|
+
updatedAt: asString(summary.updatedAt, "").trim() || null,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
function normalizeEvermoreWakeLivenessContinuation(value) {
|
|
223
|
+
const continuation = parseObject(value);
|
|
224
|
+
const attempt = asNumber(continuation.attempt, 0);
|
|
225
|
+
const maxAttempts = asNumber(continuation.maxAttempts, 0);
|
|
226
|
+
const sourceRunId = asString(continuation.sourceRunId, "").trim() || null;
|
|
227
|
+
const state = asString(continuation.state, "").trim() || null;
|
|
228
|
+
const reason = asString(continuation.reason, "").trim() || null;
|
|
229
|
+
const instruction = asString(continuation.instruction, "").trim() || null;
|
|
230
|
+
if (!attempt && !maxAttempts && !sourceRunId && !state && !reason && !instruction)
|
|
231
|
+
return null;
|
|
232
|
+
return {
|
|
233
|
+
attempt: attempt > 0 ? attempt : null,
|
|
234
|
+
maxAttempts: maxAttempts > 0 ? maxAttempts : null,
|
|
235
|
+
sourceRunId,
|
|
236
|
+
state,
|
|
237
|
+
reason,
|
|
238
|
+
instruction,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
function normalizeEvermoreWakeChildIssueSummary(value) {
|
|
242
|
+
const child = parseObject(value);
|
|
243
|
+
const id = asString(child.id, "").trim() || null;
|
|
244
|
+
const identifier = asString(child.identifier, "").trim() || null;
|
|
245
|
+
const title = asString(child.title, "").trim() || null;
|
|
246
|
+
const status = asString(child.status, "").trim() || null;
|
|
247
|
+
const priority = asString(child.priority, "").trim() || null;
|
|
248
|
+
const summary = asString(child.summary, "").trim() || null;
|
|
249
|
+
if (!id && !identifier && !title && !status && !summary)
|
|
250
|
+
return null;
|
|
251
|
+
return { id, identifier, title, status, priority, summary };
|
|
252
|
+
}
|
|
253
|
+
function normalizeEvermoreWakeBlockerSummary(value) {
|
|
254
|
+
const blocker = parseObject(value);
|
|
255
|
+
const id = asString(blocker.id, "").trim() || null;
|
|
256
|
+
const identifier = asString(blocker.identifier, "").trim() || null;
|
|
257
|
+
const title = asString(blocker.title, "").trim() || null;
|
|
258
|
+
const status = asString(blocker.status, "").trim() || null;
|
|
259
|
+
const priority = asString(blocker.priority, "").trim() || null;
|
|
260
|
+
if (!id && !identifier && !title && !status)
|
|
261
|
+
return null;
|
|
262
|
+
return { id, identifier, title, status, priority };
|
|
263
|
+
}
|
|
264
|
+
function normalizeEvermoreWakeTreeHoldSummary(value) {
|
|
265
|
+
const hold = parseObject(value);
|
|
266
|
+
const holdId = asString(hold.holdId, "").trim() || null;
|
|
267
|
+
const rootIssueId = asString(hold.rootIssueId, "").trim() || null;
|
|
268
|
+
const mode = asString(hold.mode, "").trim() || null;
|
|
269
|
+
const reason = asString(hold.reason, "").trim() || null;
|
|
270
|
+
if (!holdId && !rootIssueId && !mode && !reason)
|
|
271
|
+
return null;
|
|
272
|
+
return { holdId, rootIssueId, mode, reason };
|
|
273
|
+
}
|
|
274
|
+
function normalizeEvermoreWakeExecutionPrincipal(value) {
|
|
275
|
+
const principal = parseObject(value);
|
|
276
|
+
const typeRaw = asString(principal.type, "").trim().toLowerCase();
|
|
277
|
+
if (typeRaw !== "agent" && typeRaw !== "user")
|
|
278
|
+
return null;
|
|
279
|
+
return {
|
|
280
|
+
type: typeRaw,
|
|
281
|
+
agentId: asString(principal.agentId, "").trim() || null,
|
|
282
|
+
userId: asString(principal.userId, "").trim() || null,
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
function normalizeEvermoreWakeExecutionStage(value) {
|
|
286
|
+
const stage = parseObject(value);
|
|
287
|
+
const wakeRoleRaw = asString(stage.wakeRole, "").trim().toLowerCase();
|
|
288
|
+
const wakeRole = wakeRoleRaw === "reviewer" || wakeRoleRaw === "approver" || wakeRoleRaw === "executor"
|
|
289
|
+
? wakeRoleRaw
|
|
290
|
+
: null;
|
|
291
|
+
const allowedActions = Array.isArray(stage.allowedActions)
|
|
292
|
+
? stage.allowedActions
|
|
293
|
+
.filter((entry) => typeof entry === "string" && entry.trim().length > 0)
|
|
294
|
+
.map((entry) => entry.trim())
|
|
295
|
+
: [];
|
|
296
|
+
const currentParticipant = normalizeEvermoreWakeExecutionPrincipal(stage.currentParticipant);
|
|
297
|
+
const returnAssignee = normalizeEvermoreWakeExecutionPrincipal(stage.returnAssignee);
|
|
298
|
+
const reviewRequestRaw = parseObject(stage.reviewRequest);
|
|
299
|
+
const reviewInstructions = asString(reviewRequestRaw.instructions, "").trim();
|
|
300
|
+
const reviewRequest = reviewInstructions ? { instructions: reviewInstructions } : null;
|
|
301
|
+
const stageId = asString(stage.stageId, "").trim() || null;
|
|
302
|
+
const stageType = asString(stage.stageType, "").trim() || null;
|
|
303
|
+
const lastDecisionOutcome = asString(stage.lastDecisionOutcome, "").trim() || null;
|
|
304
|
+
if (!wakeRole && !stageId && !stageType && !currentParticipant && !returnAssignee && !reviewRequest && !lastDecisionOutcome && allowedActions.length === 0) {
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
return {
|
|
308
|
+
wakeRole,
|
|
309
|
+
stageId,
|
|
310
|
+
stageType,
|
|
311
|
+
currentParticipant,
|
|
312
|
+
returnAssignee,
|
|
313
|
+
reviewRequest,
|
|
314
|
+
lastDecisionOutcome,
|
|
315
|
+
allowedActions,
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
export function normalizeEvermoreWakePayload(value) {
|
|
319
|
+
const payload = parseObject(value);
|
|
320
|
+
const comments = Array.isArray(payload.comments)
|
|
321
|
+
? payload.comments
|
|
322
|
+
.map((entry) => normalizeEvermoreWakeComment(entry))
|
|
323
|
+
.filter((entry) => Boolean(entry))
|
|
324
|
+
: [];
|
|
325
|
+
const commentWindow = parseObject(payload.commentWindow);
|
|
326
|
+
const commentIds = Array.isArray(payload.commentIds)
|
|
327
|
+
? payload.commentIds
|
|
328
|
+
.filter((entry) => typeof entry === "string" && entry.trim().length > 0)
|
|
329
|
+
.map((entry) => entry.trim())
|
|
330
|
+
: [];
|
|
331
|
+
const executionStage = normalizeEvermoreWakeExecutionStage(payload.executionStage);
|
|
332
|
+
const continuationSummary = normalizeEvermoreWakeContinuationSummary(payload.continuationSummary);
|
|
333
|
+
const livenessContinuation = normalizeEvermoreWakeLivenessContinuation(payload.livenessContinuation);
|
|
334
|
+
const childIssueSummaries = Array.isArray(payload.childIssueSummaries)
|
|
335
|
+
? payload.childIssueSummaries
|
|
336
|
+
.map((entry) => normalizeEvermoreWakeChildIssueSummary(entry))
|
|
337
|
+
.filter((entry) => Boolean(entry))
|
|
338
|
+
: [];
|
|
339
|
+
const unresolvedBlockerIssueIds = Array.isArray(payload.unresolvedBlockerIssueIds)
|
|
340
|
+
? payload.unresolvedBlockerIssueIds
|
|
341
|
+
.map((entry) => asString(entry, "").trim())
|
|
342
|
+
.filter(Boolean)
|
|
343
|
+
: [];
|
|
344
|
+
const unresolvedBlockerSummaries = Array.isArray(payload.unresolvedBlockerSummaries)
|
|
345
|
+
? payload.unresolvedBlockerSummaries
|
|
346
|
+
.map((entry) => normalizeEvermoreWakeBlockerSummary(entry))
|
|
347
|
+
.filter((entry) => Boolean(entry))
|
|
348
|
+
: [];
|
|
349
|
+
const activeTreeHold = normalizeEvermoreWakeTreeHoldSummary(payload.activeTreeHold);
|
|
350
|
+
if (comments.length === 0 && commentIds.length === 0 && childIssueSummaries.length === 0 && unresolvedBlockerIssueIds.length === 0 && unresolvedBlockerSummaries.length === 0 && !activeTreeHold && !executionStage && !continuationSummary && !livenessContinuation && !normalizeEvermoreWakeIssue(payload.issue)) {
|
|
351
|
+
return null;
|
|
352
|
+
}
|
|
353
|
+
return {
|
|
354
|
+
reason: asString(payload.reason, "").trim() || null,
|
|
355
|
+
issue: normalizeEvermoreWakeIssue(payload.issue),
|
|
356
|
+
checkedOutByHarness: asBoolean(payload.checkedOutByHarness, false),
|
|
357
|
+
dependencyBlockedInteraction: asBoolean(payload.dependencyBlockedInteraction, false),
|
|
358
|
+
treeHoldInteraction: asBoolean(payload.treeHoldInteraction, false),
|
|
359
|
+
activeTreeHold,
|
|
360
|
+
unresolvedBlockerIssueIds,
|
|
361
|
+
unresolvedBlockerSummaries,
|
|
362
|
+
executionStage,
|
|
363
|
+
continuationSummary,
|
|
364
|
+
livenessContinuation,
|
|
365
|
+
interactionKind: asString(payload.interactionKind, "").trim() || null,
|
|
366
|
+
interactionStatus: asString(payload.interactionStatus, "").trim() || null,
|
|
367
|
+
childIssueSummaries,
|
|
368
|
+
childIssueSummaryTruncated: asBoolean(payload.childIssueSummaryTruncated, false),
|
|
369
|
+
commentIds,
|
|
370
|
+
latestCommentId: asString(payload.latestCommentId, "").trim() || null,
|
|
371
|
+
comments,
|
|
372
|
+
requestedCount: asNumber(commentWindow.requestedCount, comments.length || commentIds.length),
|
|
373
|
+
includedCount: asNumber(commentWindow.includedCount, comments.length),
|
|
374
|
+
missingCount: asNumber(commentWindow.missingCount, 0),
|
|
375
|
+
truncated: asBoolean(payload.truncated, false),
|
|
376
|
+
fallbackFetchNeeded: asBoolean(payload.fallbackFetchNeeded, false),
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
export function stringifyEvermoreWakePayload(value) {
|
|
380
|
+
const normalized = normalizeEvermoreWakePayload(value);
|
|
381
|
+
if (!normalized)
|
|
382
|
+
return null;
|
|
383
|
+
return JSON.stringify(normalized);
|
|
384
|
+
}
|
|
385
|
+
export function readEvermoreIssueWorkModeFromContext(value) {
|
|
386
|
+
const context = parseObject(value);
|
|
387
|
+
const issue = parseObject(context.evermoreIssue);
|
|
388
|
+
const direct = asString(issue.workMode, "").trim();
|
|
389
|
+
if (direct)
|
|
390
|
+
return direct;
|
|
391
|
+
const wake = normalizeEvermoreWakePayload(context.evermoreWake);
|
|
392
|
+
return wake?.issue?.workMode ?? null;
|
|
393
|
+
}
|
|
394
|
+
export function renderEvermoreWakePrompt(value, options = {}) {
|
|
395
|
+
const normalized = normalizeEvermoreWakePayload(value);
|
|
396
|
+
if (!normalized)
|
|
397
|
+
return "";
|
|
398
|
+
const resumedSession = options.resumedSession === true;
|
|
399
|
+
const executionStage = normalized.executionStage;
|
|
400
|
+
const principalLabel = (principal) => {
|
|
401
|
+
if (!principal || !principal.type)
|
|
402
|
+
return "unknown";
|
|
403
|
+
if (principal.type === "agent")
|
|
404
|
+
return principal.agentId ? `agent ${principal.agentId}` : "agent";
|
|
405
|
+
return principal.userId ? `user ${principal.userId}` : "user";
|
|
406
|
+
};
|
|
407
|
+
const lines = resumedSession
|
|
408
|
+
? [
|
|
409
|
+
"## Evermore Resume Delta",
|
|
410
|
+
"",
|
|
411
|
+
"You are resuming an existing Evermore session.",
|
|
412
|
+
"This heartbeat is scoped to the issue below. Do not switch to another issue until you have handled this wake.",
|
|
413
|
+
"Focus on the new wake delta below and continue the current task without restating the full heartbeat boilerplate.",
|
|
414
|
+
"Fetch the API thread only when `fallbackFetchNeeded` is true or you need broader history than this batch.",
|
|
415
|
+
"",
|
|
416
|
+
"Execution contract: take concrete action in this heartbeat when the issue is actionable; do not stop at a plan unless planning was requested. Leave durable progress and then give the issue a clear final disposition before ending the heartbeat: `done`, `in_review` with a real reviewer/approval/interaction path, `blocked` with first-class blockers or a named unblock owner/action, delegated follow-up issues with blockers, or `in_progress` only when a live continuation path exists. Use child issues for long or parallel delegated work instead of polling. Comments, documents, screenshots, work products, and `Remaining` bullets are evidence, not valid liveness paths by themselves.",
|
|
417
|
+
"",
|
|
418
|
+
`- reason: ${normalized.reason ?? "unknown"}`,
|
|
419
|
+
`- issue: ${normalized.issue?.identifier ?? normalized.issue?.id ?? "unknown"}${normalized.issue?.title ? ` ${normalized.issue.title}` : ""}`,
|
|
420
|
+
`- pending comments: ${normalized.includedCount}/${normalized.requestedCount}`,
|
|
421
|
+
`- latest comment id: ${normalized.latestCommentId ?? "unknown"}`,
|
|
422
|
+
`- fallback fetch needed: ${normalized.fallbackFetchNeeded ? "yes" : "no"}`,
|
|
423
|
+
]
|
|
424
|
+
: [
|
|
425
|
+
"## Evermore Wake Payload",
|
|
426
|
+
"",
|
|
427
|
+
"Treat this wake payload as the highest-priority change for the current heartbeat.",
|
|
428
|
+
"This heartbeat is scoped to the issue below. Do not switch to another issue until you have handled this wake.",
|
|
429
|
+
"Before generic repo exploration or boilerplate heartbeat updates, acknowledge the latest comment and explain how it changes your next action.",
|
|
430
|
+
"Use this inline wake data first before refetching the issue thread.",
|
|
431
|
+
"Only fetch the API thread when `fallbackFetchNeeded` is true or you need broader history than this batch.",
|
|
432
|
+
"",
|
|
433
|
+
"Execution contract: take concrete action in this heartbeat when the issue is actionable; do not stop at a plan unless planning was requested. Leave durable progress and then give the issue a clear final disposition before ending the heartbeat: `done`, `in_review` with a real reviewer/approval/interaction path, `blocked` with first-class blockers or a named unblock owner/action, delegated follow-up issues with blockers, or `in_progress` only when a live continuation path exists. Use child issues for long or parallel delegated work instead of polling. Comments, documents, screenshots, work products, and `Remaining` bullets are evidence, not valid liveness paths by themselves.",
|
|
434
|
+
"",
|
|
435
|
+
`- reason: ${normalized.reason ?? "unknown"}`,
|
|
436
|
+
`- issue: ${normalized.issue?.identifier ?? normalized.issue?.id ?? "unknown"}${normalized.issue?.title ? ` ${normalized.issue.title}` : ""}`,
|
|
437
|
+
`- pending comments: ${normalized.includedCount}/${normalized.requestedCount}`,
|
|
438
|
+
`- latest comment id: ${normalized.latestCommentId ?? "unknown"}`,
|
|
439
|
+
`- fallback fetch needed: ${normalized.fallbackFetchNeeded ? "yes" : "no"}`,
|
|
440
|
+
];
|
|
441
|
+
if (normalized.issue?.status) {
|
|
442
|
+
lines.push(`- issue status: ${normalized.issue.status}`);
|
|
443
|
+
}
|
|
444
|
+
if (normalized.issue?.workMode) {
|
|
445
|
+
lines.push(`- issue work mode: ${normalized.issue.workMode}`);
|
|
446
|
+
}
|
|
447
|
+
if (normalized.issue?.priority) {
|
|
448
|
+
lines.push(`- issue priority: ${normalized.issue.priority}`);
|
|
449
|
+
}
|
|
450
|
+
if (normalized.issue?.workMode === "planning") {
|
|
451
|
+
const hasWakeComments = normalized.comments.length > 0;
|
|
452
|
+
const acceptedPlanContinuation = !hasWakeComments &&
|
|
453
|
+
normalized.interactionKind === "request_confirmation" && normalized.interactionStatus === "accepted";
|
|
454
|
+
let directive = "Make the plan only. Do not write code or perform implementation work.";
|
|
455
|
+
if (hasWakeComments) {
|
|
456
|
+
directive = "Update the plan only. Do not write code or perform implementation work.";
|
|
457
|
+
}
|
|
458
|
+
if (acceptedPlanContinuation) {
|
|
459
|
+
directive = "Create child issues from the approved plan only. Do not write code or perform implementation work on the planning issue.";
|
|
460
|
+
}
|
|
461
|
+
lines.push(`- planning directive: ${directive}`);
|
|
462
|
+
if (acceptedPlanContinuation) {
|
|
463
|
+
lines.push("- accepted-plan continuation: you may create child implementation issues from the approved plan, but must not start implementation work on the planning issue itself");
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
if (normalized.checkedOutByHarness) {
|
|
467
|
+
lines.push("- checkout: already claimed by the harness for this run");
|
|
468
|
+
}
|
|
469
|
+
if (normalized.dependencyBlockedInteraction) {
|
|
470
|
+
lines.push("- dependency-blocked interaction: yes");
|
|
471
|
+
lines.push("- execution scope: respond or triage the human comment; do not treat blocker-dependent deliverable work as unblocked");
|
|
472
|
+
if (normalized.unresolvedBlockerSummaries.length > 0) {
|
|
473
|
+
const blockers = normalized.unresolvedBlockerSummaries
|
|
474
|
+
.map((blocker) => `${blocker.identifier ?? blocker.id ?? "unknown"}${blocker.title ? ` ${blocker.title}` : ""}${blocker.status ? ` (${blocker.status})` : ""}`)
|
|
475
|
+
.join("; ");
|
|
476
|
+
lines.push(`- unresolved blockers: ${blockers}`);
|
|
477
|
+
}
|
|
478
|
+
else if (normalized.unresolvedBlockerIssueIds.length > 0) {
|
|
479
|
+
lines.push(`- unresolved blocker issue ids: ${normalized.unresolvedBlockerIssueIds.join(", ")}`);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
if (normalized.treeHoldInteraction) {
|
|
483
|
+
lines.push("- tree-hold interaction: yes");
|
|
484
|
+
lines.push("- execution scope: respond or triage the human comment; the subtree remains paused until an explicit resume action");
|
|
485
|
+
if (normalized.activeTreeHold) {
|
|
486
|
+
const hold = normalized.activeTreeHold;
|
|
487
|
+
lines.push(`- active tree hold: ${hold.holdId ?? "unknown"}${hold.rootIssueId ? ` rooted at ${hold.rootIssueId}` : ""}${hold.mode ? ` (${hold.mode})` : ""}`);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
if (normalized.missingCount > 0) {
|
|
491
|
+
lines.push(`- omitted comments: ${normalized.missingCount}`);
|
|
492
|
+
}
|
|
493
|
+
if (executionStage) {
|
|
494
|
+
lines.push(`- execution wake role: ${executionStage.wakeRole ?? "unknown"}`, `- execution stage: ${executionStage.stageType ?? "unknown"}`, `- execution participant: ${principalLabel(executionStage.currentParticipant)}`, `- execution return assignee: ${principalLabel(executionStage.returnAssignee)}`, `- last decision outcome: ${executionStage.lastDecisionOutcome ?? "none"}`);
|
|
495
|
+
if (executionStage.allowedActions.length > 0) {
|
|
496
|
+
lines.push(`- allowed actions: ${executionStage.allowedActions.join(", ")}`);
|
|
497
|
+
}
|
|
498
|
+
if (executionStage.reviewRequest) {
|
|
499
|
+
lines.push("", "Review request instructions:", executionStage.reviewRequest.instructions);
|
|
500
|
+
}
|
|
501
|
+
lines.push("");
|
|
502
|
+
if (executionStage.wakeRole === "reviewer" || executionStage.wakeRole === "approver") {
|
|
503
|
+
lines.push(`You are waking as the active ${executionStage.wakeRole} for this issue.`, "Do not execute the task itself or continue executor work.", "Review the issue and choose one of the allowed actions above.", "If you request changes, the workflow routes back to the stored return assignee.", "");
|
|
504
|
+
}
|
|
505
|
+
else if (executionStage.wakeRole === "executor") {
|
|
506
|
+
lines.push("You are waking because changes were requested in the execution workflow.", "Address the requested changes on this issue and resubmit when the work is ready.", "");
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
if (normalized.continuationSummary) {
|
|
510
|
+
lines.push("", "Issue continuation summary:", normalized.continuationSummary.body);
|
|
511
|
+
if (normalized.continuationSummary.bodyTruncated) {
|
|
512
|
+
lines.push("[continuation summary truncated]");
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
if (normalized.livenessContinuation) {
|
|
516
|
+
const continuation = normalized.livenessContinuation;
|
|
517
|
+
lines.push("", "Run liveness continuation:");
|
|
518
|
+
if (continuation.attempt) {
|
|
519
|
+
lines.push(`- attempt: ${continuation.attempt}${continuation.maxAttempts ? `/${continuation.maxAttempts}` : ""}`);
|
|
520
|
+
}
|
|
521
|
+
if (continuation.sourceRunId) {
|
|
522
|
+
lines.push(`- source run: ${continuation.sourceRunId}`);
|
|
523
|
+
}
|
|
524
|
+
if (continuation.state) {
|
|
525
|
+
lines.push(`- liveness state: ${continuation.state}`);
|
|
526
|
+
}
|
|
527
|
+
if (continuation.reason) {
|
|
528
|
+
lines.push(`- reason: ${continuation.reason}`);
|
|
529
|
+
}
|
|
530
|
+
if (continuation.instruction) {
|
|
531
|
+
lines.push(`- instruction: ${continuation.instruction}`);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
if (normalized.childIssueSummaries.length > 0) {
|
|
535
|
+
lines.push("", "Direct child issue summaries:");
|
|
536
|
+
for (const child of normalized.childIssueSummaries) {
|
|
537
|
+
const label = child.identifier ?? child.id ?? "unknown";
|
|
538
|
+
lines.push(`- ${label}${child.title ? ` ${child.title}` : ""}${child.status ? ` (${child.status})` : ""}`);
|
|
539
|
+
if (child.summary) {
|
|
540
|
+
lines.push(` ${child.summary}`);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
if (normalized.childIssueSummaryTruncated) {
|
|
544
|
+
lines.push("[child issue summaries truncated]");
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
if (normalized.checkedOutByHarness) {
|
|
548
|
+
lines.push("", "The harness already checked out this issue for the current run.", "Do not call `/api/issues/{id}/checkout` again unless you intentionally switch to a different task.", "");
|
|
549
|
+
}
|
|
550
|
+
if (normalized.comments.length > 0) {
|
|
551
|
+
lines.push("New comments in order:");
|
|
552
|
+
}
|
|
553
|
+
for (const [index, comment] of normalized.comments.entries()) {
|
|
554
|
+
const authorLabel = comment.authorId
|
|
555
|
+
? `${comment.authorType ?? "unknown"} ${comment.authorId}`
|
|
556
|
+
: comment.authorType ?? "unknown";
|
|
557
|
+
lines.push(`${index + 1}. comment ${comment.id ?? "unknown"} at ${comment.createdAt ?? "unknown"} by ${authorLabel}`, comment.body);
|
|
558
|
+
if (comment.bodyTruncated) {
|
|
559
|
+
lines.push("[comment body truncated]");
|
|
560
|
+
}
|
|
561
|
+
lines.push("");
|
|
562
|
+
}
|
|
563
|
+
return lines.join("\n").trim();
|
|
564
|
+
}
|
|
565
|
+
export function redactEnvForLogs(env) {
|
|
566
|
+
const redacted = {};
|
|
567
|
+
for (const [key, value] of Object.entries(env)) {
|
|
568
|
+
redacted[key] = SENSITIVE_ENV_KEY.test(key) ? REDACTED_LOG_VALUE : value;
|
|
569
|
+
}
|
|
570
|
+
return redacted;
|
|
571
|
+
}
|
|
572
|
+
export function redactCommandTextForLogs(command) {
|
|
573
|
+
return redactCommandText(command, REDACTED_LOG_VALUE);
|
|
574
|
+
}
|
|
575
|
+
export function buildInvocationEnvForLogs(env, options = {}) {
|
|
576
|
+
const merged = { ...env };
|
|
577
|
+
const runtimeEnv = options.runtimeEnv ?? {};
|
|
578
|
+
for (const key of options.includeRuntimeKeys ?? []) {
|
|
579
|
+
if (key in merged)
|
|
580
|
+
continue;
|
|
581
|
+
const value = runtimeEnv[key];
|
|
582
|
+
if (typeof value !== "string" || value.length === 0)
|
|
583
|
+
continue;
|
|
584
|
+
merged[key] = value;
|
|
585
|
+
}
|
|
586
|
+
const resolvedCommand = options.resolvedCommand?.trim();
|
|
587
|
+
if (resolvedCommand) {
|
|
588
|
+
merged[options.resolvedCommandEnvKey ?? "EVERMORE_RESOLVED_COMMAND"] = redactCommandTextForLogs(resolvedCommand);
|
|
589
|
+
}
|
|
590
|
+
return redactEnvForLogs(merged);
|
|
591
|
+
}
|
|
592
|
+
export function buildEvermoreEnv(agent) {
|
|
593
|
+
const resolveHostForUrl = (rawHost) => {
|
|
594
|
+
const host = rawHost.trim();
|
|
595
|
+
if (!host || host === "0.0.0.0" || host === "::")
|
|
596
|
+
return "localhost";
|
|
597
|
+
if (host.includes(":") && !host.startsWith("[") && !host.endsWith("]"))
|
|
598
|
+
return `[${host}]`;
|
|
599
|
+
return host;
|
|
600
|
+
};
|
|
601
|
+
const vars = {
|
|
602
|
+
EVERMORE_AGENT_ID: agent.id,
|
|
603
|
+
EVERMORE_COMPANY_ID: agent.companyId,
|
|
604
|
+
};
|
|
605
|
+
const runtimeHost = resolveHostForUrl(process.env.EVERMORE_LISTEN_HOST ?? process.env.HOST ?? "localhost");
|
|
606
|
+
const runtimePort = process.env.EVERMORE_LISTEN_PORT ?? process.env.PORT ?? "3100";
|
|
607
|
+
const apiUrl = process.env.EVERMORE_RUNTIME_API_URL ??
|
|
608
|
+
process.env.EVERMORE_API_URL ??
|
|
609
|
+
`http://${runtimeHost}:${runtimePort}`;
|
|
610
|
+
vars.EVERMORE_API_URL = apiUrl;
|
|
611
|
+
return vars;
|
|
612
|
+
}
|
|
613
|
+
export function applyEvermoreWorkspaceEnv(env, input) {
|
|
614
|
+
const mappings = [
|
|
615
|
+
["EVERMORE_WORKSPACE_CWD", input.workspaceCwd],
|
|
616
|
+
["EVERMORE_WORKSPACE_SOURCE", input.workspaceSource],
|
|
617
|
+
["EVERMORE_WORKSPACE_STRATEGY", input.workspaceStrategy],
|
|
618
|
+
["EVERMORE_WORKSPACE_ID", input.workspaceId],
|
|
619
|
+
["EVERMORE_WORKSPACE_REPO_URL", input.workspaceRepoUrl],
|
|
620
|
+
["EVERMORE_WORKSPACE_REPO_REF", input.workspaceRepoRef],
|
|
621
|
+
["EVERMORE_WORKSPACE_BRANCH", input.workspaceBranch],
|
|
622
|
+
["EVERMORE_WORKSPACE_WORKTREE_PATH", input.workspaceWorktreePath],
|
|
623
|
+
["AGENT_HOME", input.agentHome],
|
|
624
|
+
];
|
|
625
|
+
for (const [key, value] of mappings) {
|
|
626
|
+
if (typeof value === "string" && value.length > 0) {
|
|
627
|
+
env[key] = value;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
return env;
|
|
631
|
+
}
|
|
632
|
+
export function shapeEvermoreWorkspaceEnvForExecution(input) {
|
|
633
|
+
const workspaceCwd = typeof input.workspaceCwd === "string" && input.workspaceCwd.trim().length > 0
|
|
634
|
+
? input.workspaceCwd.trim()
|
|
635
|
+
: null;
|
|
636
|
+
const workspaceWorktreePath = typeof input.workspaceWorktreePath === "string" && input.workspaceWorktreePath.trim().length > 0
|
|
637
|
+
? input.workspaceWorktreePath.trim()
|
|
638
|
+
: null;
|
|
639
|
+
const workspaceHints = Array.isArray(input.workspaceHints) ? input.workspaceHints : [];
|
|
640
|
+
if (!input.executionTargetIsRemote) {
|
|
641
|
+
return {
|
|
642
|
+
workspaceCwd,
|
|
643
|
+
workspaceWorktreePath,
|
|
644
|
+
workspaceHints,
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
const executionCwd = typeof input.executionCwd === "string" && input.executionCwd.trim().length > 0
|
|
648
|
+
? input.executionCwd.trim()
|
|
649
|
+
: null;
|
|
650
|
+
// On a remote target we must never fall back to the local workspaceCwd —
|
|
651
|
+
// doing so leaks host paths into the remote env (the exact failure mode
|
|
652
|
+
// this helper exists to prevent). Callers are expected to resolve
|
|
653
|
+
// executionCwd via adapterExecutionTargetRemoteCwd before calling this
|
|
654
|
+
// helper, which always returns a non-empty string. Surface a warning so
|
|
655
|
+
// future callers don't silently regress to the leak.
|
|
656
|
+
if (executionCwd === null) {
|
|
657
|
+
// eslint-disable-next-line no-console
|
|
658
|
+
console.warn("[evermore] shapeEvermoreWorkspaceEnvForExecution called with executionCwd=null on a remote target; " +
|
|
659
|
+
"stripping workspaceCwd to avoid leaking local paths into the remote environment.");
|
|
660
|
+
}
|
|
661
|
+
const realizedWorkspaceCwd = executionCwd;
|
|
662
|
+
const localWorkspaceCwd = workspaceCwd ? path.resolve(workspaceCwd) : null;
|
|
663
|
+
const shapedWorkspaceHints = workspaceHints.map((hint) => {
|
|
664
|
+
const nextHint = { ...hint };
|
|
665
|
+
const hintCwd = typeof nextHint.cwd === "string" ? nextHint.cwd.trim() : "";
|
|
666
|
+
if (!hintCwd)
|
|
667
|
+
return nextHint;
|
|
668
|
+
if (localWorkspaceCwd && path.resolve(hintCwd) === localWorkspaceCwd) {
|
|
669
|
+
if (realizedWorkspaceCwd) {
|
|
670
|
+
nextHint.cwd = realizedWorkspaceCwd;
|
|
671
|
+
}
|
|
672
|
+
else {
|
|
673
|
+
delete nextHint.cwd;
|
|
674
|
+
}
|
|
675
|
+
return nextHint;
|
|
676
|
+
}
|
|
677
|
+
delete nextHint.cwd;
|
|
678
|
+
return nextHint;
|
|
679
|
+
});
|
|
680
|
+
return {
|
|
681
|
+
workspaceCwd: realizedWorkspaceCwd,
|
|
682
|
+
workspaceWorktreePath: null,
|
|
683
|
+
workspaceHints: shapedWorkspaceHints,
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
export function sanitizeInheritedEvermoreEnv(baseEnv) {
|
|
687
|
+
const env = { ...baseEnv };
|
|
688
|
+
for (const key of Object.keys(env)) {
|
|
689
|
+
if (!key.startsWith("EVERMORE_"))
|
|
690
|
+
continue;
|
|
691
|
+
if (key === "EVERMORE_RUNTIME_API_URL")
|
|
692
|
+
continue;
|
|
693
|
+
if (key === "EVERMORE_LISTEN_HOST")
|
|
694
|
+
continue;
|
|
695
|
+
if (key === "EVERMORE_LISTEN_PORT")
|
|
696
|
+
continue;
|
|
697
|
+
delete env[key];
|
|
698
|
+
}
|
|
699
|
+
return env;
|
|
700
|
+
}
|
|
701
|
+
export function defaultPathForPlatform() {
|
|
702
|
+
if (process.platform === "win32") {
|
|
703
|
+
return "C:\\Windows\\System32;C:\\Windows;C:\\Windows\\System32\\Wbem";
|
|
704
|
+
}
|
|
705
|
+
return "/usr/local/bin:/opt/homebrew/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin";
|
|
706
|
+
}
|
|
707
|
+
function windowsPathExts(env) {
|
|
708
|
+
return (env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean);
|
|
709
|
+
}
|
|
710
|
+
async function pathExists(candidate) {
|
|
711
|
+
try {
|
|
712
|
+
await fs.access(candidate, process.platform === "win32" ? fsConstants.F_OK : fsConstants.X_OK);
|
|
713
|
+
return true;
|
|
714
|
+
}
|
|
715
|
+
catch {
|
|
716
|
+
return false;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
async function resolveCommandPath(command, cwd, env) {
|
|
720
|
+
const hasPathSeparator = command.includes("/") || command.includes("\\");
|
|
721
|
+
if (hasPathSeparator) {
|
|
722
|
+
const absolute = path.isAbsolute(command) ? command : path.resolve(cwd, command);
|
|
723
|
+
return (await pathExists(absolute)) ? absolute : null;
|
|
724
|
+
}
|
|
725
|
+
const pathValue = env.PATH ?? env.Path ?? "";
|
|
726
|
+
const delimiter = process.platform === "win32" ? ";" : ":";
|
|
727
|
+
const dirs = pathValue.split(delimiter).filter(Boolean);
|
|
728
|
+
const exts = process.platform === "win32" ? windowsPathExts(env) : [""];
|
|
729
|
+
const hasExtension = process.platform === "win32" && path.extname(command).length > 0;
|
|
730
|
+
for (const dir of dirs) {
|
|
731
|
+
const candidates = process.platform === "win32"
|
|
732
|
+
? hasExtension
|
|
733
|
+
? [path.join(dir, command)]
|
|
734
|
+
: exts.map((ext) => path.join(dir, `${command}${ext}`))
|
|
735
|
+
: [path.join(dir, command)];
|
|
736
|
+
for (const candidate of candidates) {
|
|
737
|
+
if (await pathExists(candidate))
|
|
738
|
+
return candidate;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
return null;
|
|
742
|
+
}
|
|
743
|
+
export async function resolveCommandForLogs(command, cwd, env, options = {}) {
|
|
744
|
+
const remote = options.remoteExecution ?? null;
|
|
745
|
+
if (remote) {
|
|
746
|
+
return `ssh://${remote.username}@${remote.host}:${remote.port}/${remote.remoteCwd} :: ${command}`;
|
|
747
|
+
}
|
|
748
|
+
return (await resolveCommandPath(command, cwd, env)) ?? command;
|
|
749
|
+
}
|
|
750
|
+
function quoteForCmd(arg) {
|
|
751
|
+
if (!arg.length)
|
|
752
|
+
return '""';
|
|
753
|
+
const escaped = arg.replace(/"/g, '""');
|
|
754
|
+
return /[\s"&<>|^()]/.test(escaped) ? `"${escaped}"` : escaped;
|
|
755
|
+
}
|
|
756
|
+
export function sanitizeSshRemoteEnv(env, inheritedEnv = process.env) {
|
|
757
|
+
return sanitizeRemoteExecutionEnv(env, inheritedEnv);
|
|
758
|
+
}
|
|
759
|
+
function resolveWindowsCmdShell(env) {
|
|
760
|
+
const fallbackRoot = env.SystemRoot || process.env.SystemRoot || "C:\\Windows";
|
|
761
|
+
return path.join(fallbackRoot, "System32", "cmd.exe");
|
|
762
|
+
}
|
|
763
|
+
async function resolveSpawnTarget(command, args, cwd, env, options = {}) {
|
|
764
|
+
const remote = options.remoteExecution ?? null;
|
|
765
|
+
if (remote) {
|
|
766
|
+
const sshResolved = await resolveCommandPath("ssh", process.cwd(), env);
|
|
767
|
+
if (!sshResolved) {
|
|
768
|
+
throw new Error('Command not found in PATH: "ssh"');
|
|
769
|
+
}
|
|
770
|
+
const spawnTarget = await buildSshSpawnTarget({
|
|
771
|
+
spec: remote,
|
|
772
|
+
command,
|
|
773
|
+
args,
|
|
774
|
+
env: Object.fromEntries(Object.entries(options.remoteEnv ?? {}).filter((entry) => typeof entry[1] === "string")),
|
|
775
|
+
});
|
|
776
|
+
return {
|
|
777
|
+
command: sshResolved,
|
|
778
|
+
args: spawnTarget.args,
|
|
779
|
+
cwd: process.cwd(),
|
|
780
|
+
cleanup: spawnTarget.cleanup,
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
const resolved = await resolveCommandPath(command, cwd, env);
|
|
784
|
+
const executable = resolved ?? command;
|
|
785
|
+
if (process.platform !== "win32") {
|
|
786
|
+
return { command: executable, args };
|
|
787
|
+
}
|
|
788
|
+
if (/\.(cmd|bat)$/i.test(executable)) {
|
|
789
|
+
// Always use cmd.exe for .cmd/.bat wrappers. Some environments override
|
|
790
|
+
// ComSpec to PowerShell, which breaks cmd-specific flags like /d /s /c.
|
|
791
|
+
const shell = resolveWindowsCmdShell(env);
|
|
792
|
+
const commandLine = [quoteForCmd(executable), ...args.map(quoteForCmd)].join(" ");
|
|
793
|
+
return {
|
|
794
|
+
command: shell,
|
|
795
|
+
args: ["/d", "/s", "/c", commandLine],
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
return { command: executable, args };
|
|
799
|
+
}
|
|
800
|
+
export function ensurePathInEnv(env) {
|
|
801
|
+
if (typeof env.PATH === "string" && env.PATH.length > 0)
|
|
802
|
+
return env;
|
|
803
|
+
if (typeof env.Path === "string" && env.Path.length > 0)
|
|
804
|
+
return env;
|
|
805
|
+
return { ...env, PATH: defaultPathForPlatform() };
|
|
806
|
+
}
|
|
807
|
+
export async function ensureAbsoluteDirectory(cwd, opts = {}) {
|
|
808
|
+
if (!path.isAbsolute(cwd)) {
|
|
809
|
+
throw new Error(`Working directory must be an absolute path: "${cwd}"`);
|
|
810
|
+
}
|
|
811
|
+
const assertDirectory = async () => {
|
|
812
|
+
const stats = await fs.stat(cwd);
|
|
813
|
+
if (!stats.isDirectory()) {
|
|
814
|
+
throw new Error(`Working directory is not a directory: "${cwd}"`);
|
|
815
|
+
}
|
|
816
|
+
};
|
|
817
|
+
try {
|
|
818
|
+
await assertDirectory();
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
catch (err) {
|
|
822
|
+
const code = err.code;
|
|
823
|
+
if (!opts.createIfMissing || code !== "ENOENT") {
|
|
824
|
+
if (code === "ENOENT") {
|
|
825
|
+
throw new Error(`Working directory does not exist: "${cwd}"`);
|
|
826
|
+
}
|
|
827
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
try {
|
|
831
|
+
await fs.mkdir(cwd, { recursive: true });
|
|
832
|
+
await assertDirectory();
|
|
833
|
+
}
|
|
834
|
+
catch (err) {
|
|
835
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
836
|
+
throw new Error(`Could not create working directory "${cwd}": ${reason}`);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
export async function resolveEvermoreSkillsDir(moduleDir, additionalCandidates = []) {
|
|
840
|
+
const candidates = [
|
|
841
|
+
...EVERMORE_SKILL_ROOT_RELATIVE_CANDIDATES.map((relativePath) => path.resolve(moduleDir, relativePath)),
|
|
842
|
+
...additionalCandidates.map((candidate) => path.resolve(candidate)),
|
|
843
|
+
];
|
|
844
|
+
const seenRoots = new Set();
|
|
845
|
+
for (const root of candidates) {
|
|
846
|
+
if (seenRoots.has(root))
|
|
847
|
+
continue;
|
|
848
|
+
seenRoots.add(root);
|
|
849
|
+
const isDirectory = await fs.stat(root).then((stats) => stats.isDirectory()).catch(() => false);
|
|
850
|
+
if (isDirectory)
|
|
851
|
+
return root;
|
|
852
|
+
}
|
|
853
|
+
return null;
|
|
854
|
+
}
|
|
855
|
+
async function readSkillRequired(skillDir) {
|
|
856
|
+
try {
|
|
857
|
+
const content = await fs.readFile(path.join(skillDir, "SKILL.md"), "utf8");
|
|
858
|
+
const normalized = content.replace(/\r\n/g, "\n");
|
|
859
|
+
if (!normalized.startsWith("---\n"))
|
|
860
|
+
return true;
|
|
861
|
+
const closing = normalized.indexOf("\n---\n", 4);
|
|
862
|
+
if (closing < 0)
|
|
863
|
+
return true;
|
|
864
|
+
const frontmatter = normalized.slice(4, closing);
|
|
865
|
+
return !/^\s*required\s*:\s*false\s*$/m.test(frontmatter);
|
|
866
|
+
}
|
|
867
|
+
catch {
|
|
868
|
+
return true;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
export async function listEvermoreSkillEntries(moduleDir, additionalCandidates = []) {
|
|
872
|
+
const root = await resolveEvermoreSkillsDir(moduleDir, additionalCandidates);
|
|
873
|
+
if (!root)
|
|
874
|
+
return [];
|
|
875
|
+
try {
|
|
876
|
+
const entries = await fs.readdir(root, { withFileTypes: true });
|
|
877
|
+
const dirs = entries.filter((entry) => entry.isDirectory());
|
|
878
|
+
return Promise.all(dirs.map(async (entry) => {
|
|
879
|
+
const skillDir = path.join(root, entry.name);
|
|
880
|
+
const required = await readSkillRequired(skillDir);
|
|
881
|
+
return {
|
|
882
|
+
key: `phuctm97/evermore/${entry.name}`,
|
|
883
|
+
runtimeName: entry.name,
|
|
884
|
+
source: skillDir,
|
|
885
|
+
required,
|
|
886
|
+
requiredReason: required
|
|
887
|
+
? "Bundled Evermore skills are always available for local adapters."
|
|
888
|
+
: null,
|
|
889
|
+
};
|
|
890
|
+
}));
|
|
891
|
+
}
|
|
892
|
+
catch {
|
|
893
|
+
return [];
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
export async function readInstalledSkillTargets(skillsHome) {
|
|
897
|
+
const entries = await fs.readdir(skillsHome, { withFileTypes: true }).catch(() => []);
|
|
898
|
+
const out = new Map();
|
|
899
|
+
for (const entry of entries) {
|
|
900
|
+
const fullPath = path.join(skillsHome, entry.name);
|
|
901
|
+
const linkedPath = entry.isSymbolicLink() ? await fs.readlink(fullPath).catch(() => null) : null;
|
|
902
|
+
out.set(entry.name, resolveInstalledEntryTarget(skillsHome, entry.name, entry, linkedPath));
|
|
903
|
+
}
|
|
904
|
+
return out;
|
|
905
|
+
}
|
|
906
|
+
export function buildPersistentSkillSnapshot(options) {
|
|
907
|
+
const { adapterType, availableEntries, desiredSkills, installed, skillsHome, locationLabel, installedDetail, missingDetail, externalConflictDetail, externalDetail, } = options;
|
|
908
|
+
const availableByKey = new Map(availableEntries.map((entry) => [entry.key, entry]));
|
|
909
|
+
const desiredSet = new Set(desiredSkills);
|
|
910
|
+
const entries = [];
|
|
911
|
+
const warnings = [...(options.warnings ?? [])];
|
|
912
|
+
for (const available of availableEntries) {
|
|
913
|
+
const installedEntry = installed.get(available.runtimeName) ?? null;
|
|
914
|
+
const desired = desiredSet.has(available.key);
|
|
915
|
+
let state = "available";
|
|
916
|
+
let managed = false;
|
|
917
|
+
let detail = null;
|
|
918
|
+
if (installedEntry?.targetPath === available.source) {
|
|
919
|
+
managed = true;
|
|
920
|
+
state = desired ? "installed" : "stale";
|
|
921
|
+
detail = installedDetail ?? null;
|
|
922
|
+
}
|
|
923
|
+
else if (installedEntry) {
|
|
924
|
+
state = "external";
|
|
925
|
+
detail = desired ? externalConflictDetail : externalDetail;
|
|
926
|
+
}
|
|
927
|
+
else if (desired) {
|
|
928
|
+
state = "missing";
|
|
929
|
+
detail = missingDetail;
|
|
930
|
+
}
|
|
931
|
+
entries.push({
|
|
932
|
+
key: available.key,
|
|
933
|
+
runtimeName: available.runtimeName,
|
|
934
|
+
desired,
|
|
935
|
+
managed,
|
|
936
|
+
state,
|
|
937
|
+
sourcePath: available.source,
|
|
938
|
+
targetPath: path.join(skillsHome, available.runtimeName),
|
|
939
|
+
detail,
|
|
940
|
+
required: Boolean(available.required),
|
|
941
|
+
requiredReason: available.requiredReason ?? null,
|
|
942
|
+
...buildManagedSkillOrigin(available),
|
|
943
|
+
});
|
|
944
|
+
}
|
|
945
|
+
for (const desiredSkill of desiredSkills) {
|
|
946
|
+
if (availableByKey.has(desiredSkill))
|
|
947
|
+
continue;
|
|
948
|
+
warnings.push(`Desired skill "${desiredSkill}" is not available from the Evermore skills directory.`);
|
|
949
|
+
entries.push({
|
|
950
|
+
key: desiredSkill,
|
|
951
|
+
runtimeName: null,
|
|
952
|
+
desired: true,
|
|
953
|
+
managed: true,
|
|
954
|
+
state: "missing",
|
|
955
|
+
sourcePath: null,
|
|
956
|
+
targetPath: null,
|
|
957
|
+
detail: "Evermore cannot find this skill in the local runtime skills directory.",
|
|
958
|
+
origin: "external_unknown",
|
|
959
|
+
originLabel: "External or unavailable",
|
|
960
|
+
readOnly: false,
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
for (const [name, installedEntry] of installed.entries()) {
|
|
964
|
+
if (availableEntries.some((entry) => entry.runtimeName === name))
|
|
965
|
+
continue;
|
|
966
|
+
entries.push({
|
|
967
|
+
key: name,
|
|
968
|
+
runtimeName: name,
|
|
969
|
+
desired: false,
|
|
970
|
+
managed: false,
|
|
971
|
+
state: "external",
|
|
972
|
+
origin: "user_installed",
|
|
973
|
+
originLabel: "User-installed",
|
|
974
|
+
locationLabel: skillLocationLabel(locationLabel),
|
|
975
|
+
readOnly: true,
|
|
976
|
+
sourcePath: null,
|
|
977
|
+
targetPath: installedEntry.targetPath ?? path.join(skillsHome, name),
|
|
978
|
+
detail: externalDetail,
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
entries.sort((left, right) => left.key.localeCompare(right.key));
|
|
982
|
+
return {
|
|
983
|
+
adapterType,
|
|
984
|
+
supported: true,
|
|
985
|
+
mode: "persistent",
|
|
986
|
+
desiredSkills,
|
|
987
|
+
entries,
|
|
988
|
+
warnings,
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
function normalizeConfiguredEvermoreRuntimeSkills(value) {
|
|
992
|
+
if (!Array.isArray(value))
|
|
993
|
+
return [];
|
|
994
|
+
const out = [];
|
|
995
|
+
for (const rawEntry of value) {
|
|
996
|
+
const entry = parseObject(rawEntry);
|
|
997
|
+
const key = asString(entry.key, asString(entry.name, "")).trim();
|
|
998
|
+
const runtimeName = asString(entry.runtimeName, asString(entry.name, "")).trim();
|
|
999
|
+
const source = asString(entry.source, "").trim();
|
|
1000
|
+
if (!key || !runtimeName || !source)
|
|
1001
|
+
continue;
|
|
1002
|
+
out.push({
|
|
1003
|
+
key,
|
|
1004
|
+
runtimeName,
|
|
1005
|
+
source,
|
|
1006
|
+
required: asBoolean(entry.required, false),
|
|
1007
|
+
requiredReason: typeof entry.requiredReason === "string" && entry.requiredReason.trim().length > 0
|
|
1008
|
+
? entry.requiredReason.trim()
|
|
1009
|
+
: null,
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
return out;
|
|
1013
|
+
}
|
|
1014
|
+
export async function readEvermoreRuntimeSkillEntries(config, moduleDir, additionalCandidates = []) {
|
|
1015
|
+
const configuredEntries = normalizeConfiguredEvermoreRuntimeSkills(config.evermoreRuntimeSkills);
|
|
1016
|
+
if (configuredEntries.length > 0)
|
|
1017
|
+
return configuredEntries;
|
|
1018
|
+
return listEvermoreSkillEntries(moduleDir, additionalCandidates);
|
|
1019
|
+
}
|
|
1020
|
+
export async function readEvermoreSkillMarkdown(moduleDir, skillKey) {
|
|
1021
|
+
const normalized = skillKey.trim().toLowerCase();
|
|
1022
|
+
if (!normalized)
|
|
1023
|
+
return null;
|
|
1024
|
+
const entries = await listEvermoreSkillEntries(moduleDir);
|
|
1025
|
+
const match = entries.find((entry) => entry.key === normalized);
|
|
1026
|
+
if (!match)
|
|
1027
|
+
return null;
|
|
1028
|
+
try {
|
|
1029
|
+
return await fs.readFile(path.join(match.source, "SKILL.md"), "utf8");
|
|
1030
|
+
}
|
|
1031
|
+
catch {
|
|
1032
|
+
return null;
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
export function readEvermoreSkillSyncPreference(config) {
|
|
1036
|
+
const raw = config.evermoreSkillSync;
|
|
1037
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
1038
|
+
return { explicit: false, desiredSkills: [] };
|
|
1039
|
+
}
|
|
1040
|
+
const syncConfig = raw;
|
|
1041
|
+
const desiredValues = syncConfig.desiredSkills;
|
|
1042
|
+
const desired = Array.isArray(desiredValues)
|
|
1043
|
+
? desiredValues
|
|
1044
|
+
.filter((value) => typeof value === "string")
|
|
1045
|
+
.map((value) => value.trim())
|
|
1046
|
+
.filter(Boolean)
|
|
1047
|
+
: [];
|
|
1048
|
+
return {
|
|
1049
|
+
explicit: Object.prototype.hasOwnProperty.call(raw, "desiredSkills"),
|
|
1050
|
+
desiredSkills: Array.from(new Set(desired)),
|
|
1051
|
+
};
|
|
1052
|
+
}
|
|
1053
|
+
function canonicalizeDesiredEvermoreSkillReference(reference, availableEntries) {
|
|
1054
|
+
const normalizedReference = reference.trim().toLowerCase();
|
|
1055
|
+
if (!normalizedReference)
|
|
1056
|
+
return "";
|
|
1057
|
+
const exactKey = availableEntries.find((entry) => entry.key.trim().toLowerCase() === normalizedReference);
|
|
1058
|
+
if (exactKey)
|
|
1059
|
+
return exactKey.key;
|
|
1060
|
+
const byRuntimeName = availableEntries.filter((entry) => typeof entry.runtimeName === "string" && entry.runtimeName.trim().toLowerCase() === normalizedReference);
|
|
1061
|
+
if (byRuntimeName.length === 1)
|
|
1062
|
+
return byRuntimeName[0].key;
|
|
1063
|
+
const slugMatches = availableEntries.filter((entry) => entry.key.trim().toLowerCase().split("/").pop() === normalizedReference);
|
|
1064
|
+
if (slugMatches.length === 1)
|
|
1065
|
+
return slugMatches[0].key;
|
|
1066
|
+
return normalizedReference;
|
|
1067
|
+
}
|
|
1068
|
+
export function resolveEvermoreDesiredSkillNames(config, availableEntries) {
|
|
1069
|
+
const preference = readEvermoreSkillSyncPreference(config);
|
|
1070
|
+
const requiredSkills = availableEntries
|
|
1071
|
+
.filter((entry) => entry.required)
|
|
1072
|
+
.map((entry) => entry.key);
|
|
1073
|
+
if (!preference.explicit) {
|
|
1074
|
+
return Array.from(new Set(requiredSkills));
|
|
1075
|
+
}
|
|
1076
|
+
const desiredSkills = preference.desiredSkills
|
|
1077
|
+
.map((reference) => canonicalizeDesiredEvermoreSkillReference(reference, availableEntries))
|
|
1078
|
+
.filter(Boolean);
|
|
1079
|
+
return Array.from(new Set([...requiredSkills, ...desiredSkills]));
|
|
1080
|
+
}
|
|
1081
|
+
export function writeEvermoreSkillSyncPreference(config, desiredSkills) {
|
|
1082
|
+
const next = { ...config };
|
|
1083
|
+
const raw = next.evermoreSkillSync;
|
|
1084
|
+
const current = typeof raw === "object" && raw !== null && !Array.isArray(raw)
|
|
1085
|
+
? { ...raw }
|
|
1086
|
+
: {};
|
|
1087
|
+
current.desiredSkills = Array.from(new Set(desiredSkills
|
|
1088
|
+
.map((value) => value.trim())
|
|
1089
|
+
.filter(Boolean)));
|
|
1090
|
+
next.evermoreSkillSync = current;
|
|
1091
|
+
return next;
|
|
1092
|
+
}
|
|
1093
|
+
export async function ensureEvermoreSkillSymlink(source, target, linkSkill = (linkSource, linkTarget) => fs.symlink(linkSource, linkTarget)) {
|
|
1094
|
+
const existing = await fs.lstat(target).catch(() => null);
|
|
1095
|
+
if (!existing) {
|
|
1096
|
+
await linkSkill(source, target);
|
|
1097
|
+
return "created";
|
|
1098
|
+
}
|
|
1099
|
+
if (!existing.isSymbolicLink()) {
|
|
1100
|
+
return "skipped";
|
|
1101
|
+
}
|
|
1102
|
+
const linkedPath = await fs.readlink(target).catch(() => null);
|
|
1103
|
+
if (!linkedPath)
|
|
1104
|
+
return "skipped";
|
|
1105
|
+
const resolvedLinkedPath = path.resolve(path.dirname(target), linkedPath);
|
|
1106
|
+
if (resolvedLinkedPath === source) {
|
|
1107
|
+
return "skipped";
|
|
1108
|
+
}
|
|
1109
|
+
const linkedPathExists = await fs.stat(resolvedLinkedPath).then(() => true).catch(() => false);
|
|
1110
|
+
if (linkedPathExists) {
|
|
1111
|
+
return "skipped";
|
|
1112
|
+
}
|
|
1113
|
+
await fs.unlink(target);
|
|
1114
|
+
await linkSkill(source, target);
|
|
1115
|
+
return "repaired";
|
|
1116
|
+
}
|
|
1117
|
+
async function hashSkillDirectory(root) {
|
|
1118
|
+
const hash = createHash("sha256");
|
|
1119
|
+
async function visit(candidate, relativePath) {
|
|
1120
|
+
const stat = await fs.lstat(candidate);
|
|
1121
|
+
if (stat.isSymbolicLink()) {
|
|
1122
|
+
hash.update(`symlink:${relativePath}\n`);
|
|
1123
|
+
return;
|
|
1124
|
+
}
|
|
1125
|
+
if (stat.isDirectory()) {
|
|
1126
|
+
hash.update(`dir:${relativePath}\n`);
|
|
1127
|
+
const entries = await fs.readdir(candidate, { withFileTypes: true });
|
|
1128
|
+
entries.sort((left, right) => left.name.localeCompare(right.name));
|
|
1129
|
+
for (const entry of entries) {
|
|
1130
|
+
const childRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
|
|
1131
|
+
await visit(path.join(candidate, entry.name), childRelativePath);
|
|
1132
|
+
}
|
|
1133
|
+
return;
|
|
1134
|
+
}
|
|
1135
|
+
if (stat.isFile()) {
|
|
1136
|
+
hash.update(`file:${relativePath}:${stat.mode}\n`);
|
|
1137
|
+
hash.update(await fs.readFile(candidate));
|
|
1138
|
+
hash.update("\n");
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
hash.update(`other:${relativePath}:${stat.mode}\n`);
|
|
1142
|
+
}
|
|
1143
|
+
await visit(root, "");
|
|
1144
|
+
return hash.digest("hex");
|
|
1145
|
+
}
|
|
1146
|
+
async function materializedSkillFingerprintMatches(targetRoot, sourceFingerprint) {
|
|
1147
|
+
try {
|
|
1148
|
+
const raw = JSON.parse(await fs.readFile(path.join(targetRoot, MATERIALIZED_SKILL_SENTINEL), "utf8"));
|
|
1149
|
+
const parsed = parseObject(raw);
|
|
1150
|
+
return parsed.version === 1 && parsed.sourceFingerprint === sourceFingerprint;
|
|
1151
|
+
}
|
|
1152
|
+
catch {
|
|
1153
|
+
return false;
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
async function acquireMaterializeLock(lockDir) {
|
|
1157
|
+
await fs.mkdir(path.dirname(lockDir), { recursive: true });
|
|
1158
|
+
const deadline = Date.now() + MATERIALIZED_SKILL_LOCK_STALE_MS;
|
|
1159
|
+
while (true) {
|
|
1160
|
+
try {
|
|
1161
|
+
await fs.mkdir(lockDir);
|
|
1162
|
+
await fs.writeFile(path.join(lockDir, MATERIALIZED_SKILL_LOCK_OWNER), `${JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() })}\n`, "utf8");
|
|
1163
|
+
return async () => {
|
|
1164
|
+
await fs.rm(lockDir, { recursive: true, force: true });
|
|
1165
|
+
};
|
|
1166
|
+
}
|
|
1167
|
+
catch (err) {
|
|
1168
|
+
const code = err && typeof err === "object" ? err.code : null;
|
|
1169
|
+
if (code !== "EEXIST")
|
|
1170
|
+
throw err;
|
|
1171
|
+
if (await removeStaleMaterializeLock(lockDir, MATERIALIZED_SKILL_LOCK_STALE_MS))
|
|
1172
|
+
continue;
|
|
1173
|
+
if (Date.now() >= deadline) {
|
|
1174
|
+
throw new Error(`Timed out waiting for Evermore skill materialization lock at ${lockDir}`);
|
|
1175
|
+
}
|
|
1176
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
function isPidAlive(pid) {
|
|
1181
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
1182
|
+
return false;
|
|
1183
|
+
try {
|
|
1184
|
+
process.kill(pid, 0);
|
|
1185
|
+
return true;
|
|
1186
|
+
}
|
|
1187
|
+
catch (err) {
|
|
1188
|
+
const code = err && typeof err === "object" ? err.code : null;
|
|
1189
|
+
return code === "EPERM";
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
async function removeStaleMaterializeLock(lockDir, staleMs) {
|
|
1193
|
+
const ownerPath = path.join(lockDir, MATERIALIZED_SKILL_LOCK_OWNER);
|
|
1194
|
+
let shouldRemove = false;
|
|
1195
|
+
try {
|
|
1196
|
+
const raw = JSON.parse(await fs.readFile(ownerPath, "utf8"));
|
|
1197
|
+
const owner = parseObject(raw);
|
|
1198
|
+
const pid = typeof owner.pid === "number" ? owner.pid : 0;
|
|
1199
|
+
const createdAt = typeof owner.createdAt === "string" ? Date.parse(owner.createdAt) : Number.NaN;
|
|
1200
|
+
const ageMs = Number.isFinite(createdAt) ? Date.now() - createdAt : staleMs + 1;
|
|
1201
|
+
shouldRemove = !isPidAlive(pid) || ageMs > staleMs;
|
|
1202
|
+
}
|
|
1203
|
+
catch {
|
|
1204
|
+
const stat = await fs.stat(lockDir).catch(() => null);
|
|
1205
|
+
shouldRemove = !stat || Date.now() - stat.mtimeMs > staleMs;
|
|
1206
|
+
}
|
|
1207
|
+
if (!shouldRemove)
|
|
1208
|
+
return false;
|
|
1209
|
+
await fs.rm(lockDir, { recursive: true, force: true }).catch(() => { });
|
|
1210
|
+
return true;
|
|
1211
|
+
}
|
|
1212
|
+
export async function materializeEvermoreSkillCopy(source, target) {
|
|
1213
|
+
const sourceRoot = path.resolve(source);
|
|
1214
|
+
const targetRoot = path.resolve(target);
|
|
1215
|
+
const relativeTarget = path.relative(sourceRoot, targetRoot);
|
|
1216
|
+
const relativeSource = path.relative(targetRoot, sourceRoot);
|
|
1217
|
+
if (!relativeTarget ||
|
|
1218
|
+
(!relativeTarget.startsWith("..") && !path.isAbsolute(relativeTarget)) ||
|
|
1219
|
+
!relativeSource ||
|
|
1220
|
+
(!relativeSource.startsWith("..") && !path.isAbsolute(relativeSource))) {
|
|
1221
|
+
throw new Error("Refusing to materialize a skill into itself, an ancestor, or one of its descendants.");
|
|
1222
|
+
}
|
|
1223
|
+
const rootStat = await fs.lstat(sourceRoot);
|
|
1224
|
+
if (rootStat.isSymbolicLink()) {
|
|
1225
|
+
throw new Error("Refusing to materialize a skill root that is itself a symlink.");
|
|
1226
|
+
}
|
|
1227
|
+
if (!rootStat.isDirectory()) {
|
|
1228
|
+
throw new Error("Evermore skills must be directories.");
|
|
1229
|
+
}
|
|
1230
|
+
const result = {
|
|
1231
|
+
copiedFiles: 0,
|
|
1232
|
+
skippedSymlinks: [],
|
|
1233
|
+
};
|
|
1234
|
+
const lockDir = `${targetRoot}.lock`;
|
|
1235
|
+
const releaseLock = await acquireMaterializeLock(lockDir);
|
|
1236
|
+
const tempRoot = `${targetRoot}.tmp-${process.pid}-${randomUUID()}`;
|
|
1237
|
+
async function copyEntry(sourcePath, targetPath, relativePath) {
|
|
1238
|
+
const stat = await fs.lstat(sourcePath);
|
|
1239
|
+
if (stat.isSymbolicLink()) {
|
|
1240
|
+
result.skippedSymlinks.push(relativePath || ".");
|
|
1241
|
+
return;
|
|
1242
|
+
}
|
|
1243
|
+
if (stat.isDirectory()) {
|
|
1244
|
+
await fs.mkdir(targetPath, { recursive: true });
|
|
1245
|
+
const entries = await fs.readdir(sourcePath, { withFileTypes: true });
|
|
1246
|
+
entries.sort((left, right) => left.name.localeCompare(right.name));
|
|
1247
|
+
for (const entry of entries) {
|
|
1248
|
+
const childRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
|
|
1249
|
+
await copyEntry(path.join(sourcePath, entry.name), path.join(targetPath, entry.name), childRelativePath);
|
|
1250
|
+
}
|
|
1251
|
+
return;
|
|
1252
|
+
}
|
|
1253
|
+
if (stat.isFile()) {
|
|
1254
|
+
await fs.mkdir(path.dirname(targetPath), { recursive: true });
|
|
1255
|
+
await fs.copyFile(sourcePath, targetPath, fsConstants.COPYFILE_FICLONE).catch(async () => {
|
|
1256
|
+
await fs.copyFile(sourcePath, targetPath);
|
|
1257
|
+
});
|
|
1258
|
+
await fs.chmod(targetPath, stat.mode).catch(() => { });
|
|
1259
|
+
result.copiedFiles += 1;
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
try {
|
|
1263
|
+
const sourceFingerprint = await hashSkillDirectory(sourceRoot);
|
|
1264
|
+
if (await materializedSkillFingerprintMatches(targetRoot, sourceFingerprint))
|
|
1265
|
+
return result;
|
|
1266
|
+
await copyEntry(sourceRoot, tempRoot, "");
|
|
1267
|
+
await fs.writeFile(path.join(tempRoot, MATERIALIZED_SKILL_SENTINEL), `${JSON.stringify({
|
|
1268
|
+
version: 1,
|
|
1269
|
+
sourceFingerprint,
|
|
1270
|
+
copiedFiles: result.copiedFiles,
|
|
1271
|
+
skippedSymlinks: result.skippedSymlinks,
|
|
1272
|
+
}, null, 2)}\n`, "utf8");
|
|
1273
|
+
if (await materializedSkillFingerprintMatches(targetRoot, sourceFingerprint))
|
|
1274
|
+
return result;
|
|
1275
|
+
await fs.rm(targetRoot, { recursive: true, force: true });
|
|
1276
|
+
await fs.rename(tempRoot, targetRoot);
|
|
1277
|
+
return result;
|
|
1278
|
+
}
|
|
1279
|
+
finally {
|
|
1280
|
+
await fs.rm(tempRoot, { recursive: true, force: true }).catch(() => { });
|
|
1281
|
+
await releaseLock();
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
export async function removeMaintainerOnlySkillSymlinks(skillsHome, allowedSkillNames) {
|
|
1285
|
+
const allowed = new Set(Array.from(allowedSkillNames));
|
|
1286
|
+
try {
|
|
1287
|
+
const entries = await fs.readdir(skillsHome, { withFileTypes: true });
|
|
1288
|
+
const removed = [];
|
|
1289
|
+
for (const entry of entries) {
|
|
1290
|
+
if (allowed.has(entry.name))
|
|
1291
|
+
continue;
|
|
1292
|
+
const target = path.join(skillsHome, entry.name);
|
|
1293
|
+
const existing = await fs.lstat(target).catch(() => null);
|
|
1294
|
+
if (!existing?.isSymbolicLink())
|
|
1295
|
+
continue;
|
|
1296
|
+
const linkedPath = await fs.readlink(target).catch(() => null);
|
|
1297
|
+
if (!linkedPath)
|
|
1298
|
+
continue;
|
|
1299
|
+
const resolvedLinkedPath = path.isAbsolute(linkedPath)
|
|
1300
|
+
? linkedPath
|
|
1301
|
+
: path.resolve(path.dirname(target), linkedPath);
|
|
1302
|
+
if (!isMaintainerOnlySkillTarget(linkedPath) &&
|
|
1303
|
+
!isMaintainerOnlySkillTarget(resolvedLinkedPath)) {
|
|
1304
|
+
continue;
|
|
1305
|
+
}
|
|
1306
|
+
await fs.unlink(target);
|
|
1307
|
+
removed.push(entry.name);
|
|
1308
|
+
}
|
|
1309
|
+
return removed;
|
|
1310
|
+
}
|
|
1311
|
+
catch {
|
|
1312
|
+
return [];
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
export async function ensureCommandResolvable(command, cwd, env, options = {}) {
|
|
1316
|
+
if (options.remoteExecution) {
|
|
1317
|
+
const resolvedSsh = await resolveCommandPath("ssh", process.cwd(), env);
|
|
1318
|
+
if (resolvedSsh)
|
|
1319
|
+
return;
|
|
1320
|
+
throw new Error('Command not found in PATH: "ssh"');
|
|
1321
|
+
}
|
|
1322
|
+
const resolved = await resolveCommandPath(command, cwd, env);
|
|
1323
|
+
if (resolved)
|
|
1324
|
+
return;
|
|
1325
|
+
if (command.includes("/") || command.includes("\\")) {
|
|
1326
|
+
const absolute = path.isAbsolute(command) ? command : path.resolve(cwd, command);
|
|
1327
|
+
throw new Error(`Command is not executable: "${command}" (resolved: "${absolute}")`);
|
|
1328
|
+
}
|
|
1329
|
+
throw new Error(`Command not found in PATH: "${command}"`);
|
|
1330
|
+
}
|
|
1331
|
+
export async function runChildProcess(runId, command, args, opts) {
|
|
1332
|
+
const onLogError = opts.onLogError ?? ((err, id, msg) => console.warn({ err, runId: id }, msg));
|
|
1333
|
+
return new Promise((resolve, reject) => {
|
|
1334
|
+
const rawMerged = {
|
|
1335
|
+
...sanitizeInheritedEvermoreEnv(process.env),
|
|
1336
|
+
...opts.env,
|
|
1337
|
+
};
|
|
1338
|
+
// Strip Claude Code nesting-guard env vars so spawned `claude` processes
|
|
1339
|
+
// don't refuse to start with "cannot be launched inside another session".
|
|
1340
|
+
// These vars leak in when the Evermore server itself is started from
|
|
1341
|
+
// within a Claude Code session (e.g. `npx evermore.work run` in a terminal
|
|
1342
|
+
// owned by Claude Code) or when cron inherits a contaminated shell env.
|
|
1343
|
+
const CLAUDE_CODE_NESTING_VARS = [
|
|
1344
|
+
"CLAUDECODE",
|
|
1345
|
+
"CLAUDE_CODE_ENTRYPOINT",
|
|
1346
|
+
"CLAUDE_CODE_SESSION",
|
|
1347
|
+
"CLAUDE_CODE_PARENT_SESSION",
|
|
1348
|
+
];
|
|
1349
|
+
for (const key of CLAUDE_CODE_NESTING_VARS) {
|
|
1350
|
+
delete rawMerged[key];
|
|
1351
|
+
}
|
|
1352
|
+
const mergedEnv = ensurePathInEnv(rawMerged);
|
|
1353
|
+
void resolveSpawnTarget(command, args, opts.cwd, mergedEnv, {
|
|
1354
|
+
remoteExecution: opts.remoteExecution ?? null,
|
|
1355
|
+
remoteEnv: opts.remoteExecution ? opts.env : null,
|
|
1356
|
+
})
|
|
1357
|
+
.then((target) => {
|
|
1358
|
+
const child = spawn(target.command, target.args, {
|
|
1359
|
+
cwd: target.cwd ?? opts.cwd,
|
|
1360
|
+
env: mergedEnv,
|
|
1361
|
+
detached: process.platform !== "win32",
|
|
1362
|
+
shell: false,
|
|
1363
|
+
stdio: [opts.stdin != null ? "pipe" : "ignore", "pipe", "pipe"],
|
|
1364
|
+
});
|
|
1365
|
+
const startedAt = new Date().toISOString();
|
|
1366
|
+
const processGroupId = resolveProcessGroupId(child);
|
|
1367
|
+
const spawnPersistPromise = typeof child.pid === "number" && child.pid > 0 && opts.onSpawn
|
|
1368
|
+
? opts.onSpawn({ pid: child.pid, processGroupId, startedAt }).catch((err) => {
|
|
1369
|
+
onLogError(err, runId, "failed to record child process metadata");
|
|
1370
|
+
})
|
|
1371
|
+
: Promise.resolve();
|
|
1372
|
+
runningProcesses.set(runId, { child, graceSec: opts.graceSec, processGroupId });
|
|
1373
|
+
let timedOut = false;
|
|
1374
|
+
let stdout = "";
|
|
1375
|
+
let stderr = "";
|
|
1376
|
+
let logChain = Promise.resolve();
|
|
1377
|
+
let terminalResultSeen = false;
|
|
1378
|
+
let terminalCleanupStarted = false;
|
|
1379
|
+
let terminalCleanupTimer = null;
|
|
1380
|
+
let terminalCleanupKillTimer = null;
|
|
1381
|
+
let terminalResultStdoutScanOffset = 0;
|
|
1382
|
+
let terminalResultStderrScanOffset = 0;
|
|
1383
|
+
const clearTerminalCleanupTimers = () => {
|
|
1384
|
+
if (terminalCleanupTimer)
|
|
1385
|
+
clearTimeout(terminalCleanupTimer);
|
|
1386
|
+
if (terminalCleanupKillTimer)
|
|
1387
|
+
clearTimeout(terminalCleanupKillTimer);
|
|
1388
|
+
terminalCleanupTimer = null;
|
|
1389
|
+
terminalCleanupKillTimer = null;
|
|
1390
|
+
};
|
|
1391
|
+
const maybeArmTerminalResultCleanup = () => {
|
|
1392
|
+
const terminalCleanup = opts.terminalResultCleanup;
|
|
1393
|
+
if (!terminalCleanup || terminalCleanupStarted || timedOut)
|
|
1394
|
+
return;
|
|
1395
|
+
if (!terminalResultSeen) {
|
|
1396
|
+
const stdoutStart = Math.max(0, terminalResultStdoutScanOffset - TERMINAL_RESULT_SCAN_OVERLAP_CHARS);
|
|
1397
|
+
const stderrStart = Math.max(0, terminalResultStderrScanOffset - TERMINAL_RESULT_SCAN_OVERLAP_CHARS);
|
|
1398
|
+
const scanOutput = {
|
|
1399
|
+
stdout: stdout.slice(stdoutStart),
|
|
1400
|
+
stderr: stderr.slice(stderrStart),
|
|
1401
|
+
};
|
|
1402
|
+
terminalResultStdoutScanOffset = stdout.length;
|
|
1403
|
+
terminalResultStderrScanOffset = stderr.length;
|
|
1404
|
+
if (scanOutput.stdout.length === 0 && scanOutput.stderr.length === 0)
|
|
1405
|
+
return;
|
|
1406
|
+
try {
|
|
1407
|
+
terminalResultSeen = terminalCleanup.hasTerminalResult(scanOutput);
|
|
1408
|
+
}
|
|
1409
|
+
catch (err) {
|
|
1410
|
+
onLogError(err, runId, "failed to inspect terminal adapter output");
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
if (!terminalResultSeen)
|
|
1414
|
+
return;
|
|
1415
|
+
if (terminalCleanupTimer)
|
|
1416
|
+
return;
|
|
1417
|
+
const graceMs = Math.max(0, terminalCleanup.graceMs ?? 5_000);
|
|
1418
|
+
terminalCleanupTimer = setTimeout(() => {
|
|
1419
|
+
terminalCleanupTimer = null;
|
|
1420
|
+
if (terminalCleanupStarted || timedOut)
|
|
1421
|
+
return;
|
|
1422
|
+
terminalCleanupStarted = true;
|
|
1423
|
+
signalRunningProcess({ child, processGroupId }, "SIGTERM");
|
|
1424
|
+
terminalCleanupKillTimer = setTimeout(() => {
|
|
1425
|
+
terminalCleanupKillTimer = null;
|
|
1426
|
+
signalRunningProcess({ child, processGroupId }, "SIGKILL");
|
|
1427
|
+
}, Math.max(1, opts.graceSec) * 1000);
|
|
1428
|
+
}, graceMs);
|
|
1429
|
+
};
|
|
1430
|
+
const timeout = opts.timeoutSec > 0
|
|
1431
|
+
? setTimeout(() => {
|
|
1432
|
+
timedOut = true;
|
|
1433
|
+
clearTerminalCleanupTimers();
|
|
1434
|
+
signalRunningProcess({ child, processGroupId }, "SIGTERM");
|
|
1435
|
+
setTimeout(() => {
|
|
1436
|
+
signalRunningProcess({ child, processGroupId }, "SIGKILL");
|
|
1437
|
+
}, Math.max(1, opts.graceSec) * 1000);
|
|
1438
|
+
}, opts.timeoutSec * 1000)
|
|
1439
|
+
: null;
|
|
1440
|
+
child.stdout?.on("data", (chunk) => {
|
|
1441
|
+
const readable = child.stdout;
|
|
1442
|
+
if (!readable)
|
|
1443
|
+
return;
|
|
1444
|
+
readable.pause();
|
|
1445
|
+
const text = String(chunk);
|
|
1446
|
+
stdout = appendWithCap(stdout, text);
|
|
1447
|
+
maybeArmTerminalResultCleanup();
|
|
1448
|
+
logChain = logChain
|
|
1449
|
+
.then(() => opts.onLog("stdout", text))
|
|
1450
|
+
.catch((err) => onLogError(err, runId, "failed to append stdout log chunk"))
|
|
1451
|
+
.finally(() => {
|
|
1452
|
+
maybeArmTerminalResultCleanup();
|
|
1453
|
+
resumeReadable(readable);
|
|
1454
|
+
});
|
|
1455
|
+
});
|
|
1456
|
+
child.stderr?.on("data", (chunk) => {
|
|
1457
|
+
const readable = child.stderr;
|
|
1458
|
+
if (!readable)
|
|
1459
|
+
return;
|
|
1460
|
+
readable.pause();
|
|
1461
|
+
const text = String(chunk);
|
|
1462
|
+
stderr = appendWithCap(stderr, text);
|
|
1463
|
+
maybeArmTerminalResultCleanup();
|
|
1464
|
+
logChain = logChain
|
|
1465
|
+
.then(() => opts.onLog("stderr", text))
|
|
1466
|
+
.catch((err) => onLogError(err, runId, "failed to append stderr log chunk"))
|
|
1467
|
+
.finally(() => {
|
|
1468
|
+
maybeArmTerminalResultCleanup();
|
|
1469
|
+
resumeReadable(readable);
|
|
1470
|
+
});
|
|
1471
|
+
});
|
|
1472
|
+
const stdin = child.stdin;
|
|
1473
|
+
if (opts.stdin != null && stdin) {
|
|
1474
|
+
void spawnPersistPromise.finally(() => {
|
|
1475
|
+
if (child.killed || stdin.destroyed)
|
|
1476
|
+
return;
|
|
1477
|
+
stdin.write(opts.stdin);
|
|
1478
|
+
stdin.end();
|
|
1479
|
+
});
|
|
1480
|
+
}
|
|
1481
|
+
child.on("error", (err) => {
|
|
1482
|
+
if (timeout)
|
|
1483
|
+
clearTimeout(timeout);
|
|
1484
|
+
clearTerminalCleanupTimers();
|
|
1485
|
+
runningProcesses.delete(runId);
|
|
1486
|
+
void target.cleanup?.();
|
|
1487
|
+
const errno = err.code;
|
|
1488
|
+
const pathValue = mergedEnv.PATH ?? mergedEnv.Path ?? "";
|
|
1489
|
+
const msg = errno === "ENOENT"
|
|
1490
|
+
? `Failed to start command "${command}" in "${opts.cwd}". Verify adapter command, working directory, and PATH (${pathValue}).`
|
|
1491
|
+
: `Failed to start command "${command}" in "${opts.cwd}": ${err.message}`;
|
|
1492
|
+
reject(new Error(msg));
|
|
1493
|
+
});
|
|
1494
|
+
child.on("exit", () => {
|
|
1495
|
+
maybeArmTerminalResultCleanup();
|
|
1496
|
+
});
|
|
1497
|
+
child.on("close", (code, signal) => {
|
|
1498
|
+
if (timeout)
|
|
1499
|
+
clearTimeout(timeout);
|
|
1500
|
+
clearTerminalCleanupTimers();
|
|
1501
|
+
runningProcesses.delete(runId);
|
|
1502
|
+
void logChain.finally(() => {
|
|
1503
|
+
void Promise.resolve()
|
|
1504
|
+
.then(() => target.cleanup?.())
|
|
1505
|
+
.finally(() => {
|
|
1506
|
+
resolve({
|
|
1507
|
+
exitCode: code,
|
|
1508
|
+
signal,
|
|
1509
|
+
timedOut,
|
|
1510
|
+
stdout,
|
|
1511
|
+
stderr,
|
|
1512
|
+
pid: child.pid ?? null,
|
|
1513
|
+
startedAt,
|
|
1514
|
+
});
|
|
1515
|
+
});
|
|
1516
|
+
});
|
|
1517
|
+
});
|
|
1518
|
+
})
|
|
1519
|
+
.catch(reject);
|
|
1520
|
+
});
|
|
1521
|
+
}
|
|
1522
|
+
//# sourceMappingURL=server-utils.js.map
|