@usepipa/pipa 0.4.2 → 0.5.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/src/opencode.mjs CHANGED
@@ -5,12 +5,7 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { pathToFileURL } from "node:url";
7
7
 
8
- const SECRET_ENV_KEYS = new Set([
9
- "PIPA_SLACK_APP_TOKEN",
10
- "PIPA_SLACK_BOT_TOKEN",
11
- "SLACK_APP_TOKEN",
12
- "SLACK_BOT_TOKEN",
13
- ]);
8
+ const SLACK_SECRET_ENV_KEY = /(?:^|_)SLACK(?:_[A-Z0-9]+)*_(?:TOKEN|SECRET)$/iu;
14
9
  const LISTENING_URL = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d+/u;
15
10
 
16
11
  export const MAX_ATTACHMENT_BYTES = 100 * 1024 * 1024;
@@ -26,7 +21,7 @@ export class PipaStoppedError extends Error {
26
21
  }
27
22
 
28
23
  export function cleanChildEnvironment(environment = process.env) {
29
- return Object.fromEntries(Object.entries(environment).filter(([key]) => !SECRET_ENV_KEYS.has(key.toUpperCase())));
24
+ return Object.fromEntries(Object.entries(environment).filter(([key]) => !SLACK_SECRET_ENV_KEY.test(key)));
30
25
  }
31
26
 
