@selesai/code 0.9.5 → 0.9.8

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 (284) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/cli/credential-print.js +4 -4
  3. package/dist/cli.js +0 -0
  4. package/dist/core/agent-session-runtime.js +1 -4
  5. package/dist/core/agent-session.d.ts +2 -0
  6. package/dist/core/agent-session.js +26 -0
  7. package/dist/core/compaction/branch-summarization.js +30 -30
  8. package/dist/core/compaction/compaction.js +81 -81
  9. package/dist/core/compaction/utils.js +2 -2
  10. package/dist/core/export-html/template.css +1066 -1066
  11. package/dist/core/export-html/template.html +55 -55
  12. package/dist/core/export-html/template.js +1864 -1864
  13. package/dist/core/export-html/vendor/highlight.min.js +1212 -1212
  14. package/dist/core/export-html/vendor/marked.min.js +78 -78
  15. package/dist/core/handoff.d.ts +11 -0
  16. package/dist/core/handoff.js +49 -0
  17. package/dist/core/messages.js +7 -7
  18. package/dist/extensions/context-compaction-reminder.test.ts +82 -82
  19. package/dist/extensions/context-compaction-reminder.ts +28 -28
  20. package/dist/extensions/handoff-new.ts +14 -75
  21. package/dist/extensions/pi-intercom/LICENSE +21 -21
  22. package/dist/extensions/pi-intercom/broker/client.test.ts +83 -83
  23. package/dist/extensions/pi-intercom/broker/extension.test.ts +387 -387
  24. package/dist/extensions/pi-intercom/broker/framing.test.ts +114 -114
  25. package/dist/extensions/pi-intercom/broker/paths.test.ts +153 -153
  26. package/dist/extensions/pi-intercom/broker/paths.ts +134 -134
  27. package/dist/extensions/pi-intercom/broker/runtime-claim.test.ts +34 -34
  28. package/dist/extensions/pi-intercom/broker/runtime-claim.ts +21 -21
  29. package/dist/extensions/pi-intercom/cwd.test.ts +40 -40
  30. package/dist/extensions/pi-intercom/cwd.ts +31 -31
  31. package/dist/extensions/pi-intercom/extension-api.ts +44 -44
  32. package/dist/extensions/pi-intercom/format-context.test.ts +31 -31
  33. package/dist/extensions/pi-intercom/format-context.ts +32 -32
  34. package/dist/extensions/pi-intercom/test/overlay-width.test.ts +66 -66
  35. package/dist/extensions/pi-intercom/ui/compose.ts +143 -143
  36. package/dist/extensions/pi-intercom/ui/session-list.ts +166 -166
  37. package/dist/extensions/pi-powerline-footer/bash-mode/shell-session.ts +286 -286
  38. package/dist/extensions/pi-powerline-footer/bash-mode/transcript.ts +108 -108
  39. package/dist/extensions/pi-powerline-footer/separators.ts +57 -57
  40. package/dist/extensions/pi-powerline-footer/tests/session-usage.test.ts +47 -47
  41. package/dist/extensions/pi-powerline-footer/tests/tps.test.ts +39 -39
  42. package/dist/extensions/pi-powerline-footer/theme.example.json +24 -24
  43. package/dist/extensions/pi-powerline-footer/theme.json +12 -12
  44. package/dist/extensions/pi-powerline-footer/tps.ts +345 -345
  45. package/dist/extensions/pi-rewind-hook/README.md +245 -245
  46. package/dist/extensions/pi-rewind-hook/index.ts +1445 -1445
  47. package/dist/extensions/pi-rewind-hook/package.json +29 -29
  48. package/dist/extensions/pi-subagents/install.mjs +0 -0
  49. package/dist/extensions/pi-web-agent/package.json +31 -31
  50. package/dist/extensions/pi-web-agent/src/backends/config.ts +205 -205
  51. package/dist/extensions/pi-web-agent/src/backends/doctor.ts +136 -136
  52. package/dist/extensions/pi-web-agent/src/backends/factory.ts +152 -152
  53. package/dist/extensions/pi-web-agent/src/backends/settings-reader.ts +25 -25
  54. package/dist/extensions/pi-web-agent/src/cache/ttl-cache.ts +28 -28
  55. package/dist/extensions/pi-web-agent/src/changelog-notice.ts +136 -136
  56. package/dist/extensions/pi-web-agent/src/commands/web-agent-config.ts +946 -946
  57. package/dist/extensions/pi-web-agent/src/extension.ts +126 -126
  58. package/dist/extensions/pi-web-agent/src/extract/readability.ts +118 -118
  59. package/dist/extensions/pi-web-agent/src/fetch/browser-resolution.ts +199 -199
  60. package/dist/extensions/pi-web-agent/src/fetch/firecrawl-fetch.ts +100 -100
  61. package/dist/extensions/pi-web-agent/src/fetch/headless-fetch.ts +117 -117
  62. package/dist/extensions/pi-web-agent/src/fetch/http-fetch.ts +67 -67
  63. package/dist/extensions/pi-web-agent/src/orchestration/answer-synthesizer.ts +60 -60
  64. package/dist/extensions/pi-web-agent/src/orchestration/candidate-selector.ts +50 -50
  65. package/dist/extensions/pi-web-agent/src/orchestration/direct-url.ts +52 -52
  66. package/dist/extensions/pi-web-agent/src/orchestration/evidence-quality.ts +105 -105
  67. package/dist/extensions/pi-web-agent/src/orchestration/evidence-ranker.ts +45 -45
  68. package/dist/extensions/pi-web-agent/src/orchestration/index.ts +28 -28
  69. package/dist/extensions/pi-web-agent/src/orchestration/query-planner.ts +47 -47
  70. package/dist/extensions/pi-web-agent/src/orchestration/research-orchestrator.ts +376 -376
  71. package/dist/extensions/pi-web-agent/src/orchestration/research-types.ts +64 -64
  72. package/dist/extensions/pi-web-agent/src/orchestration/research-worker.ts +181 -181
  73. package/dist/extensions/pi-web-agent/src/orchestration/source-profile.ts +101 -101
  74. package/dist/extensions/pi-web-agent/src/orchestration/stop-decider.ts +81 -81
  75. package/dist/extensions/pi-web-agent/src/presentation/config-store.ts +210 -210
  76. package/dist/extensions/pi-web-agent/src/presentation/config.ts +75 -75
  77. package/dist/extensions/pi-web-agent/src/presentation/explore-presentation.ts +61 -61
  78. package/dist/extensions/pi-web-agent/src/presentation/fetch-presentation.ts +54 -54
  79. package/dist/extensions/pi-web-agent/src/presentation/search-presentation.ts +41 -41
  80. package/dist/extensions/pi-web-agent/src/presentation/select-view.ts +20 -20
  81. package/dist/extensions/pi-web-agent/src/presentation/types.ts +63 -63
  82. package/dist/extensions/pi-web-agent/src/search/brave.ts +114 -114
  83. package/dist/extensions/pi-web-agent/src/search/duckduckgo.ts +72 -72
  84. package/dist/extensions/pi-web-agent/src/search/searxng.ts +96 -96
  85. package/dist/extensions/pi-web-agent/src/tools/web-explore.ts +71 -71
  86. package/dist/extensions/pi-web-agent/src/tools/web-fetch-headless.ts +31 -31
  87. package/dist/extensions/pi-web-agent/src/tools/web-fetch.ts +31 -31
  88. package/dist/extensions/pi-web-agent/src/tools/web-search.ts +157 -157
  89. package/dist/extensions/pi-web-agent/src/types.ts +88 -88
  90. package/dist/extensions/ponytail/package.json +8 -8
  91. package/dist/extensions/question/batch.ts +103 -103
  92. package/dist/extensions/question/constants.ts +30 -30
  93. package/dist/extensions/question/helpers.ts +58 -58
  94. package/dist/extensions/question/navigation.ts +14 -14
  95. package/dist/extensions/question/package.json +19 -19
  96. package/dist/extensions/question/schemas.ts +43 -43
  97. package/dist/extensions/question/selection-mode.ts +46 -46
  98. package/dist/extensions/question/shortcuts.ts +44 -44
  99. package/dist/extensions/question/types.ts +132 -132
  100. package/dist/extensions/test-resolve-hook-impl.mjs +6 -6
  101. package/dist/extensions/test-resolve-hook.mjs +6 -6
  102. package/dist/extensions/web-agent-onboarding.ts +222 -222
  103. package/dist/extensions/workflow/package.json +17 -17
  104. package/dist/modes/interactive/components/model-selector.d.ts +1 -0
  105. package/dist/modes/interactive/components/model-selector.js +8 -4
  106. package/dist/modes/interactive/interactive-mode.js +9 -5
  107. package/dist/modes/rpc/rpc-mode.js +24 -0
  108. package/dist/modes/rpc/rpc-types.d.ts +19 -0
  109. package/dist/package-manager-cli.js +71 -71
  110. package/dist/rpc-entry.js +0 -0
  111. package/dist/skills/agent-browser/SKILL.md +52 -52
  112. package/dist/skills/batch-grill-me/SKILL.md +19 -19
  113. package/dist/skills/grill-me/SKILL.md +10 -10
  114. package/dist/skills/handoff/SKILL.md +16 -16
  115. package/dist/skills/handoff-text/SKILL.md +14 -14
  116. package/dist/skills/implanger/SKILL.md +69 -69
  117. package/dist/skills/improve-codebase/REFERENCE.md +78 -78
  118. package/dist/skills/improve-codebase/SKILL.md +178 -178
  119. package/dist/skills/planger/SKILL.md +166 -166
  120. package/dist/skills/ponytail/SKILL.md +116 -116
  121. package/dist/skills/ponytail-audit/SKILL.md +42 -42
  122. package/dist/skills/ponytail-debt/SKILL.md +45 -45
  123. package/dist/skills/ponytail-gain/SKILL.md +51 -51
  124. package/dist/skills/ponytail-help/SKILL.md +70 -70
  125. package/dist/skills/ponytail-review/SKILL.md +58 -58
  126. package/dist/skills/selesai-handoff/SKILL.md +20 -20
  127. package/dist/skills/workflow-creation/SKILL.md +73 -73
  128. package/dist/themes/powerline-footer/theme.json +33 -33
  129. package/docs/compaction.md +396 -396
  130. package/docs/containerization.md +111 -111
  131. package/docs/development.md +71 -71
  132. package/docs/docs.json +164 -164
  133. package/docs/environment-variables.md +86 -86
  134. package/docs/index.md +83 -83
  135. package/docs/json.md +82 -82
  136. package/docs/models.md +502 -502
  137. package/docs/packages.md +227 -227
  138. package/docs/plans/subagent-delegation/phase-0-correctness.md +264 -264
  139. package/docs/plans/subagent-delegation/phase-1-behavioral-contract.md +485 -485
  140. package/docs/plans/subagent-delegation/phase-2-context-controls.md +281 -281
  141. package/docs/plans/subagent-delegation/phase-3-advisory-routing.md +361 -361
  142. package/docs/plans/subagent-delegation/phase-4-optional-enforcement.md +380 -380
  143. package/docs/prompt-templates.md +95 -95
  144. package/docs/providers.md +293 -293
  145. package/docs/sdk.md +1143 -1143
  146. package/docs/security.md +59 -59
  147. package/docs/session-format.md +414 -414
  148. package/docs/sessions.md +145 -145
  149. package/docs/shared-host-extensions.md +109 -109
  150. package/docs/shell-aliases.md +13 -13
  151. package/docs/skills.md +231 -231
  152. package/docs/terminal-setup.md +142 -142
  153. package/docs/termux.md +127 -127
  154. package/docs/themes.md +295 -295
  155. package/docs/tmux.md +63 -63
  156. package/docs/tui.md +927 -927
  157. package/docs/windows.md +17 -17
  158. package/examples/README.md +25 -25
  159. package/examples/extensions/README.md +211 -211
  160. package/examples/extensions/auto-commit-on-exit.ts +49 -49
  161. package/examples/extensions/bash-spawn-hook.ts +30 -30
  162. package/examples/extensions/bookmark.ts +50 -50
  163. package/examples/extensions/border-status-editor.ts +150 -150
  164. package/examples/extensions/built-in-tool-renderer.ts +249 -249
  165. package/examples/extensions/claude-rules.ts +86 -86
  166. package/examples/extensions/commands.ts +72 -72
  167. package/examples/extensions/confirm-destructive.ts +59 -59
  168. package/examples/extensions/custom-compaction.ts +130 -130
  169. package/examples/extensions/custom-footer.ts +64 -64
  170. package/examples/extensions/custom-header.ts +73 -73
  171. package/examples/extensions/custom-provider-anthropic/index.ts +610 -610
  172. package/examples/extensions/custom-provider-anthropic/package-lock.json +24 -24
  173. package/examples/extensions/custom-provider-anthropic/package.json +19 -19
  174. package/examples/extensions/custom-provider-gitlab-duo/index.ts +404 -404
  175. package/examples/extensions/custom-provider-gitlab-duo/package.json +16 -16
  176. package/examples/extensions/custom-provider-gitlab-duo/test.ts +82 -82
  177. package/examples/extensions/dirty-repo-guard.ts +56 -56
  178. package/examples/extensions/doom-overlay/README.md +46 -46
  179. package/examples/extensions/doom-overlay/doom/build/doom.js +21 -21
  180. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  181. package/examples/extensions/doom-overlay/doom/build.sh +152 -152
  182. package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +72 -72
  183. package/examples/extensions/doom-overlay/doom-component.ts +132 -132
  184. package/examples/extensions/doom-overlay/doom-engine.ts +173 -173
  185. package/examples/extensions/doom-overlay/doom-keys.ts +104 -104
  186. package/examples/extensions/doom-overlay/index.ts +74 -74
  187. package/examples/extensions/doom-overlay/wad-finder.ts +51 -51
  188. package/examples/extensions/dynamic-resources/SKILL.md +8 -8
  189. package/examples/extensions/dynamic-resources/dynamic.json +79 -79
  190. package/examples/extensions/dynamic-resources/dynamic.md +5 -5
  191. package/examples/extensions/dynamic-resources/index.ts +15 -15
  192. package/examples/extensions/dynamic-tools.ts +74 -74
  193. package/examples/extensions/event-bus.ts +43 -43
  194. package/examples/extensions/file-trigger.ts +41 -41
  195. package/examples/extensions/git-checkpoint.ts +53 -53
  196. package/examples/extensions/git-merge-and-resolve.ts +115 -115
  197. package/examples/extensions/github-issue-autocomplete.ts +185 -185
  198. package/examples/extensions/gondolin/index.ts +531 -531
  199. package/examples/extensions/gondolin/package-lock.json +185 -185
  200. package/examples/extensions/gondolin/package.json +19 -19
  201. package/examples/extensions/handoff.ts +199 -199
  202. package/examples/extensions/hello.ts +26 -26
  203. package/examples/extensions/hidden-thinking-label.ts +53 -53
  204. package/examples/extensions/inline-bash.ts +94 -94
  205. package/examples/extensions/input-transform-streaming.ts +39 -39
  206. package/examples/extensions/input-transform.ts +43 -43
  207. package/examples/extensions/interactive-shell.ts +196 -196
  208. package/examples/extensions/mac-system-theme.ts +47 -47
  209. package/examples/extensions/message-renderer.ts +59 -59
  210. package/examples/extensions/minimal-mode.ts +426 -426
  211. package/examples/extensions/modal-editor.ts +85 -85
  212. package/examples/extensions/model-status.ts +31 -31
  213. package/examples/extensions/notify.ts +55 -55
  214. package/examples/extensions/overlay-qa-tests.ts +1450 -1450
  215. package/examples/extensions/overlay-test.ts +153 -153
  216. package/examples/extensions/permission-gate.ts +34 -34
  217. package/examples/extensions/pirate.ts +47 -47
  218. package/examples/extensions/plan-mode/README.md +66 -66
  219. package/examples/extensions/plan-mode/index.ts +390 -390
  220. package/examples/extensions/plan-mode/utils.ts +168 -168
  221. package/examples/extensions/preset.ts +436 -436
  222. package/examples/extensions/project-trust.ts +64 -64
  223. package/examples/extensions/prompt-customizer.ts +97 -97
  224. package/examples/extensions/protected-paths.ts +30 -30
  225. package/examples/extensions/provider-payload.ts +18 -18
  226. package/examples/extensions/qna.ts +122 -122
  227. package/examples/extensions/question.ts +285 -285
  228. package/examples/extensions/questionnaire.ts +448 -448
  229. package/examples/extensions/rainbow-editor.ts +88 -88
  230. package/examples/extensions/reload-runtime.ts +37 -37
  231. package/examples/extensions/rpc-demo.ts +118 -118
  232. package/examples/extensions/sandbox/index.ts +321 -321
  233. package/examples/extensions/sandbox/package-lock.json +92 -92
  234. package/examples/extensions/sandbox/package.json +19 -19
  235. package/examples/extensions/send-user-message.ts +97 -97
  236. package/examples/extensions/session-name.ts +27 -27
  237. package/examples/extensions/shutdown-command.ts +63 -63
  238. package/examples/extensions/snake.ts +343 -343
  239. package/examples/extensions/space-invaders.ts +560 -560
  240. package/examples/extensions/ssh.ts +220 -220
  241. package/examples/extensions/status-line.ts +32 -32
  242. package/examples/extensions/structured-output.ts +65 -65
  243. package/examples/extensions/subagent/README.md +175 -175
  244. package/examples/extensions/subagent/agents/planner.md +37 -37
  245. package/examples/extensions/subagent/agents/reviewer.md +35 -35
  246. package/examples/extensions/subagent/agents/scout.md +50 -50
  247. package/examples/extensions/subagent/agents/worker.md +24 -24
  248. package/examples/extensions/subagent/agents.ts +126 -126
  249. package/examples/extensions/subagent/index.ts +1015 -1015
  250. package/examples/extensions/subagent/prompts/implement-and-review.md +10 -10
  251. package/examples/extensions/subagent/prompts/implement.md +10 -10
  252. package/examples/extensions/subagent/prompts/scout-and-plan.md +9 -9
  253. package/examples/extensions/summarize.ts +209 -209
  254. package/examples/extensions/system-prompt-header.ts +17 -17
  255. package/examples/extensions/tic-tac-toe.ts +1008 -1008
  256. package/examples/extensions/timed-confirm.ts +70 -70
  257. package/examples/extensions/titlebar-spinner.ts +58 -58
  258. package/examples/extensions/todo.ts +297 -297
  259. package/examples/extensions/tool-override.ts +144 -144
  260. package/examples/extensions/tools.ts +146 -146
  261. package/examples/extensions/trigger-compact.ts +50 -50
  262. package/examples/extensions/truncated-tool.ts +195 -195
  263. package/examples/extensions/widget-placement.ts +9 -9
  264. package/examples/extensions/with-deps/index.ts +32 -32
  265. package/examples/extensions/with-deps/package-lock.json +31 -31
  266. package/examples/extensions/with-deps/package.json +22 -22
  267. package/examples/extensions/working-indicator.ts +123 -123
  268. package/examples/extensions/working-message-test.ts +25 -25
  269. package/examples/rpc-extension-ui.ts +632 -632
  270. package/examples/sdk/01-minimal.ts +26 -26
  271. package/examples/sdk/02-custom-model.ts +53 -53
  272. package/examples/sdk/03-custom-prompt.ts +75 -75
  273. package/examples/sdk/04-skills.ts +55 -55
  274. package/examples/sdk/05-tools.ts +48 -48
  275. package/examples/sdk/06-extensions.ts +99 -99
  276. package/examples/sdk/07-context-files.ts +47 -47
  277. package/examples/sdk/08-prompt-templates.ts +51 -51
  278. package/examples/sdk/09-api-keys-and-oauth.ts +52 -52
  279. package/examples/sdk/10-settings.ts +53 -53
  280. package/examples/sdk/11-sessions.ts +52 -52
  281. package/examples/sdk/12-full-control.ts +79 -79
  282. package/examples/sdk/13-session-runtime.ts +67 -67
  283. package/examples/sdk/README.md +144 -144
  284. package/package.json +1 -1
