arco-workbench 0.1.8 → 0.1.9

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 (145) hide show
  1. package/CONTRIBUTING.md +11 -0
  2. package/README.md +7 -5
  3. package/client/dist/assets/{PhosphorBackdrop-D7jdAV_G.js → PhosphorBackdrop-DRu16-Is.js} +1 -1
  4. package/client/dist/assets/{ThemedBackgroundShaderImpl-DrDm60h8.js → ThemedBackgroundShaderImpl-BLdwwQ4D.js} +1 -1
  5. package/client/dist/assets/{XtermView-BGFujb1e.js → XtermView-Xk7_9JaH.js} +1 -1
  6. package/client/dist/assets/{galleryEditor-D951A2sE.js → galleryEditor-CI8ClzBa.js} +1 -1
  7. package/client/dist/assets/{index-DD9kFGsF.css → index-BEFgrUJJ.css} +1 -1
  8. package/client/dist/assets/{index-CsVy3eZm.js → index-C7WzZfsr.js} +246 -244
  9. package/client/dist/index.html +2 -2
  10. package/client/src/App.tsx +2 -0
  11. package/client/src/components/ChatMessage.tsx +33 -8
  12. package/client/src/components/ChatModeView.tsx +2 -0
  13. package/client/src/components/ClusterRightPanel/SkillsControl.tsx +25 -8
  14. package/client/src/components/CodexLateCommand.tsx +34 -0
  15. package/client/src/components/DialogShell.tsx +2 -0
  16. package/client/src/components/MemberCard.tsx +4 -1
  17. package/client/src/components/MemberPane.tsx +3 -1
  18. package/client/src/components/PhoneUpload.tsx +288 -0
  19. package/client/src/components/PrimaryStatus.tsx +14 -6
  20. package/client/src/components/RuntimeStateBanner.tsx +5 -0
  21. package/client/src/components/SkillEditorDialog.tsx +2 -2
  22. package/client/src/components/SkillsSettings.tsx +17 -5
  23. package/client/src/components/TerminalInput.tsx +3 -1
  24. package/client/src/components/WorkflowView.tsx +2 -0
  25. package/client/src/explorer/ArtifactsLens.tsx +37 -28
  26. package/client/src/explorer/ExplorerApp.tsx +5 -4
  27. package/client/src/explorer/types.ts +8 -3
  28. package/client/src/help/content/cluster.tsx +11 -1
  29. package/client/src/help/content/composer.tsx +18 -1
  30. package/client/src/help/content/header.tsx +2 -1
  31. package/client/src/help/content/misc.tsx +1 -1
  32. package/client/src/help/content/settings.tsx +1 -1
  33. package/client/src/help/manualSections/clusters.tsx +3 -0
  34. package/client/src/help/manualSections/configuration.tsx +3 -1
  35. package/client/src/help/manualSections/gettingStarted.tsx +4 -4
  36. package/client/src/help/manualSections/maintenance.tsx +7 -6
  37. package/client/src/help/manualSections/powerFeatures.tsx +3 -2
  38. package/client/src/help/manualSections/workspace.tsx +30 -0
  39. package/client/src/stores/appStore.ts +7 -0
  40. package/client/src/stores/appStore.types.ts +4 -0
  41. package/client/src/styles/global.css +109 -0
  42. package/client/src/utils/phoneTheme.ts +38 -0
  43. package/client/src/utils/phoneUploadApi.ts +10 -0
  44. package/client/src/ws/handleServerMessage.ts +23 -6
  45. package/docs/CLIENT.md +7 -1
  46. package/docs/FEATURES.md +6 -3
  47. package/docs/GETTING_STARTED.md +8 -3
  48. package/docs/INDEX.md +1 -1
  49. package/docs/OPERATIONS.md +199 -48
  50. package/docs/PROTOCOL_CLUSTER.md +9 -1
  51. package/docs/PROVIDERS.md +34 -0
  52. package/docs/SETTINGS.md +5 -3
  53. package/native/darwin-arm64/manifest.json +1 -1
  54. package/native/linux-x64/manifest.json +1 -1
  55. package/native/win32-x64/manifest.json +1 -1
  56. package/node_modules/@arco/shared/dist/protocol/chat.d.ts +1 -0
  57. package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +2 -0
  58. package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +11 -0
  59. package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
  60. package/node_modules/@arco/shared/package.json +1 -1
  61. package/package.json +2 -2
  62. package/server/dist/clusterDirector.js +1 -0
  63. package/server/dist/clusterPeerOps.js +4 -1
  64. package/server/dist/clusterRehydrate.js +2 -0
  65. package/server/dist/explorerDocs.d.ts +10 -6
  66. package/server/dist/explorerDocs.js +75 -34
  67. package/server/dist/http/attachmentUpload.d.ts +13 -0
  68. package/server/dist/http/attachmentUpload.js +38 -0
  69. package/server/dist/http/browserWorktrees.d.ts +23 -0
  70. package/server/dist/http/browserWorktrees.js +120 -0
  71. package/server/dist/http/phoneUploadDrafts.d.ts +13 -0
  72. package/server/dist/http/phoneUploadDrafts.js +125 -0
  73. package/server/dist/http/phoneUploadListener.d.ts +17 -0
  74. package/server/dist/http/phoneUploadListener.js +81 -0
  75. package/server/dist/http/phoneUploadNetwork.d.ts +9 -0
  76. package/server/dist/http/phoneUploadNetwork.js +106 -0
  77. package/server/dist/http/phoneUploadPage.d.ts +2 -0
  78. package/server/dist/http/phoneUploadPage.js +136 -0
  79. package/server/dist/http/phoneUploadRouteHistory.d.ts +4 -0
  80. package/server/dist/http/phoneUploadRouteHistory.js +72 -0
  81. package/server/dist/http/phoneUploadRoutes.d.ts +4 -0
  82. package/server/dist/http/phoneUploadRoutes.js +419 -0
  83. package/server/dist/http/phoneUploadTheme.d.ts +17 -0
  84. package/server/dist/http/phoneUploadTheme.js +96 -0
  85. package/server/dist/http/projectBinding.d.ts +1 -0
  86. package/server/dist/http/projectBinding.js +3 -2
  87. package/server/dist/http/readConfinement.js +5 -1
  88. package/server/dist/http/router.js +13 -24
  89. package/server/dist/http/writeConfinement.js +19 -2
  90. package/server/dist/primitives/seedWorker.d.ts +1 -0
  91. package/server/dist/primitives/seedWorker.js +2 -1
  92. package/server/dist/providers/codex-appserver/heldCommands.d.ts +14 -0
  93. package/server/dist/providers/codex-appserver/heldCommands.js +54 -0
  94. package/server/dist/providers/codex-appserver/index.d.ts +52 -2
  95. package/server/dist/providers/codex-appserver/index.js +239 -21
  96. package/server/dist/providers/codex-appserver/lateCommands.d.ts +62 -0
  97. package/server/dist/providers/codex-appserver/lateCommands.js +195 -0
  98. package/server/dist/providers/codex-appserver/worker.d.ts +23 -1
  99. package/server/dist/providers/codex-appserver/worker.js +89 -20
  100. package/server/dist/providers/codex.js +2 -2
  101. package/server/dist/providers/codexCodeMode.d.ts +2 -1
  102. package/server/dist/providers/codexCodeMode.js +7 -3
  103. package/server/dist/workers/WorkerManager.d.ts +1 -0
  104. package/server/dist/workers/WorkerManager.js +1 -0
  105. package/server/dist/workers/processKill.d.ts +9 -1
  106. package/server/dist/workers/processKill.js +26 -10
  107. package/server/dist/ws/handoffHandlers.js +2 -0
  108. package/server/dist/ws/turnEngine.js +17 -0
  109. package/server/package.json +1 -1
  110. package/server/src/clusterDirector.ts +1 -0
  111. package/server/src/clusterPeerOps.ts +4 -1
  112. package/server/src/clusterRehydrate.ts +2 -0
  113. package/server/src/explorerDocs.ts +75 -34
  114. package/server/src/http/attachmentUpload.ts +49 -0
  115. package/server/src/http/browserWorktrees.ts +124 -0
  116. package/server/src/http/phoneUploadDrafts.ts +118 -0
  117. package/server/src/http/phoneUploadListener.ts +96 -0
  118. package/server/src/http/phoneUploadNetwork.ts +117 -0
  119. package/server/src/http/phoneUploadPage.ts +137 -0
  120. package/server/src/http/phoneUploadRouteHistory.ts +73 -0
  121. package/server/src/http/phoneUploadRoutes.ts +398 -0
  122. package/server/src/http/phoneUploadTheme.ts +97 -0
  123. package/server/src/http/projectBinding.ts +3 -2
  124. package/server/src/http/readConfinement.ts +5 -1
  125. package/server/src/http/router.ts +11 -25
  126. package/server/src/http/writeConfinement.ts +13 -2
  127. package/server/src/primitives/seedWorker.ts +3 -1
  128. package/server/src/providers/codex-appserver/heldCommands.ts +58 -0
  129. package/server/src/providers/codex-appserver/index.ts +222 -20
  130. package/server/src/providers/codex-appserver/lateCommands.ts +225 -0
  131. package/server/src/providers/codex-appserver/worker.ts +85 -21
  132. package/server/src/providers/codex.ts +2 -2
  133. package/server/src/providers/codexCodeMode.ts +8 -3
  134. package/server/src/workers/WorkerManager.ts +2 -0
  135. package/server/src/workers/processKill.ts +35 -7
  136. package/server/src/ws/handoffHandlers.ts +2 -0
  137. package/server/src/ws/turnEngine.ts +15 -0
  138. package/shared/dist/protocol/chat.d.ts +1 -0
  139. package/shared/dist/protocol/clusters.d.ts +2 -0
  140. package/shared/dist/protocol/serverMessages.d.ts +11 -0
  141. package/shared/dist/protocol/workflows.d.ts +1 -0
  142. package/shared/src/protocol/chat.ts +1 -0
  143. package/shared/src/protocol/clusters.ts +4 -5
  144. package/shared/src/protocol/serverMessages.ts +11 -0
  145. package/shared/src/protocol/workflows.ts +4 -0
