@clagentic/console 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/CREDITS.md +3 -0
  2. package/LICENSE +21 -0
  3. package/README.md +250 -0
  4. package/bin/cli.js +2812 -0
  5. package/lib/agents-favorites.js +164 -0
  6. package/lib/agents.js +282 -0
  7. package/lib/ask-user-mcp-server.js +120 -0
  8. package/lib/browser-mcp-server.js +484 -0
  9. package/lib/build-user-env.js +63 -0
  10. package/lib/certs/fullchain.pem +47 -0
  11. package/lib/certs/privkey.pem +5 -0
  12. package/lib/cli-sessions.js +265 -0
  13. package/lib/codex-defaults.js +18 -0
  14. package/lib/config.js +332 -0
  15. package/lib/crisis-safety.js +60 -0
  16. package/lib/daemon-projects.js +164 -0
  17. package/lib/daemon.js +1602 -0
  18. package/lib/dm.js +128 -0
  19. package/lib/ipc.js +125 -0
  20. package/lib/ipv4-only.js +39 -0
  21. package/lib/mcp-local.js +385 -0
  22. package/lib/notes.js +141 -0
  23. package/lib/os-users.js +529 -0
  24. package/lib/pages.js +1325 -0
  25. package/lib/project-connection.js +302 -0
  26. package/lib/project-external-trigger.js +236 -0
  27. package/lib/project-file-watch.js +120 -0
  28. package/lib/project-filesystem.js +528 -0
  29. package/lib/project-http.js +753 -0
  30. package/lib/project-image.js +95 -0
  31. package/lib/project-knowledge.js +88 -0
  32. package/lib/project-loop.js +1304 -0
  33. package/lib/project-mcp.js +374 -0
  34. package/lib/project-memory.js +39 -0
  35. package/lib/project-notifications.js +262 -0
  36. package/lib/project-sessions.js +1581 -0
  37. package/lib/project-user-mention.js +193 -0
  38. package/lib/project-user-message.js +628 -0
  39. package/lib/project.js +1303 -0
  40. package/lib/public/app.js +1031 -0
  41. package/lib/public/apple-touch-icon.png +0 -0
  42. package/lib/public/claude-code-avatar.png +0 -0
  43. package/lib/public/codex-avatar.png +0 -0
  44. package/lib/public/console-icon.png +0 -0
  45. package/lib/public/css/admin.css +736 -0
  46. package/lib/public/css/agent-picker.css +119 -0
  47. package/lib/public/css/base.css +235 -0
  48. package/lib/public/css/channel-layout.css +441 -0
  49. package/lib/public/css/command-palette.css +559 -0
  50. package/lib/public/css/debate.css +1609 -0
  51. package/lib/public/css/diff.css +139 -0
  52. package/lib/public/css/filebrowser.css +1976 -0
  53. package/lib/public/css/highlight.css +144 -0
  54. package/lib/public/css/home-hub.css +545 -0
  55. package/lib/public/css/icon-strip.css +1856 -0
  56. package/lib/public/css/input.css +1349 -0
  57. package/lib/public/css/loop.css +1248 -0
  58. package/lib/public/css/mention.css +317 -0
  59. package/lib/public/css/menus.css +857 -0
  60. package/lib/public/css/messages.css +1833 -0
  61. package/lib/public/css/mobile-nav.css +1332 -0
  62. package/lib/public/css/notifications-center.css +296 -0
  63. package/lib/public/css/overlays.css +1273 -0
  64. package/lib/public/css/playbook.css +264 -0
  65. package/lib/public/css/profile.css +397 -0
  66. package/lib/public/css/rewind.css +671 -0
  67. package/lib/public/css/scheduler-modal.css +1495 -0
  68. package/lib/public/css/scheduler.css +1420 -0
  69. package/lib/public/css/server-settings.css +909 -0
  70. package/lib/public/css/session-search.css +159 -0
  71. package/lib/public/css/sidebar.css +2012 -0
  72. package/lib/public/css/skills.css +789 -0
  73. package/lib/public/css/sticky-notes.css +854 -0
  74. package/lib/public/css/stt.css +155 -0
  75. package/lib/public/css/title-bar.css +674 -0
  76. package/lib/public/css/tooltip.css +67 -0
  77. package/lib/public/css/user-settings.css +702 -0
  78. package/lib/public/emoji-data.json +1 -0
  79. package/lib/public/favicon-banded-32.png +0 -0
  80. package/lib/public/favicon-banded.png +0 -0
  81. package/lib/public/favicon-dark.svg +32 -0
  82. package/lib/public/favicon.svg +32 -0
  83. package/lib/public/icon-192.png +0 -0
  84. package/lib/public/icon-512.png +0 -0
  85. package/lib/public/icon-banded-76.png +0 -0
  86. package/lib/public/icon-banded-96.png +0 -0
  87. package/lib/public/icon-mono.svg +25 -0
  88. package/lib/public/icons/email/gmail.svg +7 -0
  89. package/lib/public/icons/email/outlook.svg +35 -0
  90. package/lib/public/icons/email/yahoo.svg +1 -0
  91. package/lib/public/index.html +1946 -0
  92. package/lib/public/manifest.json +27 -0
  93. package/lib/public/markdown-worker.js +43 -0
  94. package/lib/public/marked.min.js +6 -0
  95. package/lib/public/modules/admin.js +954 -0
  96. package/lib/public/modules/agent-picker.js +429 -0
  97. package/lib/public/modules/app-connection.js +216 -0
  98. package/lib/public/modules/app-cursors.js +492 -0
  99. package/lib/public/modules/app-dm.js +265 -0
  100. package/lib/public/modules/app-favicon.js +231 -0
  101. package/lib/public/modules/app-header.js +242 -0
  102. package/lib/public/modules/app-home-hub.js +432 -0
  103. package/lib/public/modules/app-loop-ui.js +691 -0
  104. package/lib/public/modules/app-loop-wizard.js +439 -0
  105. package/lib/public/modules/app-messages.js +1415 -0
  106. package/lib/public/modules/app-misc.js +463 -0
  107. package/lib/public/modules/app-notifications.js +651 -0
  108. package/lib/public/modules/app-panels.js +1061 -0
  109. package/lib/public/modules/app-projects.js +875 -0
  110. package/lib/public/modules/app-rate-limit.js +529 -0
  111. package/lib/public/modules/app-rendering.js +739 -0
  112. package/lib/public/modules/app-skills-install.js +285 -0
  113. package/lib/public/modules/avatar.js +36 -0
  114. package/lib/public/modules/command-palette.js +491 -0
  115. package/lib/public/modules/console-logo.js +162 -0
  116. package/lib/public/modules/context-sources.js +365 -0
  117. package/lib/public/modules/diff.js +412 -0
  118. package/lib/public/modules/dom-refs.js +21 -0
  119. package/lib/public/modules/emoji-picker.js +222 -0
  120. package/lib/public/modules/events.js +21 -0
  121. package/lib/public/modules/filebrowser.js +1966 -0
  122. package/lib/public/modules/fileicons.js +172 -0
  123. package/lib/public/modules/icons.js +80 -0
  124. package/lib/public/modules/input.js +1102 -0
  125. package/lib/public/modules/longpress.js +74 -0
  126. package/lib/public/modules/markdown.js +486 -0
  127. package/lib/public/modules/mcp-ui.js +295 -0
  128. package/lib/public/modules/mention.js +1093 -0
  129. package/lib/public/modules/notifications.js +613 -0
  130. package/lib/public/modules/playbook.js +578 -0
  131. package/lib/public/modules/profile.js +594 -0
  132. package/lib/public/modules/project-settings.js +849 -0
  133. package/lib/public/modules/project-switcher.js +375 -0
  134. package/lib/public/modules/qrcode.js +87 -0
  135. package/lib/public/modules/rewind.js +381 -0
  136. package/lib/public/modules/scheduler-config.js +1611 -0
  137. package/lib/public/modules/scheduler-history.js +131 -0
  138. package/lib/public/modules/scheduler.js +1689 -0
  139. package/lib/public/modules/server-settings.js +842 -0
  140. package/lib/public/modules/session-search.js +456 -0
  141. package/lib/public/modules/settings-defaults.js +253 -0
  142. package/lib/public/modules/sidebar-mobile.js +1425 -0
  143. package/lib/public/modules/sidebar-projects.js +2022 -0
  144. package/lib/public/modules/sidebar-sessions.js +1548 -0
  145. package/lib/public/modules/sidebar-users.js +449 -0
  146. package/lib/public/modules/sidebar.js +348 -0
  147. package/lib/public/modules/skills.js +793 -0
  148. package/lib/public/modules/state.js +3 -0
  149. package/lib/public/modules/sticky-notes.js +1221 -0
  150. package/lib/public/modules/store.js +34 -0
  151. package/lib/public/modules/stt.js +266 -0
  152. package/lib/public/modules/terminal.js +987 -0
  153. package/lib/public/modules/theme.js +812 -0
  154. package/lib/public/modules/tool-palette.js +562 -0
  155. package/lib/public/modules/tools.js +2285 -0
  156. package/lib/public/modules/tooltip.js +150 -0
  157. package/lib/public/modules/user-settings.js +544 -0
  158. package/lib/public/modules/utils.js +56 -0
  159. package/lib/public/modules/ws-ref.js +26 -0
  160. package/lib/public/style.css +34 -0
  161. package/lib/public/sw.js +159 -0
  162. package/lib/push.js +149 -0
  163. package/lib/scheduler.js +471 -0
  164. package/lib/sdk-bridge.js +1792 -0
  165. package/lib/sdk-message-processor.js +740 -0
  166. package/lib/sdk-message-queue.js +42 -0
  167. package/lib/sdk-skill-discovery.js +131 -0
  168. package/lib/sdk-worker.js +677 -0
  169. package/lib/server-admin.js +712 -0
  170. package/lib/server-auth.js +737 -0
  171. package/lib/server-dm.js +170 -0
  172. package/lib/server-palette.js +104 -0
  173. package/lib/server-settings.js +553 -0
  174. package/lib/server-skills.js +280 -0
  175. package/lib/server.js +1390 -0
  176. package/lib/session-search.js +693 -0
  177. package/lib/sessions.js +946 -0
  178. package/lib/smtp.js +221 -0
  179. package/lib/terminal-manager.js +219 -0
  180. package/lib/terminal.js +39 -0
  181. package/lib/themes/ayu-light.json +9 -0
  182. package/lib/themes/catppuccin-latte.json +9 -0
  183. package/lib/themes/catppuccin-mocha.json +9 -0
  184. package/lib/themes/clagentic-dark.json +10 -0
  185. package/lib/themes/clagentic-light.json +10 -0
  186. package/lib/themes/dracula.json +9 -0
  187. package/lib/themes/everforest-light.json +9 -0
  188. package/lib/themes/everforest.json +9 -0
  189. package/lib/themes/github-light.json +9 -0
  190. package/lib/themes/gruvbox-dark.json +9 -0
  191. package/lib/themes/gruvbox-light.json +9 -0
  192. package/lib/themes/monokai.json +9 -0
  193. package/lib/themes/nord-light.json +9 -0
  194. package/lib/themes/nord.json +9 -0
  195. package/lib/themes/one-dark.json +9 -0
  196. package/lib/themes/one-light.json +9 -0
  197. package/lib/themes/rose-pine-dawn.json +9 -0
  198. package/lib/themes/rose-pine.json +9 -0
  199. package/lib/themes/solarized-dark.json +9 -0
  200. package/lib/themes/solarized-light.json +9 -0
  201. package/lib/themes/tokyo-night-light.json +9 -0
  202. package/lib/themes/tokyo-night.json +9 -0
  203. package/lib/updater.js +124 -0
  204. package/lib/user-presence.js +92 -0
  205. package/lib/users-auth.js +146 -0
  206. package/lib/users-permissions.js +118 -0
  207. package/lib/users-preferences.js +254 -0
  208. package/lib/users.js +465 -0
  209. package/lib/utils.js +64 -0
  210. package/lib/worktree.js +134 -0
  211. package/lib/ws-schema.js +464 -0
  212. package/lib/yoke/adapters/claude-worker.js +759 -0
  213. package/lib/yoke/adapters/claude.js +1599 -0
  214. package/lib/yoke/adapters/codex.js +1559 -0
  215. package/lib/yoke/codex-app-server.js +352 -0
  216. package/lib/yoke/index.js +319 -0
  217. package/lib/yoke/instructions.js +61 -0
  218. package/lib/yoke/interface.js +98 -0
  219. package/lib/yoke/mcp-bridge-server.js +302 -0
  220. package/lib/yoke/package.json +7 -0
  221. package/package.json +72 -0