@@ -1,1008 +1,1008 @@
1
- /**
2
- * Tic-Tac-Toe extension - demonstrates executionMode: "sequential" on tools.
3
- *
4
- * The user plays via /tic-tac-toe (arrow keys + Enter).
5
- * The agent plays via a single tool `tic_tac_toe` that takes ONE atomic action
6
- * per call. To play at (r, c) from its cursor (r0, c0) the agent must emit the
7
- * required move_* and a final `play` as SEPARATE tool_use blocks inside ONE
8
- * assistant response.
9
- *
10
- * Move actions share the agent cursor and have a 300ms delay. Under the
11
- * default parallel tool-execution mode this races: `play` can resolve before
12
- * the earlier `move_*` calls finish and O lands on the wrong cell. With
13
- * `executionMode: "sequential"` the runner serializes the sibling calls and O
14
- * lands on the intended cell.
15
- *
16
- * The user cursor (TUI-only) and the agent cursor (tool-only) are stored in
17
- * separate variables. Only the agent cursor is ever exposed to the agent.
18
- */
19
-
20
- import { StringEnum } from "@earendil-works/pi-ai";
21
- import type { ExtensionAPI, ExtensionContext, Theme, ToolExecutionMode } from "@earendil-works/pi-coding-agent";
22
- import { type Component, matchesKey, Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
23
- import { Type } from "typebox";
24
-
25
- // Thrown from the tool on illegal actions. The agent runtime surfaces thrown
26
- // errors as tool errors (isError=true) without resetting any of our state.
27
- class TicTacToeError extends Error {
28
- constructor(message: string) {
29
- super(message);
30
- this.name = "TicTacToeError";
31
- }
32
- }
33
-
34
- // ---------------------------------------------------------------------------
35
- // Types
36
- // ---------------------------------------------------------------------------
37
-
38
- type Cell = " " | "X" | "O";
39
- type GameStatus = "playing" | "win_X" | "win_O" | "draw";
40
-
41
- interface GameState {
42
- board: Cell[][];
43
- // User cursor (TUI-only, never exposed to the agent).
44
- userCursorRow: number;
45
- userCursorCol: number;
46
- // Agent cursor (manipulated by the tool, shown in the TUI during O's turn).
47
- agentCursorRow: number;
48
- agentCursorCol: number;
49
- status: GameStatus;
50
- userMark: Cell;
51
- agentMark: Cell;
52
- currentTurn: Cell;
53
- }
54
-
55
- // Persisted with each toolResult for state reconstruction AND sent to the
56
- // agent as `details`. Only the agent cursor is included: the user cursor is
57
- // private to the TUI.
58
- interface BoardDetails {
59
- board: Cell[][];
60
- agentCursorRow: number;
61
- agentCursorCol: number;
62
- status: GameStatus;
63
- currentTurn: Cell;
64
- }
65
-
66
- // ---------------------------------------------------------------------------
67
- // Game logic
68
- // ---------------------------------------------------------------------------
69
-
70
- // Agent cursor home: where the cursor is reset to after a SUCCESSFUL play.
71
- // Pinned at (0,0) so every non-origin play requires at least one move, which
72
- // guarantees multiple tool calls per turn and makes the parallel-vs-sequential
73
- // behavior observable in the demo. The cursor is NOT reset when the user plays
74
- // nor on a failed `play` (cell taken), so the agent can retry without
75
- // starting over.
76
- const AGENT_CURSOR_HOME_ROW = 0;
77
- const AGENT_CURSOR_HOME_COL = 0;
78
-
79
- function createInitialState(): GameState {
80
- return {
81
- board: [
82
- [" ", " ", " "],
83
- [" ", " ", " "],
84
- [" ", " ", " "],
85
- ],
86
- userCursorRow: 1,
87
- userCursorCol: 1,
88
- agentCursorRow: AGENT_CURSOR_HOME_ROW,
89
- agentCursorCol: AGENT_CURSOR_HOME_COL,
90
- status: "playing",
91
- userMark: "X",
92
- agentMark: "O",
93
- currentTurn: "X",
94
- };
95
- }
96
-
97
- function getWinLine(board: Cell[][]): [number, number][] | null {
98
- const lines: [number, number][][] = [
99
- [
100
- [0, 0],
101
- [0, 1],
102
- [0, 2],
103
- ],
104
- [
105
- [1, 0],
106
- [1, 1],
107
- [1, 2],
108
- ],
109
- [
110
- [2, 0],
111
- [2, 1],
112
- [2, 2],
113
- ],
114
- [
115
- [0, 0],
116
- [1, 0],
117
- [2, 0],
118
- ],
119
- [
120
- [0, 1],
121
- [1, 1],
122
- [2, 1],
123
- ],
124
- [
125
- [0, 2],
126
- [1, 2],
127
- [2, 2],
128
- ],
129
- [
130
- [0, 0],
131
- [1, 1],
132
- [2, 2],
133
- ],
134
- [
135
- [0, 2],
136
- [1, 1],
137
- [2, 0],
138
- ],
139
- ];
140
- for (const line of lines) {
141
- const vals = line.map(([r, c]) => board[r][c]);
142
- if (vals[0] !== " " && vals[0] === vals[1] && vals[1] === vals[2]) {
143
- return line;
144
- }
145
- }
146
- return null;
147
- }
148
-
149
- function checkWin(board: Cell[][]): GameStatus {
150
- const winLine = getWinLine(board);
151
- if (winLine) {
152
- const [r, c] = winLine[0];
153
- return board[r][c] === "X" ? "win_X" : "win_O";
154
- }
155
- if (board.every((row) => row.every((c) => c !== " "))) {
156
- return "draw";
157
- }
158
- return "playing";
159
- }
160
-
161
- function boardToAscii(board: Cell[][], agentCursorRow: number, agentCursorCol: number): string {
162
- // Plain grid with coordinates for empty cells, marking the agent cursor
163
- // position with angle brackets. The user cursor is NEVER included: it is a
164
- // TUI-only concept and must not leak to the agent.
165
- const rows = board.map((row, r) =>
166
- row
167
- .map((c, cIdx) => {
168
- const onCursor = r === agentCursorRow && cIdx === agentCursorCol;
169
- if (c === " ") return onCursor ? `<[${r},${cIdx}]>` : ` [${r},${cIdx}] `;
170
- return onCursor ? ` <${c}> ` : ` ${c} `;
171
- })
172
- .join("|"),
173
- );
174
- const separator = "---------+---------+---------";
175
- return rows.join(`\n${separator}\n`);
176
- }
177
-
178
- // ---------------------------------------------------------------------------
179
- // Visual board rendering (ANSI).
180
- // - Cells have NO background fill. Only the centered glyph is drawn.
181
- // - Played cells color their glyph AND their surrounding borders in the
182
- // player's color, so each mark reads as a colored boxed region.
183
- // - Cursor is indicated with colored borders around the cursor cell.
184
- // ---------------------------------------------------------------------------
185
-
186
- const CELL_WIDTH = 7;
187
- const CELL_HEIGHT = 3;
188
-
189
- // Player colors (SGR fg codes). Also used for the borders of played cells.
190
- const FG_CODE_X = "34"; // blue
191
- const FG_CODE_O = "33"; // yellow
192
- const FG_CODE_WIN = "32"; // green (overrides on the winning line)
193
-
194
- // Single-character glyphs, picked for maximum visual size without emoji.
195
- // - \u2573 (BOX DRAWINGS LIGHT DIAGONAL CROSS) for X
196
- // - \u25ef (LARGE CIRCLE) for O
197
- const GLYPH_X = "\u2573";
198
- const GLYPH_O = "\u25ef";
199
-
200
- const DIM = (s: string) => `\x1b[2m${s}\x1b[22m`;
201
- const RESET = "\x1b[0m";
202
-
203
- function centerPad(content: string, width: number): string {
204
- const contentLen = visibleWidth(content);
205
- if (contentLen >= width) return truncateToWidth(content, width);
206
- const pad = width - contentLen;
207
- const left = Math.floor(pad / 2);
208
- return " ".repeat(left) + content + " ".repeat(pad - left);
209
- }
210
-
211
- // Fg color for a played cell's glyph and its surrounding borders. Undefined
212
- // for empty cells.
213
- function cellFgCode(cell: Cell, isWin: boolean): string | undefined {
214
- if (cell === " ") return undefined;
215
- if (isWin) return FG_CODE_WIN;
216
- return cell === "X" ? FG_CODE_X : FG_CODE_O;
217
- }
218
-
219
- function buildCellContent(mark: Cell, lineIdx: number, isWin: boolean): string {
220
- const empty = " ".repeat(CELL_WIDTH);
221
- if (mark === " ") return empty;
222
-
223
- const isMidLine = lineIdx === Math.floor(CELL_HEIGHT / 2);
224
- if (!isMidLine) return empty;
225
-
226
- const glyph = mark === "X" ? GLYPH_X : GLYPH_O;
227
- const fg = cellFgCode(mark, isWin) as string;
228
- const padLen = CELL_WIDTH - visibleWidth(glyph);
229
- const leftPad = Math.floor(padLen / 2);
230
- const rightPad = padLen - leftPad;
231
- return `${" ".repeat(leftPad)}\x1b[${fg};1m${glyph}${RESET}${" ".repeat(rightPad)}`;
232
- }
233
-
234
- // Fg color for a border char based on its adjacent cells. Undefined when no
235
- // adjacent cell is played or when adjacent plays disagree (border stays dim
236
- // to show the separation).
237
- function borderFgCode(adjacent: ReadonlyArray<{ cell: Cell; isWin: boolean }>): string | undefined {
238
- const fgs = adjacent.map((a) => cellFgCode(a.cell, a.isWin)).filter((f): f is string => !!f);
239
- if (fgs.length === 0) return undefined;
240
- const first = fgs[0];
241
- return fgs.every((f) => f === first) ? first : undefined;
242
- }
243
-
244
- interface BoardRenderOpts {
245
- board: Cell[][];
246
- maxWidth: number;
247
- // Optional cursor overlay. Omit to render a static snapshot (used in tool
248
- // results, move messages, and the game-over banner).
249
- cursor?: { row: number; col: number; owner: "user" | "agent" };
250
- }
251
-
252
- function renderBoard(opts: BoardRenderOpts): string[] {
253
- const { board, maxWidth, cursor } = opts;
254
- const showCursor = !!cursor;
255
- const cr = cursor?.row ?? -1;
256
- const cc = cursor?.col ?? -1;
257
-
258
- // Green for user cursor, yellow for agent cursor.
259
- const cursorSgr = cursor?.owner === "agent" ? "\x1b[33;1m" : "\x1b[32;1m";
260
-
261
- const winLine = getWinLine(board);
262
- const winCells = new Set((winLine ?? []).map(([r, c]) => `${r},${c}`));
263
- const cellAt = (r: number, c: number) => ({ cell: board[r][c], isWin: winCells.has(`${r},${c}`) });
264
-
265
- const isCursorCorner = (gridR: number, gridC: number): boolean =>
266
- showCursor && (gridR === cr || gridR === cr + 1) && (gridC === cc || gridC === cc + 1);
267
- const isCursorHSegment = (gridR: number, c: number): boolean =>
268
- showCursor && c === cc && (gridR === cr || gridR === cr + 1);
269
- const isCursorVBorder = (r: number, gridC: number): boolean =>
270
- showCursor && r === cr && (gridC === cc || gridC === cc + 1);
271
-
272
- const paintBorder = (ch: string, highlighted: boolean, fgCode: string | undefined): string => {
273
- if (highlighted) return `${cursorSgr}${ch}${RESET}`;
274
- if (fgCode) return `\x1b[${fgCode};1m${ch}${RESET}`;
275
- return DIM(ch);
276
- };
277
-
278
- const cornerChar = (gridR: number, gridC: number): string => {
279
- if (gridR === 0 && gridC === 0) return "\u250c";
280
- if (gridR === 0 && gridC === 3) return "\u2510";
281
- if (gridR === 3 && gridC === 0) return "\u2514";
282
- if (gridR === 3 && gridC === 3) return "\u2518";
283
- if (gridR === 0) return "\u252c";
284
- if (gridR === 3) return "\u2534";
285
- if (gridC === 0) return "\u251c";
286
- if (gridC === 3) return "\u2524";
287
- return "\u253c";
288
- };
289
-
290
- const cornerAdjacent = (gridR: number, gridC: number) => {
291
- const out: { cell: Cell; isWin: boolean }[] = [];
292
- for (const [dr, dc] of [
293
- [-1, -1],
294
- [-1, 0],
295
- [0, -1],
296
- [0, 0],
297
- ]) {
298
- const r = gridR + dr;
299
- const c = gridC + dc;
300
- if (r >= 0 && r < 3 && c >= 0 && c < 3) out.push(cellAt(r, c));
301
- }
302
- return out;
303
- };
304
-
305
- const lines: string[] = [];
306
-
307
- for (let gridR = 0; gridR <= 3; gridR++) {
308
- // Horizontal border row.
309
- let row = "";
310
- for (let gridC = 0; gridC <= 3; gridC++) {
311
- const cornerColor = borderFgCode(cornerAdjacent(gridR, gridC));
312
- row += paintBorder(cornerChar(gridR, gridC), isCursorCorner(gridR, gridC), cornerColor);
313
- if (gridC < 3) {
314
- const adj: { cell: Cell; isWin: boolean }[] = [];
315
- if (gridR > 0) adj.push(cellAt(gridR - 1, gridC));
316
- if (gridR < 3) adj.push(cellAt(gridR, gridC));
317
- const segColor = borderFgCode(adj);
318
- row += paintBorder("\u2500".repeat(CELL_WIDTH), isCursorHSegment(gridR, gridC), segColor);
319
- }
320
- }
321
- lines.push(centerPad(row, maxWidth));
322
-
323
- if (gridR === 3) break;
324
-
325
- for (let lineIdx = 0; lineIdx < CELL_HEIGHT; lineIdx++) {
326
- let contentRow = "";
327
- for (let gridC = 0; gridC <= 3; gridC++) {
328
- const adj: { cell: Cell; isWin: boolean }[] = [];
329
- if (gridC > 0) adj.push(cellAt(gridR, gridC - 1));
330
- if (gridC < 3) adj.push(cellAt(gridR, gridC));
331
- const vColor = borderFgCode(adj);
332
- contentRow += paintBorder("\u2502", isCursorVBorder(gridR, gridC), vColor);
333
- if (gridC < 3) {
334
- contentRow += buildCellContent(board[gridR][gridC], lineIdx, winCells.has(`${gridR},${gridC}`));
335
- }
336
- }
337
- lines.push(centerPad(contentRow, maxWidth));
338
- }
339
- }
340
-
341
- return lines;
342
- }
343
-
344
- // Full TUI board with the right cursor overlayed for the current turn.
345
- function renderVisualBoard(state: GameState, maxWidth: number): string[] {
346
- const isUserTurn = state.currentTurn === state.userMark;
347
- const cursor =
348
- state.status !== "playing"
349
- ? undefined
350
- : {
351
- row: isUserTurn ? state.userCursorRow : state.agentCursorRow,
352
- col: isUserTurn ? state.userCursorCol : state.agentCursorCol,
353
- owner: (isUserTurn ? "user" : "agent") as "user" | "agent",
354
- };
355
- return renderBoard({ board: state.board, maxWidth, cursor });
356
- }
357
-
358
- /** Static snapshot used inside tool results and custom messages. */
359
- function renderBoardSnapshot(board: Cell[][], maxWidth: number): string[] {
360
- return renderBoard({ board, maxWidth });
361
- }
362
-
363
- // ---------------------------------------------------------------------------
364
- // TUI component
365
- // ---------------------------------------------------------------------------
366
-
367
- class TicTacToeComponent implements Component {
368
- private state: GameState;
369
- private onClose: () => void;
370
- private onUserPlay: (row: number, col: number) => void;
371
- private tui: { requestRender: () => void };
372
- private cachedLines: string[] = [];
373
- private cachedWidth = 0;
374
- private version = 0;
375
- private cachedVersion = -1;
376
-
377
- constructor(
378
- tui: { requestRender: () => void },
379
- onClose: () => void,
380
- onUserPlay: (row: number, col: number) => void,
381
- state: GameState,
382
- ) {
383
- this.tui = tui;
384
- this.onClose = onClose;
385
- this.onUserPlay = onUserPlay;
386
- this.state = state;
387
- }
388
-
389
- updateState(state: GameState): void {
390
- this.state = state;
391
- this.version++;
392
- this.tui.requestRender();
393
- }
394
-
395
- handleInput(data: string): boolean {
396
- if (matchesKey(data, "escape") || data === "q" || data === "Q") {
397
- this.onClose();
398
- return true;
399
- }
400
- if (this.state.status !== "playing") {
401
- if (data === "r" || data === "R") {
402
- this.onClose();
403
- return true;
404
- }
405
- return true;
406
- }
407
- if (this.state.currentTurn !== this.state.userMark) return true;
408
-
409
- if (matchesKey(data, "up") && this.state.userCursorRow > 0) {
410
- this.state.userCursorRow--;
411
- this.version++;
412
- this.tui.requestRender();
413
- } else if (matchesKey(data, "down") && this.state.userCursorRow < 2) {
414
- this.state.userCursorRow++;
415
- this.version++;
416
- this.tui.requestRender();
417
- } else if (matchesKey(data, "left") && this.state.userCursorCol > 0) {
418
- this.state.userCursorCol--;
419
- this.version++;
420
- this.tui.requestRender();
421
- } else if (matchesKey(data, "right") && this.state.userCursorCol < 2) {
422
- this.state.userCursorCol++;
423
- this.version++;
424
- this.tui.requestRender();
425
- } else if (matchesKey(data, "return") || data === " ") {
426
- const { userCursorRow, userCursorCol } = this.state;
427
- if (this.state.board[userCursorRow][userCursorCol] === " ") {
428
- this.onUserPlay(userCursorRow, userCursorCol);
429
- }
430
- }
431
- return true;
432
- }
433
-
434
- invalidate(): void {
435
- this.cachedWidth = 0;
436
- }
437
-
438
- render(width: number): string[] {
439
- if (width === this.cachedWidth && this.cachedVersion === this.version) {
440
- return this.cachedLines;
441
- }
442
-
443
- const ESC = "\x1b[";
444
- const reset = `${ESC}0m`;
445
- const bold = (s: string) => `${ESC}1m${s}${reset}`;
446
- const dim = (s: string) => `${ESC}2m${s}${reset}`;
447
- const blue = (s: string) => `${ESC}34m${s}${reset}`;
448
- const yellow = (s: string) => `${ESC}33m${s}${reset}`;
449
- const green = (s: string) => `${ESC}32m${s}${reset}`;
450
-
451
- const lines: string[] = [];
452
-
453
- // Top title banner, full width.
454
- const titleText = " Tic-Tac-Toe ";
455
- const titleLen = visibleWidth(titleText);
456
- const borderLen = Math.max(0, width - titleLen);
457
- const leftBorder = Math.floor(borderLen / 2);
458
- const rightBorder = borderLen - leftBorder;
459
- lines.push(dim("\u2500".repeat(leftBorder)) + bold(blue(titleText)) + dim("\u2500".repeat(rightBorder)));
460
-
461
- lines.push("");
462
-
463
- // Status line.
464
- if (this.state.status !== "playing") {
465
- const statusText =
466
- this.state.status === "draw"
467
- ? bold(yellow("Draw!"))
468
- : this.state.status === "win_X"
469
- ? bold(green("X wins!"))
470
- : bold(yellow("O wins!"));
471
- lines.push(centerPad(statusText, width));
472
- } else if (this.state.currentTurn === "X") {
473
- lines.push(centerPad(`Turn: ${bold(blue("X"))} (You) ${dim("|")} ${bold(yellow("O"))} (Agent)`, width));
474
- } else {
475
- lines.push(centerPad(`${blue("X")} (You) ${dim("|")} Turn: ${bold(yellow("O"))} (Agent)`, width));
476
- }
477
-
478
- lines.push("");
479
- lines.push("");
480
-
481
- lines.push(...renderVisualBoard(this.state, width));
482
-
483
- lines.push("");
484
- lines.push("");
485
-
486
- // Footer.
487
- let footer: string;
488
- if (this.state.status !== "playing") {
489
- footer = `${bold("R")} restart ${dim("|")} ${bold("Q")}/${bold("ESC")} quit`;
490
- } else if (this.state.currentTurn !== this.state.userMark) {
491
- footer = dim("Agent is thinking...");
492
- } else {
493
- footer = `${bold("\u2190\u2191\u2193\u2192")} move ${dim("|")} ${bold("ENTER")} play ${dim("|")} ${bold("ESC")} quit`;
494
- }
495
- lines.push(centerPad(footer, width));
496
-
497
- // Bottom separator between the component and the editor below.
498
- lines.push("");
499
- lines.push(dim("\u2500".repeat(width)));
500
-
501
- this.cachedLines = lines;
502
- this.cachedWidth = width;
503
- this.cachedVersion = this.version;
504
- return lines;
505
- }
506
- }
507
-
508
- // ---------------------------------------------------------------------------
509
- // Move-message renderer (full width banner)
510
- // ---------------------------------------------------------------------------
511
-
512
- // Full-width banner message with an optional board snapshot underneath.
513
- class BannerMessageComponent implements Component {
514
- private readonly title: string;
515
- private readonly details: BoardDetails | undefined;
516
- private readonly expanded: boolean;
517
- private readonly theme: Theme;
518
-
519
- constructor(title: string, details: BoardDetails | undefined, expanded: boolean, theme: Theme) {
520
- this.title = title;
521
- this.details = details;
522
- this.expanded = expanded;
523
- this.theme = theme;
524
- }
525
-
526
- invalidate(): void {}
527
-
528
- render(width: number): string[] {
529
- const dim = (s: string) => this.theme.fg("dim", s);
530
- const lines: string[] = [];
531
- const titleLen = visibleWidth(this.title);
532
- const fillLen = Math.max(0, width - titleLen - 2);
533
- const leftFill = Math.floor(fillLen / 2);
534
- const rightFill = fillLen - leftFill;
535
- lines.push(`${dim("\u2500".repeat(leftFill))} ${this.title} ${dim("\u2500".repeat(rightFill))}`);
536
-
537
- if (this.expanded && this.details) {
538
- lines.push("");
539
- lines.push(...renderBoardSnapshot(this.details.board, width));
540
- }
541
-
542
- return lines;
543
- }
544
- }
545
-
546
- // End-of-game banner: two dim hrs, a big colored title line, and the final
547
- // board with the winning line highlighted.
548
- class GameOverMessageComponent implements Component {
549
- private readonly status: GameStatus;
550
- private readonly details: BoardDetails | undefined;
551
- private readonly theme: Theme;
552
-
553
- constructor(status: GameStatus, details: BoardDetails | undefined, theme: Theme) {
554
- this.status = status;
555
- this.details = details;
556
- this.theme = theme;
557
- }
558
-
559
- invalidate(): void {}
560
-
561
- render(width: number): string[] {
562
- const dim = (s: string) => this.theme.fg("dim", s);
563
- const bold = (s: string) => this.theme.bold(s);
564
-
565
- const hr = dim("\u2500".repeat(width));
566
- const lines: string[] = [];
567
- lines.push(hr);
568
- lines.push("");
569
-
570
- let title: string;
571
- let sub: string;
572
- switch (this.status) {
573
- case "win_X":
574
- title = bold(this.theme.fg("accent", "\u2605 Player X wins \u2605"));
575
- sub = "You beat the agent.";
576
- break;
577
- case "win_O":
578
- title = bold(this.theme.fg("warning", "\u2605 Player O wins \u2605"));
579
- sub = "The agent beat you.";
580
- break;
581
- case "draw":
582
- title = bold(this.theme.fg("muted", "\u2014 Draw \u2014"));
583
- sub = "No winner.";
584
- break;
585
- default:
586
- title = bold("Game over");
587
- sub = "";
588
- break;
589
- }
590
-
591
- for (const line of [title, dim(sub)]) {
592
- const pad = Math.max(0, width - visibleWidth(line));
593
- lines.push(`${" ".repeat(Math.floor(pad / 2))}${line}`);
594
- }
595
-
596
- lines.push("");
597
- if (this.details) {
598
- lines.push(...renderBoardSnapshot(this.details.board, width));
599
- lines.push("");
600
- }
601
- lines.push(hr);
602
-
603
- return lines;
604
- }
605
- }
606
-
607
- // ---------------------------------------------------------------------------
608
- // Delay helper
609
- // ---------------------------------------------------------------------------
610
-
611
- function delay(ms: number): Promise<void> {
612
- return new Promise((resolve) => setTimeout(resolve, ms));
613
- }
614
-
615
- // ---------------------------------------------------------------------------
616
- // Extension
617
- // ---------------------------------------------------------------------------
618
-
619
- const SAVE_TYPE = "tic-tac-toe-save";
620
- const MOVE_MESSAGE_TYPE = "tic-tac-toe-move";
621
- const GAME_OVER_MESSAGE_TYPE = "tic-tac-toe-game-over";
622
-
623
- let gameState: GameState = createInitialState();
624
- let component: TicTacToeComponent | null = null;
625
- let gameActive = false;
626
-
627
- function reconstructState(ctx: ExtensionContext): void {
628
- gameState = createInitialState();
629
- gameActive = false;
630
-
631
- for (const entry of ctx.sessionManager.getBranch()) {
632
- if (entry.type !== "message") continue;
633
- const msg = entry.message;
634
- if (msg.role !== "toolResult") continue;
635
- if (msg.toolName !== "tic_tac_toe" && msg.toolName !== "tic_tac_toe_see_board") continue;
636
-
637
- const details = msg.details as BoardDetails | undefined;
638
- if (details) {
639
- gameState.board = details.board.map((row) => [...row]);
640
- gameState.agentCursorRow = details.agentCursorRow;
641
- gameState.agentCursorCol = details.agentCursorCol;
642
- gameState.status = details.status;
643
- gameState.currentTurn = details.currentTurn;
644
- }
645
- }
646
- }
647
-
648
- function getBoardDetails(): BoardDetails {
649
- return {
650
- board: gameState.board.map((row) => [...row]),
651
- agentCursorRow: gameState.agentCursorRow,
652
- agentCursorCol: gameState.agentCursorCol,
653
- status: gameState.status,
654
- currentTurn: gameState.currentTurn,
655
- };
656
- }
657
-
658
- export default function (pi: ExtensionAPI) {
659
- pi.on("session_start", async (_event, ctx) => reconstructState(ctx));
660
- pi.on("session_tree", async (_event, ctx) => reconstructState(ctx));
661
-
662
- // Sent once per game at end-of-game. The custom renderer paints the banner;
663
- // `content` is a plain-text fallback for any non-TUI consumer and for the
664
- // LLM (in case the message ends up in future context).
665
- const emitGameOverMessage = (): void => {
666
- const label =
667
- gameState.status === "win_X"
668
- ? "Player X (human) wins"
669
- : gameState.status === "win_O"
670
- ? "Player O (agent) wins"
671
- : gameState.status === "draw"
672
- ? "Draw"
673
- : "Game over";
674
- pi.sendMessage({
675
- customType: GAME_OVER_MESSAGE_TYPE,
676
- content: `Game over: ${label}.`,
677
- display: true,
678
- details: getBoardDetails(),
679
- });
680
- };
681
-
682
- // -----------------------------------------------------------------------
683
- // Custom message renderer for user move messages
684
- // -----------------------------------------------------------------------
685
- pi.registerMessageRenderer(MOVE_MESSAGE_TYPE, (message, { expanded }, theme) => {
686
- const details = message.details as BoardDetails | undefined;
687
- const turnLabel =
688
- details?.currentTurn === "O"
689
- ? `${theme.fg("warning", theme.bold("O"))} (Agent)`
690
- : `${theme.fg("accent", theme.bold("X"))} (You)`;
691
- const title = `${theme.fg("accent", theme.bold("Player X played"))} ${theme.fg("dim", "\u2192")} next: ${turnLabel}`;
692
- return new BannerMessageComponent(title, details, expanded, theme);
693
- });
694
-
695
- // -----------------------------------------------------------------------
696
- // Custom message renderer for game-over messages
697
- // -----------------------------------------------------------------------
698
- pi.registerMessageRenderer(GAME_OVER_MESSAGE_TYPE, (message, _options, theme) => {
699
- const details = message.details as BoardDetails | undefined;
700
- const status = (details?.status ?? "draw") as GameStatus;
701
- return new GameOverMessageComponent(status, details, theme);
702
- });
703
-
704
- // -----------------------------------------------------------------------
705
- // before_agent_start - inject game instructions each turn
706
- // -----------------------------------------------------------------------
707
- pi.on("before_agent_start", async (event) => {
708
- if (!gameActive) return undefined;
709
-
710
- const instructions = `
711
-
712
- ## Tic-Tac-Toe (you are Player O)
713
-
714
- A tic-tac-toe game is in progress. The human is Player X. You are Player O.
715
- The human plays through a TUI; you play through the \`tic_tac_toe\` tool.
716
-
717
- ### Turn protocol
718
-
719
- When the human plays, you receive a message that contains the cell X marked,
720
- the full board, and YOUR cursor position (Player O's cursor). The message is
721
- the source of truth for the board.
722
-
723
- Player O's cursor persists between O turns. It is reset to (row=${AGENT_CURSOR_HOME_ROW}, col=${AGENT_CURSOR_HOME_COL})
724
- only after a successful \`play\`. If a \`play\` fails (cell already taken), the
725
- cursor stays where it was, so you can move and retry.
726
-
727
- You may also call \`tic_tac_toe_see_board\` if you want the current board and
728
- your cursor position restated at any point. The user's cursor is private and
729
- is never shown to you.
730
-
731
- ### The tool
732
-
733
- \`tic_tac_toe\` takes ONE action per call:
734
- - \`move_up\` / \`move_down\` / \`move_left\` / \`move_right\`: move YOUR cursor one cell (clamped at edges)
735
- - \`play\`: place O on the cell under YOUR cursor. Errors if the cell is not empty.
736
-
737
- There is no batched form. One call = one action.
738
-
739
- ### CRITICAL: emit the whole turn in a single response
740
-
741
- To play at (r, c) from your cursor (r0, c0) emit, in order:
742
- - \`move_down\` (r - r0) times (or \`move_up\` (r0 - r) times if r < r0)
743
- - \`move_right\` (c - c0) times (or \`move_left\` (c0 - c) times if c < c0)
744
- - one call of \`play\`
745
-
746
- All of these tool calls MUST be emitted in the SAME assistant response, as
747
- separate tool_use blocks, before you stop. Do not:
748
- - split the sequence across multiple assistant responses,
749
- - wait for a move result before emitting the next move or \`play\`,
750
- - write any explanation or text between the tool calls,
751
- - call any other tool during your turn (except \`tic_tac_toe_see_board\` when you
752
- explicitly need the state restated).
753
-
754
- Decide the target cell first, then dump every action for the turn in one go.
755
-
756
- ### Examples (cursor starts at (${AGENT_CURSOR_HOME_ROW}, ${AGENT_CURSOR_HOME_COL}))
757
-
758
- - Target (0,0): one call, \`play\`.
759
- - Target (0,2): \`move_right\`, \`move_right\`, \`play\`. Three calls, one response.
760
- - Target (1,1): \`move_down\`, \`move_right\`, \`play\`. Three calls, one response.
761
- - Target (2,2): \`move_down\`, \`move_down\`, \`move_right\`, \`move_right\`, \`play\`. Five calls, one response.
762
-
763
- ### Strategy
764
-
765
- 1. If you have two O's in a line with the third cell empty, win by playing there.
766
- 2. Otherwise, if X has two in a line with the third cell empty, block there.
767
- 3. Otherwise, prefer center, then corners, then edges.
768
- `;
769
-
770
- return {
771
- systemPrompt: event.systemPrompt + instructions,
772
- };
773
- });
774
-
775
- // -----------------------------------------------------------------------
776
- // /tic-tac-toe command
777
- // -----------------------------------------------------------------------
778
- pi.registerCommand("tic-tac-toe", {
779
- description: "Play tic-tac-toe against the agent",
780
-
781
- handler: async (_args, ctx) => {
782
- if (ctx.mode !== "tui") {
783
- ctx.ui.notify("Tic-tac-toe requires interactive mode", "error");
784
- return;
785
- }
786
-
787
- reconstructState(ctx);
788
- if (gameState.status !== "playing") {
789
- gameState = createInitialState();
790
- }
791
- gameActive = true;
792
- pi.setSessionName("Tic-Tac-Toe");
793
-
794
- await ctx.ui.custom<void>((tui, _theme, _kb, done) => {
795
- component = new TicTacToeComponent(
796
- tui,
797
- () => {
798
- component = null;
799
- gameActive = false;
800
- done(undefined);
801
- },
802
- (row, col) => {
803
- gameState.board[row][col] = gameState.userMark;
804
- gameState.status = checkWin(gameState.board);
805
- if (gameState.status === "playing") {
806
- gameState.currentTurn = gameState.agentMark;
807
- }
808
- component?.updateState(gameState);
809
- pi.appendEntry(SAVE_TYPE, getBoardDetails());
810
-
811
- if (gameState.status === "playing") {
812
- // IMPORTANT: user play does NOT touch the agent cursor.
813
- // The agent cursor is only reset after a successful agent play.
814
- const boardAscii = boardToAscii(
815
- gameState.board,
816
- gameState.agentCursorRow,
817
- gameState.agentCursorCol,
818
- );
819
- pi.sendMessage(
820
- {
821
- customType: MOVE_MESSAGE_TYPE,
822
- content:
823
- `Player X played at (row=${row}, col=${col}). It is now Player O's turn.\n\n` +
824
- `Board (your cursor marked with <>):\n${boardAscii}\n\n` +
825
- `Your cursor is at (row=${gameState.agentCursorRow}, col=${gameState.agentCursorCol}). ` +
826
- `Decide your target cell, then emit every move_* and the final play ` +
827
- `as separate tic_tac_toe tool calls in THIS response.`,
828
- display: true,
829
- details: getBoardDetails(),
830
- },
831
- { triggerTurn: true },
832
- );
833
- } else {
834
- emitGameOverMessage();
835
- gameActive = false;
836
- }
837
- },
838
- gameState,
839
- );
840
- return component;
841
- });
842
- },
843
- });
844
-
845
- // -----------------------------------------------------------------------
846
- // tic_tac_toe tool - one action per call.
847
- // -----------------------------------------------------------------------
848
-
849
- type Action = "move_up" | "move_down" | "move_left" | "move_right" | "play";
850
-
851
- const ACTION_DELAYS: Record<Action, number> = {
852
- move_up: 300,
853
- move_down: 300,
854
- move_left: 300,
855
- move_right: 300,
856
- play: 0,
857
- };
858
-
859
- pi.registerTool({
860
- name: "tic_tac_toe",
861
- label: "Tic-Tac-Toe",
862
- description:
863
- "Execute ONE tic-tac-toe action as Player O. `action` is exactly one of: move_up, move_down, move_left, move_right (move YOUR cursor one cell, clamped at edges), or play (place O under YOUR cursor; errors if the cell is not empty). There is no batched form. To play at (r, c) from your current cursor (r0, c0), emit the required move_down/move_up and move_right/move_left calls, then play, all as separate tool_use blocks in the SAME assistant response. Do not split the sequence across responses and do not wait for a result before emitting the next call. Your cursor position persists between turns and is reset to (0,0) only after a successful play.",
864
- promptSnippet: "Play a tic-tac-toe action (move_up/down/left/right or play) as Player O",
865
- promptGuidelines: [
866
- "When it is your tic-tac-toe turn, decide the target cell first, then emit every move_* plus the final play as separate tic_tac_toe tool calls in a SINGLE assistant response. Never split them across responses or wait for intermediate results.",
867
- "Never ask the user for the board. The board and your cursor position are included in the user's move message; use tic_tac_toe_see_board if you need them restated.",
868
- ],
869
- parameters: Type.Object({
870
- action: StringEnum(["move_up", "move_down", "move_left", "move_right", "play"] as const, {
871
- description:
872
- "The single action to perform this call. Emit multiple tic_tac_toe calls in one response to string actions together.",
873
- }),
874
- }),
875
- executionMode: "sequential" as ToolExecutionMode,
876
-
877
- async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
878
- const actionDelay = ACTION_DELAYS[params.action];
879
- if (actionDelay > 0) await delay(actionDelay);
880
-
881
- let result: string;
882
-
883
- switch (params.action) {
884
- case "move_up":
885
- if (gameState.agentCursorRow > 0) gameState.agentCursorRow--;
886
- result = `Moved up. Cursor: (${gameState.agentCursorRow}, ${gameState.agentCursorCol})`;
887
- break;
888
- case "move_down":
889
- if (gameState.agentCursorRow < 2) gameState.agentCursorRow++;
890
- result = `Moved down. Cursor: (${gameState.agentCursorRow}, ${gameState.agentCursorCol})`;
891
- break;
892
- case "move_left":
893
- if (gameState.agentCursorCol > 0) gameState.agentCursorCol--;
894
- result = `Moved left. Cursor: (${gameState.agentCursorRow}, ${gameState.agentCursorCol})`;
895
- break;
896
- case "move_right":
897
- if (gameState.agentCursorCol < 2) gameState.agentCursorCol++;
898
- result = `Moved right. Cursor: (${gameState.agentCursorRow}, ${gameState.agentCursorCol})`;
899
- break;
900
- case "play": {
901
- if (gameState.status !== "playing") {
902
- throw new TicTacToeError(`Game is over (${gameState.status}).`);
903
- }
904
- if (gameState.currentTurn !== gameState.agentMark) {
905
- throw new TicTacToeError("It is not your turn.");
906
- }
907
- const r = gameState.agentCursorRow;
908
- const c = gameState.agentCursorCol;
909
- if (gameState.board[r][c] !== " ") {
910
- // Do NOT reset the cursor on failure. The agent can retry
911
- // from the cursor's current position.
912
- component?.updateState(gameState);
913
- pi.appendEntry(SAVE_TYPE, getBoardDetails());
914
- throw new TicTacToeError(
915
- `Cell (${r},${c}) is already ${gameState.board[r][c]}. Your cursor is still at (${r},${c}). Move to an empty cell and retry play.`,
916
- );
917
- }
918
- gameState.board[r][c] = gameState.agentMark;
919
- gameState.status = checkWin(gameState.board);
920
- // Reset agent cursor to home ONLY on successful play.
921
- gameState.agentCursorRow = AGENT_CURSOR_HOME_ROW;
922
- gameState.agentCursorCol = AGENT_CURSOR_HOME_COL;
923
- if (gameState.status === "playing") {
924
- gameState.currentTurn = gameState.userMark;
925
- result = `Placed O at (${r},${c}). Cursor reset to (${AGENT_CURSOR_HOME_ROW},${AGENT_CURSOR_HOME_COL}). Your turn, X!`;
926
- } else if (gameState.status === "win_O") {
927
- result = `Placed O at (${r},${c}). Player O wins!`;
928
- gameActive = false;
929
- emitGameOverMessage();
930
- } else if (gameState.status === "draw") {
931
- result = `Placed O at (${r},${c}). It's a draw!`;
932
- gameActive = false;
933
- emitGameOverMessage();
934
- } else {
935
- result = `Placed O at (${r},${c}).`;
936
- }
937
- break;
938
- }
939
- }
940
-
941
- component?.updateState(gameState);
942
- pi.appendEntry(SAVE_TYPE, getBoardDetails());
943
-
944
- return {
945
- content: [{ type: "text", text: result }],
946
- details: getBoardDetails(),
947
- };
948
- },
949
-
950
- renderCall(args, theme) {
951
- const action = typeof args.action === "string" ? args.action : "";
952
- return new Text(theme.fg("toolTitle", theme.bold("tic_tac_toe ")) + theme.fg("muted", action), 0, 0);
953
- },
954
-
955
- renderResult(result, { expanded }, theme, context) {
956
- const details = result.details as BoardDetails | undefined;
957
- const text = result.content[0];
958
- const msg = text?.type === "text" ? text.text : "";
959
- const prefix = context?.isError ? theme.fg("error", "\u2717 ") : theme.fg("success", "\u2713 ");
960
- const summary = prefix + theme.fg("muted", msg);
961
-
962
- if (expanded && details) {
963
- return new BannerMessageComponent(summary, details, true, theme);
964
- }
965
- return new Text(summary, 0, 0);
966
- },
967
- });
968
-
969
- // -----------------------------------------------------------------------
970
- // tic_tac_toe_see_board tool - inspect board + agent cursor.
971
- // -----------------------------------------------------------------------
972
- pi.registerTool({
973
- name: "tic_tac_toe_see_board",
974
- label: "See Board",
975
- description:
976
- "Return the current tic-tac-toe board state and YOUR cursor position (Player O). Takes no arguments. Use this if you need the current state restated mid-turn (for example after a failed play). The user's cursor is never exposed.",
977
- promptSnippet: "Inspect the tic-tac-toe board and your cursor",
978
- parameters: Type.Object({}),
979
-
980
- async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
981
- const boardAscii = boardToAscii(gameState.board, gameState.agentCursorRow, gameState.agentCursorCol);
982
- const text =
983
- `Board (your cursor marked with <>):\n${boardAscii}\n\n` +
984
- `Your cursor: (row=${gameState.agentCursorRow}, col=${gameState.agentCursorCol})\n` +
985
- `Status: ${gameState.status}\n` +
986
- `Turn: ${gameState.currentTurn === gameState.agentMark ? "Player O (you)" : "Player X"}`;
987
- return {
988
- content: [{ type: "text", text }],
989
- details: getBoardDetails(),
990
- };
991
- },
992
-
993
- renderCall(_args, theme) {
994
- return new Text(theme.fg("toolTitle", theme.bold("tic_tac_toe_see_board")), 0, 0);
995
- },
996
-
997
- renderResult(result, { expanded }, theme) {
998
- const details = result.details as BoardDetails | undefined;
999
- const summary =
1000
- theme.fg("success", "\u2713 ") +
1001
- theme.fg("muted", `cursor (${details?.agentCursorRow ?? 0},${details?.agentCursorCol ?? 0})`);
1002
- if (expanded && details) {
1003
- return new BannerMessageComponent(summary, details, true, theme);
1004
- }
1005
- return new Text(summary, 0, 0);
1006
- },
1007
- });
1008
- }
1
+ /**
2
+ * Tic-Tac-Toe extension - demonstrates executionMode: "sequential" on tools.
3
+ *
4
+ * The user plays via /tic-tac-toe (arrow keys + Enter).
5
+ * The agent plays via a single tool `tic_tac_toe` that takes ONE atomic action
6
+ * per call. To play at (r, c) from its cursor (r0, c0) the agent must emit the
7
+ * required move_* and a final `play` as SEPARATE tool_use blocks inside ONE
8
+ * assistant response.
9
+ *
10
+ * Move actions share the agent cursor and have a 300ms delay. Under the
11
+ * default parallel tool-execution mode this races: `play` can resolve before
12
+ * the earlier `move_*` calls finish and O lands on the wrong cell. With
13
+ * `executionMode: "sequential"` the runner serializes the sibling calls and O
14
+ * lands on the intended cell.
15
+ *
16
+ * The user cursor (TUI-only) and the agent cursor (tool-only) are stored in
17
+ * separate variables. Only the agent cursor is ever exposed to the agent.
18
+ */
19
+
20
+ import { StringEnum } from "@earendil-works/pi-ai";
21
+ import type { ExtensionAPI, ExtensionContext, Theme, ToolExecutionMode } from "@earendil-works/pi-coding-agent";
22
+ import { type Component, matchesKey, Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
23
+ import { Type } from "typebox";
24
+
25
+ // Thrown from the tool on illegal actions. The agent runtime surfaces thrown
26
+ // errors as tool errors (isError=true) without resetting any of our state.
27
+ class TicTacToeError extends Error {
28
+ constructor(message: string) {
29
+ super(message);
30
+ this.name = "TicTacToeError";
31
+ }
32
+ }
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // Types
36
+ // ---------------------------------------------------------------------------
37
+
38
+ type Cell = " " | "X" | "O";
39
+ type GameStatus = "playing" | "win_X" | "win_O" | "draw";
40
+
41
+ interface GameState {
42
+ board: Cell[][];
43
+ // User cursor (TUI-only, never exposed to the agent).
44
+ userCursorRow: number;
45
+ userCursorCol: number;
46
+ // Agent cursor (manipulated by the tool, shown in the TUI during O's turn).
47
+ agentCursorRow: number;
48
+ agentCursorCol: number;
49
+ status: GameStatus;
50
+ userMark: Cell;
51
+ agentMark: Cell;
52
+ currentTurn: Cell;
53
+ }
54
+
55
+ // Persisted with each toolResult for state reconstruction AND sent to the
56
+ // agent as `details`. Only the agent cursor is included: the user cursor is
57
+ // private to the TUI.
58
+ interface BoardDetails {
59
+ board: Cell[][];
60
+ agentCursorRow: number;
61
+ agentCursorCol: number;
62
+ status: GameStatus;
63
+ currentTurn: Cell;
64
+ }
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // Game logic
68
+ // ---------------------------------------------------------------------------
69
+
70
+ // Agent cursor home: where the cursor is reset to after a SUCCESSFUL play.
71
+ // Pinned at (0,0) so every non-origin play requires at least one move, which
72
+ // guarantees multiple tool calls per turn and makes the parallel-vs-sequential
73
+ // behavior observable in the demo. The cursor is NOT reset when the user plays
74
+ // nor on a failed `play` (cell taken), so the agent can retry without
75
+ // starting over.
76
+ const AGENT_CURSOR_HOME_ROW = 0;
77
+ const AGENT_CURSOR_HOME_COL = 0;
78
+
79
+ function createInitialState(): GameState {
80
+ return {
81
+ board: [
82
+ [" ", " ", " "],
83
+ [" ", " ", " "],
84
+ [" ", " ", " "],
85
+ ],
86
+ userCursorRow: 1,
87
+ userCursorCol: 1,
88
+ agentCursorRow: AGENT_CURSOR_HOME_ROW,
89
+ agentCursorCol: AGENT_CURSOR_HOME_COL,
90
+ status: "playing",
91
+ userMark: "X",
92
+ agentMark: "O",
93
+ currentTurn: "X",
94
+ };
95
+ }
96
+
97
+ function getWinLine(board: Cell[][]): [number, number][] | null {
98
+ const lines: [number, number][][] = [
99
+ [
100
+ [0, 0],
101
+ [0, 1],
102
+ [0, 2],
103
+ ],
104
+ [
105
+ [1, 0],
106
+ [1, 1],
107
+ [1, 2],
108
+ ],
109
+ [
110
+ [2, 0],
111
+ [2, 1],
112
+ [2, 2],
113
+ ],
114
+ [
115
+ [0, 0],
116
+ [1, 0],
117
+ [2, 0],
118
+ ],
119
+ [
120
+ [0, 1],
121
+ [1, 1],
122
+ [2, 1],
123
+ ],
124
+ [
125
+ [0, 2],
126
+ [1, 2],
127
+ [2, 2],
128
+ ],
129
+ [
130
+ [0, 0],
131
+ [1, 1],
132
+ [2, 2],
133
+ ],
134
+ [
135
+ [0, 2],
136
+ [1, 1],
137
+ [2, 0],
138
+ ],
139
+ ];
140
+ for (const line of lines) {
141
+ const vals = line.map(([r, c]) => board[r][c]);
142
+ if (vals[0] !== " " && vals[0] === vals[1] && vals[1] === vals[2]) {
143
+ return line;
144
+ }
145
+ }
146
+ return null;
147
+ }
148
+
149
+ function checkWin(board: Cell[][]): GameStatus {
150
+ const winLine = getWinLine(board);
151
+ if (winLine) {
152
+ const [r, c] = winLine[0];
153
+ return board[r][c] === "X" ? "win_X" : "win_O";
154
+ }
155
+ if (board.every((row) => row.every((c) => c !== " "))) {
156
+ return "draw";
157
+ }
158
+ return "playing";
159
+ }
160
+
161
+ function boardToAscii(board: Cell[][], agentCursorRow: number, agentCursorCol: number): string {
162
+ // Plain grid with coordinates for empty cells, marking the agent cursor
163
+ // position with angle brackets. The user cursor is NEVER included: it is a
164
+ // TUI-only concept and must not leak to the agent.
165
+ const rows = board.map((row, r) =>
166
+ row
167
+ .map((c, cIdx) => {
168
+ const onCursor = r === agentCursorRow && cIdx === agentCursorCol;
169
+ if (c === " ") return onCursor ? `<[${r},${cIdx}]>` : ` [${r},${cIdx}] `;
170
+ return onCursor ? ` <${c}> ` : ` ${c} `;
171
+ })
172
+ .join("|"),
173
+ );
174
+ const separator = "---------+---------+---------";
175
+ return rows.join(`\n${separator}\n`);
176
+ }
177
+
178
+ // ---------------------------------------------------------------------------
179
+ // Visual board rendering (ANSI).
180
+ // - Cells have NO background fill. Only the centered glyph is drawn.
181
+ // - Played cells color their glyph AND their surrounding borders in the
182
+ // player's color, so each mark reads as a colored boxed region.
183
+ // - Cursor is indicated with colored borders around the cursor cell.
184
+ // ---------------------------------------------------------------------------
185
+
186
+ const CELL_WIDTH = 7;
187
+ const CELL_HEIGHT = 3;
188
+
189
+ // Player colors (SGR fg codes). Also used for the borders of played cells.
190
+ const FG_CODE_X = "34"; // blue
191
+ const FG_CODE_O = "33"; // yellow
192
+ const FG_CODE_WIN = "32"; // green (overrides on the winning line)
193
+
194
+ // Single-character glyphs, picked for maximum visual size without emoji.
195
+ // - \u2573 (BOX DRAWINGS LIGHT DIAGONAL CROSS) for X
196
+ // - \u25ef (LARGE CIRCLE) for O
197
+ const GLYPH_X = "\u2573";
198
+ const GLYPH_O = "\u25ef";
199
+
200
+ const DIM = (s: string) => `\x1b[2m${s}\x1b[22m`;
201
+ const RESET = "\x1b[0m";
202
+
203
+ function centerPad(content: string, width: number): string {
204
+ const contentLen = visibleWidth(content);
205
+ if (contentLen >= width) return truncateToWidth(content, width);
206
+ const pad = width - contentLen;
207
+ const left = Math.floor(pad / 2);
208
+ return " ".repeat(left) + content + " ".repeat(pad - left);
209
+ }
210
+
211
+ // Fg color for a played cell's glyph and its surrounding borders. Undefined
212
+ // for empty cells.
213
+ function cellFgCode(cell: Cell, isWin: boolean): string | undefined {
214
+ if (cell === " ") return undefined;
215
+ if (isWin) return FG_CODE_WIN;
216
+ return cell === "X" ? FG_CODE_X : FG_CODE_O;
217
+ }
218
+
219
+ function buildCellContent(mark: Cell, lineIdx: number, isWin: boolean): string {
220
+ const empty = " ".repeat(CELL_WIDTH);
221
+ if (mark === " ") return empty;
222
+
223
+ const isMidLine = lineIdx === Math.floor(CELL_HEIGHT / 2);
224
+ if (!isMidLine) return empty;
225
+
226
+ const glyph = mark === "X" ? GLYPH_X : GLYPH_O;
227
+ const fg = cellFgCode(mark, isWin) as string;
228
+ const padLen = CELL_WIDTH - visibleWidth(glyph);
229
+ const leftPad = Math.floor(padLen / 2);
230
+ const rightPad = padLen - leftPad;
231
+ return `${" ".repeat(leftPad)}\x1b[${fg};1m${glyph}${RESET}${" ".repeat(rightPad)}`;
232
+ }
233
+
234
+ // Fg color for a border char based on its adjacent cells. Undefined when no
235
+ // adjacent cell is played or when adjacent plays disagree (border stays dim
236
+ // to show the separation).
237
+ function borderFgCode(adjacent: ReadonlyArray<{ cell: Cell; isWin: boolean }>): string | undefined {
238
+ const fgs = adjacent.map((a) => cellFgCode(a.cell, a.isWin)).filter((f): f is string => !!f);
239
+ if (fgs.length === 0) return undefined;
240
+ const first = fgs[0];
241
+ return fgs.every((f) => f === first) ? first : undefined;
242
+ }
243
+
244
+ interface BoardRenderOpts {
245
+ board: Cell[][];
246
+ maxWidth: number;
247
+ // Optional cursor overlay. Omit to render a static snapshot (used in tool
248
+ // results, move messages, and the game-over banner).
249
+ cursor?: { row: number; col: number; owner: "user" | "agent" };
250
+ }
251
+
252
+ function renderBoard(opts: BoardRenderOpts): string[] {
253
+ const { board, maxWidth, cursor } = opts;
254
+ const showCursor = !!cursor;
255
+ const cr = cursor?.row ?? -1;
256
+ const cc = cursor?.col ?? -1;
257
+
258
+ // Green for user cursor, yellow for agent cursor.
259
+ const cursorSgr = cursor?.owner === "agent" ? "\x1b[33;1m" : "\x1b[32;1m";
260
+
261
+ const winLine = getWinLine(board);
262
+ const winCells = new Set((winLine ?? []).map(([r, c]) => `${r},${c}`));
263
+ const cellAt = (r: number, c: number) => ({ cell: board[r][c], isWin: winCells.has(`${r},${c}`) });
264
+
265
+ const isCursorCorner = (gridR: number, gridC: number): boolean =>
266
+ showCursor && (gridR === cr || gridR === cr + 1) && (gridC === cc || gridC === cc + 1);
267
+ const isCursorHSegment = (gridR: number, c: number): boolean =>
268
+ showCursor && c === cc && (gridR === cr || gridR === cr + 1);
269
+ const isCursorVBorder = (r: number, gridC: number): boolean =>
270
+ showCursor && r === cr && (gridC === cc || gridC === cc + 1);
271
+
272
+ const paintBorder = (ch: string, highlighted: boolean, fgCode: string | undefined): string => {
273
+ if (highlighted) return `${cursorSgr}${ch}${RESET}`;
274
+ if (fgCode) return `\x1b[${fgCode};1m${ch}${RESET}`;
275
+ return DIM(ch);
276
+ };
277
+
278
+ const cornerChar = (gridR: number, gridC: number): string => {
279
+ if (gridR === 0 && gridC === 0) return "\u250c";
280
+ if (gridR === 0 && gridC === 3) return "\u2510";
281
+ if (gridR === 3 && gridC === 0) return "\u2514";
282
+ if (gridR === 3 && gridC === 3) return "\u2518";
283
+ if (gridR === 0) return "\u252c";
284
+ if (gridR === 3) return "\u2534";
285
+ if (gridC === 0) return "\u251c";
286
+ if (gridC === 3) return "\u2524";
287
+ return "\u253c";
288
+ };
289
+
290
+ const cornerAdjacent = (gridR: number, gridC: number) => {
291
+ const out: { cell: Cell; isWin: boolean }[] = [];
292
+ for (const [dr, dc] of [
293
+ [-1, -1],
294
+ [-1, 0],
295
+ [0, -1],
296
+ [0, 0],
297
+ ]) {
298
+ const r = gridR + dr;
299
+ const c = gridC + dc;
300
+ if (r >= 0 && r < 3 && c >= 0 && c < 3) out.push(cellAt(r, c));
301
+ }
302
+ return out;
303
+ };
304
+
305
+ const lines: string[] = [];
306
+
307
+ for (let gridR = 0; gridR <= 3; gridR++) {
308
+ // Horizontal border row.
309
+ let row = "";
310
+ for (let gridC = 0; gridC <= 3; gridC++) {
311
+ const cornerColor = borderFgCode(cornerAdjacent(gridR, gridC));
312
+ row += paintBorder(cornerChar(gridR, gridC), isCursorCorner(gridR, gridC), cornerColor);
313
+ if (gridC < 3) {
314
+ const adj: { cell: Cell; isWin: boolean }[] = [];
315
+ if (gridR > 0) adj.push(cellAt(gridR - 1, gridC));
316
+ if (gridR < 3) adj.push(cellAt(gridR, gridC));
317
+ const segColor = borderFgCode(adj);
318
+ row += paintBorder("\u2500".repeat(CELL_WIDTH), isCursorHSegment(gridR, gridC), segColor);
319
+ }
320
+ }
321
+ lines.push(centerPad(row, maxWidth));
322
+
323
+ if (gridR === 3) break;
324
+
325
+ for (let lineIdx = 0; lineIdx < CELL_HEIGHT; lineIdx++) {
326
+ let contentRow = "";
327
+ for (let gridC = 0; gridC <= 3; gridC++) {
328
+ const adj: { cell: Cell; isWin: boolean }[] = [];
329
+ if (gridC > 0) adj.push(cellAt(gridR, gridC - 1));
330
+ if (gridC < 3) adj.push(cellAt(gridR, gridC));
331
+ const vColor = borderFgCode(adj);
332
+ contentRow += paintBorder("\u2502", isCursorVBorder(gridR, gridC), vColor);
333
+ if (gridC < 3) {
334
+ contentRow += buildCellContent(board[gridR][gridC], lineIdx, winCells.has(`${gridR},${gridC}`));
335
+ }
336
+ }
337
+ lines.push(centerPad(contentRow, maxWidth));
338
+ }
339
+ }
340
+
341
+ return lines;
342
+ }
343
+
344
+ // Full TUI board with the right cursor overlayed for the current turn.
345
+ function renderVisualBoard(state: GameState, maxWidth: number): string[] {
346
+ const isUserTurn = state.currentTurn === state.userMark;
347
+ const cursor =
348
+ state.status !== "playing"
349
+ ? undefined
350
+ : {
351
+ row: isUserTurn ? state.userCursorRow : state.agentCursorRow,
352
+ col: isUserTurn ? state.userCursorCol : state.agentCursorCol,
353
+ owner: (isUserTurn ? "user" : "agent") as "user" | "agent",
354
+ };
355
+ return renderBoard({ board: state.board, maxWidth, cursor });
356
+ }
357
+
358
+ /** Static snapshot used inside tool results and custom messages. */
359
+ function renderBoardSnapshot(board: Cell[][], maxWidth: number): string[] {
360
+ return renderBoard({ board, maxWidth });
361
+ }
362
+
363
+ // ---------------------------------------------------------------------------
364
+ // TUI component
365
+ // ---------------------------------------------------------------------------
366
+
367
+ class TicTacToeComponent implements Component {
368
+ private state: GameState;
369
+ private onClose: () => void;
370
+ private onUserPlay: (row: number, col: number) => void;
371
+ private tui: { requestRender: () => void };
372
+ private cachedLines: string[] = [];
373
+ private cachedWidth = 0;
374
+ private version = 0;
375
+ private cachedVersion = -1;
376
+
377
+ constructor(
378
+ tui: { requestRender: () => void },
379
+ onClose: () => void,
380
+ onUserPlay: (row: number, col: number) => void,
381
+ state: GameState,
382
+ ) {
383
+ this.tui = tui;
384
+ this.onClose = onClose;
385
+ this.onUserPlay = onUserPlay;
386
+ this.state = state;
387
+ }
388
+
389
+ updateState(state: GameState): void {
390
+ this.state = state;
391
+ this.version++;
392
+ this.tui.requestRender();
393
+ }
394
+
395
+ handleInput(data: string): boolean {
396
+ if (matchesKey(data, "escape") || data === "q" || data === "Q") {
397
+ this.onClose();
398
+ return true;
399
+ }
400
+ if (this.state.status !== "playing") {
401
+ if (data === "r" || data === "R") {
402
+ this.onClose();
403
+ return true;
404
+ }
405
+ return true;
406
+ }
407
+ if (this.state.currentTurn !== this.state.userMark) return true;
408
+
409
+ if (matchesKey(data, "up") && this.state.userCursorRow > 0) {
410
+ this.state.userCursorRow--;
411
+ this.version++;
412
+ this.tui.requestRender();
413
+ } else if (matchesKey(data, "down") && this.state.userCursorRow < 2) {
414
+ this.state.userCursorRow++;
415
+ this.version++;
416
+ this.tui.requestRender();
417
+ } else if (matchesKey(data, "left") && this.state.userCursorCol > 0) {
418
+ this.state.userCursorCol--;
419
+ this.version++;
420
+ this.tui.requestRender();
421
+ } else if (matchesKey(data, "right") && this.state.userCursorCol < 2) {
422
+ this.state.userCursorCol++;
423
+ this.version++;
424
+ this.tui.requestRender();
425
+ } else if (matchesKey(data, "return") || data === " ") {
426
+ const { userCursorRow, userCursorCol } = this.state;
427
+ if (this.state.board[userCursorRow][userCursorCol] === " ") {
428
+ this.onUserPlay(userCursorRow, userCursorCol);
429
+ }
430
+ }
431
+ return true;
432
+ }
433
+
434
+ invalidate(): void {
435
+ this.cachedWidth = 0;
436
+ }
437
+
438
+ render(width: number): string[] {
439
+ if (width === this.cachedWidth && this.cachedVersion === this.version) {
440
+ return this.cachedLines;
441
+ }
442
+
443
+ const ESC = "\x1b[";
444
+ const reset = `${ESC}0m`;
445
+ const bold = (s: string) => `${ESC}1m${s}${reset}`;
446
+ const dim = (s: string) => `${ESC}2m${s}${reset}`;
447
+ const blue = (s: string) => `${ESC}34m${s}${reset}`;
448
+ const yellow = (s: string) => `${ESC}33m${s}${reset}`;
449
+ const green = (s: string) => `${ESC}32m${s}${reset}`;
450
+
451
+ const lines: string[] = [];
452
+
453
+ // Top title banner, full width.
454
+ const titleText = " Tic-Tac-Toe ";
455
+ const titleLen = visibleWidth(titleText);
456
+ const borderLen = Math.max(0, width - titleLen);
457
+ const leftBorder = Math.floor(borderLen / 2);
458
+ const rightBorder = borderLen - leftBorder;
459
+ lines.push(dim("\u2500".repeat(leftBorder)) + bold(blue(titleText)) + dim("\u2500".repeat(rightBorder)));
460
+
461
+ lines.push("");
462
+
463
+ // Status line.
464
+ if (this.state.status !== "playing") {
465
+ const statusText =
466
+ this.state.status === "draw"
467
+ ? bold(yellow("Draw!"))
468
+ : this.state.status === "win_X"
469
+ ? bold(green("X wins!"))
470
+ : bold(yellow("O wins!"));
471
+ lines.push(centerPad(statusText, width));
472
+ } else if (this.state.currentTurn === "X") {
473
+ lines.push(centerPad(`Turn: ${bold(blue("X"))} (You) ${dim("|")} ${bold(yellow("O"))} (Agent)`, width));
474
+ } else {
475
+ lines.push(centerPad(`${blue("X")} (You) ${dim("|")} Turn: ${bold(yellow("O"))} (Agent)`, width));
476
+ }
477
+
478
+ lines.push("");
479
+ lines.push("");
480
+
481
+ lines.push(...renderVisualBoard(this.state, width));
482
+
483
+ lines.push("");
484
+ lines.push("");
485
+
486
+ // Footer.
487
+ let footer: string;
488
+ if (this.state.status !== "playing") {
489
+ footer = `${bold("R")} restart ${dim("|")} ${bold("Q")}/${bold("ESC")} quit`;
490
+ } else if (this.state.currentTurn !== this.state.userMark) {
491
+ footer = dim("Agent is thinking...");
492
+ } else {
493
+ footer = `${bold("\u2190\u2191\u2193\u2192")} move ${dim("|")} ${bold("ENTER")} play ${dim("|")} ${bold("ESC")} quit`;
494
+ }
495
+ lines.push(centerPad(footer, width));
496
+
497
+ // Bottom separator between the component and the editor below.
498
+ lines.push("");
499
+ lines.push(dim("\u2500".repeat(width)));
500
+
501
+ this.cachedLines = lines;
502
+ this.cachedWidth = width;
503
+ this.cachedVersion = this.version;
504
+ return lines;
505
+ }
506
+ }
507
+
508
+ // ---------------------------------------------------------------------------
509
+ // Move-message renderer (full width banner)
510
+ // ---------------------------------------------------------------------------
511
+
512
+ // Full-width banner message with an optional board snapshot underneath.
513
+ class BannerMessageComponent implements Component {
514
+ private readonly title: string;
515
+ private readonly details: BoardDetails | undefined;
516
+ private readonly expanded: boolean;
517
+ private readonly theme: Theme;
518
+
519
+ constructor(title: string, details: BoardDetails | undefined, expanded: boolean, theme: Theme) {
520
+ this.title = title;
521
+ this.details = details;
522
+ this.expanded = expanded;
523
+ this.theme = theme;
524
+ }
525
+
526
+ invalidate(): void {}
527
+
528
+ render(width: number): string[] {
529
+ const dim = (s: string) => this.theme.fg("dim", s);
530
+ const lines: string[] = [];
531
+ const titleLen = visibleWidth(this.title);
532
+ const fillLen = Math.max(0, width - titleLen - 2);
533
+ const leftFill = Math.floor(fillLen / 2);
534
+ const rightFill = fillLen - leftFill;
535
+ lines.push(`${dim("\u2500".repeat(leftFill))} ${this.title} ${dim("\u2500".repeat(rightFill))}`);
536
+
537
+ if (this.expanded && this.details) {
538
+ lines.push("");
539
+ lines.push(...renderBoardSnapshot(this.details.board, width));
540
+ }
541
+
542
+ return lines;
543
+ }
544
+ }
545
+
546
+ // End-of-game banner: two dim hrs, a big colored title line, and the final
547
+ // board with the winning line highlighted.
548
+ class GameOverMessageComponent implements Component {
549
+ private readonly status: GameStatus;
550
+ private readonly details: BoardDetails | undefined;
551
+ private readonly theme: Theme;
552
+
553
+ constructor(status: GameStatus, details: BoardDetails | undefined, theme: Theme) {
554
+ this.status = status;
555
+ this.details = details;
556
+ this.theme = theme;
557
+ }
558
+
559
+ invalidate(): void {}
560
+
561
+ render(width: number): string[] {
562
+ const dim = (s: string) => this.theme.fg("dim", s);
563
+ const bold = (s: string) => this.theme.bold(s);
564
+
565
+ const hr = dim("\u2500".repeat(width));
566
+ const lines: string[] = [];
567
+ lines.push(hr);
568
+ lines.push("");
569
+
570
+ let title: string;
571
+ let sub: string;
572
+ switch (this.status) {
573
+ case "win_X":
574
+ title = bold(this.theme.fg("accent", "\u2605 Player X wins \u2605"));
575
+ sub = "You beat the agent.";
576
+ break;
577
+ case "win_O":
578
+ title = bold(this.theme.fg("warning", "\u2605 Player O wins \u2605"));
579
+ sub = "The agent beat you.";
580
+ break;
581
+ case "draw":
582
+ title = bold(this.theme.fg("muted", "\u2014 Draw \u2014"));
583
+ sub = "No winner.";
584
+ break;
585
+ default:
586
+ title = bold("Game over");
587
+ sub = "";
588
+ break;
589
+ }
590
+
591
+ for (const line of [title, dim(sub)]) {
592
+ const pad = Math.max(0, width - visibleWidth(line));
593
+ lines.push(`${" ".repeat(Math.floor(pad / 2))}${line}`);
594
+ }
595
+
596
+ lines.push("");
597
+ if (this.details) {
598
+ lines.push(...renderBoardSnapshot(this.details.board, width));
599
+ lines.push("");
600
+ }
601
+ lines.push(hr);
602
+
603
+ return lines;
604
+ }
605
+ }
606
+
607
+ // ---------------------------------------------------------------------------
608
+ // Delay helper
609
+ // ---------------------------------------------------------------------------
610
+
611
+ function delay(ms: number): Promise<void> {
612
+ return new Promise((resolve) => setTimeout(resolve, ms));
613
+ }
614
+
615
+ // ---------------------------------------------------------------------------
616
+ // Extension
617
+ // ---------------------------------------------------------------------------
618
+
619
+ const SAVE_TYPE = "tic-tac-toe-save";
620
+ const MOVE_MESSAGE_TYPE = "tic-tac-toe-move";
621
+ const GAME_OVER_MESSAGE_TYPE = "tic-tac-toe-game-over";
622
+
623
+ let gameState: GameState = createInitialState();
624
+ let component: TicTacToeComponent | null = null;
625
+ let gameActive = false;
626
+
627
+ function reconstructState(ctx: ExtensionContext): void {
628
+ gameState = createInitialState();
629
+ gameActive = false;
630
+
631
+ for (const entry of ctx.sessionManager.getBranch()) {
632
+ if (entry.type !== "message") continue;
633
+ const msg = entry.message;
634
+ if (msg.role !== "toolResult") continue;
635
+ if (msg.toolName !== "tic_tac_toe" && msg.toolName !== "tic_tac_toe_see_board") continue;
636
+
637
+ const details = msg.details as BoardDetails | undefined;
638
+ if (details) {
639
+ gameState.board = details.board.map((row) => [...row]);
640
+ gameState.agentCursorRow = details.agentCursorRow;
641
+ gameState.agentCursorCol = details.agentCursorCol;
642
+ gameState.status = details.status;
643
+ gameState.currentTurn = details.currentTurn;
644
+ }
645
+ }
646
+ }
647
+
648
+ function getBoardDetails(): BoardDetails {
649
+ return {
650
+ board: gameState.board.map((row) => [...row]),
651
+ agentCursorRow: gameState.agentCursorRow,
652
+ agentCursorCol: gameState.agentCursorCol,
653
+ status: gameState.status,
654
+ currentTurn: gameState.currentTurn,
655
+ };
656
+ }
657
+
658
+ export default function (pi: ExtensionAPI) {
659
+ pi.on("session_start", async (_event, ctx) => reconstructState(ctx));
660
+ pi.on("session_tree", async (_event, ctx) => reconstructState(ctx));
661
+
662
+ // Sent once per game at end-of-game. The custom renderer paints the banner;
663
+ // `content` is a plain-text fallback for any non-TUI consumer and for the
664
+ // LLM (in case the message ends up in future context).
665
+ const emitGameOverMessage = (): void => {
666
+ const label =
667
+ gameState.status === "win_X"
668
+ ? "Player X (human) wins"
669
+ : gameState.status === "win_O"
670
+ ? "Player O (agent) wins"
671
+ : gameState.status === "draw"
672
+ ? "Draw"
673
+ : "Game over";
674
+ pi.sendMessage({
675
+ customType: GAME_OVER_MESSAGE_TYPE,
676
+ content: `Game over: ${label}.`,
677
+ display: true,
678
+ details: getBoardDetails(),
679
+ });
680
+ };
681
+
682
+ // -----------------------------------------------------------------------
683
+ // Custom message renderer for user move messages
684
+ // -----------------------------------------------------------------------
685
+ pi.registerMessageRenderer(MOVE_MESSAGE_TYPE, (message, { expanded }, theme) => {
686
+ const details = message.details as BoardDetails | undefined;
687
+ const turnLabel =
688
+ details?.currentTurn === "O"
689
+ ? `${theme.fg("warning", theme.bold("O"))} (Agent)`
690
+ : `${theme.fg("accent", theme.bold("X"))} (You)`;
691
+ const title = `${theme.fg("accent", theme.bold("Player X played"))} ${theme.fg("dim", "\u2192")} next: ${turnLabel}`;
692
+ return new BannerMessageComponent(title, details, expanded, theme);
693
+ });
694
+
695
+ // -----------------------------------------------------------------------
696
+ // Custom message renderer for game-over messages
697
+ // -----------------------------------------------------------------------
698
+ pi.registerMessageRenderer(GAME_OVER_MESSAGE_TYPE, (message, _options, theme) => {
699
+ const details = message.details as BoardDetails | undefined;
700
+ const status = (details?.status ?? "draw") as GameStatus;
701
+ return new GameOverMessageComponent(status, details, theme);
702
+ });
703
+
704
+ // -----------------------------------------------------------------------
705
+ // before_agent_start - inject game instructions each turn
706
+ // -----------------------------------------------------------------------
707
+ pi.on("before_agent_start", async (event) => {
708
+ if (!gameActive) return undefined;
709
+
710
+ const instructions = `
711
+
712
+ ## Tic-Tac-Toe (you are Player O)
713
+
714
+ A tic-tac-toe game is in progress. The human is Player X. You are Player O.
715
+ The human plays through a TUI; you play through the \`tic_tac_toe\` tool.
716
+
717
+ ### Turn protocol
718
+
719
+ When the human plays, you receive a message that contains the cell X marked,
720
+ the full board, and YOUR cursor position (Player O's cursor). The message is
721
+ the source of truth for the board.
722
+
723
+ Player O's cursor persists between O turns. It is reset to (row=${AGENT_CURSOR_HOME_ROW}, col=${AGENT_CURSOR_HOME_COL})
724
+ only after a successful \`play\`. If a \`play\` fails (cell already taken), the
725
+ cursor stays where it was, so you can move and retry.
726
+
727
+ You may also call \`tic_tac_toe_see_board\` if you want the current board and
728
+ your cursor position restated at any point. The user's cursor is private and
729
+ is never shown to you.
730
+
731
+ ### The tool
732
+
733
+ \`tic_tac_toe\` takes ONE action per call:
734
+ - \`move_up\` / \`move_down\` / \`move_left\` / \`move_right\`: move YOUR cursor one cell (clamped at edges)
735
+ - \`play\`: place O on the cell under YOUR cursor. Errors if the cell is not empty.
736
+
737
+ There is no batched form. One call = one action.
738
+
739
+ ### CRITICAL: emit the whole turn in a single response
740
+
741
+ To play at (r, c) from your cursor (r0, c0) emit, in order:
742
+ - \`move_down\` (r - r0) times (or \`move_up\` (r0 - r) times if r < r0)
743
+ - \`move_right\` (c - c0) times (or \`move_left\` (c0 - c) times if c < c0)
744
+ - one call of \`play\`
745
+
746
+ All of these tool calls MUST be emitted in the SAME assistant response, as
747
+ separate tool_use blocks, before you stop. Do not:
748
+ - split the sequence across multiple assistant responses,
749
+ - wait for a move result before emitting the next move or \`play\`,
750
+ - write any explanation or text between the tool calls,
751
+ - call any other tool during your turn (except \`tic_tac_toe_see_board\` when you
752
+ explicitly need the state restated).
753
+
754
+ Decide the target cell first, then dump every action for the turn in one go.
755
+
756
+ ### Examples (cursor starts at (${AGENT_CURSOR_HOME_ROW}, ${AGENT_CURSOR_HOME_COL}))
757
+
758
+ - Target (0,0): one call, \`play\`.
759
+ - Target (0,2): \`move_right\`, \`move_right\`, \`play\`. Three calls, one response.
760
+ - Target (1,1): \`move_down\`, \`move_right\`, \`play\`. Three calls, one response.
761
+ - Target (2,2): \`move_down\`, \`move_down\`, \`move_right\`, \`move_right\`, \`play\`. Five calls, one response.
762
+
763
+ ### Strategy
764
+
765
+ 1. If you have two O's in a line with the third cell empty, win by playing there.
766
+ 2. Otherwise, if X has two in a line with the third cell empty, block there.
767
+ 3. Otherwise, prefer center, then corners, then edges.
768
+ `;
769
+
770
+ return {
771
+ systemPrompt: event.systemPrompt + instructions,
772
+ };
773
+ });
774
+
775
+ // -----------------------------------------------------------------------
776
+ // /tic-tac-toe command
777
+ // -----------------------------------------------------------------------
778
+ pi.registerCommand("tic-tac-toe", {
779
+ description: "Play tic-tac-toe against the agent",
780
+
781
+ handler: async (_args, ctx) => {
782
+ if (ctx.mode !== "tui") {
783
+ ctx.ui.notify("Tic-tac-toe requires interactive mode", "error");
784
+ return;
785
+ }
786
+
787
+ reconstructState(ctx);
788
+ if (gameState.status !== "playing") {
789
+ gameState = createInitialState();
790
+ }
791
+ gameActive = true;
792
+ pi.setSessionName("Tic-Tac-Toe");
793
+
794
+ await ctx.ui.custom<void>((tui, _theme, _kb, done) => {
795
+ component = new TicTacToeComponent(
796
+ tui,
797
+ () => {
798
+ component = null;
799
+ gameActive = false;
800
+ done(undefined);
801
+ },
802
+ (row, col) => {
803
+ gameState.board[row][col] = gameState.userMark;
804
+ gameState.status = checkWin(gameState.board);
805
+ if (gameState.status === "playing") {
806
+ gameState.currentTurn = gameState.agentMark;
807
+ }
808
+ component?.updateState(gameState);
809
+ pi.appendEntry(SAVE_TYPE, getBoardDetails());
810
+
811
+ if (gameState.status === "playing") {
812
+ // IMPORTANT: user play does NOT touch the agent cursor.
813
+ // The agent cursor is only reset after a successful agent play.
814
+ const boardAscii = boardToAscii(
815
+ gameState.board,
816
+ gameState.agentCursorRow,
817
+ gameState.agentCursorCol,
818
+ );
819
+ pi.sendMessage(
820
+ {
821
+ customType: MOVE_MESSAGE_TYPE,
822
+ content:
823
+ `Player X played at (row=${row}, col=${col}). It is now Player O's turn.\n\n` +
824
+ `Board (your cursor marked with <>):\n${boardAscii}\n\n` +
825
+ `Your cursor is at (row=${gameState.agentCursorRow}, col=${gameState.agentCursorCol}). ` +
826
+ `Decide your target cell, then emit every move_* and the final play ` +
827
+ `as separate tic_tac_toe tool calls in THIS response.`,
828
+ display: true,
829
+ details: getBoardDetails(),
830
+ },
831
+ { triggerTurn: true },
832
+ );
833
+ } else {
834
+ emitGameOverMessage();
835
+ gameActive = false;
836
+ }
837
+ },
838
+ gameState,
839
+ );
840
+ return component;
841
+ });
842
+ },
843
+ });
844
+
845
+ // -----------------------------------------------------------------------
846
+ // tic_tac_toe tool - one action per call.
847
+ // -----------------------------------------------------------------------
848
+
849
+ type Action = "move_up" | "move_down" | "move_left" | "move_right" | "play";
850
+
851
+ const ACTION_DELAYS: Record<Action, number> = {
852
+ move_up: 300,
853
+ move_down: 300,
854
+ move_left: 300,
855
+ move_right: 300,
856
+ play: 0,
857
+ };
858
+
859
+ pi.registerTool({
860
+ name: "tic_tac_toe",
861
+ label: "Tic-Tac-Toe",
862
+ description:
863
+ "Execute ONE tic-tac-toe action as Player O. `action` is exactly one of: move_up, move_down, move_left, move_right (move YOUR cursor one cell, clamped at edges), or play (place O under YOUR cursor; errors if the cell is not empty). There is no batched form. To play at (r, c) from your current cursor (r0, c0), emit the required move_down/move_up and move_right/move_left calls, then play, all as separate tool_use blocks in the SAME assistant response. Do not split the sequence across responses and do not wait for a result before emitting the next call. Your cursor position persists between turns and is reset to (0,0) only after a successful play.",
864
+ promptSnippet: "Play a tic-tac-toe action (move_up/down/left/right or play) as Player O",
865
+ promptGuidelines: [
866
+ "When it is your tic-tac-toe turn, decide the target cell first, then emit every move_* plus the final play as separate tic_tac_toe tool calls in a SINGLE assistant response. Never split them across responses or wait for intermediate results.",
867
+ "Never ask the user for the board. The board and your cursor position are included in the user's move message; use tic_tac_toe_see_board if you need them restated.",
868
+ ],
869
+ parameters: Type.Object({
870
+ action: StringEnum(["move_up", "move_down", "move_left", "move_right", "play"] as const, {
871
+ description:
872
+ "The single action to perform this call. Emit multiple tic_tac_toe calls in one response to string actions together.",
873
+ }),
874
+ }),
875
+ executionMode: "sequential" as ToolExecutionMode,
876
+
877
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
878
+ const actionDelay = ACTION_DELAYS[params.action];
879
+ if (actionDelay > 0) await delay(actionDelay);
880
+
881
+ let result: string;
882
+
883
+ switch (params.action) {
884
+ case "move_up":
885
+ if (gameState.agentCursorRow > 0) gameState.agentCursorRow--;
886
+ result = `Moved up. Cursor: (${gameState.agentCursorRow}, ${gameState.agentCursorCol})`;
887
+ break;
888
+ case "move_down":
889
+ if (gameState.agentCursorRow < 2) gameState.agentCursorRow++;
890
+ result = `Moved down. Cursor: (${gameState.agentCursorRow}, ${gameState.agentCursorCol})`;
891
+ break;
892
+ case "move_left":
893
+ if (gameState.agentCursorCol > 0) gameState.agentCursorCol--;
894
+ result = `Moved left. Cursor: (${gameState.agentCursorRow}, ${gameState.agentCursorCol})`;
895
+ break;
896
+ case "move_right":
897
+ if (gameState.agentCursorCol < 2) gameState.agentCursorCol++;
898
+ result = `Moved right. Cursor: (${gameState.agentCursorRow}, ${gameState.agentCursorCol})`;
899
+ break;
900
+ case "play": {
901
+ if (gameState.status !== "playing") {
902
+ throw new TicTacToeError(`Game is over (${gameState.status}).`);
903
+ }
904
+ if (gameState.currentTurn !== gameState.agentMark) {
905
+ throw new TicTacToeError("It is not your turn.");
906
+ }
907
+ const r = gameState.agentCursorRow;
908
+ const c = gameState.agentCursorCol;
909
+ if (gameState.board[r][c] !== " ") {
910
+ // Do NOT reset the cursor on failure. The agent can retry
911
+ // from the cursor's current position.
912
+ component?.updateState(gameState);
913
+ pi.appendEntry(SAVE_TYPE, getBoardDetails());
914
+ throw new TicTacToeError(
915
+ `Cell (${r},${c}) is already ${gameState.board[r][c]}. Your cursor is still at (${r},${c}). Move to an empty cell and retry play.`,
916
+ );
917
+ }
918
+ gameState.board[r][c] = gameState.agentMark;
919
+ gameState.status = checkWin(gameState.board);
920
+ // Reset agent cursor to home ONLY on successful play.
921
+ gameState.agentCursorRow = AGENT_CURSOR_HOME_ROW;
922
+ gameState.agentCursorCol = AGENT_CURSOR_HOME_COL;
923
+ if (gameState.status === "playing") {
924
+ gameState.currentTurn = gameState.userMark;
925
+ result = `Placed O at (${r},${c}). Cursor reset to (${AGENT_CURSOR_HOME_ROW},${AGENT_CURSOR_HOME_COL}). Your turn, X!`;
926
+ } else if (gameState.status === "win_O") {
927
+ result = `Placed O at (${r},${c}). Player O wins!`;
928
+ gameActive = false;
929
+ emitGameOverMessage();
930
+ } else if (gameState.status === "draw") {
931
+ result = `Placed O at (${r},${c}). It's a draw!`;
932
+ gameActive = false;
933
+ emitGameOverMessage();
934
+ } else {
935
+ result = `Placed O at (${r},${c}).`;
936
+ }
937
+ break;
938
+ }
939
+ }
940
+
941
+ component?.updateState(gameState);
942
+ pi.appendEntry(SAVE_TYPE, getBoardDetails());
943
+
944
+ return {
945
+ content: [{ type: "text", text: result }],
946
+ details: getBoardDetails(),
947
+ };
948
+ },
949
+
950
+ renderCall(args, theme) {
951
+ const action = typeof args.action === "string" ? args.action : "";
952
+ return new Text(theme.fg("toolTitle", theme.bold("tic_tac_toe ")) + theme.fg("muted", action), 0, 0);
953
+ },
954
+
955
+ renderResult(result, { expanded }, theme, context) {
956
+ const details = result.details as BoardDetails | undefined;
957
+ const text = result.content[0];
958
+ const msg = text?.type === "text" ? text.text : "";
959
+ const prefix = context?.isError ? theme.fg("error", "\u2717 ") : theme.fg("success", "\u2713 ");
960
+ const summary = prefix + theme.fg("muted", msg);
961
+
962
+ if (expanded && details) {
963
+ return new BannerMessageComponent(summary, details, true, theme);
964
+ }
965
+ return new Text(summary, 0, 0);
966
+ },
967
+ });
968
+
969
+ // -----------------------------------------------------------------------
970
+ // tic_tac_toe_see_board tool - inspect board + agent cursor.
971
+ // -----------------------------------------------------------------------
972
+ pi.registerTool({
973
+ name: "tic_tac_toe_see_board",
974
+ label: "See Board",
975
+ description:
976
+ "Return the current tic-tac-toe board state and YOUR cursor position (Player O). Takes no arguments. Use this if you need the current state restated mid-turn (for example after a failed play). The user's cursor is never exposed.",
977
+ promptSnippet: "Inspect the tic-tac-toe board and your cursor",
978
+ parameters: Type.Object({}),
979
+
980
+ async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
981
+ const boardAscii = boardToAscii(gameState.board, gameState.agentCursorRow, gameState.agentCursorCol);
982
+ const text =
983
+ `Board (your cursor marked with <>):\n${boardAscii}\n\n` +
984
+ `Your cursor: (row=${gameState.agentCursorRow}, col=${gameState.agentCursorCol})\n` +
985
+ `Status: ${gameState.status}\n` +
986
+ `Turn: ${gameState.currentTurn === gameState.agentMark ? "Player O (you)" : "Player X"}`;
987
+ return {
988
+ content: [{ type: "text", text }],
989
+ details: getBoardDetails(),
990
+ };
991
+ },
992
+
993
+ renderCall(_args, theme) {
994
+ return new Text(theme.fg("toolTitle", theme.bold("tic_tac_toe_see_board")), 0, 0);
995
+ },
996
+
997
+ renderResult(result, { expanded }, theme) {
998
+ const details = result.details as BoardDetails | undefined;
999
+ const summary =
1000
+ theme.fg("success", "\u2713 ") +
1001
+ theme.fg("muted", `cursor (${details?.agentCursorRow ?? 0},${details?.agentCursorCol ?? 0})`);
1002
+ if (expanded && details) {
1003
+ return new BannerMessageComponent(summary, details, true, theme);
1004
+ }
1005
+ return new Text(summary, 0, 0);
1006
+ },
1007
+ });
1008
+ }