@codexhost/cli-win32-x64 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +54 -5
  4. package/app/console-web.js +74 -7
  5. package/app/desktop-controller.mjs +60 -9
  6. package/app/host-runtime.mjs +1367 -322
  7. package/app/plugins/antigravity/plugin.mjs +54 -5
  8. package/app/plugins/claude-code/plugin.mjs +65 -13
  9. package/app/plugins/codebuddy/plugin.mjs +253 -93
  10. package/app/plugins/codex-usage/plugin.mjs +54 -5
  11. package/app/plugins/copilot/plugin.mjs +54 -5
  12. package/app/plugins/cursor-cli/plugin.mjs +54 -5
  13. package/app/plugins/deepseek-harness/plugin.mjs +54 -5
  14. package/app/plugins/devin/plugin.mjs +54 -5
  15. package/app/plugins/grok/plugin.mjs +54 -5
  16. package/app/plugins/hermes/plugin.mjs +54 -5
  17. package/app/plugins/kimi-code/plugin.mjs +54 -5
  18. package/app/plugins/kiro-cli/plugin.mjs +54 -5
  19. package/app/plugins/omp/plugin.mjs +54 -5
  20. package/app/plugins/opencode/plugin.mjs +54 -5
  21. package/app/plugins/pi/plugin.mjs +54 -5
  22. package/app/plugins/qoder/plugin.mjs +54 -5
  23. package/app/plugins/qoder-cn/plugin.mjs +54 -5
  24. package/app/plugins/qwen-code/plugin.mjs +54 -5
  25. package/app/plugins/workbuddy/plugin.mjs +253 -93
  26. package/app/plugins/zcode/plugin.mjs +54 -5
  27. package/app/renderer-extension.js +650 -413
  28. package/app/web/assets/{abnfDiagram-XWFEHMT6-BdinLox4.js → abnfDiagram-XWFEHMT6-Bqy7uOSy.js} +1 -1
  29. package/app/web/assets/{architectureDiagram-CSQXQB3N-DgPBbtvP.js → architectureDiagram-CSQXQB3N-6aaP1YoM.js} +1 -1
  30. package/app/web/assets/{blockDiagram-BEDRHYPZ-B4ENdwtZ.js → blockDiagram-BEDRHYPZ-B4QSFXe0.js} +1 -1
  31. package/app/web/assets/{c4Diagram-M2UUVUY5-DA6Owfyu.js → c4Diagram-M2UUVUY5-BYE-C8Gq.js} +1 -1
  32. package/app/web/assets/{chunk-2Q5K7J3B-Dvh3qOmo.js → chunk-2Q5K7J3B-CiEM-GTd.js} +1 -1
  33. package/app/web/assets/{chunk-3GCGMST5-VIkqueym.js → chunk-3GCGMST5-hzY9BiB1.js} +1 -1
  34. package/app/web/assets/{chunk-5VM5RSS4-DTYof_OI.js → chunk-5VM5RSS4-DYXznY0H.js} +1 -1
  35. package/app/web/assets/{chunk-7U7NFRK5-Dp7s2dg0.js → chunk-7U7NFRK5-Bzw5MDPr.js} +1 -1
  36. package/app/web/assets/{chunk-CNRTWJTD-TKBKxZLU.js → chunk-CNRTWJTD-DMbxMfi3.js} +1 -1
  37. package/app/web/assets/{chunk-D5HYT7QG-BRZDovSS.js → chunk-D5HYT7QG-By0ZVBtD.js} +1 -1
  38. package/app/web/assets/{chunk-EBZ3SEQC-C9USZ3tT.js → chunk-EBZ3SEQC-Yyu_sMV7.js} +2 -2
  39. package/app/web/assets/{chunk-JWPE2WC7-BrdvVNVo.js → chunk-JWPE2WC7-DDzqxIPT.js} +1 -1
  40. package/app/web/assets/{chunk-KTR4FSNJ-C7qwjGba.js → chunk-KTR4FSNJ-GlKqhtpl.js} +1 -1
  41. package/app/web/assets/{chunk-XXDRQBXY-DlSrRuwN.js → chunk-XXDRQBXY-DNc-CvYu.js} +1 -1
  42. package/app/web/assets/{classDiagram-v2-KXABOMEV-BFvB4kwX.js → classDiagram-v2-KXABOMEV-4_PFS2N_.js} +1 -1
  43. package/app/web/assets/{cose-bilkent-JH36ORCC-UyCAqNvj.js → cose-bilkent-JH36ORCC-BE3foHUY.js} +1 -1
  44. package/app/web/assets/{cynefin-EF2NZ3EQ-CwawUbjJ.js → cynefin-EF2NZ3EQ-D2PqrYZ3.js} +1 -1
  45. package/app/web/assets/{cynefinDiagram-NJNITYFG-BaWEIQJ0.js → cynefinDiagram-NJNITYFG-DOObpTbq.js} +1 -1
  46. package/app/web/assets/{dagre-KIHZ2IZ3-B7ENIjLG.js → dagre-KIHZ2IZ3-Znm2jin9.js} +1 -1
  47. package/app/web/assets/{diagram-7YQZDPLS-CxRMU8xq.js → diagram-7YQZDPLS-ByZMD-uA.js} +1 -1
  48. package/app/web/assets/{diagram-QBROCOUO-qo7sxm4K.js → diagram-QBROCOUO-BiRShpnN.js} +1 -1
  49. package/app/web/assets/{diagram-RJJCUUZO-CQiGMCMe.js → diagram-RJJCUUZO-D9wLVoK2.js} +1 -1
  50. package/app/web/assets/{diagram-WERXNKYE-D0Jps1As.js → diagram-WERXNKYE-BSbIh-yC.js} +1 -1
  51. package/app/web/assets/{diagram-YHHI257C-p4AB8cqK.js → diagram-YHHI257C-DMWrHMc8.js} +1 -1
  52. package/app/web/assets/{diagram-YR4HJLHV-Bh6JKT04.js → diagram-YR4HJLHV-C4sBAFb1.js} +1 -1
  53. package/app/web/assets/{ebnfDiagram-N527522P-DRac0k4W.js → ebnfDiagram-N527522P-BZLloaoQ.js} +1 -1
  54. package/app/web/assets/{elk-O5DQBFGD-CWTz5SZP.js → elk-O5DQBFGD-Da3e5tn5.js} +1 -1
  55. package/app/web/assets/{erDiagram-K3K3BIDK-DE3w4BEY.js → erDiagram-K3K3BIDK-B2lKAIZF.js} +1 -1
  56. package/app/web/assets/{flowDiagram-Z6JWZHQI-NYs8bi5t.js → flowDiagram-Z6JWZHQI-q2EY_kmB.js} +1 -1
  57. package/app/web/assets/{ganttDiagram-3PRQTZWP-Bspp9btW.js → ganttDiagram-3PRQTZWP-BGrNZ20b.js} +1 -1
  58. package/app/web/assets/{gitGraphDiagram-VXDFKS5L-ByGW1uvv.js → gitGraphDiagram-VXDFKS5L-DIZNXREy.js} +1 -1
  59. package/app/web/assets/{grid-E2QIVN74-CegebiIw.js → grid-E2QIVN74-0cUkPG69.js} +1 -1
  60. package/app/web/assets/{index-DFPOGLS4.js → index-PN7K-15_.js} +76 -76
  61. package/app/web/assets/{infoDiagram-EZ3ZOAHP-CexmsdZx.js → infoDiagram-EZ3ZOAHP-BHhUTQCn.js} +1 -1
  62. package/app/web/assets/{ishikawaDiagram-S3EKX5GW-BbWqKhg6.js → ishikawaDiagram-S3EKX5GW-DPOxtl4c.js} +1 -1
  63. package/app/web/assets/{journeyDiagram-POQNLL5X-27YlCe-1.js → journeyDiagram-POQNLL5X-D8RyXckG.js} +1 -1
  64. package/app/web/assets/{kanban-definition-BH5XI6FM-BAhOdeck.js → kanban-definition-BH5XI6FM-COJv3Hyh.js} +1 -1
  65. package/app/web/assets/{mermaid.core-sGgCbv5y.js → mermaid.core-DYdcDKIt.js} +4 -4
  66. package/app/web/assets/{mindmap-definition-WVAN44T4-CsMIX0Lj.js → mindmap-definition-WVAN44T4-DnYIM4ja.js} +1 -1
  67. package/app/web/assets/{pegDiagram-D4NLKWP3-Cs3LXqn_.js → pegDiagram-D4NLKWP3-Ds3GAEJ6.js} +1 -1
  68. package/app/web/assets/{pieDiagram-36ENHN4W-DdQsQX9I.js → pieDiagram-36ENHN4W-BhLUJGEB.js} +1 -1
  69. package/app/web/assets/{quadrantDiagram-ZQUDMS73-D1jOKqx_.js → quadrantDiagram-ZQUDMS73-DwtX-IxK.js} +1 -1
  70. package/app/web/assets/{railroadDiagram-JIZHGYPL-XulrgX5n.js → railroadDiagram-JIZHGYPL-D2vmTTnJ.js} +1 -1
  71. package/app/web/assets/{render-VIF2ZAQL-CSsGw-0I.js → render-VIF2ZAQL-DGU1ql-Z.js} +2 -2
  72. package/app/web/assets/{requirementDiagram-AXW2TVFA-CT66GXLN.js → requirementDiagram-AXW2TVFA-u3j1sKkI.js} +1 -1
  73. package/app/web/assets/{sankeyDiagram-FBCJTAIF-CNRKebNY.js → sankeyDiagram-FBCJTAIF-k-An9VHW.js} +1 -1
  74. package/app/web/assets/{sequenceDiagram-3LA2ROMG-DVl5y64e.js → sequenceDiagram-3LA2ROMG-DUjbYb4R.js} +1 -1
  75. package/app/web/assets/{sizeCapture-2Q2CQKSF-Kg0XxSga.js → sizeCapture-2Q2CQKSF-DATTL7FZ.js} +1 -1
  76. package/app/web/assets/{stateDiagram-v2-ATKHQDJO-DYQnfMsS.js → stateDiagram-v2-ATKHQDJO-cCJX5M2u.js} +1 -1
  77. package/app/web/assets/{swimlanes-YQL5WMAO-Chqt7pxD.js → swimlanes-YQL5WMAO-B7grWEWt.js} +1 -1
  78. package/app/web/assets/swimlanesDiagram-UCCPES4V-B8Jem9gq.js +8 -0
  79. package/app/web/assets/{timeline-definition-7Z437IG3-aHFxjIT6.js → timeline-definition-7Z437IG3-BhsLa6l1.js} +1 -1
  80. package/app/web/assets/{usecaseDiagram-RDK6N6HP-DsC5tFe4.js → usecaseDiagram-RDK6N6HP-CkPQYmQw.js} +1 -1
  81. package/app/web/assets/{vennDiagram-SHRQU5PJ-C65oZxFn.js → vennDiagram-SHRQU5PJ-CufZSwvw.js} +1 -1
  82. package/app/web/assets/{wardleyDiagram-F3OXNVQS-HTkq7DT0.js → wardleyDiagram-F3OXNVQS-CSkfpFOA.js} +1 -1
  83. package/app/web/assets/{xychartDiagram-GDYJKCDI-p1LpQ9MH.js → xychartDiagram-GDYJKCDI-BhZf9scK.js} +1 -1
  84. package/app/web/codexhost-settings.js +56 -56
  85. package/app/web/index.html +1 -1
  86. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  87. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +8 -8
  88. package/app/web/plugins/deepseek-ai__dsh-api-workspace-controller/client.js +3 -3
  89. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +75 -75
  90. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +16 -16
  91. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +16 -16
  92. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +18 -18
  93. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +70 -72
  94. package/app/web-modules/server.mjs +383 -148
  95. package/bin/codexhost.exe +0 -0
  96. package/libexec/codexhost-node-repl.exe +0 -0
  97. package/libexec/codexhost-screenshot.exe +0 -0
  98. package/libexec/codexhost-shell.exe +0 -0
  99. package/libexec/codexhost-shim.exe +0 -0
  100. package/libexec/codexhost-updater.exe +0 -0
  101. package/package.json +1 -1
  102. package/app/web/assets/swimlanesDiagram-UCCPES4V-BfREktNP.js +0 -8
@@ -13955,9 +13955,9 @@ function floatSafeRemainder(val, step) {
13955
13955
  return ratio - roundedRatio;
13956
13956
  }
13957
13957
  var EVALUATING = /* @__PURE__ */ Symbol("evaluating");
