@herbertgao/pi-extensions 2026.10.10 → 2026.10.11

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.
Files changed (108) hide show
  1. package/README.md +10 -8
  2. package/THIRD_PARTY_NOTICES.md +2 -2
  3. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +3 -0
  4. package/node_modules/@herbertgao/pi-cc-extensions/README.md +3 -0
  5. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +1 -1
  6. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +3 -3
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +126 -42
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/interaction.ts +24 -6
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/scroll.ts +69 -16
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/sticky-prompt.ts +1 -1
  11. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  12. package/node_modules/@herbertgao/sol-pi/README.md +7 -1
  13. package/node_modules/@herbertgao/sol-pi/docs/compatibility.md +28 -4
  14. package/node_modules/@herbertgao/sol-pi/docs/configuration.md +17 -4
  15. package/node_modules/@herbertgao/sol-pi/package.json +1 -1
  16. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/action-fusion/index.ts +35 -25
  17. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/action-fusion/then-run.ts +95 -26
  18. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/evidence-preserving-reducer/candidate.ts +39 -2
  19. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/evidence-preserving-reducer/index.ts +24 -0
  20. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/observation-pack/index.ts +12 -7
  21. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/online-context-compact/extension.ts +138 -130
  22. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/online-context-compact/projection.ts +88 -14
  23. package/node_modules/@herbertgao/sol-pi/src/sol-pi/extensions/online-context-compact/tools.ts +9 -0
  24. package/node_modules/@herbertgao/sol-pi/src/sol-pi/index.ts +14 -5
  25. package/node_modules/@herbertgao/sol-pi/src/sol-pi/shell-options.ts +22 -0
  26. package/node_modules/@herbertgao/sol-pi/src/sol-pi/tui.ts +11 -0
  27. package/node_modules/@juicesharp/rpiv-ask-user-question/answer-channel.ts +109 -0
  28. package/node_modules/@juicesharp/rpiv-ask-user-question/ask-user-question.ts +117 -71
  29. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/hosts.md +2 -0
  30. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/keyboard.md +3 -1
  31. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/startup-performance.md +83 -0
  32. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/tool-schema.md +74 -5
  33. package/node_modules/@juicesharp/rpiv-ask-user-question/events.ts +84 -0
  34. package/node_modules/@juicesharp/rpiv-ask-user-question/index.ts +10 -4
  35. package/node_modules/@juicesharp/rpiv-ask-user-question/package.json +4 -2
  36. package/node_modules/@juicesharp/rpiv-ask-user-question/presentation.ts +1 -1
  37. package/node_modules/@juicesharp/rpiv-ask-user-question/reconcile.ts +1 -1
  38. package/node_modules/@juicesharp/rpiv-ask-user-question/rpc-fallback.ts +5 -4
  39. package/node_modules/@juicesharp/rpiv-ask-user-question/state/build-questionnaire.ts +19 -19
  40. package/node_modules/@juicesharp/rpiv-ask-user-question/state/i18n-bridge.ts +1 -1
  41. package/node_modules/@juicesharp/rpiv-ask-user-question/state/key-router.ts +7 -4
  42. package/node_modules/@juicesharp/rpiv-ask-user-question/state/questionnaire-session.ts +10 -10
  43. package/node_modules/@juicesharp/rpiv-ask-user-question/state/row-intent.ts +2 -2
  44. package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/contract.ts +6 -6
  45. package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/derivations.ts +2 -2
  46. package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/focus.ts +1 -1
  47. package/node_modules/@juicesharp/rpiv-ask-user-question/state/selectors/projections.ts +9 -9
  48. package/node_modules/@juicesharp/rpiv-ask-user-question/state/state-reducer.ts +5 -5
  49. package/node_modules/@juicesharp/rpiv-ask-user-question/state/state.ts +2 -2
  50. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/external-answer.ts +125 -0
  51. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/format-answer.ts +1 -1
  52. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/normalize-params.ts +1 -1
  53. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/response-envelope.ts +2 -2
  54. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/types.ts +1 -1
  55. package/node_modules/@juicesharp/rpiv-ask-user-question/tool/validate-questionnaire.ts +1 -1
  56. package/node_modules/@juicesharp/rpiv-ask-user-question/view/component-binding.ts +4 -4
  57. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/multi-select-view.ts +4 -4
  58. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/option-list-view.ts +2 -2
  59. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/markdown-content-cache.ts +3 -3
  60. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-block-renderer.ts +5 -5
  61. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-layout-decider.ts +3 -3
  62. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/preview/preview-pane.ts +10 -10
  63. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/submit-picker.ts +2 -2
  64. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/tab-bar.ts +1 -1
  65. package/node_modules/@juicesharp/rpiv-ask-user-question/view/components/wrapping-select.ts +1 -1
  66. package/node_modules/@juicesharp/rpiv-ask-user-question/view/dialog-builder.ts +9 -9
  67. package/node_modules/@juicesharp/rpiv-ask-user-question/view/dialog-copy.ts +1 -1
  68. package/node_modules/@juicesharp/rpiv-ask-user-question/view/props-adapter.ts +8 -8
  69. package/node_modules/@juicesharp/rpiv-ask-user-question/view/tab-components.ts +4 -4
  70. package/node_modules/@juicesharp/rpiv-ask-user-question/view/tab-content-strategy.ts +10 -10
  71. package/node_modules/@narumitw/pi-btw/dist/index.ts +3 -0
  72. package/node_modules/@narumitw/pi-btw/dist/index.ts.map +2 -2
  73. package/node_modules/@narumitw/pi-btw/package.json +4 -4
  74. package/node_modules/@narumitw/pi-btw/src/fullscreen-ui.ts +6 -0
  75. package/node_modules/@narumitw/pi-btw/src/keybindings.ts +1 -1
  76. package/node_modules/@narumitw/pi-caffeinate/dist/index.ts +1 -0
  77. package/node_modules/@narumitw/pi-caffeinate/dist/index.ts.map +2 -2
  78. package/node_modules/@narumitw/pi-caffeinate/package.json +3 -3
  79. package/node_modules/@narumitw/pi-caffeinate/src/inhibitor-process.ts +1 -0
  80. package/node_modules/pi-antigravity/README.md +6 -2
  81. package/node_modules/pi-antigravity/package.json +2 -2
  82. package/node_modules/pi-antigravity/src/client/client.ts +44 -52
  83. package/node_modules/pi-antigravity/src/index.ts +13 -0
  84. package/node_modules/pi-antigravity/src/models/discovery.ts +25 -2
  85. package/node_modules/pi-antigravity/src/models/grouping.ts +107 -68
  86. package/node_modules/pi-antigravity/src/models/models.ts +10 -0
  87. package/node_modules/pi-antigravity/src/search/search.ts +581 -43
  88. package/node_modules/pi-antigravity/src/stream/stream.ts +53 -13
  89. package/node_modules/pi-antigravity/src/types/types.ts +13 -0
  90. package/node_modules/pi-antigravity/src/usage/usage.ts +11 -3
  91. package/node_modules/pi-web-access/CHANGELOG.md +21 -0
  92. package/node_modules/pi-web-access/README.md +22 -7
  93. package/node_modules/pi-web-access/credential-source.ts +54 -4
  94. package/node_modules/pi-web-access/curator-page.ts +3 -1
  95. package/node_modules/pi-web-access/curator-server.ts +1 -0
  96. package/node_modules/pi-web-access/deepseek.ts +204 -0
  97. package/node_modules/pi-web-access/dist/index.js +927 -642
  98. package/node_modules/pi-web-access/dist/mcp-cli.js +877 -615
  99. package/node_modules/pi-web-access/gemini-adc.ts +48 -1
  100. package/node_modules/pi-web-access/gemini-search.ts +8 -4
  101. package/node_modules/pi-web-access/index.ts +16 -1
  102. package/node_modules/pi-web-access/package.json +1 -1
  103. package/node_modules/pi-web-access/page-query.ts +12 -6
  104. package/node_modules/pi-web-access/query-rewrite.ts +16 -13
  105. package/node_modules/pi-web-access/summary-review.ts +16 -6
  106. package/node_modules/pi-web-access/utils.ts +3 -0
  107. package/node_modules/pi-web-access/web-tool-core.ts +2 -0
  108. package/package.json +9 -9
