@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/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
|
|
|
@@ -73,7 +74,6 @@ export async function startPipa(options = {}) {
|
|
|
73
74
|
artifactRoot: path.join(config.workingDirectory, ".pipa", "artifacts"),
|
|
74
75
|
baseUrl: server.baseUrl,
|
|
75
76
|
connection: server.connection,
|
|
76
|
-
recoveryFile: paths.openCodeRecovery,
|
|
77
77
|
onFatal: server.fail,
|
|
78
78
|
});
|
|
79
79
|
await executor.ready?.(config.workingDirectory);
|
|
@@ -83,9 +83,10 @@ export async function startPipa(options = {}) {
|
|
|
83
83
|
await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
|
|
84
84
|
throw error;
|
|
85
85
|
}
|
|
86
|
-
const runner = createConversationRunner({ sessionStore, abortTurn: executor.abortTurn,
|
|
86
|
+
const runner = createConversationRunner({ sessionStore, abortTurn: executor.abortTurn,
|
|
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
|
|
|
@@ -186,6 +190,31 @@ export async function startPipa(options = {}) {
|
|
|
186
190
|
for (const entry of pending) await finishReaction(entry.thread, entry.message, entry.message === currentMessage ? emoji : null);
|
|
187
191
|
};
|
|
188
192
|
|
|
193
|
+
function followCallbacks(thread, message) {
|
|
194
|
+
const allowed = async (signal) => {
|
|
195
|
+
if (!accepting || signal?.aborted) return false;
|
|
196
|
+
const current = await loadCurrentConfig();
|
|
197
|
+
return isAuthorized(thread, message, current);
|
|
198
|
+
};
|
|
199
|
+
return {
|
|
200
|
+
onResponse: async (result, signal) => {
|
|
201
|
+
if (!await allowed(signal)) return;
|
|
202
|
+
await postResult(thread, result, signal);
|
|
203
|
+
if (message) await finishPendingReactions(thread.id, message, "white_check_mark");
|
|
204
|
+
},
|
|
205
|
+
onError: async (error, signal) => {
|
|
206
|
+
if (!await allowed(signal)) return;
|
|
207
|
+
await thread.post(`${config.botName} failed: ${safeError(error)}`);
|
|
208
|
+
if (message) await finishPendingReactions(thread.id, message, "warning");
|
|
209
|
+
},
|
|
210
|
+
onInteraction: (interaction) => interactions.onInteraction({ thread, authorize: async () => {
|
|
211
|
+
if (!await allowed(interaction.signal)) throw new Error("Slack destination is no longer allowed.");
|
|
212
|
+
}, loadAllowedUserIds: async () => (await loadCurrentConfig()).allowedSlackUserIds ?? [] }, interaction),
|
|
213
|
+
onPermissionReplied: interactions.onPermissionReplied,
|
|
214
|
+
onPermissionsReconciled: interactions.onPermissionsReconciled,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
189
218
|
const handle = async (thread, message, subscribe) => {
|
|
190
219
|
if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message, config)) return;
|
|
191
220
|
if (config.mentionOnly && !subscribe && !message.isMention) return;
|
|
@@ -217,6 +246,7 @@ export async function startPipa(options = {}) {
|
|
|
217
246
|
onInteraction: (interaction) => interactions.onInteraction(interactionContext, interaction),
|
|
218
247
|
onPermissionReplied: interactions.onPermissionReplied,
|
|
219
248
|
onPermissionsReconciled: interactions.onPermissionsReconciled,
|
|
249
|
+
...(executor.capabilities?.backgroundResponses ? followCallbacks(thread, message) : {}),
|
|
220
250
|
startTyping: () => thread.startTyping("Working on it..."),
|
|
221
251
|
deliver: (result, signal) => postResult(thread, result, signal),
|
|
222
252
|
deliverFailure: (error) => thread.post(error instanceof PipaRestartingError
|
|
@@ -226,6 +256,7 @@ export async function startPipa(options = {}) {
|
|
|
226
256
|
: `${config.botName} failed: ${safeError(error)}`),
|
|
227
257
|
});
|
|
228
258
|
if (result.superseded) return;
|
|
259
|
+
if (result.pending) return;
|
|
229
260
|
await finishPendingReactions(thread.id, message, result.error instanceof PipaStoppedError ? null : result.error ? "warning" : "white_check_mark");
|
|
230
261
|
} catch (error) {
|
|
231
262
|
await finishPendingReactions(thread.id, message, "warning");
|
|
@@ -294,6 +325,7 @@ export async function startPipa(options = {}) {
|
|
|
294
325
|
await modelPicker.drain();
|
|
295
326
|
await routineScheduler?.drain();
|
|
296
327
|
await runner.drain();
|
|
328
|
+
await executor.drain?.();
|
|
297
329
|
await chat.shutdown();
|
|
298
330
|
server?.stop();
|
|
299
331
|
await server?.wait();
|
|
@@ -331,11 +363,15 @@ export function createPipaSlackAdapter(options, drainTimeoutMs = 3_000) {
|
|
|
331
363
|
adapter.startSocketMode = (...args) => disconnecting ? Promise.resolve() : startSocketMode(...args);
|
|
332
364
|
// The pinned adapter's async EventEmitter listener neither observes route
|
|
333
365
|
// rejections nor drains acknowledgments before closing its Socket Mode client.
|
|
334
|
-
adapter.routeSocketEvent = (
|
|
366
|
+
adapter.routeSocketEvent = (body, eventType, ack, options, retryNum) => {
|
|
335
367
|
if (disconnecting) return Promise.resolve();
|
|
336
368
|
const task = (async () => {
|
|
337
369
|
try {
|
|
338
|
-
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);
|
|
339
375
|
} catch {
|
|
340
376
|
// SDK errors can contain payloads/tokens; keep diagnostics credential-free.
|
|
341
377
|
adapter.logger.error("Pipa Slack Socket Mode event failed.");
|
|
@@ -480,12 +516,18 @@ export function createPendingInteractions(allowedUserIds = []) {
|
|
|
480
516
|
}
|
|
481
517
|
if (event.actionId?.startsWith("pipa_custom_")) {
|
|
482
518
|
const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
|
|
483
|
-
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 })] }));
|
|
484
520
|
return;
|
|
485
521
|
}
|
|
486
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
|
+
}
|
|
487
529
|
if (event.actionId?.startsWith("pipa_select_")) {
|
|
488
|
-
const answers = selectedAnswers(event);
|
|
530
|
+
const answers = selectedAnswers(event, entry);
|
|
489
531
|
if (!answers.length) return;
|
|
490
532
|
entry.answers[entry.questionIndex] = answers;
|
|
491
533
|
return;
|
|
@@ -496,21 +538,23 @@ export function createPendingInteractions(allowedUserIds = []) {
|
|
|
496
538
|
const blockId = `pipa_question_${entry.token}_${entry.questionIndex}`;
|
|
497
539
|
if (values && !Object.hasOwn(values, blockId)) return;
|
|
498
540
|
const selection = values?.[blockId]?.[`pipa_select_${entry.token}`];
|
|
499
|
-
if (selection) entry.answers[entry.questionIndex] = selectedAnswers(event, selection);
|
|
500
|
-
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;
|
|
501
543
|
await advance(entry, event.user);
|
|
502
544
|
return;
|
|
503
545
|
}
|
|
504
546
|
}
|
|
505
547
|
|
|
506
548
|
async function onCustomAnswer(event) {
|
|
507
|
-
const entry = pending.get(event.privateMetadata);
|
|
549
|
+
const entry = pending.get(String(event.privateMetadata ?? "").split(".")[0]);
|
|
508
550
|
if (!entry) return;
|
|
509
551
|
if (event.relatedThread?.id !== entry.threadId) return;
|
|
510
552
|
if (!await canRespond(entry, event.user)) return;
|
|
511
553
|
if (entry.busy || entry.decision !== undefined || entry.type !== "question") return;
|
|
512
|
-
|
|
513
|
-
|
|
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." } };
|
|
514
558
|
// Custom answers intentionally replace selections rather than combine with them.
|
|
515
559
|
entry.answers[entry.questionIndex] = [answer];
|
|
516
560
|
await advance(entry, event.user);
|
|
@@ -519,7 +563,8 @@ export function createPendingInteractions(allowedUserIds = []) {
|
|
|
519
563
|
async function advance(entry, user) {
|
|
520
564
|
if (++entry.questionIndex === (entry.request.questions?.length ?? 1)) {
|
|
521
565
|
const selectedBy = displayName(user?.fullName ?? user?.userName);
|
|
522
|
-
|
|
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 } : {}) });
|
|
523
568
|
}
|
|
524
569
|
else entry.message?.edit();
|
|
525
570
|
}
|
|
@@ -556,8 +601,8 @@ function renderSubmitted(entry, decision) {
|
|
|
556
601
|
if (decision?.type === "stop") content = "Dismissed.";
|
|
557
602
|
else if (entry.type === "permission") ({ title, content } = permissionOutcome(entry.request, decision));
|
|
558
603
|
else {
|
|
559
|
-
const answers =
|
|
560
|
-
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.";
|
|
561
606
|
}
|
|
562
607
|
return { title, content };
|
|
563
608
|
}
|
|
@@ -600,9 +645,9 @@ function renderSlackInteraction(entry) {
|
|
|
600
645
|
];
|
|
601
646
|
}
|
|
602
647
|
const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
|
|
603
|
-
const options = (question.options ?? []).map((option) => ({
|
|
648
|
+
const options = (question.options ?? []).map((option, index) => ({
|
|
604
649
|
text: { type: "plain_text", text: option.label ?? option },
|
|
605
|
-
value: `${entry.token}.${
|
|
650
|
+
value: `${entry.token}.${entry.questionIndex}.${index}`,
|
|
606
651
|
}));
|
|
607
652
|
const selector = options.length && (question.multiple
|
|
608
653
|
? { type: "checkboxes", action_id: `pipa_select_${entry.token}`, options }
|
|
@@ -610,6 +655,7 @@ function renderSlackInteraction(entry) {
|
|
|
610
655
|
const actions = [
|
|
611
656
|
...(question.custom || !options.length ? [slackButton(`pipa_custom_${entry.token}`, "Custom answer", entry.token)] : []),
|
|
612
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)] : []),
|
|
613
659
|
slackButton(`pipa_dismiss_${entry.token}`, "Dismiss", entry.token, "danger"),
|
|
614
660
|
];
|
|
615
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)];
|
|
@@ -678,9 +724,16 @@ function slackButton(actionId, text, value, style) {
|
|
|
678
724
|
return { type: "button", action_id: actionId, text: { type: "plain_text", text }, value, ...(style ? { style } : {}) };
|
|
679
725
|
}
|
|
680
726
|
|
|
681
|
-
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)) {
|
|
682
728
|
const values = action?.selected_options?.map((option) => option.value) ?? [action?.selected_option?.value ?? event.value];
|
|
683
|
-
|
|
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
|
+
});
|
|
684
737
|
}
|
|
685
738
|
|
|
686
739
|
function interactionToken(event) {
|
|
@@ -693,7 +746,7 @@ function displayName(value) {
|
|
|
693
746
|
return name ? name[0].toUpperCase() + name.slice(1) : "";
|
|
694
747
|
}
|
|
695
748
|
|
|
696
|
-
export function createConversationRunner({ sessionStore, runTurn, abortTurn = async () => undefined }) {
|
|
749
|
+
export function createConversationRunner({ sessionStore, runTurn, abortTurn = async () => undefined, interruptPrevious = () => true }) {
|
|
697
750
|
const latest = new Map();
|
|
698
751
|
let closed = false;
|
|
699
752
|
let closeReason;
|
|
@@ -704,7 +757,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
|
|
|
704
757
|
if (closed) return Promise.reject(closeReason);
|
|
705
758
|
const previous = latest.get(conversationKey);
|
|
706
759
|
const reason = new Error("Pipa replaced this turn with a newer message.");
|
|
707
|
-
previous?.controller.abort(reason);
|
|
760
|
+
if (interruptPrevious()) previous?.controller.abort(reason);
|
|
708
761
|
const turn = {
|
|
709
762
|
controller: new AbortController(),
|
|
710
763
|
generation: (previous?.generation ?? 0) + 1,
|
|
@@ -721,7 +774,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
|
|
|
721
774
|
|
|
722
775
|
async function execute(conversationKey, current, previous, input, abortReason) {
|
|
723
776
|
const { deliver, deliverFailure, startTyping, onSession, ...turn } = input;
|
|
724
|
-
const isLatest = () => latest.get(conversationKey)?.generation === current.generation;
|
|
777
|
+
const isLatest = () => !interruptPrevious() || latest.get(conversationKey)?.generation === current.generation;
|
|
725
778
|
const stopped = async () => {
|
|
726
779
|
const error = closeReason ?? current.controller.signal.reason;
|
|
727
780
|
if (!deliverFailure) throw error;
|
|
@@ -731,7 +784,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
|
|
|
731
784
|
let result;
|
|
732
785
|
try {
|
|
733
786
|
if (previous) {
|
|
734
|
-
if (previous.sessionId) await Promise.resolve(abortTurn(previous.sessionId, abortReason)).catch(() => undefined);
|
|
787
|
+
if (previous.sessionId && interruptPrevious()) await Promise.resolve(abortTurn(previous.sessionId, abortReason)).catch(() => undefined);
|
|
735
788
|
await previous.done.catch(() => undefined);
|
|
736
789
|
current.sessionId = previous.sessionId ?? current.sessionId;
|
|
737
790
|
}
|
|
@@ -765,7 +818,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
|
|
|
765
818
|
}
|
|
766
819
|
if (!isLatest()) return { superseded: true };
|
|
767
820
|
if (current.controller.signal.aborted) return stopped();
|
|
768
|
-
if (deliver) await deliver(result, current.controller.signal);
|
|
821
|
+
if (deliver && !result.pending) await deliver(result, current.controller.signal);
|
|
769
822
|
if (!isLatest()) return { superseded: true };
|
|
770
823
|
if (current.controller.signal.aborted) return stopped();
|
|
771
824
|
return result;
|
|
@@ -779,7 +832,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
|
|
|
779
832
|
const aborts = [];
|
|
780
833
|
for (const turn of latest.values()) {
|
|
781
834
|
turn.controller.abort(closeReason);
|
|
782
|
-
if (turn.sessionId) aborts.push(Promise.resolve(abortTurn(turn.sessionId, closeReason)).catch(() => undefined));
|
|
835
|
+
if (turn.sessionId && interruptPrevious()) aborts.push(Promise.resolve(abortTurn(turn.sessionId, closeReason)).catch(() => undefined));
|
|
783
836
|
}
|
|
784
837
|
closing = Promise.allSettled(aborts);
|
|
785
838
|
},
|
|
@@ -872,11 +925,6 @@ function warnMissingSlackScopes(auth, warn = (message) => process.stderr.write(`
|
|
|
872
925
|
} catch {}
|
|
873
926
|
}
|
|
874
927
|
|
|
875
|
-
function safeError(error) {
|
|
876
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
877
|
-
return message.replace(/xox[baprs]-[^\s]+|xapp-[^\s]+/gu, "[redacted]");
|
|
878
|
-
}
|
|
879
|
-
|
|
880
928
|
function slackContext(thread, message) {
|
|
881
929
|
const [, channelId = "", threadTs = ""] = thread.id.split(":");
|
|
882
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,72 +32,46 @@ 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
|
-
const groups = [];
|
|
67
|
-
for (const model of models) {
|
|
68
|
-
const label = model.providerID.slice(0, 75);
|
|
69
|
-
if (groups.at(-1)?.label.text !== label || groups.at(-1).options.length === 100) {
|
|
70
|
-
if (groups.length === 100) {
|
|
71
|
-
failure = "The model catalog exceeds Slack's list limit. Reduce the configured models in OpenCode, then reopen the picker.";
|
|
72
|
-
throw new Error("oversized catalog");
|
|
73
|
-
}
|
|
74
|
-
groups.push({ label: { type: "plain_text", text: label }, options: [] });
|
|
75
|
-
}
|
|
76
|
-
groups.at(-1).options.push(modelOption(model));
|
|
77
|
-
}
|
|
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() }));
|
|
78
62
|
const initialModel = currentConfig.defaultModel && models.find((model) => model.providerID === currentConfig.defaultModel.providerID && model.modelID === currentConfig.defaultModel.modelID);
|
|
79
|
-
// The pinned Chat SDK cannot express grouped selects. Native Slack groups
|
|
80
|
-
// preload more than 100 models and filter locally without options callbacks.
|
|
81
|
-
failure = `Slack couldn't display the model list. Try ${command} model again in a moment.`;
|
|
82
63
|
await event.adapter.webClient.views.update({ view_id: entry.viewId, view: {
|
|
83
64
|
...view, submit: { type: "plain_text", text: "Save" },
|
|
84
65
|
blocks: [{ type: "input", block_id: `pipa_model_${token}`, label: { type: "plain_text", text: `Default for new ${botName} threads` },
|
|
85
|
-
|
|
86
|
-
|
|
66
|
+
hint: { type: "plain_text", text: "Up to 100 matches shown. Type a model name, ID or provider to narrow the results." },
|
|
67
|
+
element: { type: "external_select", action_id: `pipa_model_${token}`, min_query_length: 0,
|
|
68
|
+
placeholder: { type: "plain_text", text: "Search models or providers" }, ...(initialModel ? { initial_option: modelOption(initialModel) } : {}) } }],
|
|
87
69
|
} });
|
|
88
70
|
} catch (error) {
|
|
89
71
|
const entry = pending.get(token);
|
|
90
|
-
|
|
72
|
+
discard(token);
|
|
91
73
|
if (closed || (token && !entry)) return;
|
|
92
|
-
|
|
93
|
-
if (error?.data?.error === "invalid_trigger_id") failure = `Slack couldn't use the request to open this window. Run ${command} model again.`;
|
|
94
|
-
if (error?.data?.error === "invalid_arguments") failure = "Slack rejected the model window. This is a Pipa issue, not an access problem.";
|
|
95
|
-
const message = `${failure} Your saved model hasn't changed.`;
|
|
74
|
+
const message = safeError(error);
|
|
96
75
|
if (entry?.viewId) {
|
|
97
76
|
try {
|
|
98
77
|
await event.adapter.webClient.views.update({ view_id: entry.viewId, view: {
|
|
@@ -106,39 +85,52 @@ export function createModelPicker({ chat, botName, commands, loadConfig, listMod
|
|
|
106
85
|
}
|
|
107
86
|
});
|
|
108
87
|
|
|
88
|
+
chat.onOptionsLoad?.(async (event) => {
|
|
89
|
+
if (!event.actionId?.startsWith("pipa_model_")) return;
|
|
90
|
+
const entry = pending.get(event.actionId.slice("pipa_model_".length));
|
|
91
|
+
try {
|
|
92
|
+
authorize(entry, event, {});
|
|
93
|
+
authorize(entry, event, await loadConfig());
|
|
94
|
+
if (pending.get(event.actionId.slice("pipa_model_".length)) !== entry || entry.saving) return [];
|
|
95
|
+
const terms = String(event.query ?? "").toLowerCase().trim().split(/\s+/u);
|
|
96
|
+
const matches = [];
|
|
97
|
+
for (const { option, search } of entry.options ?? []) {
|
|
98
|
+
if (!terms.every((term) => search.includes(term))) continue;
|
|
99
|
+
matches.push({ label: option.text.text, description: option.description.text, value: option.value });
|
|
100
|
+
if (matches.length === 100) break;
|
|
101
|
+
}
|
|
102
|
+
return matches;
|
|
103
|
+
} catch { return []; }
|
|
104
|
+
});
|
|
105
|
+
|
|
109
106
|
chat.onModalSubmit?.("pipa_model", (event) => {
|
|
110
107
|
const entry = pending.get(event.privateMetadata);
|
|
111
108
|
const inputId = `pipa_model_${event.privateMetadata}`;
|
|
112
109
|
try {
|
|
113
110
|
authorize(entry, event, {});
|
|
114
|
-
} catch {
|
|
115
|
-
return { action: "errors", errors: { [inputId]:
|
|
111
|
+
} catch (error) {
|
|
112
|
+
return { action: "errors", errors: { [inputId]: safeError(error) } };
|
|
116
113
|
}
|
|
117
114
|
if (entry.saving) return { action: "close" };
|
|
118
115
|
entry.saving = true;
|
|
119
|
-
// Acknowledge Save before config I/O
|
|
116
|
+
// Acknowledge Save before config I/O and persistence work.
|
|
120
117
|
const task = (async () => {
|
|
121
118
|
let message;
|
|
122
|
-
let failure = `I couldn't verify this model change. Reopen ${command} model. Your saved model hasn't changed.`;
|
|
123
119
|
try {
|
|
124
120
|
try {
|
|
125
121
|
authorize(entry, event, await loadConfig());
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
const model = models.find((item) => modelOption(item).value === event.values?.[inputId]);
|
|
129
|
-
failure = `That model is no longer available. Reopen ${command} model and choose another. Your saved model hasn't changed.`;
|
|
130
|
-
if (!model) throw new Error("unavailable model");
|
|
131
|
-
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.`);
|
|
132
124
|
await setting.save({ providerID: model.providerID, modelID: model.modelID }, (config) => authorize(entry, event, config));
|
|
133
125
|
message = `New threads will use ${model.name || model.modelID}.`;
|
|
134
|
-
} catch {
|
|
135
|
-
message =
|
|
126
|
+
} catch (error) {
|
|
127
|
+
message = safeError(error);
|
|
136
128
|
}
|
|
137
129
|
if (closed) return;
|
|
138
130
|
authorize(entry, event, await loadConfig());
|
|
139
131
|
await event.adapter.postEphemeral(`slack:${entry.channelId}`, entry.userId, message);
|
|
140
132
|
} finally {
|
|
141
|
-
|
|
133
|
+
discard(event.privateMetadata);
|
|
142
134
|
}
|
|
143
135
|
})();
|
|
144
136
|
saves.add(task);
|
|
@@ -150,7 +142,7 @@ export function createModelPicker({ chat, botName, commands, loadConfig, listMod
|
|
|
150
142
|
});
|
|
151
143
|
chat.onModalClose?.("pipa_model", (event) => {
|
|
152
144
|
const entry = pending.get(event.privateMetadata);
|
|
153
|
-
if (entry?.userId === userId(event) && !entry.saving)
|
|
145
|
+
if (entry?.userId === userId(event) && !entry.saving) discard(event.privateMetadata);
|
|
154
146
|
});
|
|
155
|
-
return { close() { closed = true; pending.
|
|
147
|
+
return { close() { closed = true; for (const token of pending.keys()) discard(token); }, async drain() { await Promise.allSettled([...saves]); } };
|
|
156
148
|
}
|