pi-suite 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +100 -2
- package/README.zh-CN.md +101 -0
- package/package.json +63 -4
- package/skills/pi-suite-jobs/SKILL.md +76 -0
- package/skills/pi-suite-workflow/SKILL.md +114 -0
- package/src/agents/catalog.ts +80 -0
- package/src/agents/child.ts +79 -0
- package/src/agents/commands.ts +17 -0
- package/src/agents/defaults.ts +78 -0
- package/src/agents/history.ts +112 -0
- package/src/agents/index.ts +211 -0
- package/src/agents/manager.ts +438 -0
- package/src/agents/mentions/clone.ts +51 -0
- package/src/agents/mentions/grammar.ts +64 -0
- package/src/agents/mentions/index.ts +76 -0
- package/src/agents/mentions/provider.ts +79 -0
- package/src/agents/model-editor.ts +95 -0
- package/src/agents/models.ts +43 -0
- package/src/agents/output/schema.ts +101 -0
- package/src/agents/output/tool.ts +98 -0
- package/src/agents/parent.ts +13 -0
- package/src/agents/questions.ts +63 -0
- package/src/agents/records.ts +90 -0
- package/src/agents/registry.ts +20 -0
- package/src/agents/render.ts +85 -0
- package/src/agents/resources/context.ts +48 -0
- package/src/agents/resources/loader.ts +86 -0
- package/src/agents/resources/memory.ts +67 -0
- package/src/agents/resources/packages.ts +96 -0
- package/src/agents/resources/paths.ts +8 -0
- package/src/agents/resources/prompts.ts +11 -0
- package/src/agents/resources/scope.ts +147 -0
- package/src/agents/resources/selectors.ts +186 -0
- package/src/agents/retry.ts +20 -0
- package/src/agents/rpc/handlers.ts +62 -0
- package/src/agents/rpc/index.ts +73 -0
- package/src/agents/rpc/options.ts +44 -0
- package/src/agents/run-groups.ts +16 -0
- package/src/agents/runner.ts +131 -0
- package/src/agents/runtime.ts +40 -0
- package/src/agents/schedules/index.ts +136 -0
- package/src/agents/schedules/menu.ts +38 -0
- package/src/agents/schedules/parse.ts +42 -0
- package/src/agents/schedules/store.ts +78 -0
- package/src/agents/schema.ts +5 -0
- package/src/agents/session.ts +29 -0
- package/src/agents/tools.ts +177 -0
- package/src/agents/types.ts +87 -0
- package/src/agents/ui/index.ts +42 -0
- package/src/agents/ui/runs.ts +122 -0
- package/src/agents/ui/types.ts +91 -0
- package/src/agents/viewer-info.ts +36 -0
- package/src/agents/viewer.ts +160 -0
- package/src/agents/workflow/collisions.ts +124 -0
- package/src/agents/workflow/entry.ts +93 -0
- package/src/agents/workflow/host.ts +119 -0
- package/src/agents/workflow/index.ts +100 -0
- package/src/agents/workflow/journal.ts +147 -0
- package/src/agents/workflow/literal.ts +57 -0
- package/src/agents/workflow/manager.ts +169 -0
- package/src/agents/workflow/meta.ts +323 -0
- package/src/agents/workflow/progress/format.ts +184 -0
- package/src/agents/workflow/progress/index.ts +3 -0
- package/src/agents/workflow/progress/model.ts +224 -0
- package/src/agents/workflow/progress/types.ts +144 -0
- package/src/agents/workflow/render.ts +46 -0
- package/src/agents/workflow/runtime/helpers.ts +236 -0
- package/src/agents/workflow/runtime/index.ts +3 -0
- package/src/agents/workflow/runtime/run.ts +646 -0
- package/src/agents/workflow/runtime/types.ts +273 -0
- package/src/agents/workflow/saved.ts +74 -0
- package/src/agents/workflow/store.ts +23 -0
- package/src/agents/workflow/task.ts +277 -0
- package/src/agents/workflow/tool-description.ts +32 -0
- package/src/agents/workflow/tools.ts +66 -0
- package/src/agents/workflow/ui/menu.ts +144 -0
- package/src/agents/workflow/ui/progress.ts +91 -0
- package/src/agents/workflow/worker/bootstrap.ts +316 -0
- package/src/agents/workflow/worker/flow.ts +218 -0
- package/src/agents/workflow/worker/index.ts +7 -0
- package/src/agents/workflow/worker/scope.ts +215 -0
- package/src/ask/.gitkeep +0 -0
- package/src/ask/form.ts +67 -0
- package/src/ask/index.ts +73 -0
- package/src/ask/keys.ts +32 -0
- package/src/ask/layout.ts +78 -0
- package/src/ask/queue.ts +40 -0
- package/src/ask/render.ts +62 -0
- package/src/ask/result.ts +56 -0
- package/src/ask/schema.ts +67 -0
- package/src/ask/tool-render.ts +49 -0
- package/src/ask/view.ts +406 -0
- package/src/goal/.gitkeep +0 -0
- package/src/goal/activity.ts +50 -0
- package/src/goal/commands.ts +75 -0
- package/src/goal/context.ts +36 -0
- package/src/goal/index.ts +38 -0
- package/src/goal/manager.ts +386 -0
- package/src/goal/presentation.ts +15 -0
- package/src/goal/render.ts +36 -0
- package/src/goal/snapshot.ts +78 -0
- package/src/goal/state.ts +39 -0
- package/src/goal/store.ts +59 -0
- package/src/goal/tools.ts +59 -0
- package/src/goal/wait.ts +39 -0
- package/src/index.ts +20 -0
- package/src/jobs/backends/linux-tree.ts +87 -0
- package/src/jobs/backends/pipe.ts +74 -0
- package/src/jobs/backends/process.ts +79 -0
- package/src/jobs/backends/pty-job.ts +45 -0
- package/src/jobs/backends/pty.ts +502 -0
- package/src/jobs/backends/windows-tree.ts +289 -0
- package/src/jobs/commands.ts +7 -0
- package/src/jobs/control.ts +13 -0
- package/src/jobs/index.ts +331 -0
- package/src/jobs/launch/config.ts +26 -0
- package/src/jobs/launch/name.ts +16 -0
- package/src/jobs/launch/presets.ts +61 -0
- package/src/jobs/log-viewer.ts +147 -0
- package/src/jobs/manager.ts +507 -0
- package/src/jobs/monitors/compile.ts +101 -0
- package/src/jobs/monitors/hands-free.ts +108 -0
- package/src/jobs/monitors/runtime.ts +165 -0
- package/src/jobs/output.ts +54 -0
- package/src/jobs/query.ts +62 -0
- package/src/jobs/render.ts +103 -0
- package/src/jobs/runtime.ts +89 -0
- package/src/jobs/state.ts +25 -0
- package/src/jobs/store.ts +168 -0
- package/src/jobs/terminal/keys.ts +292 -0
- package/src/jobs/terminal/protocol.ts +37 -0
- package/src/jobs/terminal/read.ts +131 -0
- package/src/jobs/terminal/render.ts +70 -0
- package/src/jobs/terminal/screen.ts +92 -0
- package/src/jobs/terminal/session.ts +100 -0
- package/src/jobs/terminal/shell.ts +22 -0
- package/src/jobs/terminal/snapshot.ts +8 -0
- package/src/jobs/terminal/visible-text.ts +53 -0
- package/src/jobs/tools.ts +203 -0
- package/src/jobs/types.ts +60 -0
- package/src/jobs/viewer/component.ts +209 -0
- package/src/jobs/viewer/metadata.ts +9 -0
- package/src/jobs/viewer.ts +149 -0
- package/src/jobs/workspace.ts +31 -0
- package/src/runtime/.gitkeep +0 -0
- package/src/runtime/binding.ts +26 -0
- package/src/runtime/cli-prompt.ts +24 -0
- package/src/runtime/clipboard.ts +16 -0
- package/src/runtime/config-edit.ts +31 -0
- package/src/runtime/config-fields.ts +65 -0
- package/src/runtime/config.ts +111 -0
- package/src/runtime/errors.ts +11 -0
- package/src/runtime/json-store.ts +156 -0
- package/src/runtime/notification-render.ts +35 -0
- package/src/runtime/notifications.ts +98 -0
- package/src/runtime/owner.ts +54 -0
- package/src/runtime/read.ts +200 -0
- package/src/runtime/renderers.ts +50 -0
- package/src/runtime/responses/index.ts +108 -0
- package/src/runtime/responses/payload.ts +78 -0
- package/src/runtime/settings/index.ts +24 -0
- package/src/runtime/settings/view.ts +84 -0
- package/src/runtime/suite.ts +192 -0
- package/src/runtime/text.ts +6 -0
- package/src/runtime/tools.ts +131 -0
- package/src/runtime/wait-render.ts +33 -0
- package/src/runtime/wait.ts +134 -0
- package/src/tasks/commands.ts +41 -0
- package/src/tasks/index.ts +305 -0
- package/src/tasks/model.ts +152 -0
- package/src/tasks/presentation.ts +40 -0
- package/src/tasks/query.ts +38 -0
- package/src/tasks/render.ts +54 -0
- package/src/tasks/schema.ts +25 -0
- package/src/tasks/store.ts +164 -0
- package/src/tasks/tools.ts +69 -0
- package/src/tasks/types.ts +61 -0
- package/src/tasks/viewer.ts +68 -0
- package/src/ui/.gitkeep +0 -0
- package/src/ui/actions.ts +50 -0
- package/src/ui/browser-chrome.ts +175 -0
- package/src/ui/browser.ts +292 -0
- package/src/ui/details.ts +111 -0
- package/src/ui/dock/line.ts +14 -0
- package/src/ui/dock/rows.ts +78 -0
- package/src/ui/dock.ts +224 -0
- package/src/ui/format.ts +25 -0
- package/src/ui/frame.ts +8 -0
- package/src/ui/inline-input.ts +98 -0
- package/src/ui/reading.ts +105 -0
- package/src/ui/rendering/builtin-command.ts +34 -0
- package/src/ui/rendering/command.ts +60 -0
- package/src/ui/rendering/read-page.ts +15 -0
- package/src/ui/rendering/shell/bash.ts +281 -0
- package/src/ui/rendering/shell/index.ts +24 -0
- package/src/ui/rendering/shell/powershell.ts +155 -0
- package/src/ui/rendering/shell/spans.ts +28 -0
- package/src/ui/scroll.ts +111 -0
- package/src/ui/select.ts +67 -0
- package/src/ui/status.ts +67 -0
- package/src/ui/structured-details.ts +41 -0
- package/src/ui/terminal.ts +137 -0
- package/src/ui/ticker.ts +18 -0
- package/src/ui/tool-render.ts +152 -0
- package/src/ui/transcript.ts +140 -0
- package/src/ui/viewer/agent-information.ts +34 -0
- package/src/ui/viewer/editor.ts +18 -0
- package/src/ui/viewer/navigation.ts +25 -0
- package/themes/oh-my-pi.json +95 -0
- package/third-party/UPSTREAM.md +88 -0
- package/third-party/licenses/.gitkeep +0 -0
- package/third-party/licenses/oh-my-pi.txt +23 -0
- package/third-party/licenses/pi-ask-user.txt +21 -0
- package/third-party/licenses/pi-background-jobs.txt +21 -0
- package/third-party/licenses/pi-goal.txt +21 -0
- package/third-party/licenses/pi-interactive-shell.txt +25 -0
- package/third-party/licenses/pi-subagents.txt +21 -0
- package/third-party/licenses/pi-tasks.txt +21 -0
- package/third-party/sources.json +111 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { Theme } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
|
|
3
|
+
import { sanitizeText } from '../runtime/text.ts';
|
|
4
|
+
import type { AskForm, Draft } from './form.ts';
|
|
5
|
+
import type { Option, Question } from './schema.ts';
|
|
6
|
+
import { answerText, optionRow } from './render.ts';
|
|
7
|
+
|
|
8
|
+
const wrap = (text: string, width: number) => sanitizeText(text).split('\n').flatMap(line => wrapTextWithAnsi(line, Math.max(1, width)));
|
|
9
|
+
export function fold(lines: string[], width: number, cap: number, hint = ''): string[] {
|
|
10
|
+
if (lines.length <= cap) return lines;
|
|
11
|
+
if (cap < 1) return [];
|
|
12
|
+
return [...lines.slice(0, cap - 1), truncateToWidth(lines[cap - 1], Math.max(0, width - visibleWidth(`… ${hint}`)), '') + `… ${hint}`];
|
|
13
|
+
}
|
|
14
|
+
export function questionLines(question: Question, theme: Theme, width: number, cap: number, expanded: boolean): string[] {
|
|
15
|
+
const lines = wrap(question.question, width);
|
|
16
|
+
return fold(lines, width, cap, expanded ? 'd full text' : 'e expand');
|
|
17
|
+
}
|
|
18
|
+
export function choiceLines(theme: Theme, question: Question, draft: Draft, option: Option | undefined, focused: boolean,
|
|
19
|
+
width: number, expanded: boolean, preview: boolean): string[] {
|
|
20
|
+
const title = optionRow(theme, question, draft, option, focused);
|
|
21
|
+
const lines = expanded ? wrapTextWithAnsi(title, Math.max(1, width)) : [truncateToWidth(title, width, '…')];
|
|
22
|
+
if (option?.description && !preview) {
|
|
23
|
+
const desc = wrap(option.description, width - 6);
|
|
24
|
+
lines.push(...(expanded ? desc : fold(desc, width - 6, 2)).map(line => ' ' + theme.fg('muted', line)));
|
|
25
|
+
}
|
|
26
|
+
return lines;
|
|
27
|
+
}
|
|
28
|
+
export function reviewLines(form: AskForm, theme: Theme, width: number, expanded: boolean): string[][] {
|
|
29
|
+
return form.questions.map((question, index) => {
|
|
30
|
+
const text = `${index + 1}. ${question.question}: ${answerText(form.response(index)) ?? theme.fg('warning', 'Unanswered')}`;
|
|
31
|
+
return expanded ? wrap(text, width) : [truncateToWidth(text.replace(/\s*\n\s*/g, ' '), width, '…')];
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
export interface Frame { width: number; inset: number; bordered: boolean; separators: boolean }
|
|
35
|
+
export function frame(width: number, limit: number): Frame {
|
|
36
|
+
const bordered = limit >= 5, inset = bordered && width >= 50 ? 3 : 0;
|
|
37
|
+
return { width: Math.max(1, width - inset * 2), inset, bordered, separators: limit >= 12 };
|
|
38
|
+
}
|
|
39
|
+
export function topBorder(theme: Theme, width: number, requester: string, heading: string | undefined, page: string, time: string): string {
|
|
40
|
+
const right = ` ${page} · ${time} `;
|
|
41
|
+
const room = Math.max(0, width - visibleWidth(right) - 4);
|
|
42
|
+
let request = sanitizeText(requester).replace(/\s+/g, ' ');
|
|
43
|
+
const headingRoom = Math.max(0, room - visibleWidth(`Ask · ${request} · `));
|
|
44
|
+
const title = heading ? truncateToWidth(sanitizeText(heading).replace(/\s+/g, ' '), headingRoom, '…') : '';
|
|
45
|
+
request = truncateToWidth(request, Math.max(0, room - visibleWidth('Ask · ') - (title ? visibleWidth(title) + 3 : 0)), '…');
|
|
46
|
+
const left = truncateToWidth(`Ask${request ? ` · ${request}` : ''}${title ? ` · ${title}` : ''}`, room);
|
|
47
|
+
const fill = '─'.repeat(Math.max(0, width - visibleWidth(left) - visibleWidth(right) - 4));
|
|
48
|
+
return theme.fg('border', '╭─ ') + theme.bold(theme.fg('accent', left)) + theme.fg('border', fill + right + '╮');
|
|
49
|
+
}
|
|
50
|
+
export function frameLines(theme: Theme, geometry: Frame, width: number, top: string, content: string[], markers: Map<number, string>): string[] {
|
|
51
|
+
if (!geometry.bordered) return content;
|
|
52
|
+
const edge = (left: string, right: string) => theme.fg('border', left + '─'.repeat(Math.max(0, width - 2)) + right);
|
|
53
|
+
return [top, ...content.map((line, index) => {
|
|
54
|
+
if (line === '\0separator') return edge('├', '┤');
|
|
55
|
+
if (!geometry.inset) return truncateToWidth(line, width);
|
|
56
|
+
const text = truncateToWidth(line, geometry.width);
|
|
57
|
+
return theme.fg('border', '│') + ' ' + text + ' '.repeat(Math.max(0, geometry.width - visibleWidth(text))) + ' ' + theme.fg('border', markers.get(index) ?? '│');
|
|
58
|
+
}), edge('╰', '╯')];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface ListPosition { offset: number; cursor: number; lengths?: number[] }
|
|
62
|
+
/** Scroll physical rows, but keep option identity for clicks and keyboard movement. */
|
|
63
|
+
export function listWindow(blocks: string[][], cursor: number, height: number, position: ListPosition): { lines: string[]; indices: number[]; total: number } {
|
|
64
|
+
const lines = blocks.flat(), indices = blocks.flatMap((block, index) => block.map(() => index));
|
|
65
|
+
const start = indices.indexOf(cursor);
|
|
66
|
+
// A resize changes physical line counts. Retain the same item and its local
|
|
67
|
+
// reading row rather than applying an old line number to unrelated content.
|
|
68
|
+
if (position.lengths && position.lengths.some((length, index) => length !== blocks[index]?.length)) {
|
|
69
|
+
let item = 0, local = position.offset;
|
|
70
|
+
while (item < position.lengths.length - 1 && local >= position.lengths[item]) local -= position.lengths[item++];
|
|
71
|
+
position.offset = blocks.slice(0, item).reduce((sum, block) => sum + block.length, 0) + Math.min(local, Math.max(0, (blocks[item]?.length ?? 1) - 1));
|
|
72
|
+
}
|
|
73
|
+
position.lengths = blocks.map(block => block.length);
|
|
74
|
+
if (position.cursor !== cursor) position.offset = Math.max(0, start - Math.max(0, height - (blocks[cursor]?.length ?? 0)));
|
|
75
|
+
position.cursor = cursor;
|
|
76
|
+
position.offset = Math.max(0, Math.min(position.offset, lines.length - height));
|
|
77
|
+
return { lines: lines.slice(position.offset, position.offset + height), indices: indices.slice(position.offset, position.offset + height), total: lines.length };
|
|
78
|
+
}
|
package/src/ask/queue.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { AskResult } from "./schema.ts";
|
|
2
|
+
|
|
3
|
+
interface Entry {
|
|
4
|
+
show: () => Promise<AskResult>; signal?: AbortSignal;
|
|
5
|
+
resolve: (result: AskResult) => void; reject: (error: unknown) => void;
|
|
6
|
+
}
|
|
7
|
+
export const cancelled = (): AskResult => ({ status: "cancelled", responses: [] });
|
|
8
|
+
|
|
9
|
+
/** Only displayed prompts own a deadline. An aborted queued prompt never opens a view. */
|
|
10
|
+
export class AskQueue {
|
|
11
|
+
private entries: Entry[] = [];
|
|
12
|
+
private running = false;
|
|
13
|
+
enqueue(show: Entry["show"], signal?: AbortSignal): Promise<AskResult> {
|
|
14
|
+
if (signal?.aborted) return Promise.resolve(cancelled());
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
const entry: Entry = { show, signal, resolve, reject };
|
|
17
|
+
const abort = () => {
|
|
18
|
+
const index = this.entries.indexOf(entry);
|
|
19
|
+
if (index >= 0) { this.entries.splice(index, 1); resolve(cancelled()); }
|
|
20
|
+
};
|
|
21
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
22
|
+
const removeListener = () => signal?.removeEventListener("abort", abort);
|
|
23
|
+
entry.resolve = result => { removeListener(); resolve(result); };
|
|
24
|
+
entry.reject = error => { removeListener(); reject(error); };
|
|
25
|
+
this.entries.push(entry);
|
|
26
|
+
void this.drain();
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
private async drain(): Promise<void> {
|
|
30
|
+
if (this.running) return;
|
|
31
|
+
this.running = true;
|
|
32
|
+
try {
|
|
33
|
+
while (this.entries.length) {
|
|
34
|
+
const entry = this.entries.shift()!;
|
|
35
|
+
try { entry.resolve(entry.signal?.aborted ? cancelled() : await entry.show()); }
|
|
36
|
+
catch (error) { entry.reject(error); }
|
|
37
|
+
}
|
|
38
|
+
} finally { this.running = false; }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
3
|
+
import type { AskForm, Draft } from "./form.ts";
|
|
4
|
+
import type { Option, Question, Response } from "./schema.ts";
|
|
5
|
+
import { sanitizeText } from "../runtime/text.ts";
|
|
6
|
+
|
|
7
|
+
const oneLine = (text: string) => sanitizeText(text).replace(/\s*\n\s*/g, " ");
|
|
8
|
+
export const answerText = (response?: Response) => response ? [
|
|
9
|
+
...response.kind === 'selection' ? response.selections : [], ...response.text ? [`✎ ${response.text}`] : [],
|
|
10
|
+
].join(', ') : undefined;
|
|
11
|
+
|
|
12
|
+
/** Shared markers keep the full list and the compact one-line layout consistent. */
|
|
13
|
+
export function optionRow(theme: Theme, question: Question, draft: Pick<Draft, 'selected' | 'text' | 'customSelected'>, option: Option | undefined, focused: boolean): string {
|
|
14
|
+
const selected = option ? draft.selected.has(option.id) : draft.customSelected && Boolean(draft.text.trim());
|
|
15
|
+
const choice = question.allowMultiple ? selected ? "☑" : "☐" : selected ? "◉" : "○";
|
|
16
|
+
const marker = option ? choice : `${question.options.length ? choice + ' ' : ''}✎`;
|
|
17
|
+
const title = option?.title ?? (draft.text.trim() ? draft.text : 'Type your own answer');
|
|
18
|
+
return (focused ? theme.fg("accent", "❯ ") : " ") + theme.fg(selected ? "success" : "dim", marker) + " " +
|
|
19
|
+
(focused ? theme.fg("accent", oneLine(title)) : oneLine(title)) + (option?.recommended ? theme.fg("accent", " (Recommended)") : "");
|
|
20
|
+
}
|
|
21
|
+
export interface TabRegion { start: number; end: number; page: number }
|
|
22
|
+
export function questionTabs(form: AskForm, theme: Theme, width: number): { line: string; regions: TabRegion[] } {
|
|
23
|
+
const page = form.reviewing ? form.questions.length : form.index;
|
|
24
|
+
const tabs = [...form.questions.map((question, index) => ({ page: index,
|
|
25
|
+
title: truncateToWidth(oneLine(question.title ?? question.question).replace(/\s+/g, ' ').trim() || 'Question', 22, '…'),
|
|
26
|
+
answered: form.answered(index),
|
|
27
|
+
})), { page: form.questions.length, title: 'Review', answered: false }];
|
|
28
|
+
// Budget every label before styling, rather than clipping the entire bar and leaving
|
|
29
|
+
// invisible tabs with clickable regions. Very narrow screens retain the active page.
|
|
30
|
+
const minimum = tabs.reduce((sum, tab) => sum + (tab.page === form.questions.length ? 6 : Math.min(3, visibleWidth(tab.title))) + Number(tab.answered), tabs.length - 1);
|
|
31
|
+
const shown = minimum <= width ? tabs : [tabs[page],
|
|
32
|
+
...page !== form.questions.length && width >= Math.min(3, visibleWidth(tabs[page].title)) + Number(tabs[page].answered) + 7 ? [tabs.at(-1)!] : []];
|
|
33
|
+
const sizes = shown.map(tab => visibleWidth(tab.title) + Number(tab.answered));
|
|
34
|
+
let excess = sizes.reduce((sum, size) => sum + size, shown.length - 1) - width;
|
|
35
|
+
while (excess > 0) {
|
|
36
|
+
let widest = -1;
|
|
37
|
+
for (let index = 0; index < shown.length; index++) {
|
|
38
|
+
if (shown.length > 1 && shown[index].page === form.questions.length) continue;
|
|
39
|
+
if (sizes[index] > 1 && (widest < 0 || sizes[index] > sizes[widest])) widest = index;
|
|
40
|
+
}
|
|
41
|
+
if (widest < 0) break;
|
|
42
|
+
sizes[widest]--; excess--;
|
|
43
|
+
}
|
|
44
|
+
let line = '';
|
|
45
|
+
const regions: TabRegion[] = [];
|
|
46
|
+
shown.forEach((tab, index) => {
|
|
47
|
+
const badge = tab.answered && sizes[index] > 1 ? theme.fg('success', '✓') : '';
|
|
48
|
+
const title = truncateToWidth(tab.title, Math.max(0, sizes[index] - visibleWidth(badge)), '…');
|
|
49
|
+
const label = (tab.page === page ? theme.fg('accent', title) : title) + badge;
|
|
50
|
+
if (index) line += ' ';
|
|
51
|
+
const start = visibleWidth(line);
|
|
52
|
+
line += label;
|
|
53
|
+
const end = visibleWidth(line);
|
|
54
|
+
if (end > start && end <= width) regions.push({ start, end, page: tab.page });
|
|
55
|
+
});
|
|
56
|
+
return { line: truncateToWidth(line, width), regions };
|
|
57
|
+
}
|
|
58
|
+
export function idleTime(deadline?: number): string {
|
|
59
|
+
if (deadline === undefined) return "no timeout";
|
|
60
|
+
const seconds = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
|
|
61
|
+
return `idle ${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
|
|
62
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { AskParams, AskResult, Question, Response } from './schema.ts';
|
|
2
|
+
import { textResult } from '../runtime/tools.ts';
|
|
3
|
+
|
|
4
|
+
export function askDetails(params: AskParams, questions: Question[], result: AskResult) {
|
|
5
|
+
// A skipped form retains partial user answers; cancellation carries no answers.
|
|
6
|
+
const common = { status: result.status, cancelled: result.status === "skipped" || result.status === "cancelled" };
|
|
7
|
+
return params.questions ? {
|
|
8
|
+
...common, kind: "batch", heading: params.question, questions,
|
|
9
|
+
answers: result.status === 'cancelled' ? [] : questions.map((_, index) => {
|
|
10
|
+
const response = result.responses[index];
|
|
11
|
+
return response ? { status: "answered", response } : { status: "unanswered" };
|
|
12
|
+
}),
|
|
13
|
+
} : { ...common, question: params.question, options: questions[0].options, response: result.responses[0] ?? null };
|
|
14
|
+
}
|
|
15
|
+
export type AskDetails = ReturnType<typeof askDetails>;
|
|
16
|
+
|
|
17
|
+
const QUESTION_WIDTH = 24;
|
|
18
|
+
const clip = (text: string) => {
|
|
19
|
+
const chars = [...text.replace(/\s+/g, ' ').trim()];
|
|
20
|
+
return chars.length > QUESTION_WIDTH ? chars.slice(0, QUESTION_WIDTH - 1).join('') + '…' : chars.join('');
|
|
21
|
+
};
|
|
22
|
+
function selection(question: Question, response: Extract<Response, { kind: 'selection' }>): string {
|
|
23
|
+
const counts = new Map<string, number>();
|
|
24
|
+
const positions = new Map(question.options.map((option, index) => [option.id, index + 1]));
|
|
25
|
+
for (const option of question.options) counts.set(option.title, (counts.get(option.title) ?? 0) + 1);
|
|
26
|
+
// A title alone is enough unless another offered option has the same title.
|
|
27
|
+
// Number by the original list, never the selected subset; IDs remain in details.
|
|
28
|
+
const titles = response.selections.map((title, index) => counts.get(title)! > 1
|
|
29
|
+
? `#${positions.get(response.optionIds[index])} ${title}` : title);
|
|
30
|
+
return titles.join(', ') + (response.text ? ` + custom: ${response.text}` : '');
|
|
31
|
+
}
|
|
32
|
+
const answer = (question: Question, response?: Response) => !response ? 'unanswered'
|
|
33
|
+
: (response.kind === 'selection' ? selection(question, response) : `custom: ${response.text}`) +
|
|
34
|
+
(response.autoSelected ? ' (auto-selected)' : '');
|
|
35
|
+
const comment = (response: Response | undefined, indent = '') => response?.comment ? [`${indent}comment: ${response.comment}`] : [];
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Model-facing ask result. The model already holds its own questions and options, so the
|
|
39
|
+
* text carries only status and answers; details keeps the full record for rendering and
|
|
40
|
+
* history. Answers attached to timed_out/skipped are labelled "not consent" because the
|
|
41
|
+
* model must not treat them as authorization (see the ask_user prompt guidelines).
|
|
42
|
+
*/
|
|
43
|
+
export function askToolResult(params: AskParams, questions: Question[], result: AskResult, source?: 'parent') {
|
|
44
|
+
const record = askDetails(params, questions, result);
|
|
45
|
+
const details = source ? { ...record, source } : record;
|
|
46
|
+
const responses = result.responses;
|
|
47
|
+
const head = result.status + (result.status === 'timed_out' || result.status === 'skipped' ? ' (not consent)' : '');
|
|
48
|
+
const lines = result.status === 'cancelled' ? ['cancelled'] : [
|
|
49
|
+
head,
|
|
50
|
+
// Both shapes keep question positions. Mark automation per answer so mixed
|
|
51
|
+
// drafts and parent timeouts cannot imply that every slot was auto-selected.
|
|
52
|
+
...questions.flatMap((question, index) => [`${index + 1}. ${clip(question.question)} → ${answer(question, responses[index])}`,
|
|
53
|
+
...comment(responses[index], ' ')]),
|
|
54
|
+
];
|
|
55
|
+
return textResult([...lines, source && `source: ${source}`], details);
|
|
56
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { Type, type Static } from "typebox";
|
|
2
|
+
|
|
3
|
+
const option = Type.Union([Type.String({ minLength: 1 }), Type.Object({
|
|
4
|
+
id: Type.Optional(Type.String({ minLength: 1 })), title: Type.String({ minLength: 1 }),
|
|
5
|
+
description: Type.Optional(Type.String()), recommended: Type.Optional(Type.Boolean()),
|
|
6
|
+
})]);
|
|
7
|
+
const fields = {
|
|
8
|
+
options: Type.Optional(Type.Array(option)),
|
|
9
|
+
allowMultiple: Type.Optional(Type.Boolean()),
|
|
10
|
+
defaultAnswer: Type.Optional(Type.String()), defaultOptionId: Type.Optional(Type.String()),
|
|
11
|
+
defaultOptionIds: Type.Optional(Type.Array(Type.String(), { uniqueItems: true })),
|
|
12
|
+
};
|
|
13
|
+
export const askSchema = Type.Object({
|
|
14
|
+
question: Type.Optional(Type.String({ minLength: 1 })), ...fields,
|
|
15
|
+
questions: Type.Optional(Type.Array(Type.Object({
|
|
16
|
+
question: Type.String({ minLength: 1 }),
|
|
17
|
+
title: Type.Optional(Type.String({ minLength: 1, maxLength: 60,
|
|
18
|
+
description: "Short tab title, e.g. 'Scope'. Omit to derive one from question; the full question is still shown." })),
|
|
19
|
+
...fields,
|
|
20
|
+
}, { additionalProperties: false }), { minItems: 2, maxItems: 4 })),
|
|
21
|
+
allowComment: Type.Optional(Type.Boolean()),
|
|
22
|
+
timeoutMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 2147483647,
|
|
23
|
+
description: "Milliseconds of user inactivity before expiry; restarted by user input. Omit for the configured default (600000); 0 disables it. On expiry each question submits its draft, else recommended options, else its first option; a question without options or draft stays unanswered." })),
|
|
24
|
+
}, { additionalProperties: false });
|
|
25
|
+
export type AskParams = Static<typeof askSchema>;
|
|
26
|
+
export type QuestionInput = NonNullable<AskParams["questions"]>[number];
|
|
27
|
+
|
|
28
|
+
export interface Option { id: string; title: string; description?: string; recommended?: boolean }
|
|
29
|
+
export interface Question extends Omit<QuestionInput, "options" | "allowMultiple"> {
|
|
30
|
+
options: Option[]; allowMultiple: boolean;
|
|
31
|
+
}
|
|
32
|
+
export type Response = (
|
|
33
|
+
// Custom text has no preset ID; mixed multi-select answers keep it in its own field.
|
|
34
|
+
| { kind: "selection"; selections: string[]; optionIds: string[]; text?: string; comment?: string }
|
|
35
|
+
| { kind: "freeform"; text: string; comment?: string }
|
|
36
|
+
) & { autoSelected?: true };
|
|
37
|
+
export type AskResult =
|
|
38
|
+
| { status: "answered"; responses: Response[] }
|
|
39
|
+
| { status: "timed_out"; responses: (Response | undefined)[] }
|
|
40
|
+
| { status: "skipped"; responses: (Response | undefined)[] }
|
|
41
|
+
| { status: "cancelled"; responses: [] };
|
|
42
|
+
|
|
43
|
+
export function normalize(params: AskParams): Question[] {
|
|
44
|
+
if (!params.questions && !params.question?.trim()) throw new Error("No question supplied. Provide nonblank question text or 2–4 questions.");
|
|
45
|
+
if (params.questions && [params.options, params.allowMultiple,
|
|
46
|
+
params.defaultAnswer, params.defaultOptionId, params.defaultOptionIds].some(value => value !== undefined)) {
|
|
47
|
+
throw new Error("With questions, put options, allowMultiple and default* settings inside each questions entry, not at the top level.");
|
|
48
|
+
}
|
|
49
|
+
return (params.questions ?? [{ ...params, question: params.question! }]).map(input => {
|
|
50
|
+
const options = (input.options ?? []).map((value, index) => typeof value === "string"
|
|
51
|
+
? { id: `option-${index + 1}`, title: value } : { ...value, id: value.id ?? `option-${index + 1}` });
|
|
52
|
+
const ids = new Set(options.map(o => o.id));
|
|
53
|
+
if (ids.size !== options.length) throw new Error("Duplicate option IDs. Give each option in the question a unique ID.");
|
|
54
|
+
const allowMultiple = input.allowMultiple ?? false;
|
|
55
|
+
const hasText = input.defaultAnswer !== undefined;
|
|
56
|
+
const hasSingle = input.defaultOptionId !== undefined;
|
|
57
|
+
const hasMulti = input.defaultOptionIds !== undefined;
|
|
58
|
+
if (Number(hasText) + Number(hasSingle) + Number(hasMulti) > 1) throw new Error("Use only one of defaultAnswer, defaultOptionId and defaultOptionIds per question");
|
|
59
|
+
if ((hasSingle && allowMultiple) || (hasMulti && !allowMultiple)) throw new Error("defaultOptionId requires single choice; defaultOptionIds requires allowMultiple: true");
|
|
60
|
+
const defaults = input.defaultOptionIds ?? (hasSingle ? [input.defaultOptionId!] : []);
|
|
61
|
+
if (defaults.some(id => !ids.has(id))) throw new Error("Default references an unknown option ID. Use an ID from this question's options.");
|
|
62
|
+
// Project current question fields instead of spreading input: historical/foreign
|
|
63
|
+
// fields must not leak into live forms or newly persisted details.
|
|
64
|
+
const { question, title, defaultAnswer, defaultOptionId, defaultOptionIds } = input as QuestionInput;
|
|
65
|
+
return { question, title, defaultAnswer, defaultOptionId, defaultOptionIds, options, allowMultiple };
|
|
66
|
+
});
|
|
67
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Text, truncateToWidth } from '@earendil-works/pi-tui';
|
|
2
|
+
import { toolRenderers, stateLine } from '../ui/tool-render.ts';
|
|
3
|
+
import { answerText, optionRow } from './render.ts';
|
|
4
|
+
import { normalize, type AskParams, type Question } from './schema.ts';
|
|
5
|
+
import type { AskDetails } from './result.ts';
|
|
6
|
+
|
|
7
|
+
// Compatibility is display-only: persisted context can be read here without
|
|
8
|
+
// widening the current schema/Question or normalizing it back into a live request.
|
|
9
|
+
type HistoricalQuestion = Question & { context?: string };
|
|
10
|
+
type Details = AskDetails & { context?: string; source?: 'parent' };
|
|
11
|
+
export function askRenderers(title = 'Ask') {
|
|
12
|
+
return toolRenderers<AskParams, Details>({
|
|
13
|
+
call: args => ({ icon: '?', tone: 'warning', title,
|
|
14
|
+
summary: args.questions ? `${args.questions.length} questions` : truncateToWidth(args.question ?? '', 60) }),
|
|
15
|
+
collapsed: data => {
|
|
16
|
+
const batch = 'answers' in data, answers = batch ? data.answers : [{ response: data.response }];
|
|
17
|
+
const unanswered = answers.filter(answer => !answer.response).length;
|
|
18
|
+
return { ...stateLine(data.status), title,
|
|
19
|
+
summary: data.status === 'cancelled' ? data.status : data.status === 'skipped'
|
|
20
|
+
? `skipped · ${batch ? `${answers.length - unanswered} answered` : answerText(data.response ?? undefined) ?? 'unanswered'}` : batch
|
|
21
|
+
? `${answers.length - unanswered} answered` : `${truncateToWidth(data.question ?? '', 40)} → ${answerText(data.response ?? undefined) ?? 'unanswered'}`,
|
|
22
|
+
meta: [...answers.some(answer => answer.response?.autoSelected) ? ['auto-selected'] : [],
|
|
23
|
+
...data.status === 'timed_out' || data.status === 'skipped' ? ['not consent'] : [],
|
|
24
|
+
...unanswered ? [`${unanswered} unanswered`] : [], ...data.source ? [`source: ${data.source}`] : []] };
|
|
25
|
+
},
|
|
26
|
+
expanded: (data, args, _text, theme) => {
|
|
27
|
+
const questions: HistoricalQuestion[] = 'questions' in data ? data.questions : normalize({ ...args, question: data.question,
|
|
28
|
+
options: data.options });
|
|
29
|
+
const responses = 'answers' in data ? data.answers.map(answer => answer.response) : [data.response];
|
|
30
|
+
return [{ label: 'state', value: data.status, tone: stateLine(data.status).tone },
|
|
31
|
+
...data.status === 'timed_out' || data.status === 'skipped' ? [{ label: 'consent', value: 'not consent', tone: 'warning' as const }] : [],
|
|
32
|
+
...data.source ? [{ label: 'source', value: data.source }] : [], ...'heading' in data && data.heading ? [{ icon: '', title: data.heading }] : [],
|
|
33
|
+
...questions.flatMap((question, index) => {
|
|
34
|
+
const response = responses[index];
|
|
35
|
+
// Use the live form's markers; the transcript has no editing focus.
|
|
36
|
+
const selected = new Set(response?.kind === 'selection' ? response.optionIds : []);
|
|
37
|
+
const draft = { selected, text: response?.text ?? '', customSelected: Boolean(response?.text) };
|
|
38
|
+
const context = 'questions' in data ? question.context : data.context;
|
|
39
|
+
return [{ icon: '?', tone: 'accent' as const, title: question.question }, ...context ? [{ label: 'context', value: context }] : [],
|
|
40
|
+
...question.options.flatMap(option => [new Text(optionRow(theme, question, draft, option, false), 0, 0),
|
|
41
|
+
...option.description ? [{ label: 'description', value: option.description }] : []]),
|
|
42
|
+
...response?.text ? [new Text(optionRow(theme, question, draft, undefined, false), 0, 0)] : [],
|
|
43
|
+
...response?.comment ? [{ label: 'comment', value: response.comment }] : [],
|
|
44
|
+
...response?.autoSelected ? [{ label: 'source', value: 'auto-selected · not consent', tone: 'warning' as const }] : [],
|
|
45
|
+
...response ? [] : [{ label: 'answer', value: 'unanswered', tone: 'warning' as const }]];
|
|
46
|
+
})];
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
}
|