@tickernelz/paperclip-pro-adapter-gemini-local 2026.925.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +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 +223 -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 +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +63 -0
- package/dist/index.js.map +1 -0
- package/dist/server/acp.d.ts +19 -0
- package/dist/server/acp.d.ts.map +1 -0
- package/dist/server/acp.js +404 -0
- package/dist/server/acp.js.map +1 -0
- package/dist/server/acp.test.d.ts +2 -0
- package/dist/server/acp.test.d.ts.map +1 -0
- package/dist/server/acp.test.js +662 -0
- package/dist/server/acp.test.js.map +1 -0
- package/dist/server/config-schema.d.ts +3 -0
- package/dist/server/config-schema.d.ts.map +1 -0
- package/dist/server/config-schema.js +67 -0
- package/dist/server/config-schema.js.map +1 -0
- package/dist/server/engine-availability.test.d.ts +2 -0
- package/dist/server/engine-availability.test.d.ts.map +1 -0
- package/dist/server/engine-availability.test.js +41 -0
- package/dist/server/engine-availability.test.js.map +1 -0
- package/dist/server/execute.acp-fallback.test.d.ts +2 -0
- package/dist/server/execute.acp-fallback.test.d.ts.map +1 -0
- package/dist/server/execute.acp-fallback.test.js +130 -0
- package/dist/server/execute.acp-fallback.test.js.map +1 -0
- package/dist/server/execute.d.ts +3 -0
- package/dist/server/execute.d.ts.map +1 -0
- package/dist/server/execute.js +625 -0
- package/dist/server/execute.js.map +1 -0
- package/dist/server/execute.remote.test.d.ts +2 -0
- package/dist/server/execute.remote.test.d.ts.map +1 -0
- package/dist/server/execute.remote.test.js +377 -0
- package/dist/server/execute.remote.test.js.map +1 -0
- package/dist/server/index.d.ts +9 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +67 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/parse.d.ts +39 -0
- package/dist/server/parse.d.ts.map +1 -0
- package/dist/server/parse.js +268 -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 +166 -0
- package/dist/server/parse.test.js.map +1 -0
- package/dist/server/skills.d.ts +8 -0
- package/dist/server/skills.d.ts.map +1 -0
- package/dist/server/skills.js +69 -0
- package/dist/server/skills.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 +270 -0
- package/dist/server/test.js.map +1 -0
- package/dist/server/utils.d.ts +2 -0
- package/dist/server/utils.d.ts.map +1 -0
- package/dist/server/utils.js +7 -0
- package/dist/server/utils.js.map +1 -0
- package/dist/ui/build-config.d.ts +3 -0
- package/dist/ui/build-config.d.ts.map +1 -0
- package/dist/ui/build-config.js +39 -0
- package/dist/ui/build-config.js.map +1 -0
- package/dist/ui/build-config.test.d.ts +2 -0
- package/dist/ui/build-config.test.d.ts.map +1 -0
- package/dist/ui/build-config.test.js +63 -0
- package/dist/ui/build-config.test.js.map +1 -0
- package/dist/ui/index.d.ts +3 -0
- package/dist/ui/index.d.ts.map +1 -0
- package/dist/ui/index.js +3 -0
- package/dist/ui/index.js.map +1 -0
- package/dist/ui/parse-stdout.d.ts +3 -0
- package/dist/ui/parse-stdout.d.ts.map +1 -0
- package/dist/ui/parse-stdout.js +265 -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 +73 -0
- package/dist/ui/parse-stdout.test.js.map +1 -0
- package/package.json +58 -0
|
@@ -0,0 +1,625 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { adapterExecutionTargetIsRemote, adapterExecutionTargetRemoteCwd, overrideAdapterExecutionTargetRemoteCwd, adapterExecutionTargetSessionIdentity, adapterExecutionTargetSessionMatches, adapterExecutionTargetUsesManagedHome, adapterExecutionTargetUsesPaperclipBridge, describeAdapterExecutionTarget, ensureAdapterExecutionTargetCommandResolvable, ensureAdapterExecutionTargetRuntimeCommandInstalled, prepareAdapterExecutionTargetRuntime, adapterExecutionTargetDuplexObservabilityRecorder, adapterExecutionTargetEnablesSandboxDuplexBridge, readAdapterExecutionTarget, readAdapterExecutionTargetHomeDir, resolveAdapterExecutionTargetTimeoutSec, resolveAdapterExecutionTargetCommandForLogs, runAdapterExecutionTargetProcess, runAdapterExecutionTargetShellCommand, startAdapterExecutionTargetPaperclipBridge, } from "@tickernelz/paperclip-pro-adapter-utils/execution-target";
|
|
6
|
+
import { asBoolean, asNumber, asString, asStringArray, buildPaperclipEnv, buildRuntimeToolsEnv, buildInvocationEnvForLogs, ensureAbsoluteDirectory, ensurePaperclipSkillSymlink, joinPromptSections, ensurePathInEnv, refreshPaperclipWorkspaceEnvForExecution, isPaperclipSkillSourceMissing, readPaperclipRuntimeSkillEntries, readPaperclipIssueWorkModeFromContext, resolveLegacyPaperclipDesiredSkillNames, removeMaintainerOnlySkillSymlinks, parseObject, renderTemplate, renderPaperclipWakePrompt, selectPaperclipTaskMarkdown, selectInitialCommunicationGuidance, isPaperclipRecoveryWakePayload, DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE, DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE, } from "@tickernelz/paperclip-pro-adapter-utils/server-utils";
|
|
7
|
+
import { DEFAULT_GEMINI_LOCAL_MODEL, SANDBOX_INSTALL_COMMAND } from "../index.js";
|
|
8
|
+
import { describeGeminiFailure, detectGeminiAuthRequired, isGeminiTransientNetworkError, isGeminiTurnLimitResult, isGeminiSessionUnrecoverableError, parseGeminiJsonl, } from "./parse.js";
|
|
9
|
+
import { firstNonEmptyLine } from "./utils.js";
|
|
10
|
+
import { createGeminiAcpExecutor, resolveGeminiExecutionEngineForRun, } from "./acp.js";
|
|
11
|
+
import { resolveGeminiSkillsHome } from "./skills.js";
|
|
12
|
+
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
|
13
|
+
const executeGeminiAcp = createGeminiAcpExecutor();
|
|
14
|
+
function hasNonEmptyEnvValue(env, key) {
|
|
15
|
+
const raw = env[key];
|
|
16
|
+
return typeof raw === "string" && raw.trim().length > 0;
|
|
17
|
+
}
|
|
18
|
+
function resolveGeminiBillingType(env) {
|
|
19
|
+
return hasNonEmptyEnvValue(env, "GEMINI_API_KEY") || hasNonEmptyEnvValue(env, "GOOGLE_API_KEY")
|
|
20
|
+
? "api"
|
|
21
|
+
: "subscription";
|
|
22
|
+
}
|
|
23
|
+
function buildGeminiHeadlessEnv(env) {
|
|
24
|
+
const next = { ...env };
|
|
25
|
+
const term = env.TERM?.trim().toLowerCase();
|
|
26
|
+
if (!term || term === "dumb" || term === "vt100") {
|
|
27
|
+
next.TERM = "xterm-256color";
|
|
28
|
+
}
|
|
29
|
+
if (!next.COLORTERM?.trim()) {
|
|
30
|
+
next.COLORTERM = "truecolor";
|
|
31
|
+
}
|
|
32
|
+
next.NO_BROWSER = "1";
|
|
33
|
+
delete next.NO_COLOR;
|
|
34
|
+
return next;
|
|
35
|
+
}
|
|
36
|
+
function buildGeminiRuntimeEnv(env) {
|
|
37
|
+
return Object.fromEntries(Object.entries(ensurePathInEnv({ ...process.env, ...buildGeminiHeadlessEnv(env) })).filter((entry) => typeof entry[1] === "string"));
|
|
38
|
+
}
|
|
39
|
+
function renderPaperclipEnvNote(env) {
|
|
40
|
+
const paperclipKeys = Object.keys(env)
|
|
41
|
+
.filter((key) => key.startsWith("PAPERCLIP_"))
|
|
42
|
+
.sort();
|
|
43
|
+
if (paperclipKeys.length === 0)
|
|
44
|
+
return "";
|
|
45
|
+
return [
|
|
46
|
+
"Paperclip runtime note:",
|
|
47
|
+
`The following PAPERCLIP_* environment variables are available in this run: ${paperclipKeys.join(", ")}`,
|
|
48
|
+
"Do not assume these variables are missing without checking your shell environment.",
|
|
49
|
+
"",
|
|
50
|
+
"",
|
|
51
|
+
].join("\n");
|
|
52
|
+
}
|
|
53
|
+
function renderApiAccessNote(env) {
|
|
54
|
+
if (!hasNonEmptyEnvValue(env, "PAPERCLIP_API_URL") || !hasNonEmptyEnvValue(env, "PAPERCLIP_API_KEY"))
|
|
55
|
+
return "";
|
|
56
|
+
return [
|
|
57
|
+
"Paperclip API access note:",
|
|
58
|
+
"Use run_shell_command with curl to make Paperclip API requests.",
|
|
59
|
+
"GET example:",
|
|
60
|
+
` run_shell_command({ command: "curl -s -H \\"Authorization: Bearer $PAPERCLIP_API_KEY\\" \\"$PAPERCLIP_API_URL/api/agents/me\\"" })`,
|
|
61
|
+
"POST/PATCH example:",
|
|
62
|
+
` run_shell_command({ command: "curl -s -X POST -H \\"Authorization: Bearer $PAPERCLIP_API_KEY\\" -H 'Content-Type: application/json' -H \\"X-Paperclip-Run-Id: $PAPERCLIP_RUN_ID\\" -d '{...}' \\"$PAPERCLIP_API_URL/api/issues/$PAPERCLIP_TASK_ID/checkout\\"" })`,
|
|
63
|
+
"When PAPERCLIP_TASK_ID is not set, substitute a real issue id from the current context; never send a placeholder like {id} in the URL.",
|
|
64
|
+
"",
|
|
65
|
+
"",
|
|
66
|
+
].join("\n");
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Inject Paperclip skills directly into the effective Gemini skills home.
|
|
70
|
+
* This avoids needing GEMINI_CLI_HOME overrides, so the CLI naturally finds
|
|
71
|
+
* both its auth credentials and the injected skills under the child HOME.
|
|
72
|
+
*/
|
|
73
|
+
async function ensureGeminiSkillsInjected(onLog, skillsEntries, desiredSkillNames, skillsHome = resolveGeminiSkillsHome({})) {
|
|
74
|
+
const desiredSet = new Set(desiredSkillNames ?? skillsEntries.map((entry) => entry.key));
|
|
75
|
+
const selectedEntries = skillsEntries.filter((entry) => desiredSet.has(entry.key));
|
|
76
|
+
if (selectedEntries.length === 0)
|
|
77
|
+
return;
|
|
78
|
+
try {
|
|
79
|
+
await fs.mkdir(skillsHome, { recursive: true });
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
await onLog("stderr", `[paperclip] Failed to prepare Gemini skills directory ${skillsHome}: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const removedSkills = await removeMaintainerOnlySkillSymlinks(skillsHome, selectedEntries.map((entry) => entry.runtimeName));
|
|
86
|
+
for (const skillName of removedSkills) {
|
|
87
|
+
await onLog("stderr", `[paperclip] Removed maintainer-only Gemini skill "${skillName}" from ${skillsHome}\n`);
|
|
88
|
+
}
|
|
89
|
+
for (const entry of selectedEntries) {
|
|
90
|
+
const target = path.join(skillsHome, entry.runtimeName);
|
|
91
|
+
try {
|
|
92
|
+
const result = await ensurePaperclipSkillSymlink(entry.source, target);
|
|
93
|
+
if (result === "skipped")
|
|
94
|
+
continue;
|
|
95
|
+
await onLog("stderr", `[paperclip] ${result === "repaired" ? "Repaired" : "Linked"} Gemini skill: ${entry.key}\n`);
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
await onLog("stderr", `[paperclip] Failed to link Gemini skill "${entry.key}": ${err instanceof Error ? err.message : String(err)}\n`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
async function buildGeminiSkillsDir(config) {
|
|
103
|
+
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-gemini-skills-"));
|
|
104
|
+
const target = path.join(tmp, "skills");
|
|
105
|
+
await fs.mkdir(target, { recursive: true });
|
|
106
|
+
const availableEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
|
|
107
|
+
const desiredNames = new Set(resolveLegacyPaperclipDesiredSkillNames(config, availableEntries));
|
|
108
|
+
for (const entry of availableEntries) {
|
|
109
|
+
if (!desiredNames.has(entry.key))
|
|
110
|
+
continue;
|
|
111
|
+
if (isPaperclipSkillSourceMissing(entry))
|
|
112
|
+
continue;
|
|
113
|
+
await fs.symlink(entry.source, path.join(target, entry.runtimeName));
|
|
114
|
+
}
|
|
115
|
+
return target;
|
|
116
|
+
}
|
|
117
|
+
export async function execute(ctx) {
|
|
118
|
+
const engineSelection = await resolveGeminiExecutionEngineForRun(ctx);
|
|
119
|
+
if (engineSelection.unavailableReason) {
|
|
120
|
+
return {
|
|
121
|
+
exitCode: 1,
|
|
122
|
+
signal: null,
|
|
123
|
+
timedOut: false,
|
|
124
|
+
errorCode: "adapter_engine_unavailable",
|
|
125
|
+
errorMessage: engineSelection.unavailableReason,
|
|
126
|
+
resultJson: {
|
|
127
|
+
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
if (engineSelection.engine === "acp") {
|
|
132
|
+
return executeGeminiAcp(ctx);
|
|
133
|
+
}
|
|
134
|
+
const { runId, agent, runtime, config, context, onLog, onMeta, onSpawn, authToken } = ctx;
|
|
135
|
+
const executionTarget = readAdapterExecutionTarget({
|
|
136
|
+
executionTarget: ctx.executionTarget,
|
|
137
|
+
legacyRemoteExecution: ctx.executionTransport?.remoteExecution,
|
|
138
|
+
});
|
|
139
|
+
const executionTargetIsRemote = adapterExecutionTargetIsRemote(executionTarget);
|
|
140
|
+
const promptTemplate = asString(config.promptTemplate, context.conversationMode === true
|
|
141
|
+
? DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE
|
|
142
|
+
: DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE);
|
|
143
|
+
const command = asString(config.command, "gemini");
|
|
144
|
+
const model = asString(config.model, DEFAULT_GEMINI_LOCAL_MODEL).trim();
|
|
145
|
+
const sandbox = asBoolean(config.sandbox, false);
|
|
146
|
+
const workspaceContext = parseObject(context.paperclipWorkspace);
|
|
147
|
+
const workspaceCwd = asString(workspaceContext.cwd, "");
|
|
148
|
+
const workspaceSource = asString(workspaceContext.source, "");
|
|
149
|
+
const workspaceId = asString(workspaceContext.workspaceId, "");
|
|
150
|
+
const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
|
|
151
|
+
const workspaceRepoRef = asString(workspaceContext.repoRef, "");
|
|
152
|
+
const agentHome = asString(workspaceContext.agentHome, "");
|
|
153
|
+
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
|
|
154
|
+
? context.paperclipWorkspaces.filter((value) => typeof value === "object" && value !== null)
|
|
155
|
+
: [];
|
|
156
|
+
const configuredCwd = asString(config.cwd, "");
|
|
157
|
+
const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0;
|
|
158
|
+
const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd;
|
|
159
|
+
const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd();
|
|
160
|
+
let effectiveExecutionCwd = adapterExecutionTargetRemoteCwd(executionTarget, cwd);
|
|
161
|
+
await ensureAbsoluteDirectory(cwd, { createIfMissing: true });
|
|
162
|
+
const geminiSkillEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
|
|
163
|
+
const desiredGeminiSkillNames = resolveLegacyPaperclipDesiredSkillNames(config, geminiSkillEntries);
|
|
164
|
+
if (!executionTargetIsRemote) {
|
|
165
|
+
await ensureGeminiSkillsInjected(onLog, geminiSkillEntries.filter((entry) => !isPaperclipSkillSourceMissing(entry)), desiredGeminiSkillNames, resolveGeminiSkillsHome(config));
|
|
166
|
+
}
|
|
167
|
+
const envConfig = parseObject(config.env);
|
|
168
|
+
const env = {
|
|
169
|
+
...buildPaperclipEnv(agent),
|
|
170
|
+
...buildRuntimeToolsEnv(ctx.runtimeTools),
|
|
171
|
+
};
|
|
172
|
+
env.PAPERCLIP_RUN_ID = runId;
|
|
173
|
+
const wakeTaskId = (typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim()) ||
|
|
174
|
+
(typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim()) ||
|
|
175
|
+
null;
|
|
176
|
+
const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0
|
|
177
|
+
? context.wakeReason.trim()
|
|
178
|
+
: null;
|
|
179
|
+
const wakeCommentId = (typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim()) ||
|
|
180
|
+
(typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim()) ||
|
|
181
|
+
null;
|
|
182
|
+
const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0
|
|
183
|
+
? context.approvalId.trim()
|
|
184
|
+
: null;
|
|
185
|
+
const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0
|
|
186
|
+
? context.approvalStatus.trim()
|
|
187
|
+
: null;
|
|
188
|
+
const linkedIssueIds = Array.isArray(context.issueIds)
|
|
189
|
+
? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0)
|
|
190
|
+
: [];
|
|
191
|
+
const issueWorkMode = readPaperclipIssueWorkModeFromContext(context);
|
|
192
|
+
if (wakeTaskId)
|
|
193
|
+
env.PAPERCLIP_TASK_ID = wakeTaskId;
|
|
194
|
+
if (issueWorkMode)
|
|
195
|
+
env.PAPERCLIP_ISSUE_WORK_MODE = issueWorkMode;
|
|
196
|
+
if (wakeReason)
|
|
197
|
+
env.PAPERCLIP_WAKE_REASON = wakeReason;
|
|
198
|
+
if (wakeCommentId)
|
|
199
|
+
env.PAPERCLIP_WAKE_COMMENT_ID = wakeCommentId;
|
|
200
|
+
if (approvalId)
|
|
201
|
+
env.PAPERCLIP_APPROVAL_ID = approvalId;
|
|
202
|
+
if (approvalStatus)
|
|
203
|
+
env.PAPERCLIP_APPROVAL_STATUS = approvalStatus;
|
|
204
|
+
if (linkedIssueIds.length > 0)
|
|
205
|
+
env.PAPERCLIP_LINKED_ISSUE_IDS = linkedIssueIds.join(",");
|
|
206
|
+
refreshPaperclipWorkspaceEnvForExecution({
|
|
207
|
+
env,
|
|
208
|
+
envConfig,
|
|
209
|
+
workspaceCwd: effectiveWorkspaceCwd,
|
|
210
|
+
workspaceSource,
|
|
211
|
+
workspaceId,
|
|
212
|
+
workspaceRepoUrl,
|
|
213
|
+
workspaceRepoRef,
|
|
214
|
+
workspaceHints,
|
|
215
|
+
agentHome,
|
|
216
|
+
executionTargetIsRemote,
|
|
217
|
+
executionCwd: effectiveExecutionCwd,
|
|
218
|
+
});
|
|
219
|
+
if (executionTargetIsRemote && typeof env.GEMINI_CLI_TRUST_WORKSPACE !== "string") {
|
|
220
|
+
env.GEMINI_CLI_TRUST_WORKSPACE = "true";
|
|
221
|
+
}
|
|
222
|
+
if (authToken) {
|
|
223
|
+
env.PAPERCLIP_API_KEY = authToken;
|
|
224
|
+
}
|
|
225
|
+
const runtimeEnv = buildGeminiRuntimeEnv(env);
|
|
226
|
+
const billingType = resolveGeminiBillingType(runtimeEnv);
|
|
227
|
+
const timeoutSec = resolveAdapterExecutionTargetTimeoutSec(executionTarget, asNumber(config.timeoutSec, 0));
|
|
228
|
+
const graceSec = asNumber(config.graceSec, 20);
|
|
229
|
+
await ensureAdapterExecutionTargetRuntimeCommandInstalled({
|
|
230
|
+
runId,
|
|
231
|
+
target: executionTarget,
|
|
232
|
+
installCommand: ctx.runtimeCommandSpec?.installCommand,
|
|
233
|
+
detectCommand: ctx.runtimeCommandSpec?.detectCommand,
|
|
234
|
+
cwd,
|
|
235
|
+
env: runtimeEnv,
|
|
236
|
+
timeoutSec,
|
|
237
|
+
graceSec,
|
|
238
|
+
onLog,
|
|
239
|
+
});
|
|
240
|
+
await ensureAdapterExecutionTargetCommandResolvable(command, executionTarget, cwd, runtimeEnv, {
|
|
241
|
+
installCommand: SANDBOX_INSTALL_COMMAND,
|
|
242
|
+
timeoutSec,
|
|
243
|
+
});
|
|
244
|
+
const resolvedCommand = await resolveAdapterExecutionTargetCommandForLogs(command, executionTarget, cwd, runtimeEnv);
|
|
245
|
+
const extraArgs = (() => {
|
|
246
|
+
const fromExtraArgs = asStringArray(config.extraArgs);
|
|
247
|
+
if (fromExtraArgs.length > 0)
|
|
248
|
+
return fromExtraArgs;
|
|
249
|
+
return asStringArray(config.args);
|
|
250
|
+
})();
|
|
251
|
+
let restoreRemoteWorkspace = null;
|
|
252
|
+
let remoteSkillsDir = null;
|
|
253
|
+
let localSkillsDir = null;
|
|
254
|
+
let remoteRuntimeRootDir = null;
|
|
255
|
+
let paperclipBridge = null;
|
|
256
|
+
if (executionTargetIsRemote) {
|
|
257
|
+
try {
|
|
258
|
+
localSkillsDir = await buildGeminiSkillsDir(config);
|
|
259
|
+
await onLog("stdout", `[paperclip] Syncing workspace and Gemini runtime assets to ${describeAdapterExecutionTarget(executionTarget)}.\n`);
|
|
260
|
+
const preparedExecutionTargetRuntime = await prepareAdapterExecutionTargetRuntime({
|
|
261
|
+
runId,
|
|
262
|
+
target: executionTarget,
|
|
263
|
+
adapterKey: "gemini",
|
|
264
|
+
timeoutSec,
|
|
265
|
+
workspaceLocalDir: cwd,
|
|
266
|
+
installCommand: SANDBOX_INSTALL_COMMAND,
|
|
267
|
+
detectCommand: command,
|
|
268
|
+
onProgress: (line) => onLog("stdout", line),
|
|
269
|
+
onRuntimeProgress: ctx.onRuntimeProgress,
|
|
270
|
+
assets: [{
|
|
271
|
+
key: "skills",
|
|
272
|
+
localDir: localSkillsDir,
|
|
273
|
+
followSymlinks: true,
|
|
274
|
+
}],
|
|
275
|
+
});
|
|
276
|
+
restoreRemoteWorkspace = () => preparedExecutionTargetRuntime.restoreWorkspace((line) => onLog("stdout", line));
|
|
277
|
+
effectiveExecutionCwd = preparedExecutionTargetRuntime.workspaceRemoteDir ?? effectiveExecutionCwd;
|
|
278
|
+
refreshPaperclipWorkspaceEnvForExecution({
|
|
279
|
+
env,
|
|
280
|
+
envConfig,
|
|
281
|
+
workspaceCwd: effectiveWorkspaceCwd,
|
|
282
|
+
workspaceSource,
|
|
283
|
+
workspaceId,
|
|
284
|
+
workspaceRepoUrl,
|
|
285
|
+
workspaceRepoRef,
|
|
286
|
+
workspaceHints,
|
|
287
|
+
agentHome,
|
|
288
|
+
executionTargetIsRemote,
|
|
289
|
+
executionCwd: effectiveExecutionCwd,
|
|
290
|
+
});
|
|
291
|
+
remoteRuntimeRootDir = preparedExecutionTargetRuntime.runtimeRootDir;
|
|
292
|
+
const managedHome = adapterExecutionTargetUsesManagedHome(executionTarget);
|
|
293
|
+
const managedRemoteHomeDir = managedHome && preparedExecutionTargetRuntime.runtimeRootDir
|
|
294
|
+
? preparedExecutionTargetRuntime.runtimeRootDir
|
|
295
|
+
: null;
|
|
296
|
+
if (managedRemoteHomeDir) {
|
|
297
|
+
env.HOME = managedRemoteHomeDir;
|
|
298
|
+
}
|
|
299
|
+
const remoteHomeDir = managedRemoteHomeDir ??
|
|
300
|
+
(await readAdapterExecutionTargetHomeDir(runId, executionTarget, {
|
|
301
|
+
cwd,
|
|
302
|
+
env,
|
|
303
|
+
timeoutSec,
|
|
304
|
+
graceSec,
|
|
305
|
+
onLog,
|
|
306
|
+
}));
|
|
307
|
+
if (remoteHomeDir && preparedExecutionTargetRuntime.assetDirs.skills) {
|
|
308
|
+
remoteSkillsDir = path.posix.join(remoteHomeDir, ".gemini", "skills");
|
|
309
|
+
await runAdapterExecutionTargetShellCommand(runId, executionTarget, `mkdir -p ${JSON.stringify(path.posix.dirname(remoteSkillsDir))} && rm -rf ${JSON.stringify(remoteSkillsDir)} && cp -a ${JSON.stringify(preparedExecutionTargetRuntime.assetDirs.skills)} ${JSON.stringify(remoteSkillsDir)}`, { cwd, env, timeoutSec, graceSec, onLog });
|
|
310
|
+
}
|
|
311
|
+
// Gemini CLI refuses headless runs without an auth selection persisted in
|
|
312
|
+
// $HOME/.gemini/settings.json ("Invalid auth method selected."); env vars
|
|
313
|
+
// alone (GEMINI_DEFAULT_AUTH_TYPE) do not satisfy it. With a managed HOME
|
|
314
|
+
// the runtime root replaces the image home, so any settings baked into the
|
|
315
|
+
// image are invisible -- pre-select the api-key auth whenever an API key
|
|
316
|
+
// is provided. Both settings schema generations are written (legacy
|
|
317
|
+
// selectedAuthType + current security.auth.selectedType). An existing
|
|
318
|
+
// settings.json (user-shipped via workspace) is left untouched.
|
|
319
|
+
// Only the managed HOME (the per-run runtime root) is touched: on
|
|
320
|
+
// non-managed remote targets remoteHomeDir is the user's real home, where
|
|
321
|
+
// creating files is out of scope and existing settings remain visible.
|
|
322
|
+
// Key presence check spans the run env AND the host process env: in the
|
|
323
|
+
// managed sandbox path the key never enters the adapter's run env -- it
|
|
324
|
+
// reaches the agent pod via the provider's per-run secret (envKeys
|
|
325
|
+
// passthrough from the host env), so the host env is the signal here.
|
|
326
|
+
const hasGeminiApiKey = Boolean(env.GEMINI_API_KEY || env.GOOGLE_API_KEY ||
|
|
327
|
+
process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
|
|
328
|
+
if (managedRemoteHomeDir && hasGeminiApiKey) {
|
|
329
|
+
const remoteSettingsPath = path.posix.join(managedRemoteHomeDir, ".gemini", "settings.json");
|
|
330
|
+
const authSettingsJson = JSON.stringify({
|
|
331
|
+
selectedAuthType: "gemini-api-key",
|
|
332
|
+
security: { auth: { selectedType: "gemini-api-key" } },
|
|
333
|
+
});
|
|
334
|
+
await runAdapterExecutionTargetShellCommand(runId, executionTarget, `mkdir -p ${JSON.stringify(path.posix.dirname(remoteSettingsPath))} && { [ -f ${JSON.stringify(remoteSettingsPath)} ] || printf '%s' ${JSON.stringify(authSettingsJson)} > ${JSON.stringify(remoteSettingsPath)}; }`, { cwd, env, timeoutSec, graceSec, onLog });
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
catch (error) {
|
|
338
|
+
await Promise.allSettled([
|
|
339
|
+
restoreRemoteWorkspace?.(),
|
|
340
|
+
localSkillsDir ? fs.rm(path.dirname(localSkillsDir), { recursive: true, force: true }).catch(() => undefined) : Promise.resolve(),
|
|
341
|
+
]);
|
|
342
|
+
throw error;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
const runtimeExecutionTarget = overrideAdapterExecutionTargetRemoteCwd(executionTarget, effectiveExecutionCwd);
|
|
346
|
+
if (executionTargetIsRemote && adapterExecutionTargetUsesPaperclipBridge(executionTarget)) {
|
|
347
|
+
paperclipBridge = await startAdapterExecutionTargetPaperclipBridge({
|
|
348
|
+
runId,
|
|
349
|
+
target: runtimeExecutionTarget,
|
|
350
|
+
enableSandboxDuplexBridge: adapterExecutionTargetEnablesSandboxDuplexBridge(runtimeExecutionTarget),
|
|
351
|
+
duplexObservabilityRecorder: adapterExecutionTargetDuplexObservabilityRecorder(runtimeExecutionTarget),
|
|
352
|
+
runtimeRootDir: remoteRuntimeRootDir,
|
|
353
|
+
adapterKey: "gemini",
|
|
354
|
+
timeoutSec,
|
|
355
|
+
hostApiToken: env.PAPERCLIP_API_KEY,
|
|
356
|
+
onLog,
|
|
357
|
+
});
|
|
358
|
+
if (paperclipBridge) {
|
|
359
|
+
Object.assign(env, paperclipBridge.env);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
const runtimeSessionParams = parseObject(runtime.sessionParams);
|
|
363
|
+
const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? "");
|
|
364
|
+
const runtimeSessionCwd = asString(runtimeSessionParams.cwd, "");
|
|
365
|
+
const runtimeRemoteExecution = parseObject(runtimeSessionParams.remoteExecution);
|
|
366
|
+
const canResumeSession = runtimeSessionId.length > 0 &&
|
|
367
|
+
(runtimeSessionCwd.length === 0 || path.resolve(runtimeSessionCwd) === path.resolve(effectiveExecutionCwd)) &&
|
|
368
|
+
adapterExecutionTargetSessionMatches(runtimeRemoteExecution, runtimeExecutionTarget);
|
|
369
|
+
const sessionId = canResumeSession ? runtimeSessionId : null;
|
|
370
|
+
if (executionTargetIsRemote && runtimeSessionId && !canResumeSession) {
|
|
371
|
+
await onLog("stdout", `[paperclip] Gemini session "${runtimeSessionId}" does not match the current remote execution identity and will not be resumed in "${effectiveExecutionCwd}". Starting a fresh remote session.\n`);
|
|
372
|
+
}
|
|
373
|
+
else if (runtimeSessionId && !canResumeSession) {
|
|
374
|
+
await onLog("stdout", `[paperclip] Gemini session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${effectiveExecutionCwd}".\n`);
|
|
375
|
+
}
|
|
376
|
+
const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
|
|
377
|
+
const instructionsDir = instructionsFilePath ? `${path.dirname(instructionsFilePath)}/` : "";
|
|
378
|
+
let instructionsPrefix = "";
|
|
379
|
+
if (instructionsFilePath) {
|
|
380
|
+
try {
|
|
381
|
+
const instructionsContents = await fs.readFile(instructionsFilePath, "utf8");
|
|
382
|
+
instructionsPrefix =
|
|
383
|
+
`${instructionsContents}\n\n` +
|
|
384
|
+
`The above agent instructions were loaded from ${instructionsFilePath}. ` +
|
|
385
|
+
`Resolve any relative file references from ${instructionsDir}.\n\n`;
|
|
386
|
+
}
|
|
387
|
+
catch (err) {
|
|
388
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
389
|
+
await onLog("stdout", `[paperclip] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason}\n`);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
const commandNotes = (() => {
|
|
393
|
+
const notes = ["Prompt is passed to Gemini via --prompt for non-interactive execution."];
|
|
394
|
+
notes.push("Added --approval-mode yolo for unattended execution.");
|
|
395
|
+
notes.push("Set headless terminal/browser env so Gemini fails fast instead of opening interactive auth or color prompts.");
|
|
396
|
+
if (executionTargetIsRemote) {
|
|
397
|
+
notes.push("Set GEMINI_CLI_TRUST_WORKSPACE=true for remote headless execution.");
|
|
398
|
+
}
|
|
399
|
+
if (!instructionsFilePath)
|
|
400
|
+
return notes;
|
|
401
|
+
if (instructionsPrefix.length > 0) {
|
|
402
|
+
notes.push(`Loaded agent instructions from ${instructionsFilePath}`, `Prepended instructions + path directive to prompt (relative references from ${instructionsDir}).`);
|
|
403
|
+
return notes;
|
|
404
|
+
}
|
|
405
|
+
notes.push(`Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.`);
|
|
406
|
+
return notes;
|
|
407
|
+
})();
|
|
408
|
+
const bootstrapPromptTemplate = asString(config.bootstrapPromptTemplate, "");
|
|
409
|
+
const templateData = {
|
|
410
|
+
agentId: agent.id,
|
|
411
|
+
companyId: agent.companyId,
|
|
412
|
+
runId,
|
|
413
|
+
company: { id: agent.companyId },
|
|
414
|
+
agent,
|
|
415
|
+
run: { id: runId, source: "on_demand" },
|
|
416
|
+
context,
|
|
417
|
+
};
|
|
418
|
+
const renderedBootstrapPrompt = !sessionId && bootstrapPromptTemplate.trim().length > 0
|
|
419
|
+
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
|
|
420
|
+
: "";
|
|
421
|
+
const taskContextNote = context.conversationMode === true
|
|
422
|
+
? selectPaperclipTaskMarkdown(context, { resumedSession: Boolean(sessionId), includeCommunicationGuidance: false })
|
|
423
|
+
: "";
|
|
424
|
+
const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, {
|
|
425
|
+
conversationMode: context.conversationMode === true,
|
|
426
|
+
resumedSession: Boolean(sessionId),
|
|
427
|
+
suppressIssueDescription: taskContextNote.length > 0,
|
|
428
|
+
});
|
|
429
|
+
const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;
|
|
430
|
+
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
|
|
431
|
+
? ""
|
|
432
|
+
: renderTemplate(promptTemplate, templateData);
|
|
433
|
+
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
|
|
434
|
+
const paperclipEnvNote = renderPaperclipEnvNote(env);
|
|
435
|
+
const apiAccessNote = renderApiAccessNote(env);
|
|
436
|
+
const basePrompt = joinPromptSections([
|
|
437
|
+
instructionsPrefix,
|
|
438
|
+
renderedBootstrapPrompt,
|
|
439
|
+
wakePrompt,
|
|
440
|
+
taskContextNote,
|
|
441
|
+
sessionHandoffNote,
|
|
442
|
+
paperclipEnvNote,
|
|
443
|
+
apiAccessNote,
|
|
444
|
+
renderedPrompt,
|
|
445
|
+
]);
|
|
446
|
+
const promptMetrics = {
|
|
447
|
+
promptChars: basePrompt.length,
|
|
448
|
+
instructionsChars: instructionsPrefix.length,
|
|
449
|
+
bootstrapPromptChars: renderedBootstrapPrompt.length,
|
|
450
|
+
wakePromptChars: wakePrompt.length,
|
|
451
|
+
taskContextChars: taskContextNote.length,
|
|
452
|
+
sessionHandoffChars: sessionHandoffNote.length,
|
|
453
|
+
runtimeNoteChars: paperclipEnvNote.length + apiAccessNote.length,
|
|
454
|
+
heartbeatPromptChars: renderedPrompt.length,
|
|
455
|
+
};
|
|
456
|
+
const buildArgs = (resumeSessionId, prompt) => {
|
|
457
|
+
const args = ["--output-format", "stream-json"];
|
|
458
|
+
if (resumeSessionId)
|
|
459
|
+
args.push("--resume", resumeSessionId);
|
|
460
|
+
if (model && model !== DEFAULT_GEMINI_LOCAL_MODEL)
|
|
461
|
+
args.push("--model", model);
|
|
462
|
+
args.push("--approval-mode", "yolo");
|
|
463
|
+
if (sandbox) {
|
|
464
|
+
args.push("--sandbox");
|
|
465
|
+
}
|
|
466
|
+
else {
|
|
467
|
+
args.push("--sandbox=none");
|
|
468
|
+
}
|
|
469
|
+
if (extraArgs.length > 0)
|
|
470
|
+
args.push(...extraArgs);
|
|
471
|
+
args.push("--prompt", prompt);
|
|
472
|
+
return args;
|
|
473
|
+
};
|
|
474
|
+
const runAttempt = async (resumeSessionId) => {
|
|
475
|
+
const prompt = joinPromptSections([
|
|
476
|
+
selectInitialCommunicationGuidance(context, { resumedSession: Boolean(resumeSessionId) }),
|
|
477
|
+
basePrompt,
|
|
478
|
+
]);
|
|
479
|
+
const args = buildArgs(resumeSessionId, prompt);
|
|
480
|
+
const invocationEnv = buildGeminiHeadlessEnv(env);
|
|
481
|
+
const invocationRuntimeEnv = buildGeminiRuntimeEnv(env);
|
|
482
|
+
const loggedEnv = buildInvocationEnvForLogs(invocationEnv, {
|
|
483
|
+
runtimeEnv: invocationRuntimeEnv,
|
|
484
|
+
includeRuntimeKeys: ["HOME"],
|
|
485
|
+
resolvedCommand,
|
|
486
|
+
});
|
|
487
|
+
if (onMeta) {
|
|
488
|
+
await onMeta({
|
|
489
|
+
adapterType: "gemini_local",
|
|
490
|
+
command: resolvedCommand,
|
|
491
|
+
cwd: effectiveExecutionCwd,
|
|
492
|
+
commandNotes,
|
|
493
|
+
commandArgs: args.map((value, index) => (index === args.length - 1 ? `<prompt ${prompt.length} chars>` : value)),
|
|
494
|
+
env: loggedEnv,
|
|
495
|
+
prompt,
|
|
496
|
+
promptMetrics: { ...promptMetrics, promptChars: prompt.length },
|
|
497
|
+
context,
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
const proc = await runAdapterExecutionTargetProcess(runId, runtimeExecutionTarget, command, args, {
|
|
501
|
+
cwd,
|
|
502
|
+
env: invocationEnv,
|
|
503
|
+
timeoutSec,
|
|
504
|
+
graceSec,
|
|
505
|
+
onSpawn,
|
|
506
|
+
onRuntimeProgress: ctx.onRuntimeProgress,
|
|
507
|
+
onLog,
|
|
508
|
+
runLogTail: paperclipBridge?.runLogTail,
|
|
509
|
+
settleRunDisposition: paperclipBridge?.settleRunDisposition,
|
|
510
|
+
});
|
|
511
|
+
return {
|
|
512
|
+
proc,
|
|
513
|
+
parsed: parseGeminiJsonl(proc.stdout),
|
|
514
|
+
};
|
|
515
|
+
};
|
|
516
|
+
const toResult = (attempt, clearSessionOnMissingSession = false, isRetry = false) => {
|
|
517
|
+
const authMeta = detectGeminiAuthRequired({
|
|
518
|
+
parsed: attempt.parsed.resultEvent,
|
|
519
|
+
stdout: attempt.proc.stdout,
|
|
520
|
+
stderr: attempt.proc.stderr,
|
|
521
|
+
});
|
|
522
|
+
const networkUnavailable = isGeminiTransientNetworkError(attempt.proc.stdout, attempt.proc.stderr);
|
|
523
|
+
if (attempt.proc.timedOut) {
|
|
524
|
+
return {
|
|
525
|
+
exitCode: attempt.proc.exitCode,
|
|
526
|
+
signal: attempt.proc.signal,
|
|
527
|
+
timedOut: true,
|
|
528
|
+
errorMessage: `Timed out after ${timeoutSec}s`,
|
|
529
|
+
errorCode: authMeta.requiresAuth
|
|
530
|
+
? "gemini_auth_required"
|
|
531
|
+
: networkUnavailable
|
|
532
|
+
? "gemini_network_unavailable"
|
|
533
|
+
: null,
|
|
534
|
+
clearSession: clearSessionOnMissingSession,
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : "";
|
|
538
|
+
const stderrLine = firstNonEmptyLine(attempt.proc.stderr);
|
|
539
|
+
const structuredFailure = attempt.parsed.resultEvent
|
|
540
|
+
? describeGeminiFailure(attempt.parsed.resultEvent)
|
|
541
|
+
: null;
|
|
542
|
+
const fallbackErrorMessage = parsedError ||
|
|
543
|
+
structuredFailure ||
|
|
544
|
+
stderrLine ||
|
|
545
|
+
`Gemini exited with code ${attempt.proc.exitCode ?? -1}`;
|
|
546
|
+
const failed = (attempt.proc.exitCode ?? 0) !== 0;
|
|
547
|
+
const clearSessionForTurnLimit = isGeminiTurnLimitResult(attempt.parsed.resultEvent, attempt.proc.exitCode);
|
|
548
|
+
// On retry, don't fall back to old session ID — the old session was stale
|
|
549
|
+
const canFallbackToRuntimeSession = !isRetry;
|
|
550
|
+
const resolvedSessionId = attempt.parsed.sessionId
|
|
551
|
+
?? (canFallbackToRuntimeSession ? (runtimeSessionId ?? runtime.sessionId ?? null) : null);
|
|
552
|
+
const resolvedSessionParams = resolvedSessionId
|
|
553
|
+
? {
|
|
554
|
+
sessionId: resolvedSessionId,
|
|
555
|
+
cwd: effectiveExecutionCwd,
|
|
556
|
+
...(workspaceId ? { workspaceId } : {}),
|
|
557
|
+
...(workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}),
|
|
558
|
+
...(workspaceRepoRef ? { repoRef: workspaceRepoRef } : {}),
|
|
559
|
+
...(executionTargetIsRemote
|
|
560
|
+
? {
|
|
561
|
+
remoteExecution: adapterExecutionTargetSessionIdentity(runtimeExecutionTarget),
|
|
562
|
+
}
|
|
563
|
+
: {}),
|
|
564
|
+
}
|
|
565
|
+
: null;
|
|
566
|
+
const resultJson = {
|
|
567
|
+
...(attempt.parsed.resultEvent ?? {
|
|
568
|
+
stdout: attempt.proc.stdout,
|
|
569
|
+
stderr: attempt.proc.stderr,
|
|
570
|
+
}),
|
|
571
|
+
...(failed && clearSessionForTurnLimit ? { stopReason: "max_turns_exhausted" } : {}),
|
|
572
|
+
};
|
|
573
|
+
return {
|
|
574
|
+
exitCode: attempt.proc.exitCode,
|
|
575
|
+
signal: attempt.proc.signal,
|
|
576
|
+
timedOut: false,
|
|
577
|
+
errorMessage: failed ? fallbackErrorMessage : null,
|
|
578
|
+
// Forward the transport-level error code from the run-disposition seam
|
|
579
|
+
// first. A lost duplex control channel surfaces the typed
|
|
580
|
+
// `duplex_channel_lost` code before any provider classification.
|
|
581
|
+
errorCode: attempt.proc.errorCode
|
|
582
|
+
? attempt.proc.errorCode
|
|
583
|
+
: failed && authMeta.requiresAuth
|
|
584
|
+
? "gemini_auth_required"
|
|
585
|
+
: failed && clearSessionForTurnLimit
|
|
586
|
+
? "max_turns_exhausted"
|
|
587
|
+
: failed && networkUnavailable
|
|
588
|
+
? "gemini_network_unavailable"
|
|
589
|
+
: null,
|
|
590
|
+
usage: attempt.parsed.usage,
|
|
591
|
+
sessionId: resolvedSessionId,
|
|
592
|
+
sessionParams: resolvedSessionParams,
|
|
593
|
+
sessionDisplayId: resolvedSessionId,
|
|
594
|
+
provider: "google",
|
|
595
|
+
biller: "google",
|
|
596
|
+
model,
|
|
597
|
+
billingType,
|
|
598
|
+
costUsd: attempt.parsed.costUsd,
|
|
599
|
+
resultJson,
|
|
600
|
+
summary: attempt.parsed.summary,
|
|
601
|
+
question: attempt.parsed.question,
|
|
602
|
+
clearSession: clearSessionForTurnLimit || Boolean(clearSessionOnMissingSession && !resolvedSessionId),
|
|
603
|
+
};
|
|
604
|
+
};
|
|
605
|
+
try {
|
|
606
|
+
const initial = await runAttempt(sessionId);
|
|
607
|
+
if (sessionId &&
|
|
608
|
+
!initial.proc.timedOut &&
|
|
609
|
+
(initial.proc.exitCode ?? 0) !== 0 &&
|
|
610
|
+
isGeminiSessionUnrecoverableError(initial.proc.stdout, initial.proc.stderr)) {
|
|
611
|
+
await onLog("stdout", `[paperclip] Gemini resume session "${sessionId}" is unavailable; retrying with a fresh session.\n`);
|
|
612
|
+
const retry = await runAttempt(null);
|
|
613
|
+
return toResult(retry, true, true);
|
|
614
|
+
}
|
|
615
|
+
return toResult(initial);
|
|
616
|
+
}
|
|
617
|
+
finally {
|
|
618
|
+
await Promise.all([
|
|
619
|
+
paperclipBridge?.stop(),
|
|
620
|
+
restoreRemoteWorkspace?.(),
|
|
621
|
+
localSkillsDir ? fs.rm(path.dirname(localSkillsDir), { recursive: true, force: true }).catch(() => undefined) : Promise.resolve(),
|
|
622
|
+
]);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
//# sourceMappingURL=execute.js.map
|