pi-qu 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BotoVed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,126 @@
1
- # Temporary Holding Version
1
+ # pi-qu — зеркало question-тула pi в Telegram
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Пакет [pi](https://github.com/earendil-works/pi-coding-agent), который дублирует в Telegram
4
+ каждый диалог инструмента `question`. Вопросы, заданные в **любой** pi-сессии (в любом
5
+ чате/окне), приходят в твой Telegram-чат сообщением с inline-кнопками; ответить можно из
6
+ Telegram, из интерфейса сессии, где был задан вопрос, или отменить с любой стороны.
7
+ **Побеждает первый ответ.**
8
+
9
+ ```plantuml
10
+ @startuml
11
+ participant "Pi-сессия (любая)" as P
12
+ participant "pi-qu (override question)" as Q
13
+ participant "Telegram (QuestionBot)" as T
14
+ actor Юзер
15
+
16
+ P -> Q : вопрос через question
17
+ Q -> T : сообщение с кнопками (✳️/ℹ️/▶️)
18
+ Q -> P : локальный диалог в TUI
19
+ Юзер -> T : ответ (кнопка / текст)
20
+ Юзер -> P : ответ (локально)
21
+ T -->> Q : poller → answers/<qid>.json
22
+ Q -> P : первый ответ побеждает,\nвторая сторона закрывается
23
+ @enduml
24
+ ```
25
+
26
+ ## Скриншоты
27
+
28
+ | Вопрос в Telegram | Множественный выбор |
29
+ | --- | --- |
30
+ | ![Вопрос в Telegram](docs/tg-question.jpg) | ![Множественный выбор](docs/tg-multiple.jpg) |
31
+
32
+ После ответа сообщение сохраняет текст вопроса, снимает кнопки и дописывает
33
+ статусную строку (`✅ Ответ: …`).
34
+
35
+ ## Возможности
36
+
37
+ - **Универсальный override** — пакет регистрирует свой инструмент `question`, поэтому
38
+ работает в каждой сессии, где загружен, независимо от того, из какого окна/чата задан вопрос.
39
+ - **Контекст сохраняется** — в сообщении: название чата (сессии), вопрос, последнее
40
+ сообщение агента («почему спрашиваю»), варианты с описаниями и пометка ✏️, если разрешён
41
+ свободный ответ.
42
+ - **Ответы: кнопки и текст** — тапай варианты (одиночные или multiple с тогглами и
43
+ «Готово») или просто напиши свободный текст в чат бота, если вопрос разрешает custom-ответ.
44
+ - **Привязка и перепривязка чата** — `/start` или `/bind` в чате бота назначает его
45
+ целевым (перепривязка работает так же в любой момент). Если `chatId` уже задан в конфиге,
46
+ сообщение привязки это подтверждает.
47
+ - **Строгая политика сообщений** — бот ретранслирует только вопросы и ответы: сообщения,
48
+ которые не `/start`, не `/bind` и не ответ на активный вопрос, игнорируются.
49
+ - **Поллер-синглтон** — один long-poll-воркер на машину (файловый лок + heartbeat в
50
+ `$AGENT_DIR/tg-ask/poller.lock`); остальные процессы просто ждут свой файл ответа.
51
+ - **Мягкий фолбэк** — нет токена, сбой отправки или мёртвый поллер → тул остаётся только
52
+ с локальным диалогом. `PI_QU_DISABLE=1` полностью отключает пакет.
53
+ - **Таймауты** — вопрос истекает через `answerTimeoutMin` минут (по умолчанию 30) и
54
+ сообщает об истечении агенту.
55
+
56
+ ## Установка
57
+
58
+ ```bash
59
+ pi install <путь-к-этому-репо> # или добавить в "packages" в ~/.pi/agent/settings.json
60
+ ```
61
+
62
+ Если используешь **@janvitos/pi-plan-build**, отключи его собственный тул вопроса, чтобы
63
+ pi-qu перехватил имя `question` (в pi при совпадении имён побеждает первый зарегистрировавший,
64
+ а порядок загрузки пакетов не гарантирован):
65
+
66
+ ```bash
67
+ # ~/.pi/agent/pi-plan-build.json
68
+ { "questionTool": false }
69
+ ```
70
+
71
+ Затем запусти `pi` и выполни команду:
72
+
73
+ ```
74
+ /tg-ask-setup
75
+ ```
76
+
77
+ Она спросит токен от BotFather, сервер Bot API (выбор «штатный» —
78
+ `https://api.telegram.org` — или свой адрес, например self-hosted Bot API server)
79
+ и id чата (можно оставить пустым и привязать позже
80
+ через `/start`), и сохранит `~/.pi/agent/tg-ask.json`:
81
+
82
+ ```json
83
+ { "token": "123456:ABC…", "apiBase": "https://api.telegram.org", "chatId": "181403158" }
84
+ ```
85
+
86
+ Env-переменные (высший приоритет): `PI_TG_ASK_TOKEN`, `PI_TG_ASK_APIBASE`,
87
+ `PI_TG_ASK_CHAT_ID`.
88
+
89
+ ## Как отвечать
90
+
91
+ | Где | Как |
92
+ | --- | --- |
93
+ | Интерфейс сессии | стандартный диалог вопроса pi (варианты, custom, Esc — отмена) |
94
+ | Telegram | inline-кнопки; свободный текст = custom-ответ; «Отмена» отменяет |
95
+
96
+ Сообщение в Telegram имеет формат:
97
+
98
+ ```
99
+ ✳️ <название чата (сессии)>:
100
+ ℹ️ <последнее сообщение агента — предпосылки вопроса>
101
+
102
+ ▶️ <текст вопроса>
103
+ • 1. вариант — описание
104
+ • 2. …
105
+ ```
106
+
107
+ При множественном выборе кнопки работают как тогглы, «✔ Готово» подтверждает выбор.
108
+ После ответа сообщение **сохраняет весь текст вопроса**, теряет кнопки и получает
109
+ статусную строку: `✅ Ответ: <выбор>` (или `✏️ Ответ текстом: …`, `🚫 Отменено`,
110
+ `⏰ Истекло без ответа`, при ответе в сессии — `✅ Ответ (в сессии): …`).
111
+
112
+ ## Разработка
113
+
114
+ ```bash
115
+ npm install
116
+ npm test # юнит-тесты (node --test, extensions/lib.test.ts)
117
+ npx tsc -p tsconfig.json # строгая проверка типов
118
+ ```
119
+
120
+ Состояние живёт в `$AGENT_DIR/tg-ask/`: `pending/*.json` (вопросы, ждущие ответа),
121
+ `answers/*.json` (обработанные ответы), `poller.lock`, `poller.log` (лог поллера),
122
+ `tool.log` (диагностика: загрузка расширения, запуск тула, результат отправки).
123
+
124
+ ## Лицензия
125
+
126
+ MIT
@@ -0,0 +1,116 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import {
4
+ answerFromChoice,
5
+ answerFromCustom,
6
+ buildKeyboard,
7
+ buildQuestionText,
8
+ CB,
9
+ type PendingQuestion,
10
+ formatAnswers,
11
+ isLockStale,
12
+ makeQid,
13
+ mergeConfig,
14
+ shortLabel,
15
+ truncateTail,
16
+ } from "./lib.ts";
17
+
18
+ const cfg = (over: Record<string, unknown>) => mergeConfig(over as never, {});
19
+
20
+ test("mergeConfig: env overrides file, defaults applied", () => {
21
+ assert.equal(mergeConfig({ token: "f", apiBase: "http://x" }, { PI_TG_ASK_TOKEN: "e" })?.token, "e");
22
+ assert.equal(mergeConfig({ token: "f" }, { PI_TG_ASK_TOKEN: "e", PI_TG_ASK_APIBASE: "http://y" })?.apiBase, "http://y");
23
+ const base = cfg({ token: "t" })!;
24
+ assert.equal(base.apiBase, "https://api.telegram.org");
25
+ assert.equal(base.answerTimeoutMin, 30);
26
+ assert.equal(base.chatId, undefined);
27
+ });
28
+
29
+ test("mergeConfig: null without token, timeout parsing", () => {
30
+ assert.equal(mergeConfig({}, {}), null);
31
+ assert.equal(cfg({ token: "t", answerTimeoutMin: 5 })?.answerTimeoutMin, 5);
32
+ assert.equal(cfg({ token: "t", answerTimeoutMin: "10" })?.answerTimeoutMin, 10);
33
+ assert.equal(cfg({ token: "t", answerTimeoutMin: -1 })?.answerTimeoutMin, 30);
34
+ });
35
+
36
+ test("truncateTail keeps tail and marks head", () => {
37
+ assert.equal(truncateTail("hello"), "hello");
38
+ const long = "x".repeat(800) + "TAIL";
39
+ const t = truncateTail(long, 700);
40
+ assert.equal(t.length, 701);
41
+ assert.ok(t.endsWith("TAIL"));
42
+ assert.ok(t.startsWith("…"));
43
+ });
44
+
45
+ test("shortLabel truncates", () => {
46
+ assert.equal(shortLabel("abc"), "abc");
47
+ assert.equal(shortLabel("a".repeat(30)).length, 24);
48
+ });
49
+
50
+ const prompt = {
51
+ session: "MySession",
52
+ header: "Deploy",
53
+ question: "Деплоим?",
54
+ options: [
55
+ { label: "Да", description: "прямо сейчас" },
56
+ { label: "Нет" },
57
+ ],
58
+ };
59
+
60
+ test("buildQuestionText: session line, context, question, numbering, custom hint", () => {
61
+ const text = buildQuestionText({ ...prompt, context: "Контекст предыдущего сообщения" });
62
+ assert.ok(text.startsWith("✳️ MySession:"));
63
+ assert.ok(text.includes("ℹ️ Контекст предыдущего сообщения"));
64
+ assert.ok(/\n\n▶️ Деплоим\?/.test(text));
65
+ assert.ok(!text.includes("["));
66
+ assert.ok(text.includes("1. Да — прямо сейчас"));
67
+ assert.ok(text.includes("2. Нет"));
68
+ assert.ok(text.includes("✏️"));
69
+ const noCustom = buildQuestionText({ ...prompt, custom: false });
70
+ assert.ok(!noCustom.includes("✏️"));
71
+ });
72
+
73
+ const p: PendingQuestion = {
74
+ qid: "q1",
75
+ chatId: "42",
76
+ messageId: 7,
77
+ session: "s",
78
+ header: "h",
79
+ question: "q",
80
+ labels: ["Alpha", "Beta", "Gamma"],
81
+ multiple: false,
82
+ custom: true,
83
+ ts: 1,
84
+ };
85
+
86
+ test("buildKeyboard: single choice, 2 per row, cancel row", () => {
87
+ const kb = buildKeyboard({ options: p.labels.map((l) => ({ label: l })) }, "q1");
88
+ assert.deepEqual(kb[0].map((b) => b.text), ["1. Alpha", "2. Beta"]);
89
+ assert.deepEqual(kb[1].map((b) => b.text), ["3. Gamma", "✖ Отмена"]);
90
+ assert.equal(kb.length, 2);
91
+ assert.equal(kb[0][0].callback_data, `${CB.tap}|q1|0`);
92
+ });
93
+
94
+ test("buildKeyboard: multiple adds done button", () => {
95
+ const kb = buildKeyboard({ options: p.labels.map((l) => ({ label: l })), multiple: true, custom: false }, "q1");
96
+ assert.equal(kb.at(-1)!.filter((b) => b.callback_data === `${CB.done}|q1`).length, 1);
97
+ });
98
+
99
+ test("answers", () => {
100
+ assert.deepEqual(answerFromChoice(p, 1), { question: "q", header: "h", answers: ["Beta"], custom: false });
101
+ assert.deepEqual(answerFromCustom(p, "свой вариант"), { question: "q", header: "h", answers: ["свой вариант"], custom: true });
102
+ assert.equal(formatAnswers([{ question: "q", header: "h", answers: ["a", "b"], custom: false }]), `"q"="a, b"`);
103
+ assert.equal(formatAnswers([{ question: "q", header: "h", answers: [], custom: false }]), `"q"="Unanswered"`);
104
+ });
105
+
106
+ test("makeQid unique enough", () => {
107
+ const set = new Set(Array.from({ length: 2000 }, () => makeQid()));
108
+ assert.ok(set.size > 1990);
109
+ });
110
+
111
+ test("isLockStale", () => {
112
+ assert.ok(isLockStale(null));
113
+ assert.ok(isLockStale({}));
114
+ assert.ok(isLockStale({ ts: Date.now() - 60_000 }));
115
+ assert.ok(!isLockStale({ ts: Date.now() }));
116
+ });
@@ -0,0 +1,199 @@
1
+ /**
2
+ * pi-qu — pure helpers, no runtime deps on pi (unit-testable with node --experimental-strip-types).
3
+ */
4
+
5
+ export interface QuConfig {
6
+ token: string;
7
+ apiBase: string; // default https://api.telegram.org
8
+ chatId?: string; // bound chat (user id for private chats)
9
+ answerTimeoutMin: number; // default 30
10
+ }
11
+
12
+ export interface QuOption {
13
+ label: string;
14
+ description?: string;
15
+ }
16
+
17
+ export interface QuPrompt {
18
+ question: string;
19
+ header: string;
20
+ options: QuOption[];
21
+ multiple?: boolean;
22
+ custom?: boolean;
23
+ }
24
+
25
+ export interface QuAnswer {
26
+ question: string;
27
+ header: string;
28
+ answers: string[];
29
+ custom: boolean;
30
+ }
31
+
32
+ export interface PendingQuestion {
33
+ qid: string;
34
+ chatId: string;
35
+ messageId: number;
36
+ session: string;
37
+ header: string;
38
+ question: string;
39
+ labels: string[];
40
+ multiple: boolean;
41
+ custom: boolean;
42
+ ts: number;
43
+ /** multiple-mode toggle state (indices), maintained by the poller */
44
+ toggled?: number[];
45
+ /** exact text the TG message was sent with — poller keeps it on edit */
46
+ text?: string;
47
+ }
48
+
49
+ export type TgAnswer =
50
+ | { type: "choice"; labels: string[]; via: "tg" }
51
+ | { type: "custom"; text: string; via: "tg" }
52
+ | { type: "cancel"; via: "tg" };
53
+
54
+ /* ------------------------------- config ------------------------------- */
55
+
56
+ export function defaultApiBase(): string {
57
+ return "https://api.telegram.org";
58
+ }
59
+
60
+ export function mergeConfig(
61
+ file: Partial<QuConfig> | null,
62
+ env: Record<string, string | undefined>,
63
+ ): QuConfig | null {
64
+ const token = (env.PI_TG_ASK_TOKEN ?? file?.token ?? "").trim();
65
+ if (!token) return null;
66
+ return {
67
+ token,
68
+ apiBase: (env.PI_TG_ASK_APIBASE ?? file?.apiBase ?? "").trim() || defaultApiBase(),
69
+ chatId: (env.PI_TG_ASK_CHAT_ID ?? file?.chatId ?? "").trim() || undefined,
70
+ answerTimeoutMin: positiveNumber(file?.answerTimeoutMin) ?? 30,
71
+ };
72
+ }
73
+
74
+ function positiveNumber(v: unknown): number | undefined {
75
+ const n = typeof v === "number" ? v : typeof v === "string" ? Number(v) : NaN;
76
+ return Number.isFinite(n) && n > 0 ? n : undefined;
77
+ }
78
+
79
+ /* ------------------------------- text --------------------------------- */
80
+
81
+ const CONTEXT_MAX = 700;
82
+ const OPTION_LABEL_MAX = 24;
83
+
84
+ /** Keep the tail (closest to the question) of long context text. */
85
+ export function truncateTail(text: string, max = CONTEXT_MAX): string {
86
+ const t = text.replace(/\s+$/g, "").trim();
87
+ if (t.length <= max) return t;
88
+ return `…${t.slice(-max)}`;
89
+ }
90
+
91
+ export function shortLabel(label: string, max = OPTION_LABEL_MAX): string {
92
+ return label.length > max ? `${label.slice(0, max - 1)}…` : label;
93
+ }
94
+
95
+ export interface BuildTextArgs {
96
+ session: string;
97
+ header: string;
98
+ question: string;
99
+ context?: string; // previous assistant message
100
+ options: QuOption[];
101
+ multiple?: boolean;
102
+ custom?: boolean;
103
+ }
104
+
105
+ /**
106
+ * Message body: [session] header, context, question, option list.
107
+ * Plain text — no parse_mode, no escaping issues.
108
+ */
109
+ export function buildQuestionText(a: BuildTextArgs): string {
110
+ const lines: string[] = [];
111
+ lines.push(`✳️ ${a.session}:`);
112
+ if (a.context?.trim()) lines.push(`ℹ️ ${truncateTail(a.context)}`);
113
+ lines.push("", `▶️ ${a.question}`);
114
+ a.options.forEach((o, i) => {
115
+ lines.push(`${a.multiple ? "□" : "•"} ${i + 1}. ${o.label}${o.description ? ` — ${o.description}` : ""}`);
116
+ });
117
+ if (a.custom !== false) lines.push("", "✏️ Можно ответить текстом (custom).");
118
+ else lines.push("", "…или кнопкой выше.");
119
+ if (a.multiple) lines.push("Множественный выбор: жмите варианты, затем «Готово».");
120
+ return lines.join("\n");
121
+ }
122
+
123
+ /* ------------------------------ keyboard ------------------------------ */
124
+
125
+ export interface TgInlineButton {
126
+ text: string;
127
+ callback_data: string;
128
+ }
129
+
130
+ export type TgInlineKeyboard = TgInlineButton[][];
131
+
132
+ export const CB = {
133
+ tap: "c", // c|qid|idx — single choice / multiple toggle
134
+ done: "d", // d|qid — multiple done
135
+ cancel: "x", // x|qid — cancel
136
+ } as const;
137
+
138
+ export function buildKeyboard(prompt: Pick<QuPrompt, "options" | "multiple" | "custom">, qid: string): TgInlineKeyboard {
139
+ const rows: TgInlineKeyboard = [];
140
+ const perRow = 2;
141
+ if (prompt.multiple) {
142
+ for (let i = 0; i < prompt.options.length; i += perRow) {
143
+ rows.push(
144
+ prompt.options.slice(i, i + perRow).map((o, j) => ({
145
+ text: shortLabel(o.label),
146
+ callback_data: `${CB.tap}|${qid}|${i + j}`,
147
+ })),
148
+ );
149
+ }
150
+ rows.push([{ text: "✔ Готово", callback_data: `${CB.done}|${qid}` }]);
151
+ } else {
152
+ for (let i = 0; i < prompt.options.length; i += perRow) {
153
+ rows.push(
154
+ prompt.options.slice(i, i + perRow).map((o, j) => ({
155
+ text: `${i + j + 1}. ${shortLabel(o.label)}`,
156
+ callback_data: `${CB.tap}|${qid}|${i + j}`,
157
+ })),
158
+ );
159
+ }
160
+ }
161
+ const cancelRow: TgInlineButton[] = [{ text: "✖ Отмена", callback_data: `${CB.cancel}|${qid}` }];
162
+ if (rows.length && rows[rows.length - 1].length < perRow) rows.push([...rows.pop()!, ...cancelRow]);
163
+ else rows.push(cancelRow);
164
+ return rows;
165
+ }
166
+
167
+ /* ------------------------------ answers ------------------------------- */
168
+
169
+ /** Same format as the upstream question tool: "question"="a, b", … joined by ", ". */
170
+ export function formatAnswers(answers: QuAnswer[]): string {
171
+ return answers
172
+ .map((a) => `"${a.question}"="${a.answers.length ? a.answers.join(", ") : "Unanswered"}"`)
173
+ .join(", ");
174
+ }
175
+
176
+ export function answerFromChoice(p: PendingQuestion, idx: number): QuAnswer {
177
+ return {
178
+ question: p.question,
179
+ header: p.header,
180
+ answers: [p.labels[idx] ?? String(idx + 1)],
181
+ custom: false,
182
+ };
183
+ }
184
+
185
+ export function answerFromCustom(p: PendingQuestion, text: string): QuAnswer {
186
+ return { question: p.question, header: p.header, answers: [text], custom: true };
187
+ }
188
+
189
+ /* ------------------------------- misc --------------------------------- */
190
+
191
+ export function makeQid(): string {
192
+ return Math.random().toString(36).slice(2, 8) + Date.now().toString(36).slice(-4);
193
+ }
194
+
195
+ export const LOCK_STALE_MS = 20_000;
196
+
197
+ export function isLockStale(lock: { ts?: number } | null | undefined): boolean {
198
+ return !lock || typeof lock.ts !== "number" || Date.now() - lock.ts > LOCK_STALE_MS;
199
+ }
@@ -0,0 +1,385 @@
1
+ /**
2
+ * pi-qu — Telegram mirror for the pi `question` tool.
3
+ *
4
+ * Overrides the `question` tool (registered by @janvitos/pi-plan-build) in every session
5
+ * that loads this package: each question is sent to Telegram (inline buttons) AND shown
6
+ * in the local session UI at the same time; the first answer wins.
7
+ *
8
+ * The bot is strictly a question/answer relay: messages outside an active question are
9
+ * ignored, except /start and /bind which (re)bind the target chat.
10
+ *
11
+ * Config: $AGENT_DIR/tg-ask.json { token, apiBase?, chatId?, answerTimeoutMin? }
12
+ * Env: PI_TG_ASK_TOKEN, PI_TG_ASK_APIBASE, PI_TG_ASK_CHAT_ID (override the file)
13
+ */
14
+
15
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
16
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
17
+ import { Type } from "typebox";
18
+ import { appendFileSync, readFileSync, writeFileSync, mkdirSync } from "fs";
19
+ import {
20
+ type QuAnswer,
21
+ type QuConfig,
22
+ type QuPrompt,
23
+ formatAnswers,
24
+ defaultApiBase,
25
+ makeQid,
26
+ mergeConfig,
27
+ } from "./lib.ts";
28
+ import {
29
+ dropPending,
30
+ setAgentDir,
31
+ startPollerOnce,
32
+ tgEditMessage,
33
+ tgSendQuestion,
34
+ tgLastError,
35
+ waitTgAnswer,
36
+ writePending,
37
+ type SentQuestion,
38
+ } from "./tg.ts";
39
+
40
+ setAgentDir(getAgentDir());
41
+
42
+ const STATE_DIR = `${getAgentDir()}/tg-ask`;
43
+
44
+ /** Lightweight file diagnostics for battle-testing (tg-ask/tool.log). */
45
+ function diag(line: string): void {
46
+ try {
47
+ appendFileSync(`${STATE_DIR}/tool.log`, `${new Date().toISOString()} ${line}\n`);
48
+ } catch {}
49
+ }
50
+
51
+ diag(`extension loaded (agentDir=${getAgentDir()})`);
52
+
53
+ const CONFIG_FILE = `${getAgentDir()}/tg-ask.json`;
54
+
55
+ /* ------------------------------- config ------------------------------- */
56
+
57
+ function readConfigFile(): Partial<QuConfig> | null {
58
+ try {
59
+ const raw = JSON.parse(readFileSync(CONFIG_FILE, "utf-8"));
60
+ return raw && typeof raw === "object" ? raw : null;
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ function loadConfig(): QuConfig | null {
67
+ return mergeConfig(readConfigFile(), process.env);
68
+ }
69
+
70
+ function writeConfigFile(patch: Partial<QuConfig>): void {
71
+ try {
72
+ mkdirSync(getAgentDir(), { recursive: true });
73
+ } catch {}
74
+ let current: Partial<QuConfig> = {};
75
+ try {
76
+ current = JSON.parse(readFileSync(CONFIG_FILE, "utf-8")) ?? {};
77
+ } catch {}
78
+ writeFileSync(CONFIG_FILE, JSON.stringify({ ...current, ...patch }, null, "\t") + "\n");
79
+ }
80
+
81
+ /* --------------------------- local question UI ------------------------ */
82
+
83
+ const CANCELLED_TEXT = "You chose not to answer the question(s). Awaiting your instructions.";
84
+ const TIMEOUT_TEXT = "Telegram question expired without an answer. Awaiting your instructions.";
85
+
86
+ class QuestionCancelledError extends Error {
87
+ constructor(message = CANCELLED_TEXT) {
88
+ super(message);
89
+ this.name = "QuestionCancelledError";
90
+ }
91
+ }
92
+
93
+ /** Local dialog path — mirrors the upstream tool's UX (MIT, @janvitos/pi-plan-build). */
94
+ async function askOneLocal(ctx: any, prompt: QuPrompt, signal: AbortSignal | undefined): Promise<QuAnswer> {
95
+ const allowCustom = prompt.custom !== false;
96
+ const labels = prompt.options.map((o) => (o.description ? `${o.label} — ${o.description}` : o.label));
97
+ const selected: string[] = [];
98
+ let usedCustom = false;
99
+
100
+ if (!prompt.multiple) {
101
+ const choices = [...labels, ...(allowCustom ? ["Type your own answer"] : [])];
102
+ const choice = await ctx.ui.select(`${prompt.header}: ${prompt.question}`, choices, { signal });
103
+ if (!choice) throw new QuestionCancelledError();
104
+ if (allowCustom && choice === "Type your own answer") {
105
+ const custom = await ctx.ui.input(prompt.header, prompt.question, { signal });
106
+ if (!custom?.trim()) throw new QuestionCancelledError();
107
+ selected.push(custom.trim());
108
+ usedCustom = true;
109
+ } else {
110
+ selected.push(prompt.options[labels.indexOf(choice)]?.label ?? choice);
111
+ }
112
+ } else {
113
+ const remaining = prompt.options.map((o) => o.label);
114
+ while (true) {
115
+ const choices = [
116
+ ...remaining.map((l) => `Add: ${l}`),
117
+ ...(allowCustom ? ["Add a custom answer"] : []),
118
+ ...(selected.length ? [`Done (${selected.join(", ")})`] : []),
119
+ ];
120
+ const choice = await ctx.ui.select(`${prompt.header}: ${prompt.question}`, choices, { signal });
121
+ if (!choice) throw new QuestionCancelledError();
122
+ if (choice.startsWith("Done (")) break;
123
+ if (choice === "Add a custom answer") {
124
+ const custom = await ctx.ui.input(prompt.header, prompt.question, { signal });
125
+ if (custom?.trim()) {
126
+ selected.push(custom.trim());
127
+ usedCustom = true;
128
+ }
129
+ continue;
130
+ }
131
+ const label = choice.slice("Add: ".length);
132
+ selected.push(label);
133
+ remaining.splice(remaining.indexOf(label), 1);
134
+ if (!remaining.length && !allowCustom) break;
135
+ }
136
+ }
137
+
138
+ return { question: prompt.question, header: prompt.header, answers: selected, custom: usedCustom };
139
+ }
140
+
141
+ /* --------------------------- previous message ------------------------- */
142
+
143
+ function extractText(content: unknown): string {
144
+ if (typeof content === "string") return content;
145
+ if (!Array.isArray(content)) return "";
146
+ return content
147
+ .filter((b: any) => b && typeof b === "object" && b.type === "text" && typeof b.text === "string")
148
+ .map((b: any) => b.text)
149
+ .join("\n");
150
+ }
151
+
152
+ function lastAssistantMessage(ctx: any): string | undefined {
153
+ try {
154
+ const entries = ctx.sessionManager.getEntries() as any[];
155
+ for (let i = entries.length - 1; i >= 0; i--) {
156
+ const e = entries[i];
157
+ if (e?.type === "message" && e.message?.role === "assistant") {
158
+ const text = extractText(e.message.content).trim();
159
+ if (text) return text;
160
+ }
161
+ }
162
+ } catch {}
163
+ return undefined;
164
+ }
165
+
166
+ /* ------------------------------- tool --------------------------------- */
167
+
168
+ const OptionSchema = Type.Object({
169
+ label: Type.String({ description: "Display label for the option" }),
170
+ description: Type.Optional(Type.String({ description: "Explanation shown with the option" })),
171
+ });
172
+
173
+ const PromptSchema = Type.Object({
174
+ question: Type.String({ description: "The question to ask" }),
175
+ header: Type.String({ description: "Short header; prefer 12 characters or fewer" }),
176
+ options: Type.Array(OptionSchema, { minItems: 2, maxItems: 4 }),
177
+ multiple: Type.Optional(Type.Boolean({ description: "Allow more than one selection" })),
178
+ custom: Type.Optional(Type.Boolean({ description: "Allow a custom answer; defaults to true" })),
179
+ });
180
+
181
+ const QuestionParameters = Type.Object({
182
+ questions: Type.Array(PromptSchema, { minItems: 1, description: "Questions to ask the user" }),
183
+ });
184
+
185
+ export default function (pi: ExtensionAPI) {
186
+ if (process.env.PI_QU_DISABLE === "1") return;
187
+
188
+ pi.registerTool({
189
+ name: "question",
190
+ label: "Question (pi-qu)",
191
+ description:
192
+ 'Use this tool when you need to ask the user questions during execution. The question is mirrored to Telegram (inline buttons) and shown locally at the same time; the first answer wins. When custom is enabled (default), do not add an Other option yourself. Put the recommended option first and suffix its label with "(Recommended)".',
193
+ parameters: QuestionParameters,
194
+ executionMode: "sequential",
195
+
196
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
197
+ diag("execute: pi-qu tool fired");
198
+ if (!ctx.hasUI) throw new Error("The question tool requires an interactive TUI or RPC client");
199
+ if (!params.questions.length) throw new Error("At least one question is required");
200
+
201
+ const cfg = loadConfig();
202
+ diag(`execute: cfg=${cfg ? `token…${cfg.token.slice(-4)} api=${cfg.apiBase} chat=${cfg.chatId ?? "—"}` : "null"}`);
203
+ const session = pi.getSessionName() || "pi";
204
+ const answers: QuAnswer[] = [];
205
+
206
+ try {
207
+ for (const prompt of params.questions) {
208
+ answers.push(await askCombined(ctx, cfg, prompt, session, signal));
209
+ }
210
+ return {
211
+ content: [{ type: "text", text: `Answers: ${formatAnswers(answers)}` }],
212
+ details: { answers },
213
+ };
214
+ } catch (error) {
215
+ if (!(error instanceof QuestionCancelledError)) throw error;
216
+ return {
217
+ content: [{ type: "text", text: error.message }],
218
+ details: { cancelled: true },
219
+ terminate: true,
220
+ };
221
+ }
222
+ },
223
+ });
224
+
225
+ /* ----------------------------- commands ----------------------------- */
226
+
227
+ async function setupHandler(_args: string, ctx: any): Promise<void> {
228
+ const current = loadConfig();
229
+ const token = (
230
+ await ctx.ui.input("pi-qu: токен бота (от BotFather)", current?.token ? "(Enter = оставить текущий)" : "123456:ABC-DEF…")
231
+ )?.trim();
232
+ if (token && token !== "(Enter = оставить текущий)" && !/^\d+:[\w-]+$/.test(token)) {
233
+ ctx.ui.notify("Токен выглядит некорректно — конфиг не сохранён", "error");
234
+ return;
235
+ }
236
+ // Server choice after the token: native Bot API by default, or a custom address.
237
+ const nativeBase = defaultApiBase();
238
+ const cur = current?.apiBase?.trim();
239
+ const hasCustom = !!cur && cur !== nativeBase;
240
+ const serverChoice = await ctx.ui.select("pi-qu: сервер Bot API", hasCustom
241
+ ? [
242
+ `Штатный (${nativeBase})`,
243
+ `Свой — оставить текущий (${cur})`,
244
+ "Свой — ввести другой адрес",
245
+ ]
246
+ : [
247
+ `Штатный (${nativeBase})`,
248
+ "Свой — ввести адрес",
249
+ ]);
250
+ let apiBase = nativeBase;
251
+ if (serverChoice.startsWith("Свой — оставить")) apiBase = cur as string;
252
+ else if (serverChoice.includes("ввести")) {
253
+ apiBase = (await ctx.ui.input("pi-qu: адрес Bot API", nativeBase))?.trim() || nativeBase;
254
+ }
255
+ const chatId = (await ctx.ui.input("pi-qu: chat id (пусто = привязать командой /start боту)", current?.chatId ?? ""))?.trim();
256
+
257
+ const patch: Partial<QuConfig> = {};
258
+ if (token && token !== "(Enter = оставить текущий)") patch.token = token;
259
+ if (apiBase) patch.apiBase = apiBase;
260
+ if (chatId !== undefined) patch.chatId = chatId || undefined;
261
+ writeConfigFile(patch);
262
+
263
+ const cfg = loadConfig();
264
+ if (cfg) {
265
+ startPollerOnce(cfg, writeConfigFile);
266
+ const where = cfg.chatId ? `чат ${cfg.chatId}` : "чат НЕ привязан — открой чат с ботом и нажми /start";
267
+ ctx.ui.notify(`pi-qu: конфиг сохранён (${cfg.apiBase}, ${where})`, "info");
268
+ } else {
269
+ ctx.ui.notify("pi-qu: токен не задан — зеркалирование выключено", "error");
270
+ }
271
+ }
272
+
273
+ pi.registerCommand("tg-ask-setup", {
274
+ description: "pi-qu: настроить Telegram-зеркало вопросов (токен, apiBase, чат)",
275
+ handler: setupHandler,
276
+ });
277
+ pi.registerCommand("pi-qu-setup", {
278
+ description: "pi-qu: alias of tg-ask-setup",
279
+ handler: setupHandler,
280
+ });
281
+
282
+ const bootCfg = loadConfig();
283
+ if (bootCfg) startPollerOnce(bootCfg, writeConfigFile);
284
+
285
+ /* ------------------------- combined asking -------------------------- */
286
+
287
+ type Combined =
288
+ | { kind: "local"; answer: QuAnswer }
289
+ | { kind: "tg"; answer: Awaited<ReturnType<typeof waitTgAnswer>> }
290
+ | { kind: "cancel" }
291
+ | { kind: "timeout" };
292
+
293
+ async function askCombined(
294
+ ctx: any,
295
+ cfg: QuConfig | null,
296
+ prompt: QuPrompt,
297
+ session: string,
298
+ agentSignal: AbortSignal | undefined,
299
+ ): Promise<QuAnswer> {
300
+ const localController = new AbortController();
301
+ const onAgentAbort = () => localController.abort();
302
+ agentSignal?.addEventListener?.("abort", onAgentAbort, { once: true });
303
+
304
+ // 1) Mirror to Telegram (silently skipped when unconfigured / send fails).
305
+ let qid: string | undefined;
306
+ let sent: SentQuestion | null = null;
307
+ if (cfg?.token && cfg.chatId) {
308
+ qid = makeQid();
309
+ try {
310
+ sent = await tgSendQuestion(cfg, prompt, qid, session, lastAssistantMessage(ctx));
311
+ } catch (e) {
312
+ diag(`tgSend threw: ${e instanceof Error ? e.message : e}`);
313
+ }
314
+ if (!sent) {
315
+ diag(`tgSend failed (local-only): lastError=${tgLastError}`);
316
+ qid = undefined; // TG send failed → local-only
317
+ } else {
318
+ writePending({
319
+ qid,
320
+ chatId: cfg.chatId,
321
+ messageId: sent.messageId,
322
+ session,
323
+ header: prompt.header,
324
+ question: prompt.question,
325
+ labels: prompt.options.map((o) => o.label),
326
+ multiple: !!prompt.multiple,
327
+ custom: prompt.custom !== false,
328
+ ts: Date.now(),
329
+ text: sent.text,
330
+ });
331
+ }
332
+ }
333
+ if (qid && cfg) startPollerOnce(cfg, writeConfigFile);
334
+
335
+ const deadline = Date.now() + (cfg?.answerTimeoutMin ?? 30) * 60_000;
336
+ try {
337
+ ctx.ui.setStatus?.("pi-qu", "waiting for answer (local/telegram)…");
338
+ } catch {}
339
+
340
+ const localPromise: Promise<Combined> = askOneLocal(ctx, prompt, localController.signal)
341
+ .then((answer): Combined => ({ kind: "local", answer }))
342
+ .catch((e: unknown) => (e instanceof QuestionCancelledError ? { kind: "cancel" } : Promise.reject(e)));
343
+ const tgPromise: Promise<Combined> = qid
344
+ ? waitTgAnswer(qid, deadline)
345
+ .then((answer): Combined => ({ kind: "tg", answer }))
346
+ .catch((e: unknown) =>
347
+ e instanceof Error && e.message === "pi-qu-timeout" ? { kind: "timeout" } : Promise.reject(e),
348
+ )
349
+ : new Promise<Combined>(() => {});
350
+
351
+ let winner: Combined;
352
+ try {
353
+ winner = await Promise.race([localPromise, tgPromise]);
354
+ } finally {
355
+ agentSignal?.removeEventListener?.("abort", onAgentAbort);
356
+ try {
357
+ ctx.ui.setStatus?.("pi-qu", "");
358
+ } catch {}
359
+ }
360
+
361
+ // Stop the losing branch.
362
+ if (winner.kind !== "local") localController.abort();
363
+ if (qid) dropPending(qid);
364
+
365
+ if (winner.kind === "local") {
366
+ if (sent && cfg) void tgEditMessage(cfg, sent, `✅ Ответ (в сессии): ${winner.answer.answers.join(", ")}`, { clearKeyboard: true });
367
+ return winner.answer;
368
+ }
369
+ if (winner.kind === "cancel") {
370
+ if (sent && cfg) void tgEditMessage(cfg, sent, "🚫 Отменено в сессии", { clearKeyboard: true });
371
+ throw new QuestionCancelledError();
372
+ }
373
+ if (winner.kind === "timeout") {
374
+ if (sent && cfg) void tgEditMessage(cfg, sent, "⏰ Истекло без ответа", { clearKeyboard: true });
375
+ throw new QuestionCancelledError(TIMEOUT_TEXT);
376
+ }
377
+
378
+ // Telegram answer.
379
+ const a = winner.answer;
380
+ if (a.type === "cancel") throw new QuestionCancelledError();
381
+ return a.type === "choice"
382
+ ? { question: prompt.question, header: prompt.header, answers: a.labels, custom: false }
383
+ : { question: prompt.question, header: prompt.header, answers: [a.text], custom: true };
384
+ }
385
+ }
@@ -0,0 +1,403 @@
1
+ /**
2
+ * pi-qu — Telegram machinery: API client, shared state (pending/answers), and the
3
+ * singleton long-poll worker. No pi dependencies — unit/E2E testable standalone.
4
+ *
5
+ * State layout under $AGENT_DIR/tg-ask/:
6
+ * pending/<qid>.json — questions waiting for an answer (shared between processes)
7
+ * answers/<qid>.json — answer written by the poller, consumed by the asking process
8
+ * poller.lock — singleton lock {pid, ts} with heartbeat
9
+ * poller.log — poller diagnostics
10
+ */
11
+
12
+ import { appendFileSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "fs";
13
+ import {
14
+ buildKeyboard,
15
+ buildQuestionText,
16
+ CB,
17
+ type TgInlineKeyboard,
18
+ isLockStale,
19
+ shortLabel,
20
+ truncateTail,
21
+ type PendingQuestion,
22
+ type QuConfig,
23
+ type QuPrompt,
24
+ type TgAnswer,
25
+ } from "./lib.ts";
26
+
27
+ let AGENT_DIR = (globalThis as any).__piquAgentDir ?? "/home/boss/.pi/agent";
28
+ let STATE_DIR = `${AGENT_DIR}/tg-ask`;
29
+ let PENDING_DIR = `${STATE_DIR}/pending`;
30
+ let ANSWERS_DIR = `${STATE_DIR}/answers`;
31
+ let LOCK_FILE = `${STATE_DIR}/poller.lock`;
32
+ let LOG_FILE = `${STATE_DIR}/poller.log`;
33
+
34
+ /** Override the agent dir before first use (tests point it at a temp dir). */
35
+ export function setAgentDir(dir: string): void {
36
+ AGENT_DIR = dir;
37
+ STATE_DIR = `${dir}/tg-ask`;
38
+ PENDING_DIR = `${STATE_DIR}/pending`;
39
+ ANSWERS_DIR = `${STATE_DIR}/answers`;
40
+ LOCK_FILE = `${STATE_DIR}/poller.lock`;
41
+ LOG_FILE = `${STATE_DIR}/poller.log`;
42
+ }
43
+
44
+ /* ------------------------------ telegram ------------------------------ */
45
+
46
+ export interface TgResult<T> {
47
+ ok: boolean;
48
+ result?: T;
49
+ description?: string;
50
+ error_code?: number;
51
+ }
52
+
53
+ /** Last failed Bot API call, for diagnostics (live binding). */
54
+ export let tgLastError = "";
55
+
56
+ export async function tg<T = any>(cfg: QuConfig, method: string, payload?: Record<string, unknown>): Promise<TgResult<T>> {
57
+ try {
58
+ const res = await fetch(`${cfg.apiBase}/bot${cfg.token}/${method}`, {
59
+ method: payload ? "POST" : "GET",
60
+ headers: payload ? { "content-type": "application/json" } : undefined,
61
+ body: payload ? JSON.stringify(payload) : undefined,
62
+ signal: AbortSignal.timeout(60_000),
63
+ });
64
+ const r = (await res.json()) as TgResult<T>;
65
+ if (!r.ok) tgLastError = `${method}: ${r.error_code ?? ""} ${r.description ?? ""}`.trim();
66
+ return r;
67
+ } catch (e) {
68
+ tgLastError = `${method}: ${e instanceof Error ? e.message : String(e)}`;
69
+ return { ok: false, description: tgLastError };
70
+ }
71
+ }
72
+
73
+ export interface SentQuestion {
74
+ chatId: string;
75
+ messageId: number;
76
+ /** exact text the message was sent with — used to keep the question on edit */
77
+ text?: string;
78
+ }
79
+
80
+ /** Send one question; returns null when the API call fails or no chat is bound. */
81
+ export async function tgSendQuestion(
82
+ cfg: QuConfig,
83
+ prompt: QuPrompt,
84
+ qid: string,
85
+ session: string,
86
+ context?: string,
87
+ ): Promise<SentQuestion | null> {
88
+ if (!cfg.chatId) return null;
89
+ const text = buildQuestionText({
90
+ session,
91
+ header: prompt.header,
92
+ question: prompt.question,
93
+ context,
94
+ options: prompt.options,
95
+ multiple: prompt.multiple,
96
+ custom: prompt.custom,
97
+ });
98
+ const res = await tg(cfg, "sendMessage", {
99
+ chat_id: cfg.chatId,
100
+ text,
101
+ disable_web_page_preview: true,
102
+ reply_markup: { inline_keyboard: buildKeyboard(prompt, qid) },
103
+ });
104
+ return res.ok && res.result
105
+ ? { chatId: String(res.result.chat?.id ?? cfg.chatId), messageId: res.result.message_id, text }
106
+ : null;
107
+ }
108
+
109
+ /** Edit a question message; keeps the original text and appends the status line. */
110
+ export function tgEditMessage(
111
+ cfg: QuConfig,
112
+ s: SentQuestion,
113
+ status: string,
114
+ opts?: { clearKeyboard?: boolean },
115
+ ): Promise<unknown> {
116
+ const text = s.text ? `${s.text}\n\n${status}` : status;
117
+ return tg(cfg, "editMessageText", {
118
+ chat_id: s.chatId,
119
+ message_id: s.messageId,
120
+ text,
121
+ ...(opts?.clearKeyboard ? { reply_markup: { inline_keyboard: [] } } : {}),
122
+ });
123
+ }
124
+
125
+ /* ------------------------------- state -------------------------------- */
126
+
127
+ export function ensureDirs(): void {
128
+ for (const d of [STATE_DIR, PENDING_DIR, ANSWERS_DIR]) {
129
+ try {
130
+ mkdirSync(d, { recursive: true });
131
+ } catch {}
132
+ }
133
+ }
134
+
135
+ const pendingPath = (qid: string) => `${PENDING_DIR}/${qid}.json`;
136
+ const answersPath = (qid: string) => `${ANSWERS_DIR}/${qid}.json`;
137
+
138
+ export function writePending(p: PendingQuestion): void {
139
+ writeFileSync(pendingPath(p.qid), JSON.stringify(p));
140
+ }
141
+
142
+ function peekPending(qid: string): PendingQuestion | null {
143
+ try {
144
+ return JSON.parse(readFileSync(pendingPath(qid), "utf-8")) as PendingQuestion;
145
+ } catch {
146
+ return null;
147
+ }
148
+ }
149
+
150
+ function takePending(qid: string): PendingQuestion | null {
151
+ const p = peekPending(qid);
152
+ if (p) rmSync(pendingPath(qid), { force: true });
153
+ return p;
154
+ }
155
+
156
+ export function dropPending(qid: string): void {
157
+ try {
158
+ rmSync(pendingPath(qid), { force: true });
159
+ } catch {}
160
+ }
161
+
162
+ function putAnswer(qid: string, answer: TgAnswer): void {
163
+ writeFileSync(answersPath(qid), JSON.stringify(answer));
164
+ }
165
+
166
+ function listPending(): PendingQuestion[] {
167
+ try {
168
+ return readdirSync(PENDING_DIR)
169
+ .filter((f) => f.endsWith(".json"))
170
+ .map((f) => peekPending(f.slice(0, -5)))
171
+ .filter((p): p is PendingQuestion => !!p)
172
+ .sort((a, b) => a.ts - b.ts);
173
+ } catch {
174
+ return [];
175
+ }
176
+ }
177
+
178
+ /* ------------------------------- poller ------------------------------- */
179
+
180
+ const g = globalThis as any;
181
+
182
+ /**
183
+ * Start the singleton poller if it is not running in this process yet.
184
+ * `onConfigPatch` is called when the user (re)binds the chat (/start, /bind).
185
+ */
186
+ export function startPollerOnce(cfg: QuConfig, onConfigPatch?: (patch: { chatId?: string }) => void): void {
187
+ if (g.__piquPollerStarted) return;
188
+ g.__piquPollerStarted = true;
189
+ ensureDirs();
190
+ acquireLockAndPoll(cfg, onConfigPatch).catch((e) => logPoller(`fatal: ${e instanceof Error ? e.stack : e}`));
191
+ }
192
+
193
+ function logPoller(line: string): void {
194
+ try {
195
+ appendFileSync(LOG_FILE, `${new Date().toISOString()} ${line}\n`);
196
+ } catch {}
197
+ }
198
+
199
+ /** Try to take the singleton lock; poll only if this process owns it. */
200
+ async function acquireLockAndPoll(cfg: QuConfig, onConfigPatch?: (patch: { chatId?: string }) => void): Promise<void> {
201
+ if (!acquireLock()) return;
202
+ await pollLoop(cfg, onConfigPatch).finally(releaseLock);
203
+ }
204
+
205
+ function acquireLock(): boolean {
206
+ try {
207
+ const lock = JSON.parse(readFileSync(LOCK_FILE, "utf-8")) as { pid?: number; ts?: number };
208
+ if (!isLockStale(lock)) return false;
209
+ rmSync(LOCK_FILE, { force: true });
210
+ } catch {}
211
+ try {
212
+ writeFileSync(LOCK_FILE, JSON.stringify({ pid: process.pid, ts: Date.now() }), { flag: "wx" });
213
+ } catch {
214
+ return false; // lost the race
215
+ }
216
+ return true;
217
+ }
218
+
219
+ function releaseLock(): void {
220
+ try {
221
+ const lock = JSON.parse(readFileSync(LOCK_FILE, "utf-8"));
222
+ if (lock?.pid === process.pid) rmSync(LOCK_FILE, { force: true });
223
+ } catch {}
224
+ }
225
+
226
+ function heartbeat(): void {
227
+ try {
228
+ writeFileSync(LOCK_FILE, JSON.stringify({ pid: process.pid, ts: Date.now() }));
229
+ } catch {}
230
+ }
231
+
232
+ function sleep(ms: number): Promise<void> {
233
+ return new Promise((r) => setTimeout(r, ms));
234
+ }
235
+
236
+ async function pollLoop(cfg: QuConfig, onConfigPatch?: (patch: { chatId?: string }) => void): Promise<void> {
237
+ let offset = 0;
238
+ logPoller(`poller start pid=${process.pid} api=${cfg.apiBase}`);
239
+ const hb = setInterval(heartbeat, 5_000);
240
+ if (typeof hb.unref === "function") hb.unref();
241
+ try {
242
+ while (true) {
243
+ const res = await tg<{ update_id: number }[]>(cfg, "getUpdates", {
244
+ offset,
245
+ timeout: 45,
246
+ allowed_updates: ["message", "callback_query"],
247
+ });
248
+ if (!res.ok) {
249
+ logPoller(`getUpdates failed: ${res.error_code ?? ""} ${res.description ?? ""}`);
250
+ if (res.error_code === 409 || res.error_code === 401) return; // another poller / bad token
251
+ await sleep(3_000);
252
+ continue;
253
+ }
254
+ for (const update of res.result ?? []) {
255
+ offset = Math.max(offset, update.update_id + 1);
256
+ try {
257
+ await handleUpdate(cfg, update as any, onConfigPatch);
258
+ } catch (e) {
259
+ logPoller(`update error: ${e instanceof Error ? e.message : e}`);
260
+ }
261
+ }
262
+ }
263
+ } finally {
264
+ clearInterval(hb);
265
+ }
266
+ }
267
+
268
+ async function handleUpdate(
269
+ cfg: QuConfig,
270
+ update: { callback_query?: any; message?: any },
271
+ onConfigPatch?: (patch: { chatId?: string }) => void,
272
+ ): Promise<void> {
273
+ if (update.callback_query) return handleCallback(cfg, update.callback_query);
274
+ if (update.message) return handleMessage(cfg, update.message, onConfigPatch);
275
+ }
276
+
277
+ interface CallbackQuery {
278
+ id: string;
279
+ data?: string;
280
+ message?: { message_id: number; chat: { id: number } };
281
+ }
282
+
283
+ async function handleCallback(cfg: QuConfig, cb: CallbackQuery): Promise<void> {
284
+ const answerCb = async (text?: string): Promise<void> => {
285
+ await tg(cfg, "answerCallbackQuery", { callback_query_id: cb.id, text });
286
+ };
287
+ const [kind, qid, idxRaw] = (cb.data ?? "").split("|");
288
+ if (!qid) return answerCb();
289
+ const s: SentQuestion = { chatId: String(cb.message?.chat?.id ?? ""), messageId: cb.message?.message_id ?? 0 };
290
+
291
+ // Cross-chat taps on a still-pending question are refused.
292
+ const p0 = peekPending(qid);
293
+ if (p0 && cfg.chatId && p0.chatId !== cfg.chatId) return answerCb("Вопрос из другого чата");
294
+
295
+ if (kind === CB.tap) {
296
+ const pending = takePending(qid);
297
+ if (!pending) return answerCb("Вопрос уже закрыт");
298
+ if (pending.multiple) {
299
+ toggleIdx(pending, Number(idxRaw));
300
+ writePending(pending);
301
+ await rebuildMultipleKeyboard(cfg, pending);
302
+ return answerCb();
303
+ }
304
+ const idx = Number(idxRaw);
305
+ putAnswer(qid, { type: "choice", labels: [pending.labels[idx] ?? `вариант ${idx + 1}`], via: "tg" });
306
+ await tgEditMessage(cfg, s, `✅ Ответ: ${pending.labels[idx] ?? ""}`, { clearKeyboard: true });
307
+ return answerCb();
308
+ }
309
+
310
+ if (kind === CB.done) {
311
+ const pending = takePending(qid);
312
+ if (!pending) return answerCb("Вопрос уже закрыт");
313
+ const toggled = pending.toggled ?? [];
314
+ if (!toggled.length) {
315
+ writePending(pending); // keep waiting
316
+ return answerCb("Ничего не выбрано");
317
+ }
318
+ putAnswer(qid, { type: "choice", labels: toggled.map((i) => pending.labels[i] ?? `вариант ${i + 1}`), via: "tg" });
319
+ await tgEditMessage(cfg, s, `✅ Ответ: ${toggled.map((i) => pending.labels[i]).join(", ")}`, { clearKeyboard: true });
320
+ return answerCb();
321
+ }
322
+
323
+ if (kind === CB.cancel) {
324
+ const pending = takePending(qid);
325
+ if (!pending) return answerCb("Вопрос уже закрыт");
326
+ putAnswer(qid, { type: "cancel", via: "tg" });
327
+ await tgEditMessage(cfg, s, "🚫 Отменено", { clearKeyboard: true });
328
+ return answerCb();
329
+ }
330
+
331
+ return answerCb();
332
+ }
333
+
334
+ function toggleIdx(p: PendingQuestion, idx: number): number[] {
335
+ const set = new Set(p.toggled ?? []);
336
+ if (set.has(idx)) set.delete(idx);
337
+ else set.add(idx);
338
+ p.toggled = [...set].sort((a, b) => a - b);
339
+ return p.toggled;
340
+ }
341
+
342
+ async function rebuildMultipleKeyboard(cfg: QuConfig, p: PendingQuestion): Promise<void> {
343
+ const toggled = p.toggled ?? [];
344
+ const rows: TgInlineKeyboard = buildKeyboard({ options: p.labels.map((label) => ({ label })), multiple: true, custom: false }, p.qid).map(
345
+ (row) =>
346
+ row.map((b) => {
347
+ const idxRaw = b.callback_data.split("|")[2];
348
+ if (idxRaw === undefined) return b; // Готово / Отмена
349
+ const idx = Number(idxRaw);
350
+ return { ...b, text: `${toggled.includes(idx) ? "🔵" : "⚪"} ${shortLabel(p.labels[idx])}` };
351
+ }),
352
+ );
353
+ await tg(cfg, "editMessageReplyMarkup", { chat_id: p.chatId, message_id: p.messageId, reply_markup: { inline_keyboard: rows } });
354
+ }
355
+
356
+ async function handleMessage(
357
+ cfg: QuConfig,
358
+ msg: { text?: string; chat: { id: number } },
359
+ onConfigPatch?: (patch: { chatId?: string }) => void,
360
+ ): Promise<void> {
361
+ const text = (msg.text ?? "").trim();
362
+ const chatId = String(msg.chat.id);
363
+
364
+ // Chat (re)binding is the ONLY thing handled outside active questions.
365
+ if (text === "/start" || text === "/bind") {
366
+ if (cfg.chatId !== chatId) {
367
+ cfg.chatId = chatId; // live update for this process
368
+ onConfigPatch?.({ chatId });
369
+ }
370
+ await tg(cfg, "sendMessage", { chat_id: chatId, text: "✅ Чат привязан к pi-qu. Вопросы будут приходить сюда." });
371
+ return;
372
+ }
373
+
374
+ // Everything else outside active questions is ignored by design.
375
+ const pendings = listPending().filter((p) => p.chatId === chatId);
376
+ if (!pendings.length) return;
377
+ const p = pendings.at(-1)!;
378
+ dropPending(p.qid);
379
+ putAnswer(p.qid, { type: "custom", text, via: "tg" });
380
+ await tgEditMessage(
381
+ cfg,
382
+ { chatId, messageId: p.messageId, text: p.text },
383
+ `✏️ Ответ текстом: ${truncateTail(text, 200)}`,
384
+ { clearKeyboard: true },
385
+ );
386
+ }
387
+
388
+ /* --------------------------- waiting for TG --------------------------- */
389
+
390
+ /** Resolve as soon as the poller (in any process) writes our answer file. */
391
+ export async function waitTgAnswer(qid: string, deadlineMs: number): Promise<TgAnswer> {
392
+ const path = answersPath(qid);
393
+ while (Date.now() < deadlineMs) {
394
+ try {
395
+ const raw = readFileSync(path, "utf-8");
396
+ rmSync(path, { force: true });
397
+ return JSON.parse(raw) as TgAnswer;
398
+ } catch {
399
+ await sleep(400);
400
+ }
401
+ }
402
+ throw new Error("pi-qu-timeout");
403
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
- "name": "pi-qu",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "pi-qu",
3
+ "version": "0.1.1",
4
+ "description": "Telegram mirror for the pi question tool: questions asked in any session are sent to Telegram with inline buttons; the first answer (local or Telegram) wins.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "BotoVed",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/BotoVed/pi-qu.git"
11
+ },
12
+ "keywords": [
13
+ "pi-package",
14
+ "pi-coding-agent",
15
+ "telegram",
16
+ "question",
17
+ "remote-answers"
18
+ ],
19
+ "engines": {
20
+ "node": ">=22.6"
21
+ },
22
+ "files": [
23
+ "extensions/"
24
+ ],
25
+ "scripts": {
26
+ "test": "node --experimental-strip-types --test extensions/lib.test.ts"
27
+ },
28
+ "peerDependencies": {
29
+ "@earendil-works/pi-coding-agent": ">=0.84.2",
30
+ "typebox": "*"
31
+ },
32
+ "pi": {
33
+ "extensions": [
34
+ "./extensions/pi-qu.ts"
35
+ ]
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^26.6.11",
39
+ "typescript": "^5.9.3"
40
+ }
41
+ }