@gajae-code/coding-agent 0.21.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/types/config/autorouting-contract.d.ts +4 -4
  3. package/dist/types/config/autorouting-tier-map.d.ts +1 -1
  4. package/dist/types/config/keybindings.d.ts +1 -5
  5. package/dist/types/config/model-profile-activation.d.ts +30 -3
  6. package/dist/types/config/model-registry.d.ts +2 -0
  7. package/dist/types/config/models-config-schema.d.ts +8 -0
  8. package/dist/types/config/settings-schema.d.ts +7 -3
  9. package/dist/types/coordinator-mcp/canonical-json.d.ts +7 -0
  10. package/dist/types/extensibility/gjc-plugins/metadata.d.ts +1 -1
  11. package/dist/types/harness-control-plane/receipts.d.ts +1 -1
  12. package/dist/types/modes/components/settings-selector.d.ts +5 -2
  13. package/dist/types/modes/controllers/command-controller.d.ts +1 -1
  14. package/dist/types/modes/controllers/input-controller.d.ts +12 -0
  15. package/dist/types/modes/controllers/selector-controller.d.ts +1 -1
  16. package/dist/types/modes/interactive-mode.d.ts +1 -1
  17. package/dist/types/modes/shared/agent-wire/workflow-gate-schema.d.ts +1 -1
  18. package/dist/types/modes/types.d.ts +1 -1
  19. package/dist/types/session/agent-session.d.ts +101 -6
  20. package/dist/types/session/session-manager.d.ts +124 -9
  21. package/dist/types/setup/provider-onboarding.d.ts +55 -2
  22. package/dist/types/slash-commands/builtin-registry.d.ts +11 -0
  23. package/dist/types/utils/clipboard.d.ts +18 -0
  24. package/dist/types/utils/pasted-image-path.d.ts +2 -0
  25. package/dist/types/web/search/providers/keenable.d.ts +30 -0
  26. package/dist/types/web/search/types.d.ts +2 -2
  27. package/package.json +7 -7
  28. package/scripts/generate-sdk-operation-inventory.ts +28 -0
  29. package/src/cli/doctor/config-repairs.ts +1 -4
  30. package/src/cli/local-provider-smoke.ts +1 -4
  31. package/src/cli/public-command-help.ts +1 -1
  32. package/src/config/autorouting-contract.ts +5 -8
  33. package/src/config/autorouting-tier-map.ts +1 -1
  34. package/src/config/keybindings.ts +1 -2
  35. package/src/config/model-profile-activation.ts +332 -28
  36. package/src/config/model-registry.ts +156 -8
  37. package/src/config/models-config-schema.ts +27 -0
  38. package/src/config/settings-schema.ts +6 -0
  39. package/src/coordinator-mcp/canonical-json.ts +15 -0
  40. package/src/coordinator-mcp/policy.ts +1 -0
  41. package/src/coordinator-mcp/question-gate-codec.ts +1 -2
  42. package/src/coordinator-mcp/question-state.ts +2 -12
  43. package/src/coordinator-mcp/server.ts +1 -10
  44. package/src/customization/import.ts +1 -5
  45. package/src/discovery/mcp-compat.ts +1 -5
  46. package/src/discovery/mcp-json.ts +1 -4
  47. package/src/edit/notebook.ts +1 -5
  48. package/src/extensibility/gjc-plugins/lifecycle.ts +1 -3
  49. package/src/extensibility/gjc-plugins/metadata.ts +2 -5
  50. package/src/extensibility/gjc-plugins/schema.ts +1 -4
  51. package/src/gjc-runtime/deep-interview-crystallize.ts +1 -4
  52. package/src/gjc-runtime/deep-interview-runtime.ts +1 -4
  53. package/src/gjc-runtime/state-renderer.ts +1 -5
  54. package/src/gjc-runtime/tmux-owner-isolation.ts +1 -3
  55. package/src/gjc-runtime/ultragoal-owner-loss-recovery.ts +1 -4
  56. package/src/gjc-runtime/ultragoal-succession.ts +1 -4
  57. package/src/goals/continuation-timeout-guard.ts +1 -4
  58. package/src/harness-control-plane/receipts.ts +1 -1
  59. package/src/internal-urls/docs-index.generated.ts +4 -4
  60. package/src/migrate/mcp-mapper.ts +2 -4
  61. package/src/modes/components/hook-editor.ts +4 -8
  62. package/src/modes/components/hook-selector.ts +3 -1
  63. package/src/modes/components/settings-selector.ts +26 -2
  64. package/src/modes/controllers/command-controller.ts +4 -98
  65. package/src/modes/controllers/extension-ui-controller.ts +6 -14
  66. package/src/modes/controllers/goal-mode-controller.ts +4 -4
  67. package/src/modes/controllers/input-controller.ts +110 -46
  68. package/src/modes/controllers/plan-mode-controller.ts +6 -10
  69. package/src/modes/controllers/selector-controller.ts +66 -23
  70. package/src/modes/controllers/todo-command-controller.ts +2 -2
  71. package/src/modes/interactive-mode.ts +2 -2
  72. package/src/modes/prompt-action-autocomplete.ts +1 -1
  73. package/src/modes/runtime-init.ts +4 -4
  74. package/src/modes/shared/agent-wire/workflow-gate-schema.ts +1 -1
  75. package/src/modes/types.ts +1 -1
  76. package/src/modes/utils/hotkeys-markdown.ts +1 -1
  77. package/src/runtime-mcp/client.ts +1 -4
  78. package/src/runtime-mcp/elicitation.ts +1 -5
  79. package/src/runtime-mcp/protocol.ts +2 -4
  80. package/src/sdk/broker/lifecycle-ledger.ts +1 -0
  81. package/src/sdk/broker/lifecycle.ts +1 -0
  82. package/src/sdk/cli/rows.ts +2 -3
  83. package/src/sdk/cli/session-cli.ts +2 -8
  84. package/src/sdk/host/query/cursor.ts +1 -0
  85. package/src/sdk/host/reverse-leases.ts +1 -0
  86. package/src/sdk/lifecycle/service.ts +1 -0
  87. package/src/sdk/protocol/operation-inventory.generated.json +154 -0
  88. package/src/session/agent-session.ts +1877 -224
  89. package/src/session/btw-prefix-ledger.ts +1 -4
  90. package/src/session/internal/managed-gc-retirement-codec.ts +1 -4
  91. package/src/session/session-manager.ts +732 -224
  92. package/src/session/task-artifact-owner-codec.ts +1 -4
  93. package/src/session-import/claude.ts +1 -4
  94. package/src/session-import/detect.ts +1 -6
  95. package/src/session-import/provider-codex.ts +1 -6
  96. package/src/session-import/provider-service.ts +4 -0
  97. package/src/setup/hermes-setup.ts +1 -4
  98. package/src/setup/provider-onboarding.ts +514 -26
  99. package/src/slash-commands/builtin-registry.ts +26 -13
  100. package/src/slash-commands/helpers/todo.ts +3 -1
  101. package/src/task/delegation-hint.ts +1 -4
  102. package/src/task/executor.ts +4 -2
  103. package/src/task/provider-retry-status.ts +1 -4
  104. package/src/tools/json-tree.ts +1 -4
  105. package/src/tools/recipe/runners/pkg.ts +1 -5
  106. package/src/utils/clipboard.ts +155 -2
  107. package/src/utils/mac-file-urls.applescript +37 -0
  108. package/src/utils/pasted-image-path.ts +5 -0
  109. package/src/web/search/provider.ts +6 -0
  110. package/src/web/search/providers/keenable.ts +207 -0
  111. package/src/web/search/types.ts +2 -0
