@tickernelz/wardmote-adapter-omp-local 0.0.0 → 2026.1108.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/dist/cli/format-event.d.ts +2 -0
- package/dist/cli/format-event.d.ts.map +1 -0
- package/dist/cli/format-event.js +56 -0
- package/dist/cli/format-event.js.map +1 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.d.ts.map +1 -0
- package/dist/cli/index.js +2 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/metadata.d.ts +9 -0
- package/dist/metadata.d.ts.map +1 -0
- package/dist/metadata.js +47 -0
- package/dist/metadata.js.map +1 -0
- package/dist/server/config.d.ts +25 -0
- package/dist/server/config.d.ts.map +1 -0
- package/dist/server/config.js +720 -0
- package/dist/server/config.js.map +1 -0
- package/dist/server/config.test.d.ts +2 -0
- package/dist/server/config.test.d.ts.map +1 -0
- package/dist/server/config.test.js +65 -0
- package/dist/server/config.test.js.map +1 -0
- package/dist/server/execute.choices.test.d.ts +2 -0
- package/dist/server/execute.choices.test.d.ts.map +1 -0
- package/dist/server/execute.choices.test.js +113 -0
- package/dist/server/execute.choices.test.js.map +1 -0
- package/dist/server/execute.cwd.test.d.ts +2 -0
- package/dist/server/execute.cwd.test.d.ts.map +1 -0
- package/dist/server/execute.cwd.test.js +88 -0
- package/dist/server/execute.cwd.test.js.map +1 -0
- package/dist/server/execute.d.ts +27 -0
- package/dist/server/execute.d.ts.map +1 -0
- package/dist/server/execute.js +1155 -0
- package/dist/server/execute.js.map +1 -0
- package/dist/server/execute.mcp.test.d.ts +2 -0
- package/dist/server/execute.mcp.test.d.ts.map +1 -0
- package/dist/server/execute.mcp.test.js +512 -0
- package/dist/server/execute.mcp.test.js.map +1 -0
- package/dist/server/execute.model-override.test.d.ts +2 -0
- package/dist/server/execute.model-override.test.d.ts.map +1 -0
- package/dist/server/execute.model-override.test.js +115 -0
- package/dist/server/execute.model-override.test.js.map +1 -0
- package/dist/server/execute.provider-stop.test.d.ts +2 -0
- package/dist/server/execute.provider-stop.test.d.ts.map +1 -0
- package/dist/server/execute.provider-stop.test.js +96 -0
- package/dist/server/execute.provider-stop.test.js.map +1 -0
- package/dist/server/execute.python-env.remote.test.d.ts +2 -0
- package/dist/server/execute.python-env.remote.test.d.ts.map +1 -0
- package/dist/server/execute.python-env.remote.test.js +102 -0
- package/dist/server/execute.python-env.remote.test.js.map +1 -0
- package/dist/server/execute.thinking.test.d.ts +2 -0
- package/dist/server/execute.thinking.test.d.ts.map +1 -0
- package/dist/server/execute.thinking.test.js +23 -0
- package/dist/server/execute.thinking.test.js.map +1 -0
- package/dist/server/execute.toggles.test.d.ts +2 -0
- package/dist/server/execute.toggles.test.d.ts.map +1 -0
- package/dist/server/execute.toggles.test.js +193 -0
- package/dist/server/execute.toggles.test.js.map +1 -0
- package/dist/server/execute.transport.test.d.ts +2 -0
- package/dist/server/execute.transport.test.d.ts.map +1 -0
- package/dist/server/execute.transport.test.js +159 -0
- package/dist/server/execute.transport.test.js.map +1 -0
- package/dist/server/execute.usage-checkpoint.test.d.ts +2 -0
- package/dist/server/execute.usage-checkpoint.test.d.ts.map +1 -0
- package/dist/server/execute.usage-checkpoint.test.js +92 -0
- package/dist/server/execute.usage-checkpoint.test.js.map +1 -0
- package/dist/server/failure.d.ts +22 -0
- package/dist/server/failure.d.ts.map +1 -0
- package/dist/server/failure.js +99 -0
- package/dist/server/failure.js.map +1 -0
- package/dist/server/failure.test.d.ts +2 -0
- package/dist/server/failure.test.d.ts.map +1 -0
- package/dist/server/failure.test.js +37 -0
- package/dist/server/failure.test.js.map +1 -0
- package/dist/server/index.d.ts +7 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +101 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/model-fallback.d.ts +34 -0
- package/dist/server/model-fallback.d.ts.map +1 -0
- package/dist/server/model-fallback.js +115 -0
- package/dist/server/model-fallback.js.map +1 -0
- package/dist/server/model-fallback.test.d.ts +2 -0
- package/dist/server/model-fallback.test.d.ts.map +1 -0
- package/dist/server/model-fallback.test.js +44 -0
- package/dist/server/model-fallback.test.js.map +1 -0
- package/dist/server/models.d.ts +19 -0
- package/dist/server/models.d.ts.map +1 -0
- package/dist/server/models.js +225 -0
- package/dist/server/models.js.map +1 -0
- package/dist/server/paperclip-mcp.d.ts +53 -0
- package/dist/server/paperclip-mcp.d.ts.map +1 -0
- package/dist/server/paperclip-mcp.js +245 -0
- package/dist/server/paperclip-mcp.js.map +1 -0
- package/dist/server/parse.d.ts +45 -0
- package/dist/server/parse.d.ts.map +1 -0
- package/dist/server/parse.js +510 -0
- package/dist/server/parse.js.map +1 -0
- package/dist/server/parse.test.d.ts +2 -0
- package/dist/server/parse.test.d.ts.map +1 -0
- package/dist/server/parse.test.js +108 -0
- package/dist/server/parse.test.js.map +1 -0
- package/dist/server/profile.d.ts +7 -0
- package/dist/server/profile.d.ts.map +1 -0
- package/dist/server/profile.js +40 -0
- package/dist/server/profile.js.map +1 -0
- package/dist/server/progress.d.ts +16 -0
- package/dist/server/progress.d.ts.map +1 -0
- package/dist/server/progress.js +235 -0
- package/dist/server/progress.js.map +1 -0
- package/dist/server/progress.todo.test.d.ts +2 -0
- package/dist/server/progress.todo.test.d.ts.map +1 -0
- package/dist/server/progress.todo.test.js +112 -0
- package/dist/server/progress.todo.test.js.map +1 -0
- package/dist/server/python-env.d.ts +28 -0
- package/dist/server/python-env.d.ts.map +1 -0
- package/dist/server/python-env.js +153 -0
- package/dist/server/python-env.js.map +1 -0
- package/dist/server/python-env.test.d.ts +2 -0
- package/dist/server/python-env.test.d.ts.map +1 -0
- package/dist/server/python-env.test.js +202 -0
- package/dist/server/python-env.test.js.map +1 -0
- package/dist/server/quota.d.ts +4 -0
- package/dist/server/quota.d.ts.map +1 -0
- package/dist/server/quota.js +129 -0
- package/dist/server/quota.js.map +1 -0
- package/dist/server/readiness.d.ts +35 -0
- package/dist/server/readiness.d.ts.map +1 -0
- package/dist/server/readiness.js +196 -0
- package/dist/server/readiness.js.map +1 -0
- package/dist/server/readiness.test.d.ts +2 -0
- package/dist/server/readiness.test.d.ts.map +1 -0
- package/dist/server/readiness.test.js +105 -0
- package/dist/server/readiness.test.js.map +1 -0
- package/dist/server/redaction-repair.d.ts +5 -0
- package/dist/server/redaction-repair.d.ts.map +1 -0
- package/dist/server/redaction-repair.js +122 -0
- package/dist/server/redaction-repair.js.map +1 -0
- package/dist/server/rpc-session.d.ts +64 -0
- package/dist/server/rpc-session.d.ts.map +1 -0
- package/dist/server/rpc-session.js +609 -0
- package/dist/server/rpc-session.js.map +1 -0
- package/dist/server/rpc-session.test.d.ts +2 -0
- package/dist/server/rpc-session.test.d.ts.map +1 -0
- package/dist/server/rpc-session.test.js +803 -0
- package/dist/server/rpc-session.test.js.map +1 -0
- package/dist/server/settings-catalog.d.ts +16 -0
- package/dist/server/settings-catalog.d.ts.map +1 -0
- package/dist/server/settings-catalog.js +86 -0
- package/dist/server/settings-catalog.js.map +1 -0
- package/dist/server/settings-catalog.test.d.ts +2 -0
- package/dist/server/settings-catalog.test.d.ts.map +1 -0
- package/dist/server/settings-catalog.test.js +41 -0
- package/dist/server/settings-catalog.test.js.map +1 -0
- package/dist/server/settings-overlay.d.ts +22 -0
- package/dist/server/settings-overlay.d.ts.map +1 -0
- package/dist/server/settings-overlay.js +131 -0
- package/dist/server/settings-overlay.js.map +1 -0
- package/dist/server/settings-overlay.test.d.ts +2 -0
- package/dist/server/settings-overlay.test.d.ts.map +1 -0
- package/dist/server/settings-overlay.test.js +134 -0
- package/dist/server/settings-overlay.test.js.map +1 -0
- package/dist/server/skills.d.ts +5 -0
- package/dist/server/skills.d.ts.map +1 -0
- package/dist/server/skills.js +111 -0
- package/dist/server/skills.js.map +1 -0
- package/dist/server/skills.test.d.ts +2 -0
- package/dist/server/skills.test.d.ts.map +1 -0
- package/dist/server/skills.test.js +65 -0
- package/dist/server/skills.test.js.map +1 -0
- package/dist/server/test.d.ts +3 -0
- package/dist/server/test.d.ts.map +1 -0
- package/dist/server/test.js +446 -0
- package/dist/server/test.js.map +1 -0
- package/dist/server/tool-guard.d.ts +22 -0
- package/dist/server/tool-guard.d.ts.map +1 -0
- package/dist/server/tool-guard.js +101 -0
- package/dist/server/tool-guard.js.map +1 -0
- package/dist/server/tool-guard.test.d.ts +2 -0
- package/dist/server/tool-guard.test.d.ts.map +1 -0
- package/dist/server/tool-guard.test.js +152 -0
- package/dist/server/tool-guard.test.js.map +1 -0
- package/dist/ui/index.d.ts +2 -0
- package/dist/ui/index.d.ts.map +1 -0
- package/dist/ui/index.js +2 -0
- package/dist/ui/index.js.map +1 -0
- package/dist/ui/parse-stdout.d.ts +4 -0
- package/dist/ui/parse-stdout.d.ts.map +1 -0
- package/dist/ui/parse-stdout.js +493 -0
- package/dist/ui/parse-stdout.js.map +1 -0
- package/dist/ui/parse-stdout.test.d.ts +2 -0
- package/dist/ui/parse-stdout.test.d.ts.map +1 -0
- package/dist/ui/parse-stdout.test.js +107 -0
- package/dist/ui/parse-stdout.test.js.map +1 -0
- package/package.json +56 -10
- package/README.md +0 -8
- package/index.js +0 -1
|
@@ -0,0 +1,1155 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import { createProviderStoppedBoundary } from "@tickernelz/wardmote-adapter-utils/provider-stopped-boundary";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { createUsageCheckpointLog } from "@tickernelz/wardmote-adapter-utils/usage-checkpoint";
|
|
6
|
+
import { inferOpenAiCompatibleBiller, } from "@tickernelz/wardmote-adapter-utils";
|
|
7
|
+
import { adapterExecutionTargetIsRemote, adapterExecutionTargetSessionIdentity, adapterExecutionTargetSessionMatches, adapterExecutionTargetSupportsLiveStdin, adapterExecutionTargetUsesManagedHome, adapterExecutionTargetUsesPaperclipBridge, describeAdapterExecutionTarget, ensureAdapterExecutionTargetCommandResolvable, ensureAdapterExecutionTargetDirectory, ensureAdapterExecutionTargetRuntimeCommandInstalled, overrideAdapterExecutionTargetRemoteCwd, prepareAdapterExecutionTargetRuntime, readAdapterExecutionTarget, resolveAdapterExecutionTargetCommandForLogs, resolveAdapterExecutionTargetTimeoutSec, runAdapterExecutionTargetProcess, startAdapterExecutionTargetPaperclipBridge, } from "@tickernelz/wardmote-adapter-utils/execution-target";
|
|
8
|
+
import { paperclipAgentPromptTemplate, appendWithCap, asBoolean, asNumber, asString, buildInvocationEnvForLogs, buildPaperclipEnv, buildRuntimeToolsEnv, ensureAbsoluteDirectory, ensurePathInEnv, joinPromptSections, parseObject, readPaperclipIssueWorkModeFromContext, refreshPaperclipWorkspaceEnvForExecution, renderPaperclipWakePrompt, renderTemplate, isForbiddenConfigEnvKey, isPaperclipRuntimeEnvKey, sanitizeInheritedPaperclipEnv, selectPaperclipTaskMarkdown, } from "@tickernelz/wardmote-adapter-utils/server-utils";
|
|
9
|
+
import { legacyEnvKey } from "@tickernelz/wardmote-shared/env-aliases";
|
|
10
|
+
import { paperclipRestGuidance, } from "@tickernelz/wardmote-adapter-utils/paperclip-mcp";
|
|
11
|
+
import { OMP_INSTALL_COMMAND } from "../metadata.js";
|
|
12
|
+
import { prepareOmpRuntimeConfig, resolveOmpCommand, } from "./config.js";
|
|
13
|
+
import { createOmpJsonlParser, createOmpOutputAccumulator, isOmpUnknownSessionError, parseOmpJsonLine, } from "./parse.js";
|
|
14
|
+
import { classifyOmpFailure } from "./failure.js";
|
|
15
|
+
import { createOmpProgressReporter } from "./progress.js";
|
|
16
|
+
import { createOmpRpcSteerSession, runOmpRpcSession } from "./rpc-session.js";
|
|
17
|
+
import { registerAdapterSteerTarget } from "@tickernelz/wardmote-adapter-utils/adapter-steer-registry";
|
|
18
|
+
import { runToolProfile } from "@tickernelz/wardmote-adapter-utils/tool-profile";
|
|
19
|
+
import { ensureOmpSkills } from "./skills.js";
|
|
20
|
+
import { writeOmpSettingsOverlay } from "./settings-overlay.js";
|
|
21
|
+
import { createOmpModelFallbackTracker, ompFallbackChain } from "./model-fallback.js";
|
|
22
|
+
import { writeOmpToolGuardExtension } from "./tool-guard.js";
|
|
23
|
+
import { prependPythonPath, writeOmpPythonEnvBridge } from "./python-env.js";
|
|
24
|
+
import { PAPERCLIP_MCP_BIN, PAPERCLIP_MCP_CREDENTIAL_CODE, PAPERCLIP_MCP_CONNECT_FAILURE_RE, PAPERCLIP_MCP_TRANSIENT_FAILURE_RE, PAPERCLIP_MCP_SERVER_NAME, PAPERCLIP_MCP_TOOLSETS_ENV, PAPERCLIP_MCP_UNAVAILABLE_CODE, paperclipMcpUnavailableRecovery, paperclipMcpGuidance, paperclipMcpEndpoint, paperclipMcpTransport, probePaperclipMcpEndpoint, paperclipMcpToolsets, probePaperclipMcpServer, resolvePaperclipMcpServerCommand, writePaperclipMcpExtension, } from "./paperclip-mcp.js";
|
|
25
|
+
const RESULT_TRANSCRIPT_MAX_CHARS = 16 * 1024;
|
|
26
|
+
const RESULT_TOOL_CALL_MAX_CHARS = 4 * 1024;
|
|
27
|
+
/** Keeps a tool call's result to a diagnostic tail so a verbose run stays inside the result budget. */
|
|
28
|
+
function boundToolCallForResult(call) {
|
|
29
|
+
const result = typeof call.result === "string" ? call.result : JSON.stringify(call.result ?? null);
|
|
30
|
+
const args = typeof call.args === "string" ? call.args : JSON.stringify(call.args ?? null);
|
|
31
|
+
return {
|
|
32
|
+
toolCallId: call.toolCallId ?? "",
|
|
33
|
+
toolName: call.toolName ?? "",
|
|
34
|
+
args: appendWithCap("", args, RESULT_TOOL_CALL_MAX_CHARS),
|
|
35
|
+
result: appendWithCap("", result, RESULT_TOOL_CALL_MAX_CHARS),
|
|
36
|
+
isError: call.isError === true,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
const CAPABILITY_MANIFEST = {
|
|
40
|
+
bindings: [
|
|
41
|
+
"omp-jsonl",
|
|
42
|
+
"session-dir-resume",
|
|
43
|
+
"paperclip-workspace-env",
|
|
44
|
+
"paperclip-skills",
|
|
45
|
+
"local-execution",
|
|
46
|
+
"ssh-execution",
|
|
47
|
+
"sandbox-execution",
|
|
48
|
+
],
|
|
49
|
+
limits: [
|
|
50
|
+
"one-process-per-heartbeat",
|
|
51
|
+
"no-live-steering",
|
|
52
|
+
"no-interactive-dialogs",
|
|
53
|
+
"no-rpc-transport",
|
|
54
|
+
"schema-driven-ui-only",
|
|
55
|
+
"no-provider-quota-hook",
|
|
56
|
+
"no-remote-session-resume",
|
|
57
|
+
],
|
|
58
|
+
};
|
|
59
|
+
const RPC_CAPABILITY_MANIFEST = {
|
|
60
|
+
bindings: [
|
|
61
|
+
"omp-jsonl",
|
|
62
|
+
"omp-rpc-transport",
|
|
63
|
+
"same-turn-steering",
|
|
64
|
+
"session-dir-resume",
|
|
65
|
+
"paperclip-workspace-env",
|
|
66
|
+
"paperclip-skills",
|
|
67
|
+
"local-execution",
|
|
68
|
+
],
|
|
69
|
+
limits: [
|
|
70
|
+
"one-process-per-heartbeat",
|
|
71
|
+
"no-interactive-dialogs",
|
|
72
|
+
"schema-driven-ui-only",
|
|
73
|
+
"no-provider-quota-hook",
|
|
74
|
+
"no-remote-session-resume",
|
|
75
|
+
],
|
|
76
|
+
};
|
|
77
|
+
export function ompRpcSteeringEnabled(config) {
|
|
78
|
+
return asBoolean(config.rpcSteering, true);
|
|
79
|
+
}
|
|
80
|
+
function stringList(value, commaSeparated = false) {
|
|
81
|
+
const values = Array.isArray(value)
|
|
82
|
+
? value
|
|
83
|
+
: typeof value === "string"
|
|
84
|
+
? value.split(commaSeparated ? /[\r\n,]+/ : /\r?\n/)
|
|
85
|
+
: [];
|
|
86
|
+
return values
|
|
87
|
+
.filter((entry) => typeof entry === "string")
|
|
88
|
+
.map((entry) => entry.trim())
|
|
89
|
+
.filter(Boolean);
|
|
90
|
+
}
|
|
91
|
+
const REMOTE_PATH_FIELDS = ["configFiles", "extensions", "hooks", "pluginDirs"];
|
|
92
|
+
export function rewriteRemoteConfigPaths(config, localCwd, remoteCwd) {
|
|
93
|
+
const rewritten = { ...config };
|
|
94
|
+
for (const field of REMOTE_PATH_FIELDS) {
|
|
95
|
+
const values = stringList(config[field]);
|
|
96
|
+
if (values.length === 0)
|
|
97
|
+
continue;
|
|
98
|
+
rewritten[field] = values.map((value) => {
|
|
99
|
+
const expanded = value === "~"
|
|
100
|
+
? os.homedir()
|
|
101
|
+
: value.startsWith("~/") || value.startsWith("~\\")
|
|
102
|
+
? path.resolve(os.homedir(), value.slice(2))
|
|
103
|
+
: path.resolve(localCwd, value);
|
|
104
|
+
const relative = path.relative(localCwd, expanded);
|
|
105
|
+
if (relative.startsWith(`..${path.sep}`) || relative === ".." || path.isAbsolute(relative)) {
|
|
106
|
+
throw new Error(`Remote OMP ${field} path must be inside the synchronized workspace: ${value}`);
|
|
107
|
+
}
|
|
108
|
+
return relative && relative !== "."
|
|
109
|
+
? path.posix.join(remoteCwd, ...relative.split(path.sep))
|
|
110
|
+
: remoteCwd;
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
return rewritten;
|
|
114
|
+
}
|
|
115
|
+
function firstNonEmptyLine(text) {
|
|
116
|
+
return text.split(/\r?\n/).map((line) => line.trim()).find(Boolean) ?? "";
|
|
117
|
+
}
|
|
118
|
+
function safePathSegment(value) {
|
|
119
|
+
return encodeURIComponent(value).replaceAll(".", "%2E");
|
|
120
|
+
}
|
|
121
|
+
function executionCwdsMatch(saved, current, remote) {
|
|
122
|
+
return remote
|
|
123
|
+
? path.posix.normalize(saved) === path.posix.normalize(current)
|
|
124
|
+
: path.resolve(saved) === path.resolve(current);
|
|
125
|
+
}
|
|
126
|
+
function stringsOnly(env) {
|
|
127
|
+
return Object.fromEntries(Object.entries(env).filter((entry) => typeof entry[1] === "string"));
|
|
128
|
+
}
|
|
129
|
+
function modelEffortOverrides(config) {
|
|
130
|
+
const raw = config.modelEfforts;
|
|
131
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw))
|
|
132
|
+
return {};
|
|
133
|
+
const overrides = {};
|
|
134
|
+
for (const [selector, effort] of Object.entries(raw)) {
|
|
135
|
+
const level = asString(effort, "").trim();
|
|
136
|
+
if (selector.trim() && level)
|
|
137
|
+
overrides[selector.trim()] = level;
|
|
138
|
+
}
|
|
139
|
+
return overrides;
|
|
140
|
+
}
|
|
141
|
+
/** The fallback's own effort when the run starts on a fallback, else the agent's thinking level. */
|
|
142
|
+
export function resolveOmpThinking(config, model) {
|
|
143
|
+
const perModel = modelEffortOverrides(config)[model];
|
|
144
|
+
if (perModel)
|
|
145
|
+
return perModel;
|
|
146
|
+
return (asString(config.thinking, "") || asString(config.thinkingEffort, "") || asString(config.effort, "")).trim();
|
|
147
|
+
}
|
|
148
|
+
function configuredModelProvider(model) {
|
|
149
|
+
if (!model || model.startsWith("@"))
|
|
150
|
+
return null;
|
|
151
|
+
const separator = model.indexOf("/");
|
|
152
|
+
return separator > 0 ? model.slice(0, separator) : null;
|
|
153
|
+
}
|
|
154
|
+
function resolveBiller(env, provider) {
|
|
155
|
+
return provider === "openai"
|
|
156
|
+
? inferOpenAiCompatibleBiller(env, "openai") ?? "unknown"
|
|
157
|
+
: provider ?? inferOpenAiCompatibleBiller(env, null) ?? "unknown";
|
|
158
|
+
}
|
|
159
|
+
function addWakeEnvironment(env, runId, context) {
|
|
160
|
+
env.PAPERCLIP_RUN_ID = runId;
|
|
161
|
+
const taskId = asString(context.taskId, "").trim() || asString(context.issueId, "").trim();
|
|
162
|
+
const wakeReason = asString(context.wakeReason, "").trim();
|
|
163
|
+
const wakeCommentId = asString(context.wakeCommentId, "").trim() || asString(context.commentId, "").trim();
|
|
164
|
+
const approvalId = asString(context.approvalId, "").trim();
|
|
165
|
+
const approvalStatus = asString(context.approvalStatus, "").trim();
|
|
166
|
+
const linkedIssueIds = Array.isArray(context.issueIds)
|
|
167
|
+
? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0)
|
|
168
|
+
: [];
|
|
169
|
+
const issueWorkMode = readPaperclipIssueWorkModeFromContext(context);
|
|
170
|
+
if (taskId)
|
|
171
|
+
env.PAPERCLIP_TASK_ID = taskId;
|
|
172
|
+
if (wakeReason)
|
|
173
|
+
env.PAPERCLIP_WAKE_REASON = wakeReason;
|
|
174
|
+
if (wakeCommentId)
|
|
175
|
+
env.PAPERCLIP_WAKE_COMMENT_ID = wakeCommentId;
|
|
176
|
+
if (approvalId)
|
|
177
|
+
env.PAPERCLIP_APPROVAL_ID = approvalId;
|
|
178
|
+
if (approvalStatus)
|
|
179
|
+
env.PAPERCLIP_APPROVAL_STATUS = approvalStatus;
|
|
180
|
+
if (linkedIssueIds.length > 0)
|
|
181
|
+
env.PAPERCLIP_LINKED_ISSUE_IDS = linkedIssueIds.join(",");
|
|
182
|
+
if (issueWorkMode)
|
|
183
|
+
env.PAPERCLIP_ISSUE_WORK_MODE = issueWorkMode;
|
|
184
|
+
}
|
|
185
|
+
export function buildOmpArgs(input) {
|
|
186
|
+
const { config } = input;
|
|
187
|
+
const args = input.rpc ? ["--mode", "rpc"] : ["--mode", "json", "-p"];
|
|
188
|
+
const baseSystemPrompt = asString(config.systemPrompt, "").trim();
|
|
189
|
+
if (baseSystemPrompt)
|
|
190
|
+
args.push("--system-prompt", baseSystemPrompt);
|
|
191
|
+
args.push("--append-system-prompt", input.systemPrompt);
|
|
192
|
+
const model = asString(config.model, "").trim();
|
|
193
|
+
const thinking = resolveOmpThinking(config, model);
|
|
194
|
+
const profile = input.effectiveProfile ?? "";
|
|
195
|
+
const smol = asString(config.smolModel, "").trim();
|
|
196
|
+
const slow = asString(config.slowModel, "").trim();
|
|
197
|
+
const plan = asString(config.planModel, "").trim();
|
|
198
|
+
const modelCycle = stringList(config.modelCycle, true);
|
|
199
|
+
const tools = stringList(config.tools, true);
|
|
200
|
+
const skills = stringList(config.skills, true);
|
|
201
|
+
const approvalMode = asString(config.approvalMode, "").trim();
|
|
202
|
+
const noSession = asBoolean(config.noSession, false);
|
|
203
|
+
if (model)
|
|
204
|
+
args.push("--model", model);
|
|
205
|
+
args.push(asBoolean(config.printThoughts, true) ? "--print-thoughts" : "--hide-thinking");
|
|
206
|
+
if (thinking)
|
|
207
|
+
args.push("--thinking", thinking);
|
|
208
|
+
if (profile && !input.omitProfile)
|
|
209
|
+
args.push("--profile", profile);
|
|
210
|
+
if (smol)
|
|
211
|
+
args.push("--smol", smol);
|
|
212
|
+
if (slow)
|
|
213
|
+
args.push("--slow", slow);
|
|
214
|
+
if (plan)
|
|
215
|
+
args.push("--plan", plan);
|
|
216
|
+
if (modelCycle.length > 0)
|
|
217
|
+
args.push("--models", modelCycle.join(","));
|
|
218
|
+
if (asBoolean(config.noTools, false))
|
|
219
|
+
args.push("--no-tools");
|
|
220
|
+
if (tools.length > 0)
|
|
221
|
+
args.push("--tools", tools.join(","));
|
|
222
|
+
if (skills.length > 0)
|
|
223
|
+
args.push("--skills", skills.join(","));
|
|
224
|
+
args.push("--approval-mode", ["always-ask", "write", "yolo"].includes(approvalMode) ? approvalMode : "yolo");
|
|
225
|
+
if (asBoolean(config.advisor, false))
|
|
226
|
+
args.push("--advisor");
|
|
227
|
+
const noPrewalk = asBoolean(config.noPrewalk, false);
|
|
228
|
+
const prewalkInto = asString(config.prewalkInto, "").trim();
|
|
229
|
+
if (noPrewalk) {
|
|
230
|
+
args.push("--no-prewalk");
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
if (asBoolean(config.prewalk, false))
|
|
234
|
+
args.push("--prewalk");
|
|
235
|
+
if (prewalkInto)
|
|
236
|
+
args.push("--prewalk-into", prewalkInto);
|
|
237
|
+
}
|
|
238
|
+
if (asBoolean(config.allowHome, false))
|
|
239
|
+
args.push("--allow-home");
|
|
240
|
+
const planYolo = asBoolean(config.planYolo, false);
|
|
241
|
+
const planYoloInto = asString(config.planYoloInto, "").trim();
|
|
242
|
+
if (planYolo) {
|
|
243
|
+
args.push("--plan-yolo");
|
|
244
|
+
if (planYoloInto)
|
|
245
|
+
args.push("--plan-yolo-into", planYoloInto);
|
|
246
|
+
}
|
|
247
|
+
const maxTime = asString(config.maxTime, "").trim() || (asNumber(config.maxTime, 0) > 0 ? String(asNumber(config.maxTime, 0)) : "");
|
|
248
|
+
if (maxTime)
|
|
249
|
+
args.push("--max-time", maxTime);
|
|
250
|
+
if (input.settingsOverlayPath)
|
|
251
|
+
args.push("--config", input.settingsOverlayPath);
|
|
252
|
+
for (const configFile of stringList(config.configFiles))
|
|
253
|
+
args.push("--config", configFile);
|
|
254
|
+
if (input.mcpExtensionPath)
|
|
255
|
+
args.push("--extension", input.mcpExtensionPath);
|
|
256
|
+
if (input.toolGuardExtensionPath)
|
|
257
|
+
args.push("--extension", input.toolGuardExtensionPath);
|
|
258
|
+
for (const extension of stringList(config.extensions))
|
|
259
|
+
args.push("--extension", extension);
|
|
260
|
+
for (const pluginDir of stringList(config.pluginDirs))
|
|
261
|
+
args.push("--plugin-dir", pluginDir);
|
|
262
|
+
for (const hook of stringList(config.hooks))
|
|
263
|
+
args.push("--hook", hook);
|
|
264
|
+
if (asBoolean(config.noExtensions, false))
|
|
265
|
+
args.push("--no-extensions");
|
|
266
|
+
if (asBoolean(config.noSkills, false))
|
|
267
|
+
args.push("--no-skills");
|
|
268
|
+
if (asBoolean(config.noRules, false))
|
|
269
|
+
args.push("--no-rules");
|
|
270
|
+
if (asBoolean(config.noLsp, false))
|
|
271
|
+
args.push("--no-lsp");
|
|
272
|
+
if (asBoolean(config.noPty, false))
|
|
273
|
+
args.push("--no-pty");
|
|
274
|
+
if (asBoolean(config.noTitle, true))
|
|
275
|
+
args.push("--no-title");
|
|
276
|
+
if (noSession) {
|
|
277
|
+
args.push("--no-session");
|
|
278
|
+
}
|
|
279
|
+
else {
|
|
280
|
+
args.push("--session-dir", input.sessionDir);
|
|
281
|
+
if (input.resumeSessionId)
|
|
282
|
+
args.push("--resume", input.resumeSessionId);
|
|
283
|
+
}
|
|
284
|
+
const primaryCwd = input.cwd ? path.resolve(input.cwd) : "";
|
|
285
|
+
const addedDirs = new Set();
|
|
286
|
+
for (const dir of stringList(config.addDirs)) {
|
|
287
|
+
const resolved = path.resolve(dir);
|
|
288
|
+
if (resolved && resolved !== primaryCwd && !addedDirs.has(resolved)) {
|
|
289
|
+
addedDirs.add(resolved);
|
|
290
|
+
args.push("--add-dir=" + resolved);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
if (input.context && Array.isArray(input.context.paperclipWorkspaces)) {
|
|
294
|
+
for (const ws of input.context.paperclipWorkspaces) {
|
|
295
|
+
if (ws && typeof ws === "object" && !Array.isArray(ws)) {
|
|
296
|
+
const wsCwd = asString(ws.cwd, "").trim();
|
|
297
|
+
if (wsCwd) {
|
|
298
|
+
const resolved = path.resolve(wsCwd);
|
|
299
|
+
if (resolved && resolved !== primaryCwd && !addedDirs.has(resolved)) {
|
|
300
|
+
addedDirs.add(resolved);
|
|
301
|
+
args.push("--add-dir=" + resolved);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
args.push(...stringList(config.extraArgs));
|
|
308
|
+
if (!input.rpc)
|
|
309
|
+
args.push(input.userPrompt);
|
|
310
|
+
return args;
|
|
311
|
+
}
|
|
312
|
+
export const OMP_TODO_PROMPT_LINE = "For multi-step work, keep your plan in the todo tool; Paperclip shows it to the user live, so no separate checklist is needed.";
|
|
313
|
+
const OMP_HEARTBEAT_PROMPT_TEMPLATE = "You are agent {{agent.id}} ({{agent.name}}). Continue your Paperclip work under the execution contract in your system prompt.";
|
|
314
|
+
async function findOmpSessionFile(sessionDir, sessionId) {
|
|
315
|
+
const entries = await fs.readdir(sessionDir).catch(() => []);
|
|
316
|
+
const match = entries.find((entry) => entry.endsWith(`${sessionId}.jsonl`));
|
|
317
|
+
return match ? path.join(sessionDir, match) : null;
|
|
318
|
+
}
|
|
319
|
+
async function readOmpSessionBytes(sessionDir, sessionId) {
|
|
320
|
+
if (!sessionId)
|
|
321
|
+
return null;
|
|
322
|
+
const file = await findOmpSessionFile(sessionDir, sessionId);
|
|
323
|
+
if (!file)
|
|
324
|
+
return null;
|
|
325
|
+
const stats = await fs.stat(file).catch(() => null);
|
|
326
|
+
return stats?.isFile() ? stats.size : null;
|
|
327
|
+
}
|
|
328
|
+
async function buildPrompts(input) {
|
|
329
|
+
const templateData = {
|
|
330
|
+
agentId: input.agent.id,
|
|
331
|
+
companyId: input.agent.companyId,
|
|
332
|
+
runId: input.runId,
|
|
333
|
+
company: { id: input.agent.companyId },
|
|
334
|
+
agent: input.agent,
|
|
335
|
+
run: { id: input.runId, source: "on_demand" },
|
|
336
|
+
context: input.context,
|
|
337
|
+
};
|
|
338
|
+
const notes = [];
|
|
339
|
+
const instructionsPath = asString(input.config.instructionsFilePath, "").trim();
|
|
340
|
+
let instructions = "";
|
|
341
|
+
if (instructionsPath) {
|
|
342
|
+
const resolvedPath = path.resolve(input.cwd, instructionsPath);
|
|
343
|
+
try {
|
|
344
|
+
const contents = await fs.readFile(resolvedPath, "utf8");
|
|
345
|
+
instructions = joinPromptSections([
|
|
346
|
+
contents,
|
|
347
|
+
`The above agent instructions were loaded from ${resolvedPath}. Resolve relative file references from ${path.dirname(resolvedPath)}/.`,
|
|
348
|
+
]);
|
|
349
|
+
notes.push(`Loaded agent instructions from ${resolvedPath}`);
|
|
350
|
+
}
|
|
351
|
+
catch (error) {
|
|
352
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
353
|
+
await input.onLog("stderr", `[paperclip] Warning: could not read agent instructions file "${resolvedPath}": ${reason}\n`);
|
|
354
|
+
notes.push(`Configured instructionsFilePath ${resolvedPath}, but it could not be read.`);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
const contractTemplate = paperclipAgentPromptTemplate(input.paperclipAccess);
|
|
358
|
+
const paperclipContract = renderTemplate(contractTemplate, templateData);
|
|
359
|
+
const systemPrompt = joinPromptSections([instructions, paperclipContract, OMP_TODO_PROMPT_LINE]);
|
|
360
|
+
const promptTemplate = asString(input.config.promptTemplate, OMP_HEARTBEAT_PROMPT_TEMPLATE);
|
|
361
|
+
const bootstrapTemplate = asString(input.config.bootstrapPromptTemplate, "");
|
|
362
|
+
const bootstrapPrompt = !input.resumedSession && bootstrapTemplate.trim()
|
|
363
|
+
? renderTemplate(bootstrapTemplate, templateData).trim()
|
|
364
|
+
: "";
|
|
365
|
+
const taskContextNote = selectPaperclipTaskMarkdown(input.context, { resumedSession: input.resumedSession });
|
|
366
|
+
const wakePrompt = renderPaperclipWakePrompt(input.context.paperclipWake, {
|
|
367
|
+
resumedSession: input.resumedSession,
|
|
368
|
+
suppressIssueDescription: taskContextNote.length > 0,
|
|
369
|
+
paperclipAccess: input.paperclipAccess,
|
|
370
|
+
});
|
|
371
|
+
const wakePayload = parseObject(input.context.paperclipWake);
|
|
372
|
+
const recoveryWake = Object.keys(parseObject(wakePayload.recovery)).length > 0 ||
|
|
373
|
+
asString(wakePayload.reason, "").trim() === "source_scoped_recovery_action";
|
|
374
|
+
const heartbeatPrompt = ((input.resumedSession && wakePrompt.length > 0) || recoveryWake)
|
|
375
|
+
? ""
|
|
376
|
+
: renderTemplate(promptTemplate, templateData).trim();
|
|
377
|
+
const sessionHandoff = asString(input.context.paperclipSessionHandoffMarkdown, "").trim();
|
|
378
|
+
const userPrompt = joinPromptSections([
|
|
379
|
+
bootstrapPrompt,
|
|
380
|
+
wakePrompt,
|
|
381
|
+
sessionHandoff,
|
|
382
|
+
taskContextNote,
|
|
383
|
+
heartbeatPrompt,
|
|
384
|
+
]);
|
|
385
|
+
return {
|
|
386
|
+
systemPrompt,
|
|
387
|
+
userPrompt,
|
|
388
|
+
promptMetrics: {
|
|
389
|
+
systemPromptChars: systemPrompt.length,
|
|
390
|
+
instructionsChars: instructions.length,
|
|
391
|
+
promptChars: userPrompt.length,
|
|
392
|
+
bootstrapPromptChars: bootstrapPrompt.length,
|
|
393
|
+
wakePromptChars: wakePrompt.length,
|
|
394
|
+
sessionHandoffChars: sessionHandoff.length,
|
|
395
|
+
taskContextChars: taskContextNote.length,
|
|
396
|
+
heartbeatPromptChars: heartbeatPrompt.length,
|
|
397
|
+
},
|
|
398
|
+
notes,
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
export function applyOmpRuntimeToggleEnv(env, config) {
|
|
402
|
+
if (asBoolean(config.noPty, false))
|
|
403
|
+
env.PI_NO_PTY = "1";
|
|
404
|
+
else
|
|
405
|
+
delete env.PI_NO_PTY;
|
|
406
|
+
if (asBoolean(config.noTitle, true))
|
|
407
|
+
env.PI_NO_TITLE = "1";
|
|
408
|
+
else
|
|
409
|
+
delete env.PI_NO_TITLE;
|
|
410
|
+
env.OMP_MCP_STARTUP_TIMEOUT_MS = "0";
|
|
411
|
+
}
|
|
412
|
+
export function applyRuntimeToolAccess(env, tools, mcp) {
|
|
413
|
+
const sections = [];
|
|
414
|
+
if (tools) {
|
|
415
|
+
Object.assign(env, buildRuntimeToolsEnv(tools));
|
|
416
|
+
sections.push([
|
|
417
|
+
"Paperclip runtime tools are delivered through the environment of this run.",
|
|
418
|
+
`Bearer token: $PAPERCLIP_RUNTIME_TOOLS_TOKEN (valid until ${tools.expiresAt}).`,
|
|
419
|
+
`Search connections: POST $PAPERCLIP_RUNTIME_TOOLS_CONNECTIONS_SEARCH_URL`,
|
|
420
|
+
`Request a connection: POST $PAPERCLIP_RUNTIME_TOOLS_CONNECTION_REQUEST_URL`,
|
|
421
|
+
`MCP endpoint: $PAPERCLIP_RUNTIME_TOOLS_MCP_URL`,
|
|
422
|
+
"Send the bearer token as the Authorization header. Never print the token.",
|
|
423
|
+
].join("\n"));
|
|
424
|
+
}
|
|
425
|
+
const servers = mcp?.getServers() ?? [];
|
|
426
|
+
if (servers.length > 0) {
|
|
427
|
+
env.PAPERCLIP_RUNTIME_MCP_SERVERS = JSON.stringify(servers.map((server) => ({ name: server.name, url: server.url, connectionId: server.connectionId })));
|
|
428
|
+
env.PAPERCLIP_RUNTIME_MCP_TOKENS = JSON.stringify(Object.fromEntries(servers.map((server) => [server.name, server.token])));
|
|
429
|
+
sections.push([
|
|
430
|
+
`Paperclip provisioned ${servers.length} MCP server(s) for this run: ${servers.map((s) => s.name).join(", ")}.`,
|
|
431
|
+
"Endpoints are in $PAPERCLIP_RUNTIME_MCP_SERVERS and their bearer tokens in $PAPERCLIP_RUNTIME_MCP_TOKENS, keyed by server name.",
|
|
432
|
+
"OMP loads MCP servers from its agent directory, so reach these over HTTP for this run instead of expecting them in the tool list.",
|
|
433
|
+
].join("\n"));
|
|
434
|
+
}
|
|
435
|
+
return sections.join("\n\n");
|
|
436
|
+
}
|
|
437
|
+
export function applyPreparedOmpAgentEnvironment(env, prepared, agentDir = prepared.agentDir) {
|
|
438
|
+
if (agentDir)
|
|
439
|
+
env.PI_CODING_AGENT_DIR = agentDir;
|
|
440
|
+
if (!prepared.materialized && !(prepared.profileSpecified && prepared.profile === null))
|
|
441
|
+
return;
|
|
442
|
+
env.OMP_PROFILE = "";
|
|
443
|
+
env.PI_PROFILE = "";
|
|
444
|
+
}
|
|
445
|
+
export async function execute(ctx) {
|
|
446
|
+
const { runId, agent, runtime, config, context, onLog, onMeta, onSpawn, authToken } = ctx;
|
|
447
|
+
const executionTarget = readAdapterExecutionTarget({
|
|
448
|
+
executionTarget: ctx.executionTarget,
|
|
449
|
+
legacyRemoteExecution: ctx.executionTransport?.remoteExecution,
|
|
450
|
+
});
|
|
451
|
+
const remote = adapterExecutionTargetIsRemote(executionTarget);
|
|
452
|
+
const workspace = parseObject(context.paperclipWorkspace);
|
|
453
|
+
const workspaceCwd = asString(workspace.cwd, "").trim();
|
|
454
|
+
const workspaceSource = asString(workspace.source, "");
|
|
455
|
+
const configuredCwd = asString(config.cwd, "").trim();
|
|
456
|
+
const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0;
|
|
457
|
+
const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd;
|
|
458
|
+
const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd();
|
|
459
|
+
await ensureAbsoluteDirectory(cwd, { createIfMissing: true });
|
|
460
|
+
const preparedConfig = await prepareOmpRuntimeConfig(config, { forceMaterialized: remote });
|
|
461
|
+
const providerStop = createProviderStoppedBoundary(ctx.onProviderStopped);
|
|
462
|
+
let restoreWorkspace = null;
|
|
463
|
+
let paperclipBridge = null;
|
|
464
|
+
let settingsOverlay = null;
|
|
465
|
+
let mcpExtension = null;
|
|
466
|
+
let toolGuardExtension = null;
|
|
467
|
+
let pythonEnvBridge = null;
|
|
468
|
+
try {
|
|
469
|
+
await ensureOmpSkills(config, preparedConfig.agentDir ?? undefined);
|
|
470
|
+
const configuredEnv = parseObject(config.env);
|
|
471
|
+
const env = buildPaperclipEnv(agent, { sameHost: !remote }, ctx.agentIdentity);
|
|
472
|
+
addWakeEnvironment(env, runId, context);
|
|
473
|
+
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
|
|
474
|
+
? context.paperclipWorkspaces.filter((value) => value !== null && typeof value === "object" && !Array.isArray(value))
|
|
475
|
+
: [];
|
|
476
|
+
let effectiveExecutionCwd = executionTarget?.kind === "remote" ? executionTarget.remoteCwd : cwd;
|
|
477
|
+
refreshPaperclipWorkspaceEnvForExecution({
|
|
478
|
+
env,
|
|
479
|
+
envConfig: {},
|
|
480
|
+
workspaceCwd: effectiveWorkspaceCwd,
|
|
481
|
+
workspaceSource,
|
|
482
|
+
workspaceStrategy: asString(workspace.strategy, ""),
|
|
483
|
+
workspaceId: asString(workspace.workspaceId, ""),
|
|
484
|
+
workspaceRepoUrl: asString(workspace.repoUrl, ""),
|
|
485
|
+
workspaceRepoRef: asString(workspace.repoRef, ""),
|
|
486
|
+
workspaceBranch: asString(workspace.branch, ""),
|
|
487
|
+
workspaceWorktreePath: asString(workspace.worktreePath, ""),
|
|
488
|
+
workspaceHints,
|
|
489
|
+
agentHome: asString(workspace.agentHome, ""),
|
|
490
|
+
executionTargetIsRemote: remote,
|
|
491
|
+
executionCwd: effectiveExecutionCwd,
|
|
492
|
+
});
|
|
493
|
+
for (const [key, value] of Object.entries(configuredEnv)) {
|
|
494
|
+
if (typeof value !== "string")
|
|
495
|
+
continue;
|
|
496
|
+
if (isForbiddenConfigEnvKey(key))
|
|
497
|
+
continue;
|
|
498
|
+
if (isPaperclipRuntimeEnvKey(key) && Object.hasOwn(env, legacyEnvKey(key)))
|
|
499
|
+
continue;
|
|
500
|
+
env[key] = value;
|
|
501
|
+
}
|
|
502
|
+
if (!env.PAPERCLIP_API_KEY && authToken)
|
|
503
|
+
env.PAPERCLIP_API_KEY = authToken;
|
|
504
|
+
const runtimeToolGuidance = applyRuntimeToolAccess(env, ctx.runtimeTools, ctx.runtimeMcp);
|
|
505
|
+
applyPreparedOmpAgentEnvironment(env, preparedConfig);
|
|
506
|
+
const inheritedLocalEnv = stringsOnly(sanitizeInheritedPaperclipEnv(process.env));
|
|
507
|
+
applyPreparedOmpAgentEnvironment(inheritedLocalEnv, preparedConfig, null);
|
|
508
|
+
if (preparedConfig.materialized || (preparedConfig.profileSpecified && preparedConfig.profile === null)) {
|
|
509
|
+
inheritedLocalEnv.OMP_PROFILE = "";
|
|
510
|
+
inheritedLocalEnv.PI_PROFILE = "";
|
|
511
|
+
}
|
|
512
|
+
applyOmpRuntimeToggleEnv(env, config);
|
|
513
|
+
applyOmpRuntimeToggleEnv(inheritedLocalEnv, config);
|
|
514
|
+
const localRuntimeEnv = stringsOnly(ensurePathInEnv({ ...inheritedLocalEnv, ...env }));
|
|
515
|
+
const targetEnv = remote ? stringsOnly(ensurePathInEnv(env)) : localRuntimeEnv;
|
|
516
|
+
const command = resolveOmpCommand(config);
|
|
517
|
+
const timeoutSec = resolveAdapterExecutionTargetTimeoutSec(executionTarget, asNumber(config.timeoutSec, 43200));
|
|
518
|
+
const graceSec = asNumber(config.graceSec, 20);
|
|
519
|
+
await ensureAdapterExecutionTargetRuntimeCommandInstalled({
|
|
520
|
+
runId,
|
|
521
|
+
target: executionTarget,
|
|
522
|
+
installCommand: ctx.runtimeCommandSpec?.installCommand,
|
|
523
|
+
detectCommand: ctx.runtimeCommandSpec?.detectCommand ?? command,
|
|
524
|
+
cwd,
|
|
525
|
+
env: targetEnv,
|
|
526
|
+
timeoutSec,
|
|
527
|
+
graceSec,
|
|
528
|
+
onLog,
|
|
529
|
+
});
|
|
530
|
+
await ensureAdapterExecutionTargetCommandResolvable(command, executionTarget, cwd, targetEnv, {
|
|
531
|
+
installCommand: OMP_INSTALL_COMMAND,
|
|
532
|
+
timeoutSec,
|
|
533
|
+
});
|
|
534
|
+
let runtimeRootDir = null;
|
|
535
|
+
let executionConfig = config;
|
|
536
|
+
if (remote) {
|
|
537
|
+
await onLog("stdout", `[paperclip] Syncing workspace and OMP runtime assets to ${describeAdapterExecutionTarget(executionTarget)}.\n`);
|
|
538
|
+
const preparedTarget = await prepareAdapterExecutionTargetRuntime({
|
|
539
|
+
runId,
|
|
540
|
+
target: executionTarget,
|
|
541
|
+
adapterKey: "omp",
|
|
542
|
+
workspaceLocalDir: cwd,
|
|
543
|
+
timeoutSec,
|
|
544
|
+
installCommand: ctx.runtimeCommandSpec?.installCommand ?? OMP_INSTALL_COMMAND,
|
|
545
|
+
detectCommand: ctx.runtimeCommandSpec?.detectCommand ?? command,
|
|
546
|
+
onProgress: (line) => onLog("stdout", line),
|
|
547
|
+
onRuntimeProgress: ctx.onRuntimeProgress,
|
|
548
|
+
assets: preparedConfig.agentDir
|
|
549
|
+
? [{ key: "agentDir", localDir: preparedConfig.agentDir, followSymlinks: true }]
|
|
550
|
+
: [],
|
|
551
|
+
});
|
|
552
|
+
restoreWorkspace = () => preparedTarget.restoreWorkspace((line) => onLog("stdout", line));
|
|
553
|
+
effectiveExecutionCwd = preparedTarget.workspaceRemoteDir ?? effectiveExecutionCwd;
|
|
554
|
+
executionConfig = { ...rewriteRemoteConfigPaths(config, cwd, effectiveExecutionCwd), noSession: true };
|
|
555
|
+
runtimeRootDir = preparedTarget.runtimeRootDir;
|
|
556
|
+
applyPreparedOmpAgentEnvironment(env, preparedConfig, preparedTarget.assetDirs.agentDir ?? null);
|
|
557
|
+
if (adapterExecutionTargetUsesManagedHome(executionTarget) && runtimeRootDir)
|
|
558
|
+
env.HOME = runtimeRootDir;
|
|
559
|
+
refreshPaperclipWorkspaceEnvForExecution({
|
|
560
|
+
env,
|
|
561
|
+
envConfig: {},
|
|
562
|
+
workspaceCwd: effectiveWorkspaceCwd,
|
|
563
|
+
workspaceSource,
|
|
564
|
+
workspaceStrategy: asString(workspace.strategy, ""),
|
|
565
|
+
workspaceId: asString(workspace.workspaceId, ""),
|
|
566
|
+
workspaceRepoUrl: asString(workspace.repoUrl, ""),
|
|
567
|
+
workspaceRepoRef: asString(workspace.repoRef, ""),
|
|
568
|
+
workspaceBranch: asString(workspace.branch, ""),
|
|
569
|
+
workspaceWorktreePath: asString(workspace.worktreePath, ""),
|
|
570
|
+
workspaceHints,
|
|
571
|
+
agentHome: asString(workspace.agentHome, ""),
|
|
572
|
+
executionTargetIsRemote: true,
|
|
573
|
+
executionCwd: effectiveExecutionCwd,
|
|
574
|
+
});
|
|
575
|
+
applyPreparedOmpAgentEnvironment(env, preparedConfig, preparedTarget.assetDirs.agentDir ?? null);
|
|
576
|
+
}
|
|
577
|
+
const runtimeTarget = overrideAdapterExecutionTargetRemoteCwd(executionTarget, effectiveExecutionCwd);
|
|
578
|
+
if (remote && adapterExecutionTargetUsesPaperclipBridge(runtimeTarget)) {
|
|
579
|
+
paperclipBridge = await startAdapterExecutionTargetPaperclipBridge({
|
|
580
|
+
runId,
|
|
581
|
+
target: runtimeTarget,
|
|
582
|
+
runtimeRootDir,
|
|
583
|
+
adapterKey: "omp",
|
|
584
|
+
timeoutSec,
|
|
585
|
+
hostApiToken: env.PAPERCLIP_API_KEY,
|
|
586
|
+
hostApiUrl: env.PAPERCLIP_API_URL,
|
|
587
|
+
onLog,
|
|
588
|
+
});
|
|
589
|
+
if (paperclipBridge)
|
|
590
|
+
Object.assign(env, paperclipBridge.env);
|
|
591
|
+
}
|
|
592
|
+
const omitProfile = preparedConfig.materialized || (preparedConfig.profileSpecified && preparedConfig.profile === null);
|
|
593
|
+
const invocationEnv = remote ? stringsOnly(ensurePathInEnv(env)) : localRuntimeEnv;
|
|
594
|
+
if (remote)
|
|
595
|
+
applyPreparedOmpAgentEnvironment(invocationEnv, preparedConfig, env.PI_CODING_AGENT_DIR ?? null);
|
|
596
|
+
const resolvedCommand = await resolveAdapterExecutionTargetCommandForLogs(command, runtimeTarget, cwd, invocationEnv);
|
|
597
|
+
const loggedEnv = buildInvocationEnvForLogs(env, {
|
|
598
|
+
runtimeEnv: invocationEnv,
|
|
599
|
+
includeRuntimeKeys: ["HOME"],
|
|
600
|
+
resolvedCommand,
|
|
601
|
+
});
|
|
602
|
+
const runtimeParams = parseObject(runtime.sessionParams);
|
|
603
|
+
const savedSessionId = asString(runtimeParams.sessionId, runtime.sessionId ?? "").trim();
|
|
604
|
+
const savedCwd = asString(runtimeParams.cwd, "").trim();
|
|
605
|
+
const savedSessionDir = asString(runtimeParams.sessionDir, "").trim();
|
|
606
|
+
const savedRemoteExecution = parseObject(runtimeParams.remoteExecution);
|
|
607
|
+
const ephemeralSession = asBoolean(executionConfig.noSession, false);
|
|
608
|
+
const canResume = Boolean(!ephemeralSession &&
|
|
609
|
+
savedSessionId &&
|
|
610
|
+
(!savedCwd || executionCwdsMatch(savedCwd, effectiveExecutionCwd, remote)) &&
|
|
611
|
+
adapterExecutionTargetSessionMatches(savedRemoteExecution, runtimeTarget));
|
|
612
|
+
if (savedSessionId && !canResume) {
|
|
613
|
+
await onLog("stdout", `[paperclip] OMP session "${savedSessionId}" does not match the current workspace or execution target; starting fresh.\n`);
|
|
614
|
+
}
|
|
615
|
+
const configuredSessionDir = asString(executionConfig.sessionDir, "").trim();
|
|
616
|
+
const defaultSessionDir = remote
|
|
617
|
+
? path.posix.join(runtimeRootDir ?? path.posix.join(effectiveExecutionCwd, ".paperclip-runtime", "omp"), "sessions", safePathSegment(agent.id))
|
|
618
|
+
: path.join(os.homedir(), ".omp", "paperclip", "sessions", safePathSegment(agent.id));
|
|
619
|
+
const sessionDir = canResume && savedSessionDir
|
|
620
|
+
? savedSessionDir
|
|
621
|
+
: configuredSessionDir || defaultSessionDir;
|
|
622
|
+
if (!ephemeralSession) {
|
|
623
|
+
await ensureAdapterExecutionTargetDirectory(runId, runtimeTarget, sessionDir, {
|
|
624
|
+
cwd,
|
|
625
|
+
env: invocationEnv,
|
|
626
|
+
timeoutSec: Math.min(timeoutSec || 15, 15),
|
|
627
|
+
graceSec: Math.min(graceSec, 5),
|
|
628
|
+
onLog,
|
|
629
|
+
createIfMissing: true,
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
settingsOverlay = await writeOmpSettingsOverlay({
|
|
633
|
+
runId,
|
|
634
|
+
target: runtimeTarget,
|
|
635
|
+
remote,
|
|
636
|
+
config: executionConfig,
|
|
637
|
+
remoteRootDir: runtimeRootDir,
|
|
638
|
+
cwd: remote ? effectiveExecutionCwd : cwd,
|
|
639
|
+
env: invocationEnv,
|
|
640
|
+
timeoutSec,
|
|
641
|
+
graceSec,
|
|
642
|
+
});
|
|
643
|
+
const fallbackChain = ompFallbackChain(executionConfig);
|
|
644
|
+
const rpcActive = ompRpcSteeringEnabled(executionConfig) && adapterExecutionTargetSupportsLiveStdin(runtimeTarget);
|
|
645
|
+
const mcpToolsets = paperclipMcpToolsets(executionConfig);
|
|
646
|
+
const mcpEnabled = asBoolean(executionConfig.paperclipMcp, true);
|
|
647
|
+
const mcpTransport = paperclipMcpTransport(executionConfig);
|
|
648
|
+
const mcpCommand = remote || mcpTransport === "http"
|
|
649
|
+
? { command: PAPERCLIP_MCP_BIN, args: ["--toolsets", mcpToolsets], source: "path" }
|
|
650
|
+
: resolvePaperclipMcpServerCommand();
|
|
651
|
+
const mcpApiKey = asString(invocationEnv.PAPERCLIP_API_KEY, "").trim();
|
|
652
|
+
const mcpEndpoint = paperclipMcpEndpoint(asString(invocationEnv.PAPERCLIP_API_URL, ""), mcpToolsets);
|
|
653
|
+
let mcpProbe = null;
|
|
654
|
+
if (mcpEnabled && mcpApiKey && (mcpTransport === "http" || !remote)) {
|
|
655
|
+
mcpProbe = mcpTransport === "http"
|
|
656
|
+
? await probePaperclipMcpEndpoint({
|
|
657
|
+
url: mcpEndpoint,
|
|
658
|
+
apiKey: mcpApiKey,
|
|
659
|
+
runId: asString(invocationEnv.PAPERCLIP_RUN_ID, runId),
|
|
660
|
+
})
|
|
661
|
+
: await probePaperclipMcpServer({
|
|
662
|
+
command: mcpCommand,
|
|
663
|
+
env: { ...invocationEnv, [PAPERCLIP_MCP_TOOLSETS_ENV]: mcpToolsets },
|
|
664
|
+
});
|
|
665
|
+
if (!mcpProbe.ok) {
|
|
666
|
+
const source = mcpTransport === "http" ? mcpEndpoint : mcpCommand.command;
|
|
667
|
+
const message = mcpProbe.credentialRejected
|
|
668
|
+
? `Paperclip MCP endpoint (${source}) rejected this run's credentials: ${mcpProbe.detail}`
|
|
669
|
+
: `Paperclip MCP ${mcpTransport === "http" ? "endpoint" : "server"} (${source}) is unavailable: ${mcpProbe.detail}`;
|
|
670
|
+
await onLog("stderr", `[paperclip] ${message}\n`);
|
|
671
|
+
return {
|
|
672
|
+
exitCode: 1,
|
|
673
|
+
signal: null,
|
|
674
|
+
timedOut: false,
|
|
675
|
+
errorMessage: message,
|
|
676
|
+
...(mcpProbe.credentialRejected
|
|
677
|
+
? { errorCode: PAPERCLIP_MCP_CREDENTIAL_CODE }
|
|
678
|
+
: {
|
|
679
|
+
errorCode: PAPERCLIP_MCP_UNAVAILABLE_CODE,
|
|
680
|
+
...(mcpProbe.transient ? paperclipMcpUnavailableRecovery() : {}),
|
|
681
|
+
}),
|
|
682
|
+
usageComplete: true,
|
|
683
|
+
usageBasis: "per_run",
|
|
684
|
+
costStatus: "unpriced",
|
|
685
|
+
costUsd: null,
|
|
686
|
+
sessionId: null,
|
|
687
|
+
sessionParams: null,
|
|
688
|
+
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
689
|
+
resultJson: {
|
|
690
|
+
capabilityManifest: rpcActive ? RPC_CAPABILITY_MANIFEST : CAPABILITY_MANIFEST,
|
|
691
|
+
paperclipMcp: {
|
|
692
|
+
transport: mcpTransport,
|
|
693
|
+
source,
|
|
694
|
+
toolsets: mcpToolsets,
|
|
695
|
+
detail: mcpProbe.detail,
|
|
696
|
+
durationMs: mcpProbe.durationMs,
|
|
697
|
+
},
|
|
698
|
+
},
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
if (mcpEnabled && !mcpApiKey) {
|
|
703
|
+
await onLog("stderr", "[paperclip] Warning: this run carries no Paperclip API key, so the Paperclip MCP tools are not armed.\n");
|
|
704
|
+
}
|
|
705
|
+
if (!mcpEnabled) {
|
|
706
|
+
await onLog("stderr", "[paperclip] Warning: paperclipMcp is off for this agent. The agent has no Paperclip tools this run and cannot read issues, comment, or update status.\n");
|
|
707
|
+
}
|
|
708
|
+
if (mcpApiKey) {
|
|
709
|
+
mcpExtension = await writePaperclipMcpExtension({
|
|
710
|
+
runId,
|
|
711
|
+
target: runtimeTarget,
|
|
712
|
+
remote,
|
|
713
|
+
enabled: mcpEnabled,
|
|
714
|
+
transport: mcpTransport,
|
|
715
|
+
toolsets: mcpToolsets,
|
|
716
|
+
command: mcpCommand,
|
|
717
|
+
env: invocationEnv,
|
|
718
|
+
remoteRootDir: runtimeRootDir,
|
|
719
|
+
cwd: remote ? effectiveExecutionCwd : cwd,
|
|
720
|
+
timeoutSec,
|
|
721
|
+
graceSec,
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
toolGuardExtension = await writeOmpToolGuardExtension({
|
|
725
|
+
runId,
|
|
726
|
+
target: runtimeTarget,
|
|
727
|
+
remote,
|
|
728
|
+
env: invocationEnv,
|
|
729
|
+
remoteRootDir: runtimeRootDir,
|
|
730
|
+
cwd: remote ? effectiveExecutionCwd : cwd,
|
|
731
|
+
timeoutSec,
|
|
732
|
+
graceSec,
|
|
733
|
+
profile: runToolProfile(context),
|
|
734
|
+
});
|
|
735
|
+
pythonEnvBridge = await writeOmpPythonEnvBridge({
|
|
736
|
+
runId,
|
|
737
|
+
target: runtimeTarget,
|
|
738
|
+
remote,
|
|
739
|
+
env: invocationEnv,
|
|
740
|
+
remoteRootDir: runtimeRootDir,
|
|
741
|
+
cwd: remote ? effectiveExecutionCwd : cwd,
|
|
742
|
+
timeoutSec,
|
|
743
|
+
graceSec,
|
|
744
|
+
});
|
|
745
|
+
if (!remote) {
|
|
746
|
+
invocationEnv.PYTHONPATH = prependPythonPath(pythonEnvBridge.dir, invocationEnv.PYTHONPATH, path.delimiter);
|
|
747
|
+
}
|
|
748
|
+
const launchOmp = pythonEnvBridge.launch;
|
|
749
|
+
const mcpArmed = mcpEnabled && mcpExtension !== null;
|
|
750
|
+
const paperclipAccess = mcpArmed ? "mcp" : "rest";
|
|
751
|
+
const prompts = await buildPrompts({
|
|
752
|
+
config: executionConfig,
|
|
753
|
+
context,
|
|
754
|
+
agent,
|
|
755
|
+
runId,
|
|
756
|
+
resumedSession: canResume,
|
|
757
|
+
cwd,
|
|
758
|
+
paperclipAccess,
|
|
759
|
+
onLog,
|
|
760
|
+
});
|
|
761
|
+
prompts.systemPrompt = joinPromptSections([
|
|
762
|
+
prompts.systemPrompt,
|
|
763
|
+
runtimeToolGuidance,
|
|
764
|
+
mcpArmed
|
|
765
|
+
? paperclipMcpGuidance(mcpToolsets, mcpProbe?.toolCount ?? null)
|
|
766
|
+
: paperclipRestGuidance(),
|
|
767
|
+
]);
|
|
768
|
+
prompts.promptMetrics.systemPromptChars = prompts.systemPrompt.length;
|
|
769
|
+
const commandNotes = [
|
|
770
|
+
...preparedConfig.notes,
|
|
771
|
+
...prompts.notes,
|
|
772
|
+
canResume ? `Resuming OMP session ${savedSessionId}` : `Using fresh OMP session directory ${sessionDir}`,
|
|
773
|
+
...(remote ? ["Remote execution uses an ephemeral OMP session; remote runtime directories are per run."] : []),
|
|
774
|
+
rpcActive
|
|
775
|
+
? "OMP runs in RPC mode: the prompt travels on stdin and same-turn steering is available for this run."
|
|
776
|
+
: "OMP runs in one-shot print mode; same-turn steering is unavailable for this run.",
|
|
777
|
+
mcpArmed
|
|
778
|
+
? `Paperclip MCP server armed from ${mcpCommand.source === "path" ? PAPERCLIP_MCP_BIN : mcpCommand.command} with toolsets ${mcpToolsets}${mcpProbe ? ` (${mcpProbe.toolCount ?? 0} tools, handshake ${mcpProbe.durationMs}ms)` : ""}`
|
|
779
|
+
: mcpEnabled
|
|
780
|
+
? "Paperclip MCP server not armed: this run has no Paperclip API key."
|
|
781
|
+
: "Paperclip MCP server disabled by adapter configuration; the agent has no Paperclip tools this run.",
|
|
782
|
+
];
|
|
783
|
+
const runAttempt = async (resumeSessionId) => {
|
|
784
|
+
const args = buildOmpArgs({
|
|
785
|
+
config: executionConfig,
|
|
786
|
+
context,
|
|
787
|
+
cwd,
|
|
788
|
+
systemPrompt: prompts.systemPrompt,
|
|
789
|
+
userPrompt: prompts.userPrompt,
|
|
790
|
+
sessionDir,
|
|
791
|
+
resumeSessionId,
|
|
792
|
+
omitProfile,
|
|
793
|
+
effectiveProfile: preparedConfig.profile,
|
|
794
|
+
settingsOverlayPath: settingsOverlay?.path ?? null,
|
|
795
|
+
mcpExtensionPath: mcpExtension?.path ?? null,
|
|
796
|
+
toolGuardExtensionPath: toolGuardExtension?.path ?? null,
|
|
797
|
+
rpc: rpcActive,
|
|
798
|
+
});
|
|
799
|
+
if (onMeta) {
|
|
800
|
+
await onMeta({
|
|
801
|
+
adapterType: "omp_local",
|
|
802
|
+
command: resolvedCommand,
|
|
803
|
+
cwd: effectiveExecutionCwd,
|
|
804
|
+
commandArgs: rpcActive
|
|
805
|
+
? args
|
|
806
|
+
: args.map((value, index) => index === args.length - 1 ? `<prompt ${prompts.userPrompt.length} chars>` : value),
|
|
807
|
+
commandNotes,
|
|
808
|
+
env: loggedEnv,
|
|
809
|
+
prompt: prompts.userPrompt,
|
|
810
|
+
promptMetrics: prompts.promptMetrics,
|
|
811
|
+
context,
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
let stdoutBuffer = "";
|
|
815
|
+
let reporterFailed = false;
|
|
816
|
+
let logQueue = Promise.resolve();
|
|
817
|
+
const queueLog = (stream, chunk) => {
|
|
818
|
+
logQueue = logQueue.then(() => onLog(stream, chunk)).catch(() => { });
|
|
819
|
+
return logQueue;
|
|
820
|
+
};
|
|
821
|
+
const reporter = createOmpProgressReporter(ctx.onRuntimeProgress, ctx.onEvent);
|
|
822
|
+
const accumulator = createOmpOutputAccumulator();
|
|
823
|
+
const fallbackTracker = fallbackChain
|
|
824
|
+
? createOmpModelFallbackTracker({
|
|
825
|
+
primary: asString(context.paperclipPrimaryModel, "").trim() || fallbackChain.key,
|
|
826
|
+
start: fallbackChain.key,
|
|
827
|
+
emit: ctx.onEvent,
|
|
828
|
+
})
|
|
829
|
+
: null;
|
|
830
|
+
const ingestLine = async (line) => {
|
|
831
|
+
const trimmed = line.trim();
|
|
832
|
+
if (!trimmed)
|
|
833
|
+
return;
|
|
834
|
+
const event = parseOmpJsonLine(trimmed);
|
|
835
|
+
accumulator.push(trimmed, event);
|
|
836
|
+
await fallbackTracker?.ingest(event);
|
|
837
|
+
try {
|
|
838
|
+
await reporter.ingest(trimmed, event);
|
|
839
|
+
}
|
|
840
|
+
catch {
|
|
841
|
+
reporterFailed = true;
|
|
842
|
+
}
|
|
843
|
+
};
|
|
844
|
+
let mcpConnectFailed = false;
|
|
845
|
+
let mcpConnectTransient = false;
|
|
846
|
+
let stdoutTranscript = "";
|
|
847
|
+
const bufferedOnLog = async (stream, chunk) => {
|
|
848
|
+
const connectFailure = mcpArmed && !mcpConnectFailed ? PAPERCLIP_MCP_CONNECT_FAILURE_RE.exec(chunk) : null;
|
|
849
|
+
if (connectFailure) {
|
|
850
|
+
mcpConnectFailed = true;
|
|
851
|
+
const lineEnd = chunk.indexOf("\n", connectFailure.index);
|
|
852
|
+
mcpConnectTransient = PAPERCLIP_MCP_TRANSIENT_FAILURE_RE.test(chunk.slice(connectFailure.index, lineEnd < 0 ? undefined : lineEnd));
|
|
853
|
+
await queueLog("stderr", "[paperclip] The Paperclip MCP server did not connect, so the agent has no Paperclip tools. Stopping the run.\n");
|
|
854
|
+
triggerProcessAbort();
|
|
855
|
+
}
|
|
856
|
+
if (stream === "stderr") {
|
|
857
|
+
await queueLog(stream, chunk);
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
stdoutBuffer += chunk;
|
|
861
|
+
let newline = stdoutBuffer.indexOf("\n");
|
|
862
|
+
while (newline >= 0) {
|
|
863
|
+
const completeLine = stdoutBuffer.slice(0, newline + 1);
|
|
864
|
+
stdoutBuffer = stdoutBuffer.slice(newline + 1);
|
|
865
|
+
await queueLog("stdout", completeLine);
|
|
866
|
+
await ingestLine(completeLine);
|
|
867
|
+
stdoutTranscript = appendWithCap(stdoutTranscript, completeLine, RESULT_TRANSCRIPT_MAX_CHARS);
|
|
868
|
+
newline = stdoutBuffer.indexOf("\n");
|
|
869
|
+
}
|
|
870
|
+
};
|
|
871
|
+
let spawnedPgid = null;
|
|
872
|
+
let spawnedPid = null;
|
|
873
|
+
let abortHandler = null;
|
|
874
|
+
const handleSpawn = async (meta) => {
|
|
875
|
+
spawnedPid = meta.pid;
|
|
876
|
+
spawnedPgid = meta.processGroupId;
|
|
877
|
+
if (onSpawn)
|
|
878
|
+
await onSpawn(meta);
|
|
879
|
+
if (ctx.signal?.aborted) {
|
|
880
|
+
triggerProcessAbort();
|
|
881
|
+
}
|
|
882
|
+
};
|
|
883
|
+
const triggerProcessAbort = () => {
|
|
884
|
+
try {
|
|
885
|
+
if (spawnedPgid && spawnedPgid > 0) {
|
|
886
|
+
process.kill(-spawnedPgid, "SIGINT");
|
|
887
|
+
}
|
|
888
|
+
else if (spawnedPid && spawnedPid > 0) {
|
|
889
|
+
process.kill(spawnedPid, "SIGINT");
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
catch {
|
|
893
|
+
}
|
|
894
|
+
};
|
|
895
|
+
if (ctx.signal) {
|
|
896
|
+
abortHandler = () => triggerProcessAbort();
|
|
897
|
+
if (ctx.signal.aborted) {
|
|
898
|
+
triggerProcessAbort();
|
|
899
|
+
}
|
|
900
|
+
else {
|
|
901
|
+
ctx.signal.addEventListener("abort", abortHandler, { once: true });
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
await ctx.onCancellationReady?.();
|
|
905
|
+
let proc;
|
|
906
|
+
let rpcSessionId = null;
|
|
907
|
+
let rpcPromptError = null;
|
|
908
|
+
let rpcProtocolVersion = null;
|
|
909
|
+
const steerSession = rpcActive ? createOmpRpcSteerSession() : null;
|
|
910
|
+
const releaseSteerTarget = steerSession
|
|
911
|
+
? registerAdapterSteerTarget(runId, steerSession)
|
|
912
|
+
: null;
|
|
913
|
+
const consumeAccounting = createOmpJsonlParser();
|
|
914
|
+
let retainedAccounting = consumeAccounting("");
|
|
915
|
+
const accountingLog = createUsageCheckpointLog(bufferedOnLog, ctx.onUsage ?? undefined, stdout => {
|
|
916
|
+
retainedAccounting = consumeAccounting(stdout);
|
|
917
|
+
const parsed = retainedAccounting;
|
|
918
|
+
const provider = parsed.provider ?? configuredModelProvider(asString(executionConfig.model, "").trim());
|
|
919
|
+
const model = parsed.model ?? (asString(executionConfig.model, "").trim() || null);
|
|
920
|
+
const hasCompleteAccounting = parsed.usageComplete || parsed.costUsd != null;
|
|
921
|
+
return {
|
|
922
|
+
usage: parsed.usageReported ? (parsed.usage ?? undefined) : undefined,
|
|
923
|
+
usageBasis: "per_run",
|
|
924
|
+
provider,
|
|
925
|
+
biller: resolveBiller(invocationEnv, provider),
|
|
926
|
+
billingType: "unknown",
|
|
927
|
+
model,
|
|
928
|
+
costUsd: parsed.costUsd,
|
|
929
|
+
costStatus: hasCompleteAccounting ? undefined : "unpriced",
|
|
930
|
+
complete: parsed.usageComplete,
|
|
931
|
+
};
|
|
932
|
+
});
|
|
933
|
+
const launch = launchOmp(command, args);
|
|
934
|
+
try {
|
|
935
|
+
if (rpcActive && steerSession) {
|
|
936
|
+
const rpcRun = await runOmpRpcSession({
|
|
937
|
+
runId,
|
|
938
|
+
command: launch.command,
|
|
939
|
+
args: launch.args,
|
|
940
|
+
cwd,
|
|
941
|
+
env: invocationEnv,
|
|
942
|
+
timeoutSec,
|
|
943
|
+
graceSec,
|
|
944
|
+
prompt: prompts.userPrompt,
|
|
945
|
+
runtimeTarget,
|
|
946
|
+
onLog: accountingLog,
|
|
947
|
+
onSpawn: handleSpawn,
|
|
948
|
+
onRuntimeProgress: ctx.onRuntimeProgress,
|
|
949
|
+
session: steerSession,
|
|
950
|
+
onProcessStopped: providerStop.beginInvocation(),
|
|
951
|
+
});
|
|
952
|
+
proc = rpcRun.proc;
|
|
953
|
+
if (rpcRun.sessionId)
|
|
954
|
+
rpcSessionId = rpcRun.sessionId;
|
|
955
|
+
rpcPromptError = rpcRun.promptError;
|
|
956
|
+
rpcProtocolVersion = rpcRun.protocolVersion;
|
|
957
|
+
}
|
|
958
|
+
else {
|
|
959
|
+
proc = await runAdapterExecutionTargetProcess(runId, runtimeTarget, launch.command, launch.args, {
|
|
960
|
+
onProcessStopped: providerStop.beginInvocation(),
|
|
961
|
+
cwd,
|
|
962
|
+
env: invocationEnv,
|
|
963
|
+
timeoutSec,
|
|
964
|
+
graceSec,
|
|
965
|
+
onSpawn: handleSpawn,
|
|
966
|
+
onRuntimeProgress: ctx.onRuntimeProgress,
|
|
967
|
+
onLog: accountingLog,
|
|
968
|
+
runLogTail: paperclipBridge?.runLogTail,
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
if (stdoutBuffer) {
|
|
972
|
+
await queueLog("stdout", stdoutBuffer);
|
|
973
|
+
await ingestLine(stdoutBuffer);
|
|
974
|
+
}
|
|
975
|
+
await logQueue;
|
|
976
|
+
await accountingLog.flush();
|
|
977
|
+
await accountingLog.flush({
|
|
978
|
+
complete: proc.exitCode === 0 && !proc.timedOut && !proc.signal
|
|
979
|
+
&& (retainedAccounting.usageComplete || retainedAccounting.costUsd != null),
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
finally {
|
|
983
|
+
releaseSteerTarget?.();
|
|
984
|
+
if (ctx.signal && abortHandler) {
|
|
985
|
+
ctx.signal.removeEventListener("abort", abortHandler);
|
|
986
|
+
}
|
|
987
|
+
try {
|
|
988
|
+
await reporter.flush();
|
|
989
|
+
}
|
|
990
|
+
catch {
|
|
991
|
+
reporterFailed = true;
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
return {
|
|
995
|
+
proc,
|
|
996
|
+
parsed: accumulator.result(),
|
|
997
|
+
pendingToolCount: reporter.pendingToolCount(),
|
|
998
|
+
sawProviderWork: reporter.sawProviderWork(),
|
|
999
|
+
reporterFailed,
|
|
1000
|
+
mcpConnectFailed,
|
|
1001
|
+
mcpConnectTransient,
|
|
1002
|
+
rpcSessionId,
|
|
1003
|
+
rpcPromptError,
|
|
1004
|
+
rpcProtocolVersion,
|
|
1005
|
+
stdoutTranscript,
|
|
1006
|
+
modelFallback: fallbackTracker?.snapshot() ?? null,
|
|
1007
|
+
accounting: retainedAccounting,
|
|
1008
|
+
};
|
|
1009
|
+
};
|
|
1010
|
+
const toResult = (attempt, retriedFresh, priorAttempt) => {
|
|
1011
|
+
const parsedError = attempt.parsed.errors.find((error) => error.trim()) ?? "";
|
|
1012
|
+
const rpcPromptError = attempt.rpcPromptError ?? "";
|
|
1013
|
+
const stderrLine = firstNonEmptyLine(attempt.proc.stderr);
|
|
1014
|
+
const processExitCode = attempt.proc.exitCode ?? (attempt.proc.signal ? 1 : 0);
|
|
1015
|
+
const effectiveExitCode = processExitCode === 0 && (parsedError || rpcPromptError) ? 1 : processExitCode;
|
|
1016
|
+
const resolvedSessionId = ephemeralSession
|
|
1017
|
+
? null
|
|
1018
|
+
: attempt.rpcSessionId
|
|
1019
|
+
?? attempt.parsed.sessionId
|
|
1020
|
+
?? (!retriedFresh ? savedSessionId || null : null);
|
|
1021
|
+
const remoteExecution = remote ? adapterExecutionTargetSessionIdentity(runtimeTarget) : null;
|
|
1022
|
+
const sessionParams = resolvedSessionId
|
|
1023
|
+
? {
|
|
1024
|
+
sessionId: resolvedSessionId,
|
|
1025
|
+
cwd: effectiveExecutionCwd,
|
|
1026
|
+
sessionDir,
|
|
1027
|
+
...(remoteExecution ? { remoteExecution } : {}),
|
|
1028
|
+
}
|
|
1029
|
+
: null;
|
|
1030
|
+
const provider = attempt.parsed.provider ?? configuredModelProvider(asString(executionConfig.model, "").trim());
|
|
1031
|
+
const model = attempt.parsed.model ?? (asString(executionConfig.model, "").trim() || null);
|
|
1032
|
+
const mcpFailure = attempt.mcpConnectFailed
|
|
1033
|
+
? `Paperclip MCP server "${PAPERCLIP_MCP_SERVER_NAME}" failed to connect; the agent had no Paperclip tools.`
|
|
1034
|
+
: "";
|
|
1035
|
+
const fallbackError = mcpFailure || rpcPromptError || parsedError || stderrLine || `OMP exited with code ${effectiveExitCode}.`;
|
|
1036
|
+
const failed = effectiveExitCode !== 0 || attempt.proc.timedOut || attempt.mcpConnectFailed;
|
|
1037
|
+
const classification = failed
|
|
1038
|
+
? classifyOmpFailure({
|
|
1039
|
+
parsedError: rpcPromptError || parsedError,
|
|
1040
|
+
stderr: attempt.proc.stderr,
|
|
1041
|
+
timedOut: attempt.proc.timedOut,
|
|
1042
|
+
exitCode: effectiveExitCode,
|
|
1043
|
+
signal: attempt.proc.signal,
|
|
1044
|
+
})
|
|
1045
|
+
: { errorCode: null, errorFamily: null, retryNotBefore: null };
|
|
1046
|
+
const failureContract = attempt.mcpConnectFailed
|
|
1047
|
+
? {
|
|
1048
|
+
errorCode: PAPERCLIP_MCP_UNAVAILABLE_CODE,
|
|
1049
|
+
errorFamily: null,
|
|
1050
|
+
retryNotBefore: null,
|
|
1051
|
+
...(attempt.mcpConnectTransient ? paperclipMcpUnavailableRecovery() : {}),
|
|
1052
|
+
}
|
|
1053
|
+
: classification;
|
|
1054
|
+
const cancelled = ctx.signal?.aborted === true && (failed || attempt.proc.signal !== null);
|
|
1055
|
+
const executionRecovery = cancelled && resolvedSessionId && attempt.pendingToolCount === 0
|
|
1056
|
+
? { kind: "interrupted", providerStopped: true, sessionPreserved: true, actionOutcomes: "settled" }
|
|
1057
|
+
: !attempt.sawProviderWork && failed
|
|
1058
|
+
? { kind: "bootstrap", providerWorkStarted: false }
|
|
1059
|
+
: null;
|
|
1060
|
+
const accounting = attempt.accounting;
|
|
1061
|
+
const hasCompleteAccounting = accounting.usageComplete || accounting.costUsd != null;
|
|
1062
|
+
const usageComplete = accounting.usageReported && hasCompleteAccounting
|
|
1063
|
+
&& !attempt.proc.timedOut && !attempt.proc.signal && attempt.proc.exitCode === 0;
|
|
1064
|
+
const result = {
|
|
1065
|
+
exitCode: effectiveExitCode,
|
|
1066
|
+
signal: attempt.proc.signal,
|
|
1067
|
+
timedOut: attempt.proc.timedOut,
|
|
1068
|
+
errorMessage: attempt.proc.timedOut
|
|
1069
|
+
? `Timed out after ${timeoutSec}s`
|
|
1070
|
+
: failed
|
|
1071
|
+
? fallbackError
|
|
1072
|
+
: null,
|
|
1073
|
+
...(failureContract.errorCode ? { errorCode: failureContract.errorCode } : {}),
|
|
1074
|
+
...(failureContract.errorFamily ? { errorFamily: failureContract.errorFamily } : {}),
|
|
1075
|
+
...(failureContract.retryNotBefore ? { retryNotBefore: failureContract.retryNotBefore } : {}),
|
|
1076
|
+
...(executionRecovery ? { executionRecovery } : {}),
|
|
1077
|
+
usage: accounting.usageReported ? (accounting.usage ?? undefined) : undefined,
|
|
1078
|
+
usageComplete,
|
|
1079
|
+
usageBasis: "per_run",
|
|
1080
|
+
sessionId: resolvedSessionId,
|
|
1081
|
+
sessionParams,
|
|
1082
|
+
sessionDisplayId: resolvedSessionId,
|
|
1083
|
+
provider,
|
|
1084
|
+
biller: resolveBiller(invocationEnv, provider),
|
|
1085
|
+
model,
|
|
1086
|
+
billingType: "unknown",
|
|
1087
|
+
costUsd: accounting.costUsd,
|
|
1088
|
+
...(accounting.costUsd != null && accounting.costUsd > 0 ? { cacheAdjustedCostUsd: accounting.costUsd } : {}),
|
|
1089
|
+
...(hasCompleteAccounting ? {} : { costStatus: "unpriced" }),
|
|
1090
|
+
summary: attempt.parsed.finalMessage ?? attempt.parsed.messages.at(-1) ?? null,
|
|
1091
|
+
clearSession: retriedFresh && !resolvedSessionId,
|
|
1092
|
+
resultJson: {
|
|
1093
|
+
...(executionRecovery?.kind === "interrupted"
|
|
1094
|
+
? { executionCancellation: { state: "acknowledged" } }
|
|
1095
|
+
: {}),
|
|
1096
|
+
...(attempt.modelFallback ? { modelFallback: attempt.modelFallback } : {}),
|
|
1097
|
+
stdout: attempt.stdoutTranscript,
|
|
1098
|
+
stderr: attempt.proc.stderr,
|
|
1099
|
+
errors: rpcPromptError ? [...attempt.parsed.errors, rpcPromptError] : attempt.parsed.errors,
|
|
1100
|
+
toolCalls: attempt.parsed.toolCalls.map(boundToolCallForResult),
|
|
1101
|
+
unknownLines: attempt.parsed.unknownLines,
|
|
1102
|
+
...(attempt.reporterFailed ? { progressReporterFailed: true } : {}),
|
|
1103
|
+
capabilityManifest: rpcActive ? RPC_CAPABILITY_MANIFEST : CAPABILITY_MANIFEST,
|
|
1104
|
+
...(rpcActive
|
|
1105
|
+
? { ompTransport: { mode: "rpc", protocolVersion: attempt.rpcProtocolVersion } }
|
|
1106
|
+
: {}),
|
|
1107
|
+
...(priorAttempt
|
|
1108
|
+
? {
|
|
1109
|
+
staleSessionAttempt: {
|
|
1110
|
+
stdout: priorAttempt.proc.stdout,
|
|
1111
|
+
stderr: priorAttempt.proc.stderr,
|
|
1112
|
+
},
|
|
1113
|
+
}
|
|
1114
|
+
: {}),
|
|
1115
|
+
},
|
|
1116
|
+
};
|
|
1117
|
+
return result;
|
|
1118
|
+
};
|
|
1119
|
+
const attachSessionBytes = async (result) => {
|
|
1120
|
+
result.sessionBytes = await readOmpSessionBytes(sessionDir, result.sessionId ?? null);
|
|
1121
|
+
return result;
|
|
1122
|
+
};
|
|
1123
|
+
const initial = await runAttempt(canResume ? savedSessionId : null);
|
|
1124
|
+
const initialFailed = !initial.proc.timedOut && ((initial.proc.exitCode ?? 0) !== 0 || initial.parsed.errors.length > 0);
|
|
1125
|
+
if (canResume &&
|
|
1126
|
+
initialFailed &&
|
|
1127
|
+
isOmpUnknownSessionError(initial.proc.stdout, initial.proc.stderr)) {
|
|
1128
|
+
await onLog("stdout", `[paperclip] OMP session "${savedSessionId}" is unavailable; retrying once with a fresh session.\n`);
|
|
1129
|
+
const retry = await runAttempt(null);
|
|
1130
|
+
return attachSessionBytes(toResult(retry, true, initial));
|
|
1131
|
+
}
|
|
1132
|
+
return attachSessionBytes(toResult(initial, false));
|
|
1133
|
+
}
|
|
1134
|
+
finally {
|
|
1135
|
+
try {
|
|
1136
|
+
try {
|
|
1137
|
+
await providerStop.collectBeforeRestore();
|
|
1138
|
+
}
|
|
1139
|
+
finally {
|
|
1140
|
+
await Promise.all([
|
|
1141
|
+
paperclipBridge?.stop(),
|
|
1142
|
+
restoreWorkspace?.(),
|
|
1143
|
+
]);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
finally {
|
|
1147
|
+
await settingsOverlay?.cleanup().catch(() => { });
|
|
1148
|
+
await mcpExtension?.cleanup().catch(() => { });
|
|
1149
|
+
await toolGuardExtension?.cleanup().catch(() => { });
|
|
1150
|
+
await pythonEnvBridge?.cleanup().catch(() => { });
|
|
1151
|
+
await preparedConfig.cleanup();
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
//# sourceMappingURL=execute.js.map
|