13958
- function defineLazy(object12, key, getter) {
13958
+ function defineLazy(object13, key, getter) {
13959
13959
  let value2 = void 0;
13960
- Object.defineProperty(object12, key, {
13960
+ Object.defineProperty(object13, key, {
13961
13961
  get() {
13962
13962
  if (value2 === EVALUATING) {
13963
13963
  return void 0;
@@ -13969,7 +13969,7 @@ function defineLazy(object12, key, getter) {
13969
13969
  return value2;
13970
13970
  },
13971
13971
  set(v) {
13972
- Object.defineProperty(object12, key, {
13972
+ Object.defineProperty(object13, key, {
13973
13973
  value: v
13974
13974
  // configurable: true,
13975
13975
  });
@@ -29084,8 +29084,8 @@ function foldObjects(members2) {
29084
29084
  }
29085
29085
  const properties = {};
29086
29086
  const required2 = /* @__PURE__ */ new Set();
29087
- for (const object12 of objects) {
29088
- for (const key in object12.properties) {
29087
+ for (const object13 of objects) {
29088
+ for (const key in object13.properties) {
29089
29089
  if (Object.prototype.hasOwnProperty.call(properties, key))
29090
29090
  continue;
29091
29091
  const parts = [];
@@ -29099,18 +29099,18 @@ function foldObjects(members2) {
29099
29099
  const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts };
29100
29100
  assignProp(properties, key, merged);
29101
29101
  }
29102
- for (const key of object12.required ?? [])
29102
+ for (const key of object13.required ?? [])
29103
29103
  required2.add(key);
29104
29104
  }
29105
29105
  const folded = { type: "object", properties };
29106
29106
  if (required2.size)
29107
29107
  folded.required = [...required2];
29108
- if (objects.every((object12) => object12.additionalProperties === false)) {
29108
+ if (objects.every((object13) => object13.additionalProperties === false)) {
29109
29109
  folded.additionalProperties = false;
29110
29110
  } else {
29111
29111
  const constraints = [];
29112
- for (const object12 of objects) {
29113
- const constraint = undeclaredConstraint(object12);
29112
+ for (const object13 of objects) {
29113
+ const constraint = undeclaredConstraint(object13);
29114
29114
  if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))
29115
29115
  constraints.push(constraint);
29116
29116
  }
@@ -38484,6 +38484,45 @@ var nativeCodexGoalResultSchema = external_exports.object({
38484
38484
  var CLIENT_CHANNEL_VERSION = 1;
38485
38485
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
38486
38486
  var THREAD_QUEUE_START_IF_EMPTY_PARAM = "codexhostQueueStartIfEmpty";
38487
+ var THREAD_SECTION_CAPABILITY = "threadSectionsV1";
38488
+ var threadSectionName = external_exports.string().trim().min(1);
38489
+ var threadSectionId = external_exports.string().min(1);
38490
+ var threadSectionAppearance = external_exports.object({
38491
+ icon: external_exports.string().nullable(),
38492
+ color: external_exports.string().nullable()
38493
+ });
38494
+ var clientThreadSectionAppearanceSchema = threadSectionAppearance.nullable();
38495
+ var CLIENT_THREAD_SECTION_MUTATIONS = {
38496
+ create: {
38497
+ method: "codexhost/thread/sections/create",
38498
+ params: external_exports.object({ name: threadSectionName }).strict()
38499
+ },
38500
+ update: {
38501
+ method: "codexhost/thread/sections/update",
38502
+ params: external_exports.object({
38503
+ sectionId: threadSectionId,
38504
+ name: threadSectionName,
38505
+ appearance: threadSectionAppearance.strict().nullable().optional()
38506
+ }).strict()
38507
+ },
38508
+ delete: {
38509
+ method: "codexhost/thread/sections/delete",
38510
+ params: external_exports.object({ sectionId: threadSectionId }).strict()
38511
+ }
38512
+ };
38513
+ var clientThreadSectionMutationResultSchema = external_exports.discriminatedUnion("status", [
38514
+ external_exports.object({ status: external_exports.literal("unknown") }),
38515
+ external_exports.object({
38516
+ status: external_exports.literal("confirmed"),
38517
+ sectionId: threadSectionId,
38518
+ section: external_exports.object({
38519
+ id: threadSectionId,
38520
+ name: external_exports.string().min(1),
38521
+ appearance: clientThreadSectionAppearanceSchema
38522
+ }).nullable(),
38523
+ syncPending: external_exports.boolean()
38524
+ })
38525
+ ]);
38487
38526
  var CLIENT_CHANNEL_METHODS = [
38488
38527
  "codexhost/skills/list",
38489
38528
  "codexhost/voice/status",
@@ -38530,6 +38569,9 @@ var CLIENT_CHANNEL_METHODS = [
38530
38569
  "codexhost/thread/pins/list",
38531
38570
  "codexhost/thread/sections/list",
38532
38571
  "codexhost/thread/sections/move",
38572
+ CLIENT_THREAD_SECTION_MUTATIONS.create.method,
38573
+ CLIENT_THREAD_SECTION_MUTATIONS.update.method,
38574
+ CLIENT_THREAD_SECTION_MUTATIONS.delete.method,
38533
38575
  "codexhost/thread/pins/set",
38534
38576
  "codexhost/harness/plugins/list",
38535
38577
  "codexhost/harness/inspect",
@@ -38580,16 +38622,21 @@ var CLIENT_CHANNEL_METHODS = [
38580
38622
  "codexhost/sessions/loaded/list"
38581
38623
  ];
38582
38624
  var clientThreadSectionsSchema = external_exports.object({
38625
+ [THREAD_SECTION_CAPABILITY]: external_exports.literal(true).optional(),
38626
+ complete: external_exports.literal(false).optional(),
38583
38627
  sections: external_exports.array(external_exports.object({
38584
38628
  id: external_exports.string().min(1),
38585
38629
  name: external_exports.string().min(1),
38630
+ appearance: clientThreadSectionAppearanceSchema.optional(),
38586
38631
  threads: external_exports.array(jsonObjectSchema)
38587
- }).strict())
38588
- }).strict();
38632
+ }))
38633
+ });
38589
38634
  var clientThreadSectionMoveSchema = external_exports.object({
38590
38635
  threadId: external_exports.string().min(1).max(1024),
38591
- sectionId: external_exports.string().min(1).max(1024).nullable()
38592
- }).strict();
38636
+ sectionId: external_exports.string().min(1).max(1024).nullable(),
38637
+ beforeThreadId: external_exports.string().min(1).max(1024).nullable().optional(),
38638
+ expectedSourceSectionId: external_exports.string().min(1).max(1024).optional()
38639
+ }).refine((move) => move.expectedSourceSectionId === void 0 || move.sectionId === null);
38593
38640
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
38594
38641
  var clientThreadPinParamsSchema = external_exports.object({ threadId: external_exports.string().min(1).max(1024), pinned: external_exports.boolean() }).strict();
38595
38642
  var clientThreadTreeReadParamsSchema = external_exports.object({}).strict();
@@ -38636,6 +38683,7 @@ var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
38636
38683
  harnessId: external_exports.string().min(1)
38637
38684
  }),
38638
38685
  external_exports.object({ type: external_exports.literal("display-settings-changed"), cursor: clientChannelCursorSchema }),
38686
+ external_exports.object({ type: external_exports.literal("sections-changed"), cursor: clientChannelCursorSchema }),
38639
38687
  external_exports.object({
38640
38688
  type: external_exports.literal("preferences-changed"),
38641
38689
  cursor: clientChannelCursorSchema,
@@ -38802,7 +38850,8 @@ var clientChannelDescriptorSchema = external_exports.object({
38802
38850
  startedAt: external_exports.number(),
38803
38851
  epoch: external_exports.string().uuid(),
38804
38852
  capabilities: external_exports.object({
38805
- peerDelegation: external_exports.literal(1).optional()
38853
+ peerDelegation: external_exports.literal(1).optional(),
38854
+ threadReferenceContext: external_exports.literal(1).optional()
38806
38855
  }).optional()
38807
38856
  });
38808
38857
  var clientChannelResponseSchema = external_exports.object({
@@ -39064,7 +39113,24 @@ var webAccessStateSchema = external_exports.object({
39064
39113
  var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
39065
39114
  var REMOTE_THREAD_CONTROL_TIMEOUT_MS = 4e4;
39066
39115
  var DELEGATION_READ_METHOD = "codexhost/thread/delegation-read";
39116
+ var THREAD_REFERENCE_CONTEXT_CAPABILITY_METHOD = "codexhost/thread/reference-context/capability";
39067
39117
  var THREAD_REFERENCE_SOURCE_HOST_PARAM = "codexhostSourceHostId";
39118
+ function isDesktopSshHostId(hostId2) {
39119
+ return typeof hostId2 === "string" && hostId2.length <= 1024 && /^remote-ssh(?:-[^:\x00-\x20\x7f]+)?:[^\x00-\x20\x7f]+$/u.test(hostId2);
39120
+ }
39121
+ function threadReferenceSourceHost(params2) {
39122
+ const direct = params2[THREAD_REFERENCE_SOURCE_HOST_PARAM];
39123
+ if (typeof direct === "string")
39124
+ return direct;
39125
+ const context = params2.additionalContext;
39126
+ if (!context || typeof context !== "object")
39127
+ return void 0;
39128
+ const source = context[THREAD_REFERENCE_SOURCE_HOST_PARAM];
39129
+ if (!source || typeof source !== "object")
39130
+ return void 0;
39131
+ const { kind, value: value2 } = source;
39132
+ return kind === "application" && isDesktopSshHostId(value2) ? value2 : void 0;
39133
+ }
39068
39134
  var delegationReadParamsSchema = external_exports.strictObject({
39069
39135
  threadId: external_exports.string().min(1).max(1024),
39070
39136
  view: external_exports.enum(["result", "messages"]),
@@ -51024,6 +51090,7 @@ An external client that omits --parent-thread starts the work as itself (parent
51024
51090
  The response confirms cwd and parent. Use its Thread reference with thread read, wait, send, cancel, or watch.`,
51025
51091
  "thread send": `codexhost thread send <thread> (--message <text> | --message-file <path|->) [--host <hostId>] [--interrupt] [--steer true|false] [--watch true|false] [--watch-timeout-ms <n>] [--format json|compact|text]
51026
51092
  Start a new Turn in a writable Thread and return after submission. Accepts thread://<id>?hostId=<encoded-host-id> or --host <remote-peer:id> for paired Peers.
51093
+ A Desktop SSH link also works from a Codex or external Harness Thread when the Runtime confirms that the caller is running on the same SSH Host. Use a local Thread ID for --watch on that Host.
51027
51094
  --message and --message-file are mutually exclusive. --message-file reads UTF-8 from a file, or stdin for -; maximum 262144 bytes (256 KiB) before removing one final LF or CRLF. Other whitespace and special characters are preserved; empty/whitespace-only input is rejected. Terminal stdin is rejected: use a quoted heredoc (<<'EOF') or a pipe. --message is unchanged.
51028
51095
  Without --interrupt or --steer true, THREAD_BUSY means the current Turn is still active. Messages are not queued.
51029
51096
  --interrupt cancels an active Turn and confirms it stopped before sending (30 s stop timeout); an idle Thread is sent normally. Cancellation failure/timeout sends nothing. It preserves existing watches, suppressing the temporary stop notification; it never retries or queues a failed send.
@@ -51036,7 +51103,7 @@ Request cancellation of the active Turn while preserving the Thread and history.
51036
51103
  Accepted cancellation also removes all watches on that Thread; thread send --interrupt instead preserves them.
51037
51104
  cancelled=true (compact: cancelRequested=true) means the cancellation request was accepted. Read or wait to confirm the terminal state. An idle Thread returns false.`,
51038
51105
  "thread read": `codexhost thread read <thread> [--host <hostId>] [--view result|messages] [--from <n>] [--to <m>] [--format json|compact|text]
51039
- Read immediately without starting a Turn. Accepts thread://<id>?hostId=<encoded-host-id> or --host with a bare ID. Explicit remote Hosts use the paired Peer channel (remote-peer:<id>) or existing Desktop connection, never local fallback. Codex Desktop remote Hosts support thread read only.
51106
+ Read immediately without starting a Turn. Accepts thread://<id>?hostId=<encoded-host-id> or --host with a bare ID. The Runtime reads locally when the caller's execution Host matches the reference. Cross-host reads use the paired Peer channel (remote-peer:<id>) or an existing Desktop connection.
51040
51107
  pendingQuestions lists the unanswered Questions, with interaction ID, Turn, kind, and native question data in request; an empty list means none. No watch is needed to read or answer them.
51041
51108
  The default result view reports the latest Turn's status and result. Text result output shows Thread metadata, then --- and verbatim result text. Full JSON retains the complete snapshot. Tool calls/output, file activity, and reasoning are not included.
51042
51109
  ${MESSAGE_VIEW_HELP}`,
@@ -52331,8 +52398,9 @@ async function runDelegationCli(input3) {
52331
52398
  );
52332
52399
  }
52333
52400
  const target2 = resolveThreadTarget(rawThread, value(parsed2, "--host"), {
52334
- allowNonPeerRemote: false
52401
+ allowNonPeerRemote: true
52335
52402
  });
52403
+ if (!isDesktopSshHostId(target2.hostId)) assertRemotePeerHostOption(target2.hostId);
52336
52404
  const remote = isRemoteHostId(target2.hostId);
52337
52405
  const steer = value(parsed2, "--steer");
52338
52406
  if (steer !== void 0 && steer !== "true" && steer !== "false")
@@ -53610,6 +53678,7 @@ var OfficialRuntimeOwner = class {
53610
53678
  #clients = /* @__PURE__ */ new Set();
53611
53679
  /** Observed active official Turns per Thread, keyed by Turn ID -> live observer clients. */
53612
53680
  #activeTurns = /* @__PURE__ */ new Map();
53681
+ #executionHosts = /* @__PURE__ */ new WeakMap();
53613
53682
  /** Bounded set of recently completed `threadId\0turnId` pairs to reject late starts/responses. */
53614
53683
  #completedTurns = /* @__PURE__ */ new Set();
53615
53684
  /** Per-Thread monotonic ordinal incremented whenever a Turn start is observed. */
@@ -53661,9 +53730,18 @@ var OfficialRuntimeOwner = class {
53661
53730
  isTurnCompleted(threadId2, turnId) {
53662
53731
  return this.#completedTurns.has(`${threadId2}\0${turnId}`);
53663
53732
  }
53733
+ executionHostId(threadId2) {
53734
+ if (!this.running) return void 0;
53735
+ const turnId = this.activeTurnId(threadId2);
53736
+ const observers = turnId && this.#activeTurns.get(threadId2)?.get(turnId);
53737
+ return observers && this.#hasLiveObserver(observers) ? this.#executionHosts.get(observers) : void 0;
53738
+ }
53664
53739
  get running() {
53665
53740
  return this.#phase === "running";
53666
53741
  }
53742
+ get supportsThreadReferenceContext() {
53743
+ return this.running && this.#backend?.forwardsThreadReferenceContext !== false;
53744
+ }
53667
53745
  /** Stays true when a confirmed generation is retired or its replacement fails to start. */
53668
53746
  get hasStartedSuccessfully() {
53669
53747
  return this.#hasStartedSuccessfully;
@@ -53886,7 +53964,7 @@ var OfficialRuntimeOwner = class {
53886
53964
  try {
53887
53965
  const runtime = await this.#connection(client);
53888
53966
  await this.#restoreBeforeRequest(client, runtime, method, params2);
53889
- const forwarded = method === "thread/fork" ? this.#forkParams(params2) : params2;
53967
+ const forwarded = this.#forwardParams(method, params2);
53890
53968
  const snapshotStartOrdinal = (method === "thread/read" || method === "thread/resume") && typeof params2.threadId === "string" ? this.#threadStartOrdinal.get(params2.threadId) ?? 0 : void 0;
53891
53969
  if (turnStart) client.pendingTurnStarts.add(turnStart);
53892
53970
  response = await runtime.request(method, forwarded);
@@ -53920,8 +53998,7 @@ var OfficialRuntimeOwner = class {
53920
53998
  try {
53921
53999
  const runtime = await this.#connection(client);
53922
54000
  await this.#restoreBeforeRequest(client, runtime, method, params2);
53923
- if (method === "thread/fork" && object4(value2.params))
53924
- value2 = { ...value2, params: this.#forkParams(params2) };
54001
+ if (object4(value2.params)) value2 = { ...value2, params: this.#forwardParams(method, params2) };
53925
54002
  const snapshotStartOrdinal = (method === "thread/read" || method === "thread/resume") && typeof params2.threadId === "string" ? this.#threadStartOrdinal.get(params2.threadId) ?? 0 : void 0;
53926
54003
  if (typeof value2.id === "string" || typeof value2.id === "number") {
53927
54004
  const key = requestKey(value2.id);
@@ -53951,6 +54028,23 @@ var OfficialRuntimeOwner = class {
53951
54028
  throw new Error("Initialization cannot use the ordinary request path");
53952
54029
  }
53953
54030
  }
54031
+ #forwardParams(method, params2) {
54032
+ if (method === "thread/fork") return this.#forkParams(params2);
54033
+ if (method !== "turn/start" && method !== "turn/steer" || this.#backend?.forwardsThreadReferenceContext)
54034
+ return params2;
54035
+ const context = params2.additionalContext;
54036
+ const hasContext = object4(context) && Object.hasOwn(context, THREAD_REFERENCE_SOURCE_HOST_PARAM);
54037
+ if (!hasContext && !Object.hasOwn(params2, THREAD_REFERENCE_SOURCE_HOST_PARAM)) return params2;
54038
+ const forwarded = { ...params2 };
54039
+ delete forwarded[THREAD_REFERENCE_SOURCE_HOST_PARAM];
54040
+ if (hasContext) {
54041
+ const remaining = { ...context };
54042
+ delete remaining[THREAD_REFERENCE_SOURCE_HOST_PARAM];
54043
+ if (Object.keys(remaining).length) forwarded.additionalContext = remaining;
54044
+ else delete forwarded.additionalContext;
54045
+ }
54046
+ return forwarded;
54047
+ }
53954
54048
  async #output(client, event) {
53955
54049
  if (!this.#clients.has(client) || event.generation !== this.#generation || !["running", "starting"].includes(this.#phase))
53956
54050
  return;
@@ -54166,6 +54260,10 @@ var OfficialRuntimeOwner = class {
54166
54260
  const activeStatus = turn !== null && (turn.status === "inProgress" || turn.status === "running" || turn.status === void 0 && turnId !== null);
54167
54261
  if (method === "turn/start" && typeof params2.threadId === "string" && activeStatus && (!turnId || !turnStart?.completedTurnIds.has(turnId) && !this.isTurnCompleted(params2.threadId, turnId))) {
54168
54262
  this.#markActiveTurn(client, params2.threadId, turnId);
54263
+ if (turnId) this.#rememberExecutionHost(params2.threadId, turnId, params2);
54264
+ }
54265
+ if (method === "turn/steer" && typeof params2.threadId === "string" && typeof response.result.turnId === "string") {
54266
+ this.#rememberExecutionHost(params2.threadId, response.result.turnId, params2);
54169
54267
  }
54170
54268
  if ((method === "thread/read" || method === "thread/resume") && typeof params2.threadId === "string" && object4(response.result.thread) && response.result.thread.id === params2.threadId && snapshotStartOrdinal !== void 0) {
54171
54269
  this.#reconcileThreadSnapshot(
@@ -54285,6 +54383,12 @@ var OfficialRuntimeOwner = class {
54285
54383
  client.pendingTurnStarts.clear();
54286
54384
  client.serverRequests.clear();
54287
54385
  }
54386
+ #rememberExecutionHost(threadId2, turnId, params2) {
54387
+ const observers = this.#activeTurns.get(threadId2)?.get(turnId);
54388
+ if (!observers) return;
54389
+ const hostId2 = threadReferenceSourceHost(params2);
54390
+ if (isDesktopSshHostId(hostId2)) this.#executionHosts.set(observers, hostId2);
54391
+ }
54288
54392
  #unavailable() {
54289
54393
  this.#phase = "unavailable";
54290
54394
  for (const client of this.#clients) {
@@ -54723,6 +54827,8 @@ async function createRemoteOfficialAppServerConnection(endpoint, options = {}) {
54723
54827
  // packages/host-runtime/src/shared-thread-peer.ts
54724
54828
  import { randomUUID as randomUUID12 } from "node:crypto";
54725
54829
  var DEFAULT_REQUEST_TIMEOUT_MS = 12e4;
54830
+ var SHARED_THREAD_LIST_METHOD = "codexhost/shared-threads/list";
54831
+ var SHARED_THREAD_OWNERSHIP_METHOD = "codexhost/shared-threads/ownership/list";
54726
54832
  function object5(value2) {
54727
54833
  return value2 !== null && typeof value2 === "object" && !Array.isArray(value2);
54728
54834
  }
@@ -54903,6 +55009,9 @@ function sharedNativeBackend(dataDirectory) {
54903
55009
  });
54904
55010
  };
54905
55011
  return {
55012
+ get forwardsThreadReferenceContext() {
55013
+ return descriptor?.capabilities?.threadReferenceContext === 1;
55014
+ },
54906
55015
  closed: ended.promise,
54907
55016
  connect,
54908
55017
  async start() {
@@ -58834,7 +58943,7 @@ async function readThreadCatalog(input3) {
58834
58943
  (query) => measure(query.archived ? "sharedArchived" : "shared", async (count2) => {
58835
58944
  if (!input3.sharedThreads) return [];
58836
58945
  count2();
58837
- return input3.sharedThreads.list(query.params);
58946
+ return input3.sharedThreads.list(query.params, { requireComplete: true });
58838
58947
  })
58839
58948
  )
58840
58949
  )
@@ -68841,7 +68950,7 @@ var HarnessDelegationCoordinator = class {
68841
68950
  ...session.initialState.nativeRef ? {} : { restoredState: session.initialState }
68842
68951
  });
68843
68952
  const beforeRevision = thread4.stateObserver.revision;
68844
- await this.#startExternalTurn(thread4, input3.task, turnId);
68953
+ await this.#startExternalTurn(thread4, input3.task, turnId, input3.sourceHostId);
68845
68954
  if (!thread4.record.nativeSessionRef) {
68846
68955
  const deadline = Date.now() + NATIVE_REF_TIMEOUT_MS;
68847
68956
  let revision2 = beforeRevision;
@@ -68925,7 +69034,7 @@ var HarnessDelegationCoordinator = class {
68925
69034
  if (!input3.steer) {
68926
69035
  throw new DelegationControlError("THREAD_BUSY", "Thread already has an active Turn");
68927
69036
  }
68928
- const turnId2 = await this.#steerExternalTurn(thread4, input3.message);
69037
+ const turnId2 = await this.#steerExternalTurn(thread4, input3.message, input3.sourceHostId);
68929
69038
  return this.#turnResult(thread4.id, turnId2, thread4.harnessId);
68930
69039
  }
68931
69040
  if (!input3.steer && !input3.interrupt && this.#externalQueueWaiting(thread4)) {
@@ -68936,7 +69045,7 @@ var HarnessDelegationCoordinator = class {
68936
69045
  }
68937
69046
  const turnId = hostTurnIdSchema.parse(randomUUID30());
68938
69047
  try {
68939
- await this.#startExternalTurn(thread4, input3.message, turnId);
69048
+ await this.#startExternalTurn(thread4, input3.message, turnId, input3.sourceHostId);
68940
69049
  } catch (error62) {
68941
69050
  if (error62 instanceof DelegationControlError) throw error62;
68942
69051
  throw new DelegationControlError(
@@ -69301,8 +69410,8 @@ import { pathToFileURL } from "node:url";
69301
69410
  function isNullable(value2) {
69302
69411
  return value2 === null || value2 === void 0;
69303
69412
  }
69304
- function defineProperty(object12, key, value2) {
69305
- return Object.defineProperty(object12, key, {
69413
+ function defineProperty(object13, key, value2) {
69414
+ return Object.defineProperty(object13, key, {
69306
69415
  writable: true,
69307
69416
  value: value2,
69308
69417
  enumerable: false
@@ -70841,8 +70950,8 @@ var Fiber = class {
70841
70950
  });
70842
70951
  }
70843
70952
  };
70844
- function isApplicable(object12) {
70845
- return object12 && typeof object12 === "object" && typeof object12.apply === "function";
70953
+ function isApplicable(object13) {
70954
+ return object13 && typeof object13 === "object" && typeof object13.apply === "function";
70846
70955
  }
70847
70956
  function Inject(name, config2) {
70848
70957
  return function(value2, decorator) {
@@ -72252,6 +72361,12 @@ var ClientChannelEvents = class {
72252
72361
  cursor: { epoch: this.epoch, sequence: ++this.sequence }
72253
72362
  });
72254
72363
  }
72364
+ sectionsChanged() {
72365
+ this.publish({
72366
+ type: "sections-changed",
72367
+ cursor: { epoch: this.epoch, sequence: ++this.sequence }
72368
+ });
72369
+ }
72255
72370
  skillsChanged(cwd) {
72256
72371
  this.publish({
72257
72372
  type: "skills-changed",
@@ -72816,6 +72931,9 @@ import { homedir as homedir6 } from "node:os";
72816
72931
  // packages/host-runtime/src/external-thread-sections.ts
72817
72932
  var MAX_OFFICIAL_PAGES = 256;
72818
72933
  var OFFICIAL_PAGE_SIZE2 = 100;
72934
+ var SHARED_SECTIONS_WATCH_METHOD = "codexhost/shared-threads/sections/watch";
72935
+ var SHARED_SECTIONS_CHANGED_METHOD = "codexhost/shared-threads/sections/changed";
72936
+ var SHARED_SECTIONS_RECONCILE_METHOD = "codexhost/shared-threads/sections/reconcile";
72819
72937
  var ThreadSectionError = class extends Error {
72820
72938
  constructor(message2) {
72821
72939
  super(message2);
@@ -72888,62 +73006,142 @@ function planSectionMove(input3) {
72888
73006
  officialBeforeThreadId: intended.slice(index + 1).find((id3) => !input3.isExternal(id3)) ?? null
72889
73007
  };
72890
73008
  }
72891
- async function listAllOfficialRows(requestOfficial, params2) {
73009
+ async function listAllOfficialRows(requestOfficial, params2, requireComplete = false) {
72892
73010
  const rows = [];
73011
+ const seen = requireComplete ? /* @__PURE__ */ new Set() : void 0;
72893
73012
  let cursor = null;
72894
73013
  for (let page = 0; page < MAX_OFFICIAL_PAGES; page += 1) {
72895
- const result = officialThreadListPageFromResponse(
72896
- await requestOfficial("thread/list", { ...params2, cursor, limit: OFFICIAL_PAGE_SIZE2 })
72897
- );
73014
+ const response = await requestOfficial("thread/list", {
73015
+ ...params2,
73016
+ cursor,
73017
+ limit: OFFICIAL_PAGE_SIZE2
73018
+ });
73019
+ const result = officialThreadListPageFromResponse(response);
73020
+ if (seen && (!object9(response.result) || response.result.nextCursor === void 0)) {
73021
+ throw new ThreadSectionError("Incomplete official section order");
73022
+ }
72898
73023
  rows.push(...result.data);
72899
- if (result.nextCursor === null || result.nextCursor === cursor) return rows;
72900
- cursor = result.nextCursor;
73024
+ const next = result.nextCursor;
73025
+ if (next === null) return rows;
73026
+ if (seen) {
73027
+ if (!next || seen.has(next))
73028
+ throw new ThreadSectionError("Incomplete official section order");
73029
+ seen.add(next);
73030
+ } else if (next === cursor) return rows;
73031
+ cursor = next;
72901
73032
  }
72902
73033
  throw new Error("Official thread/list pagination exceeded its request bound");
72903
73034
  }
73035
+ async function officialSectionOrder(input3) {
73036
+ const rows = await listAllOfficialRows(
73037
+ input3.requestOfficial,
73038
+ {
73039
+ sectionId: input3.sectionId,
73040
+ sortKey: "section_position",
73041
+ modelProviders: [],
73042
+ useStateDbOnly: true,
73043
+ ...input3.requireComplete ? { sortDirection: "asc" } : {}
73044
+ },
73045
+ input3.requireComplete
73046
+ );
73047
+ const officialIds = rows.map((row) => String(row.id));
73048
+ if (input3.requireComplete && (rows.some((row) => typeof row.id !== "string" || !row.id) || new Set(officialIds).size !== officialIds.length))
73049
+ throw new ThreadSectionError("Invalid official section members");
73050
+ return officialIds;
73051
+ }
72904
73052
  async function sectionOrder(input3) {
72905
- const rows = await listAllOfficialRows(input3.requestOfficial, {
72906
- sectionId: input3.sectionId,
72907
- sortKey: "section_position",
72908
- modelProviders: [],
72909
- useStateDbOnly: true
72910
- });
72911
73053
  return mergeSectionOrder(
72912
- rows.map((row) => String(row.id)),
73054
+ await officialSectionOrder(input3),
72913
73055
  input3.placements.filter((placement) => placement.section.id === input3.sectionId)
72914
73056
  );
72915
73057
  }
73058
+ function object9(value2) {
73059
+ return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
73060
+ }
73061
+ function officialSectionDefinition(value2) {
73062
+ if (!object9(value2) || typeof value2.id !== "string" || !value2.id || typeof value2.name !== "string" || !value2.name.trim())
73063
+ return null;
73064
+ const appearance = value2.appearance;
73065
+ if (appearance != null && !object9(appearance)) return null;
73066
+ const icon = appearance?.icon ?? null;
73067
+ const color = appearance?.color ?? null;
73068
+ if (icon !== null && typeof icon !== "string" || color !== null && typeof color !== "string")
73069
+ return null;
73070
+ return {
73071
+ id: value2.id,
73072
+ name: value2.name,
73073
+ appearance: appearance ? { icon, color } : null
73074
+ };
73075
+ }
73076
+ var SectionDefinitions = class {
73077
+ constructor(pinnedSectionId) {
73078
+ this.pinnedSectionId = pinnedSectionId;
73079
+ }
73080
+ pinnedSectionId;
73081
+ #complete;
73082
+ #confirmed = /* @__PURE__ */ new Map();
73083
+ replace(definitions) {
73084
+ this.#complete = definitions;
73085
+ this.#confirmed.clear();
73086
+ }
73087
+ confirm(sectionId, section) {
73088
+ this.#confirmed.set(sectionId, section);
73089
+ }
73090
+ project(placements, complete = this.#complete) {
73091
+ let next;
73092
+ for (const [index, placement] of placements.entries()) {
73093
+ const { section } = placement;
73094
+ const confirmed = complete === this.#complete ? this.#confirmed.get(section.id) : void 0;
73095
+ const current2 = confirmed !== void 0 ? confirmed : complete?.get(section.id);
73096
+ if (section.id !== this.pinnedSectionId && (current2 === null || current2 === void 0 && complete)) {
73097
+ next ??= placements.slice(0, index);
73098
+ } else if (current2 && !sameSectionDefinition(section, current2)) {
73099
+ next ??= placements.slice(0, index);
73100
+ next.push({ ...placement, section: current2 });
73101
+ } else {
73102
+ next?.push(placement);
73103
+ }
73104
+ }
73105
+ return next ?? placements;
73106
+ }
73107
+ };
73108
+ function sameSectionDefinition(left, right) {
73109
+ return left.name === right.name && left.appearance === null === (right.appearance === null) && left.appearance?.icon === right.appearance?.icon && left.appearance?.color === right.appearance?.color;
73110
+ }
73111
+ function sameProjectedSections(before, after) {
73112
+ return before === after || before.length === after.length && before.every((placement, index) => {
73113
+ const next = after[index];
73114
+ return next !== void 0 && (placement === next || placement.hostThreadId === next.hostThreadId && placement.section.id === next.section.id && sameSectionDefinition(placement.section, next.section));
73115
+ });
73116
+ }
72916
73117
  async function* officialThreadSections(requestOfficial) {
72917
73118
  let cursor = null;
72918
73119
  const seen = /* @__PURE__ */ new Set();
73120
+ const cursors = /* @__PURE__ */ new Set();
72919
73121
  for (let page = 0; page < MAX_OFFICIAL_PAGES; page += 1) {
72920
73122
  const response = await requestOfficial("threadSection/list", {
72921
73123
  cursor,
72922
73124
  limit: OFFICIAL_PAGE_SIZE2
72923
73125
  });
72924
73126
  const result = response.result;
72925
- if (typeof result !== "object" || result === null || Array.isArray(result)) {
72926
- throw new Error("Official threadSection/list failed");
72927
- }
72928
- const data = Array.isArray(result.data) ? result.data : [];
72929
- for (const entry of data) {
72930
- if (typeof entry !== "object" || entry === null || Array.isArray(entry)) continue;
72931
- if (typeof entry.id !== "string" || !entry.id || seen.has(entry.id)) continue;
72932
- seen.add(entry.id);
72933
- const appearance = entry.appearance;
72934
- yield {
72935
- id: entry.id,
72936
- name: typeof entry.name === "string" ? entry.name : "",
72937
- appearance: typeof appearance === "object" && appearance !== null && !Array.isArray(appearance) ? {
72938
- icon: typeof appearance.icon === "string" ? appearance.icon : null,
72939
- color: typeof appearance.color === "string" ? appearance.color : null
72940
- } : null
72941
- };
72942
- }
72943
- const next = typeof result.nextCursor === "string" ? result.nextCursor : null;
72944
- if (next === null || next === cursor) break;
73127
+ if (!object9(result) || !Array.isArray(result.data) || result.nextCursor !== null && typeof result.nextCursor !== "string") {
73128
+ throw new Error("Invalid official threadSection/list response");
73129
+ }
73130
+ for (const entry of result.data) {
73131
+ const section = officialSectionDefinition(entry);
73132
+ if (!section || seen.has(section.id))
73133
+ throw new Error("Invalid or duplicate official Thread section");
73134
+ seen.add(section.id);
73135
+ yield section;
73136
+ }
73137
+ const next = result.nextCursor;
73138
+ if (next === null) return;
73139
+ if (!next || cursors.has(next))
73140
+ throw new Error("Official Thread section pagination did not advance");
73141
+ cursors.add(next);
72945
73142
  cursor = next;
72946
73143
  }
73144
+ throw new Error("Official Thread section pagination exceeded its request bound");
72947
73145
  }
72948
73146
  async function findOfficialSection(requestOfficial, sectionId) {
72949
73147
  for await (const section of officialThreadSections(requestOfficial)) {
@@ -72985,16 +73183,87 @@ function officialError(response) {
72985
73183
  const error62 = response.error;
72986
73184
  return typeof error62 === "object" && error62 !== null && !Array.isArray(error62) ? error62 : null;
72987
73185
  }
73186
+ function sameSectionAnchors(actual, expected) {
73187
+ return actual.length === expected.length && actual.every((placement, index) => {
73188
+ const original = expected[index];
73189
+ return original !== void 0 && placement.hostThreadId === original.hostThreadId && placement.section.id === original.section.id && placement.enteredAt === original.enteredAt && placement.beforeThreadId === original.beforeThreadId;
73190
+ });
73191
+ }
73192
+ async function officialThreadIsUnsectioned(requestOfficial, threadId2) {
73193
+ const response = await requestOfficial("thread/read", { threadId: threadId2, includeTurns: false });
73194
+ const thread4 = object9(response.result) ? response.result.thread : void 0;
73195
+ if (officialError(response) || !object9(thread4) || thread4.id !== threadId2) {
73196
+ throw new ThreadSectionError("Could not confirm the moved Thread's section");
73197
+ }
73198
+ return thread4.section === null;
73199
+ }
73200
+ function sectionAnchorRecovery(input3) {
73201
+ const { expectedNativeOrders, unsectionedThreadId, requestOfficial, savePlacements } = input3;
73202
+ const affected = (placement) => expectedNativeOrders.has(placement.section.id);
73203
+ const previous = input3.previous.filter(affected);
73204
+ const planned = input3.planned.filter(affected);
73205
+ return async (loadPlacements) => {
73206
+ for (const [sectionId, expected] of expectedNativeOrders) {
73207
+ const actual = await officialSectionOrder({
73208
+ sectionId,
73209
+ requestOfficial,
73210
+ requireComplete: true
73211
+ });
73212
+ if (actual.length !== expected.length || actual.some((id3, index) => id3 !== expected[index])) {
73213
+ return false;
73214
+ }
73215
+ }
73216
+ if (unsectionedThreadId !== null && !await officialThreadIsUnsectioned(requestOfficial, unsectionedThreadId))
73217
+ return false;
73218
+ const placements = await loadPlacements();
73219
+ const current2 = placements.filter(affected);
73220
+ const alreadyApplied = sameSectionAnchors(current2, planned);
73221
+ if (!alreadyApplied && !sameSectionAnchors(current2, previous)) return false;
73222
+ if (alreadyApplied) return true;
73223
+ const anchors = new Map(
73224
+ planned.map((placement) => [placement.hostThreadId, placement.beforeThreadId])
73225
+ );
73226
+ const next = [];
73227
+ for (const placement of placements) {
73228
+ if (!affected(placement)) {
73229
+ next.push(placement);
73230
+ continue;
73231
+ }
73232
+ const beforeThreadId = anchors.get(placement.hostThreadId);
73233
+ if (beforeThreadId !== void 0) next.push({ ...placement, beforeThreadId });
73234
+ }
73235
+ await savePlacements(next);
73236
+ return true;
73237
+ };
73238
+ }
72988
73239
  async function moveThreadSection(input3) {
72989
- const { move, requestOfficial } = input3;
73240
+ const { move, requestOfficial, custom: custom2 } = input3;
72990
73241
  const isExternal = (threadId2) => input3.externalThreadIds.has(threadId2);
72991
- if (!input3.movingExternal && input3.placements.length === 0 && !(move.beforeThreadId !== null && isExternal(move.beforeThreadId))) {
72992
- return { kind: "forward" };
73242
+ if (!custom2 && !input3.movingExternal && input3.placements.length === 0 && !(move.beforeThreadId !== null && isExternal(move.beforeThreadId))) {
73243
+ return {
73244
+ kind: "forward",
73245
+ async confirm() {
73246
+ const { threadId: threadId2, sectionId, beforeThreadId } = move;
73247
+ if (sectionId === null)
73248
+ return beforeThreadId === null && officialThreadIsUnsectioned(requestOfficial, threadId2);
73249
+ const order = await officialSectionOrder({
73250
+ sectionId,
73251
+ requestOfficial,
73252
+ requireComplete: true
73253
+ });
73254
+ const index = order.indexOf(threadId2);
73255
+ return index >= 0 && (order[index + 1] ?? null) === beforeThreadId;
73256
+ }
73257
+ };
72993
73258
  }
72994
73259
  try {
72995
73260
  let currentSectionId;
72996
73261
  let destination = null;
72997
- if (input3.movingExternal) {
73262
+ if (custom2) {
73263
+ currentSectionId = custom2.currentSectionId;
73264
+ if (move.sectionId !== null)
73265
+ destination = custom2.destination ?? await findOfficialSection(requestOfficial, move.sectionId);
73266
+ } else if (input3.movingExternal) {
72998
73267
  currentSectionId = input3.placements.find((placement) => placement.hostThreadId === move.threadId)?.section.id ?? null;
72999
73268
  if (move.sectionId !== null)
73000
73269
  destination = await findOfficialSection(requestOfficial, move.sectionId);
@@ -73009,13 +73278,36 @@ async function moveThreadSection(input3) {
73009
73278
  if (move.sectionId !== null) destination = { id: move.sectionId, name: "", appearance: null };
73010
73279
  }
73011
73280
  const orders = /* @__PURE__ */ new Map();
73281
+ const nativeOrders = input3.movingExternal ? null : /* @__PURE__ */ new Map();
73012
73282
  for (const sectionId of /* @__PURE__ */ new Set([currentSectionId, move.sectionId])) {
73013
73283
  if (sectionId === null) continue;
73284
+ const native = await officialSectionOrder({
73285
+ sectionId,
73286
+ requestOfficial,
73287
+ requireComplete: custom2 !== void 0 || nativeOrders !== null
73288
+ });
73289
+ nativeOrders?.set(sectionId, native);
73014
73290
  orders.set(
73015
73291
  sectionId,
73016
- await sectionOrder({ sectionId, placements: input3.placements, requestOfficial })
73292
+ mergeSectionOrder(
73293
+ native,
73294
+ input3.placements.filter((placement) => placement.section.id === sectionId)
73295
+ )
73017
73296
  );
73018
73297
  }
73298
+ if (custom2 && currentSectionId !== null) {
73299
+ const order = orders.get(currentSectionId) ?? [];
73300
+ const index = order.indexOf(move.threadId);
73301
+ if (index < 0) throw new ThreadSectionError("Moved Thread is missing from the section order");
73302
+ if (currentSectionId === move.sectionId) {
73303
+ if (move.beforeThreadId !== null && !order.includes(move.beforeThreadId)) {
73304
+ throw new ThreadSectionError(
73305
+ `before thread ${move.beforeThreadId} is not in section ${move.sectionId}`
73306
+ );
73307
+ }
73308
+ if ((order[index + 1] ?? null) === move.beforeThreadId) return { kind: "unchanged" };
73309
+ }
73310
+ }
73019
73311
  const plan = planSectionMove({
73020
73312
  move,
73021
73313
  movingExternal: input3.movingExternal,
@@ -73026,22 +73318,59 @@ async function moveThreadSection(input3) {
73026
73318
  isExternal,
73027
73319
  now: input3.now
73028
73320
  });
73029
- if (!input3.movingExternal) {
73030
- const response = await requestOfficial("thread/section/move", {
73031
- threadId: move.threadId,
73032
- sectionId: move.sectionId,
73033
- beforeThreadId: plan.officialBeforeThreadId
73034
- });
73035
- const error62 = officialError(response);
73036
- if (error62) return { kind: "error", error: error62 };
73321
+ if (!nativeOrders) {
73322
+ await input3.savePlacements(plan.placements);
73323
+ return { kind: "moved" };
73324
+ }
73325
+ const currentNativeOrder = currentSectionId === null ? void 0 : nativeOrders.get(currentSectionId);
73326
+ const currentIndex = currentNativeOrder?.indexOf(move.threadId) ?? -1;
73327
+ const nativeMove = !custom2 || currentSectionId !== move.sectionId || currentSectionId !== null && (currentIndex < 0 || (currentNativeOrder?.[currentIndex + 1] ?? null) !== plan.officialBeforeThreadId);
73328
+ const readBack = (nativeConfirmed, cause) => {
73329
+ for (const [sectionId, order] of nativeOrders) {
73330
+ const current2 = order.indexOf(move.threadId);
73331
+ if (current2 >= 0) order.splice(current2, 1);
73332
+ if (sectionId === move.sectionId) {
73333
+ const before = plan.officialBeforeThreadId;
73334
+ order.splice(before === null ? order.length : order.indexOf(before), 0, move.threadId);
73335
+ }
73336
+ }
73337
+ return {
73338
+ kind: "needs-readback",
73339
+ nativeConfirmed,
73340
+ cause,
73341
+ recover: sectionAnchorRecovery({
73342
+ expectedNativeOrders: nativeOrders,
73343
+ unsectionedThreadId: move.sectionId === null ? move.threadId : null,
73344
+ previous: input3.placements,
73345
+ planned: plan.placements,
73346
+ requestOfficial,
73347
+ savePlacements: input3.savePlacements
73348
+ })
73349
+ };
73350
+ };
73351
+ if (nativeMove) {
73037
73352
  try {
73038
- await input3.savePlacements(plan.placements);
73039
- } catch (persistError) {
73040
- return { kind: "moved", persistError };
73353
+ const response = await requestOfficial("thread/section/move", {
73354
+ threadId: move.threadId,
73355
+ sectionId: move.sectionId,
73356
+ beforeThreadId: plan.officialBeforeThreadId
73357
+ });
73358
+ const error62 = officialError(response);
73359
+ if (error62) return { kind: "error", error: error62 };
73360
+ } catch (error62) {
73361
+ return readBack(false, error62);
73041
73362
  }
73042
- return { kind: "moved" };
73043
73363
  }
73044
- await input3.savePlacements(plan.placements);
73364
+ if (custom2 && sameSectionAnchors(input3.placements, plan.placements)) {
73365
+ return { kind: nativeMove ? "moved" : "unchanged" };
73366
+ }
73367
+ try {
73368
+ await input3.savePlacements(plan.placements);
73369
+ } catch (persistError) {
73370
+ if (!nativeMove) throw persistError;
73371
+ if (!custom2) return { kind: "moved", persistError };
73372
+ return readBack(true, persistError);
73373
+ }
73045
73374
  return { kind: "moved" };
73046
73375
  } catch (error62) {
73047
73376
  if (error62 instanceof ThreadSectionError)
@@ -73141,10 +73470,24 @@ var ThreadPins = class {
73141
73470
  now: /* @__PURE__ */ new Date()
73142
73471
  });
73143
73472
  if (outcome.kind === "forward") {
73144
- const response = await this.requestOfficial("thread/section/move", move);
73145
- if (response.error) throw new ThreadSectionError(pinError(response));
73473
+ const response = await this.requestOfficial("thread/section/move", move).catch(
73474
+ async (error62) => {
73475
+ if (await outcome.confirm().catch(() => false)) return void 0;
73476
+ throw new Error("Native pin change outcome is unknown; refresh before retrying", {
73477
+ cause: error62
73478
+ });
73479
+ }
73480
+ );
73481
+ if (response?.error) throw new ThreadSectionError(pinError(response));
73146
73482
  } else if (outcome.kind === "error") {
73147
73483
  throw new ThreadSectionError(String(outcome.error.message ?? "Native pin change failed"));
73484
+ } else if (outcome.kind === "needs-readback") {
73485
+ const recovered = await outcome.recover(() => this.repository.listSectionPlacements()).catch(() => false);
73486
+ if (!recovered) {
73487
+ throw new Error("Native pin change outcome is unknown; refresh before retrying", {
73488
+ cause: outcome.cause
73489
+ });
73490
+ }
73148
73491
  }
73149
73492
  if (pinned) this.observedIds.add(threadId2);
73150
73493
  else this.observedIds.delete(threadId2);
@@ -73537,7 +73880,7 @@ async function requestNativeGoal(params2, request, resume) {
73537
73880
  }
73538
73881
 
73539
73882
  // packages/host-runtime/src/native-queued-steering.ts
73540
- var object9 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
73883
+ var object10 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
73541
73884
  async function sendNativeQueuedMessage(request, threadId2, itemId) {
73542
73885
  const turns = await request("thread/turns/list", {
73543
73886
  threadId: threadId2,
@@ -73546,12 +73889,12 @@ async function sendNativeQueuedMessage(request, threadId2, itemId) {
73546
73889
  itemsView: "notLoaded"
73547
73890
  });
73548
73891
  if ("error" in turns) return turns;
73549
- if (!object9(turns.result) || !Array.isArray(turns.result.data))
73892
+ if (!object10(turns.result) || !Array.isArray(turns.result.data))
73550
73893
  return { error: { code: -32603, message: "Codex returned an invalid Turn page" } };
73551
73894
  const active3 = turns.result.data.find(
73552
- (turn) => object9(turn) && turn.status === "inProgress" && typeof turn.id === "string"
73895
+ (turn) => object10(turn) && turn.status === "inProgress" && typeof turn.id === "string"
73553
73896
  );
73554
- if (!object9(active3) || typeof active3.id !== "string")
73897
+ if (!object10(active3) || typeof active3.id !== "string")
73555
73898
  return request("thread/queue/start", { threadId: threadId2, queuedSubmissionId: itemId });
73556
73899
  let cursor;
73557
73900
  const cursors = /* @__PURE__ */ new Set();
@@ -73563,10 +73906,10 @@ async function sendNativeQueuedMessage(request, threadId2, itemId) {
73563
73906
  ...cursor ? { cursor } : {}
73564
73907
  });
73565
73908
  if ("error" in page) return page;
73566
- if (!object9(page.result) || !Array.isArray(page.result.data))
73909
+ if (!object10(page.result) || !Array.isArray(page.result.data))
73567
73910
  return { error: { code: -32603, message: "Codex returned an invalid queue page" } };
73568
- const found = page.result.data.find((entry) => object9(entry) && entry.id === itemId);
73569
- if (object9(found)) {
73911
+ const found = page.result.data.find((entry) => object10(entry) && entry.id === itemId);
73912
+ if (object10(found)) {
73570
73913
  item = found;
73571
73914
  break;
73572
73915
  }
@@ -73584,13 +73927,13 @@ async function sendNativeQueuedMessage(request, threadId2, itemId) {
73584
73927
  clientUserMessageId: item.clientUserMessageId
73585
73928
  });
73586
73929
  if ("error" in steered) return steered;
73587
- if (!object9(steered.result) || steered.result.turnId !== active3.id)
73930
+ if (!object10(steered.result) || steered.result.turnId !== active3.id)
73588
73931
  return {
73589
73932
  error: { code: -32090, message: "Codex did not confirm the steered Turn. Do not resend." }
73590
73933
  };
73591
73934
  try {
73592
73935
  const deleted = await request("thread/queue/delete", { threadId: threadId2, queuedSubmissionId: itemId });
73593
- if ("result" in deleted && object9(deleted.result) && deleted.result.deleted === true)
73936
+ if ("result" in deleted && object10(deleted.result) && deleted.result.deleted === true)
73594
73937
  return steered;
73595
73938
  } catch {
73596
73939
  }
@@ -73603,21 +73946,21 @@ async function sendNativeQueuedMessage(request, threadId2, itemId) {
73603
73946
  }
73604
73947
 
73605
73948
  // packages/host-runtime/src/native-queued-input.ts
73606
- var object10 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
73949
+ var object11 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
73607
73950
  async function submitNativeQueuedInput(request, params2) {
73608
73951
  const threadId2 = params2.threadId;
73609
73952
  if (typeof threadId2 !== "string")
73610
73953
  return { error: { code: -32602, message: "threadId is required" } };
73611
73954
  const read = await request("thread/read", { threadId: threadId2, includeTurns: false });
73612
73955
  if ("error" in read) return read;
73613
- const thread4 = object10(read.result) ? read.result.thread : void 0;
73614
- if (!object10(thread4) || thread4.id !== threadId2 || !object10(thread4.status))
73956
+ const thread4 = object11(read.result) ? read.result.thread : void 0;
73957
+ if (!object11(thread4) || thread4.id !== threadId2 || !object11(thread4.status))
73615
73958
  return { error: { code: -32603, message: "Codex did not confirm the Thread runtime state" } };
73616
73959
  const idle = thread4.status.type === "idle";
73617
73960
  const added = await request("thread/queue/add", params2);
73618
73961
  if ("error" in added) return added;
73619
- const item = object10(added.result) ? added.result.queuedSubmission : void 0;
73620
- if (!object10(item) || typeof item.id !== "string")
73962
+ const item = object11(added.result) ? added.result.queuedSubmission : void 0;
73963
+ if (!object11(item) || typeof item.id !== "string")
73621
73964
  return {
73622
73965
  error: { code: -32090, message: "Codex did not confirm the queued input. Do not resend." }
73623
73966
  };
@@ -73630,10 +73973,10 @@ async function submitNativeQueuedInput(request, params2) {
73630
73973
  });
73631
73974
  try {
73632
73975
  const queue = await request("thread/queue/list", { threadId: threadId2, limit: 1 });
73633
- if ("error" in queue || !object10(queue.result) || !Array.isArray(queue.result.data))
73976
+ if ("error" in queue || !object11(queue.result) || !Array.isArray(queue.result.data))
73634
73977
  return unconfirmed();
73635
73978
  const head = queue.result.data[0];
73636
- if (!object10(head) || head.id !== item.id) return added;
73979
+ if (!object11(head) || head.id !== item.id) return added;
73637
73980
  const started = await request("thread/queue/start", {
73638
73981
  threadId: threadId2,
73639
73982
  queuedSubmissionId: item.id
@@ -73643,20 +73986,20 @@ async function submitNativeQueuedInput(request, params2) {
73643
73986
  return added;
73644
73987
  return unconfirmed();
73645
73988
  }
73646
- const turn = object10(started.result) ? started.result.turn : void 0;
73647
- return object10(turn) && typeof turn.id === "string" ? started : unconfirmed();
73989
+ const turn = object11(started.result) ? started.result.turn : void 0;
73990
+ return object11(turn) && typeof turn.id === "string" ? started : unconfirmed();
73648
73991
  } catch {
73649
73992
  return unconfirmed();
73650
73993
  }
73651
73994
  }
73652
73995
 
73653
73996
  // packages/host-runtime/src/native-client-items.ts
73654
- var object11 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
73997
+ var object12 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
73655
73998
  var time3 = (value2) => typeof value2 === "number" && Number.isFinite(value2) && value2 >= 0;
73656
73999
  function chronological(items) {
73657
- if (!items.every((item) => object11(item) && time3(item.startedAtMs))) return items;
74000
+ if (!items.every((item) => object12(item) && time3(item.startedAtMs))) return items;
73658
74001
  return items.toSorted(
73659
- (left, right) => object11(left) && object11(right) && time3(left.startedAtMs) && time3(right.startedAtMs) ? left.startedAtMs - right.startedAtMs : 0
74002
+ (left, right) => object12(left) && object12(right) && time3(left.startedAtMs) && time3(right.startedAtMs) ? left.startedAtMs - right.startedAtMs : 0
73660
74003
  );
73661
74004
  }
73662
74005
  var NativeClientItems = class {
@@ -73669,7 +74012,7 @@ var NativeClientItems = class {
73669
74012
  return;
73670
74013
  }
73671
74014
  if (typeof params2.turnId !== "string") return;
73672
- const item = object11(params2.item) ? params2.item : void 0;
74015
+ const item = object12(params2.item) ? params2.item : void 0;
73673
74016
  const id3 = item?.id ?? params2.itemId;
73674
74017
  if (typeof id3 !== "string") return;
73675
74018
  const key = JSON.stringify([params2.threadId, params2.turnId, id3]);
@@ -73702,16 +74045,16 @@ var NativeClientItems = class {
73702
74045
  return {
73703
74046
  ...result,
73704
74047
  data: result.data.map((turn) => {
73705
- if (!object11(turn) || !Array.isArray(turn.items) || turn.itemsView === "notLoaded" || turn.itemsView === "summary")
74048
+ if (!object12(turn) || !Array.isArray(turn.items) || turn.itemsView === "notLoaded" || turn.itemsView === "summary")
73706
74049
  return turn;
73707
74050
  const items = turn.items.map(
73708
- (item) => object11(item) && item.type === "contextCompaction" ? { ...item, status: item.status ?? "completed" } : item
74051
+ (item) => object12(item) && item.type === "contextCompaction" ? { ...item, status: item.status ?? "completed" } : item
73709
74052
  );
73710
74053
  for (const [key, entry] of this.#items) {
73711
74054
  if (entry.threadId !== threadId2 || entry.turnId !== turn.id) continue;
73712
- const index = items.findIndex((item) => object11(item) && item.id === entry.item.id);
74055
+ const index = items.findIndex((item) => object12(item) && item.id === entry.item.id);
73713
74056
  const persisted2 = index === -1 ? void 0 : items[index];
73714
- if (object11(persisted2) && persisted2.status !== "inProgress") {
74057
+ if (object12(persisted2) && persisted2.status !== "inProgress") {
73715
74058
  if (entry.item.type === "contextCompaction")
73716
74059
  entry.item = { ...entry.item, ...persisted2 };
73717
74060
  else this.#items.delete(key);
@@ -73721,13 +74064,13 @@ var NativeClientItems = class {
73721
74064
  ...entry.item,
73722
74065
  status: turn.status === "failed" ? "failed" : "interrupted",
73723
74066
  error: {
73724
- message: object11(turn.error) && turn.error.message || "Turn ended before context compaction completed"
74067
+ message: object12(turn.error) && turn.error.message || "Turn ended before context compaction completed"
73725
74068
  }
73726
74069
  };
73727
74070
  if (index === -1) items.push(structuredClone(entry.item));
73728
74071
  else
73729
74072
  items[index] = structuredClone({
73730
- ...object11(persisted2) ? persisted2 : {},
74073
+ ...object12(persisted2) ? persisted2 : {},
73731
74074
  ...entry.item
73732
74075
  });
73733
74076
  }
@@ -74658,7 +75001,6 @@ var OFFICIAL_METHODS = {
74658
75001
  "codexhost/thread/commands/inspect": "host",
74659
75002
  "codexhost/thread/command/execute": "host",
74660
75003
  "codexhost/thread/pins/set": "host",
74661
- "codexhost/thread/sections/move": "host",
74662
75004
  "codexhost/thread/usage/inspect": "host",
74663
75005
  "codexhost/thread/inspect": "native"
74664
75006
  };
@@ -74784,7 +75126,7 @@ var ClientChannelHost = class {
74784
75126
  }
74785
75127
  };
74786
75128
  }
74787
- if (typeof params2.threadId === "string") {
75129
+ if (typeof params2.threadId === "string" && method !== "codexhost/thread/sections/move") {
74788
75130
  const location = await this.#host.locateExternalThread(params2.threadId);
74789
75131
  if (method === NATIVE_CODEX_GOAL_METHOD && location.kind !== "official")
74790
75132
  return { error: { code: -32078, message: "Goals require a local native Codex Thread" } };
@@ -74923,9 +75265,7 @@ var ClientChannelHost = class {
74923
75265
  operation
74924
75266
  ) : operation();
74925
75267
  }
74926
- /** Absolute, bounded state; capture fields and delivery cursor without yielding.
74927
- * Notifications are invalidations, not text deltas to replay over this snapshot.
74928
- */
75268
+ /** Absolute, bounded state; notifications invalidate fields rather than replaying text deltas. */
74929
75269
  async clientSnapshot(threadId2, options = {}) {
74930
75270
  const location = await this.#host.locateExternalThread(threadId2);
74931
75271
  if (location.kind === "error")
@@ -75006,6 +75346,13 @@ var ClientChannelHost = class {
75006
75346
  }
75007
75347
  if (!thread4) throw new Error("Thread is not owned by this local Host");
75008
75348
  const handoff2 = await this.#host.readThreadHandoff?.(threadId2) ?? void 0;
75349
+ const cursor = this.clientEvents.cursor;
75350
+ let placements;
75351
+ try {
75352
+ placements = await this.#host.listSectionPlacements();
75353
+ } catch {
75354
+ }
75355
+ const sectionFields = placements ? threadSectionFields(placements.find((entry) => entry.hostThreadId === threadId2)) : void 0;
75009
75356
  const interactions = [
75010
75357
  ...[...this.#host.interactions.approvals].filter(([, pending2]) => pending2.thread === thread4).map(([requestId, pending2]) => ({
75011
75358
  requestId,
@@ -75029,13 +75376,18 @@ var ClientChannelHost = class {
75029
75376
  const effectivePermissionModeId = state.effectivePermissionModeId ?? saved?.permissionModeId;
75030
75377
  const snapshot2 = clientThreadSnapshotSchema.parse(
75031
75378
  copyAsJson({
75032
- cursor: this.clientEvents.cursor,
75379
+ cursor,
75033
75380
  activeTurnId: thread4.activeTurnId,
75034
75381
  command: thread4.clientCommand ? {
75035
75382
  ...thread4.clientCommand,
75036
75383
  turn: thread4.activeTurnId && thread4.activeTurnId === thread4.clientCommand.turn.id ? thread4.projectedTurns.get(thread4.activeTurnId)?.projector.snapshotTurn() ?? thread4.clientCommand.turn : thread4.clientCommand.turn
75037
75384
  } : void 0,
75038
- thread: { ...thread4.thread, turns: [] },
75385
+ thread: {
75386
+ ...thread4.thread,
75387
+ section: sectionFields?.section,
75388
+ sectionEnteredAt: sectionFields?.sectionEnteredAt,
75389
+ turns: []
75390
+ },
75039
75391
  turnsPage: listExternalTurns(this.#host.clientHistoryTurns(thread4), {
75040
75392
  limit: 5,
75041
75393
  sortDirection: "desc",
@@ -78400,7 +78752,7 @@ var ThreadTreeWatch = class {
78400
78752
  }
78401
78753
  }
78402
78754
  const bounded3 = limitTreeEdges(parents, handoffRecords);
78403
- if (!this.options.externalOnly) {
78755
+ if (!this.options.externalOnly || onDemand) {
78404
78756
  const candidates = [...bounded3.ids].filter(
78405
78757
  (id3) => !external.has(id3) && !this.options.shared?.knowsTreeOwner(id3) && !this.#read.has(id3)
78406
78758
  );
@@ -78949,6 +79301,8 @@ var ObservedSessionUsage = class {
78949
79301
 
78950
79302
  // packages/host-runtime/src/app-server-host.ts
78951
79303
  var CONSOLE_REQUEST_TIMEOUT_MS = 12e4;
79304
+ var SECTION_RECONCILE_RETRY_MS = 100;
79305
+ var SECTION_RECONCILE_MAX_RETRY_MS = 3e4;
78952
79306
  var SUBAGENT_TERMINAL_REFRESH_DELAYS_MS = [0, 50, 100, 150];
78953
79307
  var THREAD_USAGE_UPDATED_METHOD = "codexhost/thread/usage/updated";
78954
79308
  var OFFICIAL_THINKING_LABELS = /* @__PURE__ */ new Map([
@@ -79336,6 +79690,11 @@ var AppServerHost = class {
79336
79690
  #threadTree;
79337
79691
  #treeWatch;
79338
79692
  #sectionOperations = Promise.resolve();
79693
+ #sectionReconcileTimer;
79694
+ #sectionReconcileDelay = SECTION_RECONCILE_RETRY_MS;
79695
+ #sectionDefinitions = new SectionDefinitions(PINNED_THREAD_SECTION_ID);
79696
+ /** A native move may have committed before its external anchors reached disk. */
79697
+ #pendingSectionMoves = /* @__PURE__ */ new Map();
79339
79698
  #turnProjection;
79340
79699
  /** Console requests share Desktop handling; their replies return to the console. */
79341
79700
  #consoleRequestPrefix = `codexhost-console:${randomUUID39()}:`;
@@ -79417,7 +79776,7 @@ var AppServerHost = class {
79417
79776
  environment: () => this.#options.environment ?? process.env,
79418
79777
  waitForPlugins: () => this.#waitForPlugins(),
79419
79778
  listRecords: () => this.#repository.list(),
79420
- listSectionPlacements: () => this.#repository.listSectionPlacements(),
79779
+ listSectionPlacements: async () => this.#sectionDefinitions.project(await this.#repository.listSectionPlacements()),
79421
79780
  locateExternalThread: (threadId2) => this.#locateExternalThread(threadId2),
79422
79781
  loadedThread: (threadId2) => this.#externalRuntime?.get(threadId2),
79423
79782
  readColdExternalThread: (threadId2) => this.#externalRuntime.idleRelease.runOperation(
@@ -79517,6 +79876,7 @@ var AppServerHost = class {
79517
79876
  const replaced = readyGeneration !== void 0 && readyGeneration !== owner.generation;
79518
79877
  readyGeneration = owner.generation;
79519
79878
  if (replaced) this.clientEvents.harnessInspectionChanged("codex");
79879
+ if (replaced) this.#scheduleSectionReconciliation();
79520
79880
  return;
79521
79881
  }
79522
79882
  const snapshot2 = this.#accountControl.snapshot();
@@ -79579,8 +79939,8 @@ var AppServerHost = class {
79579
79939
  externalRuntime: this.#externalRuntime,
79580
79940
  repository: this.#repository,
79581
79941
  registerExternalThread: (input3) => this.#registerExternalThread(input3),
79582
- startExternalTurn: (thread4, text5, turnId) => this.#startDelegatedExternalTurn(thread4, text5, turnId),
79583
- steerExternalTurn: (thread4, text5) => this.#steerDelegatedExternalTurn(thread4, text5),
79942
+ startExternalTurn: (thread4, text5, turnId, sourceHostId) => this.#startDelegatedExternalTurn(thread4, text5, turnId, sourceHostId),
79943
+ steerExternalTurn: (thread4, text5, sourceHostId) => this.#steerDelegatedExternalTurn(thread4, text5, sourceHostId),
79584
79944
  notifyThreadStarted: (thread4) => this.#notifyExternalThreadStarted(thread4),
79585
79945
  notifyTreeChanged: (threadId2) => this.clientEvents.changed(threadId2, "codexhost/thread/tree/changed"),
79586
79946
  readDelegationDefault: async (harnessId) => (await this.#preferences.get("external")).values.delegation?.byHarness[harnessId],
@@ -79683,6 +80043,7 @@ var AppServerHost = class {
79683
80043
  const thread4 = this.#externalRuntime.get(threadId2);
79684
80044
  return thread4 ? this.#executionHosts.get(thread4) : void 0;
79685
80045
  },
80046
+ nativeExecutionHostId: (threadId2) => this.#officialRuntimeScope.owner.executionHostId(threadId2),
79686
80047
  onThreadIdle: (listener) => {
79687
80048
  this.#threadIdleListeners.add(listener);
79688
80049
  return () => {
@@ -79829,6 +80190,7 @@ var AppServerHost = class {
79829
80190
  if (this.#closeRequested) return;
79830
80191
  this.#closeRequested = true;
79831
80192
  this.#releaseExtensionActivity();
80193
+ clearTimeout(this.#sectionReconcileTimer);
79832
80194
  if (!this.#options.hostExtensions) void this.hostExtensions?.close();
79833
80195
  this.#skills?.dispose();
79834
80196
  this.#options.sharedThreads?.close();
@@ -79976,8 +80338,13 @@ var AppServerHost = class {
79976
80338
  if (!this.#closeRequested && !this.#options.hostExtensions) void this.hostExtensions?.start();
79977
80339
  void this.#waitForPlugins().then(() => this.#attachUsageStatistics());
79978
80340
  this.#options.sharedThreads?.start((message2) => {
80341
+ if (message2.method === SHARED_SECTIONS_CHANGED_METHOD) {
80342
+ this.clientEvents.sectionsChanged();
80343
+ return;
80344
+ }
79979
80345
  void this.#writer.json(message2).catch((error62) => this.#diagnose(error62));
79980
80346
  });
80347
+ this.#scheduleSectionReconciliation();
79981
80348
  if (this.#closeRequested) await this.#closeOfficialRuntime();
79982
80349
  try {
79983
80350
  await this.#forwardDesktop();
@@ -79988,6 +80355,8 @@ var AppServerHost = class {
79988
80355
  await this.#closeOfficialRuntime();
79989
80356
  return this.#closeRequested ? 0 : 1;
79990
80357
  } finally {
80358
+ this.#desktopInputEnded = true;
80359
+ clearTimeout(this.#sectionReconcileTimer);
79991
80360
  this.#skills?.dispose();
79992
80361
  this.#treeWatch.close();
79993
80362
  this.#releaseExtensionActivity();
@@ -80329,6 +80698,7 @@ var AppServerHost = class {
80329
80698
  if (!isRecord25(response.error)) this.#observedSessionUsage.initialized(nativeParams);
80330
80699
  await this.#writer.json({ ...response, id: request.id });
80331
80700
  this.#nativeAccountObserver?.initialized(nativeGeneration);
80701
+ this.#scheduleSectionReconciliation();
80332
80702
  } catch (error62) {
80333
80703
  await this.#writer.json(rpcError(request, -32087, errorMessage3(error62)));
80334
80704
  }
@@ -80352,6 +80722,7 @@ var AppServerHost = class {
80352
80722
  );
80353
80723
  }
80354
80724
  this.#desktopInputEnded = true;
80725
+ clearTimeout(this.#sectionReconcileTimer);
80355
80726
  this.#externalRuntime.idleRelease.disable();
80356
80727
  this.#pluginLoadAbort.abort();
80357
80728
  await this.#desktopRequests.drain();
@@ -80435,6 +80806,16 @@ var AppServerHost = class {
80435
80806
  await this.#writer.json(rpcEnvelope(request, { result: jsonValueSchema.parse(result) }));
80436
80807
  return;
80437
80808
  }
80809
+ if (request.method === THREAD_REFERENCE_CONTEXT_CAPABILITY_METHOD) {
80810
+ await this.#writer.json(
80811
+ rpcEnvelope(request, {
80812
+ result: {
80813
+ threadReferenceContext: this.#officialRuntimeScope.owner.supportsThreadReferenceContext
80814
+ }
80815
+ })
80816
+ );
80817
+ return;
80818
+ }
80438
80819
  if (request.method === DELEGATION_READ_METHOD) {
80439
80820
  const parsed2 = delegationReadParamsSchema.safeParse(request.params);
80440
80821
  if (!parsed2.success) {
@@ -80460,17 +80841,93 @@ var AppServerHost = class {
80460
80841
  this.#dispatchDesktopReply(request, () => this.#readThreadCatalog(request));
80461
80842
  return;
80462
80843
  }
80844
+ if (request.method === SHARED_THREAD_LIST_METHOD || request.method === SHARED_THREAD_OWNERSHIP_METHOD) {
80845
+ if (!this.#options.externalOnly) {
80846
+ await this.#writer.json(rpcError(request, -32601, "Not a shared Thread Host"));
80847
+ return;
80848
+ }
80849
+ this.#dispatchDesktopReply(request, async () => {
80850
+ if (request.method === SHARED_THREAD_OWNERSHIP_METHOD) {
80851
+ await this.#listThreadOwnership(request, true);
80852
+ return;
80853
+ }
80854
+ let query;
80855
+ try {
80856
+ query = decodeThreadListRequest({
80857
+ id: request.id,
80858
+ method: "thread/list",
80859
+ params: requestObject(request)
80860
+ });
80861
+ if (!query?.supportsExternal || query.sortKey === "section_position")
80862
+ throw new Error("Invalid shared Thread list query");
80863
+ } catch (error62) {
80864
+ await this.#writer.json(rpcError(request, -32602, errorMessage3(error62)));
80865
+ return;
80866
+ }
80867
+ await this.#listThreads(request, query, origin, true);
80868
+ });
80869
+ return;
80870
+ }
80463
80871
  if (this.#options.externalOnly && request.method === "codexhost/shared-threads/placements") {
80872
+ if (requestObject(request).requireComplete === true) {
80873
+ try {
80874
+ const [local, shared] = await Promise.all([
80875
+ this.#repository.listSectionPlacements(),
80876
+ this.#options.sharedThreads?.placements(true) ?? []
80877
+ ]);
80878
+ await this.#writer.json(
80879
+ rpcEnvelope(request, {
80880
+ result: { placements: jsonValueSchema.parse([...local, ...shared]) }
80881
+ })
80882
+ );
80883
+ } catch (error62) {
80884
+ this.#diagnose(error62);
80885
+ await this.#writer.json(
80886
+ rpcError(request, -32078, "Complete section placements are unavailable")
80887
+ );
80888
+ }
80889
+ return;
80890
+ }
80464
80891
  await this.#writer.json(
80465
80892
  rpcEnvelope(request, {
80466
- result: jsonValueSchema.parse(await this.#repository.listSectionPlacements())
80893
+ result: jsonValueSchema.parse(
80894
+ this.#sectionDefinitions.project(await this.#repository.listSectionPlacements())
80895
+ )
80467
80896
  })
80468
80897
  );
80469
80898
  return;
80470
80899
  }
80900
+ if (this.#options.externalOnly && request.method === SHARED_SECTIONS_RECONCILE_METHOD) {
80901
+ await this.#runSectionOperation(async () => {
80902
+ const syncPending = await this.#reconcileSectionPlacements({
80903
+ readOnly: requestObject(request).readOnly === true,
80904
+ refreshEmpty: true
80905
+ });
80906
+ await this.#publishSectionsChanged();
80907
+ await this.#writer.json(rpcEnvelope(request, { result: { syncPending } }));
80908
+ });
80909
+ return;
80910
+ }
80911
+ const sectionMethod = request.method;
80912
+ const sectionOperation = sectionMethod.startsWith("threadSection/") ? sectionMethod.slice("threadSection/".length) : sectionMethod.startsWith("codexhost/thread/sections/") ? sectionMethod.slice("codexhost/thread/sections/".length) : void 0;
80913
+ if (sectionOperation === "create" || sectionOperation === "update" || sectionOperation === "delete") {
80914
+ this.#dispatchDesktopReply(
80915
+ request,
80916
+ () => this.#handleSectionMutation(request, sectionOperation)
80917
+ );
80918
+ return;
80919
+ }
80920
+ if (sectionMethod === "codexhost/thread/sections/move") {
80921
+ this.#dispatchDesktopReply(request, () => this.#handleCustomSectionMove(request));
80922
+ return;
80923
+ }
80471
80924
  if (this.#options.sharedThreads && (request.method.startsWith("thread/") || request.method.startsWith("turn/") || request.method.startsWith("codexhost/thread/") || request.method.startsWith("codexhost/harness/") || this.#options.sharedThreads.handlesControl(request.method))) {
80472
80925
  try {
80473
- const reply2 = await this.#options.sharedThreads.route(request);
80926
+ const shared = this.#options.sharedThreads;
80927
+ const ownerMove = !this.#options.externalOnly && shared.options.delegateCreates && (request.method === "thread/section/move" || request.method === "codexhost/thread/pins/set");
80928
+ const reply2 = ownerMove ? await shared.routeSectionWrite(request, async (threadId2) => {
80929
+ return (await this.#locateExternalThread(threadId2)).kind === "official" && await this.#hasLocalNativeThread(threadId2);
80930
+ }) : await shared.route(request);
80474
80931
  if (reply2) {
80475
80932
  await this.#writer.json(reply2);
80476
80933
  return;
@@ -80535,77 +80992,77 @@ var AppServerHost = class {
80535
80992
  this.#dispatchDesktopReply(request, () => this.#handleThreadPins(request));
80536
80993
  return;
80537
80994
  }
80538
- if (request.method === "codexhost/thread/sections/move") {
80539
- const move = clientThreadSectionMoveSchema.safeParse(request.params);
80540
- if (!move.success || move.data.sectionId === PINNED_THREAD_SECTION_ID) {
80541
- await this.#writer.json(rpcError(request, -32602, "Invalid custom Thread section move"));
80542
- return;
80543
- }
80544
- const params2 = { ...move.data, beforeThreadId: null };
80545
- this.#dispatchDesktopReply(
80546
- request,
80547
- () => this.#runSectionOperation(async () => {
80548
- const location = await this.#locateExternalThread(params2.threadId);
80549
- if (await this.#writeResolutionError(request, location)) return;
80550
- if (location.kind !== "official") {
80551
- await this.#writer.json(
80552
- rpcError(
80553
- request,
80554
- -32078,
80555
- "Only native Codex Threads can change custom sections in Web"
80556
- )
80557
- );
80558
- return;
80559
- }
80560
- const current2 = await this.#requestOfficial("thread/read", {
80561
- threadId: params2.threadId,
80562
- includeTurns: false
80995
+ if (request.method === "codexhost/thread/sections/list") {
80996
+ this.#dispatchDesktopReply(request, async () => {
80997
+ try {
80998
+ const requestOfficial = (method, params3) => this.#requestOfficial(method, params3);
80999
+ const definitions = await this.#runSectionOperation(async () => {
81000
+ const definitions2 = await this.#readSectionDefinitions();
81001
+ this.#sectionDefinitions.replace(definitions2);
81002
+ return definitions2;
80563
81003
  });
80564
- const thread4 = current2.result?.thread;
80565
- if (!isRecord25(thread4) || thread4.id !== params2.threadId || thread4.archived === true || typeof thread4.parentThreadId === "string" || isRecord25(thread4.section) && thread4.section.id === PINNED_THREAD_SECTION_ID) {
80566
- await this.#writer.json(
80567
- rpcError(request, -32078, "An active, unpinned Codex Thread is required")
80568
- );
80569
- return;
80570
- }
80571
- const sectionId = isRecord25(thread4.section) ? thread4.section.id ?? null : null;
80572
- if (sectionId === params2.sectionId) {
80573
- await this.#writer.json(rpcEnvelope(request, { result: {} }));
81004
+ const params2 = isRecord25(request.params) ? request.params : {};
81005
+ const supportsSections = params2[THREAD_SECTION_CAPABILITY] === true;
81006
+ const requireComplete = params2.requireComplete === true;
81007
+ const capability = supportsSections ? { [THREAD_SECTION_CAPABILITY]: true } : {};
81008
+ const sections = [...definitions.values()].filter((section) => section.id !== PINNED_THREAD_SECTION_ID).map(
81009
+ (section) => supportsSections ? section : { id: section.id, name: section.name }
81010
+ );
81011
+ if (sections.length === 0) {
81012
+ await this.#writer.json(rpcEnvelope(request, { result: { ...capability, sections } }));
80574
81013
  return;
80575
81014
  }
80576
- await this.#moveThreadSection(
80577
- {
80578
- id: request.id,
80579
- ...request.jsonrpc ? { jsonrpc: request.jsonrpc } : {},
80580
- method: "thread/section/move",
80581
- params: params2
80582
- },
80583
- params2
81015
+ const query = decodeThreadListRequest({
81016
+ id: request.id,
81017
+ method: "thread/list",
81018
+ params: { archived: false, sortKey: "updated_at", sortDirection: "desc" }
81019
+ });
81020
+ if (!query) throw new Error("Section Thread list query could not be decoded");
81021
+ const { placements, externalRows, complete } = await this.#sectionThreadCatalog(
81022
+ query,
81023
+ requireComplete ? "complete" : "native-fallback",
81024
+ definitions
80584
81025
  );
80585
- })
80586
- );
80587
- return;
80588
- }
80589
- if (request.method === "codexhost/thread/sections/list") {
80590
- this.#dispatchDesktopReply(request, async () => {
80591
- try {
80592
- const requestOfficial = (method, params2) => this.#requestOfficial(method, params2);
80593
- const sections = [];
80594
- for await (const { id: id3, name } of officialThreadSections(requestOfficial)) {
80595
- if (id3 !== PINNED_THREAD_SECTION_ID && name) sections.push({ id: id3, name });
81026
+ const placementsBySection = /* @__PURE__ */ new Map();
81027
+ for (const placement of placements) {
81028
+ const inSection = placementsBySection.get(placement.section.id);
81029
+ if (inSection) inSection.push(placement);
81030
+ else placementsBySection.set(placement.section.id, [placement]);
80596
81031
  }
80597
81032
  const sectionRows = await Promise.all(
80598
- sections.map(async (section) => ({
80599
- ...section,
80600
- threads: await listAllOfficialRows(requestOfficial, {
80601
- sectionId: section.id,
80602
- sortKey: "section_position",
80603
- modelProviders: [],
80604
- useStateDbOnly: true
80605
- })
80606
- }))
81033
+ sections.map(async (section) => {
81034
+ const officialRows = await listAllOfficialRows(
81035
+ requestOfficial,
81036
+ {
81037
+ sectionId: section.id,
81038
+ sortDirection: "asc",
81039
+ sortKey: "section_position",
81040
+ modelProviders: [],
81041
+ useStateDbOnly: true
81042
+ },
81043
+ true
81044
+ );
81045
+ const inSection = placementsBySection.get(section.id);
81046
+ if (!inSection) return { ...section, threads: officialRows };
81047
+ const rows = new Map(officialRows.map((row) => [String(row.id), row]));
81048
+ const order = mergeSectionOrder([...rows.keys()], inSection);
81049
+ for (const { hostThreadId } of inSection) {
81050
+ const row = externalRows.get(hostThreadId);
81051
+ if (row) rows.set(hostThreadId, row);
81052
+ else rows.delete(hostThreadId);
81053
+ }
81054
+ return { ...section, threads: order.flatMap((id3) => rows.get(id3) ?? []) };
81055
+ })
81056
+ );
81057
+ await this.#writer.json(
81058
+ rpcEnvelope(request, {
81059
+ result: {
81060
+ ...capability,
81061
+ ...supportsSections && !complete ? { complete } : {},
81062
+ sections: sectionRows
81063
+ }
81064
+ })
80607
81065
  );
80608
- await this.#writer.json(rpcEnvelope(request, { result: { sections: sectionRows } }));
80609
81066
  } catch (error62) {
80610
81067
  this.#diagnose(error62);
80611
81068
  await this.#writer.json(
@@ -80981,10 +81438,13 @@ var AppServerHost = class {
80981
81438
  if (this.#externalRuntime.get(threadId2)) return true;
80982
81439
  const parsed2 = hostThreadIdSchema.safeParse(threadId2);
80983
81440
  if (parsed2.success && await this.#repository.find(parsed2.data) !== null) return true;
81441
+ return this.#hasLocalNativeThread(threadId2);
81442
+ }
81443
+ async #hasLocalNativeThread(threadId2) {
80984
81444
  try {
80985
81445
  const reply2 = await this.#requestOfficial("thread/read", { threadId: threadId2, includeTurns: false });
80986
81446
  const thread4 = isRecord25(reply2.result) ? reply2.result.thread : void 0;
80987
- return isRecord25(thread4) && thread4.id === threadId2;
81447
+ return !reply2.error && isRecord25(thread4) && thread4.id === threadId2;
80988
81448
  } catch {
80989
81449
  return false;
80990
81450
  }
@@ -81189,6 +81649,7 @@ var AppServerHost = class {
81189
81649
  const turn = await this.#requestOfficial("turn/start", {
81190
81650
  threadId: threadId2,
81191
81651
  input: [{ type: "text", text: input3.task }],
81652
+ ...input3.sourceHostId ? { [THREAD_REFERENCE_SOURCE_HOST_PARAM]: input3.sourceHostId } : {},
81192
81653
  ...nativeSelection,
81193
81654
  ...thinkingOptionId ? { effort: thinkingOptionId } : {}
81194
81655
  });
@@ -81266,6 +81727,11 @@ var AppServerHost = class {
81266
81727
  throw new DelegationControlError("INTERNAL_ERROR", "Official Thread read returned no result");
81267
81728
  }
81268
81729
  const currentThread = isRecord25(current2.result.thread) ? current2.result.thread : null;
81730
+ const turnInput = {
81731
+ threadId: input3.threadId,
81732
+ input: [{ type: "text", text: input3.message }],
81733
+ ...input3.sourceHostId ? { [THREAD_REFERENCE_SOURCE_HOST_PARAM]: input3.sourceHostId } : {}
81734
+ };
81269
81735
  if (officialThreadBusy(currentThread)) {
81270
81736
  const latestTurn = currentThread && Array.isArray(currentThread.turns) ? currentThread.turns.at(-1) : null;
81271
81737
  const turnId2 = isRecord25(latestTurn) && typeof latestTurn.id === "string" && (latestTurn.status === "inProgress" || latestTurn.status === "running") ? latestTurn.id : this.#activeOfficialTurnId(input3.threadId);
@@ -81273,9 +81739,8 @@ var AppServerHost = class {
81273
81739
  throw new DelegationControlError("THREAD_BUSY", "Thread already has an active Turn");
81274
81740
  }
81275
81741
  const response2 = await this.#requestOfficial("turn/steer", {
81276
- threadId: input3.threadId,
81277
- expectedTurnId: turnId2,
81278
- input: [{ type: "text", text: input3.message }]
81742
+ ...turnInput,
81743
+ expectedTurnId: turnId2
81279
81744
  });
81280
81745
  if (isRecord25(response2.error)) {
81281
81746
  throw new DelegationControlError(
@@ -81318,10 +81783,7 @@ var AppServerHost = class {
81318
81783
  { notStarted: true }
81319
81784
  );
81320
81785
  }
81321
- const response = await this.#requestOfficial("turn/start", {
81322
- threadId: input3.threadId,
81323
- input: [{ type: "text", text: input3.message }]
81324
- });
81786
+ const response = await this.#requestOfficial("turn/start", turnInput);
81325
81787
  if (isRecord25(response.error)) {
81326
81788
  throw new DelegationControlError(
81327
81789
  "DELEGATION_FAILED",
@@ -81620,13 +82082,13 @@ var AppServerHost = class {
81620
82082
  );
81621
82083
  }
81622
82084
  }
81623
- async #listThreads(request, listRequest, origin) {
82085
+ async #listThreads(request, listRequest, origin, requireComplete = false) {
81624
82086
  const timing = new ThreadListTiming();
81625
82087
  let ok = false;
81626
82088
  try {
81627
82089
  const { records, placements, officialImportTimes } = await timing.measure(
81628
82090
  "store",
81629
- () => this.#localThreadCatalog()
82091
+ () => this.#localThreadCatalog(requireComplete)
81630
82092
  );
81631
82093
  timing.counts.mappingRecords = records.length;
81632
82094
  timing.counts.placements = placements.length;
@@ -81634,7 +82096,10 @@ var AppServerHost = class {
81634
82096
  placements.map((entry) => [entry.hostThreadId, entry])
81635
82097
  );
81636
82098
  const sharedCatalog = this.#options.sharedThreads;
81637
- const sharedThreads = sharedCatalog ? await timing.measure("shared_catalog", () => sharedCatalog.list(listRequest.params)) : void 0;
82099
+ const sharedThreads = sharedCatalog ? await timing.measure(
82100
+ "shared_catalog",
82101
+ () => sharedCatalog.list(listRequest.params, { requireComplete })
82102
+ ) : void 0;
81638
82103
  timing.counts.sharedRows = sharedThreads?.length ?? 0;
81639
82104
  const result = await timing.measure(
81640
82105
  "aggregate",
@@ -81647,7 +82112,7 @@ var AppServerHost = class {
81647
82112
  runtimeFor: (threadId2) => this.#listRuntimeState(threadId2),
81648
82113
  placementOf: (threadId2) => placementById.get(threadId2),
81649
82114
  requestOfficialPage: async (params2) => {
81650
- if (this.#options.externalOnly && origin !== "client")
82115
+ if (requireComplete || this.#options.externalOnly && origin !== "client")
81651
82116
  return { data: [], nextCursor: null, backwardsCursor: null };
81652
82117
  let official;
81653
82118
  try {
@@ -81666,7 +82131,9 @@ var AppServerHost = class {
81666
82131
  })
81667
82132
  );
81668
82133
  timing.counts.returnedRows = result.data.length;
81669
- await this.#writer.json(rpcEnvelope(request, { result }));
82134
+ await this.#writer.json(
82135
+ rpcEnvelope(request, { result: requireComplete ? { ...result, complete: true } : result })
82136
+ );
81670
82137
  ok = true;
81671
82138
  } catch (error62) {
81672
82139
  if (error62 instanceof OfficialThreadListError) {
@@ -81680,13 +82147,12 @@ var AppServerHost = class {
81680
82147
  timing.report(request.id, listRequest, ok, (line) => this.#diagnose(line));
81681
82148
  }
81682
82149
  }
81683
- /**
81684
- * Local records and placements, minus Threads the shared Host owns. A viewer's Mapping Store can
81685
- * keep a copy from before the Thread was shared; the shared Host's row is canonical even when
81686
- * the current query excludes it (archived, moved out of a section).
81687
- */
81688
- async #localThreadCatalog() {
81689
- const [records, placements] = await Promise.all([
82150
+ async #localThreadCatalog(requireComplete = false) {
82151
+ const local = await this.#readLocalThreadCatalog();
82152
+ return this.#excludeSharedThreadCopies(local, requireComplete);
82153
+ }
82154
+ async #readLocalThreadCatalog(rawPlacements = false) {
82155
+ const [records, storedPlacements] = await Promise.all([
81690
82156
  this.#repository.listSummaries(),
81691
82157
  this.#repository.listSectionPlacements()
81692
82158
  ]);
@@ -81694,26 +82160,37 @@ var AppServerHost = class {
81694
82160
  this.#officialRuntimeScope.permanentHome,
81695
82161
  records
81696
82162
  );
82163
+ const placements = rawPlacements ? storedPlacements : this.#sectionDefinitions.project(storedPlacements);
82164
+ return { records, placements, officialImportTimes };
82165
+ }
82166
+ /**
82167
+ * The shared Host owns the canonical row even when the query excludes it.
82168
+ * A viewer's Mapping Store can still hold a copy from before sharing.
82169
+ */
82170
+ async #excludeSharedThreadCopies(local, requireComplete) {
81697
82171
  const shared = this.#options.sharedThreads;
81698
- if (!shared) return { records, placements, officialImportTimes };
82172
+ if (!shared) return local;
82173
+ const { records, placements } = local;
81699
82174
  const ids = [...new Set([...records, ...placements].map((entry) => entry.hostThreadId))];
81700
82175
  const sharedOwners = /* @__PURE__ */ new Map();
81701
82176
  try {
81702
82177
  for (let offset = 0; offset < ids.length; offset += THREAD_OWNERSHIP_LIST_MAX_LENGTH) {
81703
82178
  const owners = await shared.ownership(
81704
- ids.slice(offset, offset + THREAD_OWNERSHIP_LIST_MAX_LENGTH)
82179
+ ids.slice(offset, offset + THREAD_OWNERSHIP_LIST_MAX_LENGTH),
82180
+ requireComplete
81705
82181
  );
81706
82182
  for (const [id3, harnessId] of owners) sharedOwners.set(id3, harnessId);
81707
82183
  }
81708
82184
  } catch (error62) {
82185
+ if (requireComplete) throw error62;
81709
82186
  this.#diagnose(error62);
81710
- return { records, placements, officialImportTimes };
82187
+ return local;
81711
82188
  }
81712
- if (sharedOwners.size === 0) return { records, placements, officialImportTimes };
82189
+ if (sharedOwners.size === 0) return local;
81713
82190
  return {
81714
82191
  records: records.filter((record7) => !sharedOwners.has(record7.hostThreadId)),
81715
82192
  placements: placements.filter((placement) => !sharedOwners.has(placement.hostThreadId)),
81716
- officialImportTimes,
82193
+ officialImportTimes: local.officialImportTimes,
81717
82194
  sharedOwners
81718
82195
  };
81719
82196
  }
@@ -81726,37 +82203,57 @@ var AppServerHost = class {
81726
82203
  hasSubmittedTurn: !thread4.unsubmittedPrewarm && (thread4.activeTurnId !== null || thread4.projectedTerminalTurnId !== null)
81727
82204
  } : null;
81728
82205
  }
82206
+ async #sectionThreadCatalog(query, mode, definitions) {
82207
+ const shared = this.#options.sharedThreads;
82208
+ let local = await this.#readLocalThreadCatalog(true);
82209
+ let sharedPlacements = [];
82210
+ let sharedThreads = [];
82211
+ if (shared) {
82212
+ const requireComplete = mode !== "best-effort";
82213
+ try {
82214
+ [local, sharedPlacements, sharedThreads] = await Promise.all([
82215
+ this.#excludeSharedThreadCopies(local, requireComplete),
82216
+ shared.placements(true),
82217
+ shared.list(query.params, { requireComplete })
82218
+ ]);
82219
+ } catch (error62) {
82220
+ if (mode === "complete") throw error62;
82221
+ this.#diagnose(error62);
82222
+ return { placements: [], externalRows: /* @__PURE__ */ new Map(), complete: false };
82223
+ }
82224
+ }
82225
+ const { records, placements: localPlacements } = local;
82226
+ const placementById = /* @__PURE__ */ new Map();
82227
+ for (const placement of localPlacements) placementById.set(placement.hostThreadId, placement);
82228
+ for (const placement of sharedPlacements) placementById.set(placement.hostThreadId, placement);
82229
+ const placements = await this.#projectSectionPlacements(
82230
+ [...placementById.values()],
82231
+ definitions
82232
+ );
82233
+ placementById.clear();
82234
+ for (const placement of placements) placementById.set(placement.hostThreadId, placement);
82235
+ const externalRows = new Map(
82236
+ externalThreadListEntries({
82237
+ records,
82238
+ query,
82239
+ runtimeFor: (threadId2) => this.#listRuntimeState(threadId2),
82240
+ placementOf: (threadId2) => placementById.get(threadId2)
82241
+ }).map((entry) => [String(entry.thread.id), entry.thread])
82242
+ );
82243
+ for (const thread4 of sharedThreads) {
82244
+ const id3 = String(thread4.id);
82245
+ externalRows.set(id3, { ...thread4, ...threadSectionFields(placementById.get(id3)) });
82246
+ }
82247
+ return { placements, externalRows };
82248
+ }
81729
82249
  /** `section_position` lists merge External section placements into the official order. */
81730
82250
  async #listSectionThreads(request, frame, query) {
81731
82251
  try {
81732
- const [{ records, placements: localPlacements }, sharedPlacements, sharedThreads] = await Promise.all([
81733
- this.#localThreadCatalog(),
81734
- this.#options.sharedThreads?.placements() ?? [],
81735
- this.#options.sharedThreads?.list(query.params) ?? []
81736
- ]);
81737
- const sharedIds = new Set(sharedPlacements.map((p) => p.hostThreadId));
81738
- const placements = [
81739
- ...localPlacements.filter((p) => !sharedIds.has(p.hostThreadId)),
81740
- ...sharedPlacements
81741
- ];
81742
- const placementById = new Map(
81743
- placements.map((entry) => [entry.hostThreadId, entry])
81744
- );
81745
- const externalRows = new Map(
81746
- externalThreadListEntries({
81747
- records,
81748
- query,
81749
- runtimeFor: (threadId2) => this.#listRuntimeState(threadId2),
81750
- placementOf: (threadId2) => placementById.get(threadId2)
81751
- }).map((entry) => [String(entry.thread.id), entry.thread])
81752
- );
82252
+ const { placements, externalRows } = await this.#sectionThreadCatalog(query, "best-effort");
81753
82253
  const page = await listSectionThreads({
81754
82254
  query,
81755
82255
  placements,
81756
- externalRows: new Map([
81757
- ...externalRows,
81758
- ...sharedThreads.map((thread4) => [String(thread4.id), thread4])
81759
- ]),
82256
+ externalRows,
81760
82257
  requestOfficial: (method, params2) => this.#requestOfficial(method, params2)
81761
82258
  });
81762
82259
  if (!page) {
@@ -81778,6 +82275,187 @@ var AppServerHost = class {
81778
82275
  this.#sectionOperations = next.catch(() => void 0);
81779
82276
  return next;
81780
82277
  }
82278
+ async #readSectionDefinitions() {
82279
+ let generation;
82280
+ const definitions = /* @__PURE__ */ new Map();
82281
+ const owner = this.#officialRuntimeScope.owner;
82282
+ for await (const section of officialThreadSections(async (method, params2) => {
82283
+ const response = await this.#requestOfficial(method, params2);
82284
+ generation ??= owner.generation;
82285
+ if (generation !== owner.generation)
82286
+ throw new Error("Official generation changed while listing Thread sections");
82287
+ return response;
82288
+ }))
82289
+ definitions.set(section.id, section);
82290
+ return definitions;
82291
+ }
82292
+ async #projectSectionPlacements(placements, definitions) {
82293
+ if (!placements.some(({ section }) => section.id !== PINNED_THREAD_SECTION_ID))
82294
+ return placements;
82295
+ if (!definitions) {
82296
+ try {
82297
+ definitions = await this.#readSectionDefinitions();
82298
+ } catch {
82299
+ return this.#sectionDefinitions.project(placements);
82300
+ }
82301
+ }
82302
+ return this.#sectionDefinitions.project(placements, definitions);
82303
+ }
82304
+ #scheduleSectionReconciliation() {
82305
+ if (this.#closeRequested || this.#desktopInputEnded || !this.#options.externalOnly && this.#options.sharedThreads?.options.delegateCreates)
82306
+ return;
82307
+ this.#dispatchDesktopRequest(
82308
+ () => this.#desktopRequests.run(
82309
+ void 0,
82310
+ () => this.#runSectionOperation(async () => {
82311
+ await this.#reconcileSectionPlacements({ notifyClients: true });
82312
+ })
82313
+ )
82314
+ );
82315
+ }
82316
+ #updateSectionReconcileRetry(pending2) {
82317
+ if (!pending2) {
82318
+ clearTimeout(this.#sectionReconcileTimer);
82319
+ this.#sectionReconcileTimer = void 0;
82320
+ this.#sectionReconcileDelay = SECTION_RECONCILE_RETRY_MS;
82321
+ } else if (!this.#sectionReconcileTimer && !this.#closeRequested && !this.#desktopInputEnded) {
82322
+ this.#sectionReconcileTimer = setTimeout(() => {
82323
+ this.#sectionReconcileTimer = void 0;
82324
+ this.#scheduleSectionReconciliation();
82325
+ }, this.#sectionReconcileDelay);
82326
+ this.#sectionReconcileTimer.unref();
82327
+ this.#sectionReconcileDelay = Math.min(
82328
+ this.#sectionReconcileDelay * 2,
82329
+ SECTION_RECONCILE_MAX_RETRY_MS
82330
+ );
82331
+ }
82332
+ }
82333
+ /** Runs on the MappingStore owner, inside the same serial boundary as moves. */
82334
+ async #reconcileSectionPlacements({
82335
+ readOnly = false,
82336
+ refreshEmpty = false,
82337
+ confirmed,
82338
+ notifyClients = false
82339
+ } = {}) {
82340
+ let placements;
82341
+ let previous;
82342
+ let projected;
82343
+ let pending2 = false;
82344
+ try {
82345
+ placements = await this.#repository.listSectionPlacements();
82346
+ if (!refreshEmpty && !confirmed && !placements.some(({ section }) => section.id !== PINNED_THREAD_SECTION_ID))
82347
+ return false;
82348
+ previous = this.#sectionDefinitions.project(placements);
82349
+ if (confirmed) this.#sectionDefinitions.confirm(confirmed.id, confirmed.section);
82350
+ const definitions = await this.#readSectionDefinitions();
82351
+ this.#sectionDefinitions.replace(definitions);
82352
+ projected = this.#sectionDefinitions.project(placements);
82353
+ if (!readOnly && projected !== placements)
82354
+ await this.#repository.replaceSectionPlacements(projected);
82355
+ return false;
82356
+ } catch (error62) {
82357
+ this.#diagnose(error62);
82358
+ if (!placements && confirmed)
82359
+ this.#sectionDefinitions.confirm(confirmed.id, confirmed.section);
82360
+ if (placements) projected ??= this.#sectionDefinitions.project(placements);
82361
+ pending2 = !placements || placements.some(({ section }) => section.id !== PINNED_THREAD_SECTION_ID);
82362
+ return pending2;
82363
+ } finally {
82364
+ if (!readOnly) this.#updateSectionReconcileRetry(pending2);
82365
+ if (notifyClients && previous && projected && !sameProjectedSections(previous, projected)) {
82366
+ await this.#publishSectionsChanged();
82367
+ }
82368
+ }
82369
+ }
82370
+ async #publishSectionsChanged() {
82371
+ this.clientEvents.sectionsChanged();
82372
+ if (this.#options.externalOnly) {
82373
+ await this.#writer.json({ method: SHARED_SECTIONS_CHANGED_METHOD, params: {} }).catch((error62) => this.#diagnose(error62));
82374
+ }
82375
+ }
82376
+ async #handleSectionMutation(request, operation) {
82377
+ const contract = CLIENT_THREAD_SECTION_MUTATIONS[operation];
82378
+ const native = request.method !== contract.method;
82379
+ const raw = requestObject(request);
82380
+ const parsed2 = native ? void 0 : contract.params.safeParse(raw);
82381
+ if (parsed2?.success === false || raw.sectionId === PINNED_THREAD_SECTION_ID) {
82382
+ await this.#writer.json(rpcError(request, -32602, "Invalid custom Thread section change"));
82383
+ return;
82384
+ }
82385
+ const params2 = parsed2?.data ?? raw;
82386
+ const shared = this.#options.externalOnly ? void 0 : this.#options.sharedThreads;
82387
+ if (shared?.options.delegateCreates) {
82388
+ try {
82389
+ const reply2 = await shared.request(request.method, params2);
82390
+ await this.#writer.json(rpcEnvelope(request, { ...reply2, id: request.id }));
82391
+ } catch (error62) {
82392
+ this.#diagnose(error62);
82393
+ try {
82394
+ this.#sectionDefinitions.replace(await this.#readSectionDefinitions());
82395
+ } catch (refreshError) {
82396
+ this.#diagnose(refreshError);
82397
+ }
82398
+ await this.#publishSectionsChanged();
82399
+ await this.#writeUnknownSectionMutation(request, native);
82400
+ }
82401
+ return;
82402
+ }
82403
+ await this.#runSectionOperation(async () => {
82404
+ let reply2;
82405
+ try {
82406
+ reply2 = await this.#requestOfficial(`threadSection/${operation}`, params2);
82407
+ } catch (error62) {
82408
+ this.#diagnose(error62);
82409
+ }
82410
+ if (reply2 && !Object.hasOwn(reply2, "result") && jsonRpcErrorSchema.safeParse(reply2.error).success) {
82411
+ await this.#writer.json(rpcEnvelope(request, { ...reply2, id: request.id }));
82412
+ return;
82413
+ }
82414
+ const section = operation === "delete" || !isRecord25(reply2?.result) ? null : officialSectionDefinition(reply2.result.section);
82415
+ const sectionId = operation === "create" ? section?.id : raw.sectionId;
82416
+ if (!reply2 || Object.hasOwn(reply2, "error") || !isRecord25(reply2.result) || typeof sectionId !== "string" || !sectionId || sectionId === PINNED_THREAD_SECTION_ID || operation !== "delete" && section?.id !== sectionId) {
82417
+ await this.#reconcileSectionPlacements({ refreshEmpty: true });
82418
+ if (shared) await this.#refreshSharedSectionPlacements(shared);
82419
+ await this.#publishSectionsChanged();
82420
+ await this.#writeUnknownSectionMutation(request, native);
82421
+ return;
82422
+ }
82423
+ let syncPending = await this.#reconcileSectionPlacements({
82424
+ confirmed: { id: sectionId, section }
82425
+ });
82426
+ await this.#publishSectionsChanged();
82427
+ if (shared) {
82428
+ syncPending = await this.#refreshSharedSectionPlacements(shared) || syncPending;
82429
+ }
82430
+ const result = {
82431
+ status: "confirmed",
82432
+ sectionId,
82433
+ section,
82434
+ syncPending
82435
+ };
82436
+ await this.#writer.json(
82437
+ rpcEnvelope(request, native ? { ...reply2, id: request.id } : { result })
82438
+ );
82439
+ });
82440
+ }
82441
+ async #refreshSharedSectionPlacements(shared) {
82442
+ try {
82443
+ const reply2 = await shared.request(SHARED_SECTIONS_RECONCILE_METHOD, {});
82444
+ return reply2.error !== void 0 || !isRecord25(reply2.result) || reply2.result.syncPending !== false;
82445
+ } catch (error62) {
82446
+ this.#diagnose(error62);
82447
+ return true;
82448
+ }
82449
+ }
82450
+ #writeUnknownSectionMutation(request, native) {
82451
+ return this.#writer.json(
82452
+ native ? rpcError(
82453
+ request,
82454
+ -32093,
82455
+ "Native section change outcome is unknown; do not retry automatically"
82456
+ ) : rpcEnvelope(request, { result: { status: "unknown" } })
82457
+ );
82458
+ }
81781
82459
  async #handleThreadPins(request) {
81782
82460
  const change = request.method === "codexhost/thread/pins/set" ? clientThreadPinParamsSchema.safeParse(request.params) : void 0;
81783
82461
  if (change && !change.success) {
@@ -81797,42 +82475,242 @@ var AppServerHost = class {
81797
82475
  await this.#writer.json(rpcError(request, -32081, errorMessage3(error62)));
81798
82476
  }
81799
82477
  }
81800
- async #moveThreadSection(request, move) {
82478
+ async #handleCustomSectionMove(request) {
82479
+ const parsed2 = clientThreadSectionMoveSchema.safeParse(request.params);
82480
+ if (!parsed2.success || parsed2.data.sectionId === PINNED_THREAD_SECTION_ID) {
82481
+ await this.#writer.json(rpcError(request, -32602, "Invalid custom Thread section move"));
82482
+ return;
82483
+ }
82484
+ const { threadId: threadId2, sectionId, beforeThreadId, expectedSourceSectionId } = parsed2.data;
82485
+ if (typeof beforeThreadId === "string" && (sectionId === null || beforeThreadId === threadId2)) {
82486
+ await this.#writer.json(rpcError(request, -32602, "Invalid Thread section anchor"));
82487
+ return;
82488
+ }
82489
+ const shared = this.#options.sharedThreads;
82490
+ if (shared?.options.delegateCreates && !this.#options.externalOnly) {
82491
+ try {
82492
+ const reply2 = await shared.request(request.method, {
82493
+ threadId: threadId2,
82494
+ sectionId,
82495
+ ...beforeThreadId === void 0 ? {} : { beforeThreadId },
82496
+ ...expectedSourceSectionId === void 0 ? {} : { expectedSourceSectionId }
82497
+ });
82498
+ await this.#writer.json(rpcEnvelope(request, { ...reply2, id: request.id }));
82499
+ } catch (error62) {
82500
+ await this.#writer.json(rpcError(request, -32090, errorMessage3(error62)));
82501
+ }
82502
+ return;
82503
+ }
82504
+ await this.#runSectionOperation(async () => {
82505
+ const ownerError = rpcError(
82506
+ request,
82507
+ -32078,
82508
+ "Complete Thread section order is unavailable across owners"
82509
+ );
82510
+ const readParams = { threadId: threadId2, includeTurns: false };
82511
+ let remote;
82512
+ try {
82513
+ remote = await shared?.route({ id: request.id, method: "thread/read", params: readParams });
82514
+ } catch (error62) {
82515
+ this.#diagnose(error62);
82516
+ await this.#writer.json(ownerError);
82517
+ return;
82518
+ }
82519
+ const location = remote ? void 0 : await this.#locateExternalThread(threadId2);
82520
+ if (location && await this.#writeResolutionError(request, location)) return;
82521
+ const movingExternal = location?.kind === "external";
82522
+ let placements;
82523
+ let destination;
82524
+ let currentSectionId;
82525
+ if (movingExternal) {
82526
+ const { record: record7 } = location;
82527
+ placements = await this.#repository.listSectionPlacements();
82528
+ const placement = placements.find((entry) => entry.hostThreadId === threadId2);
82529
+ currentSectionId = placement?.section.id ?? null;
82530
+ if (record7.archived || record7.subagent !== void 0 || record7.attachedToThreadId !== void 0 || currentSectionId === PINNED_THREAD_SECTION_ID) {
82531
+ await this.#writer.json(
82532
+ rpcError(request, -32078, "An active, unpinned top-level Thread is required")
82533
+ );
82534
+ return;
82535
+ }
82536
+ if (placement || sectionId !== null) {
82537
+ const definitions = await this.#readSectionDefinitions();
82538
+ if (placement && this.#sectionDefinitions.project([placement], definitions).length === 0)
82539
+ currentSectionId = null;
82540
+ if (sectionId !== null) {
82541
+ destination = definitions.get(sectionId);
82542
+ if (!destination) {
82543
+ await this.#writer.json(rpcError(request, -32602, "Thread section does not exist"));
82544
+ return;
82545
+ }
82546
+ }
82547
+ }
82548
+ } else {
82549
+ const current2 = remote ?? await this.#requestOfficial("thread/read", readParams);
82550
+ const thread4 = current2.result?.thread;
82551
+ if (!isRecord25(thread4) || thread4.id !== threadId2 || thread4.archived === true || typeof thread4.parentThreadId === "string" || isRecord25(thread4.section) && thread4.section.id === PINNED_THREAD_SECTION_ID) {
82552
+ await this.#writer.json(
82553
+ remote ? ownerError : rpcError(request, -32078, "An active, unpinned Codex Thread is required")
82554
+ );
82555
+ return;
82556
+ }
82557
+ currentSectionId = isRecord25(thread4.section) && typeof thread4.section.id === "string" ? thread4.section.id : null;
82558
+ }
82559
+ const pending2 = currentSectionId === sectionId && !remote && !movingExternal ? this.#pendingSectionMoves.get(threadId2) : void 0;
82560
+ const recovery = pending2?.sectionId === sectionId && (beforeThreadId === void 0 || pending2.beforeThreadId === beforeThreadId) && (expectedSourceSectionId === void 0 || pending2.sourceSectionId === expectedSourceSectionId) ? pending2 : void 0;
82561
+ if (!recovery && expectedSourceSectionId !== void 0 && expectedSourceSectionId !== currentSectionId) {
82562
+ await this.#writer.json(
82563
+ rpcError(request, -32078, "Thread no longer belongs to its drag source section")
82564
+ );
82565
+ return;
82566
+ }
82567
+ if (!recovery && currentSectionId === sectionId && (beforeThreadId === void 0 || sectionId === null)) {
82568
+ await this.#writer.json(rpcEnvelope(request, { result: {} }));
82569
+ return;
82570
+ }
82571
+ if (remote) {
82572
+ await this.#writer.json(ownerError);
82573
+ return;
82574
+ }
82575
+ if (shared) {
82576
+ try {
82577
+ const foreign = await shared.placements(true);
82578
+ if (foreign.some(
82579
+ ({ section, hostThreadId }) => section.id === (recovery?.sourceSectionId ?? currentSectionId) || section.id === sectionId || hostThreadId === beforeThreadId || hostThreadId === threadId2
82580
+ ) || typeof beforeThreadId === "string" && (shared.knowsTreeOwner(beforeThreadId) || (await shared.ownership([beforeThreadId])).has(beforeThreadId))) {
82581
+ await this.#writer.json(ownerError);
82582
+ return;
82583
+ }
82584
+ } catch (error62) {
82585
+ this.#diagnose(error62);
82586
+ await this.#writer.json(ownerError);
82587
+ return;
82588
+ }
82589
+ }
82590
+ if (recovery) {
82591
+ await this.#finishPartialSectionMove(
82592
+ request,
82593
+ threadId2,
82594
+ recovery.recover,
82595
+ recovery.nativeConfirmed
82596
+ );
82597
+ return;
82598
+ }
82599
+ if (!movingExternal && sectionId !== null) {
82600
+ destination = (await this.#readSectionDefinitions()).get(sectionId);
82601
+ if (!destination) {
82602
+ await this.#writer.json(rpcError(request, -32602, "Thread section does not exist"));
82603
+ return;
82604
+ }
82605
+ }
82606
+ placements ??= await this.#repository.listSectionPlacements();
82607
+ await this.#moveThreadSection(
82608
+ request,
82609
+ { threadId: threadId2, sectionId, beforeThreadId: beforeThreadId ?? null },
82610
+ { currentSectionId, placements, movingExternal, ...destination ? { destination } : {} }
82611
+ );
82612
+ });
82613
+ }
82614
+ async #moveThreadSection(request, move, custom2) {
81801
82615
  try {
81802
- const location = await this.#locateExternalThread(move.threadId);
81803
- if (await this.#writeResolutionError(request, location)) return;
82616
+ let movingExternal = custom2?.movingExternal;
82617
+ if (movingExternal === void 0) {
82618
+ const location = await this.#locateExternalThread(move.threadId);
82619
+ if (await this.#writeResolutionError(request, location)) return;
82620
+ movingExternal = location.kind === "external";
82621
+ }
81804
82622
  const [records, placements] = await Promise.all([
81805
- this.#repository.list(),
81806
- this.#repository.listSectionPlacements()
82623
+ this.#repository.listSummaries(),
82624
+ custom2?.placements ?? this.#repository.listSectionPlacements()
81807
82625
  ]);
81808
82626
  const outcome = await moveThreadSection({
81809
82627
  move,
81810
- movingExternal: location.kind === "external",
82628
+ ...custom2 ? { custom: custom2 } : {},
82629
+ movingExternal,
81811
82630
  externalThreadIds: new Set(records.map((record7) => record7.hostThreadId)),
81812
82631
  placements,
81813
82632
  requestOfficial: (method, params2) => this.#requestOfficial(method, params2),
81814
- savePlacements: (next) => this.#repository.replaceSectionPlacements(next),
82633
+ savePlacements: async (next) => {
82634
+ await this.#repository.replaceSectionPlacements(next);
82635
+ if (movingExternal && move.sectionId !== null) {
82636
+ const saved = next.find(({ hostThreadId }) => hostThreadId === move.threadId);
82637
+ if (saved) this.#sectionDefinitions.confirm(saved.section.id, saved.section);
82638
+ }
82639
+ },
81815
82640
  now: /* @__PURE__ */ new Date()
81816
82641
  });
81817
82642
  if (outcome.kind === "moved" && outcome.persistError !== void 0)
81818
82643
  this.#diagnose(outcome.persistError);
81819
82644
  if (outcome.kind === "forward") {
81820
- const response = await this.#requestOfficial(request.method, requestObject(request));
82645
+ let response;
82646
+ try {
82647
+ response = await this.#requestOfficial(request.method, requestObject(request));
82648
+ } catch (error62) {
82649
+ this.#diagnose(error62);
82650
+ await this.#finishPartialSectionMove(request, move.threadId, outcome.confirm, false);
82651
+ return;
82652
+ }
81821
82653
  await this.#writer.json(rpcEnvelope(request, { ...response, id: request.id }));
81822
82654
  if (response.error) return;
82655
+ this.#pendingSectionMoves.delete(move.threadId);
81823
82656
  } else if (outcome.kind === "error") {
81824
82657
  await this.#writer.json(rpcEnvelope(request, { error: outcome.error }));
81825
82658
  return;
81826
- } else await this.#writer.json(rpcEnvelope(request, { result: {} }));
81827
- this.clientEvents.changed(move.threadId, "codexhost/thread/tree/changed");
82659
+ } else if (outcome.kind === "unchanged") {
82660
+ await this.#writer.json(rpcEnvelope(request, { result: {} }));
82661
+ return;
82662
+ } else if (outcome.kind === "needs-readback") {
82663
+ this.#diagnose(outcome.cause);
82664
+ this.#pendingSectionMoves.set(move.threadId, {
82665
+ sectionId: move.sectionId,
82666
+ sourceSectionId: custom2?.currentSectionId,
82667
+ beforeThreadId: move.beforeThreadId,
82668
+ recover: outcome.recover,
82669
+ nativeConfirmed: outcome.nativeConfirmed
82670
+ });
82671
+ await this.#finishPartialSectionMove(
82672
+ request,
82673
+ move.threadId,
82674
+ outcome.recover,
82675
+ outcome.nativeConfirmed
82676
+ );
82677
+ return;
82678
+ } else {
82679
+ this.#pendingSectionMoves.delete(move.threadId);
82680
+ if (custom2) await this.#publishSectionsChanged();
82681
+ await this.#writer.json(rpcEnvelope(request, { result: {} }));
82682
+ }
82683
+ if (!custom2) {
82684
+ this.clientEvents.changed(move.threadId, "codexhost/thread/tree/changed");
82685
+ await this.#publishSectionsChanged();
82686
+ }
81828
82687
  } catch (error62) {
81829
82688
  await this.#writer.json(rpcError(request, -32081, "Thread section could not be moved"));
81830
82689
  this.#diagnose(error62);
81831
82690
  }
81832
82691
  }
82692
+ async #finishPartialSectionMove(request, threadId2, recover, nativeConfirmed) {
82693
+ const recovered = await recover(() => this.#repository.listSectionPlacements()).catch(
82694
+ (error62) => {
82695
+ this.#diagnose(error62);
82696
+ return false;
82697
+ }
82698
+ );
82699
+ if (recovered) this.#pendingSectionMoves.delete(threadId2);
82700
+ await this.#publishSectionsChanged();
82701
+ await this.#writer.json(
82702
+ recovered ? rpcEnvelope(request, { result: {} }) : rpcError(
82703
+ request,
82704
+ -32081,
82705
+ nativeConfirmed ? "Native Thread moved, but external section order could not be saved; refresh before retrying" : "Native Thread move outcome is unknown; refresh before retrying"
82706
+ )
82707
+ );
82708
+ }
81833
82709
  async #externalSectionFields(threadId2) {
81834
- const placements = await this.#repository.listSectionPlacements();
81835
- return threadSectionFields(placements.find((entry) => entry.hostThreadId === threadId2));
82710
+ const placement = (await this.#repository.listSectionPlacements()).find(
82711
+ (entry) => entry.hostThreadId === threadId2
82712
+ );
82713
+ return threadSectionFields(placement && this.#sectionDefinitions.project([placement])[0]);
81836
82714
  }
81837
82715
  /** Cached External Thread projections predate section moves; responses read the placement. */
81838
82716
  async #withExternalSection(thread4) {
@@ -82417,14 +83295,17 @@ var AppServerHost = class {
82417
83295
  this.#officialRateLimits.getResetCredits(accountId)
82418
83296
  );
82419
83297
  }
82420
- async #listThreadOwnership(request) {
83298
+ async #listThreadOwnership(request, requireComplete = false) {
82421
83299
  const params2 = threadOwnershipListParamsSchema.safeParse(request.params);
82422
83300
  if (!params2.success) {
82423
83301
  await this.#writer.json(rpcError(request, -32602, "Invalid Thread ownership-list params"));
82424
83302
  return;
82425
83303
  }
82426
83304
  try {
82427
- const shared = await this.#options.sharedThreads?.ownership(params2.data.threadIds);
83305
+ const shared = await this.#options.sharedThreads?.ownership(
83306
+ params2.data.threadIds,
83307
+ requireComplete
83308
+ );
82428
83309
  const threads = await Promise.all(
82429
83310
  params2.data.threadIds.map(async (threadId2) => {
82430
83311
  const sharedHarness = shared?.get(threadId2);
@@ -83968,7 +84849,7 @@ var AppServerHost = class {
83968
84849
  #externalSessionAvailable(thread4) {
83969
84850
  return !this.#closeRequested && !thread4.sessionUnavailable && this.#externalRuntime.get(thread4.id) === thread4;
83970
84851
  }
83971
- async #startDelegatedExternalTurn(thread4, text5, requestedTurnId) {
84852
+ async #startDelegatedExternalTurn(thread4, text5, requestedTurnId, sourceHostId) {
83972
84853
  if (this.#externalThreadBusy(thread4)) {
83973
84854
  throw new DelegationControlError("THREAD_BUSY", "External Thread already has an active Turn");
83974
84855
  }
@@ -83988,6 +84869,7 @@ var AppServerHost = class {
83988
84869
  thread4.projectedTerminalTurnId = null;
83989
84870
  thread4.projectedTurns.set(turnId, projection);
83990
84871
  thread4.responseGates.set(turnId, gate);
84872
+ const restoreExecutionHost = this.#setExecutionHost(thread4, sourceHostId);
83991
84873
  try {
83992
84874
  const stored = await this.#repository.find(thread4.id);
83993
84875
  await this.#drainPendingAutonomousOutputs(thread4);
@@ -84021,6 +84903,7 @@ var AppServerHost = class {
84021
84903
  gate.resolve();
84022
84904
  await this.#releaseInjectedText(thread4, turnId, injected);
84023
84905
  } catch (error62) {
84906
+ restoreExecutionHost();
84024
84907
  if (thread4.admittingTurnId === turnId) thread4.admittingTurnId = null;
84025
84908
  thread4.projectedTurns.delete(turnId);
84026
84909
  thread4.responseGates.delete(turnId);
@@ -84094,7 +84977,7 @@ var AppServerHost = class {
84094
84977
  requestInput(params2),
84095
84978
  typeof params2.clientUserMessageId === "string" ? params2.clientUserMessageId : void 0,
84096
84979
  requestPresentationInput(params2),
84097
- params2[THREAD_REFERENCE_SOURCE_HOST_PARAM]
84980
+ threadReferenceSourceHost(params2)
84098
84981
  );
84099
84982
  await this.#publishExternalQueue(thread4.id);
84100
84983
  await this.#writer.json(
@@ -84120,7 +85003,7 @@ var AppServerHost = class {
84120
85003
  void 0,
84121
85004
  typeof params2.clientUserMessageId === "string" ? params2.clientUserMessageId : void 0,
84122
85005
  clientRequest,
84123
- params2[THREAD_REFERENCE_SOURCE_HOST_PARAM]
85006
+ threadReferenceSourceHost(params2)
84124
85007
  );
84125
85008
  try {
84126
85009
  await this.#writer.json(rpcEnvelope(request, { result: { turn: started.turn } }));
@@ -84229,7 +85112,7 @@ var AppServerHost = class {
84229
85112
  requestInput(params2),
84230
85113
  typeof params2.clientUserMessageId === "string" ? params2.clientUserMessageId : void 0,
84231
85114
  requestPresentationInput(params2),
84232
- params2[THREAD_REFERENCE_SOURCE_HOST_PARAM]
85115
+ threadReferenceSourceHost(params2)
84233
85116
  );
84234
85117
  await this.#publishExternalQueue(thread4.id);
84235
85118
  await this.#writer.json(
@@ -84380,7 +85263,7 @@ var AppServerHost = class {
84380
85263
  assertActive,
84381
85264
  item.clientUserMessageId,
84382
85265
  true,
84383
- item.sourceHostId
85266
+ item.sourceHostId ?? this.#executionHosts.get(thread4)
84384
85267
  ),
84385
85268
  (input3) => this.#insertExternalInput(thread4, input3)
84386
85269
  ) : await this.#startQueuedExternalTurn(thread4, item.id);
@@ -84413,7 +85296,7 @@ var AppServerHost = class {
84413
85296
  }
84414
85297
  }
84415
85298
  /** `thread send --steer` uses the same steering operation as Desktop. */
84416
- async #steerDelegatedExternalTurn(thread4, text5) {
85299
+ async #steerDelegatedExternalTurn(thread4, text5, sourceHostId) {
84417
85300
  if (this.#externalSteering.hasPending(thread4.id) || !thread4.running || !thread4.activeTurnId) {
84418
85301
  throw new DelegationControlError("THREAD_BUSY", "Thread is not ready for steering");
84419
85302
  }
@@ -84421,7 +85304,14 @@ var AppServerHost = class {
84421
85304
  const started = await this.#externalSteering.run(
84422
85305
  thread4,
84423
85306
  { expectedTurnId: thread4.activeTurnId, input: [{ type: "text", text: text5 }] },
84424
- (replacementText, assertActive) => this.#beginExternalInputTurn(thread4, replacementText, assertActive, void 0, true),
85307
+ (replacementText, assertActive) => this.#beginExternalInputTurn(
85308
+ thread4,
85309
+ replacementText,
85310
+ assertActive,
85311
+ void 0,
85312
+ true,
85313
+ sourceHostId ?? this.#executionHosts.get(thread4)
85314
+ ),
84425
85315
  (input3) => this.#insertExternalInput(thread4, input3)
84426
85316
  );
84427
85317
  started.gate.resolve();
@@ -84490,7 +85380,7 @@ var AppServerHost = class {
84490
85380
  assertActive,
84491
85381
  typeof params3.clientUserMessageId === "string" ? params3.clientUserMessageId : void 0,
84492
85382
  String(request.id).startsWith(this.#clientRequestPrefix),
84493
- queued ? queued.sourceHostId : params3[THREAD_REFERENCE_SOURCE_HOST_PARAM]
85383
+ queued ? queued.sourceHostId ?? this.#executionHosts.get(thread4) : threadReferenceSourceHost(params3)
84494
85384
  ),
84495
85385
  (input3) => this.#insertExternalInput(thread4, input3)
84496
85386
  );
@@ -88590,7 +89480,13 @@ var DelegationControlRegistry = class {
88590
89480
  }
88591
89481
  async start(input3) {
88592
89482
  const authContext = getCallerAuthContext(input3);
88593
- const { hostId: hostId2, callerThreadId: callerThreadId2, refs: requested, ...start } = input3;
89483
+ const {
89484
+ hostId: hostId2,
89485
+ callerThreadId: callerThreadId2,
89486
+ sourceHostId: _sourceHostId,
89487
+ refs: requested,
89488
+ ...start
89489
+ } = input3;
88594
89490
  const own2 = normalizeRefs(requested);
88595
89491
  if (isRemoteHostId(hostId2)) {
88596
89492
  const { parentThreadId, ...remoteStart } = start;
@@ -88633,7 +89529,9 @@ var DelegationControlRegistry = class {
88633
89529
  }
88634
89530
  const parentForPrecheck = localStart.parentThreadId;
88635
89531
  const precheckedParentLineage = parentForPrecheck && parentForPrecheck !== trustedCaller ? await this.#inspectLineage(parentForPrecheck) : callerLineage;
88636
- const result = await (await this.#registrationForStart(localStart)).start(localStart);
89532
+ const owner = await this.#registrationForStart(localStart);
89533
+ const sourceHostId = authContext?.kind === "agent" && typeof trustedCaller === "string" ? await this.#callerSshHost(trustedCaller, !!authContext.boundThreadId) : void 0;
89534
+ const result = await owner.start(sourceHostId ? { ...localStart, sourceHostId } : localStart);
88637
89535
  const parent = result.parentThreadId ?? localStart.parentThreadId;
88638
89536
  if (callerLineage.kind === "remote") {
88639
89537
  this.markRemoteOriginThread(result.threadId, callerLineage.hops);
@@ -88657,8 +89555,9 @@ var DelegationControlRegistry = class {
88657
89555
  "INVALID_ARGUMENT",
88658
89556
  "steer and interrupt are mutually exclusive"
88659
89557
  );
88660
- const { hostId: hostId2, callerThreadId: callerThreadId2, ...local } = input3;
88661
- if (isRemoteHostId(hostId2)) {
89558
+ const { hostId: hostId2, callerThreadId: callerThreadId2, sourceHostId: _sourceHostId, ...local } = input3;
89559
+ const sameSshHost = isDesktopSshHostId(hostId2) && await this.#callerRunsOnHost(hostId2, callerThreadId2, authContext, true);
89560
+ if (isRemoteHostId(hostId2) && !sameSshHost) {
88662
89561
  const result = await this.#callRemotePeer(
88663
89562
  hostId2,
88664
89563
  "send",
@@ -88673,8 +89572,8 @@ var DelegationControlRegistry = class {
88673
89572
  };
88674
89573
  }
88675
89574
  const registration = await this.#registrationForThread(local.threadId);
88676
- if (!local.interrupt) return registration.send(local);
88677
- const send = { threadId: local.threadId, message: local.message, interrupt: true };
89575
+ const send = sameSshHost ? { ...local, sourceHostId: hostId2 } : local;
89576
+ if (!local.interrupt) return registration.send(send);
88678
89577
  return this.#watchService.holdNotifications(
88679
89578
  local.threadId,
88680
89579
  () => interruptAndSend(registration, send)
@@ -88705,24 +89604,38 @@ var DelegationControlRegistry = class {
88705
89604
  }
88706
89605
  return withRefs(snapshot2, await this.#refs?.get(snapshot2.threadId) ?? []);
88707
89606
  }
89607
+ async #callerSshHost(caller, bound) {
89608
+ const hosts = /* @__PURE__ */ new Set();
89609
+ for (const registration of this.#registrations) {
89610
+ const hostId2 = bound ? registration.executionHostId?.(caller) : registration.nativeExecutionHostId?.(caller);
89611
+ if (isDesktopSshHostId(hostId2) && (!bound || await registration.ownsThread(caller)))
89612
+ hosts.add(hostId2);
89613
+ }
89614
+ return hosts.size === 1 ? [...hosts][0] : void 0;
89615
+ }
89616
+ async #callerRunsOnHost(hostId2, callerThreadId2, authContext, requireAuthenticatedCaller = false) {
89617
+ const boundThreadId = authContext?.kind === "agent" ? authContext.boundThreadId : void 0;
89618
+ const caller = boundThreadId || callerThreadId2;
89619
+ if (typeof caller !== "string" || !caller) return false;
89620
+ const canUseNativeContext = authContext?.kind === "agent" && !boundThreadId && isDesktopSshHostId(hostId2);
89621
+ const callers = await this.#matching(
89622
+ (registration) => canUseNativeContext && registration.nativeExecutionHostId?.(caller) === hostId2 || (!requireAuthenticatedCaller || !!boundThreadId) && registration.executionHostId?.(caller) === hostId2 && registration.ownsThread(caller)
89623
+ );
89624
+ if (callers.length === 0) return false;
89625
+ this.#selectExplicitThreadRegistration(
89626
+ callers,
89627
+ "Calling Thread has ambiguous execution Host context"
89628
+ );
89629
+ return true;
89630
+ }
88708
89631
  async #read(input3) {
88709
89632
  const authContext = getCallerAuthContext(input3);
88710
89633
  const { callerThreadId: callerThreadId2, ...read } = input3;
88711
89634
  if (isRemoteHostId(read.hostId)) {
88712
- const effectiveCallerForSameHost = authContext?.kind === "agent" && authContext.boundThreadId ? authContext.boundThreadId : callerThreadId2;
88713
- if (typeof effectiveCallerForSameHost === "string" && effectiveCallerForSameHost) {
88714
- const callers = await this.#matching(
88715
- (registration) => registration.executionHostId?.(effectiveCallerForSameHost) === read.hostId && registration.ownsThread(effectiveCallerForSameHost)
88716
- );
88717
- if (callers.length > 0) {
88718
- this.#selectExplicitThreadRegistration(
88719
- callers,
88720
- "Calling Thread has ambiguous execution Host context"
88721
- );
88722
- const { hostId: hostId2, ...local } = read;
88723
- const snapshot2 = await (await this.#registrationForThread(local.threadId)).read(local);
88724
- return { ...snapshot2, hostId: hostId2 };
88725
- }
89635
+ if (await this.#callerRunsOnHost(read.hostId, callerThreadId2, authContext)) {
89636
+ const { hostId: hostId2, ...local } = read;
89637
+ const snapshot2 = await (await this.#registrationForThread(local.threadId)).read(local);
89638
+ return { ...snapshot2, hostId: hostId2 };
88726
89639
  }
88727
89640
  if (isRemotePeerHostId(read.hostId)) {
88728
89641
  const { hostId: hostId2, ...remoteRead } = read;
@@ -90379,10 +91292,15 @@ var SharedThreadOwner = class {
90379
91292
  #interactions = /* @__PURE__ */ new Map();
90380
91293
  #clients = /* @__PURE__ */ new Map();
90381
91294
  #treeClients = /* @__PURE__ */ new Map();
91295
+ #sectionClients = /* @__PURE__ */ new Set();
90382
91296
  #closed = false;
90383
91297
  #receipts = /* @__PURE__ */ new Map();
90384
91298
  constructor() {
90385
91299
  this.#peer.subscribe((message2) => {
91300
+ if (message2.method === SHARED_SECTIONS_CHANGED_METHOD) {
91301
+ for (const listener of this.#sectionClients) listener(message2);
91302
+ return;
91303
+ }
90386
91304
  if (message2.method === THREAD_TREE_SNAPSHOT_METHOD) {
90387
91305
  const id3 = object5(message2.params) ? message2.params.subscriptionId : void 0;
90388
91306
  if (typeof id3 === "string") this.#treeClients.get(id3)?.(message2);
@@ -90443,6 +91361,10 @@ var SharedThreadOwner = class {
90443
91361
  closed: ended.promise,
90444
91362
  request: async (method, params2) => {
90445
91363
  if (closed) throw new Error("Shared Thread client is closed");
91364
+ if (method === SHARED_SECTIONS_WATCH_METHOD) {
91365
+ this.#sectionClients.add(publish);
91366
+ return { result: {} };
91367
+ }
90446
91368
  if (method === THREAD_TREE_UNWATCH_METHOD) {
90447
91369
  const id3 = params2.subscriptionId;
90448
91370
  if (typeof id3 !== "string" || this.#treeClients.get(id3) !== publish)
@@ -90475,6 +91397,7 @@ var SharedThreadOwner = class {
90475
91397
  if (closed) return;
90476
91398
  closed = true;
90477
91399
  this.#clients.delete(publish);
91400
+ this.#sectionClients.delete(publish);
90478
91401
  for (const [id3, listener] of this.#treeClients) {
90479
91402
  if (listener !== publish) continue;
90480
91403
  this.#treeClients.delete(id3);
@@ -90609,6 +91532,7 @@ async function startClientChannelServer(options) {
90609
91532
  epoch: url2.searchParams.get("epoch"),
90610
91533
  sequence: Number(url2.searchParams.get("after"))
90611
91534
  }) : void 0;
91535
+ const supportsSections = url2.searchParams.get(THREAD_SECTION_CAPABILITY) === "1";
90612
91536
  response.writeHead(200, {
90613
91537
  "content-type": "application/x-ndjson",
90614
91538
  "cache-control": "no-store"
@@ -90618,7 +91542,8 @@ async function startClientChannelServer(options) {
90618
91542
  response.destroy();
90619
91543
  throw new Error("Slow client detached");
90620
91544
  }
90621
- response.write(JSON.stringify(event) + "\n");
91545
+ const frame = event.type === "sections-changed" && !supportsSections ? { type: "hello", version: 1, cursor: event.cursor, reset: true } : event;
91546
+ response.write(JSON.stringify(frame) + "\n");
90622
91547
  }, after);
90623
91548
  const heartbeat = setInterval(() => response.write("\n"), 15e3);
90624
91549
  heartbeat.unref();
@@ -90732,7 +91657,12 @@ async function startClientChannelServer(options) {
90732
91657
  token,
90733
91658
  startedAt: Date.now(),
90734
91659
  epoch: options.target.clientEvents.epoch,
90735
- ...options.peerDelegation ? { capabilities: { peerDelegation: 1 } } : {}
91660
+ ...options.peerDelegation || options.nativeSession ? {
91661
+ capabilities: {
91662
+ ...options.peerDelegation ? { peerDelegation: 1 } : {},
91663
+ ...options.nativeSession ? { threadReferenceContext: 1 } : {}
91664
+ }
91665
+ } : {}
90736
91666
  };
90737
91667
  try {
90738
91668
  await mkdir33(directory2, { recursive: true, mode: 448 });
@@ -90777,18 +91707,22 @@ function sharedThreadSocketPath(environment) {
90777
91707
  async function connectSharedThreads(environment) {
90778
91708
  if (process.platform === "win32") return null;
90779
91709
  const socketPath = sharedThreadSocketPath(environment);
90780
- const metadata2 = await lstat19(socketPath).catch(() => null);
91710
+ const metadata2 = await lstat19(socketPath).catch((error62) => {
91711
+ if (error62.code === "ENOENT") return null;
91712
+ throw error62;
91713
+ });
90781
91714
  if (!metadata2) return null;
90782
91715
  if (!metadata2.isSocket() || metadata2.uid !== process.getuid?.() || (metadata2.mode & 63) !== 0) {
90783
91716
  throw new Error("Shared Thread socket must be private and owned by the current user");
90784
91717
  }
90785
- const connection = await createRemoteOfficialAppServerConnection(socketPath).catch(() => null);
90786
- if (!connection) return null;
91718
+ const connection = await createRemoteOfficialAppServerConnection(socketPath);
90787
91719
  connection.stderr.resume();
90788
91720
  return new StreamThreadPeer(connection.stdout, connection.stdin, () => connection.close());
90789
91721
  }
90790
91722
  var SHARED_LIST_REUSE_MS = 5e3;
90791
91723
  var LIST_CHANGING_METHODS = /* @__PURE__ */ new Set([
91724
+ "codexhost/thread/pins/set",
91725
+ "codexhost/thread/sections/move",
90792
91726
  "thread/archive",
90793
91727
  "thread/delete",
90794
91728
  "thread/fork",
@@ -90815,9 +91749,12 @@ var SharedThreadBridge = class {
90815
91749
  #treeAttempt;
90816
91750
  #treeDiagnosed = false;
90817
91751
  #peer = null;
91752
+ #peerMayExist = false;
90818
91753
  #connecting = null;
90819
91754
  #closed = false;
90820
91755
  #timer;
91756
+ #sectionWatchPeer;
91757
+ #sectionWatchNeedsRefresh = false;
90821
91758
  #publish = () => void 0;
90822
91759
  // A client pages its own catalog while each of its pages needs every shared row. One shared
90823
91760
  // walk per query serves those pages; a Thread notification or a new peer starts a fresh walk.
@@ -90830,7 +91767,8 @@ var SharedThreadBridge = class {
90830
91767
  start(publish) {
90831
91768
  this.#publish = publish;
90832
91769
  const discover = () => {
90833
- void this.#connect().catch(this.options.diagnose);
91770
+ if (this.#peer) this.#watchSections(this.#peer);
91771
+ else void this.#connect().catch(this.options.diagnose);
90834
91772
  };
90835
91773
  discover();
90836
91774
  this.#timer = setInterval(discover, 3e3);
@@ -90847,7 +91785,13 @@ var SharedThreadBridge = class {
90847
91785
  return null;
90848
91786
  }
90849
91787
  this.#peer = peer;
91788
+ this.#peerMayExist = true;
90850
91789
  peer.subscribe((message2) => {
91790
+ if (message2.method === SHARED_SECTIONS_CHANGED_METHOD) {
91791
+ this.#invalidateLists();
91792
+ this.#publish(message2);
91793
+ return;
91794
+ }
90851
91795
  if (typeof message2.method === "string" && message2.method.startsWith("thread/")) {
90852
91796
  this.#invalidateLists();
90853
91797
  }
@@ -90865,7 +91809,11 @@ var SharedThreadBridge = class {
90865
91809
  this.#publish(message2);
90866
91810
  });
90867
91811
  void peer.closed.then(() => {
90868
- if (this.#peer === peer) this.#peer = null;
91812
+ if (this.#peer === peer) {
91813
+ this.#peer = null;
91814
+ this.#sectionWatchPeer = void 0;
91815
+ this.#sectionWatchNeedsRefresh = true;
91816
+ }
90869
91817
  if (this.#treeAttempt?.peer === peer) {
90870
91818
  this.#treeAttempt = void 0;
90871
91819
  this.#treeListener?.(null);
@@ -90873,9 +91821,11 @@ var SharedThreadBridge = class {
90873
91821
  }
90874
91822
  this.#invalidateLists();
90875
91823
  });
91824
+ this.#watchSections(peer);
90876
91825
  this.#startTree(peer);
90877
91826
  return peer;
90878
91827
  }).catch((error62) => {
91828
+ this.#peerMayExist = true;
90879
91829
  this.#peer?.close();
90880
91830
  this.#peer = null;
90881
91831
  throw error62;
@@ -90884,6 +91834,29 @@ var SharedThreadBridge = class {
90884
91834
  });
90885
91835
  return this.#connecting;
90886
91836
  }
91837
+ #watchSections(peer) {
91838
+ if (this.#sectionWatchPeer === peer) return;
91839
+ this.#sectionWatchPeer = peer;
91840
+ void peer.request(SHARED_SECTIONS_WATCH_METHOD, {}).then((reply2) => {
91841
+ if (this.#peer !== peer) return;
91842
+ if (object5(reply2.error) && reply2.error.code === -32601) return;
91843
+ if (reply2.error !== void 0 || !object5(reply2.result)) {
91844
+ throw new Error(
91845
+ object5(reply2.error) ? String(reply2.error.message ?? "Shared section watch failed") : "Invalid shared section watch reply"
91846
+ );
91847
+ }
91848
+ if (!this.#sectionWatchNeedsRefresh) return;
91849
+ this.#sectionWatchNeedsRefresh = false;
91850
+ this.#invalidateLists();
91851
+ this.#publish({ method: SHARED_SECTIONS_CHANGED_METHOD, params: {} });
91852
+ }).catch((error62) => {
91853
+ if (this.#peer !== peer) return;
91854
+ this.#sectionWatchPeer = void 0;
91855
+ if (this.#sectionWatchNeedsRefresh) return;
91856
+ this.#sectionWatchNeedsRefresh = true;
91857
+ this.options.diagnose(error62);
91858
+ });
91859
+ }
90887
91860
  knowsTreeOwner(id3) {
90888
91861
  return this.#known.has(id3);
90889
91862
  }
@@ -90936,22 +91909,18 @@ var SharedThreadBridge = class {
90936
91909
  }
90937
91910
  this.#treeListener?.(snapshot2);
90938
91911
  }
90939
- async ownership(threadIds) {
91912
+ async ownership(threadIds, requireComplete = false) {
90940
91913
  if (threadIds.length === 0) return /* @__PURE__ */ new Map();
90941
91914
  try {
90942
91915
  const peer = await this.#connect();
90943
- if (!peer) throw new Error("Shared Thread Host is disconnected");
90944
- const response = await peer.request("codexhost/thread/ownership/list", { threadIds });
90945
- const result = threadOwnershipListResultSchema.parse(response.result);
90946
- const owners = /* @__PURE__ */ new Map();
90947
- for (const thread4 of result.threads) {
90948
- if (thread4.owner === "external") {
90949
- owners.set(thread4.threadId, thread4.harnessId);
90950
- this.#known.add(thread4.threadId);
90951
- }
91916
+ if (!peer) {
91917
+ if (requireComplete && !this.#peerMayExist && !this.options.delegateCreates)
91918
+ return /* @__PURE__ */ new Map();
91919
+ throw new Error("Shared Thread Host is disconnected");
90952
91920
  }
90953
- return owners;
91921
+ return await this.#readOwnership(peer, threadIds, requireComplete);
90954
91922
  } catch (error62) {
91923
+ if (requireComplete) throw error62;
90955
91924
  if (threadIds.some((id3) => this.#known.has(id3))) throw error62;
90956
91925
  const probe = this.#localProbe;
90957
91926
  if (probe && (await Promise.all(threadIds.map((id3) => probe(id3)))).every(Boolean)) {
@@ -90962,6 +91931,26 @@ var SharedThreadBridge = class {
90962
91931
  return /* @__PURE__ */ new Map();
90963
91932
  }
90964
91933
  }
91934
+ async #readOwnership(peer, threadIds, requireComplete = false) {
91935
+ const response = await peer.request(
91936
+ requireComplete ? SHARED_THREAD_OWNERSHIP_METHOD : "codexhost/thread/ownership/list",
91937
+ { threadIds }
91938
+ );
91939
+ const result = threadOwnershipListResultSchema.parse(response.result);
91940
+ if (requireComplete) {
91941
+ const requested = new Set(threadIds);
91942
+ if (result.threads.length !== requested.size || result.threads.some(({ threadId: threadId2 }) => !requested.has(threadId2)))
91943
+ throw new Error("Incomplete shared Thread ownership");
91944
+ }
91945
+ const owners = /* @__PURE__ */ new Map();
91946
+ for (const thread4 of result.threads) {
91947
+ if (thread4.owner === "external") {
91948
+ owners.set(thread4.threadId, thread4.harnessId);
91949
+ this.#known.add(thread4.threadId);
91950
+ }
91951
+ }
91952
+ return owners;
91953
+ }
90965
91954
  handlesControl(method) {
90966
91955
  return this.options.delegateCreates && [
90967
91956
  LOADED_SESSIONS_METHOD,
@@ -90974,7 +91963,36 @@ var SharedThreadBridge = class {
90974
91963
  async request(method, params2) {
90975
91964
  const peer = await this.#connect();
90976
91965
  if (!peer) throw new Error("Shared Thread Host is disconnected");
90977
- return peer.request(method, params2);
91966
+ const reply2 = await peer.request(method, params2);
91967
+ if (LIST_CHANGING_METHODS.has(method)) this.#invalidateLists();
91968
+ return reply2;
91969
+ }
91970
+ async routeSectionWrite(request, isLocalNativeThread) {
91971
+ const params2 = object5(request.params) ? request.params : {};
91972
+ const { threadId: threadId2, beforeThreadId } = params2;
91973
+ if (typeof threadId2 !== "string") return null;
91974
+ let peer = null;
91975
+ let owned = this.#known.has(threadId2);
91976
+ try {
91977
+ peer = await this.#connect();
91978
+ if (peer) {
91979
+ owned ||= this.options.ownsNativeSections === true;
91980
+ if (!owned) {
91981
+ const ids = typeof beforeThreadId === "string" && beforeThreadId !== threadId2 ? [threadId2, beforeThreadId] : [threadId2];
91982
+ owned = (await this.#readOwnership(peer, ids)).has(threadId2);
91983
+ }
91984
+ }
91985
+ } catch (error62) {
91986
+ this.options.diagnose(error62);
91987
+ }
91988
+ if (peer && owned) {
91989
+ const reply2 = await peer.request(request.method, params2);
91990
+ this.#invalidateLists();
91991
+ return { ...reply2, id: request.id };
91992
+ }
91993
+ if (!owned && await isLocalNativeThread(threadId2) && (typeof beforeThreadId !== "string" || beforeThreadId === threadId2 || !this.#known.has(beforeThreadId) && await isLocalNativeThread(beforeThreadId)))
91994
+ return null;
91995
+ throw new Error("Thread section owner is unavailable");
90978
91996
  }
90979
91997
  async route(request) {
90980
91998
  const params2 = object5(request.params) ? request.params : {};
@@ -90991,14 +92009,17 @@ var SharedThreadBridge = class {
90991
92009
  if (LIST_CHANGING_METHODS.has(request.method)) this.#invalidateLists();
90992
92010
  return { ...reply2, id: request.id };
90993
92011
  }
90994
- async #rows(peer, params2) {
92012
+ async #rows(peer, params2, requireComplete) {
92013
+ const method = requireComplete ? SHARED_THREAD_LIST_METHOD : "thread/list";
90995
92014
  const rows = [];
90996
92015
  let cursor = null;
90997
92016
  const seen = /* @__PURE__ */ new Set();
90998
92017
  do {
90999
- const reply2 = await peer.request("thread/list", { ...params2, cursor, limit: 200 });
91000
- if (!object5(reply2.result) || !Array.isArray(reply2.result.data))
92018
+ const reply2 = await peer.request(method, { ...params2, cursor, limit: 200 });
92019
+ if (reply2.error !== void 0 || !object5(reply2.result) || !Array.isArray(reply2.result.data))
91001
92020
  throw new Error("Shared Thread list failed");
92021
+ if (requireComplete && reply2.result.complete !== true)
92022
+ throw new Error("Shared Thread Host did not confirm complete Thread list");
91002
92023
  for (const row of reply2.result.data) {
91003
92024
  if (!object5(row) || typeof row.id !== "string")
91004
92025
  throw new Error("Invalid shared Thread row");
@@ -91011,48 +92032,70 @@ var SharedThreadBridge = class {
91011
92032
  if (typeof next === "string" && seen.has(next))
91012
92033
  throw new Error("Shared Thread pagination did not advance");
91013
92034
  cursor = next;
91014
- if (cursor) seen.add(cursor);
92035
+ if (cursor !== null) seen.add(cursor);
91015
92036
  } while (cursor !== null);
91016
92037
  return rows;
91017
92038
  }
91018
92039
  /** Every shared row of one query; the caller's own cursor and page size do not apply. */
91019
- async list(params2) {
92040
+ async list(params2, { requireComplete = false } = {}) {
91020
92041
  const query = { ...params2 };
91021
92042
  delete query.cursor;
91022
92043
  delete query.limit;
91023
92044
  if (query.sortKey === "section_position") query.sortKey = "updated_at";
91024
- const key = JSON.stringify(query);
92045
+ const key = JSON.stringify([requireComplete, query]);
91025
92046
  const now = this.options.now ?? Date.now;
91026
92047
  try {
91027
92048
  const cached2 = this.#lists.get(key);
91028
- if (cached2 && cached2.generation === this.#listGeneration && now() - cached2.startedAtMs < SHARED_LIST_REUSE_MS) {
91029
- return await cached2.rows ?? [];
91030
- }
91031
- const entry = {
91032
- generation: this.#listGeneration,
91033
- startedAtMs: now(),
91034
- rows: this.#connect().then((peer) => peer ? this.#rows(peer, query) : null)
91035
- };
91036
- this.#lists.set(key, entry);
91037
- const forget = () => {
91038
- if (this.#lists.get(key) === entry) this.#lists.delete(key);
91039
- };
91040
- entry.rows.then((rows) => {
91041
- if (rows === null) forget();
91042
- }, forget);
91043
- return await entry.rows ?? [];
92049
+ let rows;
92050
+ if (cached2 && cached2.generation === this.#listGeneration && now() - cached2.startedAtMs < SHARED_LIST_REUSE_MS && // A new strict walk checks the nested peer again; continuations can reuse it.
92051
+ (!requireComplete || cached2.pending || typeof params2.cursor === "string")) {
92052
+ rows = await cached2.rows;
92053
+ } else {
92054
+ const entry = {
92055
+ generation: this.#listGeneration,
92056
+ startedAtMs: now(),
92057
+ pending: true,
92058
+ rows: this.#connect().then(
92059
+ (peer) => peer ? this.#rows(peer, query, requireComplete) : null
92060
+ )
92061
+ };
92062
+ this.#lists.set(key, entry);
92063
+ const forget = () => {
92064
+ if (this.#lists.get(key) === entry) this.#lists.delete(key);
92065
+ };
92066
+ entry.rows.then((rows2) => {
92067
+ entry.pending = false;
92068
+ if (rows2 === null) forget();
92069
+ }, forget);
92070
+ rows = await entry.rows;
92071
+ }
92072
+ if (rows === null && requireComplete && (this.#peerMayExist || this.options.delegateCreates))
92073
+ throw new Error("Shared Thread Host is disconnected");
92074
+ return rows ?? [];
91044
92075
  } catch (error62) {
92076
+ if (requireComplete) throw error62;
91045
92077
  this.options.diagnose(error62);
91046
92078
  return [];
91047
92079
  }
91048
92080
  }
91049
- async placements() {
92081
+ async placements(requireComplete = false) {
91050
92082
  try {
91051
92083
  const peer = await this.#connect();
91052
- if (!peer) return [];
91053
- const reply2 = await peer.request("codexhost/shared-threads/placements", {});
91054
- return storedSectionPlacementV1Schema.array().parse(reply2.result);
92084
+ if (!peer) {
92085
+ if (requireComplete && (this.#peerMayExist || this.options.delegateCreates))
92086
+ throw new Error("Shared Thread Host is disconnected");
92087
+ return [];
92088
+ }
92089
+ const reply2 = await peer.request(
92090
+ "codexhost/shared-threads/placements",
92091
+ requireComplete ? { requireComplete } : {}
92092
+ );
92093
+ const result = reply2.result;
92094
+ if (requireComplete && !object5(result))
92095
+ throw new Error("Shared Thread Host did not confirm complete section placements");
92096
+ return storedSectionPlacementV1Schema.array().parse(requireComplete && object5(result) ? result.placements : result);
91055
92097
  } catch (error62) {
92098
+ if (requireComplete) throw error62;
91056
92099
  this.options.diagnose(error62);
91057
92100
  return [];
91058
92101
  }
@@ -93635,6 +94678,7 @@ async function runHostRuntime(input3) {
93635
94678
  sharedThreads: new SharedThreadBridge({
93636
94679
  connect: async () => sharedOwner.connect(),
93637
94680
  delegateCreates: true,
94681
+ ownsNativeSections: true,
93638
94682
  diagnose: (error62) => diagnosticOutput.write(`codexhost shared Threads: ${String(error62)}
93639
94683
  `)
93640
94684
  }),
@@ -93787,6 +94831,7 @@ function sharedHostDesktop(options, streams, request) {
93787
94831
  sharedThreads: new SharedThreadBridge({
93788
94832
  connect: async () => options.owner.connect(),
93789
94833
  delegateCreates: true,
94834
+ ownsNativeSections: true,
93790
94835
  diagnose: (error62) => streams.diagnosticOutput.write(`Shared Host: ${String(error62)}
93791
94836
  `)
93792
94837
  }),