@@ -6,6 +6,8 @@
6
6
  * `skipped_unmappable`), and failed (F, `failed_invalid_source`). Secret-indirection
7
7
  * fields are always omitted-with-warning; their values are never read or emitted.
8
8
  */
9
+
10
+ import { isRecord } from "@gajae-code/utils";
9
11
  import type { MCPServerConfig } from "../runtime-mcp/types";
10
12
  import type { MigrateSource } from "./types";
11
13
 
@@ -13,10 +15,6 @@ export type McpMapOutcome =
13
15
  | { ok: true; config: MCPServerConfig; warnings: string[] }
14
16
  | { ok: false; status: "skipped_unmappable" | "failed_invalid_source"; reason: string };
15
17
 
16
- function isRecord(value: unknown): value is Record<string, unknown> {
17
- return typeof value === "object" && value !== null && !Array.isArray(value);
18
- }
19
-
20
18
  function asStringArray(value: unknown): string[] | undefined | "invalid" {
21
19
  if (value === undefined) return undefined;
22
20
  if (!Array.isArray(value) || !value.every(v => typeof v === "string")) return "invalid";
@@ -6,7 +6,7 @@
6
6
  * - Default (hook): Enter inserts newline, Ctrl+Enter submits, bordered popup
7
7
  * - Prompt-style (ask): Enter submits, Shift+Enter inserts newline, legacy ask chrome
8
8
  */
9
- import { Container, Editor, matchesKey, Spacer, Text, type TUI } from "@gajae-code/tui";
9
+ import { Container, Editor, isBareLineFeed, matchesKey, Spacer, Text, type TUI } from "@gajae-code/tui";
10
10
  import { getEditorTheme, theme } from "../../modes/theme/theme";
11
11
  import { matchesAppExternalEditor, matchesAppInterrupt } from "../../modes/utils/keybinding-matchers";
12
12
  import { getEditorCommand, openInEditor } from "../../utils/external-editor";
@@ -17,10 +17,6 @@ export interface HookEditorOptions {
17
17
  promptStyle?: boolean;
18
18
  }
19
19
 
20
- function isWindowsRawLfNewlineInput(keyData: string): boolean {
21
- return process.platform === "win32" && keyData === "\n";
22
- }
23
-
24
20
  export class HookEditorComponent extends Container {
25
21
  #editor: Editor;
26
22
  #onSubmitCallback: (value: string) => void;
@@ -96,10 +92,10 @@ export class HookEditorComponent extends Container {
96
92
  return;
97
93
  }
98
94
 
99
- // Submit on Enter and Ctrl+Enter encodings. On Windows, raw LF is reserved for
100
- // terminal newline mappings (Shift+Enter/Ctrl+J); plain Enter reports CR.
95
+ // Submit on Enter and Ctrl+Enter encodings. A bare LF is the newline chord
96
+ // (Ctrl+J, Shift+Enter→LF terminal mappings), as in the main composer.
101
97
  if (
102
- !isWindowsRawLfNewlineInput(keyData) &&
98
+ !isBareLineFeed(keyData) &&
103
99
  (matchesKey(keyData, "enter") || matchesKey(keyData, "return") || matchesKey(keyData, "ctrl+enter"))
104
100
  ) {
105
101
  this.#onSubmitCallback(this.#editor.getText());
@@ -6,6 +6,7 @@ import {
6
6
  type AutocompleteProvider,
7
7
  Container,
8
8
  Editor,
9
+ isBareLineFeed,
9
10
  Markdown,
10
11
  matchesKey,
11
12
  padding,
@@ -663,7 +664,8 @@ export class HookSelectorComponent extends Container {
663
664
  void this.#openExternalEditor(editor);
664
665
  return;
665
666
  }
666
- if (matchesKey(keyData, "enter") || matchesKey(keyData, "return")) {
667
+ // A bare LF is the newline chord (Ctrl+J, Shift+Enter→LF terminal mappings).
668
+ if (!isBareLineFeed(keyData) && (matchesKey(keyData, "enter") || matchesKey(keyData, "return"))) {
667
669
  const text = editor.getExpandedText();
668
670
  if (this.#activeInput?.allowEmpty === false && text.trim() === "") {
669
671
  return;
@@ -1522,8 +1522,11 @@ export interface StatusLinePreviewSettings {
1522
1522
  }
1523
1523
 
1524
1524
  export interface SettingsCallbacks {
1525
- /** Called when any setting value changes */
1526
- onChange: (path: SettingPath, newValue: unknown) => void;
1525
+ /**
1526
+ * Called when any setting value changes. A returned promise means the change is
1527
+ * committed by a session-owned control; session-owned settings await it.
1528
+ */
1529
+ onChange: (path: SettingPath, newValue: unknown) => unknown;
1527
1530
  /** Called for theme preview while browsing theme settings */
1528
1531
  onThemePreview?: (theme: string) => void | Promise<void>;
1529
1532
  /** Called to restore the rendered theme when theme settings preview is cancelled */
@@ -1965,6 +1968,7 @@ export class SettingsSelectorComponent extends Container {
1965
1968
  const getPreview = isThemeSetting ? this.callbacks.getStatusLinePreview : undefined;
1966
1969
 
1967
1970
  let submenu: SelectSubmenu;
1971
+ let thinkingCommitPending = false;
1968
1972
  const finish = (value?: string): void => {
1969
1973
  if (this.#activeSelectSubmenu === submenu) this.#activeSelectSubmenu = null;
1970
1974
  if (this.#activeModelProfileSubmenu === submenu) this.#activeModelProfileSubmenu = null;
@@ -1978,6 +1982,26 @@ export class SettingsSelectorComponent extends Container {
1978
1982
  options,
1979
1983
  currentValue,
1980
1984
  value => {
1985
+ if (def.path === "defaultThinkingLevel") {
1986
+ if (thinkingCommitPending) return;
1987
+ thinkingCommitPending = true;
1988
+ // The session control owns admission, persistence, and publication.
1989
+ // Keep the draft open until that transaction has succeeded.
1990
+ void (async () => {
1991
+ try {
1992
+ await this.callbacks.onChange(def.path, value);
1993
+ } catch (error) {
1994
+ this.callbacks.onError?.(error instanceof Error ? error.message : String(error));
1995
+ return;
1996
+ } finally {
1997
+ thinkingCommitPending = false;
1998
+ }
1999
+ if (this.#activeSelectSubmenu !== submenu) return;
2000
+ finish(value);
2001
+ this.callbacks.onRenderRequested?.();
2002
+ })();
2003
+ return;
2004
+ }
1981
2005
  if (def.path === "modelProfile.default") {
1982
2006
  this.callbacks.onChange(def.path, value);
1983
2007
  finish(value);
@@ -2,13 +2,7 @@ import * as fs from "node:fs/promises";
2
2
  import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import { CompactionCancelledError, type CompactionOutcome } from "@gajae-code/agent-core/compaction";
5
- import {
6
- collapseUsageLimitsForDisplay,
7
- getEnvApiKey,
8
- type ToolCall,
9
- type UsageLimit,
10
- type UsageReport,
11
- } from "@gajae-code/ai/core";
5
+ import { collapseUsageLimitsForDisplay, getEnvApiKey, type UsageLimit, type UsageReport } from "@gajae-code/ai/core";
12
6
  import type { ProviderDetails } from "@gajae-code/ai/provider-details";
13
7
  import { type Keybinding, Loader, Markdown, padding, Spacer, Text, visibleWidth } from "@gajae-code/tui";
14
8
  import { formatBytes, formatDuration, sanitizeDisplayLine, setProjectDir } from "@gajae-code/utils";
@@ -620,23 +614,7 @@ export class CommandController {
620
614
  }
621
615
  }
622
616
 
623
- handleCopyCommand(sub?: string) {
624
- switch (sub) {
625
- case "code":
626
- return this.#copyCode();
627
- case "all":
628
- return this.#copyAllCode();
629
- case "cmd":
630
- return this.#copyLastCommand();
631
- case "last":
632
- case undefined:
633
- return this.#copyLastMessage();
634
- default:
635
- this.ctx.showError(`Unknown subcommand: ${sub}. Use code, all, cmd, or last.`);
636
- }
637
- }
638
-
639
- #copyLastMessage() {
617
+ handleCopyCommand() {
640
618
  const assistantText = this.ctx.session.getLastAssistantText();
641
619
  if (assistantText) {
642
620
  this.#doCopy(assistantText, "Copied last agent message to clipboard");
@@ -654,78 +632,6 @@ export class CommandController {
654
632
  this.ctx.showError("No agent messages to copy yet.");
655
633
  }
656
634
 
657
- #copyCode() {
658
- const text = this.ctx.session.getLastAssistantText();
659
- if (!text) {
660
- this.ctx.showError("No agent messages to copy yet.");
661
- return;
662
- }
663
- const matches = [...text.matchAll(/^```[^\n]*\n([\s\S]*?)^```/gm)];
664
- const lastMatch = matches.at(-1);
665
- if (!lastMatch) {
666
- this.ctx.showWarning("No code block found in the last agent message.");
667
- return;
668
- }
669
- this.#doCopy(lastMatch[1].replace(/\n$/, ""), "Copied last code block to clipboard");
670
- }
671
-
672
- #copyAllCode() {
673
- const text = this.ctx.session.getLastAssistantText();
674
- if (!text) {
675
- this.ctx.showError("No agent messages to copy yet.");
676
- return;
677
- }
678
- const matches = [...text.matchAll(/^```[^\n]*\n([\s\S]*?)^```/gm)];
679
- if (matches.length === 0) {
680
- this.ctx.showWarning("No code blocks found in the last agent message.");
681
- return;
682
- }
683
- const combined = matches.map(m => m[1].replace(/\n$/, "")).join("\n\n");
684
- this.#doCopy(combined, `Copied ${matches.length} code block${matches.length > 1 ? "s" : ""} to clipboard`);
685
- }
686
-
687
- #extractEvalCode(args: unknown): string | undefined {
688
- if (!args || typeof args !== "object") return undefined;
689
- const cells = (args as { cells?: unknown }).cells;
690
- if (!Array.isArray(cells)) return undefined;
691
-
692
- const codeBlocks: string[] = [];
693
- for (const cell of cells) {
694
- if (!cell || typeof cell !== "object") continue;
695
- const code = (cell as { code?: unknown }).code;
696
- if (typeof code === "string" && code.length > 0) {
697
- codeBlocks.push(code);
698
- }
699
- }
700
-
701
- return codeBlocks.length > 0 ? codeBlocks.join("\n\n") : undefined;
702
- }
703
-
704
- #copyLastCommand() {
705
- const messages = this.ctx.session.messages;
706
- // Walk backwards to find the last bash/eval tool call
707
- for (let i = messages.length - 1; i >= 0; i--) {
708
- const msg = messages[i];
709
- if (msg.role !== "assistant") continue;
710
- const toolCalls = msg.content.filter((c): c is ToolCall => c.type === "toolCall");
711
- for (let j = toolCalls.length - 1; j >= 0; j--) {
712
- const tc = toolCalls[j];
713
- if (tc.name === "bash" && typeof tc.arguments?.command === "string") {
714
- this.#doCopy(tc.arguments.command, "Copied last bash command to clipboard");
715
- return;
716
- }
717
- if (tc.name === "eval") {
718
- const code = this.#extractEvalCode(tc.arguments);
719
- if (code) {
720
- this.#doCopy(code, "Copied last eval code to clipboard");
721
- return;
722
- }
723
- }
724
- }
725
- }
726
- this.ctx.showWarning("No bash or eval command found in the conversation.");
727
- }
728
-
729
635
  #doCopy(content: string, label: string) {
730
636
  copyToClipboard(content).then(
731
637
  () => this.ctx.showStatus(label),
@@ -1502,7 +1408,7 @@ export class CommandController {
1502
1408
  return;
1503
1409
  }
1504
1410
 
1505
- const stored = await this.ctx.sessionManager.setSessionName(generated, "user");
1411
+ const stored = await this.ctx.session.setSessionName(generated, "user");
1506
1412
  if (!stored) {
1507
1413
  this.ctx.showError("Session name cannot be empty.");
1508
1414
  return;
@@ -1512,7 +1418,7 @@ export class CommandController {
1512
1418
  }
1513
1419
 
1514
1420
  invalidateSessionTitleGeneration(this.ctx.sessionManager);
1515
- const stored = await this.ctx.sessionManager.setSessionName(title, "user");
1421
+ const stored = await this.ctx.session.setSessionName(title, "user");
1516
1422
  if (!stored) {
1517
1423
  this.ctx.showError("Session name cannot be empty.");
1518
1424
  return;
@@ -437,7 +437,7 @@ export class ExtensionUiController {
437
437
  await session.reload();
438
438
  return { reloaded: true };
439
439
  case "service_tier.set":
440
- session.setServiceTier(input.tier as never);
440
+ await session.setServiceTier(input.tier as never);
441
441
  return { changed: true };
442
442
  case "queue.message.remove": {
443
443
  const removed = session.removeQueuedMessageForEditing(String(input.id));
@@ -620,12 +620,8 @@ export class ExtensionUiController {
620
620
  });
621
621
  },
622
622
  sendUserMessage: this.#sendExtensionUserMessage,
623
- appendEntry: (customType, data) => {
624
- this.ctx.sessionManager.appendCustomEntry(customType, data);
625
- },
626
- setLabel: (targetId, label) => {
627
- this.ctx.sessionManager.appendLabelChange(targetId, label);
628
- },
623
+ appendEntry: (customType, data) => this.ctx.session.appendCustomEntryInBackground(customType, data),
624
+ setLabel: (targetId, label) => this.ctx.session.appendLabelChangeInBackground(targetId, label),
629
625
  getActiveTools: () => this.ctx.session.getActiveToolNames(),
630
626
  getAllTools: () => this.ctx.session.getAllToolNames(),
631
627
  resolveTool: name => {
@@ -865,12 +861,8 @@ export class ExtensionUiController {
865
861
  });
866
862
  },
867
863
  sendUserMessage: this.#sendExtensionUserMessage,
868
- appendEntry: (customType, data) => {
869
- this.ctx.sessionManager.appendCustomEntry(customType, data);
870
- },
871
- setLabel: (targetId, label) => {
872
- this.ctx.sessionManager.appendLabelChange(targetId, label);
873
- },
864
+ appendEntry: (customType, data) => this.ctx.session.appendCustomEntryInBackground(customType, data),
865
+ setLabel: (targetId, label) => this.ctx.session.appendLabelChangeInBackground(targetId, label),
874
866
  getActiveTools: () => this.ctx.session.getActiveToolNames(),
875
867
  getAllTools: () => this.ctx.session.getAllToolNames(),
876
868
  resolveTool: name => {
@@ -1622,7 +1614,7 @@ export class ExtensionUiController {
1622
1614
  }
1623
1615
 
1624
1616
  async #updateSessionName(name: string): Promise<void> {
1625
- await this.ctx.sessionManager.setSessionName(name, "user");
1617
+ await this.ctx.session.setSessionName(name, "user");
1626
1618
  setSessionTerminalTitle(this.ctx.sessionManager.getSessionName(), this.ctx.sessionManager.getCwd());
1627
1619
  }
1628
1620
 
@@ -277,14 +277,14 @@ export class GoalModeController {
277
277
  const goalEnabled = this.ctx.session.settings.get("goal.enabled");
278
278
  if (!goalEnabled && (sessionContext.mode === "goal" || sessionContext.mode === "goal_paused")) {
279
279
  if (recoveryHydration) return false;
280
- this.ctx.sessionManager.appendModeChange("none");
280
+ this.ctx.session.appendModeChangeInBackground("none");
281
281
  return true;
282
282
  }
283
283
  if (sessionContext.mode === "goal" || sessionContext.mode === "goal_paused") {
284
284
  const goal = normalizeGoal(sessionContext.modeData?.goal) ?? undefined;
285
285
  if (!goal) {
286
286
  if (recoveryHydration) throw new Error("Recovery hydration rejected an invalid persisted goal state.");
287
- this.ctx.sessionManager.appendModeChange("none");
287
+ this.ctx.session.appendModeChangeInBackground("none");
288
288
  return true;
289
289
  }
290
290
  this.ctx.session.setGoalModeState({ enabled: sessionContext.mode === "goal", mode: "active", goal });
@@ -442,8 +442,8 @@ export class GoalModeController {
442
442
  const currentState = this.ctx.session.getGoalModeState();
443
443
  if (options?.reason === "completed") {
444
444
  this.ctx.session.setGoalModeState(undefined);
445
- this.ctx.sessionManager.appendModeChange("none");
446
- this.ctx.sessionManager.appendCustomEntry("goal-completed", {
445
+ this.ctx.session.appendModeChangeInBackground("none");
446
+ this.ctx.session.appendCustomEntryInBackground("goal-completed", {
447
447
  objective: currentState?.goal?.objective,
448
448
  tokensUsed: currentState?.goal?.tokensUsed,
449
449
  timeUsedSeconds: currentState?.goal?.timeUsedSeconds,
@@ -1,6 +1,7 @@
1
1
  import * as fs from "node:fs/promises";
2
2
  import * as path from "node:path";
3
3
  import { type AgentMessage, ThinkingLevel } from "@gajae-code/agent-core";
4
+ import type { ClipboardImage } from "@gajae-code/natives";
4
5
  import { type AutocompleteProvider, getKeybindings, matchesKey, type SlashCommand } from "@gajae-code/tui";
5
6
  import { $pickenv, logger, sanitizeText } from "@gajae-code/utils";
6
7
  import { type AppKeybinding, KEYBINDINGS } from "../../config/keybindings";
@@ -22,7 +23,13 @@ import type { AgentSessionEvent, QueuedMessageEditEntry } from "../../session/ag
22
23
  import { SKILL_PROMPT_MESSAGE_TYPE, type SkillPromptDetails } from "../../session/messages";
23
24
  import { getUserMessageViewportAnchorIds } from "../../session/session-manager";
24
25
  import { executeBuiltinSlashCommand } from "../../slash-commands/builtin-registry";
25
- import { copyToClipboard, pasteFromClipboard, readImageFromClipboard } from "../../utils/clipboard";
26
+ import {
27
+ copyToClipboard,
28
+ pasteFromClipboard,
29
+ readImageFromClipboard,
30
+ readMacFileUrlsFromClipboard,
31
+ readTextFromClipboard,
32
+ } from "../../utils/clipboard";
26
33
  import { getEditorCommand, openInEditor } from "../../utils/external-editor";
27
34
  import { ensureSupportedImageInput, ImageInputTooLargeError } from "../../utils/image-loading";
28
35
  import { resizeImage } from "../../utils/image-resize";
@@ -30,6 +37,7 @@ import { loadPastedImageBatch, PastedImageBatchError } from "../../utils/pasted-
30
37
  import {
31
38
  decodePastedPathCandidate,
32
39
  formatPastedImageReference,
40
+ imageFilePathsFromList,
33
41
  imageReferenceNumbers,
34
42
  locatePastedImageReferenceAroundCursor,
35
43
  parsePastedImagePaths,
@@ -85,8 +93,15 @@ function isItermPetDragPaste(text: string): boolean {
85
93
  return ITERM_PET_DRAG_PATH_PATTERN.test(decodePastedPathCandidate(text) ?? "");
86
94
  }
87
95
 
96
+ interface ClipboardReaders {
97
+ readImage: typeof readImageFromClipboard;
98
+ readText: typeof readTextFromClipboard;
99
+ readMacFileUrls: typeof readMacFileUrlsFromClipboard;
100
+ }
101
+
88
102
  interface InputControllerDependencies {
89
103
  loadPastedImageBatch?: typeof loadPastedImageBatch;
104
+ clipboard?: Partial<ClipboardReaders>;
90
105
  }
91
106
 
92
107
  function isExpandable(obj: unknown): obj is Expandable {
@@ -96,6 +111,7 @@ function isExpandable(obj: unknown): obj is Expandable {
96
111
  export class InputController {
97
112
  readonly actionRegistry: ActionRegistry<void>;
98
113
  readonly #loadPastedImageBatch: typeof loadPastedImageBatch;
114
+ readonly #clipboard: ClipboardReaders;
99
115
  /** Session id with an automatic-title request pending, if any. */
100
116
  #autoTitleInFlightSessionId: string | undefined;
101
117
  #deferredSubmission?: {
@@ -114,6 +130,12 @@ export class InputController {
114
130
  dependencies: InputControllerDependencies = {},
115
131
  ) {
116
132
  this.#loadPastedImageBatch = dependencies.loadPastedImageBatch ?? loadPastedImageBatch;
133
+ this.#clipboard = {
134
+ readImage: readImageFromClipboard,
135
+ readText: readTextFromClipboard,
136
+ readMacFileUrls: readMacFileUrlsFromClipboard,
137
+ ...dependencies.clipboard,
138
+ };
117
139
  this.actionRegistry = new ActionRegistry({
118
140
  context: undefined,
119
141
  showError: actionId => this.ctx.showError(actionId),
@@ -1660,7 +1682,7 @@ export class InputController {
1660
1682
  )
1661
1683
  .then(async title => {
1662
1684
  if (!title || this.ctx.sessionManager.getSessionId() !== sessionId) return;
1663
- const applied = await this.ctx.sessionManager.setSessionName(title, "auto");
1685
+ const applied = await this.ctx.session.setSessionName(title, "auto");
1664
1686
  if (applied) {
1665
1687
  setSessionTerminalTitle(this.ctx.sessionManager.getSessionName()!, this.ctx.sessionManager.getCwd());
1666
1688
  this.ctx.updateEditorBorderColor();
@@ -1992,19 +2014,32 @@ export class InputController {
1992
2014
  return true;
1993
2015
  }
1994
2016
  if (this.ctx.isBashMode || this.ctx.isPythonMode) return false;
2017
+ // Cmd+V on an image-only clipboard arrives as an empty bracketed paste in some
2018
+ // terminals: read the image from the clipboard instead of inserting nothing.
2019
+ if (text.length === 0) return this.handleImagePaste();
1995
2020
  const parsed = parsePastedImagePaths(text, { cwd: this.ctx.sessionManager.getCwd() });
1996
2021
  if (!parsed) return false;
1997
2022
  if (parsed.kind === "too-many") {
1998
2023
  this.ctx.showStatus(`Cannot attach more than ${parsed.maxCandidates} pasted images.`);
1999
2024
  return false;
2000
2025
  }
2001
- return this.#attachPastedImagePaths(parsed.paths, parsed.requiresConfirmation, context);
2026
+ return this.#attachPastedImagePaths(
2027
+ parsed.paths,
2028
+ parsed.requiresConfirmation ? "confirm" : "clipboard-temp",
2029
+ context,
2030
+ );
2002
2031
  }
2003
2032
 
2004
- /** Return false on every failure so CustomEditor restores the exact paste. */
2033
+ /**
2034
+ * Return false on every failure so CustomEditor restores the exact paste.
2035
+ *
2036
+ * `clipboard-temp` attaches one terminal-written temp image without asking; `confirm` asks
2037
+ * before reading any other pasted path; `user-selected` (files copied in Finder and pasted
2038
+ * with the image-paste key) is already an explicit choice and attaches without asking.
2039
+ */
2005
2040
  async #attachPastedImagePaths(
2006
2041
  imagePaths: readonly string[],
2007
- requiresConfirmation: boolean,
2042
+ access: "clipboard-temp" | "confirm" | "user-selected",
2008
2043
  context: PasteTextContext,
2009
2044
  ): Promise<boolean> {
2010
2045
  const signal = context.signal;
@@ -2013,7 +2048,7 @@ export class InputController {
2013
2048
  const pendingImages = this.ctx.pendingImages;
2014
2049
  const pendingImageCount = pendingImages.length;
2015
2050
  try {
2016
- if (requiresConfirmation) {
2051
+ if (access === "confirm") {
2017
2052
  const selection = await this.ctx.showHookSelector(
2018
2053
  `Attach ${imagePaths.length} pasted images?\nOnly attach files you intend to send to the model.`,
2019
2054
  ["Attach images", "Paste paths literally"],
@@ -2026,7 +2061,7 @@ export class InputController {
2026
2061
  const loaded = await this.#loadPastedImageBatch({
2027
2062
  paths: imagePaths,
2028
2063
  autoResize: this.ctx.settings.get("images.autoResize"),
2029
- sourcePolicy: requiresConfirmation ? "confirmed" : "automatic-temp",
2064
+ sourcePolicy: access === "clipboard-temp" ? "automatic-temp" : "confirmed",
2030
2065
  signal,
2031
2066
  });
2032
2067
  signal.throwIfAborted();
@@ -2184,54 +2219,83 @@ export class InputController {
2184
2219
  this.ctx.pendingImages = [];
2185
2220
  }
2186
2221
 
2222
+ /**
2223
+ * Ctrl+V / Cmd+V smart paste. Order matters: macOS pasteboard file URLs first (a Finder-copied
2224
+ * image also carries a generic file-icon bitmap), then the bitmap, then clipboard text, inserted
2225
+ * verbatim.
2226
+ */
2187
2227
  async handleImagePaste(): Promise<boolean> {
2188
2228
  try {
2189
- const image = await readImageFromClipboard();
2190
- if (image) {
2191
- const base64Data = image.data.toBase64();
2192
- let imageData = await ensureSupportedImageInput({
2193
- type: "image",
2194
- data: base64Data,
2195
- mimeType: image.mimeType,
2196
- });
2197
- if (!imageData) {
2198
- this.ctx.showStatus(`Unsupported clipboard image format: ${image.mimeType}`);
2199
- return false;
2200
- }
2201
- if (this.ctx.settings.get("images.autoResize")) {
2202
- try {
2203
- const resized = await resizeImage({
2204
- type: "image",
2205
- data: imageData.data,
2206
- mimeType: imageData.mimeType,
2207
- });
2208
- imageData = { type: "image", data: resized.data, mimeType: resized.mimeType };
2209
- } catch {
2210
- // Keep the normalized image when resize fails.
2211
- }
2212
- }
2229
+ const filePaths = imageFilePathsFromList(await this.#clipboard.readMacFileUrls());
2230
+ if (filePaths.length > 0)
2231
+ return await this.#attachPastedImagePaths(filePaths, "user-selected", this.#unguardedPasteContext());
2232
+
2233
+ // Start the text bridge alongside the image bridge: either can shell out, so serial awaits
2234
+ // would stall an empty clipboard by their sum. Settle-mark it so an image-read throw that
2235
+ // skips the text await can never become an unhandled rejection.
2236
+ const textPromise = this.#clipboard.readText();
2237
+ textPromise.then(
2238
+ () => {},
2239
+ () => {},
2240
+ );
2241
+ const image = await this.#clipboard.readImage();
2242
+ if (image) return await this.#attachClipboardImage(image);
2213
2243
 
2214
- this.ctx.pendingImages = [
2215
- ...this.ctx.pendingImages,
2216
- {
2217
- type: "image",
2218
- data: imageData.data,
2219
- mimeType: imageData.mimeType,
2220
- },
2221
- ];
2222
- this.ctx.editor.insertText(`${this.#nextImagePlaceholder()} `);
2223
- this.ctx.ui.requestRender();
2224
- return true;
2244
+ const text = await textPromise;
2245
+ if (!text) {
2246
+ this.ctx.showStatus("Clipboard is empty");
2247
+ return false;
2225
2248
  }
2226
- this.ctx.showStatus(
2227
- "No image in clipboard. Use #paste-image, paste a copied image, or attach an image file with @path/to/image.png.",
2228
- );
2229
- return false;
2249
+ this.ctx.editor.insertText(text);
2250
+ this.ctx.ui.requestRender();
2251
+ return true;
2230
2252
  } catch {
2231
2253
  this.ctx.showStatus("Failed to read clipboard");
2232
2254
  return false;
2233
2255
  }
2234
2256
  }
2257
+
2258
+ /** Paste context for keybinding-driven pastes, which have no editor transaction to abort or commit. */
2259
+ #unguardedPasteContext(): PasteTextContext {
2260
+ return { signal: new AbortController().signal, commit: commit => commit() };
2261
+ }
2262
+
2263
+ async #attachClipboardImage(image: ClipboardImage): Promise<boolean> {
2264
+ let imageData = await ensureSupportedImageInput({
2265
+ type: "image",
2266
+ data: image.data.toBase64(),
2267
+ mimeType: image.mimeType,
2268
+ });
2269
+ if (!imageData) {
2270
+ this.ctx.showStatus(`Unsupported clipboard image format: ${image.mimeType}`);
2271
+ return false;
2272
+ }
2273
+ if (this.ctx.settings.get("images.autoResize")) {
2274
+ try {
2275
+ const resized = await resizeImage({
2276
+ type: "image",
2277
+ data: imageData.data,
2278
+ mimeType: imageData.mimeType,
2279
+ });
2280
+ imageData = { type: "image", data: resized.data, mimeType: resized.mimeType };
2281
+ } catch {
2282
+ // Keep the normalized image when resize fails.
2283
+ }
2284
+ }
2285
+
2286
+ this.ctx.pendingImages = [
2287
+ ...this.ctx.pendingImages,
2288
+ {
2289
+ type: "image",
2290
+ data: imageData.data,
2291
+ mimeType: imageData.mimeType,
2292
+ },
2293
+ ];
2294
+ this.ctx.editor.insertText(`${this.#nextImagePlaceholder()} `);
2295
+ this.ctx.ui.requestRender();
2296
+ return true;
2297
+ }
2298
+
2235
2299
  /**
2236
2300
  * Explicit "Paste text from configured clipboard" action (P3-b v1). Only
2237
2301
  * meaningful when `clipboard.transport` is `ssh` — reads via `pbpaste` on
@@ -140,7 +140,7 @@ export class PlanModeController {
140
140
  if (this.ctx.session.isExplicitEmptyToolSelection()) return;
141
141
  if (!this.ctx.session.settings.get("plan.enabled")) {
142
142
  if (sessionContext.mode === "plan" || sessionContext.mode === "plan_paused")
143
- this.ctx.sessionManager.appendModeChange("none");
143
+ this.ctx.session.appendModeChangeInBackground("none");
144
144
  return;
145
145
  }
146
146
  if (sessionContext.mode !== "plan" && sessionContext.mode !== "plan_paused") return;
@@ -204,7 +204,7 @@ export class PlanModeController {
204
204
  this.#hasEntered = true;
205
205
  await this.#applyModel();
206
206
  this.#updateStatus();
207
- this.ctx.sessionManager.appendModeChange("plan", { planFilePath });
207
+ this.ctx.session.appendModeChangeInBackground("plan", { planFilePath });
208
208
  this.ctx.showStatus(`Plan mode enabled. Plan file: ${planFilePath}`);
209
209
  }
210
210
 
@@ -223,7 +223,7 @@ export class PlanModeController {
223
223
  } else if (this.#previousModelState) {
224
224
  const previous = this.#previousModelState;
225
225
  if (modelsAreEqual(this.ctx.session.model, previous.model))
226
- this.ctx.session.setThinkingLevel(previous.thinkingLevel);
226
+ await this.ctx.session.setThinkingLevelForSession(previous.thinkingLevel);
227
227
  else if (this.ctx.session.isStreaming) this.#pendingModelSwitch = previous;
228
228
  else
229
229
  await this.ctx.session.setModelTemporary(previous.model, previous.thinkingLevel, {
@@ -244,7 +244,7 @@ export class PlanModeController {
244
244
  this.#previousModelState = undefined;
245
245
  if (!this.#paused) this.ctx.modeGate.exit("plan");
246
246
  this.#updateStatus();
247
- this.ctx.sessionManager.appendModeChange(this.#paused ? "plan_paused" : "none");
247
+ this.ctx.session.appendModeChangeInBackground(this.#paused ? "plan_paused" : "none");
248
248
  if (!options?.silent) this.ctx.showStatus(this.#paused ? "Plan mode paused." : "Plan mode disabled.");
249
249
  }
250
250
 
@@ -352,7 +352,7 @@ export class PlanModeController {
352
352
  ? { model: current, thinkingLevel: this.ctx.session.thinkingLevel }
353
353
  : undefined;
354
354
  if (modelsAreEqual(current, resolved.model)) {
355
- if (thinkingLevel) this.ctx.session.setThinkingLevel(thinkingLevel);
355
+ if (thinkingLevel) await this.ctx.session.setThinkingLevelForSession(thinkingLevel);
356
356
  return;
357
357
  }
358
358
  if (this.ctx.session.isStreaming) {
@@ -599,11 +599,7 @@ export class PlanModeController {
599
599
  );
600
600
  }
601
601
  const name = humanizePlanTitle(options.title);
602
- if (
603
- name &&
604
- !this.ctx.sessionManager.getSessionName() &&
605
- (await this.ctx.sessionManager.setSessionName(name, "auto"))
606
- ) {
602
+ if (name && !this.ctx.sessionManager.getSessionName() && (await this.ctx.session.setSessionName(name, "auto"))) {
607
603
  setSessionTerminalTitle(this.ctx.sessionManager.getSessionName(), this.ctx.sessionManager.getCwd());
608
604
  this.ctx.updateEditorChrome();
609
605
  }