@@ -1,3 +1,4 @@
1
+ import { CodexLateCommands, type HeldCommandResult } from './lateCommands.js';
1
2
  import { historyBinding } from '../handoffHistoryBinding.js';
2
3
  import { codexWebSearchMode } from '../codexWebSearch.js';
3
4
  import { codexImageToolConfig } from '../codexImageTool.js';
@@ -52,6 +53,7 @@ import type { TurnInterruptParams } from './bindings/v2/TurnInterruptParams.js';
52
53
  import type { TurnSteerParams } from './bindings/v2/TurnSteerParams.js';
53
54
  import type { TurnSteerResponse } from './bindings/v2/TurnSteerResponse.js';
54
55
  import type { ThreadStartedNotification } from './bindings/v2/ThreadStartedNotification.js';
56
+ import type { ThreadClosedNotification } from './bindings/v2/ThreadClosedNotification.js';
55
57
  import type { TurnStartedNotification } from './bindings/v2/TurnStartedNotification.js';
56
58
  import type { TurnCompletedNotification } from './bindings/v2/TurnCompletedNotification.js';
57
59
  import type { ItemStartedNotification } from './bindings/v2/ItemStartedNotification.js';
@@ -355,6 +357,9 @@ interface CurrentTurnState {
355
357
  // wall of text ("…release process.Kernel.org confirms…"). We insert a
356
358
  // paragraph break when the item id changes. Null until the first delta.
357
359
  lastAgentMsgItemId: string | null;
360
+ // The agent's final answer has started: a command that ends after this
361
+ // point was never seen by the model.
362
+ finalAnswerStarted: boolean;
358
363
  artifacts: Set<Promise<void>>;
359
364
  settling: boolean;
360
365
  }
