@usepipa/pipa 0.6.0-beta.1 → 0.6.0-beta.2
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 +12 -10
- package/package.json +1 -1
- package/src/app.mjs +36 -8
- package/src/models.mjs +22 -16
- package/src/opencode-v2.mjs +387 -606
- package/src/opencode.mjs +44 -26
- package/src/state.mjs +0 -1
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,10 +185,11 @@ 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
195
|
const newThreadModel = normalizeModel(defaultModel);
|
|
@@ -185,32 +206,27 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
185
206
|
try {
|
|
186
207
|
temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
|
|
187
208
|
controller.signal.throwIfAborted();
|
|
188
|
-
const files = await stageAttachments(attachments, temporaryDirectory, useDataUrls, controller.signal);
|
|
209
|
+
const files = await stageAttachments(attachments, temporaryDirectory, useDataUrls || !!onResponse, controller.signal);
|
|
189
210
|
if (stopReason) throw stopReason;
|
|
190
211
|
await abortable(ready(workingDirectory), controller.signal);
|
|
191
212
|
const prepared = await adapter.resolveSession(sessionId, workingDirectory, controller);
|
|
192
213
|
const selectedSessionId = prepared.sessionId;
|
|
193
214
|
|
|
194
|
-
if (activeSessions.has(selectedSessionId) && activeSessions.get(selectedSessionId).controller !== controller) throw new Error("OpenCode attribution conflict: the session already has an active writer.");
|
|
215
|
+
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
216
|
activeSessions.set(selectedSessionId, { controller, workingDirectory, resolved: true });
|
|
196
217
|
await onSession?.(selectedSessionId);
|
|
197
218
|
if (controller.signal.aborted) throw controller.signal.reason;
|
|
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,7 +273,8 @@ 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
|
+
// Slack is acknowledged before discovery; allow slow catalogs without waiting forever.
|
|
277
|
+
const timer = setTimeout(() => controller.abort(new Error("Model discovery timed out.")), 30_000);
|
|
261
278
|
try {
|
|
262
279
|
await abortable(ready(workingDirectory), controller.signal);
|
|
263
280
|
controller.signal.throwIfAborted();
|
|
@@ -292,7 +309,10 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
292
309
|
},
|
|
293
310
|
async abortTurn(sessionId, reason = new Error("OpenCode turn aborted.")) {
|
|
294
311
|
const turn = activeSessions.get(sessionId);
|
|
295
|
-
if (!turn)
|
|
312
|
+
if (!turn) {
|
|
313
|
+
if (capabilities?.backgroundResponses) await adapter.abortTurn(sessionId);
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
296
316
|
try {
|
|
297
317
|
if (turn.resolved) await adapter.abortTurn(sessionId, turn.workingDirectory);
|
|
298
318
|
} catch {
|
|
@@ -305,7 +325,9 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
305
325
|
stopReason ??= reason;
|
|
306
326
|
readinessController.abort(stopReason);
|
|
307
327
|
for (const controller of active) controller.abort(stopReason);
|
|
328
|
+
adapter?.stopAll?.(stopReason);
|
|
308
329
|
},
|
|
330
|
+
async drain() { await adapter?.drain?.(); },
|
|
309
331
|
};
|
|
310
332
|
}
|
|
311
333
|
|
|
@@ -434,10 +456,6 @@ async function stageAttachments(attachments, temporaryDirectory, useDataUrls, si
|
|
|
434
456
|
function turnInstructions(contextEnvironment, artifactDirectory) {
|
|
435
457
|
const context = Object.entries(contextEnvironment).filter(([, value]) => value !== undefined && value !== null && String(value));
|
|
436
458
|
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
459
|
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
460
|
if (contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack") {
|
|
443
461
|
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.");
|
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
|
|