@narumitw/pi-plan-mode 0.54.0 → 0.55.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/README.md CHANGED
@@ -9,7 +9,7 @@ This independently installable extension adds a Codex-like `/plan` collaboration
9
9
  ## ✨ Features
10
10
 
11
11
  - Starts and manages Plan mode through `/plan`, `/plan start`, or `/plan <prompt>`.
12
- - Defers Plan helper schemas until first use by default, then keeps the unlocked tool envelope stable while runtime policy blocks mutations and unsafe shell forms.
12
+ - Keeps Plan helper schemas stable from startup while runtime policy blocks inactive helpers, mutations, and unsafe shell forms.
13
13
  - Requires structured questions for important ambiguity and explicit completion for a decision-ready plan.
14
14
  - Reviews the complete plan before implementation, export, save, continued planning, or discard.
15
15
  - Starts implementation in the planning session or a fresh linked session with the exact approved plan.
@@ -61,13 +61,11 @@ An inactive legacy state entry alone does not inject a Normal contract, so sessi
61
61
  Manual `/tree` navigation restores branch-owned Plan state and chooses the matching effective contract without navigating automatically or adding a branch summary.
62
62
  Pi currently lists hidden custom transition messages in `/tree`; Plan mode rejects those internal targets, so select an adjacent conversation entry instead.
63
63
 
64
- The default `toolVisibility: "after-first-plan"` keeps `plan_mode_question` and `plan_mode_complete` registered but inactive until the first successful Plan activation in an extension runtime.
65
- That activation appends the two helpers in canonical order and may cause one provider-prefix cache miss because `/plan` is a slash-command transition rather than a model-called deferred-tool loader.
66
- The helpers and their active-only prompt metadata remain visible after that boundary across off, exit, save, export, implementation, and same-runtime session starts.
67
- Failed, cancelled, stale, or workflow-busy activation restores the exact prior active-tool list and does not consume the first-activation boundary.
68
- Choose `toolVisibility: "always"` to expose both helpers at session startup and preserve the previous stable-prefix behavior from the first request.
69
- Neither choice guarantees a cache hit because provider serialization, cache lifetime, minimum cacheable prefix, implementation details, and session affinity still control reuse.
70
- A user, Pi, or another extension can change the active tool set outside this extension's guarantee.
64
+ Plan mode registers `plan_mode_question` and `plan_mode_complete` once and keeps their names and definitions stable across Normal, Plan, ready, implementation, and restored workflows.
65
+ Visible helpers do not mean `/plan` is active, and their global descriptions explicitly exclude ordinary planning, the `writing-plans` skill, roadmaps, checklists, and plan-file work.
66
+ Positive helper instructions live only in the latest effective active Plan contract, while inactive or stale calls fail without accepting a plan or opening question UI.
67
+ Plan mode never widens a restrictive active-tool policy; start or restore fails when a required helper is unavailable.
68
+ Stable schemas preserve a cache-eligible prefix but cannot guarantee a hit because provider serialization, cache lifetime, minimum cacheable prefix, implementation details, and session affinity remain external.
71
69
 
72
70
  The default `thinkingLevel: "inherit"` path also avoids a Plan-specific reasoning-parameter change.
73
71
  Choosing a fixed Plan thinking level remains supported, but switching reasoning parameters can prevent provider-side state reuse even when system instructions and tool schemas are stable.
@@ -121,7 +119,7 @@ Relative paths resolve from the command's current `ctx.cwd` at export time, abso
121
119
  Explicit `/plan export <path>` input always wins over the setting.
122
120
  Export never overwrites an existing file, directory, or symbolic link: choose another path or remove the existing target first.
123
121
  A successful export adds one trailing newline but otherwise preserves the accepted Markdown exactly.
124
- After a ready plan is written, Plan mode ends, its thinking level is restored, the current helper visibility is retained, and the ready state is cleared without starting a model turn.
122
+ After a ready plan is written, Plan mode ends, its thinking level is restored, the stable helper envelope is unchanged, and the ready state is cleared without starting a model turn.
125
123
  Exporting a saved or active implementation plan leaves that state unchanged.
126
124
  Failed or cancelled exports leave every Plan-mode state unchanged.
127
125
  The resulting file is available to the agent through its normal file-reading tools.
@@ -140,10 +138,8 @@ The agent may inspect files and run read-only commands, but it should not edit f
140
138
  It should explore first, then use structured questions when your preference or a tradeoff materially changes the plan.
141
139
  Configure persistent defaults or a one-workflow tool override before activation; Planning and ready menus deliberately keep those controls locked.