@@ -3,7 +3,33 @@
3
3
  * SPDX-License-Identifier: MIT
4
4
  */
5
5
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
6
- import { estimateTokens, sessionEntryToContextMessages, type SessionEntry } from "@earendil-works/pi-coding-agent";
6
+ import * as pi from "@earendil-works/pi-coding-agent";
7
+ import { estimateTokens, findCutPoint, sessionEntryToContextMessages, type SessionEntry } from "@earendil-works/pi-coding-agent";
8
+
9
+ type ProjectedEntry = { readonly sourceEntry: SessionEntry; readonly messages: readonly AgentMessage[] };
10
+ type ProjectionApi = {
11
+ readonly buildSessionProjection?: (entries: SessionEntry[]) => { readonly entries: readonly ProjectedEntry[] };
12
+ };
13
+
14
+ /** Pi 1.0 applies context edits before choosing a cut; older Pi uses raw messages. */
15
+ function contextEntries(entries: readonly SessionEntry[]): readonly ProjectedEntry[] {
16
+ // SAFETY: Pi 1.x publicly returns sourceEntry/messages pairs; older Pi omits this API and uses the fallback below.
17
+ const buildProjection = (pi as unknown as ProjectionApi).buildSessionProjection;
18
+ if (buildProjection) return buildProjection([...entries]).entries;
19
+ const lastCompaction = entries.findLastIndex((entry) => entry.type === "compaction");
20
+ let active = entries;
21
+ if (lastCompaction >= 0) {
22
+ const compaction = entries[lastCompaction];
23
+ if (compaction?.type === "compaction") {
24
+ const firstKept = entries.findIndex((entry) => entry.id === compaction.firstKeptEntryId);
25
+ active = [compaction, ...(firstKept >= 0 ? entries.slice(firstKept, lastCompaction) : []), ...entries.slice(lastCompaction + 1)];
26
+ }
27
+ }
28
+ return active.map((sourceEntry, index) => ({
29
+ sourceEntry,
30
+ messages: sourceEntry.type === "compaction" && index > 0 ? [] : sessionEntryToContextMessages(sourceEntry),
31
+ }));
32
+ }
7
33
 
8
34
  /** ObservationPack changes tool-result content while preserving its call identity. */