@@ -0,0 +1,1559 @@
1
+ // YOKE Codex Adapter
2
+ // -------------------
3
+ // Implements the YOKE interface using codex app-server protocol.
4
+ // Bidirectional JSON-RPC over stdin/stdout enables interactive approval flows.
5
+
6
+ var path = require("path");
7
+ var fs = require("fs");
8
+ var { CodexAppServer } = require("../codex-app-server");
9
+
10
+ // --- Claude skill discovery ---
11
+ // Finds Claude skills in ~/.claude/skills/ and <cwd>/.claude/skills/
12
+ // so Codex can recognize $<skill-name> in user input.
13
+ function discoverClaudeSkills(cwd) {
14
+ var skills = {};
15
+ var REAL_HOME;
16
+ try { REAL_HOME = require("../../config").REAL_HOME; } catch (e) { REAL_HOME = require("os").homedir(); }
17
+ var dirs = [
18
+ path.join(REAL_HOME, ".claude", "skills"),
19
+ path.join(cwd || "", ".claude", "skills"),
20
+ ];
21
+ for (var d = 0; d < dirs.length; d++) {
22
+ var base = dirs[d];
23
+ if (!base) continue;
24
+ var entries;
25
+ try { entries = fs.readdirSync(base, { withFileTypes: true }); } catch (e) { continue; }
26
+ for (var i = 0; i < entries.length; i++) {
27
+ var entry = entries[i];
28
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
29
+ var skillMd = path.join(base, entry.name, "SKILL.md");
30
+ try {
31
+ fs.accessSync(skillMd, fs.constants.R_OK);
32
+ // project skills override global skills
33
+ skills[entry.name] = skillMd;
34
+ } catch (e) {}
35
+ }
36
+ }
37
+ return skills;
38
+ }
39
+
40
+ // Parse user text for $<skill-name> references.
41
+ // Returns { text, skills: [{ name, path }] }
42
+ function parseSkillRefs(text, availableSkills) {
43
+ if (typeof text !== "string") return { text: text, skills: [] };
44
+ var skills = [];
45
+ var seen = {};
46
+ var re = /\$([a-zA-Z0-9_-]+)/g;
47
+ var match;
48
+ while ((match = re.exec(text)) !== null) {
49
+ var name = match[1];
50
+ if (seen[name]) continue;
51
+ if (availableSkills[name]) {
52
+ seen[name] = true;
53
+ skills.push({ name: name, path: availableSkills[name] });
54
+ }
55
+ }
56
+ return { text: text, skills: skills };
57
+ }
58
+
59
+ // --- Event flattening ---
60
+ // Converts app-server JSON-RPC notifications into flat objects with a yokeType field.
61
+ //
62
+ // App-server events use slash notation (item/started) and camelCase item types.
63
+ // We normalize to the same YOKE event format used by the rest of the system.
64
+ //
65
+ // Server -> Client notifications:
66
+ // thread/started -> { params: { thread } }
67
+ // turn/started -> { params: {} }
68
+ // turn/completed -> { params: { usage } }
69
+ // turn/failed -> { params: { error } }
70
+ // item/started -> { params: { item } }
71
+ // item/updated -> { params: { item } }
72
+ // item/completed -> { params: { item } }
73
+ // item/agentMessage/delta -> { params: { itemId, delta } }
74
+ //
75
+ // Item types (camelCase in app-server):
76
+ // agentMessage -> text response
77
+ // reasoning -> thinking
78
+ // commandExecution -> bash/shell
79
+ // fileChange -> file edits
80
+ // mcpToolCall -> MCP tool
81
+ // webSearch -> web search
82
+ // error -> error
83
+
84
+ var _uuidCounter = 0;
85
+ function generateUuid() {
86
+ var ts = Date.now().toString(36);
87
+ var cnt = (++_uuidCounter).toString(36);
88
+ var rnd = Math.random().toString(36).substring(2, 8);
89
+ return "codex-" + ts + "-" + cnt + "-" + rnd;
90
+ }
91
+
92
+ function waitMs(ms) {
93
+ return new Promise(function(resolve) {
94
+ setTimeout(resolve, ms);
95
+ });
96
+ }
97
+
98
+ function waitForProcessExit(proc, timeoutMs) {
99
+ return new Promise(function(resolve) {
100
+ if (!proc) {
101
+ resolve(true);
102
+ return;
103
+ }
104
+
105
+ if (proc.exitCode !== null || proc.signalCode !== null) {
106
+ resolve(true);
107
+ return;
108
+ }
109
+
110
+ var done = false;
111
+ var timer = null;
112
+
113
+ function cleanup() {
114
+ if (done) return;
115
+ done = true;
116
+ if (timer) clearTimeout(timer);
117
+ proc.removeListener("exit", onDone);
118
+ proc.removeListener("close", onDone);
119
+ }
120
+
121
+ function onDone() {
122
+ cleanup();
123
+ resolve(true);
124
+ }
125
+
126
+ proc.once("exit", onDone);
127
+ proc.once("close", onDone);
128
+
129
+ timer = setTimeout(function() {
130
+ cleanup();
131
+ resolve(false);
132
+ }, timeoutMs || 5000);
133
+ });
134
+ }
135
+
136
+ function createShutdownError() {
137
+ var err = new Error("Codex adapter is shutting down, retry shortly");
138
+ err.code = "CODEX_ADAPTER_SHUTTING_DOWN";
139
+ return err;
140
+ }
141
+
142
+ function normalizePlanStatus(status) {
143
+ if (status === "inProgress") return "in_progress";
144
+ if (status === "completed") return "completed";
145
+ return "pending";
146
+ }
147
+
148
+ function extractPromptSuggestion(params) {
149
+ if (!params) return "";
150
+ if (typeof params.suggestion === "string") return params.suggestion;
151
+ if (typeof params.promptSuggestion === "string") return params.promptSuggestion;
152
+ if (typeof params.suggestedPrompt === "string") return params.suggestedPrompt;
153
+ if (Array.isArray(params.suggestions) && typeof params.suggestions[0] === "string") return params.suggestions[0];
154
+ if (Array.isArray(params.promptSuggestions) && typeof params.promptSuggestions[0] === "string") return params.promptSuggestions[0];
155
+ if (Array.isArray(params.followUpSuggestions) && typeof params.followUpSuggestions[0] === "string") return params.followUpSuggestions[0];
156
+ return "";
157
+ }
158
+
159
+ function flattenEvent(notification, state) {
160
+ var events = [];
161
+ var method = notification.method;
162
+ var params = notification.params || {};
163
+
164
+
165
+ if (method === "thread/started") {
166
+ state.threadId = params.thread ? params.thread.id : (params.threadId || null);
167
+ return events;
168
+ }
169
+
170
+ if (method === "turn/started") {
171
+ state.turnStarted = true;
172
+ var userUuid = generateUuid();
173
+ events.push({ yokeType: "turn_start", uuid: userUuid, messageType: "user" });
174
+ return events;
175
+ }
176
+
177
+ if (method === "turn/completed") {
178
+ var usage = params.usage || null;
179
+ var turnStatus = params.status || (params.turn && params.turn.status) || null;
180
+ state.lastUsage = usage;
181
+ // Emit interrupted status so UI shows "stopped" message
182
+ if (turnStatus === "interrupted" || state.aborted) {
183
+ events.push({ yokeType: "interrupted" });
184
+ }
185
+ var inputTokens = state.lastInputTokens || (usage ? (usage.input_tokens || 0) + (usage.cached_input_tokens || 0) : 0);
186
+ var outputTokens = usage ? (usage.output_tokens || 0) : 0;
187
+ var cachedTokens = usage ? (usage.cached_input_tokens || 0) : 0;
188
+ var hasTokenData = inputTokens > 0 || outputTokens > 0;
189
+ var resultModelUsage = {};
190
+ resultModelUsage[state.model] = { contextWindow: null };
191
+ var assistantUuid = generateUuid();
192
+ events.push({
193
+ yokeType: "result",
194
+ uuid: assistantUuid,
195
+ messageType: "assistant",
196
+ cost: null,
197
+ duration: null,
198
+ usage: hasTokenData ? {
199
+ input_tokens: inputTokens,
200
+ output_tokens: outputTokens,
201
+ cache_read_input_tokens: cachedTokens,
202
+ cache_creation_input_tokens: 0,
203
+ } : null,
204
+ modelUsage: resultModelUsage,
205
+ sessionId: state.threadId || null,
206
+ lastStreamInputTokens: state.lastInputTokens || null,
207
+ });
208
+ state.lastInputTokens = null;
209
+ return events;
210
+ }
211
+
212
+ if (method === "turn/plan/updated") {
213
+ events.push({
214
+ yokeType: "plan_updated",
215
+ turnId: params.turnId || null,
216
+ explanation: params.explanation || "",
217
+ title: "Plan",
218
+ plan: Array.isArray(params.plan) ? params.plan.map(function(step) {
219
+ return {
220
+ step: step && step.step ? step.step : "",
221
+ status: normalizePlanStatus(step && step.status),
222
+ };
223
+ }) : [],
224
+ });
225
+ return events;
226
+ }
227
+
228
+ if (method === "turn/failed") {
229
+ events.push({
230
+ yokeType: "error",
231
+ text: params.error ? params.error.message : "Turn failed",
232
+ });
233
+ return events;
234
+ }
235
+
236
+ // Rate limits from Codex account
237
+ if (method === "account/rateLimits/updated") {
238
+ var rl = params.rateLimits;
239
+ if (rl) {
240
+ var windows = [
241
+ { key: "primary", type: "five_hour" },
242
+ { key: "secondary", type: "seven_day" },
243
+ ];
244
+ for (var wi = 0; wi < windows.length; wi++) {
245
+ var w = rl[windows[wi].key];
246
+ if (!w) continue;
247
+ var utilization = (w.usedPercent || 0) / 100;
248
+ var status = "allowed";
249
+ if (w.usedPercent >= 100) status = "rejected";
250
+ else if (w.usedPercent >= 80) status = "allowed_warning";
251
+ events.push({
252
+ yokeType: "rate_limit",
253
+ rateLimitInfo: {
254
+ status: status,
255
+ resetsAt: w.resetsAt || null,
256
+ rateLimitType: windows[wi].type,
257
+ utilization: utilization,
258
+ isUsingOverage: false,
259
+ },
260
+ });
261
+ }
262
+ }
263
+ return events;
264
+ }
265
+
266
+ // Streaming text delta (app-server specific, not present in exec mode)
267
+ if (method === "item/agentMessage/delta") {
268
+ var deltaItemId = params.itemId || params.id;
269
+ if (deltaItemId && !state.textBlocks[deltaItemId]) {
270
+ state.textBlocks[deltaItemId] = true;
271
+ state.blockCounter++;
272
+ events.push({ yokeType: "text_start", blockId: "blk_" + state.blockCounter });
273
+ }
274
+ if (params.delta) {
275
+ events.push({
276
+ yokeType: "text_delta",
277
+ blockId: "blk_" + state.blockCounter,
278
+ text: params.delta,
279
+ });
280
+ // Track cumulative streamed length so item/completed doesn't re-send the full text
281
+ if (deltaItemId) {
282
+ state.textLengths[deltaItemId] = (state.textLengths[deltaItemId] || 0) + params.delta.length;
283
+ }
284
+ }
285
+ return events;
286
+ }
287
+
288
+ if (method === "item/plan/delta") {
289
+ var planDeltaItemId = params.itemId || params.id;
290
+ var nextPlanText = (state.planTexts[planDeltaItemId] || "") + (params.delta || "");
291
+ if (planDeltaItemId) state.planTexts[planDeltaItemId] = nextPlanText;
292
+ if (nextPlanText) {
293
+ events.push({
294
+ yokeType: "plan_content",
295
+ content: nextPlanText,
296
+ itemId: planDeltaItemId || null,
297
+ });
298
+ }
299
+ return events;
300
+ }
301
+
302
+ // serverRequest/resolved - confirmation that an approval was processed
303
+ if (method === "serverRequest/resolved") {
304
+ return events; // no-op, approval already handled
305
+ }
306
+
307
+ // Item events
308
+ if (method === "item/started" || method === "item/updated" || method === "item/completed") {
309
+ var item = params.item;
310
+ if (!item) return events;
311
+
312
+ var evtPhase = method.split("/")[1]; // "started", "updated", "completed"
313
+
314
+ if (item.type === "plan") {
315
+ if (typeof item.text === "string") {
316
+ state.planTexts[item.id] = item.text;
317
+ events.push({
318
+ yokeType: "plan_content",
319
+ content: item.text,
320
+ itemId: item.id,
321
+ final: evtPhase === "completed",
322
+ });
323
+ }
324
+ return events;
325
+ }
326
+
327
+ if (item.type === "contextCompaction" || item.type === "context_compaction") {
328
+ events.push({
329
+ yokeType: "status",
330
+ status: evtPhase === "completed" ? "processing" : "compacting",
331
+ });
332
+ return events;
333
+ }
334
+
335
+ // Agent message (text response)
336
+ if (item.type === "agentMessage" || item.type === "agent_message") {
337
+ if (!state.textBlocks[item.id]) {
338
+ state.textBlocks[item.id] = true;
339
+ state.blockCounter++;
340
+ events.push({ yokeType: "text_start", blockId: "blk_" + state.blockCounter });
341
+ }
342
+ if (item.text) {
343
+ var prevLen = state.textLengths[item.id] || 0;
344
+ if (item.text.length > prevLen) {
345
+ events.push({
346
+ yokeType: "text_delta",
347
+ blockId: "blk_" + state.blockCounter,
348
+ text: item.text.substring(prevLen),
349
+ });
350
+ state.textLengths[item.id] = item.text.length;
351
+ }
352
+ }
353
+ return events;
354
+ }
355
+
356
+ // Reasoning (thinking)
357
+ if (item.type === "reasoning") {
358
+ if (!state.thinkingBlocks[item.id]) {
359
+ state.blockCounter++;
360
+ state.thinkingBlocks[item.id] = "blk_" + state.blockCounter;
361
+ events.push({ yokeType: "thinking_start", blockId: "blk_" + state.blockCounter });
362
+ }
363
+ // Codex reasoning items may expose plain text via `text`, a short
364
+ // `summary`, or nested `content` parts. Prefer whichever is present;
365
+ // many turns arrive with only encrypted reasoning and no readable
366
+ // text at all, in which case the UI will hide the expand affordance.
367
+ var reasoningText = "";
368
+ if (typeof item.text === "string" && item.text.length > 0) {
369
+ reasoningText = item.text;
370
+ } else if (typeof item.summary === "string" && item.summary.length > 0) {
371
+ reasoningText = item.summary;
372
+ } else if (Array.isArray(item.content)) {
373
+ var parts = [];
374
+ for (var rpi = 0; rpi < item.content.length; rpi++) {
375
+ var rp = item.content[rpi];
376
+ if (rp && typeof rp.text === "string") parts.push(rp.text);
377
+ }
378
+ reasoningText = parts.join("\n");
379
+ }
380
+ if (reasoningText) {
381
+ var thinkBlockId = state.thinkingBlocks[item.id];
382
+ var prevThinkLen = state.thinkingLengths[item.id] || 0;
383
+ if (reasoningText.length > prevThinkLen) {
384
+ events.push({
385
+ yokeType: "thinking_delta",
386
+ blockId: thinkBlockId,
387
+ text: reasoningText.substring(prevThinkLen),
388
+ });
389
+ state.thinkingLengths[item.id] = reasoningText.length;
390
+ }
391
+ }
392
+ if (evtPhase === "completed") {
393
+ events.push({ yokeType: "thinking_stop", blockId: state.thinkingBlocks[item.id] });
394
+ }
395
+ return events;
396
+ }
397
+
398
+ // Command execution (bash/shell)
399
+ if (item.type === "commandExecution" || item.type === "command_execution") {
400
+ var commandText = item.command || state.commandInputs[item.id] || "";
401
+ if (commandText) state.commandInputs[item.id] = commandText;
402
+ if (!state.toolBlocks[item.id]) {
403
+ state.blockCounter++;
404
+ state.toolBlocks[item.id] = "blk_" + state.blockCounter;
405
+ var toolBlockId = state.toolBlocks[item.id];
406
+ events.push({
407
+ yokeType: "tool_start",
408
+ blockId: toolBlockId,
409
+ toolId: item.id,
410
+ toolName: "Bash",
411
+ });
412
+ events.push({
413
+ yokeType: "tool_executing",
414
+ blockId: toolBlockId,
415
+ toolId: item.id,
416
+ toolName: "Bash",
417
+ input: { command: commandText },
418
+ });
419
+ }
420
+ if (evtPhase === "completed") {
421
+ events.push({
422
+ yokeType: "tool_result",
423
+ toolId: item.id,
424
+ blockId: state.toolBlocks[item.id],
425
+ content: item.aggregated_output || item.output || "",
426
+ isError: item.status === "failed",
427
+ });
428
+ }
429
+ return events;
430
+ }
431
+
432
+ // File change
433
+ if (item.type === "fileChange" || item.type === "file_change") {
434
+ var changes = item.changes || [];
435
+ var changeDesc = changes.map(function(c) { return c.kind + " " + c.path; }).join(", ");
436
+ var primaryPath = changes.length === 1 ? (changes[0].path || "") : "";
437
+ if (!state.toolBlocks[item.id]) {
438
+ state.blockCounter++;
439
+ state.toolBlocks[item.id] = "blk_" + state.blockCounter;
440
+ var fcBlockId = state.toolBlocks[item.id];
441
+ events.push({
442
+ yokeType: "tool_start",
443
+ blockId: fcBlockId,
444
+ toolId: item.id,
445
+ toolName: "Edit",
446
+ });
447
+ events.push({
448
+ yokeType: "tool_executing",
449
+ blockId: fcBlockId,
450
+ toolId: item.id,
451
+ toolName: "Edit",
452
+ input: {
453
+ changes: changeDesc,
454
+ file_path: primaryPath || undefined,
455
+ },
456
+ });
457
+ }
458
+ if (evtPhase === "completed") {
459
+ var diffText = changes.map(function(c) {
460
+ return c && c.diff ? c.diff : "";
461
+ }).filter(Boolean).join("\n\n");
462
+ events.push({
463
+ yokeType: "tool_result",
464
+ toolId: item.id,
465
+ blockId: state.toolBlocks[item.id],
466
+ content: diffText || (item.status === "completed" ? "Changes applied" : "Changes failed"),
467
+ isError: item.status === "failed",
468
+ });
469
+ }
470
+ return events;
471
+ }
472
+
473
+ // MCP tool call
474
+ if (item.type === "mcpToolCall" || item.type === "mcp_tool_call") {
475
+ console.log("[yoke/codex] MCP event:", method, "tool=" + (item.tool || "?"), "status=" + (item.status || "?"), "error=" + (item.error ? JSON.stringify(item.error) : "none"));
476
+ if (!state.toolBlocks[item.id]) {
477
+ state.blockCounter++;
478
+ state.toolBlocks[item.id] = "blk_" + state.blockCounter;
479
+ var mcpBlockId = state.toolBlocks[item.id];
480
+ events.push({
481
+ yokeType: "tool_start",
482
+ blockId: mcpBlockId,
483
+ toolId: item.id,
484
+ toolName: item.tool || "mcp_tool",
485
+ });
486
+ events.push({
487
+ yokeType: "tool_executing",
488
+ blockId: mcpBlockId,
489
+ toolId: item.id,
490
+ toolName: item.tool || "mcp_tool",
491
+ input: item.arguments || {},
492
+ });
493
+ }
494
+ if (evtPhase === "completed") {
495
+ var resultText = "";
496
+ if (item.result && item.result.content) {
497
+ resultText = item.result.content.map(function(c) { return c.text || ""; }).join("\n");
498
+ }
499
+ if (item.error) resultText = item.error.message;
500
+ events.push({
501
+ yokeType: "tool_result",
502
+ toolId: item.id,
503
+ blockId: state.toolBlocks[item.id],
504
+ content: resultText,
505
+ isError: !!item.error,
506
+ });
507
+ }
508
+ return events;
509
+ }
510
+
511
+ // Web search
512
+ if (item.type === "webSearch" || item.type === "web_search") {
513
+ if (!state.toolBlocks[item.id]) {
514
+ state.blockCounter++;
515
+ state.toolBlocks[item.id] = "blk_" + state.blockCounter;
516
+ events.push({
517
+ yokeType: "tool_start",
518
+ blockId: state.toolBlocks[item.id],
519
+ toolId: item.id,
520
+ toolName: "WebSearch",
521
+ });
522
+ }
523
+ return events;
524
+ }
525
+
526
+ // Error item
527
+ if (item.type === "error") {
528
+ events.push({
529
+ yokeType: "error",
530
+ text: item.message || "Unknown error",
531
+ });
532
+ return events;
533
+ }
534
+ }
535
+
536
+ // Token usage update - track input tokens for context bar
537
+ if (method === "thread/tokenUsage/updated") {
538
+ var tu = params.tokenUsage;
539
+ if (tu && tu.total) {
540
+ state.lastInputTokens = tu.total.inputTokens || 0;
541
+ }
542
+ return events;
543
+ }
544
+
545
+ var promptSuggestion = extractPromptSuggestion(params);
546
+ if (promptSuggestion) {
547
+ events.push({
548
+ yokeType: "prompt_suggestion",
549
+ suggestion: promptSuggestion,
550
+ });
551
+ return events;
552
+ }
553
+
554
+ // Unknown event type - pass through
555
+ console.log("[yoke/codex] UNHANDLED event:", method, JSON.stringify(params).substring(0, 200));
556
+ events.push({
557
+ yokeType: "runtime_specific",
558
+ vendor: "codex",
559
+ eventType: method,
560
+ raw: params,
561
+ });
562
+
563
+ return events;
564
+ }
565
+
566
+ // --- QueryHandle ---
567
+
568
+ function createCodexQueryHandle(appServer, queryOpts) {
569
+ var abortController = queryOpts.abortController;
570
+ var systemPrompt = queryOpts.systemPrompt || "";
571
+ var canUseTool = queryOpts.canUseTool || null;
572
+ var onElicitation = queryOpts.onElicitation || null;
573
+ var onFinished = queryOpts.onFinished || null;
574
+
575
+ // Check if the query was cancelled (either via handle.abort() or direct signal abort)
576
+ function isCancelled() {
577
+ return state.aborted || (abortController && abortController.signal && abortController.signal.aborted);
578
+ }
579
+
580
+ var state = {
581
+ blockCounter: 0,
582
+ threadId: null,
583
+ turnStarted: false,
584
+ lastUsage: null,
585
+ lastInputTokens: null, // from thread/tokenUsage/updated
586
+ done: false,
587
+ aborted: false,
588
+ loopStarted: false,
589
+ model: queryOpts.model || "gpt-5.4",
590
+ // Track incremental text deltas
591
+ textBlocks: {}, // itemId -> true (text_start sent)
592
+ textLengths: {}, // itemId -> last sent length
593
+ thinkingBlocks: {}, // itemId -> blockId
594
+ thinkingLengths: {}, // itemId -> last sent length
595
+ toolBlocks: {}, // itemId -> blockId (for tool_start dedup)
596
+ commandInputs: {}, // itemId -> command captured from approval/start events
597
+ planTexts: {}, // itemId -> streamed plan text
598
+ };
599
+
600
+ // Internal event buffer for async iterator
601
+ var eventBuffer = [];
602
+ var eventWaiting = null;
603
+ var iteratorDone = false;
604
+ var finishedNotified = false;
605
+
606
+ function notifyFinished() {
607
+ if (finishedNotified) return;
608
+ finishedNotified = true;
609
+ if (typeof onFinished === "function") {
610
+ try {
611
+ onFinished();
612
+ } catch (e) {
613
+ console.error("[yoke/codex] onFinished error:", e.message || e);
614
+ }
615
+ }
616
+ }
617
+
618
+ function pushEvent(evt) {
619
+ if (iteratorDone) return;
620
+ if (eventWaiting) {
621
+ var resolve = eventWaiting;
622
+ eventWaiting = null;
623
+ resolve({ value: evt, done: false });
624
+ } else {
625
+ eventBuffer.push(evt);
626
+ }
627
+ }
628
+
629
+ function endIterator() {
630
+ iteratorDone = true;
631
+ if (eventWaiting) {
632
+ var resolve = eventWaiting;
633
+ eventWaiting = null;
634
+ resolve({ value: undefined, done: true });
635
+ }
636
+ notifyFinished();
637
+ }
638
+
639
+ // Message queue for multi-turn
640
+ var messageQueue = [];
641
+ var messageWaiting = null;
642
+ var messageQueueEnded = false;
643
+
644
+ function pushMessageToQueue(msg) {
645
+ if (messageQueueEnded) return;
646
+ if (messageWaiting) {
647
+ var resolve = messageWaiting;
648
+ messageWaiting = null;
649
+ resolve(msg);
650
+ } else {
651
+ messageQueue.push(msg);
652
+ }
653
+ }
654
+
655
+ function waitForMessage() {
656
+ if (messageQueue.length > 0) return Promise.resolve(messageQueue.shift());
657
+ if (messageQueueEnded) return Promise.resolve(null);
658
+ return new Promise(function(resolve) { messageWaiting = resolve; });
659
+ }
660
+
661
+ // Track whether this turn is still active (waiting for turn/completed or turn/failed)
662
+ var turnResolve = null;
663
+
664
+ // --- App-server event handler ---
665
+ function handleServerEvent(msg) {
666
+ var method = msg.method;
667
+ var params = msg.params || {};
668
+
669
+ // Ignore events from other threads (app-server is shared across sessions)
670
+ if (params.threadId && state.threadId && params.threadId !== state.threadId) return;
671
+
672
+ // After abort, only let turn-ending events through
673
+ if (isCancelled() && method !== "turn/completed" && method !== "turn/failed" && method !== "serverRequest/resolved" && method !== "thread/status/changed") return;
674
+
675
+ // --- Approval helper ---
676
+ // canUseTool returns { behavior: "allow"|"deny", updatedInput } or truthy/falsy
677
+ function isApproved(decision) {
678
+ if (!decision) return false;
679
+ if (decision === true) return true;
680
+ if (decision.behavior === "allow") return true;
681
+ return false;
682
+ }
683
+
684
+ // Command approval request
685
+ if (method === "item/commandExecution/requestApproval") {
686
+ var cmdParams = msg.params || {};
687
+ if (cmdParams.itemId && cmdParams.command) {
688
+ state.commandInputs[cmdParams.itemId] = cmdParams.command;
689
+ }
690
+ if (canUseTool) {
691
+ canUseTool("Bash", { command: cmdParams.command }, {}).then(function(decision) {
692
+ var approved = isApproved(decision);
693
+ // Response must be wrapped in { decision: ... } object per app-server protocol
694
+ appServer.respond(msg.id, { decision: approved ? "accept" : "decline" });
695
+ }).catch(function(err) {
696
+ console.error("[yoke/codex] canUseTool error:", err.message);
697
+ appServer.respond(msg.id, { decision: "decline" });
698
+ });
699
+ } else {
700
+ appServer.respond(msg.id, { decision: "accept" });
701
+ }
702
+ return;
703
+ }
704
+
705
+ // File change approval request
706
+ if (method === "item/fileChange/requestApproval") {
707
+ var fcParams = msg.params || {};
708
+ if (canUseTool) {
709
+ var changeInfo = (fcParams.changes || []).map(function(c) { return c.kind + " " + c.path; }).join(", ");
710
+ canUseTool("Edit", { changes: changeInfo, path: fcParams.path }, {}).then(function(decision) {
711
+ appServer.respond(msg.id, { decision: isApproved(decision) ? "accept" : "decline" });
712
+ }).catch(function(err) {
713
+ console.error("[yoke/codex] canUseTool error:", err.message);
714
+ appServer.respond(msg.id, { decision: "decline" });
715
+ });
716
+ } else {
717
+ appServer.respond(msg.id, { decision: "accept" });
718
+ }
719
+ return;
720
+ }
721
+
722
+ // MCP tool approval / elicitation (app-server uses mcpServer/elicitation/request)
723
+ if (method === "item/tool/requestUserInput" || method === "mcpServer/elicitation/request") {
724
+ var mcpParams = msg.params || {};
725
+ var mcpMeta = mcpParams._meta || {};
726
+ console.log("[yoke/codex] MCP approval request:", (mcpMeta.tool || "?"), "server=" + (mcpParams.serverName || "?"));
727
+ if (onElicitation) {
728
+ var request = {
729
+ serverName: mcpParams.serverName || (mcpMeta.tool || "Tool"),
730
+ message: mcpParams.message || mcpParams.prompt || "",
731
+ mode: mcpParams.url ? "url" : "form",
732
+ url: mcpParams.url || null,
733
+ elicitationId: mcpParams.elicitationId || null,
734
+ requestedSchema: mcpParams.requestedSchema || null,
735
+ };
736
+ if (!request.requestedSchema && Array.isArray(mcpParams.questions) && mcpParams.questions.length > 0) {
737
+ var schema = { type: "object", properties: {}, required: [] };
738
+ for (var qi = 0; qi < mcpParams.questions.length; qi++) {
739
+ var q = mcpParams.questions[qi];
740
+ var qid = q.id || ("question_" + (qi + 1));
741
+ schema.required.push(qid);
742
+ if (Array.isArray(q.options) && q.options.length > 0) {
743
+ schema.properties[qid] = {
744
+ type: "string",
745
+ description: q.question || q.prompt || qid,
746
+ enum: q.options.map(function(opt) { return opt && (opt.value || opt.label) ? (opt.value || opt.label) : ""; }).filter(Boolean),
747
+ };
748
+ } else {
749
+ schema.properties[qid] = {
750
+ type: "string",
751
+ description: q.question || q.prompt || qid,
752
+ };
753
+ }
754
+ }
755
+ request.requestedSchema = schema;
756
+ }
757
+ onElicitation(request, {
758
+ signal: { addEventListener: function() {} },
759
+ }).then(function(result) {
760
+ appServer.respond(msg.id, result || { action: "reject" });
761
+ }).catch(function(err) {
762
+ console.error("[yoke/codex] elicitation_response send failed:", err.message || err);
763
+ appServer.respond(msg.id, { action: "reject" });
764
+ });
765
+ } else if (canUseTool) {
766
+ canUseTool("mcp__" + (mcpParams.serverName || "unknown") + "__" + (mcpMeta.tool || "call"), mcpParams, {}).then(function(decision) {
767
+ appServer.respond(msg.id, { action: isApproved(decision) ? "accept" : "decline" });
768
+ }).catch(function(err) {
769
+ console.error("[yoke/codex] MCP canUseTool error:", err.message);
770
+ appServer.respond(msg.id, { action: "decline" });
771
+ });
772
+ } else {
773
+ appServer.respond(msg.id, { action: "accept" });
774
+ }
775
+ return;
776
+ }
777
+
778
+ // Regular events: flatten and push to iterator
779
+ var yokeEvents = flattenEvent(msg, state);
780
+ for (var i = 0; i < yokeEvents.length; i++) {
781
+ pushEvent(yokeEvents[i]);
782
+ }
783
+
784
+ // Resolve turn promise when turn ends
785
+ if (method === "turn/completed" || method === "turn/failed") {
786
+ if (turnResolve) {
787
+ var resolve = turnResolve;
788
+ turnResolve = null;
789
+ resolve();
790
+ }
791
+ }
792
+ }
793
+
794
+ // --- Main query loop ---
795
+ async function runQueryLoop(initialMessage) {
796
+ // Prepend system prompt (project instructions from YOKE layer) to first message.
797
+ // initialMessage may be a string (text-only) or an array of content items
798
+ // (e.g. [{ type: "text", text: "..." }, ...] when images/attachments are present).
799
+ // Naive string concatenation on an array coerces it via toString(), producing
800
+ // "[object Object]" inside the prompt, so we must branch on the shape.
801
+ var currentMessage;
802
+ if (!systemPrompt) {
803
+ currentMessage = initialMessage;
804
+ } else if (typeof initialMessage === "string") {
805
+ currentMessage = systemPrompt + "\n\n" + initialMessage;
806
+ } else if (Array.isArray(initialMessage)) {
807
+ // Prepend systemPrompt to the first text item; if none exists, insert one.
808
+ var cloned = initialMessage.slice();
809
+ var injected = false;
810
+ for (var i = 0; i < cloned.length; i++) {
811
+ if (cloned[i] && cloned[i].type === "text") {
812
+ cloned[i] = {
813
+ type: "text",
814
+ text: systemPrompt + "\n\n" + (cloned[i].text || ""),
815
+ };
816
+ injected = true;
817
+ break;
818
+ }
819
+ }
820
+ if (!injected) {
821
+ cloned.unshift({ type: "text", text: systemPrompt });
822
+ }
823
+ currentMessage = cloned;
824
+ } else {
825
+ currentMessage = initialMessage;
826
+ }
827
+
828
+ // Register with the multiplexed event handler so concurrent queries on the
829
+ // same app-server instance don't clobber each other's handler. Start with
830
+ // threadId=null (receives all events) and narrow to the specific thread once
831
+ // we know it, so events that arrive before thread/started are not dropped.
832
+ var _handlerEntry = appServer.addEventHandler(handleServerEvent, null);
833
+
834
+ try {
835
+ // Start or resume thread
836
+ var threadParams = {
837
+ model: queryOpts.model || "gpt-5.4",
838
+ sandbox: queryOpts.sandboxMode || "workspace-write",
839
+ approvalPolicy: queryOpts.approvalPolicy || "on-failure",
840
+ cwd: queryOpts.cwd,
841
+ skipGitRepoCheck: true,
842
+ };
843
+ if (queryOpts.modelReasoningEffort) {
844
+ threadParams.modelReasoningEffort = queryOpts.modelReasoningEffort;
845
+ }
846
+ if (queryOpts.webSearchMode) {
847
+ threadParams.webSearchMode = queryOpts.webSearchMode;
848
+ }
849
+
850
+ var threadResult;
851
+ if (queryOpts.resumeSessionId) {
852
+ threadResult = await appServer.send("thread/resume", {
853
+ threadId: queryOpts.resumeSessionId,
854
+ model: threadParams.model,
855
+ sandbox: threadParams.sandbox,
856
+ approvalPolicy: threadParams.approvalPolicy,
857
+ cwd: threadParams.cwd,
858
+ }, 60000);
859
+ } else {
860
+ threadResult = await appServer.send("thread/start", threadParams, 60000);
861
+ }
862
+
863
+ if (threadResult && threadResult.thread) {
864
+ state.threadId = threadResult.thread.id;
865
+ // Narrow the handler to only receive events for this thread so other
866
+ // concurrent queries (e.g. auto-title) are not routed to us.
867
+ appServer.updateHandlerThreadId(_handlerEntry, state.threadId);
868
+ }
869
+
870
+ while (!isCancelled()) {
871
+ // Reset per-turn state
872
+ state.turnStarted = false;
873
+ state.textBlocks = {};
874
+ state.textLengths = {};
875
+ state.thinkingBlocks = {};
876
+ state.thinkingLengths = {};
877
+ state.toolBlocks = {};
878
+ state.commandInputs = {};
879
+ state.planTexts = {};
880
+
881
+ // Start turn
882
+ var turnPromise = new Promise(function(resolve) { turnResolve = resolve; });
883
+
884
+ var input;
885
+ if (typeof currentMessage === "string") {
886
+ input = [{ type: "text", text: currentMessage }];
887
+ } else {
888
+ input = currentMessage;
889
+ }
890
+
891
+ // Detect $<skill-name> references (Claude skills) and inject skill input items
892
+ var availableSkills = discoverClaudeSkills(queryOpts.cwd);
893
+ var skillItemsToInject = [];
894
+ var injected = {};
895
+ for (var ii = 0; ii < input.length; ii++) {
896
+ if (input[ii].type === "text" && input[ii].text) {
897
+ var parsed = parseSkillRefs(input[ii].text, availableSkills);
898
+ for (var si = 0; si < parsed.skills.length; si++) {
899
+ if (!injected[parsed.skills[si].name]) {
900
+ injected[parsed.skills[si].name] = true;
901
+ skillItemsToInject.push({ type: "skill", name: parsed.skills[si].name, path: parsed.skills[si].path });
902
+ }
903
+ }
904
+ }
905
+ }
906
+ if (skillItemsToInject.length > 0) {
907
+ console.log("[yoke/codex] injecting Claude skills:", skillItemsToInject.map(function(s) { return s.name; }).join(", "));
908
+ input = input.concat(skillItemsToInject);
909
+ }
910
+
911
+ await appServer.send("turn/start", {
912
+ threadId: state.threadId,
913
+ input: input,
914
+ }, 60000);
915
+
916
+ // Wait for turn to complete
917
+ await turnPromise;
918
+
919
+ if (isCancelled()) break;
920
+
921
+ // Wait for next message (multi-turn)
922
+ var nextMsg = await waitForMessage();
923
+ if (nextMsg === null) break;
924
+ currentMessage = nextMsg;
925
+ }
926
+ } catch (e) {
927
+ // Suppress AbortError when the user stopped the query.
928
+ if (!isCancelled() && e.name !== "AbortError") {
929
+ console.error("[yoke/codex] runQueryLoop error:", e.message || e);
930
+ console.error("[yoke/codex] stack:", e.stack || "(no stack)");
931
+ pushEvent({
932
+ yokeType: "error",
933
+ text: e.message || String(e),
934
+ });
935
+ }
936
+ } finally {
937
+ // Always deregister this query's handler so it doesn't receive stale events
938
+ // from a future query on the same app-server thread ID.
939
+ appServer.removeEventHandler(_handlerEntry);
940
+ }
941
+
942
+ state.done = true;
943
+ endIterator();
944
+ }
945
+
946
+ var handle = {
947
+ [Symbol.asyncIterator]: function() {
948
+ return {
949
+ next: function() {
950
+ if (eventBuffer.length > 0) {
951
+ return Promise.resolve({ value: eventBuffer.shift(), done: false });
952
+ }
953
+ if (iteratorDone) {
954
+ return Promise.resolve({ value: undefined, done: true });
955
+ }
956
+ return new Promise(function(resolve) { eventWaiting = resolve; });
957
+ },
958
+ };
959
+ },
960
+
961
+ pushMessage: function(text, images) {
962
+ var input;
963
+ if (images && images.length > 0) {
964
+ input = [];
965
+ for (var i = 0; i < images.length; i++) {
966
+ // Codex supports local_image with path, not base64
967
+ // For now, text-only
968
+ }
969
+ input.push({ type: "text", text: text || "" });
970
+ } else {
971
+ input = text || "";
972
+ }
973
+
974
+ if (!state.loopStarted) {
975
+ state.loopStarted = true;
976
+ runQueryLoop(input);
977
+ } else {
978
+ pushMessageToQueue(input);
979
+ }
980
+ },
981
+
982
+ setModel: function(model) {
983
+ // Model is set at thread creation. Cannot change mid-thread.
984
+ return Promise.resolve();
985
+ },
986
+
987
+ setEffort: function(effort) {
988
+ // Stored for next thread
989
+ return Promise.resolve();
990
+ },
991
+
992
+ setToolPolicy: function(policy) {
993
+ // Codex uses approvalPolicy at thread creation
994
+ return Promise.resolve();
995
+ },
996
+
997
+ stopTask: function(taskId) {
998
+ // Codex doesn't expose sub-task stopping
999
+ return Promise.resolve();
1000
+ },
1001
+
1002
+ getContextUsage: function() {
1003
+ return Promise.resolve(state.lastUsage);
1004
+ },
1005
+
1006
+ abort: function() {
1007
+ console.log("[yoke/codex] handle.abort() called, threadId=" + state.threadId + " already aborted=" + state.aborted);
1008
+ state.aborted = true;
1009
+ // Send turn/interrupt to stop the server-side turn
1010
+ if (state.threadId && appServer.started) {
1011
+ appServer.send("turn/interrupt", { threadId: state.threadId }, 5000).catch(function() {});
1012
+ }
1013
+ // End iterator immediately. sdk-bridge's post-loop code checks
1014
+ // session.taskStopRequested and sends the interrupted message + done.
1015
+ // This matches Claude's abort pattern.
1016
+ if (turnResolve) {
1017
+ var resolve = turnResolve;
1018
+ turnResolve = null;
1019
+ resolve();
1020
+ }
1021
+ endIterator();
1022
+ },
1023
+
1024
+ close: function() {
1025
+ messageQueueEnded = true;
1026
+ if (messageWaiting) {
1027
+ var resolve = messageWaiting;
1028
+ messageWaiting = null;
1029
+ resolve(null);
1030
+ }
1031
+ endIterator();
1032
+ },
1033
+
1034
+ endInput: function() {
1035
+ messageQueueEnded = true;
1036
+ if (messageWaiting) {
1037
+ var resolve = messageWaiting;
1038
+ messageWaiting = null;
1039
+ resolve(null);
1040
+ }
1041
+ },
1042
+ };
1043
+
1044
+ // Listen for external abort (sdk-bridge's stopTask calls session.abortController.abort())
1045
+ if (abortController && abortController.signal) {
1046
+ abortController.signal.addEventListener("abort", function() {
1047
+ if (!state.aborted) handle.abort();
1048
+ }, { once: true });
1049
+ }
1050
+
1051
+ return handle;
1052
+ }
1053
+
1054
+ // --- Adapter factory ---
1055
+
1056
+ function createCodexAdapter(opts) {
1057
+ var _cwd = (opts && opts.cwd) || process.cwd();
1058
+ var _slug = (opts && opts.slug) || "";
1059
+ var _defaultInitOpts = Object.assign({}, opts || {});
1060
+ var _cachedModels = [];
1061
+ var _appServer = null;
1062
+ var _initPromise = null;
1063
+ var _shutdownPromise = null;
1064
+ var _refCount = 0;
1065
+ var _lastActiveAt = Date.now();
1066
+ var _shuttingDown = false;
1067
+ var _activeQueries = [];
1068
+
1069
+ function updateLastActiveAt() {
1070
+ _lastActiveAt = Date.now();
1071
+ }
1072
+
1073
+ function registerActiveQuery(entry) {
1074
+ _activeQueries.push(entry);
1075
+ }
1076
+
1077
+ function removeActiveQuery(entry) {
1078
+ var next = [];
1079
+ for (var i = 0; i < _activeQueries.length; i++) {
1080
+ if (_activeQueries[i] !== entry) next.push(_activeQueries[i]);
1081
+ }
1082
+ _activeQueries = next;
1083
+ }
1084
+
1085
+ function decrementRefCount() {
1086
+ if (_refCount > 0) {
1087
+ _refCount--;
1088
+ } else {
1089
+ console.error("[yoke/codex] refCount negative, bug!");
1090
+ _refCount = 0;
1091
+ }
1092
+ updateLastActiveAt();
1093
+ }
1094
+
1095
+ function buildReadyResponse(skillNames) {
1096
+ return {
1097
+ models: _cachedModels,
1098
+ defaultModel: "gpt-5.4",
1099
+ skills: skillNames || [],
1100
+ slashCommands: skillNames || [],
1101
+ fastModeState: null,
1102
+ capabilities: {
1103
+ thinking: true,
1104
+ betas: false,
1105
+ rewind: false,
1106
+ sessionResume: true,
1107
+ promptSuggestions: true,
1108
+ elicitation: true,
1109
+ fileCheckpointing: false,
1110
+ contextCompacting: false,
1111
+ toolPolicy: ["ask", "allow-all"],
1112
+ },
1113
+ };
1114
+ }
1115
+
1116
+ function clearRuntimeState() {
1117
+ _appServer = null;
1118
+ _initPromise = null;
1119
+ _cachedModels = [];
1120
+ _refCount = 0;
1121
+ _activeQueries = [];
1122
+ updateLastActiveAt();
1123
+ }
1124
+
1125
+ function waitForRefCount(targetCount, timeoutMs) {
1126
+ var deadline = Date.now() + (timeoutMs || 5000);
1127
+ return new Promise(function(resolve) {
1128
+ function tick() {
1129
+ if (_refCount <= targetCount) {
1130
+ resolve(true);
1131
+ return;
1132
+ }
1133
+ if (Date.now() >= deadline) {
1134
+ resolve(false);
1135
+ return;
1136
+ }
1137
+ setTimeout(tick, 50);
1138
+ }
1139
+ tick();
1140
+ });
1141
+ }
1142
+
1143
+ function stopAppServer(deadlineMs) {
1144
+ var proc = _appServer && _appServer.proc ? _appServer.proc : null;
1145
+ if (!_appServer) return Promise.resolve(true);
1146
+ try {
1147
+ _appServer.stop();
1148
+ } catch (e) {
1149
+ console.error("[yoke/codex] App-server stop error:", e.message || e);
1150
+ }
1151
+ if (!proc) return Promise.resolve(true);
1152
+ var remaining = (typeof deadlineMs === "number") ? Math.max(0, deadlineMs - Date.now()) : 5000;
1153
+ return waitForProcessExit(proc, remaining).then(function(exited) {
1154
+ if (!exited) {
1155
+ try {
1156
+ proc.kill("SIGKILL");
1157
+ } catch (e) {}
1158
+ }
1159
+ return exited;
1160
+ });
1161
+ }
1162
+
1163
+ function beginShutdown(force, idleMs) {
1164
+ if (_shutdownPromise) return _shutdownPromise;
1165
+ if (_shuttingDown) return null;
1166
+
1167
+ _shuttingDown = true;
1168
+
1169
+ _shutdownPromise = (async function() {
1170
+ var deadline = Date.now() + 5000;
1171
+ var shouldAbort = !!force;
1172
+
1173
+ if (_initPromise) {
1174
+ try {
1175
+ await Promise.race([
1176
+ _initPromise.catch(function() { return null; }),
1177
+ waitMs(Math.max(0, deadline - Date.now())),
1178
+ ]);
1179
+ } catch (e) {}
1180
+ }
1181
+
1182
+ if (shouldAbort && _activeQueries.length > 0) {
1183
+ var active = _activeQueries.slice();
1184
+ for (var i = 0; i < active.length; i++) {
1185
+ try {
1186
+ if (active[i] && active[i].abort) active[i].abort();
1187
+ } catch (e) {}
1188
+ }
1189
+ await waitForRefCount(0, Math.max(0, deadline - Date.now()));
1190
+ }
1191
+
1192
+ if (_appServer) {
1193
+ await stopAppServer(deadline);
1194
+ }
1195
+
1196
+ clearRuntimeState();
1197
+ _shuttingDown = false;
1198
+ _shutdownPromise = null;
1199
+ return true;
1200
+ })().catch(function(err) {
1201
+ clearRuntimeState();
1202
+ _shuttingDown = false;
1203
+ _shutdownPromise = null;
1204
+ throw err;
1205
+ });
1206
+
1207
+ return _shutdownPromise;
1208
+ }
1209
+
1210
+ var adapter = {
1211
+ vendor: "codex",
1212
+
1213
+ init: function(initOpts) {
1214
+ if (_shuttingDown) {
1215
+ return Promise.reject(createShutdownError());
1216
+ }
1217
+
1218
+ var effectiveInitOpts = Object.assign({}, _defaultInitOpts, initOpts || {});
1219
+
1220
+ // Already initialized - return cached result
1221
+ if (_appServer && _appServer.started && _cachedModels.length > 0) {
1222
+ return Promise.resolve(buildReadyResponse([]));
1223
+ }
1224
+
1225
+ // Deduplicate concurrent init calls
1226
+ if (_initPromise) return _initPromise;
1227
+
1228
+ _initPromise = (async function() {
1229
+ var serverOpts = { cwd: _cwd };
1230
+
1231
+ // Extract adapter options
1232
+ if (effectiveInitOpts && effectiveInitOpts.adapterOptions && effectiveInitOpts.adapterOptions.CODEX) {
1233
+ var co = effectiveInitOpts.adapterOptions.CODEX;
1234
+ if (co.apiKey) serverOpts.env = Object.assign({}, serverOpts.env || {}, { OPENAI_API_KEY: co.apiKey });
1235
+ if (co.baseUrl) serverOpts.env = Object.assign({}, serverOpts.env || {}, { OPENAI_BASE_URL: co.baseUrl });
1236
+ if (co.config) serverOpts.config = co.config;
1237
+ }
1238
+
1239
+ // Track 1: Read local MCP server definitions from ~/.clay/mcp.json
1240
+ // and inject into Codex config so Codex manages them natively.
1241
+ var mcpServerConfig = {};
1242
+ try {
1243
+ var mcpLocal = require("../../mcp-local");
1244
+ var localMcpServers = mcpLocal.readMergedServers();
1245
+ var mcpNames = Object.keys(localMcpServers);
1246
+ for (var mi = 0; mi < mcpNames.length; mi++) {
1247
+ var ms = localMcpServers[mcpNames[mi]];
1248
+ if (ms.command) {
1249
+ mcpServerConfig[mcpNames[mi]] = { command: ms.command, args: ms.args || [] };
1250
+ if (ms.env && Object.keys(ms.env).length > 0) {
1251
+ mcpServerConfig[mcpNames[mi]].env = ms.env;
1252
+ }
1253
+ }
1254
+ }
1255
+ } catch (e) {
1256
+ console.error("[codex] Failed to read local MCP config:", e.message);
1257
+ }
1258
+
1259
+ // Track 2: Add clay-tools bridge server for in-app + remote MCP tools.
1260
+ var bridgePath = require("path").join(__dirname, "..", "mcp-bridge-server.js");
1261
+ var clayPort = effectiveInitOpts.clayPort || process.env.CLAY_PORT || 2633;
1262
+ var clayTls = effectiveInitOpts.clayTls || false;
1263
+ var clayAuthToken = effectiveInitOpts.clayAuthToken || "";
1264
+ var claySlug = effectiveInitOpts.slug || _slug || "";
1265
+ try {
1266
+ if (require("fs").existsSync(bridgePath)) {
1267
+ var bridgeArgs = [bridgePath, "--port", String(clayPort), "--slug", claySlug];
1268
+ if (clayTls) bridgeArgs.push("--tls");
1269
+ var bridgeEnv = {};
1270
+ if (clayAuthToken) bridgeEnv.CLAY_AUTH_TOKEN = clayAuthToken;
1271
+ mcpServerConfig["clay-tools"] = {
1272
+ command: process.execPath,
1273
+ args: bridgeArgs,
1274
+ env: Object.keys(bridgeEnv).length > 0 ? bridgeEnv : undefined,
1275
+ };
1276
+ }
1277
+ } catch (e) {
1278
+ console.error("[codex] Failed to configure clay-tools bridge:", e.message);
1279
+ }
1280
+
1281
+ if (Object.keys(mcpServerConfig).length > 0) {
1282
+ serverOpts.config = Object.assign({}, serverOpts.config || {}, {
1283
+ mcp_servers: mcpServerConfig,
1284
+ });
1285
+ console.log("[codex] MCP servers configured:", Object.keys(mcpServerConfig).join(", "));
1286
+ try {
1287
+ var names = Object.keys(mcpServerConfig);
1288
+ for (var di = 0; di < names.length; di++) {
1289
+ var sc = mcpServerConfig[names[di]];
1290
+ console.log("[codex] MCP server '" + names[di] + "': command=" + sc.command + " args=" + JSON.stringify(sc.args));
1291
+ }
1292
+ } catch (e) {}
1293
+ }
1294
+
1295
+ // Spawn and initialize app-server
1296
+ _appServer = new CodexAppServer(null, serverOpts);
1297
+ await _appServer.start();
1298
+
1299
+ await _appServer.send("initialize", {
1300
+ clientInfo: { name: "clay", title: "Clay", version: "1.0.0" },
1301
+ capabilities: { experimentalApi: true },
1302
+ });
1303
+ _appServer.notify("initialized", {});
1304
+
1305
+ if (_shuttingDown) {
1306
+ await stopAppServer(Date.now() + 1000);
1307
+ throw createShutdownError();
1308
+ }
1309
+
1310
+ console.log("[codex] App-server initialized, models: gpt-5.4, gpt-5.4-mini, gpt-5.3-codex, gpt-5.3-codex-spark, gpt-5.2");
1311
+
1312
+ _cachedModels = [
1313
+ "gpt-5.4",
1314
+ "gpt-5.4-mini",
1315
+ "gpt-5.3-codex",
1316
+ "gpt-5.3-codex-spark",
1317
+ "gpt-5.2",
1318
+ ];
1319
+
1320
+ // Discover skills: built-in Codex skills + Claude skills
1321
+ var skillNames = [];
1322
+ try {
1323
+ var REAL_HOME;
1324
+ try { REAL_HOME = require("../../config").REAL_HOME; } catch (e) { REAL_HOME = require("os").homedir(); }
1325
+ var claudeSkillsDir = require("path").join(REAL_HOME, ".claude", "skills");
1326
+ var extraRoots = _cwd ? [{ cwd: _cwd, extraUserRoots: [claudeSkillsDir] }] : [];
1327
+ var skillsResult = await _appServer.send("skills/list", {
1328
+ cwds: _cwd ? [_cwd] : [],
1329
+ forceReload: true,
1330
+ perCwdExtraUserRoots: extraRoots,
1331
+ }, 10000).catch(function(e) {
1332
+ console.error("[codex] skills/list failed:", e.message);
1333
+ return null;
1334
+ });
1335
+ // Response shape: { data: [{ cwd, skills: [{ name, ... }] }] }
1336
+ if (skillsResult && skillsResult.data) {
1337
+ for (var di = 0; di < skillsResult.data.length; di++) {
1338
+ var entry = skillsResult.data[di];
1339
+ if (!entry.skills) continue;
1340
+ for (var sk = 0; sk < entry.skills.length; sk++) {
1341
+ if (entry.skills[sk].name && skillNames.indexOf(entry.skills[sk].name) === -1) {
1342
+ skillNames.push(entry.skills[sk].name);
1343
+ }
1344
+ }
1345
+ }
1346
+ }
1347
+ // Also discover Claude skills directly as fallback
1348
+ var claudeSkills = discoverClaudeSkills(_cwd);
1349
+ var claudeSkillNames = Object.keys(claudeSkills);
1350
+ for (var csn = 0; csn < claudeSkillNames.length; csn++) {
1351
+ if (skillNames.indexOf(claudeSkillNames[csn]) === -1) skillNames.push(claudeSkillNames[csn]);
1352
+ }
1353
+ console.log("[codex] Discovered skills:", skillNames.length, "(" + skillNames.slice(0, 5).join(", ") + (skillNames.length > 5 ? "..." : "") + ")");
1354
+ } catch (e) {
1355
+ console.error("[codex] Failed to discover skills:", e.message);
1356
+ }
1357
+
1358
+ if (_shuttingDown) {
1359
+ await stopAppServer(Date.now() + 1000);
1360
+ throw createShutdownError();
1361
+ }
1362
+
1363
+ _initPromise = null;
1364
+ updateLastActiveAt();
1365
+
1366
+ return buildReadyResponse(skillNames);
1367
+ })();
1368
+
1369
+ return _initPromise;
1370
+ },
1371
+
1372
+ supportedModels: function() {
1373
+ return Promise.resolve(_cachedModels.slice());
1374
+ },
1375
+
1376
+ createToolServer: function(def) {
1377
+ // Codex handles tools internally (file ops, bash, etc.)
1378
+ // MCP tools are configured via Codex config, not SDK.
1379
+ console.log("[yoke/codex] createToolServer skipped: Codex handles tools internally");
1380
+ return null;
1381
+ },
1382
+
1383
+ createQuery: async function(queryOpts) {
1384
+ if (_shuttingDown) {
1385
+ throw createShutdownError();
1386
+ }
1387
+
1388
+ if (!_appServer || !_appServer.started) {
1389
+ await adapter.init(queryOpts || {});
1390
+ }
1391
+
1392
+ if (_shuttingDown) {
1393
+ throw createShutdownError();
1394
+ }
1395
+
1396
+ if (!_appServer || !_appServer.started) {
1397
+ throw new Error("[yoke/codex] Adapter not initialized. Call init() first.");
1398
+ }
1399
+
1400
+ var model = queryOpts.model || "gpt-5.4";
1401
+ var ac = queryOpts.abortController || new AbortController();
1402
+ var activeEntry = {
1403
+ abort: function() {
1404
+ try {
1405
+ ac.abort();
1406
+ } catch (e) {}
1407
+ },
1408
+ };
1409
+
1410
+ // Map YOKE options to Codex thread options
1411
+ var codexOpts = (queryOpts.adapterOptions && queryOpts.adapterOptions.CODEX) || {};
1412
+
1413
+ var handleOpts = {
1414
+ model: model,
1415
+ cwd: queryOpts.cwd || _cwd,
1416
+ systemPrompt: queryOpts.systemPrompt || "",
1417
+ abortController: ac,
1418
+ canUseTool: queryOpts.canUseTool || null,
1419
+ onElicitation: queryOpts.onElicitation || null,
1420
+ resumeSessionId: queryOpts.resumeSessionId || null,
1421
+ };
1422
+
1423
+ // Reasoning effort
1424
+ if (queryOpts.effort || codexOpts.modelReasoningEffort) {
1425
+ handleOpts.modelReasoningEffort = codexOpts.modelReasoningEffort || queryOpts.effort || "medium";
1426
+ }
1427
+
1428
+ // Tool policy -> approval mode
1429
+ if (queryOpts.toolPolicy === "allow-all") {
1430
+ handleOpts.approvalPolicy = "never";
1431
+ } else {
1432
+ handleOpts.approvalPolicy = codexOpts.approvalPolicy || "on-failure";
1433
+ }
1434
+
1435
+ // Sandbox mode
1436
+ handleOpts.sandboxMode = codexOpts.sandboxMode || "workspace-write";
1437
+
1438
+ // Web search
1439
+ if (codexOpts.webSearchMode && codexOpts.webSearchMode !== "disabled") {
1440
+ handleOpts.webSearchMode = codexOpts.webSearchMode;
1441
+ }
1442
+
1443
+ console.log("[yoke/codex] createQuery: model=" + model + " approval=" + handleOpts.approvalPolicy + " sandbox=" + handleOpts.sandboxMode);
1444
+
1445
+ _refCount++;
1446
+ registerActiveQuery(activeEntry);
1447
+
1448
+ var handle;
1449
+ try {
1450
+ handleOpts.onFinished = function() {
1451
+ removeActiveQuery(activeEntry);
1452
+ decrementRefCount();
1453
+ };
1454
+ handle = createCodexQueryHandle(_appServer, handleOpts);
1455
+ } catch (e) {
1456
+ removeActiveQuery(activeEntry);
1457
+ decrementRefCount();
1458
+ throw e;
1459
+ }
1460
+
1461
+ activeEntry.handle = handle;
1462
+ activeEntry.abort = function() {
1463
+ try {
1464
+ if (handle && typeof handle.abort === "function") {
1465
+ handle.abort();
1466
+ } else {
1467
+ ac.abort();
1468
+ }
1469
+ } catch (e) {}
1470
+ };
1471
+
1472
+ return handle;
1473
+ },
1474
+
1475
+ // --- Title generation ---
1476
+ generateTitle: async function(messages, opts) {
1477
+ var systemPrompt = "You are a title generator. Output only a short title (3-8 words). No quotes, no punctuation at the end, no explanation.";
1478
+ var prompt = "Below is a conversation between a user and an AI assistant. Generate a short, descriptive title (3-8 words) that captures the main topic. Reply with ONLY the title, nothing else.\n\n";
1479
+ for (var i = 0; i < messages.length; i++) {
1480
+ prompt += "User message " + (i + 1) + ": " + messages[i] + "\n";
1481
+ }
1482
+ var ac = new AbortController();
1483
+ var handle = await adapter.createQuery({
1484
+ cwd: (opts && opts.cwd) || _cwd,
1485
+ systemPrompt: systemPrompt,
1486
+ model: "gpt-5.4-mini",
1487
+ abortController: ac,
1488
+ canUseTool: function() { return Promise.resolve({ behavior: "deny", message: "No tools." }); },
1489
+ });
1490
+ handle.pushMessage(prompt);
1491
+ var title = "";
1492
+ var streamed = false;
1493
+ try {
1494
+ for await (var msg of handle) {
1495
+ if (msg.yokeType === "text_delta" && msg.text) {
1496
+ streamed = true;
1497
+ title += msg.text;
1498
+ } else if (msg.yokeType === "message" && msg.messageRole === "assistant" && !streamed && msg.content) {
1499
+ var content = msg.content;
1500
+ if (Array.isArray(content)) {
1501
+ for (var ci = 0; ci < content.length; ci++) {
1502
+ if (content[ci].type === "text" && content[ci].text) {
1503
+ title += content[ci].text;
1504
+ }
1505
+ }
1506
+ }
1507
+ } else if (msg.yokeType === "result") {
1508
+ break;
1509
+ }
1510
+ }
1511
+ } finally {
1512
+ handle.close();
1513
+ }
1514
+ return title.replace(/[\r\n]+/g, " ").replace(/^["'\s]+|["'\s.]+$/g, "").trim();
1515
+ },
1516
+
1517
+ // Codex has session persistence via thread IDs
1518
+ getSessionInfo: function(sessionId) {
1519
+ return Promise.resolve(null);
1520
+ },
1521
+ listSessions: function() { return Promise.resolve([]); },
1522
+ renameSession: function() { return Promise.resolve(); },
1523
+ forkSession: function(threadId, opts) {
1524
+ if (!_appServer || !_appServer.started) return Promise.resolve(null);
1525
+ return _appServer.send("thread/fork", { threadId: threadId }, 30000).then(function(result) {
1526
+ var newThreadId = (result && result.thread) ? result.thread.id : null;
1527
+ if (!newThreadId) throw new Error("thread/fork did not return a new thread id");
1528
+ return { sessionId: newThreadId };
1529
+ });
1530
+ },
1531
+ rollbackThread: function(threadId, numTurns) {
1532
+ if (!_appServer || !_appServer.started) return Promise.resolve(null);
1533
+ return _appServer.send("thread/rollback", { threadId: threadId, numTurns: numTurns }, 30000);
1534
+ },
1535
+
1536
+ // Shutdown the app-server process
1537
+ shutdown: function() {
1538
+ return beginShutdown(true);
1539
+ },
1540
+
1541
+ shutdownIfIdle: function(idleMs) {
1542
+ if (_shuttingDown || _shutdownPromise) return Promise.resolve(false);
1543
+ if (_initPromise) return Promise.resolve(false);
1544
+ if (!_appServer) return Promise.resolve(false);
1545
+ if (_refCount > 0) return Promise.resolve(false);
1546
+ if (Date.now() - _lastActiveAt < (idleMs || 0)) return Promise.resolve(false);
1547
+ return beginShutdown(false).then(function() {
1548
+ console.log("[yoke/codex] Reclaimed idle adapter for project " + (_slug || _cwd));
1549
+ return true;
1550
+ });
1551
+ },
1552
+ };
1553
+
1554
+ return adapter;
1555
+ }
1556
+
1557
+ module.exports = {
1558
+ createCodexAdapter: createCodexAdapter,
1559
+ };