142
140
 
143
- Plan mode registers `plan_mode_question` and `plan_mode_complete` during extension load.
144
- With the default **After first plan** visibility, `session_start` leaves both helpers inactive until the first admitted Plan workflow appends them in that order.
145
- With **Always**, `session_start` appends missing helpers in the same canonical order.
146
- Once revealed, ordinary Plan transitions never remove them during that extension runtime.
141
+ Plan mode registers `plan_mode_question` and `plan_mode_complete` during extension load and never changes their active status itself.
142
+ Another active-tool policy may hide them, in which case Plan start or restore fails without widening that policy.
147
143
  By default, the Plan policy allows active safe built-ins such as `read`, limited `bash`, limited `powershell`, `grep`, `find`, and `ls`.
148
144
  The optional native `powershell` tool must already be active, for example through Pi's Windows `defaultTools` setting, before Plan mode can select it.
149
145
  Built-in `edit` and `write`, `update_plan`, inactive tools, and deselected tools are blocked at execution time even though active schemas remain visible.
@@ -311,7 +307,7 @@ Guaranteed coexistence with Goal requires `@narumitw/pi-goal` `0.53.0` or newer
311
307
 
312
308
  ## ⚙️ Settings
313
309
 
314
- Open **Settings** from an inactive `/plan` menu to edit one flat group of six workflow choices: **Plan thinking**, **Plan policy tools**, **Plan reinjection**, **Export destination**, **Plan mode shortcut**, and **Plan tools**.
310
+ Open **Settings** from an inactive `/plan` menu to edit one flat group of five workflow choices: **Plan thinking**, **Plan policy tools**, **Plan reinjection**, **Export destination**, and **Plan mode shortcut**.
315
311
  You can also edit `$PI_CODING_AGENT_DIR/pi-plan-mode.json` (normally `~/.pi/agent/pi-plan-mode.json`) manually.
316
312
  `safeSubcommands` remains JSON-only.
317
313
  You can change the Plan-mode shortcut with `toggleShortcut` as long as the file remains JSON-only and uses a valid key string.
@@ -320,7 +316,6 @@ When omitted, the shortcut is disabled by default.
320
316
  ```json
321
317
  {
322
318
  "thinkingLevel": "inherit",
323
- "toolVisibility": "after-first-plan",
324
319
  "defaultPlanTools": ["read", "bash", "grep", "find", "ls"],
325
320
  "implementationPlanRetention": "clear-on-start",
326
321
  "defaultPlanExportPath": "PLAN.md",
@@ -332,17 +327,12 @@ When omitted, the shortcut is disabled by default.
332
327
  }
333
328
  ```
334
329
 
335
- ### Plan helper visibility
330
+ ### Plan helper tools
336
331
 
337
- `toolVisibility` accepts `"after-first-plan"` or `"always"`.
338
- Omit it—or choose **After first plan**—to keep both Plan helpers out of model requests until the first successful Plan activation in that extension runtime.
339
- A successful activation keeps the helpers visible for the rest of that runtime; changing the setting back to **After first plan** while inactive resets and hides them at an idle, mutex-admitted boundary.
340
- Choose **Always** to make the helpers model-visible at session startup and avoid the lazy first-use prefix change.
341
- Settings-menu changes apply and persist immediately only after idle and Workflow Mutex admission; failure restores the prior runtime and displayed value.
342
- Manual file changes reload automatically and apply visibility when the session is inactive, idle, and mutex-admitted.
343
- An unsafe manual reload keeps the current tool envelope until the next session start or successful Plan activation.
344
- A restored active Plan reveals its helpers only after acquiring workflow ownership, while a busy restore leaves active tools untouched.
345
- This setting uses ordinary active-tool activation and does not claim Pi native deferred loading.
332
+ Plan helper schemas are stable from extension registration onward, and Plan mode does not call `setActiveTools()`.
333
+ Tool visibility alone is not Plan activation.
334
+ Only the latest effective active Plan contract authorizes `plan_mode_question` or `plan_mode_complete`; ordinary planning and the `writing-plans` skill use their own workflow instead.
335
+ The retired `toolVisibility` key is ignored and preserved as unknown data when another setting is saved or a legacy settings file is migrated.
346
336
 
347
337
  ### Default Plan policy tools
348
338
 
@@ -465,7 +455,7 @@ A missing file stays absent until an explicit save.
465
455
  Invalid JSON, invalid values, oversized content, non-regular files, and read failures make Settings read-only; the existing bytes and previous effective settings remain.