32
27
  export async function startSocketOpenCodeServer(config, options = {}) {
@@ -38,7 +33,7 @@ export async function startSocketOpenCodeServer(config, options = {}) {
38
33
 
39
34
  if (attachUrl) {
40
35
  const baseUrl = normalizeBaseUrl(attachUrl);
41
- await waitForHealth(baseUrl, fetchImpl, headers, startupTimeoutMs);
36
+ await waitForWorkspace(baseUrl, config.workingDirectory, fetchImpl, headers, startupTimeoutMs);
42
37
  return externalServer(baseUrl);
43
38
  }
44
39
 
@@ -65,7 +60,7 @@ export async function startSocketOpenCodeServer(config, options = {}) {
65
60
  child.stdout?.resume();
66
61
  child.stderr?.resume();
67
62
  await Promise.race([
68
- waitForHealth(baseUrl, fetchImpl, headers, startupTimeoutMs),
63
+ waitForWorkspace(baseUrl, config.workingDirectory, fetchImpl, headers, startupTimeoutMs),
69
64
  exit.then((code) => { throw new Error(`OpenCode server exited before startup with code ${code}.`); }),
70
65
  ]);
71
66
  return ownedServer(baseUrl, child, exit, platform);
@@ -202,7 +197,7 @@ export function createOpenCodeExecutor(options = {}) {
202
197
  }
203
198
  await request(`/session/${encodeURIComponent(selectedSessionId)}/prompt_async`, {
204
199
  method: "POST",
205
- body: JSON.stringify(promptBody(prompt.trim(), files, contextEnvironment, artifactDirectory)),
200
+ body: JSON.stringify(promptBody(prompt, files, contextEnvironment, artifactDirectory)),
206
201
  }, workingDirectory, controller, [204]);
207
202
 
208
203
  while (true) {
@@ -214,7 +209,7 @@ export function createOpenCodeExecutor(options = {}) {
214
209
  const status = statuses?.[selectedSessionId]?.type;
215
210
  if (dismissed && status !== "busy" && status !== "retry") return { text: "", sessionId: selectedSessionId };
216
211
  if (["error", "failed", "cancelled"].includes(status) || finalMessage?.error) throw new Error("OpenCode failed to complete the turn.");
217
- if (finalMessage && (status === "idle" || (!status && finalMessage.completed))) {
212
+ if (finalMessage && ((status !== "retry" && finalMessage.completed && finalMessage.finish === "stop") || status === "idle" || (!status && finalMessage.completed))) {
218
213
  if (!finalMessage.text && permissionRejected) return { text: "Stopped after a permission was rejected.", sessionId: selectedSessionId };
219
214
  if (!finalMessage.text) throw new Error("OpenCode completed without assistant text.");
220
215
  const parsed = slackTurn ? parseArtifactDeclaration(finalMessage.text) : { text: finalMessage.text };
@@ -377,7 +372,7 @@ async function stageAttachments(attachments, temporaryDirectory, timeoutMs, useD
377
372
  function promptBody(prompt, files, contextEnvironment, artifactDirectory) {
378
373
  const parts = [{ type: "text", text: prompt }, ...files.map((file) => ({ type: "file", ...file }))];
379
374
  const context = Object.entries(contextEnvironment).filter(([, value]) => value !== undefined && value !== null && String(value));
380
- const instructions = [];
375
+ 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."];
381
376
  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")}`);
382
377
  if (contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack") {
383
378
  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.");
@@ -471,6 +466,7 @@ function latestAssistantMessage(messages, baseline) {
471
466
  return {
472
467
  completed: typeof message.info.time?.completed === "number",
473
468
  error: message.info.error,
469
+ finish: message.info.finish,
474
470
  text: message.parts
475
471
  .filter((part) => part.type === "text" && typeof part.text === "string" && part.text)
476
472
  .map((part) => part.text)
@@ -528,21 +524,23 @@ function externalServer(baseUrl) {
528
524
  };
529
525
  }
530
526
 
531
- async function waitForHealth(baseUrl, fetchImpl, headers, timeoutMs) {
527
+ async function waitForWorkspace(baseUrl, workingDirectory, fetchImpl, headers, timeoutMs) {
532
528
  const deadline = Date.now() + timeoutMs;
533
529
  while (Date.now() < deadline) {
534
530
  try {
535
- const response = await fetchImpl(`${baseUrl}/global/health`, {
531
+ const status = await fetchImpl(serverUrl(baseUrl, "/session/status", workingDirectory), {
536
532
  headers,
537
533
  signal: AbortSignal.timeout(Math.min(5_000, Math.max(1, deadline - Date.now()))),
538
534
  });
539
- if (response.ok && (await response.json())?.healthy === true) return;
535
+ const sessions = status.ok ? await status.json() : null;
536
+ if (sessions && typeof sessions === "object" && !Array.isArray(sessions)
537
+ && Object.values(sessions).every((session) => session && typeof session === "object" && typeof session.type === "string")) return;
540
538
  } catch {
541
- // The server can accept its socket shortly before the health route is ready.
539
+ // OpenCode can accept its socket before the configured workspace is ready.
542
540
  }
543
541
  await delay(Math.min(250, Math.max(0, deadline - Date.now())));
544
542
  }
545
- throw new Error("OpenCode server health check timed out.");
543
+ throw new Error("OpenCode workspace readiness check timed out.");
546
544
  }
547
545
 
548
546
  function readListeningUrl(child, timeoutMs) {
@@ -680,14 +678,22 @@ function watchInteractions({ baseUrl, fetchImpl, headers, requestTimeoutMs, sess
680
678
  }
681
679
  };
682
680
 
683
- void (async () => {
681
+ const watching = (async () => {
684
682
  while (!controller.signal.aborted) {
685
683
  try {
686
684
  const url = serverUrl(baseUrl, "/event", workingDirectory);
687
- const response = await fetchImpl(url, {
688
- headers: { ...headers, accept: "text/event-stream" },
689
- signal: AbortSignal.any([controller.signal, AbortSignal.timeout(requestTimeoutMs)]),
690
- });
685
+ const connection = new AbortController();
686
+ const connectionTimer = setTimeout(() => connection.abort(new Error("OpenCode event connection timed out.")), requestTimeoutMs);
687
+ connectionTimer.unref?.();
688
+ let response;
689
+ try {
690
+ response = await fetchImpl(url, {
691
+ headers: { ...headers, accept: "text/event-stream" },
692
+ signal: AbortSignal.any([controller.signal, connection.signal]),
693
+ });
694
+ } finally {
695
+ clearTimeout(connectionTimer);
696
+ }
691
697
  if (!response.ok) throw new OpenCodeRequestError(response.status);
692
698
  await reconcile();
693
699
  if (!subscribed) {
@@ -708,7 +714,10 @@ function watchInteractions({ baseUrl, fetchImpl, headers, requestTimeoutMs, sess
708
714
  await reconcile();
709
715
  await delay(250, controller.signal).catch(() => undefined);
710
716
  } catch (error) {
711
- if (controller.signal.aborted) return;
717
+ if (controller.signal.aborted) {
718
+ if (!subscribed) rejectReady(controller.signal.reason);
719
+ return;
720
+ }
712
721
  if (!subscribed) {
713
722
  rejectReady(error);
714
723
  return;
@@ -717,6 +726,10 @@ function watchInteractions({ baseUrl, fetchImpl, headers, requestTimeoutMs, sess
717
726
  }
718
727
  }
719
728
  })();
729
+ void watching.catch((error) => {
730
+ if (!subscribed) rejectReady(error);
731
+ else if (!controller.signal.aborted) process.stderr.write("OpenCode interaction watcher failed.\n");
732
+ });
720
733
  return { ready };
721
734
  }
722
735