@usepipa/pipa 0.4.3 → 0.5.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/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 = {}) {
@@ -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)
@@ -682,7 +678,7 @@ function watchInteractions({ baseUrl, fetchImpl, headers, requestTimeoutMs, sess
682
678
  }
683
679
  };
684
680
 
685
- void (async () => {
681
+ const watching = (async () => {
686
682
  while (!controller.signal.aborted) {
687
683
  try {
688
684
  const url = serverUrl(baseUrl, "/event", workingDirectory);
@@ -718,7 +714,10 @@ function watchInteractions({ baseUrl, fetchImpl, headers, requestTimeoutMs, sess
718
714
  await reconcile();
719
715
  await delay(250, controller.signal).catch(() => undefined);
720
716
  } catch (error) {
721
- if (controller.signal.aborted) return;
717
+ if (controller.signal.aborted) {
718
+ if (!subscribed) rejectReady(controller.signal.reason);
719
+ return;
720
+ }
722
721
  if (!subscribed) {
723
722
  rejectReady(error);
724
723
  return;
@@ -727,6 +726,10 @@ function watchInteractions({ baseUrl, fetchImpl, headers, requestTimeoutMs, sess
727
726
  }
728
727
  }
729
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
+ });
730
733
  return { ready };
731
734
  }
732
735