@usepipa/pipa 0.6.0-beta.2 → 0.6.0-beta.4
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 -124
- package/bin/pipa.mjs +5 -15
- package/package.json +1 -1
- package/src/app.mjs +43 -23
- package/src/errors.mjs +4 -0
- package/src/models.mjs +25 -39
- package/src/opencode-v2.mjs +107 -149
- package/src/opencode.mjs +10 -9
- package/src/state.mjs +0 -1
package/src/app.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import { createSlackAdapter } from "@chat-adapter/slack";
|
|
|
5
5
|
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
6
6
|
import { canonicalWorkingDirectory, createManifest, createModelSetting, createSessionStore, loadConfig, pipaPaths, saveConfig, slackCommandNames } from "./state.mjs";
|
|
7
7
|
import { createModelPicker } from "./models.mjs";
|
|
8
|
+
import { safeError } from "./errors.mjs";
|
|
8
9
|
import { checkOpenCodeConnection, createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, parseOpenCodeVersion, PipaRestartingError, PipaStoppedError, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
|
|
9
10
|
import { assertRoutineDestinationAllowed, createRoutineScheduler, loadRoutineState } from "./routines.mjs";
|
|
10
11
|
|
|
@@ -85,7 +86,7 @@ export async function startPipa(options = {}) {
|
|
|
85
86
|
const runner = createConversationRunner({ sessionStore, abortTurn: executor.abortTurn,
|
|
86
87
|
interruptPrevious: () => !executor.capabilities?.backgroundResponses, runTurn: async (input) => {
|
|
87
88
|
const currentConfig = await loadCurrentConfig();
|
|
88
|
-
return executor.runTurn({ ...input,
|
|
89
|
+
return executor.runTurn({ ...input, defaultModel: currentConfig.defaultModel });
|
|
89
90
|
} });
|
|
90
91
|
let accepting = true;
|
|
91
92
|
const interactions = createPendingInteractions(config.allowedSlackUserIds);
|
|
@@ -175,7 +176,10 @@ export async function startPipa(options = {}) {
|
|
|
175
176
|
},
|
|
176
177
|
}) : null;
|
|
177
178
|
const modelPicker = createModelPicker({ chat, botName: config.botName, commands, loadConfig: loadCurrentConfig,
|
|
178
|
-
listModels: () =>
|
|
179
|
+
listModels: async (signal) => {
|
|
180
|
+
const catalog = await executor.listModels({ workingDirectory: config.workingDirectory, signal });
|
|
181
|
+
return catalog.models.map((model) => ({ providerID: model.providerID, modelID: model.id, name: model.name }));
|
|
182
|
+
}, setting: createModelSetting(paths.config) });
|
|
179
183
|
chat.onAction?.(interactions.onAction);
|
|
180
184
|
chat.onModalSubmit?.("pipa_custom", interactions.onCustomAnswer);
|
|
181
185
|
|
|
@@ -359,11 +363,15 @@ export function createPipaSlackAdapter(options, drainTimeoutMs = 3_000) {
|
|
|
359
363
|
adapter.startSocketMode = (...args) => disconnecting ? Promise.resolve() : startSocketMode(...args);
|
|
360
364
|
// The pinned adapter's async EventEmitter listener neither observes route
|
|
361
365
|
// rejections nor drains acknowledgments before closing its Socket Mode client.
|
|
362
|
-
adapter.routeSocketEvent = (
|
|
366
|
+
adapter.routeSocketEvent = (body, eventType, ack, options, retryNum) => {
|
|
363
367
|
if (disconnecting) return Promise.resolve();
|
|
364
368
|
const task = (async () => {
|
|
365
369
|
try {
|
|
366
|
-
await route(
|
|
370
|
+
await route(body, eventType, async (response) => {
|
|
371
|
+
// shortcut: 19 KiB stalls live Slack; keep 12 KiB until larger replies pass live trials.
|
|
372
|
+
while (response?.options?.length && Buffer.byteLength(JSON.stringify(response)) > 12 * 1024) response.options.pop();
|
|
373
|
+
await ack(response);
|
|
374
|
+
}, options, retryNum);
|
|
367
375
|
} catch {
|
|
368
376
|
// SDK errors can contain payloads/tokens; keep diagnostics credential-free.
|
|
369
377
|
adapter.logger.error("Pipa Slack Socket Mode event failed.");
|
|
@@ -508,12 +516,18 @@ export function createPendingInteractions(allowedUserIds = []) {
|
|
|
508
516
|
}
|
|
509
517
|
if (event.actionId?.startsWith("pipa_custom_")) {
|
|
510
518
|
const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
|
|
511
|
-
await event.openModal?.(Modal({ callbackId: "pipa_custom", privateMetadata: token
|
|
519
|
+
await event.openModal?.(Modal({ callbackId: "pipa_custom", privateMetadata: `${token}.${entry.questionIndex}`, title: "Custom answer", submitLabel: "Submit", children: [TextInput({ id: "answer", label: question.multiple ? "Answer (replaces checkbox selections)" : "Answer", optional: question.required === false })] }));
|
|
512
520
|
return;
|
|
513
521
|
}
|
|
514
522
|
if (entry.type !== "question") return;
|
|
523
|
+
const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
|
|
524
|
+
if (event.actionId === `pipa_skip_${entry.token}_${entry.questionIndex}` && question.required === false) {
|
|
525
|
+
entry.answers[entry.questionIndex] = null;
|
|
526
|
+
await advance(entry, event.user);
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
515
529
|
if (event.actionId?.startsWith("pipa_select_")) {
|
|
516
|
-
const answers = selectedAnswers(event);
|
|
530
|
+
const answers = selectedAnswers(event, entry);
|
|
517
531
|
if (!answers.length) return;
|
|
518
532
|
entry.answers[entry.questionIndex] = answers;
|
|
519
533
|
return;
|
|
@@ -524,21 +538,23 @@ export function createPendingInteractions(allowedUserIds = []) {
|
|
|
524
538
|
const blockId = `pipa_question_${entry.token}_${entry.questionIndex}`;
|
|
525
539
|
if (values && !Object.hasOwn(values, blockId)) return;
|
|
526
540
|
const selection = values?.[blockId]?.[`pipa_select_${entry.token}`];
|
|
527
|
-
if (selection) entry.answers[entry.questionIndex] = selectedAnswers(event, selection);
|
|
528
|
-
if (!entry.answers[entry.questionIndex]?.length) return;
|
|
541
|
+
if (selection) entry.answers[entry.questionIndex] = selectedAnswers(event, entry, selection);
|
|
542
|
+
if (!entry.answers[entry.questionIndex]?.length && !(selection && question.multiple && question.required === false)) return;
|
|
529
543
|
await advance(entry, event.user);
|
|
530
544
|
return;
|
|
531
545
|
}
|
|
532
546
|
}
|
|
533
547
|
|
|
534
548
|
async function onCustomAnswer(event) {
|
|
535
|
-
const entry = pending.get(event.privateMetadata);
|
|
549
|
+
const entry = pending.get(String(event.privateMetadata ?? "").split(".")[0]);
|
|
536
550
|
if (!entry) return;
|
|
537
551
|
if (event.relatedThread?.id !== entry.threadId) return;
|
|
538
552
|
if (!await canRespond(entry, event.user)) return;
|
|
539
553
|
if (entry.busy || entry.decision !== undefined || entry.type !== "question") return;
|
|
540
|
-
|
|
541
|
-
|
|
554
|
+
if (event.privateMetadata !== `${entry.token}.${entry.questionIndex}`) return;
|
|
555
|
+
const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
|
|
556
|
+
const answer = question.required === undefined ? event.values?.answer?.trim() : event.values?.answer ?? "";
|
|
557
|
+
if (!answer && question.required !== false) return { action: "errors", errors: { answer: "Enter an answer." } };
|
|
542
558
|
// Custom answers intentionally replace selections rather than combine with them.
|
|
543
559
|
entry.answers[entry.questionIndex] = [answer];
|
|
544
560
|
await advance(entry, event.user);
|
|
@@ -547,7 +563,8 @@ export function createPendingInteractions(allowedUserIds = []) {
|
|
|
547
563
|
async function advance(entry, user) {
|
|
548
564
|
if (++entry.questionIndex === (entry.request.questions?.length ?? 1)) {
|
|
549
565
|
const selectedBy = displayName(user?.fullName ?? user?.userName);
|
|
550
|
-
|
|
566
|
+
const answers = entry.answers.map(values => values?.map(answer => typeof answer === "string" ? answer : answer.value ?? answer.label) ?? null);
|
|
567
|
+
await entry.choose({ type: "answer", answers, ...(selectedBy ? { selectedBy } : {}) });
|
|
551
568
|
}
|
|
552
569
|
else entry.message?.edit();
|
|
553
570
|
}
|
|
@@ -584,8 +601,8 @@ function renderSubmitted(entry, decision) {
|
|
|
584
601
|
if (decision?.type === "stop") content = "Dismissed.";
|
|
585
602
|
else if (entry.type === "permission") ({ title, content } = permissionOutcome(entry.request, decision));
|
|
586
603
|
else {
|
|
587
|
-
const answers =
|
|
588
|
-
content = `${decision?.selectedBy ? `${decision.selectedBy} selected` : "Selected"}: ${answers.map((answer) => `“${answer}”`).join(", ")}
|
|
604
|
+
const answers = entry.answers.flat().filter(answer => answer !== null && answer !== undefined && answer !== "");
|
|
605
|
+
content = answers.length ? `${decision?.selectedBy ? `${decision.selectedBy} selected` : "Selected"}: ${answers.map((answer) => `“${typeof answer === "string" ? answer : answer.label}”`).join(", ")}.` : "Optional answers left blank.";
|
|
589
606
|
}
|
|
590
607
|
return { title, content };
|
|
591
608
|
}
|
|
@@ -628,9 +645,9 @@ function renderSlackInteraction(entry) {
|
|
|
628
645
|
];
|
|
629
646
|
}
|
|
630
647
|
const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
|
|
631
|
-
const options = (question.options ?? []).map((option) => ({
|
|
648
|
+
const options = (question.options ?? []).map((option, index) => ({
|
|
632
649
|
text: { type: "plain_text", text: option.label ?? option },
|
|
633
|
-
value: `${entry.token}.${
|
|
650
|
+
value: `${entry.token}.${entry.questionIndex}.${index}`,
|
|
634
651
|
}));
|
|
635
652
|
const selector = options.length && (question.multiple
|
|
636
653
|
? { type: "checkboxes", action_id: `pipa_select_${entry.token}`, options }
|
|
@@ -638,6 +655,7 @@ function renderSlackInteraction(entry) {
|
|
|
638
655
|
const actions = [
|
|
639
656
|
...(question.custom || !options.length ? [slackButton(`pipa_custom_${entry.token}`, "Custom answer", entry.token)] : []),
|
|
640
657
|
...(options.length ? [slackButton(`pipa_submit_${entry.token}`, "Submit", entry.token, "primary")] : []),
|
|
658
|
+
...(question.required === false ? [slackButton(`pipa_skip_${entry.token}_${entry.questionIndex}`, "Skip", entry.token)] : []),
|
|
641
659
|
slackButton(`pipa_dismiss_${entry.token}`, "Dismiss", entry.token, "danger"),
|
|
642
660
|
];
|
|
643
661
|
return [slackHeader(question.header || "Question"), ...(entry.error ? [slackText(entry.error)] : []), slackText(question.question ?? question.header ?? "Choose an answer."), ...(selector ? [{ ...slackActions([selector]), block_id: `pipa_question_${entry.token}_${entry.questionIndex}` }] : []), slackActions(actions)];
|
|
@@ -706,9 +724,16 @@ function slackButton(actionId, text, value, style) {
|
|
|
706
724
|
return { type: "button", action_id: actionId, text: { type: "plain_text", text }, value, ...(style ? { style } : {}) };
|
|
707
725
|
}
|
|
708
726
|
|
|
709
|
-
function selectedAnswers(event, action = event.raw?.actions?.find((item) => item.action_id === event.actionId)) {
|
|
727
|
+
function selectedAnswers(event, entry, action = event.raw?.actions?.find((item) => item.action_id === event.actionId)) {
|
|
710
728
|
const values = action?.selected_options?.map((option) => option.value) ?? [action?.selected_option?.value ?? event.value];
|
|
711
|
-
|
|
729
|
+
const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
|
|
730
|
+
const prefix = `${entry.token}.${entry.questionIndex}.`;
|
|
731
|
+
return values.flatMap(value => {
|
|
732
|
+
if (typeof value !== "string" || !value.startsWith(prefix)) return [];
|
|
733
|
+
const index = value.slice(prefix.length);
|
|
734
|
+
const option = question.options?.[Number(index)];
|
|
735
|
+
return option !== undefined && String(Number(index)) === index ? [option] : [];
|
|
736
|
+
});
|
|
712
737
|
}
|
|
713
738
|
|
|
714
739
|
function interactionToken(event) {
|
|
@@ -900,11 +925,6 @@ function warnMissingSlackScopes(auth, warn = (message) => process.stderr.write(`
|
|
|
900
925
|
} catch {}
|
|
901
926
|
}
|
|
902
927
|
|
|
903
|
-
function safeError(error) {
|
|
904
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
905
|
-
return message.replace(/xox[baprs]-[^\s]+|xapp-[^\s]+/gu, "[redacted]");
|
|
906
|
-
}
|
|
907
|
-
|
|
908
928
|
function slackContext(thread, message) {
|
|
909
929
|
const [, channelId = "", threadTs = ""] = thread.id.split(":");
|
|
910
930
|
return {
|
package/src/errors.mjs
ADDED
package/src/models.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { safeError } from "./errors.mjs";
|
|
2
3
|
|
|
3
4
|
function modelOption(model) {
|
|
4
5
|
return {
|
|
@@ -12,6 +13,10 @@ export function createModelPicker({ chat, botName, commands, loadConfig, listMod
|
|
|
12
13
|
const command = commands[0];
|
|
13
14
|
const pending = new Map();
|
|
14
15
|
const saves = new Set();
|
|
16
|
+
const discard = (token) => {
|
|
17
|
+
pending.get(token)?.controller.abort();
|
|
18
|
+
pending.delete(token);
|
|
19
|
+
};
|
|
15
20
|
let closed = false;
|
|
16
21
|
const userId = (event) => event.user?.userId ?? event.user?.id;
|
|
17
22
|
const authorize = (entry, event, config) => {
|
|
@@ -27,45 +32,34 @@ export function createModelPicker({ chat, botName, commands, loadConfig, listMod
|
|
|
27
32
|
if (closed) return;
|
|
28
33
|
if (event.text.trim() !== "model") return reply(`Use ${command} model to choose the default for this Pipa installation.`);
|
|
29
34
|
let token;
|
|
30
|
-
let failure = `I couldn't read ${botName}'s saved settings. Try ${command} model again in a moment.`;
|
|
31
35
|
try {
|
|
32
36
|
const config = await loadConfig();
|
|
33
37
|
const channelId = event.channel.id.split(":")[1];
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
const entry = { userId: userId(event), channelId, expires: now() + 30 * 60_000 };
|
|
38
|
+
if (!/^[CG][A-Z0-9]+$/u.test(channelId ?? "") || !userId(event) || event.user?.isBot) throw new Error("Model selection isn't enabled for this account or channel.");
|
|
39
|
+
const entry = { userId: userId(event), channelId, expires: now() + 30 * 60_000, controller: new AbortController() };
|
|
37
40
|
authorize(entry, event, config);
|
|
38
|
-
for (const [id, context] of pending) if (context.expires <= now())
|
|
41
|
+
for (const [id, context] of pending) if (context.expires <= now()) discard(id);
|
|
39
42
|
// ponytail: bound abandoned modals in memory; reopen when the oldest context is evicted.
|
|
40
|
-
if (pending.size >= 1000)
|
|
43
|
+
if (pending.size >= 1000) discard(pending.keys().next().value);
|
|
41
44
|
token = randomUUID();
|
|
42
45
|
pending.set(token, entry);
|
|
43
46
|
const view = {
|
|
44
47
|
type: "modal", callback_id: "pipa_model", private_metadata: JSON.stringify({ m: token }), notify_on_close: true,
|
|
45
48
|
title: { type: "plain_text", text: "Pipa model" }, close: { type: "plain_text", text: "Cancel" },
|
|
46
49
|
};
|
|
47
|
-
failure = `Slack couldn't open the model window. Try ${command} model again in a moment.`;
|
|
48
50
|
// Exchange Slack's short-lived trigger before waiting on catalog discovery.
|
|
49
51
|
const opened = await event.adapter.webClient.views.open({ trigger_id: event.triggerId,
|
|
50
52
|
view: { ...view, blocks: [{ type: "section", text: { type: "plain_text", text: "Loading available models…" } }] } });
|
|
51
|
-
if (!opened?.view?.id) throw new Error("
|
|
53
|
+
if (!opened?.view?.id) throw new Error("Slack did not return a model window ID.");
|
|
52
54
|
entry.viewId = opened.view.id;
|
|
53
|
-
|
|
54
|
-
const models = await listModels();
|
|
55
|
+
const models = await listModels(entry.controller.signal);
|
|
55
56
|
if (closed || !pending.has(token)) return;
|
|
56
|
-
failure = `I couldn't read ${botName}'s saved settings. Try ${command} model again in a moment.`;
|
|
57
57
|
const currentConfig = await loadConfig();
|
|
58
58
|
if (closed || pending.get(token) !== entry) return;
|
|
59
|
-
failure = "Model selection isn't enabled for this account or channel. Ask the installation owner to update its access settings.";
|
|
60
59
|
authorize(entry, { ...event, viewId: entry.viewId }, currentConfig);
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
failure = "No configured models are available. Connect a provider in OpenCode, then reopen the model picker.";
|
|
64
|
-
throw new Error("empty catalog");
|
|
65
|
-
}
|
|
66
|
-
entry.options = models.map((model) => ({ option: modelOption(model), search: `${model.providerID} ${model.modelID} ${model.name ?? ""}`.toLowerCase() }));
|
|
60
|
+
if (!models.length) throw new Error("No configured models are available. In a terminal on the machine running Pipa, run `opencode auth login` to connect a provider, then reopen this picker. If Pipa uses an attached OpenCode server, ask its operator to connect a provider there.");
|
|
61
|
+
entry.options = models.map((model) => ({ model: { providerID: model.providerID, modelID: model.modelID, name: model.name }, option: modelOption(model), search: `${model.providerID} ${model.modelID} ${model.name ?? ""}`.toLowerCase() }));
|
|
67
62
|
const initialModel = currentConfig.defaultModel && models.find((model) => model.providerID === currentConfig.defaultModel.providerID && model.modelID === currentConfig.defaultModel.modelID);
|
|
68
|
-
failure = `Slack couldn't display the model list. Try ${command} model again in a moment.`;
|
|
69
63
|
await event.adapter.webClient.views.update({ view_id: entry.viewId, view: {
|
|
70
64
|
...view, submit: { type: "plain_text", text: "Save" },
|
|
71
65
|
blocks: [{ type: "input", block_id: `pipa_model_${token}`, label: { type: "plain_text", text: `Default for new ${botName} threads` },
|
|
@@ -75,12 +69,9 @@ export function createModelPicker({ chat, botName, commands, loadConfig, listMod
|
|
|
75
69
|
} });
|
|
76
70
|
} catch (error) {
|
|
77
71
|
const entry = pending.get(token);
|
|
78
|
-
|
|
72
|
+
discard(token);
|
|
79
73
|
if (closed || (token && !entry)) return;
|
|
80
|
-
|
|
81
|
-
if (error?.data?.error === "invalid_trigger_id") failure = `Slack couldn't use the request to open this window. Run ${command} model again.`;
|
|
82
|
-
if (error?.data?.error === "invalid_arguments") failure = "Slack rejected the model window. This is a Pipa issue, not an access problem.";
|
|
83
|
-
const message = `${failure} Your saved model hasn't changed.`;
|
|
74
|
+
const message = safeError(error);
|
|
84
75
|
if (entry?.viewId) {
|
|
85
76
|
try {
|
|
86
77
|
await event.adapter.webClient.views.update({ view_id: entry.viewId, view: {
|
|
@@ -117,34 +108,29 @@ export function createModelPicker({ chat, botName, commands, loadConfig, listMod
|
|
|
117
108
|
const inputId = `pipa_model_${event.privateMetadata}`;
|
|
118
109
|
try {
|
|
119
110
|
authorize(entry, event, {});
|
|
120
|
-
} catch {
|
|
121
|
-
return { action: "errors", errors: { [inputId]:
|
|
111
|
+
} catch (error) {
|
|
112
|
+
return { action: "errors", errors: { [inputId]: safeError(error) } };
|
|
122
113
|
}
|
|
123
114
|
if (entry.saving) return { action: "close" };
|
|
124
115
|
entry.saving = true;
|
|
125
|
-
// Acknowledge Save before config I/O
|
|
116
|
+
// Acknowledge Save before config I/O and persistence work.
|
|
126
117
|
const task = (async () => {
|
|
127
118
|
let message;
|
|
128
|
-
let failure = `I couldn't verify this model change. Reopen ${command} model. Your saved model hasn't changed.`;
|
|
129
119
|
try {
|
|
130
120
|
try {
|
|
131
121
|
authorize(entry, event, await loadConfig());
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
const model = models.find((item) => modelOption(item).value === event.values?.[inputId]);
|
|
135
|
-
failure = `That model is no longer available. Reopen ${command} model and choose another. Your saved model hasn't changed.`;
|
|
136
|
-
if (!model) throw new Error("unavailable model");
|
|
137
|
-
failure = `I couldn't save your model choice. Reopen ${command} model to try again. Your saved model hasn't changed.`;
|
|
122
|
+
const model = entry.options?.find((item) => item.option.value === event.values?.[inputId])?.model;
|
|
123
|
+
if (!model) throw new Error(`That model is not in this picker. Reopen ${command} model.`);
|
|
138
124
|
await setting.save({ providerID: model.providerID, modelID: model.modelID }, (config) => authorize(entry, event, config));
|
|
139
125
|
message = `New threads will use ${model.name || model.modelID}.`;
|
|
140
|
-
} catch {
|
|
141
|
-
message =
|
|
126
|
+
} catch (error) {
|
|
127
|
+
message = safeError(error);
|
|
142
128
|
}
|
|
143
129
|
if (closed) return;
|
|
144
130
|
authorize(entry, event, await loadConfig());
|
|
145
131
|
await event.adapter.postEphemeral(`slack:${entry.channelId}`, entry.userId, message);
|
|
146
132
|
} finally {
|
|
147
|
-
|
|
133
|
+
discard(event.privateMetadata);
|
|
148
134
|
}
|
|
149
135
|
})();
|
|
150
136
|
saves.add(task);
|
|
@@ -156,7 +142,7 @@ export function createModelPicker({ chat, botName, commands, loadConfig, listMod
|
|
|
156
142
|
});
|
|
157
143
|
chat.onModalClose?.("pipa_model", (event) => {
|
|
158
144
|
const entry = pending.get(event.privateMetadata);
|
|
159
|
-
if (entry?.userId === userId(event) && !entry.saving)
|
|
145
|
+
if (entry?.userId === userId(event) && !entry.saving) discard(event.privateMetadata);
|
|
160
146
|
});
|
|
161
|
-
return { close() { closed = true; pending.
|
|
147
|
+
return { close() { closed = true; for (const token of pending.keys()) discard(token); }, async drain() { await Promise.allSettled([...saves]); } };
|
|
162
148
|
}
|