@usepipa/pipa 0.6.0-beta.1 → 0.6.0-beta.3
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/README.md +68 -122
- package/bin/pipa.mjs +5 -15
- package/package.json +1 -1
- package/src/app.mjs +79 -31
- package/src/errors.mjs +4 -0
- package/src/models.mjs +46 -54
- package/src/opencode-v2.mjs +398 -659
- package/src/opencode.mjs +48 -33
- package/src/state.mjs +0 -2
package/src/opencode.mjs
CHANGED
|
@@ -119,17 +119,37 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
119
119
|
signal: AbortSignal.any([readinessController.signal, ...(options.signal ? [options.signal] : [])]),
|
|
120
120
|
});
|
|
121
121
|
headers = connection.headers ?? headers;
|
|
122
|
-
capabilities = Object.freeze({ modelDiscovery: true, liveModelSwitch: connection.major === 2 });
|
|
122
|
+
capabilities = Object.freeze({ modelDiscovery: true, liveModelSwitch: connection.major === 2, backgroundResponses: connection.major === 2 });
|
|
123
123
|
adapter = connection.major === 2
|
|
124
124
|
? createV2Adapter({ ...options, baseUrl, fetch: fetchImpl, headers, environment, pollIntervalMs })
|
|
125
125
|
: createV1Adapter({ request, baseUrl, fetchImpl, headers, pollIntervalMs });
|
|
126
126
|
await adapter.ready?.(workingDirectory);
|
|
127
127
|
})();
|
|
128
128
|
await readiness;
|
|
129
|
-
//
|
|
129
|
+
// Legacy v1 can reject subsequent work after uncertain admission or cancellation.
|
|
130
130
|
await adapter.ready?.(workingDirectory);
|
|
131
131
|
}
|
|
132
132
|
|
|
133
|
+
async function prepareArtifacts(sessionId, workingDirectory, persistent = false) {
|
|
134
|
+
if (useDataUrls || !artifactRoot) return;
|
|
135
|
+
try {
|
|
136
|
+
await mkdir(artifactRoot, { recursive: true, mode: 0o700 });
|
|
137
|
+
const directory = await sessionArtifactDirectory(artifactRoot, sessionId, workingDirectory);
|
|
138
|
+
if (!persistent) await remove(directory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
|
139
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
140
|
+
const stats = await lstat(directory);
|
|
141
|
+
if (!stats.isDirectory() || stats.isSymbolicLink()) throw new Error("Invalid artifact directory.");
|
|
142
|
+
await chmod(directory, 0o700);
|
|
143
|
+
return directory;
|
|
144
|
+
} catch { return undefined; }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function response(text, sessionId, artifactDirectory, slackTurn) {
|
|
148
|
+
const parsed = slackTurn ? parseArtifactDeclaration(text) : { text };
|
|
149
|
+
const files = artifactDirectory && parsed.paths ? await readArtifacts(artifactDirectory, parsed.paths, options.onArtifactOpened) : [];
|
|
150
|
+
return { text: parsed.text, sessionId, ...(files.length ? { files } : {}) };
|
|
151
|
+
}
|
|
152
|
+
|
|
133
153
|
async function request(pathname, init, workingDirectory, controller, acceptedStatuses = [200], reportFatal = true) {
|
|
134
154
|
const url = serverUrl(baseUrl, pathname, workingDirectory);
|
|
135
155
|
let response;
|
|
@@ -165,13 +185,13 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
165
185
|
}
|
|
166
186
|
}
|
|
167
187
|
|
|
168
|
-
async function runTurn({ prompt, sessionId, model, defaultModel, workingDirectory, contextEnvironment = {}, attachments = [], signal, onSession, onInteraction, onPermissionReplied, onPermissionsReconciled }) {
|
|
188
|
+
async function runTurn({ prompt, sessionId, model, defaultModel, workingDirectory, contextEnvironment = {}, attachments = [], signal, onSession, onInteraction, onPermissionReplied, onPermissionsReconciled, onResponse, onError }) {
|
|
169
189
|
if (!prompt?.trim()) throw new Error("A prompt is required.");
|
|
170
190
|
if (stopReason) throw stopReason;
|
|
171
|
-
|
|
191
|
+
const legacySession = options.connection?.major === 1 || capabilities?.backgroundResponses === false;
|
|
192
|
+
if (legacySession && sessionId && activeSessions.has(sessionId)) throw new Error("OpenCode attribution conflict: the session already has an active writer.");
|
|
172
193
|
let temporaryDirectory;
|
|
173
194
|
const selectedModel = normalizeModel(model);
|
|
174
|
-
const newThreadModel = normalizeModel(defaultModel);
|
|
175
195
|
const slackTurn = contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack";
|
|
176
196
|
const controller = new AbortController();
|
|
177
197
|
const abort = () => controller.abort(signal.reason);
|
|
@@ -185,32 +205,28 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
185
205
|
try {
|
|
186
206
|
temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
|
|
187
207
|
controller.signal.throwIfAborted();
|
|
188
|
-
const files = await stageAttachments(attachments, temporaryDirectory, useDataUrls, controller.signal);
|
|
208
|
+
const files = await stageAttachments(attachments, temporaryDirectory, useDataUrls || !!onResponse, controller.signal);
|
|
189
209
|
if (stopReason) throw stopReason;
|
|
190
210
|
await abortable(ready(workingDirectory), controller.signal);
|
|
191
211
|
const prepared = await adapter.resolveSession(sessionId, workingDirectory, controller);
|
|
192
212
|
const selectedSessionId = prepared.sessionId;
|
|
193
213
|
|
|
194
|
-
if (activeSessions.has(selectedSessionId) && activeSessions.get(selectedSessionId).controller !== controller) throw new Error("OpenCode attribution conflict: the session already has an active writer.");
|
|
214
|
+
if (!capabilities.backgroundResponses && activeSessions.has(selectedSessionId) && activeSessions.get(selectedSessionId).controller !== controller) throw new Error("OpenCode attribution conflict: the session already has an active writer.");
|
|
195
215
|
activeSessions.set(selectedSessionId, { controller, workingDirectory, resolved: true });
|
|
196
216
|
await onSession?.(selectedSessionId);
|
|
197
217
|
if (controller.signal.aborted) throw controller.signal.reason;
|
|
218
|
+
const newThreadModel = !selectedModel && (prepared.defaultEligible ?? !prepared.threadModel) ? normalizeModel(defaultModel) : null;
|
|
198
219
|
|
|
199
|
-
if (slackTurn
|
|
200
|
-
try {
|
|
201
|
-
await mkdir(artifactRoot, { recursive: true, mode: 0o700 });
|
|
202
|
-
artifactDirectory = await sessionArtifactDirectory(artifactRoot, selectedSessionId, workingDirectory);
|
|
203
|
-
await remove(artifactDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
|
204
|
-
await mkdir(artifactDirectory, { mode: 0o700 });
|
|
205
|
-
await chmod(artifactDirectory, 0o700);
|
|
206
|
-
} catch {}
|
|
207
|
-
}
|
|
220
|
+
if (slackTurn) artifactDirectory = await prepareArtifacts(selectedSessionId, workingDirectory, capabilities.backgroundResponses && !!onResponse);
|
|
208
221
|
|
|
209
222
|
const text = await adapter.execute({ ...prepared, model: selectedModel, defaultModel: newThreadModel, workingDirectory, controller, prompt, files,
|
|
210
|
-
instructions: turnInstructions(contextEnvironment, artifactDirectory), onInteraction, onPermissionReplied, onPermissionsReconciled
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
223
|
+
instructions: turnInstructions(contextEnvironment, artifactDirectory), onInteraction, onPermissionReplied, onPermissionsReconciled,
|
|
224
|
+
...(capabilities.backgroundResponses && onResponse ? {
|
|
225
|
+
onResponse: async (text, messageId, followSignal) => onResponse(await response(text, selectedSessionId, artifactDirectory, slackTurn), followSignal),
|
|
226
|
+
onError,
|
|
227
|
+
} : {}) });
|
|
228
|
+
if (text?.pending) return { pending: true, sessionId: selectedSessionId };
|
|
229
|
+
return await response(text, selectedSessionId, artifactDirectory, slackTurn);
|
|
214
230
|
} catch (error) {
|
|
215
231
|
if (controller.signal.aborted) throw controller.signal.reason;
|
|
216
232
|
throw error;
|
|
@@ -228,7 +244,7 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
228
244
|
process.stderr.write("Pipa could not remove temporary attachment files.\n");
|
|
229
245
|
}
|
|
230
246
|
}
|
|
231
|
-
if (artifactDirectory) {
|
|
247
|
+
if (artifactDirectory && !(capabilities?.backgroundResponses && onResponse)) {
|
|
232
248
|
try {
|
|
233
249
|
await remove(artifactDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
|
234
250
|
} catch {
|
|
@@ -257,11 +273,11 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
257
273
|
if (signal?.aborted) abort();
|
|
258
274
|
else signal?.addEventListener("abort", abort, { once: true });
|
|
259
275
|
active.add(controller);
|
|
260
|
-
|
|
276
|
+
let timer;
|
|
261
277
|
try {
|
|
262
278
|
await abortable(ready(workingDirectory), controller.signal);
|
|
263
279
|
controller.signal.throwIfAborted();
|
|
264
|
-
if (!capabilities.
|
|
280
|
+
if (!capabilities.backgroundResponses) timer = setTimeout(() => controller.abort(new Error("Model discovery timed out.")), 30_000);
|
|
265
281
|
const catalog = await abortable(adapter.listModels(workingDirectory, controller.signal), controller.signal);
|
|
266
282
|
controller.signal.throwIfAborted();
|
|
267
283
|
return flat ? catalog.models.map((model) => ({ providerID: model.providerID, modelID: model.id, name: model.name })) : catalog;
|
|
@@ -292,7 +308,10 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
292
308
|
},
|
|
293
309
|
async abortTurn(sessionId, reason = new Error("OpenCode turn aborted.")) {
|
|
294
310
|
const turn = activeSessions.get(sessionId);
|
|
295
|
-
if (!turn)
|
|
311
|
+
if (!turn) {
|
|
312
|
+
if (capabilities?.backgroundResponses) await adapter.abortTurn(sessionId);
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
296
315
|
try {
|
|
297
316
|
if (turn.resolved) await adapter.abortTurn(sessionId, turn.workingDirectory);
|
|
298
317
|
} catch {
|
|
@@ -305,7 +324,9 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
305
324
|
stopReason ??= reason;
|
|
306
325
|
readinessController.abort(stopReason);
|
|
307
326
|
for (const controller of active) controller.abort(stopReason);
|
|
327
|
+
adapter?.stopAll?.(stopReason);
|
|
308
328
|
},
|
|
329
|
+
async drain() { await adapter?.drain?.(); },
|
|
309
330
|
};
|
|
310
331
|
}
|
|
311
332
|
|
|
@@ -434,10 +455,6 @@ async function stageAttachments(attachments, temporaryDirectory, useDataUrls, si
|
|
|
434
455
|
function turnInstructions(contextEnvironment, artifactDirectory) {
|
|
435
456
|
const context = Object.entries(contextEnvironment).filter(([, value]) => value !== undefined && value !== null && String(value));
|
|
436
457
|
const instructions = ["For scheduling requests, consult `pipa routine --help`, convert timezone wording to an IANA timezone, preview first, show the normalized details, and create only after user confirmation."];
|
|
437
|
-
const restartCommand = contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack" && contextEnvironment.PIPA_CURRENT_SLACK_CHANNEL_ID
|
|
438
|
-
? `pipa restart --channel ${contextEnvironment.PIPA_CURRENT_SLACK_CHANNEL_ID}${contextEnvironment.PIPA_CURRENT_SLACK_THREAD_TS ? ` --thread ${contextEnvironment.PIPA_CURRENT_SLACK_THREAD_TS}` : ""}`
|
|
439
|
-
: "pipa restart";
|
|
440
|
-
instructions.push(`When asked to restart Pipa, run \`${restartCommand}\`; existing messaging authorization is sufficient. It requests a detached restart and may end this turn. Use \`pipa restart --status\` to inspect the durable outcome; do not claim completion from the request alone. Both commands must run on the Pipa host, not a remote attached OpenCode host. If you lack command access to the Pipa host, explain that limitation instead of running them remotely. The Pipa profile home on that host is ${JSON.stringify(path.resolve(process.env.PIPA_HOME || os.homedir()))}; ensure PIPA_HOME has this value in the command environment. Do not use sequential stop/start or OpenCode /instance/dispose: that disposes an instance, not restarts the server.`);
|
|
441
458
|
if (context.length) instructions.push(`Slack context for this turn (provided here, not as shell environment variables):\n${context.map(([key, value]) => `${key}=${value}`).join("\n")}`);
|
|
442
459
|
if (contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack") {
|
|
443
460
|
instructions.push("Keep naturally short answers inline. For deeper work or larger deliverables, keep the Slack response concise and use the most suitable artifact format.");
|
|
@@ -614,22 +631,20 @@ export async function checkOpenCodeConnection(baseUrl, workingDirectory, options
|
|
|
614
631
|
} else {
|
|
615
632
|
const headers = authenticationHeaders(environment, 2);
|
|
616
633
|
const info = await read("/api/info", headers, undefined, true);
|
|
617
|
-
if (
|
|
618
|
-
|| !Array.isArray(info.urls) || !info.urls.every((url) => typeof url === "string") || typeof info.paths?.tmp !== "string") {
|
|
634
|
+
if (typeof info?.version !== "string") {
|
|
619
635
|
throw new Error("OpenCode identity protocol is unsupported. Check the selected server URL and install a supported v1 or v2 runtime.");
|
|
620
636
|
}
|
|
621
637
|
const identity = parseOpenCodeVersion(info.version);
|
|
622
638
|
if (identity.major !== 2) throw new Error("OpenCode identity/protocol mismatch at /api/info.");
|
|
623
639
|
connection = { ...identity, headers };
|
|
624
640
|
}
|
|
625
|
-
if (options.identity && options.identity.version !== connection.version) throw new Error("OpenCode CLI/server identity mismatch. Check the executable and selected listening server.");
|
|
641
|
+
if (options.identity && (options.identity.major !== connection.major || (connection.major === 1 && options.identity.version !== connection.version))) throw new Error("OpenCode CLI/server identity mismatch. Check the executable and selected listening server.");
|
|
626
642
|
}
|
|
627
643
|
const headers = connection.headers;
|
|
628
644
|
if (connection.major === 2) {
|
|
629
645
|
const locationUrl = `/api/location?${new URLSearchParams({ "location[directory]": workingDirectory })}`;
|
|
630
646
|
const location = await read(locationUrl, headers);
|
|
631
|
-
if (typeof location?.directory !== "string" || !path.isAbsolute(location.directory)
|
|
632
|
-
|| typeof location.project?.directory !== "string" || typeof location.project?.canonical !== "string") throw new Error("OpenCode location protocol has an invalid schema.");
|
|
647
|
+
if (typeof location?.directory !== "string" || !path.isAbsolute(location.directory)) throw new Error("OpenCode location protocol has an invalid schema.");
|
|
633
648
|
if (path.resolve(location.directory) !== path.resolve(workingDirectory)) throw new Error("OpenCode workspace identity mismatch. Select a server serving the configured working directory.");
|
|
634
649
|
} else {
|
|
635
650
|
const location = await read("/path", headers, workingDirectory);
|
package/src/state.mjs
CHANGED
|
@@ -62,7 +62,6 @@ export function pipaPaths(home = process.env.PIPA_HOME || os.homedir()) {
|
|
|
62
62
|
routines: path.join(directory, "routines.json"),
|
|
63
63
|
routinesLock: path.join(directory, "routines.lock"),
|
|
64
64
|
sessions: path.join(directory, "sessions.json"),
|
|
65
|
-
openCodeRecovery: path.join(directory, "opencode-recovery.json"),
|
|
66
65
|
};
|
|
67
66
|
}
|
|
68
67
|
|
|
@@ -205,7 +204,6 @@ export async function loadConfig(file = pipaPaths().config) {
|
|
|
205
204
|
if (config.mentionOnly !== undefined && typeof config.mentionOnly !== "boolean") {
|
|
206
205
|
throw new Error("Invalid Pipa config: mentionOnly must be a boolean.");
|
|
207
206
|
}
|
|
208
|
-
normalizeModel(config.defaultModel);
|
|
209
207
|
return { ...config, slackMode };
|
|
210
208
|
}
|
|
211
209
|
|