466
456
  This in-process queue is not a cross-process lock, so concurrent separate Pi processes can still race.
467
457
 
468
- Invalid settings produce a warning and fall back to inherited thinking, `after-first-plan` helper visibility, available safe-built-in tool defaults, `clear-on-start`, and `PLAN.md`.
458
+ Invalid settings produce a warning and fall back to inherited thinking, available safe-built-in tool defaults, `clear-on-start`, and `PLAN.md`.
469
459
  Compatibility: a valid legacy `plan-mode.json` remains readable with a warning and is never modified automatically.
470
460
  If Settings is explicitly saved while only that legacy file exists, the extension creates canonical `pi-plan-mode.json` from the complete legacy document, applies the selected change, preserves unknown fields, and leaves the legacy file untouched.
471
461
  If both files exist, the canonical filename takes precedence.
@@ -482,7 +472,7 @@ This extension maps Codex's `ModeKind::Plan` behavior onto Pi's extension API:
482
472
  - The implementation boundary is explicit: Plan mode appends the Normal contract and lifts its runtime allowlist before saving or starting implementation, while revealed helpers remain active.
483
473
  - The default `clear-on-start` policy follows Codex by using ordinary conversation history only; `clear-after-first-run` and `keep` add explicit exact-plan guarantees.
484
474
  - Pi extension safety is approximated with tool classification and separate fail-closed filtering for every effective tool named `bash` or `powershell`; other non-built-in tools remain user-selected at user risk because Pi does not expose standardized tool mutability metadata.
485
- - Plan and Normal instructions are append-only conversation contracts; **Always** keeps tool schemas stable from startup, while **After first plan** intentionally changes the helper schema and prompt-metadata prefix once before keeping it stable.
475
+ - Plan and Normal instructions are append-only conversation contracts, while helper schemas stay stable from startup and visible helpers remain inactive without the latest effective Plan contract.
486
476
  - Unlike native Codex, this extension uses a terminating Pi tool plus an `agent_settled` ready flow; Pi cannot provide sandbox-level enforcement.
487
477
 
488
478
  ## 🗂️ Package layout
@@ -304,240 +304,6 @@ function contentText(content) {
304
304
  }).filter(Boolean).join("\n");
305
305
  }
306
306
 