@@ -372,6 +377,7 @@ function emptyTurnState(): CurrentTurnState {
372
377
  transientNoticeKey: null,
373
378
  transientNoticeCount: 0,
374
379
  lastAgentMsgItemId: null,
380
+ finalAnswerStarted: false,
375
381
  artifacts: new Set(),
376
382
  settling: false,
377
383
  };
@@ -676,7 +682,7 @@ export class CodexAppServerWorker extends EventEmitter {
676
682
  // element. Empty prompt + image-only payload is a valid request shape now
677
683
  // that images are first-class — no more "Please inspect the attached
678
684
  // image(s)." synthetic fallback.
679
- async beginTurn(prompt: string, appendSystemPrompt: string | undefined): Promise<void> {
685
+ async beginTurn(prompt: string, appendSystemPrompt: string | undefined, options: { continuation?: boolean } = {}): Promise<void> {
680
686
  if (this.disposed) throw new Error('codex app-server worker disposed');
681
687
  if (!this.rpc || !this.threadId) {
682
688
  throw new Error('codex app-server worker not bootstrapped');
@@ -689,7 +695,8 @@ export class CodexAppServerWorker extends EventEmitter {
689
695
  }
690
696
 
691
697
  const preparationGeneration = this.preparationGeneration;
692
- const prepared = await prepareProviderAttachments(this.config.attachments, true, undefined, false, this.config.interactionMode === 'chat' && !this.config.voiceOperator);
698
+ // A continuation carries command results, never the operator's files again.
699
+ const prepared = await prepareProviderAttachments(options.continuation ? undefined : this.config.attachments, true, undefined, false, this.config.interactionMode === 'chat' && !this.config.voiceOperator);
693
700
  if (preparationGeneration !== this.preparationGeneration) throw new Error('Worker killed');
694
701
  const modelImages = await persistProviderImages(prepared.images);
695
702
  if (preparationGeneration !== this.preparationGeneration) throw new Error('Worker killed');
@@ -1055,6 +1062,68 @@ export class CodexAppServerWorker extends EventEmitter {
1055
1062
 
1056
1063
  // ── Notification handling ────────────────────────────────────────────
1057
1064
 
1065
+ private readonly lateCommands = new CodexLateCommands((event, state) => {
1066
+ this.emit('late_command', event, state);
1067
+ }, () => this.emit('held_commands'));
1068
+
1069
+ get runningLateCommands() { return this.lateCommands.snapshot(); }
1070
+
1071
+ // Commands the agent waits on after its Codex turn ended. The per-turn
1072
+ // wrapper holds the Arco turn open for them and delivers each result once.
1073
+ get heldCommands() { return this.lateCommands.running(); }
1074
+ hasHeldResults(): boolean { return this.lateCommands.hasResults(); }
1075
+ hasFailedHeldResult(): boolean { return this.lateCommands.hasFailedResult(); }
1076
+ takeHeldResults(): HeldCommandResult[] { return this.lateCommands.takeResults(); }
1077
+ restoreHeldResults(results: HeldCommandResult[]): void { this.lateCommands.restoreResults(results); }
1078
+ showHeldUntil(until: number): void { this.lateCommands.hold(until); }
1079
+ releaseHeldWait(): void { this.lateCommands.release(); }
1080
+ // Arco's text may join the running turn only before its final answer starts.
1081
+ get acceptsResultSteer(): boolean { return !!this.current.turnId && !this.current.finalAnswerStarted; }
1082
+ abandonHeldCommands(): void { this.lateCommands.abandon(); }
1083
+
1084
+ /** Add Arco's text to the running turn. False when no turn takes it. */
1085
+ async steerText(text: string): Promise<boolean> {
1086
+ const turn = this.current;
1087
+ if (!this.rpc || !this.threadId || !turn.turnId) return false;
1088
+ try {
1089
+ await this.rpc.request<TurnSteerResponse>('turn/steer', {
1090
+ threadId: this.threadId, input: buildSteerInput([{ content: text }]),
1091
+ responsesapiClientMetadata: null, expectedTurnId: turn.turnId,
1092
+ } satisfies TurnSteerParams);
1093
+ return true;
1094
+ } catch (err) {
1095
+ console.warn(`[appserver:${this.workflowId.slice(0, 8)}] command result steer failed: ${err instanceof Error ? err.message : String(err)}`);
1096
+ return false;
1097
+ }
1098
+ }
1099
+
1100
+ private commandToolUse(item: Extract<ThreadItem, { type: 'commandExecution' }>, completed: boolean): ToolUseEvent {
1101
+ return {
1102
+ name: 'Bash',
1103
+ input: JSON.stringify({ command: item.command, cwd: item.cwd }),
1104
+ status: completed ? (item.exitCode === 0 ? 'completed' : 'failed') : 'started',
1105
+ provider: appServerProvider(this.config), itemType: 'command_execution', itemId: item.id,
1106
+ ...(completed && item.aggregatedOutput != null ? { output: item.aggregatedOutput } : {}),
1107
+ ...(completed && item.exitCode != null ? { exitCode: item.exitCode } : {}),
1108
+ };
1109
+ }
1110
+
1111
+ private handleCommandItem(p: ItemStartedNotification | ItemCompletedNotification, completed: boolean): boolean {
1112
+ if (p.item.type !== 'commandExecution') return false;
1113
+ if (p.threadId !== this.threadId || appServerProvider(this.config) !== 'codex') return false;
1114
+ const active = this.current.startedAt && (!this.current.turnId || p.turnId === this.current.turnId);
1115
+ const event = this.commandToolUse(p.item, completed);
1116
+ if (completed) {
1117
+ // One completion per command: one that ended after the agent's final
1118
+ // answer began is kept for after this turn; one from a turn that has
1119
+ // already completed belongs to the long-lived publisher.
1120
+ if (active && this.current.finalAnswerStarted) this.lateCommands.completeUnseen(p.turnId, event);
1121
+ else if (this.lateCommands.complete(p.turnId, event)) return true;
1122
+ } else if (active) this.lateCommands.start(p.turnId, event);
1123
+ if (active) this.emit('tool_use', event);
1124
+ return true;
1125
+ }
1126
+
1058
1127
  private onNotification(n: JsonRpcNotification): void {
1059
1128
  switch (n.method) {
1060
1129
  case 'serverRequest/resolved': {
@@ -1062,6 +1131,12 @@ export class CodexAppServerWorker extends EventEmitter {
1062
1131
  if (p.threadId === this.threadId) this.operatorQuestions.resolvedRpc(p.requestId);
1063
1132
  return;
1064
1133
  }
1134
+ case 'thread/closed': {
1135
+ // Codex unloaded the thread and stopped its terminals: no held
1136
+ // command will report an end any more.
1137
+ if ((n.params as ThreadClosedNotification).threadId === this.threadId) this.lateCommands.disconnect();
1138
+ return;
1139
+ }
1065
1140
  case 'thread/started': {
1066
1141
  const p = n.params as ThreadStartedNotification;
1067
1142
  this.threadId = p.thread.id;
@@ -1137,12 +1212,14 @@ export class CodexAppServerWorker extends EventEmitter {
1137
1212
  }
1138
1213
  case 'item/started': {
1139
1214
  const p = n.params as ItemStartedNotification;
1140
- this.emitToolUseFromItem(p.item, 'started');
1215
+ if (p.item.type === 'agentMessage' && p.item.phase === 'final_answer' && p.threadId === this.threadId
1216
+ && this.current.startedAt && (!this.current.turnId || p.turnId === this.current.turnId)) this.current.finalAnswerStarted = true;
1217
+ if (!this.handleCommandItem(p, false)) this.emitToolUseFromItem(p.item, 'started');
1141
1218
  return;
1142
1219
  }
1143
1220
  case 'item/completed': {
1144
1221
  const p = n.params as ItemCompletedNotification;
1145
- this.emitToolUseFromItem(p.item, 'completed');
1222
+ if (!this.handleCommandItem(p, true)) this.emitToolUseFromItem(p.item, 'completed');
1146
1223
  const asyncItem = p.item as ThreadItem & { delivery?: string; questions?: unknown };
1147
1224
  if (asyncItem.type === 'agentMessage' && asyncItem.delivery === 'async' && p.threadId === this.threadId && this.current.startedAt && (!this.current.turnId || p.turnId === this.current.turnId)) {
1148
1225
  try { this.operatorQuestions.acceptAsync(p.threadId, p.turnId, asyncItem); }
@@ -1254,24 +1331,9 @@ export class CodexAppServerWorker extends EventEmitter {
1254
1331
  // unchanged on appserver tabs.
1255
1332
  const provider = appServerProvider(this.config);
1256
1333
  switch (item.type) {
1257
- case 'commandExecution': {
1258
- const completed = status === 'completed';
1259
- const finalStatus: ToolUseEvent['status'] =
1260
- completed ? (item.exitCode === 0 ? 'completed' : 'failed') : 'started';
1261
- this.emit('tool_use', {
1262
- name: 'Bash',
1263
- input: JSON.stringify({ command: item.command, cwd: item.cwd }),
1264
- status: finalStatus,
1265
- provider,
1266
- itemType: 'command_execution',
1267
- itemId: item.id,
1268
- ...(completed && item.aggregatedOutput !== null
1269
- ? { output: item.aggregatedOutput }
1270
- : {}),
1271
- ...(completed && item.exitCode !== null ? { exitCode: item.exitCode } : {}),
1272
- });
1334
+ case 'commandExecution':
1335
+ this.emit('tool_use', this.commandToolUse(item, status === 'completed'));
1273
1336
  return;
1274
- }
1275
1337
  case 'fileChange': {
1276
1338
  const completed = status === 'completed';
1277
1339
  const finalStatus: ToolUseEvent['status'] =
@@ -1640,6 +1702,7 @@ export class CodexAppServerWorker extends EventEmitter {
1640
1702
  this.emit('turn_settled', data);
1641
1703
  return;
1642
1704
  }
1705
+ if (this.current.turnId) this.lateCommands.settle(this.current.turnId);
1643
1706
  this.current = emptyTurnState();
1644
1707
  if (data.error && data.error !== 'Worker killed') {
1645
1708
  // Also run the stderr fallback throttle sniffer in case the protocol
@@ -1663,6 +1726,7 @@ export class CodexAppServerWorker extends EventEmitter {
1663
1726
  }
1664
1727
 
1665
1728
  private teardownProcess(): void {
1729
+ this.lateCommands.disconnect();
1666
1730
  this.operatorQuestions.cancel('The Codex connection closed.');
1667
1731
  if (this.rpc) {
1668
1732
  try { this.rpc.close('worker teardown'); } catch { /* ignore */ }
@@ -1,4 +1,4 @@
1
- import { buildTurnWaitInstructions } from '@arco/shared';
1
+ import { codexTurnWaitInstructions } from './codexCodeMode.js';
2
2
  import { prepareProviderHistory, historyBinding } from './handoffHistoryBinding.js';
3
3
  import { prepareLocalFileContext, combineChatAttachments } from './localFileMedia.js';
4
4
  import { codexChatOverrides, requireCodexChatCapabilities } from './codexChatBoundary.js';
@@ -112,7 +112,7 @@ class CodexWorkerProcess extends EventEmitter implements ProviderProcess {
112
112
  // prefix cache like the rest of the framing. Covers operator turns AND
113
113
  // primitive seeds (both carry config.goal). Absent / blank ⇒ no change.
114
114
  // The output-style addendum closes the prefix, as on app-server.
115
- const prefixParts = [buildTurnWaitInstructions(this.config.clusterRole), goalBlock(this.config.goal), this.config.appendSystemPrompt, cliFileReadGuidance(this.config), outputStyleAddendum(this.config.outputStyle)]
115
+ const prefixParts = [codexTurnWaitInstructions(this.config.clusterRole), goalBlock(this.config.goal), this.config.appendSystemPrompt, cliFileReadGuidance(this.config), outputStyleAddendum(this.config.outputStyle)]
116
116
  .filter((s): s is string => typeof s === 'string' && s.length > 0);
117
117
  const prefixSp = prefixParts.length > 0 ? prefixParts.join('\n\n') : undefined;
118
118
  const fullPrompt = prefixSp
@@ -13,7 +13,7 @@ import * as fs from 'node:fs';
13
13
  import { resolveCodexHome } from './codexHome.js';
14
14
  import * as path from 'node:path';
15
15
  import type { WorkerConfig } from '@arco/shared';
16
- import { AGENT_TURN_WAIT, buildTurnWaitInstructions } from '@arco/shared';
16
+ import { AGENT_TURN_WAIT, buildTurnWaitInstructions, isClusterDirector } from '@arco/shared';
17
17
  import { buildClusterDirectorDoctrine } from '../clusterDirector.js';
18
18
 
19
19
  interface CodeModeEntry {
@@ -94,7 +94,12 @@ export function codexCodeModeClusterAddendum(): string {
94
94
  }
95
95
 
96
96
  // Standing turn discipline for every Codex workflow (cluster and single).
97
- export const CODEX_TURN_DISCIPLINE = AGENT_TURN_WAIT;
97
+ const CODEX_COMMAND_WAIT = 'A command reply with a session ID and no exit code means it is still running. Poll that session until it exits before reporting, and do not end the turn saying you are waiting for it. Start a program meant to keep running, such as a server or a watcher, in the background with & or nohup, so Arco does not wait for it.';
98
+ export const CODEX_TURN_DISCIPLINE = AGENT_TURN_WAIT + ' ' + CODEX_COMMAND_WAIT;
99
+
100
+ export function codexTurnWaitInstructions(role: string | undefined): string {
101
+ return isClusterDirector(role) ? buildTurnWaitInstructions(role) : CODEX_TURN_DISCIPLINE;
102
+ }
98
103
 
99
104
  // app-server can place Arco's durable cluster identity at developer level
100
105
  // when a thread starts/resumes. Per-turn plan content still rides in user
@@ -104,7 +109,7 @@ export const CODEX_TURN_DISCIPLINE = AGENT_TURN_WAIT;
104
109
  // wait for the result their report depends on and check for messages between waits.
105
110
  export function codexClusterDeveloperInstructions(config: WorkerConfig): string | null {
106
111
  if (config.provider !== 'codex') return null;
107
- const blocks: string[] = [buildTurnWaitInstructions(config.clusterRole)];
112
+ const blocks: string[] = [codexTurnWaitInstructions(config.clusterRole)];
108
113
  if (config.clusterId) {
109
114
  blocks.push(
110
115
  '--- Arco cluster identity ---',
@@ -151,6 +151,7 @@ export class WorkerManager {
151
151
  // queue entries. See WorkerConfig.drainSteer.
152
152
  drainSteer?: WorkerConfig['drainSteer'];
153
153
  peekSteer?: WorkerConfig['peekSteer'];
154
+ pendingInput?: WorkerConfig['pendingInput'];
154
155
  // Phase 6b — paired with drainSteer for the Codex app-server worker.
155
156
  // Called when `turn/steer` round-trip fails and the drained items
156
157
  // need to land back in a queue. Bucket determines whether items
@@ -291,6 +292,7 @@ export class WorkerManager {
291
292
  incognito: options?.incognito,
292
293
  drainSteer: options?.drainSteer,
293
294
  peekSteer: options?.peekSteer,
295
+ pendingInput: options?.pendingInput,
294
296
  requeueSteer: options?.requeueSteer,
295
297
  onSteerDelivered: options?.onSteerDelivered,
296
298
  // Phase 6 — workflowId is required for per-workflow-lifetime providers
@@ -166,9 +166,15 @@ export function _shellTreeTagForTest(child: ChildProcess): string | undefined {
166
166
  // Prints, one per line, the Windows process id (or, outside Windows, the
167
167
  // process id) of every MSYS process whose environment holds the tag. Bash
168
168
  // built-ins only, so it starts nothing per process.
169
+ // Test observations on stderr contain process IDs and readability only.
169
170
  export const MSYS_TREE_SWEEP = [
170
171
  'tag=$1',
172
+ 'if [ -n "$2" ]; then exec 3>&2; fi',
171
173
  'for d in /proc/[0-9]*; do',
174
+ ' if [ -n "$2" ]; then',
175
+ ' readable=no; [ -r "$d/environ" ] && readable=yes',
176
+ ' printf \'entry %s readable=%s\\n\' "${d#/proc/}" "$readable" >&3',
177
+ ' fi',
172
178
  ' [ -r "$d/environ" ] || continue',
173
179
  ' hit=',
174
180
  ' while IFS= read -r -d \'\' e || [ -n "$e" ]; do',
@@ -177,6 +183,7 @@ export const MSYS_TREE_SWEEP = [
177
183
  ' [ -n "$hit" ] || continue',
178
184
  ' w=',
179
185
  ' [ -r "$d/winpid" ] && read -r w < "$d/winpid"',
186
+ ' if [ -n "$2" ]; then printf \'match %s pid=%s\\n\' "${d#/proc/}" "$w" >&3; fi',
180
187
  ' printf \'%s\\n\' "${w:-${d#/proc/}}"',
181
188
  'done 2>/dev/null',
182
189
  '',
@@ -190,30 +197,51 @@ function listMsysTree(tree: { tag: string; bash: string }): Promise<number[]> {
190
197
  return msysTreeSweep(tree.bash, tree.tag, process.platform);
191
198
  }
192
199
 
193
- export function msysTreeSweep(bash: string, tag: string, platform: NodeJS.Platform = process.platform): Promise<number[]> {
200
+ interface MsysSweepObservation {
201
+ code: number | null;
202
+ signal: NodeJS.Signals | null;
203
+ error?: string;
204
+ stdout: string;
205
+ stderr: string;
206
+ }
207
+
208
+ export function msysTreeSweep(
209
+ bash: string,
210
+ tag: string,
211
+ platform: NodeJS.Platform = process.platform,
212
+ observe?: (result: MsysSweepObservation) => void,
213
+ ): Promise<number[]> {
194
214
  return new Promise((resolve) => {
195
215
  const env = { ...process.env };
196
216
  delete env[PROCESS_TREE_ENV];
197
217
  let out = '';
218
+ let stderr = '';
198
219
  let done = false;
199
- const finish = (): void => {
220
+ const finish = (code: number | null, signal: NodeJS.Signals | null, error?: string): void => {
200
221
  if (done) return;
201
222
  done = true;
202
223
  clearTimeout(timer);
224
+ observe?.({ code, signal, error, stdout: out, stderr });
203
225
  resolve(out.split(/\r?\n/).filter((l) => /^\d+$/.test(l.trim())).map((l) => Number(l.trim())));
204
226
  };
205
- const timer = setTimeout(() => { try { sweeper?.kill(); } catch { /* gone */ } finish(); }, SWEEP_TIMEOUT_MS);
227
+ const timer = setTimeout(() => {
228
+ try { sweeper?.kill(); } catch { /* gone */ }
229
+ finish(null, null, 'sweep timed out');
230
+ }, SWEEP_TIMEOUT_MS);
206
231
  let sweeper: ChildProcess | undefined;
207
232
  try {
208
- const plan = shellSpawnPlan({ file: bash, args: ['-c', MSYS_TREE_SWEEP, 'arco-sweep', tag], msys: true }, { env, stdio: ['ignore', 'pipe', 'ignore'] }, platform);
233
+ const args = ['-c', MSYS_TREE_SWEEP, 'arco-sweep', tag];
234
+ if (observe) args.push('observe');
235
+ const plan = shellSpawnPlan({ file: bash, args, msys: true }, { env, stdio: ['ignore', 'pipe', observe ? 'pipe' : 'ignore'] }, platform);
209
236
  // The sweep itself must not carry a tag, or it would list itself.
210
237
  if (plan.options.env) delete (plan.options.env as NodeJS.ProcessEnv)[PROCESS_TREE_ENV];
211
238
  sweeper = spawn(plan.file, plan.args, plan.options);
212
239
  sweeper.stdout?.on('data', (b: Buffer) => { out += b.toString('utf8'); });
213
- sweeper.on('error', finish);
240
+ sweeper.stderr?.on('data', (b: Buffer) => { stderr += b.toString('utf8'); });
241
+ sweeper.on('error', (error: NodeJS.ErrnoException) => finish(null, null, error.code ?? error.name));
214
242
  sweeper.on('close', finish);
215
- } catch {
216
- finish();
243
+ } catch (error) {
244
+ finish(null, null, (error as NodeJS.ErrnoException).code ?? 'sweep spawn failed');
217
245
  }
218
246
  });
219
247
  }
@@ -1,3 +1,4 @@
1
+ import { runningCodexLateCommands } from '../providers/codex-appserver/index.js';
1
2
  import { ensureWorkflowMetadata, providerConversationState, saveProviderSession } from '../providerConversation.js';
2
3
  import { isClaudeNativeTaskActive } from '../providers/claude-native/index.js';
3
4
  import { appendHandoffNotice } from '../handoffHistoryTool.js';
@@ -1895,6 +1896,7 @@ export async function rehydrateOneWorkflow(
1895
1896
  const msg: ServerMessage = {
1896
1897
  type: 'workflow_state_snapshot',
1897
1898
  workflowId,
1899
+ ...(wf.primary.provider === 'codex' ? { codexLateCommands: runningCodexLateCommands(workflowId) } : {}),
1898
1900
  ...(conversationState ? { providerConversation: conversationState } : {}),
1899
1901
  workers: {},
1900
1902
  busy: wf.busy,
@@ -132,6 +132,7 @@ WorkflowState
132
132
  } from '../workflows/types.js';
133
133
  import { takeQueuedTurn } from './messageQueue.js';
134
134
  import { awaitModelImages } from '../providers/attachments.js';
135
+ import { adoptPhoneDrafts } from '../http/phoneUploadDrafts.js';
135
136
 
136
137
  const PUBLIC_REPO_SAFETY_SYSTEM_BLOCK = [
137
138
  'Genesis public repository safety:',
@@ -1578,6 +1579,10 @@ export async function handleUserMessage(
1578
1579
  type: 'system_notice', workflowId,
1579
1580
  content: '[INTERRUPT & SEND] No interruptible Claude or Codex primary turn is running. Your message is queued as a follow-up.',
1580
1581
  });
1582
+ if (!isolatedMember && !adoptPhoneDrafts(workflowId, attachments)) {
1583
+ send(ws, { type: 'error', workflowId, message: 'A phone attachment expired or belongs to another conversation.' });
1584
+ return;
1585
+ }
1581
1586
  const arr = bucket === 'steer' ? wf.queue.steering : wf.queue.followUp;
1582
1587
  const queuedAttachments = [...new Set([...(attachments ?? []), ...contextAttachments])];
1583
1588
  const queuedItem = { clusterBusyReminder: opts?.clusterBusyReminder, automaticKind: opts?.automaticKind, content, attachments: isolatedMember || !queuedAttachments.length ? undefined : queuedAttachments, clientMessageId, expandedContext, pickedSkills, editPickedSkills, ollamaInputSeq: undefined as number | undefined, ...(interrupt ? { interrupt: true } : {}) };
@@ -1659,6 +1664,10 @@ export async function handleUserMessage(
1659
1664
  // Refuse before taking queued input: a restore admitted during preflight
1660
1665
  // must leave the queue available for an explicit later attempt.
1661
1666
  assertCheckoutAvailable(workflowWritePaths(wf));
1667
+ if (!fromQueue && !isolatedMember && !adoptPhoneDrafts(workflowId, attachments)) {
1668
+ send(ws, { type: 'error', workflowId, message: 'A phone attachment expired or belongs to another conversation.' });
1669
+ return;
1670
+ }
1662
1671
  let activeOllamaInputSeqs: number[] = [];
1663
1672
  let activeInputClientIds: string[] = [];
1664
1673
  if (fromQueue) {
@@ -2626,6 +2635,12 @@ export async function handleUserMessage(
2626
2635
  if (!dispatchCurrent() || wf.primaryTurn?.holdSteer || wf.queue.steering.some((item) => item.interrupt)) return [];
2627
2636
  return wf.queue.steering;
2628
2637
  },
2638
+ pendingInput: () => {
2639
+ if (!dispatchCurrent() || wf.queue.steering.some((item) => item.interrupt)) return undefined;
2640
+ const direct = (item: { automaticKind?: string }) => item.automaticKind !== 'auto-pickup';
2641
+ if (!wf.primaryTurn?.holdSteer && wf.queue.steering.some(direct)) return 'steer';
2642
+ return wf.queue.followUp.some(direct) ? 'follow-up' : undefined;
2643
+ },
2629
2644
  requeueSteer: (items, bucket) => {
2630
2645
  if (workflows.get(workflowId) === wf && (busyRevocations.get(wf) ?? 0) === interruptEpoch) requeueSteerForWorker(workflowId, ws, items, bucket);
2631
2646
  },
@@ -9,6 +9,7 @@ export interface ChatMessage {
9
9
  id: string;
10
10
  role: 'user' | 'assistant' | 'system' | 'peer-sent' | 'peer-received' | 'ctx-divider';
11
11
  content: string;
12
+ peerFullContent?: string;
12
13
  automaticKind?: AutomaticMessageKind;
13
14
  authRecovery?: AuthRecoveryContext;
14
15
  operatorQuestion?: OperatorQuestionState;
@@ -15,6 +15,8 @@ export interface PeerMessageSentMessage {
15
15
  from: string;
16
16
  to: string;
17
17
  contentPreview: string;
18
+ content?: string;
19
+ ts?: number;
18
20
  chainDepth?: number;
19
21
  }
20
22
  export interface PeerMessageReceivedMessage {
@@ -332,10 +332,20 @@ export interface PrimaryThinkingMessage {
332
332
  workflowId: string;
333
333
  text: string;
334
334
  }
335
+ export interface CodexLateCommand {
336
+ itemId: string;
337
+ input: string;
338
+ startedAt: number;
339
+ waitingUntil: number;
340
+ waiting?: boolean;
341
+ }
335
342
  export interface PrimaryToolUseMessage {
336
343
  ollamaExecutionId?: string;
337
344
  type: 'primary_tool_use';
338
345
  workflowId: string;
346
+ lateCommand?: Omit<CodexLateCommand, 'itemId' | 'input'> & {
347
+ state: 'running' | 'finished' | 'lost' | 'untracked';
348
+ };
339
349
  tool: string;
340
350
  input: string;
341
351
  status?: 'started' | 'in_progress' | 'completed' | 'failed';
@@ -515,6 +525,7 @@ export interface ProviderConversationStateMessage {
515
525
  }
516
526
  export interface WorkflowStateSnapshotMessage {
517
527
  type: 'workflow_state_snapshot';
528
+ codexLateCommands?: CodexLateCommand[];
518
529
  providerConversation?: 'unavailable' | 'awaiting-reading';
519
530
  workflowId: string;
520
531
  workers: Record<string, WorkerState>;
@@ -224,6 +224,7 @@ export interface WorkerConfig {
224
224
  sandbox?: 'read-only' | 'workspace-write' | 'danger-full-access';
225
225
  drainSteer?: () => SteerItem[];
226
226
  peekSteer?: () => readonly SteerItem[];
227
+ pendingInput?: () => 'steer' | 'follow-up' | undefined;
227
228
  requeueSteer?: (items: SteerItem[], bucket: 'steer' | 'follow-up') => void;
228
229
  onSteerDelivered?: (items: SteerItem[]) => void;
229
230
  workflowId?: string;
@@ -19,6 +19,7 @@ export interface ChatMessage {
19
19
  // chat row, so a reload preserves the visual peer-message timeline.
20
20
  role: 'user' | 'assistant' | 'system' | 'peer-sent' | 'peer-received' | 'ctx-divider';
21
21
  content: string;
22
+ peerFullContent?: string; // sent mail body; absent for older preview-only records
22
23
  automaticKind?: AutomaticMessageKind;
23
24
  authRecovery?: AuthRecoveryContext;
24
25
  operatorQuestion?: OperatorQuestionState;
@@ -35,10 +35,7 @@ export function isClusterMemberAccessMode(v: unknown): v is ClusterMemberAccessM
35
35
  // Three kinds, all workflow-scoped (each member's events.jsonl carries
36
36
  // only the events that apply to it):
37
37
  // peer_message_sent — emitted on the SENDER's workflow when
38
- // peer_send succeeds. Carries a content
39
- // preview only (the full content can be
40
- // reconstructed from the recipient's
41
- // matching peer_message_received).
38
+ // peer_send succeeds. Carries the preview and, for new messages, the full body.
42
39
  // peer_message_received — emitted on the RECIPIENT's workflow at
43
40
  // injection time (pre-turn drain or mid-turn
44
41
  // peer_read). Replay reproduces the
@@ -59,7 +56,9 @@ export interface PeerMessageSentMessage {
59
56
  msgId: string;
60
57
  from: string; // sender workflowId (== workflowId above)
61
58
  to: string; // recipient workflowId
62
- contentPreview: string; // up to 200 chars; full content lives in the recipient's record
59
+ contentPreview: string; // up to 200 chars
60
+ content?: string; // absent on older sender records
61
+ ts?: number; // original send time
63
62
  // Auto-turn-on-mailbox chain depth (docs/PROTOCOL_CLUSTER.md). 0 (or
64
63
  // absent) for operator-initiated sends. When the auto-turn detector fires a
65
64
  // turn on a recipient, peer_send originating during that turn carries
@@ -714,10 +714,20 @@ export interface PrimaryThinkingMessage {
714
714
  // Primary invoked a tool. `input` is JSON-stringified so the ACTIVITY tab can
715
715
  // render an abbreviated summary (e.g. "Read server/src/index.ts",
716
716
  // "Grep primary_thinking"). One event per tool call.
717
+ export interface CodexLateCommand {
718
+ itemId: string;
719
+ input: string;
720
+ startedAt: number;
721
+ waitingUntil: number;
722
+ // The tab's turn is open only because the agent waits on this command.
723
+ waiting?: boolean;
724
+ }
725
+
717
726
  export interface PrimaryToolUseMessage {
718
727
  ollamaExecutionId?: string;
719
728
  type: 'primary_tool_use';
720
729
  workflowId: string;
730
+ lateCommand?: Omit<CodexLateCommand, 'itemId' | 'input'> & { state: 'running' | 'finished' | 'lost' | 'untracked' };
721
731
  tool: string;
722
732
  input: string;
723
733
  status?: 'started' | 'in_progress' | 'completed' | 'failed';
@@ -961,6 +971,7 @@ export interface ProviderConversationStateMessage {
961
971
  // ground truth so stale client-side state snaps to truth immediately.
962
972
  export interface WorkflowStateSnapshotMessage {
963
973
  type: 'workflow_state_snapshot';
974
+ codexLateCommands?: CodexLateCommand[];
964
975
  providerConversation?: 'unavailable' | 'awaiting-reading';
965
976
  workflowId: string;
966
977
  workers: Record<string, WorkerState>;
@@ -579,6 +579,10 @@ export interface WorkerConfig {
579
579
  // Native uses their identity to show one notice per held message without
580
580
  // acknowledging or removing input before its safe delivery boundary.
581
581
  peekSteer?: () => readonly SteerItem[];
582
+ // Codex app-server only: while a turn waits on a command, which queued
583
+ // input the operator (or an explicit nudge) has sent. Automatic pickup
584
+ // reminders are left out: they wait for the turn to end as usual.
585
+ pendingInput?: () => 'steer' | 'follow-up' | undefined;
582
586
  // Phase 6b — re-enqueue hook for the Codex app-server worker. Called when
583
587
  // a `turn/steer` round-trip fails and the drained items have to land
584
588
  // back in a queue: `'steer'` for `activeTurnNotSteerable` (the next