9
35
  function messageKey(message: AgentMessage): string {
@@ -17,22 +43,14 @@ export function projectedEntryTokens(
17
43
  entries: readonly SessionEntry[],
18
44
  projected: readonly AgentMessage[],
19
45
  ): ReadonlyMap<string, number> {
20
- const lastCompaction = entries.findLastIndex((entry) => entry.type === "compaction");
21
- let active = entries;
22
- if (lastCompaction >= 0) {
23
- const compaction = entries[lastCompaction];
24
- if (compaction?.type === "compaction") {
25
- const firstKept = entries.findIndex((entry) => entry.id === compaction.firstKeptEntryId);
26
- active = [compaction, ...(firstKept >= 0 ? entries.slice(firstKept, lastCompaction) : []), ...entries.slice(lastCompaction + 1)];
27
- }
28
- }
29
46
  const sources = new Map<string, string[]>();
30
- for (const entry of active) {
31
- if (entry.type === "compaction" && entry !== entries[lastCompaction]) continue;
32
- for (const message of sessionEntryToContextMessages(entry)) {
47
+ for (const { sourceEntry, messages } of contextEntries(entries)) {
48
+ for (const message of messages) {
49
+ // A compaction preserves its system checkpoint; only its summary is replaced.
50
+ if (String(message.role) === "system") continue;
33
51
  const key = messageKey(message);
34
52
  const ids = sources.get(key) ?? [];
35
- ids.push(entry.id);
53
+ ids.push(sourceEntry.id);
36
54
  sources.set(key, ids);
37
55
  }
38
56
  }
@@ -56,3 +74,59 @@ export function projectedEntryTokens(
56
74
  }
57
75
  return tokens;
58
76
  }
77
+
78
+ /** Materialize Pi's canonical messages for its public cut-point helper. */
79
+ function cutEntries(projected: readonly ProjectedEntry[]): SessionEntry[] {
80
+ return projected.map(({ sourceEntry, messages }) => {
81
+ if (sourceEntry.type === "compaction") {
82
+ // The latest checkpoint is outside the cut range. Retained older checkpoints
83
+ // are invisible, but their entry type still stops metadata-boundary movement.
84
+ return { ...sourceEntry, summary: "", systemMessage: undefined };
85
+ }
86
+ const message = messages[0];
87
+ if (message) return { ...sourceEntry, type: "message", message } as SessionEntry;
88
+ return { ...sourceEntry, type: "custom", customType: "sol-pi-projection-empty", data: undefined } as SessionEntry;
89
+ });
90
+ }
91
+
92
+ /**
93
+ * Price the prefix Pi can remove, using its canonical projection for the cut and
94
+ * the last observed extension projection for savings. No context hook runs twice.
95
+ */
96
+ export function estimateProjectedCompactionTokens(
97
+ entries: readonly SessionEntry[],
98
+ keepRecentTokens: number,
99
+ projectedMessages?: readonly AgentMessage[],
100
+ ): number {
101
+ const projected = contextEntries(entries);
102
+ const path = cutEntries(projected);
103
+ const previous = projected.findIndex(({ sourceEntry, messages }) => sourceEntry.type === "compaction" && messages.length > 0);
104
+ const start = previous >= 0 ? previous + 1 : 0;
105
+ // The agent can append an empty aborted assistant after OCC stops the turn.
106
+ // It contributes no tokens but makes the same trailing cut available to Pi.
107
+ path.push({
108
+ type: "message", id: "sol-pi-online-context-compact-abort-marker", parentId: path.at(-1)?.id ?? null,
109
+ timestamp: new Date(0).toISOString(),
110
+ message: { role: "assistant", content: [], api: "sol-pi", provider: "sol-pi", model: "aborted",
111
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0,
112
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, stopReason: "aborted", timestamp: 0 },
113
+ } as SessionEntry);
114
+ // Pi 1.0 can additionally advance through a closed recovery-omission suffix.
115
+ // Its public helper may keep that suffix; conservatively price the smaller prefix.
116
+ const cut = findCutPoint(path, start, path.length, keepRecentTokens).firstKeptEntryIndex;
117
+ const prefix = projected.slice(start, cut);
118
+ // System messages survive as the next checkpoint and are never summarized.
119
+ const removable = (entry: ProjectedEntry): readonly AgentMessage[] =>
120
+ entry.sourceEntry.type === "compaction" ? [] : entry.messages.filter((message) => String(message.role) !== "system");
121
+ if (!prefix.some((entry) => removable(entry).length > 0)) return 0;
122
+ const sizes = projectedMessages === undefined ? undefined : projectedEntryTokens(entries, projectedMessages);
123
+ const prefixTokens = prefix.reduce((total, entry) => total + (sizes
124
+ ? sizes.get(entry.sourceEntry.id) ?? 0
125
+ : removable(entry).reduce((sum, message) => sum + estimateTokens(message), 0)), 0);
126
+ const previousEntry = projected[previous];
127
+ const previousTokens = previousEntry ? (sizes
128
+ ? sizes.get(previousEntry.sourceEntry.id) ?? 0
129
+ : previousEntry.messages.filter((message) => message.role === "compactionSummary")
130
+ .reduce((sum, message) => sum + estimateTokens(message), 0)) : 0;
131
+ return prefixTokens + previousTokens;
132
+ }
@@ -45,8 +45,17 @@ const planStepSchema = Type.Object(
45
45
  { additionalProperties: false },
46
46
  );
47
47
 
48
+ /**
49
+ * Pi 1.0 tool exposure: keep update_plan declared to the model, including in codemode `only` mode,
50
+ * and never callable from codemode scripts. A script call gets a nested `<parent>/<n>` id that no
51
+ * turn reports as a tool result, so its plan boundary could never compact. Pi 0.84.2 has no
52
+ * exposure field and ignores it; spreading a constant keeps its tool type free of the property.
53
+ */
54
+ const MODEL_ONLY_EXPOSURE = { exposure: "model-only" } as const;
55
+
48
56
  export function registerOnlineTools(pi: ExtensionAPI, handlers: OnlineToolHandlers): void {
49
57
  pi.registerTool({
58
+ ...MODEL_ONLY_EXPOSURE,
50
59
  name: "update_plan",
51
60
  label: "Update plan",
52
61
  description:
@@ -3,15 +3,20 @@
3
3
  * SPDX-License-Identifier: MIT
4
4
  */
5
5
 
6
- import { getAgentDir, type ExtensionAPI, type ExtensionContext, type ExtensionFactory } from "@earendil-works/pi-coding-agent";
6
+ import { getAgentDir, type BashToolOptions, type ExtensionAPI, type ExtensionContext, type ExtensionFactory } from "@earendil-works/pi-coding-agent";
7
7
  import { loadSolPiConfig, type SolPiConfig } from "./config.ts";
8
- import { registerActionFusion } from "./extensions/action-fusion/index.ts";
8
+ import { createActionFusionExtension } from "./extensions/action-fusion/index.ts";
9
+ import { loadActionFusionBashOptions } from "./shell-options.ts";
9
10
  import { registerEvidencePreservingReducer } from "./extensions/evidence-preserving-reducer/index.ts";
10
11
  import { registerObservationPack } from "./extensions/observation-pack/index.ts";
11
12
  import { registerOnlineContextCompact } from "./extensions/online-context-compact/index.ts";
12
13
 
13
- export function registerConfiguredFeatures(pi: ExtensionAPI, config: SolPiConfig): void {
14
- if (config.actionFusion) registerActionFusion(pi);
14
+ export function registerConfiguredFeatures(
15
+ pi: ExtensionAPI,
16
+ config: SolPiConfig,
17
+ bashOptions?: BashToolOptions,
18
+ ): void {
19
+ if (config.actionFusion) createActionFusionExtension({ bashOptions })(pi);
15
20
  if (config.observationPack) registerObservationPack(pi);
16
21
  if (config.evidencePreservingReducer) {
17
22
  registerEvidencePreservingReducer(pi, {
@@ -31,8 +36,12 @@ export function createSolPiExtension(
31
36
  let initialized = false;
32
37
  pi.on("session_start", (_event, ctx) => {
33
38
  if (initialized) return;
39
+ const config = loadConfig(ctx);
40
+ const bashOptions = config.actionFusion
41
+ ? loadActionFusionBashOptions(ctx.cwd, ctx.isProjectTrusted())
42
+ : undefined;
34
43
  initialized = true;
35
- registerConfiguredFeatures(pi, loadConfig(ctx));
44
+ registerConfiguredFeatures(pi, config, bashOptions);
36
45
  });
37
46
  };
38
47
  }
@@ -0,0 +1,22 @@
1
+ /*
2
+ * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+ import { getAgentDir, SettingsManager, type BashToolOptions } from "@earendil-works/pi-coding-agent";
6
+
7
+ /** Inherit Pi's file-backed shell settings without trusting unapproved project settings. */
8
+ export function loadActionFusionBashOptions(
9
+ cwd: string,
10
+ projectTrusted: boolean,
11
+ agentDir: string = getAgentDir(),
12
+ ): BashToolOptions {
13
+ const settings = SettingsManager.create(cwd, agentDir, { projectTrusted });
14
+ const errors = settings.drainErrors();
15
+ if (errors.length > 0) {
16
+ throw new Error(`Action Fusion could not load Pi shell settings: ${errors.map(({ error }) => error.message).join("; ")}`);
17
+ }
18
+ return {
19
+ shellPath: settings.getShellPath(),
20
+ commandPrefix: settings.getShellCommandPrefix(),
21
+ };
22
+ }
@@ -49,6 +49,17 @@ export function renderSolPiTool(
49
49
  return container;
50
50
  }
51
51
 
52
+ /**
53
+ * Whether a tool call was made by another tool through `ctx.executeTool()`,
54
+ * such as a codemode script, rather than by the model. Pi 0.99+ gives such
55
+ * calls the id `<calling id>/<n>` (documented on `ExtensionToolContext`) and
56
+ * passes no other marker to `execute()`. Provider-issued ids do not end in
57
+ * `/<digits>`; a false match would only suppress a savings notice.
58
+ */
59
+ export function isNestedToolCallId(toolCallId: string): boolean {
60
+ return /\/\d+$/u.test(toolCallId);
61
+ }
62
+
52
63
  export function showSolPiSavings(
53
64
  context: ExtensionContext,
54
65
  mechanism: SolPiTuiMechanism,
@@ -0,0 +1,109 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ ASK_USER_ANSWER_EVENT,
4
+ ASK_USER_ANSWER_RESULT_EVENT,
5
+ type AskUserAnswerRejectCode,
6
+ type AskUserAnswerResultEventPayload,
7
+ } from "./events.ts";
8
+ import { resolveExternalAnswer } from "./tool/external-answer.ts";
9
+ import type { QuestionData, QuestionnaireResult } from "./tool/types.ts";
10
+
11
+ /** "rpc" while the RPC dialog walker owns the prompts — those cannot be answered from outside. */
12
+ export type AnswerHost = "tui" | "rpc";
13
+
14
+ /**
15
+ * One questionnaire an inbound `rpiv:ask-user:answer` may resolve, opened by `execute()`
16
+ * before its prompt event goes out and closed in its `finally`. Both answer sources —
17
+ * the dialog's own `done` and the inbound event — go through `settle`, so the first
18
+ * wins and a later one is refused instead of reported as applied.
19
+ */
20
+ export class OpenQuestionnaire {
21
+ private result: QuestionnaireResult | undefined;
22
+ private deliver: ((result: QuestionnaireResult) => void) | undefined;
23
+ private resolveEarly!: (result: QuestionnaireResult) => void;
24
+ /** Resolves with an answer accepted while no dialog was mounted to take it. */
25
+ readonly answeredEarly = new Promise<QuestionnaireResult>((resolve) => {
26
+ this.resolveEarly = resolve;
27
+ });
28
+
29
+ constructor(
30
+ readonly toolCallId: string,
31
+ readonly questions: readonly QuestionData[],
32
+ public host: AnswerHost,
33
+ ) {}
34
+
35
+ /** The accepted result, once settled. */
36
+ get settled(): QuestionnaireResult | undefined {
37
+ return this.result;
38
+ }
39
+
40
+ /** Hand over the mounted dialog's `done`; answers from now on close the dialog through it. */
41
+ attach(done: (result: QuestionnaireResult) => void): void {
42
+ this.deliver = done;
43
+ }
44
+
45
+ /** First answer wins. False when this questionnaire is already settled. */
46
+ settle(result: QuestionnaireResult): boolean {
47
+ if (this.result) return false;
48
+ this.result = result;
49
+ if (this.deliver) this.deliver(result);
50
+ else this.resolveEarly(result);
51
+ return true;
52
+ }
53
+ }
54
+
55
+ export interface AnswerChannel {
56
+ open(toolCallId: string, questions: readonly QuestionData[], host: AnswerHost): OpenQuestionnaire;
57
+ close(questionnaire: OpenQuestionnaire): void;
58
+ }
59
+
60
+ const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
61
+
62
+ /**
63
+ * Listen for `rpiv:ask-user:answer` and answer every attempt on `rpiv:ask-user:answer-result`.
64
+ * Open questionnaires are keyed by tool-call id: Pi runs tool calls in parallel, so several
65
+ * can be open at once and the emitter must name the one it answers.
66
+ */
67
+ export function registerAnswerChannel(pi: ExtensionAPI): AnswerChannel {
68
+ const open = new Map<string, OpenQuestionnaire>();
69
+
70
+ pi.events.on(ASK_USER_ANSWER_EVENT, (data: unknown) => {
71
+ const payload = isRecord(data) ? data : {};
72
+ const requestId = typeof payload.requestId === "string" ? payload.requestId : undefined;
73
+ const toolCallId = typeof payload.toolCallId === "string" ? payload.toolCallId : undefined;
74
+ const reply = (code?: AskUserAnswerRejectCode, reason?: string) => {
75
+ const verdict: AskUserAnswerResultEventPayload = {
76
+ ok: code === undefined,
77
+ ...(code ? { code, reason } : {}),
78
+ ...(requestId !== undefined ? { requestId } : {}),
79
+ ...(toolCallId !== undefined ? { toolCallId } : {}),
80
+ };
81
+ pi.events.emit(ASK_USER_ANSWER_RESULT_EVENT, verdict);
82
+ };
83
+
84
+ if (!isRecord(data)) return reply("invalid_payload", "payload must be an object");
85
+ if (payload.requestId !== undefined && requestId === undefined) {
86
+ return reply("invalid_payload", "requestId must be a string");
87
+ }
88
+ if (toolCallId === undefined) return reply("invalid_payload", "toolCallId must be a string");
89
+ const target = open.get(toolCallId);
90
+ if (!target || target.settled) return reply("not_found", `no open questionnaire for tool call ${toolCallId}`);
91
+ if (target.host === "rpc") return reply("unsupported_host", "this host shows the questions in its own dialogs");
92
+
93
+ const outcome = resolveExternalAnswer(target.questions, payload);
94
+ if (!outcome.ok) return reply(outcome.code, outcome.reason);
95
+ if (!target.settle(outcome.result)) return reply("not_found", `tool call ${toolCallId} is already answered`);
96
+ reply();
97
+ });
98
+
99
+ return {
100
+ open(toolCallId, questions, host) {
101
+ const questionnaire = new OpenQuestionnaire(toolCallId, questions, host);
102
+ open.set(toolCallId, questionnaire);
103
+ return questionnaire;
104
+ },
105
+ close(questionnaire) {
106
+ if (open.get(questionnaire.toolCallId) === questionnaire) open.delete(questionnaire.toolCallId);
107
+ },
108
+ };
109
+ }
@@ -1,18 +1,19 @@
1
1
  import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
2
2
  import { isKeyRelease, isKeyRepeat, matchesKey, type OverlayHandle, type TUI } from "@earendil-works/pi-tui";
3
+ import { type OpenQuestionnaire, registerAnswerChannel } from "./answer-channel.ts";
3
4
  import {
4
5
  COLLAPSE_KEY_OFF,
5
6
  formatKeySpecForDisplay,
6
7
  loadConfig,
7
8
  resolveCollapseKey,
8
9
  validateGuidanceFields,
9
- } from "./config.js";
10
+ } from "./config.ts";
10
11
  import {
11
12
  ASK_USER_BLOCKED_EVENT,
12
13
  ASK_USER_PROMPT_EVENT,
13
14
  type AskUserBlockedEventPayload,
14
15
  type AskUserPromptEventPayload,
15
- } from "./events.js";
16
+ } from "./events.ts";
16
17
  // Static import is fine — rpc-fallback pulls only types + the i18n bridge,
17
18
  // none of the ~560ms TUI render graph that QuestionnaireSession lazy-loads.
18
19
  import {
@@ -22,12 +23,12 @@ import {
22
23
  rowBudgetForHost,
23
24
  STACKED_OVERLAY_PRESENTATION,
24
25
  YIELD_TO_OVERLAY,
25
- } from "./presentation.js";
26
- import { type DialogUI, hasDialogUI, runRpcQuestionnaire } from "./rpc-fallback.js";
27
- import { displayLabel, t } from "./state/i18n-bridge.js";
28
- import { sentinelsToAppend } from "./state/row-intent.js";
29
- import { normalizeQuestionParams, prepareQuestionArguments } from "./tool/normalize-params.js";
30
- import { buildQuestionnaireResponse, buildToolResult } from "./tool/response-envelope.js";
26
+ } from "./presentation.ts";
27
+ import { type DialogUI, hasDialogUI, runRpcQuestionnaire } from "./rpc-fallback.ts";
28
+ import { displayLabel, t } from "./state/i18n-bridge.ts";
29
+ import { sentinelsToAppend } from "./state/row-intent.ts";
30
+ import { normalizeQuestionParams, prepareQuestionArguments } from "./tool/normalize-params.ts";
31
+ import { buildQuestionnaireResponse, buildToolResult } from "./tool/response-envelope.ts";
31
32
  import {
32
33
  MAX_OPTIONS,
33
34
  MAX_QUESTIONS,
@@ -37,12 +38,13 @@ import {
37
38
  type QuestionnaireResult,
38
39
  type QuestionParams,
39
40
  QuestionParamsSchema,
40
- } from "./tool/types.js";
41
- import { validateQuestionnaire } from "./tool/validate-questionnaire.js";
42
- import type { WrappingSelectItem } from "./view/components/wrapping-select.js";
41
+ } from "./tool/types.ts";
42
+ import { validateQuestionnaire } from "./tool/validate-questionnaire.ts";
43
+ import type { WrappingSelectItem } from "./view/components/wrapping-select.ts";
43
44
 
44
- function emitAskUserPromptEvent(pi: ExtensionAPI, params: QuestionParams): void {
45
+ function emitAskUserPromptEvent(pi: ExtensionAPI, params: QuestionParams, toolCallId: string): void {
45
46
  const payload: AskUserPromptEventPayload = {
47
+ toolCallId,
46
48
  questions: params.questions.map((q) => ({
47
49
  question: q.question,
48
50
  header: q.header,
@@ -57,8 +59,8 @@ function emitAskUserPromptEvent(pi: ExtensionAPI, params: QuestionParams): void
57
59
  pi.events.emit(ASK_USER_PROMPT_EVENT, payload);
58
60
  }
59
61
 
60
- function emitAskUserBlockedEvent(pi: ExtensionAPI, active: boolean): void {
61
- const payload: AskUserBlockedEventPayload = { active };
62
+ function emitAskUserBlockedEvent(pi: ExtensionAPI, active: boolean, toolCallId: string): void {
63
+ const payload: AskUserBlockedEventPayload = { active, toolCallId };
62
64
  pi.events.emit(ASK_USER_BLOCKED_EVENT, payload);
63
65
  }
64
66
 
@@ -68,13 +70,13 @@ function rejectWithoutUi() {
68
70
  }
69
71
 
70
72
  /** Sequential native-dialog walker for RPC hosts; brackets it with the blocked-event pair + terminal bell. */
71
- async function runRpcPath(pi: ExtensionAPI, ui: DialogUI, typed: QuestionParams) {
72
- emitAskUserBlockedEvent(pi, true);
73
+ async function runRpcPath(pi: ExtensionAPI, ui: DialogUI, typed: QuestionParams, toolCallId: string) {
74
+ emitAskUserBlockedEvent(pi, true, toolCallId);
73
75
  try {
74
76
  emitTerminalAttention();
75
77
  return buildQuestionnaireResponse(await runRpcQuestionnaire(ui, typed), typed);
76
78
  } finally {
77
- emitAskUserBlockedEvent(pi, false);
79
+ emitAskUserBlockedEvent(pi, false, toolCallId);
78
80
  }
79
81
  }
80
82
 
@@ -113,9 +115,9 @@ function emitTerminalAttention(): void {
113
115
  /** Delay before the background session-graph pre-warm; mirrors rpiv-workflow's /wf prewarm. */
114
116
  export const PREWARM_DELAY_MS = 2000;
115
117
 
116
- type SessionModule = typeof import("./state/questionnaire-session.js");
118
+ type SessionModule = typeof import("./state/questionnaire-session.ts");
117
119
 
118
- type SessionRef = { current: import("./state/questionnaire-session.js").QuestionnaireSession | null };
120
+ type SessionRef = { current: import("./state/questionnaire-session.ts").QuestionnaireSession | null };
119
121
  type OverlayHandleRef = { current: OverlayHandle | undefined };
120
122
 
121
123
  type SessionLoad =
@@ -136,7 +138,7 @@ type SessionLoad =
136
138
  export async function loadQuestionnaireSession(): Promise<SessionLoad> {
137
139
  let mod: SessionModule;
138
140
  try {
139
- mod = await import("./state/questionnaire-session.js");
141
+ mod = await import("./state/questionnaire-session.ts");
140
142
  } catch (e) {
141
143
  const cause = e instanceof Error ? e.message : String(e);
142
144
  return { ok: false, error: "session_load_failed", message: `${ERROR_SESSION_LOAD_FAILED} (cause: ${cause})` };
@@ -200,33 +202,43 @@ function makeSessionFactory(config: {
200
202
  canReopenWhileHidden: boolean;
201
203
  presentation: Presentation;
202
204
  sessionRef: SessionRef;
205
+ open: OpenQuestionnaire;
203
206
  Session: SessionModule["QuestionnaireSession"];
204
207
  }) {
205
- const { ctx, typed, itemsByTab, collapseKey, canReopenWhileHidden, presentation, sessionRef, Session } = config;
208
+ const { ctx, typed, itemsByTab, collapseKey, canReopenWhileHidden, presentation, sessionRef, open, Session } =
209
+ config;
206
210
  return (
207
211
  tui: TUI,
208
212
  theme: Theme,
209
- keybindings: import("./state/questionnaire-session.js").QuestionnaireSessionConfig["keybindings"],
213
+ keybindings: import("./state/questionnaire-session.ts").QuestionnaireSessionConfig["keybindings"],
210
214
  done: (result: QuestionnaireResult) => void,
211
- ): import("./state/questionnaire-session.js").QuestionnaireSessionComponent => {
215
+ ): import("./state/questionnaire-session.ts").QuestionnaireSessionComponent => {
212
216
  // The factory runs at mount time — the first point the TUI is reachable — so this is
213
217
  // where an inline mount notices an overlay already on screen and gives the slot up.
214
218
  if (!presentation.overlay && mustYieldInlineSlot(tui)) {
215
219
  done(YIELD_TO_OVERLAY);
216
220
  return INERT_COMPONENT;
217
221
  }
222
+ // Answered from outside before this mount (a host may mount late, e.g. a lane
223
+ // console): close at once with that answer.
224
+ if (open.settled) {
225
+ done(open.settled);
226
+ return INERT_COMPONENT;
227
+ }
228
+ open.attach(done);
218
229
  const session = new Session({
219
230
  tui,
220
231
  theme,
221
232
  params: typed,
222
233
  itemsByTab,
223
- done,
234
+ // Through the first-answer-wins gate shared with inbound answers.
235
+ done: (result) => open.settle(result),
224
236
  keybindings,
225
237
  editInput: async (value) => {
226
238
  try {
227
239
  const [{ SettingsManager }, { editWithExternalEditor }] = await Promise.all([
228
240
  import("@earendil-works/pi-coding-agent"),
229
- import("./state/external-editor.js"),
241
+ import("./state/external-editor.ts"),
230
242
  ]);
231
243
  const editorCommand = SettingsManager.create(ctx.cwd, undefined, {
232
244
  projectTrusted: ctx.isProjectTrusted(),
@@ -249,7 +261,7 @@ function makeSessionFactory(config: {
249
261
  }
250
262
 
251
263
  /** Stand-in returned by a mount that resolved before mounting (Pi discards it unmounted). */
252
- const INERT_COMPONENT: import("./state/questionnaire-session.js").QuestionnaireSessionComponent = {
264
+ const INERT_COMPONENT: import("./state/questionnaire-session.ts").QuestionnaireSessionComponent = {
253
265
  render: () => [],
254
266
  invalidate: () => {},
255
267
  handleInput: () => {},
@@ -268,6 +280,7 @@ async function mountQuestionnaire(config: {
268
280
  itemsByTab: WrappingSelectItem[][];
269
281
  collapseKey: string;
270
282
  presentation: Presentation;
283
+ open: OpenQuestionnaire;
271
284
  Session: SessionModule["QuestionnaireSession"];
272
285
  }): Promise<QuestionnaireResult | undefined> {
273
286
  const { ctx, collapseKey, presentation } = config;
@@ -317,6 +330,73 @@ async function resolveUndefinedResult(ctx: ExtensionContext, typed: QuestionPara
317
330
  return buildToolResult(ERROR_NO_CUSTOM_UI, { answers: [], cancelled: true, error: "no_custom_ui" });
318
331
  }
319
332
 
333
+ /**
334
+ * The terminal dialog: inline in Pi's editor slot, or an overlay (see presentation.ts).
335
+ * Each mount races `open.answeredEarly`, so an inbound answer accepted before any dialog
336
+ * took it ends the call — a host that mounts later closes the dialog on sight (factory).
337
+ */
338
+ async function runTuiPath(pi: ExtensionAPI, ctx: ExtensionContext, typed: QuestionParams, open: OpenQuestionnaire) {
339
+ const itemsByTab: WrappingSelectItem[][] = typed.questions.map((q) => buildItemsForQuestion(q));
340
+ let presentation: Presentation | undefined;
341
+
342
+ // Bracketed from before the load: every prompt event is followed by exactly one
343
+ // `{ active: false }` for its tool call, however the call ends — a remote mirror
344
+ // dismisses on it.
345
+ emitAskUserBlockedEvent(pi, true, open.toolCallId);
346
+ try {
347
+ // Lazy — QuestionnaireSession pulls the ~560ms view/TUI render graph;
348
+ // load it only when the tool runs, not at extension registration.
349
+ const sessionLoad = await loadQuestionnaireSession();
350
+ // Answered during the load: the answer needs no dialog.
351
+ if (open.settled) return buildQuestionnaireResponse(open.settled, typed);
352
+ if (!sessionLoad.ok) {
353
+ return buildToolResult(sessionLoad.message, { answers: [], cancelled: true, error: sessionLoad.error });
354
+ }
355
+ const { QuestionnaireSession } = sessionLoad.module;
356
+ // Resolve the collapse/expand key spec from config. Default is `ctrl+]`; users
357
+ // with non-US layouts (e.g. Latin American, where `]` is shifted) can override
358
+ // via the `collapseKey` config field. `resolveCollapseKey` also accepts the
359
+ // sentinel value `"off"` to disable the shortcut entirely.
360
+ const collapseKey = resolveCollapseKey(loadConfig());
361
+ const mount = (p: Presentation) =>
362
+ Promise.race([
363
+ mountQuestionnaire({
364
+ ctx,
365
+ typed,
366
+ itemsByTab,
367
+ collapseKey,
368
+ presentation: p,
369
+ open,
370
+ Session: QuestionnaireSession,
371
+ }),
372
+ open.answeredEarly,
373
+ ]);
374
+
375
+ // Pi's editor slot (#253); the overlay only while another questionnaire holds the slot,
376
+ // or stacked when another overlay is already on screen (see below).
377
+ presentation = resolvePresentation();
378
+ emitTerminalAttention();
379
+ let result = await mount(presentation);
380
+ if (result === YIELD_TO_OVERLAY) {
381
+ // Another overlay was on screen: stack on top of it instead (see mustYieldInlineSlot).
382
+ presentation.release?.();
383
+ presentation = STACKED_OVERLAY_PRESENTATION;
384
+ result = await mount(presentation);
385
+ }
386
+
387
+ if (result === undefined) {
388
+ // The RPC walker takes over; its prompts cannot be answered from outside.
389
+ open.host = "rpc";
390
+ return await resolveUndefinedResult(ctx, typed);
391
+ }
392
+
393
+ return buildQuestionnaireResponse(result, typed);
394
+ } finally {
395
+ presentation?.release?.();
396
+ emitAskUserBlockedEvent(pi, false, open.toolCallId);
397
+ }
398
+ }
399
+
320
400
  /**
321
401
  * Pre-warm the lazy session graph once startup settles (#107). A graph
322
402
  * evaluated while the paths Pi resolved at boot still exist stays in memory
@@ -374,6 +454,7 @@ Preview content is rendered as markdown in a monospace box. Multi-line text with
374
454
 
375
455
  export function registerAskUserQuestionTool(pi: ExtensionAPI): void {
376
456
  const guidance = validateGuidanceFields(loadConfig().guidance);
457
+ const answers = registerAnswerChannel(pi);
377
458
  pi.registerTool({
378
459
  name: ASK_USER_QUESTION_TOOL_NAME,
379
460
  label: "Ask User Question",
@@ -384,7 +465,7 @@ export function registerAskUserQuestionTool(pi: ExtensionAPI): void {
384
465
  // Undo double-encoded nested arguments before Pi validates them (#244).
385
466
  prepareArguments: prepareQuestionArguments,
386
467
 
387
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
468
+ async execute(toolCallId, params, _signal, _onUpdate, ctx) {
388
469
  // Line-terminator normalization runs once here, ahead of validation, so
389
470
  // every downstream consumer — validator, TUI, RPC walker, envelope, prompt
390
471
  // event — sees the same clean text (#192).
@@ -400,58 +481,23 @@ export function registerAskUserQuestionTool(pi: ExtensionAPI): void {
400
481
  });
401
482
  }
402
483
 
403
- // Emit event for external listeners (e.g., notification plugins)
404
- emitAskUserPromptEvent(pi, typed);
405
-
406
484
  // RPC hosts (VSCode pendant, ACP clients like Zed/Paseo — issue #78):
407
485
  // ui.custom() cannot render there, but the select/input dialog
408
486
  // sub-protocol works. Hosts that advertise ctx.mode (pi ≥0.79) route to
409
487
  // the sequential dialog walker up front, skipping the TUI render-graph
410
488
  // import entirely; RPC builds that predate ctx.mode are caught by the
411
489
  // custom()-resolved-undefined backstop below. See ./rpc-fallback.ts.
412
- if ((ctx as { mode?: string }).mode === "rpc" && hasDialogUI(ctx.ui)) {
413
- return runRpcPath(pi, ctx.ui, typed);
414
- }
415
-
416
- const itemsByTab: WrappingSelectItem[][] = typed.questions.map((q) => buildItemsForQuestion(q));
417
-
418
- // Lazy — QuestionnaireSession pulls the ~560ms view/TUI render graph;
419
- // load it only when the tool runs, not at extension registration.
420
- const sessionLoad = await loadQuestionnaireSession();
421
- if (!sessionLoad.ok) {
422
- return buildToolResult(sessionLoad.message, { answers: [], cancelled: true, error: sessionLoad.error });
423
- }
424
- const { QuestionnaireSession } = sessionLoad.module;
425
- // Resolve the collapse/expand key spec from config. Default is `ctrl+]`; users
426
- // with non-US layouts (e.g. Latin American, where `]` is shifted) can override
427
- // via the `collapseKey` config field. `resolveCollapseKey` also accepts the
428
- // sentinel value `"off"` to disable the shortcut entirely.
429
- const collapseKey = resolveCollapseKey(loadConfig());
430
- // Pi's editor slot (#253); the overlay only while another questionnaire holds the slot,
431
- // or stacked when another overlay is already on screen (see below).
432
- let presentation = resolvePresentation();
433
- const mount = (p: Presentation) =>
434
- mountQuestionnaire({ ctx, typed, itemsByTab, collapseKey, presentation: p, Session: QuestionnaireSession });
435
-
436
- emitAskUserBlockedEvent(pi, true);
490
+ const viaRpc = (ctx as { mode?: string }).mode === "rpc" && hasDialogUI(ctx.ui);
491
+ // Open for inbound answers before the prompt goes out: an emitter may answer
492
+ // straight from its prompt listener.
493
+ const open = answers.open(toolCallId, typed.questions, viaRpc ? "rpc" : "tui");
437
494
  try {
438
- emitTerminalAttention();
439
- let result = await mount(presentation);
440
- if (result === YIELD_TO_OVERLAY) {
441
- // Another overlay was on screen: stack on top of it instead (see mustYieldInlineSlot).
442
- presentation.release?.();
443
- presentation = STACKED_OVERLAY_PRESENTATION;
444
- result = await mount(presentation);
445
- }
446
-
447
- if (result === undefined) {
448
- return resolveUndefinedResult(ctx, typed);
449
- }
450
-
451
- return buildQuestionnaireResponse(result, typed);
495
+ // Emit event for external listeners (e.g., notification plugins)
496
+ emitAskUserPromptEvent(pi, typed, toolCallId);
497
+ if (viaRpc) return await runRpcPath(pi, ctx.ui, typed, toolCallId);
498
+ return await runTuiPath(pi, ctx, typed, open);
452
499
  } finally {
453
- presentation.release?.();
454
- emitAskUserBlockedEvent(pi, false);
500
+ answers.close(open);
455
501
  }
456
502
  },
457
503
  });