307
- // src/question-tool.ts
308
- var PLAN_MODE_QUESTION_TOOL_NAME = "plan_mode_question";
309
- var MAX_PLAN_MODE_RESPONSE_LENGTH = 4e3;
310
- var PLAN_MODE_QUESTION_PARAMS = {
311
- type: "object",
312
- additionalProperties: false,
313
- required: ["questions"],
314
- properties: {
315
- questions: {
316
- type: "array",
317
- minItems: 1,
318
- maxItems: 3,
319
- description: "Questions to show the user. Prefer 1 and do not exceed 3.",
320
- items: {
321
- type: "object",
322
- additionalProperties: false,
323
- required: ["id", "header", "question", "options"],
324
- properties: {
325
- id: {
326
- type: "string",
327
- description: "Stable identifier for mapping answers (snake_case)."
328
- },
329
- header: {
330
- type: "string",
331
- description: "Short header label shown in the UI (12 or fewer chars)."
332
- },
333
- question: { type: "string", description: "Single-sentence prompt shown to the user." },
334
- options: {
335
- type: "array",
336
- minItems: 2,
337
- maxItems: 4,
338
- description: "Provide 2-4 mutually exclusive choices. Put the recommended option first when there is a clear default.",
339
- items: {
340
- type: "object",
341
- additionalProperties: false,
342
- required: ["label", "description"],
343
- properties: {
344
- label: { type: "string", description: "User-facing label (1-5 words)." },
345
- description: {
346
- type: "string",
347
- description: "One short sentence explaining impact/tradeoff if selected."
348
- }
349
- }
350
- }
351
- }
352
- }
353
- }
354
- }
355
- }
356
- };
357
- function normalizePlanModeQuestionParams(input) {
358
- if (!isRecord2(input) || !Array.isArray(input.questions)) {
359
- return { ok: false, error: "questions must be an array" };
360
- }
361
- if (input.questions.length < 1 || input.questions.length > 3) {
362
- return { ok: false, error: "questions must contain 1-3 items" };
363
- }
364
- const questions = [];
365
- for (const [questionIndex, rawQuestion] of input.questions.entries()) {
366
- if (!isRecord2(rawQuestion)) {
367
- return { ok: false, error: `question ${questionIndex + 1} must be an object` };
368
- }
369
- const id = stringField(rawQuestion.id);
370
- const header = stringField(rawQuestion.header);
371
- const question = stringField(rawQuestion.question);
372
- if (!id || !header || !question) {
373
- return {
374
- ok: false,
375
- error: `question ${questionIndex + 1} requires non-empty id, header, and question`
376
- };
377
- }
378
- if (!Array.isArray(rawQuestion.options)) {
379
- return { ok: false, error: `question ${questionIndex + 1} options must be an array` };
380
- }
381
- if (rawQuestion.options.length < 2 || rawQuestion.options.length > 4) {
382
- return { ok: false, error: `question ${questionIndex + 1} options must contain 2-4 items` };
383
- }
384
- const options = [];
385
- for (const [optionIndex, rawOption] of rawQuestion.options.entries()) {
386
- if (!isRecord2(rawOption)) {
387
- return {
388
- ok: false,
389
- error: `question ${questionIndex + 1} option ${optionIndex + 1} must be an object`
390
- };
391
- }
392
- const label = stringField(rawOption.label);
393
- if (!label) {
394
- return {
395
- ok: false,
396
- error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a label`
397
- };
398
- }
399
- const description = stringField(rawOption.description);
400
- if (!description) {
401
- return {
402
- ok: false,
403
- error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a description`
404
- };
405
- }
406
- options.push({ label, description });
407
- }
408
- questions.push({ id, header, question, options });
409
- }
410
- return { ok: true, questions };
411
- }
412
- async function answerPlanModeQuestions(questions, ctx, lifecycle) {
413
- const answers = await askPlanModeQuestions(
414
- questions,
415
- ctx,
416
- () => lifecycle.isCurrent() && lifecycle.isEnabled()
417
- );
418
- if (!lifecycle.isCurrent()) {
419
- return planModeQuestionCancelled(
420
- questions,
421
- "cancelled",
422
- "Plan-mode question cancelled because the session changed."
423
- );
424
- }
425
- if (!lifecycle.isEnabled()) {
426
- return planModeQuestionCancelled(
427
- questions,
428
- "plan_mode_inactive",
429
- "Plan-mode question cancelled because Plan mode is no longer active."
430
- );
431
- }
432
- if (!answers) {
433
- return planModeQuestionCancelled(
434
- questions,
435
- "cancelled",
436
- "User cancelled the Plan-mode question prompt."
437
- );
438
- }
439
- return planModeQuestionAnswered(questions, answers);
440
- }
441
- async function askPlanModeQuestions(questions, ctx, shouldContinue = () => true) {
442
- const { runQuestionnaire, sanitizeTerminalText } = await import("@narumitw/pi-tui-kit");
443
- if (!shouldContinue()) return void 0;
444
- const runnerQuestions = questions.map((question, index) => ({
445
- id: String(index),
446
- header: displayText(question.header, `Question ${index + 1}`, sanitizeTerminalText),
447
- prompt: displayText(question.question, `Question ${index + 1}`, sanitizeTerminalText),
448
- options: question.options.map((option, optionIndex) => ({
449
- ...option,
450
- label: displayText(option.label, `Option ${optionIndex + 1}`, sanitizeTerminalText)
451
- }))
452
- }));
453
- const result = await runQuestionnaire(ctx, {
454
- questions: runnerQuestions,
455
- allowNotes: true,
456
- maxTextLength: MAX_PLAN_MODE_RESPONSE_LENGTH,
457
- signal: ctx.signal,
458
- isCurrent: shouldContinue
459
- });
460
- if (!shouldContinue()) return void 0;
461
- return mapQuestionnaireResult(questions, result);
462
- }
463
- function mapQuestionnaireResult(questions, result) {
464
- if (result.kind !== "submitted") return void 0;
465
- if (result.answers.length !== questions.length) {
466
- throw new Error("Questionnaire returned an incomplete answer set");
467
- }
468
- const answers = /* @__PURE__ */ new Map();
469
- for (const answer of result.answers) {
470
- const index = Number(answer.questionId);
471
- if (!Number.isSafeInteger(index) || String(index) !== answer.questionId || !questions[index]) {
472
- throw new Error("Questionnaire returned an answer for an unknown question");
473
- }
474
- if (answers.has(index)) throw new Error("Questionnaire returned duplicate answers");
475
- if (answer.wasCustom) {
476
- if (answer.optionIndex !== void 0) {
477
- throw new Error("Questionnaire returned a custom answer with an option index");
478
- }
479
- if (!answer.answer.trim()) return void 0;
480
- } else if (answer.optionIndex === void 0 || !questions[index]?.options[answer.optionIndex - 1]) {
481
- throw new Error("Questionnaire returned an invalid selected option");
482
- }
483
- answers.set(index, answer);
484
- }
485
- return questions.map((question, index) => {
486
- const answer = answers.get(index);
487
- if (!answer) throw new Error("Questionnaire returned an incomplete answer set");
488
- const answerText = answer.wasCustom ? answer.answer : question.options[(answer.optionIndex ?? 0) - 1]?.label ?? answer.answer;
489
- return answerFor(question, answerText, {
490
- wasCustom: answer.wasCustom,
491
- optionIndex: answer.optionIndex,
492
- note: answer.note
493
- });
494
- });
495
- }
496
- function displayText(value, fallback, sanitize) {
497
- const sanitized = sanitize(value);
498
- return sanitized.trim() ? sanitized : fallback;
499
- }
500
- function answerFor(question, answer, options) {
501
- const result = {
502
- id: question.id,
503
- header: question.header,
504
- question: question.question,
505
- answer,
506
- wasCustom: options.wasCustom
507
- };
508
- if (options.optionIndex !== void 0) result.optionIndex = options.optionIndex;
509
- if (options.note !== void 0) result.note = options.note;
510
- return result;
511
- }
512
- function planModeQuestionAnswered(questions, answers) {
513
- return {
514
- content: [
515
- { type: "text", text: formatPlanModeQuestionPayload({ cancelled: false, answers }) }
516
- ],
517
- details: { cancelled: false, questions, answers }
518
- };
519
- }
520
- function planModeQuestionCancelled(questions, reason, message) {
521
- return {
522
- content: [
523
- {
524
- type: "text",
525
- text: formatPlanModeQuestionPayload({ cancelled: true, reason, message })
526
- }
527
- ],
528
- details: { cancelled: true, reason, questions }
529
- };
530
- }
531
- function formatPlanModeQuestionPayload(payload) {
532
- return JSON.stringify(payload, null, 2);
533
- }
534
- function isRecord2(value) {
535
- return typeof value === "object" && value !== null;
536
- }
537
- function stringField(value) {
538
- return typeof value === "string" ? value.trim() : void 0;
539
- }
540
-
541
307
  // src/implementation-retention.ts
542
308
  function retentionLabel(retention) {
543
309
  return {
@@ -1173,8 +939,6 @@ var IMPLEMENTATION_PLAN_RETENTIONS = [
1173
939
  "clear-after-first-run",
1174
940
  "keep"
1175
941
  ];
1176
- var PLAN_MODE_TOOL_VISIBILITIES = ["always", "after-first-plan"];
1177
- var DEFAULT_PLAN_MODE_TOOL_VISIBILITY = "after-first-plan";
1178
942
  var DEFAULT_PLAN_EXPORT_PATH = "PLAN.md";
1179
943
  var MODIFIERS = /* @__PURE__ */ new Set(["ctrl", "shift", "alt", "super"]);
1180
944
  var BASE_KEYS = /* @__PURE__ */ new Set([
@@ -1247,13 +1011,6 @@ function normalizePlanModeSettings(value) {
1247
1011
  const settings = {
1248
1012
  thinkingLevel
1249
1013
  };
1250
- if (Object.hasOwn(value, "toolVisibility")) {
1251
- const toolVisibility = Reflect.get(value, "toolVisibility");
1252
- if (!PLAN_MODE_TOOL_VISIBILITIES.includes(toolVisibility)) {
1253
- return void 0;
1254
- }
1255
- settings.toolVisibility = toolVisibility;
1256
- }
1257
1014
  if (Object.hasOwn(value, "defaultPlanTools")) {
1258
1015
  const defaultPlanTools = normalizeToolNames(Reflect.get(value, "defaultPlanTools"));
1259
1016
  if (!defaultPlanTools) return void 0;
@@ -1371,7 +1128,6 @@ function updatePlanModeSettings(patch, options = {}) {
1371
1128
  const current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);
1372
1129
  const updated = { ...current };
1373
1130
  if (patch.thinkingLevel !== void 0) updated.thinkingLevel = patch.thinkingLevel;
1374
- if (patch.toolVisibility !== void 0) updated.toolVisibility = patch.toolVisibility;
1375
1131
  if (patch.defaultPlanTools === null) delete updated.defaultPlanTools;
1376
1132
  else if (patch.defaultPlanTools !== void 0) {
1377
1133
  updated.defaultPlanTools = [...patch.defaultPlanTools];
@@ -1530,9 +1286,6 @@ function safeReadError(error) {
1530
1286
  function configuredThinkingLevel(settings) {
1531
1287
  return settings.thinkingLevel === "inherit" ? void 0 : settings.thinkingLevel;
1532
1288
  }
1533
- function configuredPlanModeToolVisibility(settings) {
1534
- return settings.toolVisibility ?? DEFAULT_PLAN_MODE_TOOL_VISIBILITY;
1535
- }
1536
1289
  function configuredImplementationPlanRetention(settings) {
1537
1290
  return settings.implementationPlanRetention ?? "clear-on-start";
1538
1291
  }
@@ -1634,6 +1387,240 @@ function isNodeError2(error) {
1634
1387
  return error instanceof Error && "code" in error;
1635
1388
  }
1636
1389
 
1390
+ // src/question-tool.ts
1391
+ var PLAN_MODE_QUESTION_TOOL_NAME = "plan_mode_question";
1392
+ var MAX_PLAN_MODE_RESPONSE_LENGTH = 4e3;
1393
+ var PLAN_MODE_QUESTION_PARAMS = {
1394
+ type: "object",
1395
+ additionalProperties: false,
1396
+ required: ["questions"],
1397
+ properties: {
1398
+ questions: {
1399
+ type: "array",
1400
+ minItems: 1,
1401
+ maxItems: 3,
1402
+ description: "Questions to show the user. Prefer 1 and do not exceed 3.",
1403
+ items: {
1404
+ type: "object",
1405
+ additionalProperties: false,
1406
+ required: ["id", "header", "question", "options"],
1407
+ properties: {
1408
+ id: {
1409
+ type: "string",
1410
+ description: "Stable identifier for mapping answers (snake_case)."
1411
+ },
1412
+ header: {
1413
+ type: "string",
1414
+ description: "Short header label shown in the UI (12 or fewer chars)."
1415
+ },
1416
+ question: { type: "string", description: "Single-sentence prompt shown to the user." },
1417
+ options: {
1418
+ type: "array",
1419
+ minItems: 2,
1420
+ maxItems: 4,
1421
+ description: "Provide 2-4 mutually exclusive choices. Put the recommended option first when there is a clear default.",
1422
+ items: {
1423
+ type: "object",
1424
+ additionalProperties: false,
1425
+ required: ["label", "description"],
1426
+ properties: {
1427
+ label: { type: "string", description: "User-facing label (1-5 words)." },
1428
+ description: {
1429
+ type: "string",
1430
+ description: "One short sentence explaining impact/tradeoff if selected."
1431
+ }
1432
+ }
1433
+ }
1434
+ }
1435
+ }
1436
+ }
1437
+ }
1438
+ }
1439
+ };
1440
+ function normalizePlanModeQuestionParams(input) {
1441
+ if (!isRecord2(input) || !Array.isArray(input.questions)) {
1442
+ return { ok: false, error: "questions must be an array" };
1443
+ }
1444
+ if (input.questions.length < 1 || input.questions.length > 3) {
1445
+ return { ok: false, error: "questions must contain 1-3 items" };
1446
+ }
1447
+ const questions = [];
1448
+ for (const [questionIndex, rawQuestion] of input.questions.entries()) {
1449
+ if (!isRecord2(rawQuestion)) {
1450
+ return { ok: false, error: `question ${questionIndex + 1} must be an object` };
1451
+ }
1452
+ const id = stringField(rawQuestion.id);
1453
+ const header = stringField(rawQuestion.header);
1454
+ const question = stringField(rawQuestion.question);
1455
+ if (!id || !header || !question) {
1456
+ return {
1457
+ ok: false,
1458
+ error: `question ${questionIndex + 1} requires non-empty id, header, and question`
1459
+ };
1460
+ }
1461
+ if (!Array.isArray(rawQuestion.options)) {
1462
+ return { ok: false, error: `question ${questionIndex + 1} options must be an array` };
1463
+ }
1464
+ if (rawQuestion.options.length < 2 || rawQuestion.options.length > 4) {
1465
+ return { ok: false, error: `question ${questionIndex + 1} options must contain 2-4 items` };
1466
+ }
1467
+ const options = [];
1468
+ for (const [optionIndex, rawOption] of rawQuestion.options.entries()) {
1469
+ if (!isRecord2(rawOption)) {
1470
+ return {
1471
+ ok: false,
1472
+ error: `question ${questionIndex + 1} option ${optionIndex + 1} must be an object`
1473
+ };
1474
+ }
1475
+ const label = stringField(rawOption.label);
1476
+ if (!label) {
1477
+ return {
1478
+ ok: false,
1479
+ error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a label`
1480
+ };
1481
+ }
1482
+ const description = stringField(rawOption.description);
1483
+ if (!description) {
1484
+ return {
1485
+ ok: false,
1486
+ error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a description`
1487
+ };
1488
+ }
1489
+ options.push({ label, description });
1490
+ }
1491
+ questions.push({ id, header, question, options });
1492
+ }
1493
+ return { ok: true, questions };
1494
+ }
1495
+ async function answerPlanModeQuestions(questions, ctx, lifecycle) {
1496
+ const answers = await askPlanModeQuestions(
1497
+ questions,
1498
+ ctx,
1499
+ () => lifecycle.isCurrent() && lifecycle.isEnabled()
1500
+ );
1501
+ if (!lifecycle.isCurrent()) {
1502
+ return planModeQuestionCancelled(
1503
+ questions,
1504
+ "cancelled",
1505
+ "Plan-mode question cancelled because the session changed."
1506
+ );
1507
+ }
1508
+ if (!lifecycle.isEnabled()) {
1509
+ return planModeQuestionCancelled(
1510
+ questions,
1511
+ "plan_mode_inactive",
1512
+ "Plan-mode question cancelled because Plan mode is no longer active."
1513
+ );
1514
+ }
1515
+ if (!answers) {
1516
+ return planModeQuestionCancelled(
1517
+ questions,
1518
+ "cancelled",
1519
+ "User cancelled the Plan-mode question prompt."
1520
+ );
1521
+ }
1522
+ return planModeQuestionAnswered(questions, answers);
1523
+ }
1524
+ async function askPlanModeQuestions(questions, ctx, shouldContinue = () => true) {
1525
+ const { runQuestionnaire, sanitizeTerminalText } = await import("@narumitw/pi-tui-kit");
1526
+ if (!shouldContinue()) return void 0;
1527
+ const runnerQuestions = questions.map((question, index) => ({
1528
+ id: String(index),
1529
+ header: displayText(question.header, `Question ${index + 1}`, sanitizeTerminalText),
1530
+ prompt: displayText(question.question, `Question ${index + 1}`, sanitizeTerminalText),
1531
+ options: question.options.map((option, optionIndex) => ({
1532
+ ...option,
1533
+ label: displayText(option.label, `Option ${optionIndex + 1}`, sanitizeTerminalText)
1534
+ }))
1535
+ }));
1536
+ const result = await runQuestionnaire(ctx, {
1537
+ questions: runnerQuestions,
1538
+ allowNotes: true,
1539
+ maxTextLength: MAX_PLAN_MODE_RESPONSE_LENGTH,
1540
+ signal: ctx.signal,
1541
+ isCurrent: shouldContinue
1542
+ });
1543
+ if (!shouldContinue()) return void 0;
1544
+ return mapQuestionnaireResult(questions, result);
1545
+ }
1546
+ function mapQuestionnaireResult(questions, result) {
1547
+ if (result.kind !== "submitted") return void 0;
1548
+ if (result.answers.length !== questions.length) {
1549
+ throw new Error("Questionnaire returned an incomplete answer set");
1550
+ }
1551
+ const answers = /* @__PURE__ */ new Map();
1552
+ for (const answer of result.answers) {
1553
+ const index = Number(answer.questionId);
1554
+ if (!Number.isSafeInteger(index) || String(index) !== answer.questionId || !questions[index]) {
1555
+ throw new Error("Questionnaire returned an answer for an unknown question");
1556
+ }
1557
+ if (answers.has(index)) throw new Error("Questionnaire returned duplicate answers");
1558
+ if (answer.wasCustom) {
1559
+ if (answer.optionIndex !== void 0) {
1560
+ throw new Error("Questionnaire returned a custom answer with an option index");
1561
+ }
1562
+ if (!answer.answer.trim()) return void 0;
1563
+ } else if (answer.optionIndex === void 0 || !questions[index]?.options[answer.optionIndex - 1]) {
1564
+ throw new Error("Questionnaire returned an invalid selected option");
1565
+ }
1566
+ answers.set(index, answer);
1567
+ }
1568
+ return questions.map((question, index) => {
1569
+ const answer = answers.get(index);
1570
+ if (!answer) throw new Error("Questionnaire returned an incomplete answer set");
1571
+ const answerText = answer.wasCustom ? answer.answer : question.options[(answer.optionIndex ?? 0) - 1]?.label ?? answer.answer;
1572
+ return answerFor(question, answerText, {
1573
+ wasCustom: answer.wasCustom,
1574
+ optionIndex: answer.optionIndex,
1575
+ note: answer.note
1576
+ });
1577
+ });
1578
+ }
1579
+ function displayText(value, fallback, sanitize) {
1580
+ const sanitized = sanitize(value);
1581
+ return sanitized.trim() ? sanitized : fallback;
1582
+ }
1583
+ function answerFor(question, answer, options) {
1584
+ const result = {
1585
+ id: question.id,
1586
+ header: question.header,
1587
+ question: question.question,
1588
+ answer,
1589
+ wasCustom: options.wasCustom
1590
+ };
1591
+ if (options.optionIndex !== void 0) result.optionIndex = options.optionIndex;
1592
+ if (options.note !== void 0) result.note = options.note;
1593
+ return result;
1594
+ }
1595
+ function planModeQuestionAnswered(questions, answers) {
1596
+ return {
1597
+ content: [
1598
+ { type: "text", text: formatPlanModeQuestionPayload({ cancelled: false, answers }) }
1599
+ ],
1600
+ details: { cancelled: false, questions, answers }
1601
+ };
1602
+ }
1603
+ function planModeQuestionCancelled(questions, reason, message) {
1604
+ return {
1605
+ content: [
1606
+ {
1607
+ type: "text",
1608
+ text: formatPlanModeQuestionPayload({ cancelled: true, reason, message })
1609
+ }
1610
+ ],
1611
+ details: { cancelled: true, reason, questions }
1612
+ };
1613
+ }
1614
+ function formatPlanModeQuestionPayload(payload) {
1615
+ return JSON.stringify(payload, null, 2);
1616
+ }
1617
+ function isRecord2(value) {
1618
+ return typeof value === "object" && value !== null;
1619
+ }
1620
+ function stringField(value) {
1621
+ return typeof value === "string" ? value.trim() : void 0;
1622
+ }
1623
+
1637
1624
  // src/tool-selection.ts
1638
1625
  function toolNameFromLegacyKey(key, tools) {
1639
1626
  const directName = tools.find((tool) => tool.name === key)?.name;
@@ -1692,11 +1679,6 @@ export {
1692
1679
  latestAssistantText,
1693
1680
  latestAssistantStopReason,
1694
1681
  messageTextContent,
1695
- PLAN_MODE_QUESTION_TOOL_NAME,
1696
- PLAN_MODE_QUESTION_PARAMS,
1697
- normalizePlanModeQuestionParams,
1698
- answerPlanModeQuestions,
1699
- planModeQuestionCancelled,
1700
1682
  retentionLabel,
1701
1683
  implementationRetentionPreview,
1702
1684
  createImplementationRetentionCoordinator,
@@ -1707,19 +1689,22 @@ export {
1707
1689
  findBlockedPowerShellCommandSegment,
1708
1690
  PLAN_MODE_THINKING_LEVELS,
1709
1691
  IMPLEMENTATION_PLAN_RETENTIONS,
1710
- PLAN_MODE_TOOL_VISIBILITIES,
1711
1692
  planModeSettingsPath,
1712
1693
  normalizeKeyId,
1713
1694
  readPlanModeSettings,
1714
1695
  updatePlanModeSettings,
1715
1696
  awaitPlanModeSettingsWrites,
1716
1697
  configuredThinkingLevel,
1717
- configuredPlanModeToolVisibility,
1718
1698
  configuredImplementationPlanRetention,
1719
1699
  configuredPlanExportPath,
1720
1700
  configuredPlanModeToggleShortcut,
1721
1701
  exportStoredPlan,
1722
1702
  planExportDestination,
1703
+ PLAN_MODE_QUESTION_TOOL_NAME,
1704
+ PLAN_MODE_QUESTION_PARAMS,
1705
+ normalizePlanModeQuestionParams,
1706
+ answerPlanModeQuestions,
1707
+ planModeQuestionCancelled,
1723
1708
  compareTools,
1724
1709
  toolPolicyLabel,
1725
1710
  unique,
@@ -1727,4 +1712,4 @@ export {
1727
1712
  defaultPlanModeToolNames,
1728
1713
  snapshotPlanModeSelectedNames
1729
1714
  };
1730
- //# sourceMappingURL=chunk-U5CQ7RQX.js.map
1715
+ //# sourceMappingURL=chunk-KSGLZ4S2.js.map