@zergai/ztc 0.26.6-dev.202611240947 → 0.27.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/README.md +629 -167
  2. package/RUST_THIRD_PARTY_LICENSES.txt +5 -5
  3. package/bin/zmux-darwin-arm64 +0 -0
  4. package/bin/zmux-linux-x64 +0 -0
  5. package/bin/ztc-audio-darwin-arm64 +0 -0
  6. package/bin/ztc-capture-darwin-arm64 +0 -0
  7. package/bin/ztc-computer-darwin-arm64 +0 -0
  8. package/bin/ztc-llm-darwin-arm64 +0 -0
  9. package/bin/ztc-tts-darwin-arm64 +0 -0
  10. package/bin/ztc-tui-darwin-arm64 +0 -0
  11. package/bin/ztc-tui-linux-x64 +0 -0
  12. package/bin/zterm-darwin-arm64 +2 -2
  13. package/dist/App.js +6 -1
  14. package/dist/agent/agent.d.ts +21 -15
  15. package/dist/agent/agent.js +389 -163
  16. package/dist/agent/backends/codex_app_server.d.ts +7 -1
  17. package/dist/agent/backends/codex_app_server.js +11 -1
  18. package/dist/agent/backends/gemini.js +22 -8
  19. package/dist/agent/commands/batch.js +8 -0
  20. package/dist/agent/commands/config.js +10 -0
  21. package/dist/agent/commands/environment.js +5 -5
  22. package/dist/agent/commands/goal.d.ts +1 -0
  23. package/dist/agent/commands/goal.js +2 -1
  24. package/dist/agent/commands/index.js +2 -1
  25. package/dist/agent/commands/manifest.js +4 -0
  26. package/dist/agent/commands/optimize.js +5 -2
  27. package/dist/agent/commands/pane_cli.d.ts +29 -0
  28. package/dist/agent/commands/pane_cli.js +303 -0
  29. package/dist/agent/commands/settings.js +13 -3
  30. package/dist/agent/commands/shannon.js +8 -0
  31. package/dist/agent/commands/update.js +15 -3
  32. package/dist/agent/commands/zerg.js +31 -1
  33. package/dist/agent/commands/ztc_pane.js +3 -1
  34. package/dist/agent/factory.d.ts +4 -0
  35. package/dist/agent/factory.js +11 -1
  36. package/dist/agent/loop_policy.d.ts +42 -5
  37. package/dist/agent/loop_policy.js +206 -3
  38. package/dist/agent/runtime/command_jobs.d.ts +5 -0
  39. package/dist/agent/runtime/command_jobs.js +241 -31
  40. package/dist/agent/runtime/command_wait.d.ts +2 -0
  41. package/dist/agent/runtime/command_wait.js +1 -0
  42. package/dist/agent/runtime/done_report.d.ts +18 -0
  43. package/dist/agent/runtime/done_report.js +130 -0
  44. package/dist/agent/runtime/execution_context.js +4 -1
  45. package/dist/agent/runtime/failure_cause.d.ts +2 -0
  46. package/dist/agent/runtime/failure_cause.js +35 -0
  47. package/dist/agent/runtime/policy.d.ts +14 -2
  48. package/dist/agent/runtime/policy.js +104 -12
  49. package/dist/agent/runtime/quiet_job.d.ts +18 -0
  50. package/dist/agent/runtime/quiet_job.js +48 -0
  51. package/dist/agent/runtime/recovery.d.ts +1 -5
  52. package/dist/agent/runtime/recovery.js +2 -44
  53. package/dist/agent/runtime/tool_runtime.d.ts +1 -0
  54. package/dist/agent/runtime/tool_runtime.js +2 -0
  55. package/dist/agent/subagent.js +6 -1
  56. package/dist/agent/tools/deferred.js +1 -0
  57. package/dist/agent/tools/index.d.ts +2 -0
  58. package/dist/agent/tools/index.js +1 -0
  59. package/dist/agent/tools/outcome.d.ts +15 -0
  60. package/dist/agent/tools/outcome.js +107 -0
  61. package/dist/agent/tools/pane.d.ts +2 -1
  62. package/dist/agent/tools/pane.js +21 -3
  63. package/dist/agent/tools/registry.js +2 -0
  64. package/dist/agent/tools/shell.d.ts +1 -0
  65. package/dist/agent/tools/shell.js +128 -17
  66. package/dist/agent/tools/sim_domain_tools.js +4 -2
  67. package/dist/agent/tools/supervision.js +4 -2
  68. package/dist/agent/tools/types.d.ts +3 -0
  69. package/dist/app/command_context.js +5 -9
  70. package/dist/app/conversation_compaction.d.ts +4 -2
  71. package/dist/app/conversation_compaction.js +16 -5
  72. package/dist/app/headless_shell_mode.d.ts +14 -0
  73. package/dist/app/headless_shell_mode.js +7 -0
  74. package/dist/app/hosted_resident.d.ts +356 -0
  75. package/dist/app/hosted_resident.js +677 -0
  76. package/dist/app/restart.js +11 -2
  77. package/dist/app/session_manager.d.ts +5 -0
  78. package/dist/app/session_manager.js +21 -6
  79. package/dist/app/session_messages.js +6 -6
  80. package/dist/app/workspace_layout_controller.js +7 -0
  81. package/dist/batch/worktree.d.ts +10 -0
  82. package/dist/batch/worktree.js +15 -0
  83. package/dist/bench/registry.js +4 -2
  84. package/dist/cli_args.js +1 -1
  85. package/dist/cli_main.js +80 -10
  86. package/dist/cli_ratatui.d.ts +75 -0
  87. package/dist/cli_ratatui.js +485 -84
  88. package/dist/components/InputArea.js +4 -4
  89. package/dist/config/execution.d.ts +10 -0
  90. package/dist/config/execution.js +10 -0
  91. package/dist/config/hosted_runtime.d.ts +4 -1
  92. package/dist/config/hosted_runtime.js +4 -1
  93. package/dist/config/permission_pin.d.ts +34 -2
  94. package/dist/config/permission_pin.js +52 -2
  95. package/dist/config/person_command_policy.d.ts +38 -0
  96. package/dist/config/person_command_policy.js +11 -0
  97. package/dist/config/profiles.d.ts +21 -0
  98. package/dist/config/profiles.js +56 -2
  99. package/dist/config/types.d.ts +4 -1
  100. package/dist/config.js +34 -19
  101. package/dist/desktop/daily/codex_exec_adapter.js +7 -2
  102. package/dist/desktop/daily/desktop_wiring.d.ts +7 -1
  103. package/dist/desktop/daily/desktop_wiring.js +11 -3
  104. package/dist/desktop/daily/recipes.js +20 -4
  105. package/dist/desktop/health.d.ts +24 -0
  106. package/dist/desktop/health.js +151 -0
  107. package/dist/desktop/native_dialogs.d.ts +37 -0
  108. package/dist/desktop/native_dialogs.js +105 -0
  109. package/dist/diagnostics/session_export.d.ts +1 -0
  110. package/dist/diagnostics/session_export.js +28 -0
  111. package/dist/embedded/registry.js +4 -2
  112. package/dist/emulation/tool_adapters.js +9 -4
  113. package/dist/emulation/ztc_addendum.js +3 -0
  114. package/dist/headless.d.ts +11 -4
  115. package/dist/headless.js +99 -34
  116. package/dist/headless_approval.d.ts +6 -0
  117. package/dist/headless_cli.js +1 -1
  118. package/dist/hooks/runner.js +7 -6
  119. package/dist/library.d.ts +4 -0
  120. package/dist/library.js +3 -0
  121. package/dist/mcp/client.js +3 -3
  122. package/dist/modes/registry.js +13 -4
  123. package/dist/onboarding/setup_environment.js +13 -1
  124. package/dist/optimize/adapters/kernelbench.js +88 -10
  125. package/dist/optimize/adapters/types.d.ts +5 -0
  126. package/dist/optimize/executor.js +21 -0
  127. package/dist/panes/cli_install.d.ts +54 -0
  128. package/dist/panes/cli_install.js +157 -0
  129. package/dist/panes/model_catalog.js +3 -0
  130. package/dist/panes/new_pane_choices.d.ts +6 -2
  131. package/dist/panes/new_pane_choices.js +24 -12
  132. package/dist/panes/pane_cli_launch.d.ts +50 -0
  133. package/dist/panes/pane_cli_launch.js +124 -0
  134. package/dist/panes/pane_clis.d.ts +171 -0
  135. package/dist/panes/pane_clis.js +325 -0
  136. package/dist/panes/person_only_panes.d.ts +45 -0
  137. package/dist/panes/person_only_panes.js +117 -0
  138. package/dist/plugin/simulation_living.js +0 -2
  139. package/dist/plugin/simulation_living_engine.d.ts +1 -0
  140. package/dist/plugin/simulation_living_engine.js +1 -0
  141. package/dist/plugin/simulation_living_labels.d.ts +3 -0
  142. package/dist/plugin/simulation_living_labels.js +2 -0
  143. package/dist/router_auth.js +12 -1
  144. package/dist/session.js +26 -1
  145. package/dist/simulation/art/gemini_image.js +11 -5
  146. package/dist/simulation/domains/loader.js +25 -3
  147. package/dist/simulation/living/cold.d.ts +23 -0
  148. package/dist/simulation/living/cold.js +41 -0
  149. package/dist/simulation/living/context.d.ts +591 -1283
  150. package/dist/simulation/living/context.js +378 -244
  151. package/dist/simulation/living/contradictions.d.ts +14 -0
  152. package/dist/simulation/living/contradictions.js +282 -0
  153. package/dist/simulation/living/core/ids.d.ts +53 -0
  154. package/dist/simulation/living/core/ids.js +39 -0
  155. package/dist/simulation/living/core/kind.d.ts +20 -0
  156. package/dist/simulation/living/core/kind.js +15 -0
  157. package/dist/simulation/living/core/laws.d.ts +179 -0
  158. package/dist/simulation/living/core/laws.js +184 -0
  159. package/dist/simulation/living/core/ops.d.ts +257 -0
  160. package/dist/simulation/living/core/ops.js +34 -0
  161. package/dist/simulation/living/definer.d.ts +17 -1
  162. package/dist/simulation/living/definer.js +130 -51
  163. package/dist/simulation/living/definition.d.ts +174 -65
  164. package/dist/simulation/living/definition.js +287 -180
  165. package/dist/simulation/living/director.d.ts +80 -0
  166. package/dist/simulation/living/director.js +363 -0
  167. package/dist/simulation/living/frame.d.ts +108 -21
  168. package/dist/simulation/living/frame.js +111 -66
  169. package/dist/simulation/living/identifiers.d.ts +0 -1
  170. package/dist/simulation/living/identifiers.js +0 -3
  171. package/dist/simulation/living/index.d.ts +18 -9
  172. package/dist/simulation/living/index.js +18 -9
  173. package/dist/simulation/living/inference.d.ts +92 -50
  174. package/dist/simulation/living/inference.js +319 -175
  175. package/dist/simulation/living/knowledge.d.ts +28 -0
  176. package/dist/simulation/living/knowledge.js +73 -0
  177. package/dist/simulation/living/library.json +1177 -0
  178. package/dist/simulation/living/mechanics.d.ts +31 -34
  179. package/dist/simulation/living/mechanics.js +222 -138
  180. package/dist/simulation/living/model-input.d.ts +6 -3
  181. package/dist/simulation/living/model-input.js +18 -26
  182. package/dist/simulation/living/open-world.d.ts +74 -94
  183. package/dist/simulation/living/open-world.js +151 -30
  184. package/dist/simulation/living/phrases.d.ts +3 -0
  185. package/dist/simulation/living/phrases.js +37 -0
  186. package/dist/simulation/living/phrases.json +560 -0
  187. package/dist/simulation/living/projection.d.ts +316 -2
  188. package/dist/simulation/living/projection.js +50 -2
  189. package/dist/simulation/living/prompts/example-spec.json +11 -0
  190. package/dist/simulation/living/prompts/role-text.json +14 -0
  191. package/dist/simulation/living/prompts.d.ts +5 -0
  192. package/dist/simulation/living/prompts.js +275 -0
  193. package/dist/simulation/living/recall.d.ts +2 -2
  194. package/dist/simulation/living/reduce.d.ts +51 -14
  195. package/dist/simulation/living/reduce.js +941 -579
  196. package/dist/simulation/living/replay.d.ts +5 -4
  197. package/dist/simulation/living/replay.js +10 -9
  198. package/dist/simulation/living/runtime.d.ts +135 -25
  199. package/dist/simulation/living/runtime.js +1641 -583
  200. package/dist/simulation/living/scale.d.ts +96 -0
  201. package/dist/simulation/living/scale.js +124 -0
  202. package/dist/simulation/living/script.d.ts +5 -0
  203. package/dist/simulation/living/script.js +115 -0
  204. package/dist/simulation/living/shared-kinds.d.ts +4 -11
  205. package/dist/simulation/living/shared-kinds.js +11 -81
  206. package/dist/simulation/living/space.d.ts +14 -0
  207. package/dist/simulation/living/space.js +132 -0
  208. package/dist/simulation/living/state.d.ts +100 -0
  209. package/dist/simulation/living/state.js +393 -0
  210. package/dist/simulation/living/types.d.ts +829 -512
  211. package/dist/simulation/living/types.js +162 -187
  212. package/dist/simulation/living/world-rules.d.ts +100 -0
  213. package/dist/simulation/living/world-rules.js +267 -0
  214. package/dist/simulation/plugins/loader.js +11 -0
  215. package/dist/skills/loader.js +4 -0
  216. package/dist/tools.d.ts +1 -0
  217. package/dist/tools.js +1 -0
  218. package/dist/ui/ratatui/headless_pane_manager.d.ts +4 -1
  219. package/dist/ui/ratatui/headless_pane_manager.js +13 -9
  220. package/dist/ui/ratatui/pane_relay.js +29 -0
  221. package/dist/ui/ratatui/pane_type.d.ts +10 -0
  222. package/dist/ui/ratatui/pane_type.js +11 -0
  223. package/dist/ui/ratatui/process.d.ts +30 -0
  224. package/dist/ui/ratatui/process.js +133 -19
  225. package/dist/ui/ratatui/protocol.d.ts +124 -2
  226. package/dist/ui/ratatui/protocol.js +35 -0
  227. package/dist/ui/ratatui/relay_policy.js +3 -0
  228. package/dist/ui/ratatui/ztc_launch_trust.d.ts +2 -1
  229. package/dist/ui/ratatui/ztc_launch_trust.js +8 -1
  230. package/dist/ui/terminal_image.d.ts +12 -0
  231. package/dist/ui/terminal_image.js +21 -1
  232. package/dist/utils/codex_project_trust.d.ts +19 -0
  233. package/dist/utils/codex_project_trust.js +37 -0
  234. package/dist/utils/compaction.js +103 -20
  235. package/dist/utils/git_program_files.d.ts +19 -12
  236. package/dist/utils/git_program_files.js +411 -83
  237. package/dist/utils/host_shell.d.ts +10 -1
  238. package/dist/utils/host_shell.js +14 -1
  239. package/dist/utils/mid_turn_compaction.d.ts +2 -0
  240. package/dist/utils/mid_turn_compaction.js +2 -0
  241. package/dist/utils/models.js +6 -1
  242. package/dist/utils/sandbox.d.ts +109 -8
  243. package/dist/utils/sandbox.js +981 -187
  244. package/dist/utils/shell.d.ts +2 -0
  245. package/dist/utils/shell.js +10 -4
  246. package/dist/utils/subprocess_env.d.ts +47 -11
  247. package/dist/utils/subprocess_env.js +107 -15
  248. package/dist/utils/system_ps.d.ts +8 -0
  249. package/dist/utils/system_ps.js +39 -7
  250. package/dist/utils/unattended_compaction.d.ts +9 -0
  251. package/dist/utils/unattended_compaction.js +13 -0
  252. package/dist/utils/ztc_own_state.d.ts +8 -5
  253. package/dist/utils/ztc_own_state.js +17 -11
  254. package/dist/web/mirror_client.js +1 -0
  255. package/dist/web/mirror_stream.d.ts +50 -6
  256. package/dist/web/mirror_stream.js +160 -15
  257. package/dist/workflows/registry.js +3 -1
  258. package/dist/workspace/controller.js +12 -0
  259. package/dist/workspace_collision.d.ts +3 -0
  260. package/dist/workspace_collision.js +14 -1
  261. package/dist/workspace_session_context.js +2 -1
  262. package/dist/zlm-embed.mjs +3823 -1970
  263. package/node_modules/@zerg/model-contracts/README.md +16 -4
  264. package/node_modules/@zerg/model-contracts/index.js +6 -1
  265. package/npm-shrinkwrap.json +1 -1
  266. package/package.json +42 -24
  267. package/packages/model-contracts/README.md +16 -4
  268. package/packages/model-contracts/index.js +6 -1
@@ -8,7 +8,7 @@ import { compactWithJev, collectJevCalls, resolveJevOptions, } from './jev_compa
8
8
  import { createRouterJevAsker } from './jev_client.js';
9
9
  import { DEFAULT_JEV_SETTINGS } from '../config/compaction.js';
10
10
  import { requiredRouterModel } from '../config/router_required.js';
11
- import { isIncompleteModelResponse } from '../agent/completion_state.js';
11
+ import { isIncompleteModelResponse, outputLimitRetryEffort } from '../agent/completion_state.js';
12
12
  import { toolResultText } from '../agent/tool_result_parsing.js';
13
13
  import { BackendHttpError, retryAfterDelayMs } from '../agent/backends/http_error.js';
14
14
  import { isTransportError } from '../agent/backends/transport_errors.js';
@@ -558,24 +558,53 @@ function selectCarriedUserMessages(messages) {
558
558
  const authored = new Map(messages.map(message => [message.id, message]));
559
559
  const realUser = selectRealUserMessages(messages)
560
560
  .map(message => authored.get(message.id) ?? message);
561
- const carried = [];
561
+ if (realUser.length === 0)
562
+ return [];
563
+ const first = realUser[realUser.length - 1];
564
+ const latest = realUser[0];
565
+ const selected = new Map();
562
566
  let used = 0;
567
+ const truncateTo = (message, budget) => {
568
+ const cost = estimateMessageTokens(message);
569
+ const perChar = cost / Math.max(1, message.content.length);
570
+ const keepChars = Math.max(1, Math.floor(budget / (perChar || 0.25)));
571
+ return { ...message, id: crypto.randomUUID(), content: truncate(message.content, keepChars),
572
+ metadata: { ...message.metadata, compactionSourceId: message.id } };
573
+ };
574
+ const firstCost = estimateMessageTokens(first);
575
+ const latestCost = latest.id === first.id ? 0 : estimateMessageTokens(latest);
576
+ if (firstCost + latestCost > HANDOFF_INPUT_TOKEN_LIMIT) {
577
+ const larger = firstCost >= latestCost ? first : latest;
578
+ const other = larger === first ? latest : first;
579
+ const otherCost = larger === first ? latestCost : firstCost;
580
+ selected.set(other.id, other);
581
+ selected.set(larger.id, truncateTo(larger, HANDOFF_INPUT_TOKEN_LIMIT - otherCost));
582
+ used = HANDOFF_INPUT_TOKEN_LIMIT;
583
+ }
584
+ else {
585
+ selected.set(first.id, first);
586
+ used += firstCost;
587
+ if (latest.id !== first.id) {
588
+ selected.set(latest.id, latest);
589
+ used += latestCost;
590
+ }
591
+ }
563
592
  for (const message of realUser) {
593
+ if (selected.has(message.id))
594
+ continue;
564
595
  const cost = estimateMessageTokens(message);
565
596
  if (used + cost > HANDOFF_INPUT_TOKEN_LIMIT) {
566
597
  const remaining = HANDOFF_INPUT_TOKEN_LIMIT - used;
567
598
  if (remaining > 0) {
568
- const perChar = cost / Math.max(1, message.content.length);
569
- const keepChars = Math.max(1, Math.floor(remaining / (perChar || 0.25)));
570
- carried.push({ ...message, id: crypto.randomUUID(), content: truncate(message.content, keepChars),
571
- metadata: { ...message.metadata, compactionSourceId: message.id } });
599
+ selected.set(message.id, truncateTo(message, remaining));
572
600
  }
573
601
  break;
574
602
  }
575
- carried.push(message);
603
+ selected.set(message.id, message);
576
604
  used += cost;
577
605
  }
578
- return carried.reverse();
606
+ return realUser.filter(message => selected.has(message.id)).reverse()
607
+ .map(message => selected.get(message.id));
579
608
  }
580
609
  export function buildHandoffHistory(systemMessage, conversation, summary) {
581
610
  const carried = selectCarriedUserMessages(conversation);
@@ -611,6 +640,8 @@ export function projectHandoffHistory(messages) {
611
640
  */
612
641
  const MAX_HANDOFF_TIMEOUT_MS = 300_000;
613
642
  const MAX_HANDOFF_OVERFLOW_RETRIES = 8;
643
+ const HANDOFF_OUTPUT_LIMIT_RETRY_PROMPT = 'Your previous answer was cut off by the output limit. '
644
+ + 'Write only the handoff summary now, in at most 200 words, with no preamble and no analysis.';
614
645
  /** A failure worth asking again after a pause: rate limits, server errors and dropped connections. */
615
646
  function isTransientHandoffError(error) {
616
647
  if (error instanceof BackendHttpError)
@@ -662,15 +693,21 @@ export function modelHandoffSummarizer(backend, model, options) {
662
693
  const timeoutMs = typeof options.timeoutMs === 'number' && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0
663
694
  ? Math.min(Math.max(1, Math.floor(options.timeoutMs)), MAX_HANDOFF_TIMEOUT_MS)
664
695
  : MAX_HANDOFF_TIMEOUT_MS;
696
+ const requestOptions = options.request;
697
+ let maxTokensOverride;
698
+ let retryPrompt;
699
+ let outputLimitRetried = false;
700
+ let effortOverride;
665
701
  const buildRequest = (history, signal) => ({
666
- ...options.request,
702
+ ...requestOptions,
667
703
  model,
668
- maxTokens: options.maxTokens,
704
+ maxTokens: maxTokensOverride ?? options.maxTokens,
705
+ ...(effortOverride !== undefined ? { codexEffort: effortOverride } : {}),
669
706
  system: options.system,
670
707
  tools: options.tools,
671
708
  messages: [
672
709
  ...history,
673
- { role: 'user', content: options.prompt ?? HANDOFF_PROMPT },
710
+ { role: 'user', content: retryPrompt ?? options.prompt ?? HANDOFF_PROMPT },
674
711
  ],
675
712
  signal,
676
713
  });
@@ -688,8 +725,20 @@ export function modelHandoffSummarizer(backend, model, options) {
688
725
  try {
689
726
  const response = await backend.generate(buildRequest(history, controller.signal));
690
727
  options.onUsage?.(response.usage ?? { inputTokens: 0, outputTokens: 0, totalTokens: 0, estimated: true, unreported: true });
691
- if (isIncompleteModelResponse(response.stopReason))
728
+ if (isIncompleteModelResponse(response.stopReason)) {
729
+ if (!outputLimitRetried) {
730
+ outputLimitRetried = true;
731
+ const capabilities = backend.getModelCapabilities?.(model);
732
+ const lowerEffort = outputLimitRetryEffort(capabilities?.reasoning?.choices, requestOptions?.codexEffort);
733
+ maxTokensOverride = capabilities?.max_output_tokens;
734
+ effortOverride = lowerEffort;
735
+ if (maxTokensOverride !== undefined || lowerEffort !== undefined) {
736
+ retryPrompt = HANDOFF_OUTPUT_LIMIT_RETRY_PROMPT;
737
+ continue;
738
+ }
739
+ }
692
740
  return fallback('model stopped at its output limit');
741
+ }
693
742
  if (response.content.some(block => block.type === 'tool_use'))
694
743
  return fallback('model called a tool instead of writing the handoff');
695
744
  const text = response.content
@@ -982,6 +1031,24 @@ export async function compactMessages(messages, model, summarizer, targetPercent
982
1031
  && estimateConversationTokens([...systemMessages.slice(0, 1), ...recentMessages]) > targetTokens) {
983
1032
  recentMessages = stripOrphanedToolCalls(removeOrphanedToolResults(recentMessages.slice(1)));
984
1033
  }
1034
+ const realUser = selectRealUserMessages(messages);
1035
+ const summaryReserve = 400;
1036
+ const admittedPins = [];
1037
+ for (const candidate of [realUser[0], realUser[realUser.length - 1]]) {
1038
+ if (!candidate || admittedPins.some(message => message.id === candidate.id))
1039
+ continue;
1040
+ const withCandidate = estimateConversationTokens([...systemMessages.slice(0, 1), ...admittedPins, candidate]);
1041
+ if (withCandidate + summaryReserve <= targetTokens)
1042
+ admittedPins.push(candidate);
1043
+ }
1044
+ const outputTokens = (recent) => {
1045
+ const pinned = admittedPins.filter(message => !recent.some(retained => retained.id === message.id));
1046
+ return estimateConversationTokens([...systemMessages.slice(0, 1), ...pinned, ...recent]);
1047
+ };
1048
+ while (recentMessages.length > 0 && outputTokens(recentMessages) > targetTokens) {
1049
+ recentMessages = removeOrphanedToolResults(recentMessages.slice(1));
1050
+ }
1051
+ const pinnedMessages = admittedPins.filter(message => !recentMessages.some(retained => retained.id === message.id));
985
1052
  const retainedIds = new Set(recentMessages.map((message) => message.id));
986
1053
  const oldMessages = asAuthored(nonSystemMessages.filter((message) => !retainedIds.has(message.id)));
987
1054
  if (oldMessages.length === 0) {
@@ -1001,7 +1068,11 @@ export async function compactMessages(messages, model, summarizer, targetPercent
1001
1068
  const summary = await summarizer(oldMessages);
1002
1069
  if (summarizer.handoffWritten === true && historyMode === 'handoff') {
1003
1070
  const next = buildHandoffHistory(systemMessages[0], messages, summary);
1004
- return { messages: next, removed: oldMessages.length, tokensBefore, tokensAfter: estimateConversationTokens(next) };
1071
+ const tokensAfter = estimateConversationTokens(next);
1072
+ if (tokensAfter === tokensBefore) {
1073
+ return { messages, removed: 0, tokensBefore, tokensAfter: tokensBefore };
1074
+ }
1075
+ return { messages: next, removed: oldMessages.length, tokensBefore, tokensAfter };
1005
1076
  }
1006
1077
  // R0 carrier rule: role 'user' (not 'system') so formatMessages keeps it and the
1007
1078
  // summary — the only surviving copy of the original task after the first user
@@ -1015,22 +1086,29 @@ export async function compactMessages(messages, model, summarizer, targetPercent
1015
1086
  timestamp: new Date(),
1016
1087
  metadata: { compactionSummary: true },
1017
1088
  };
1089
+ const pinTask = summary.trim().length > 0;
1090
+ const openingId = realUser[realUser.length - 1]?.id;
1091
+ const carriedPinned = pinnedMessages.map(message => message.id === openingId
1092
+ && message.metadata?.compactionSourceId === undefined
1093
+ ? { ...message, id: crypto.randomUUID(), metadata: { ...message.metadata, compactionSourceId: message.id } }
1094
+ : message);
1018
1095
  // The request itself is carried by the saved task handoff row, which keeps the session's identity; this layout keeps
1019
1096
  // the summary and the recent turns.
1020
- const buildMessages = (summaryContent, recent) => [
1097
+ const buildMessages = (summaryContent, recent, pins) => [
1021
1098
  ...systemMessages.slice(0, 1),
1099
+ ...(pinTask ? (summaryContent ? pins : pinnedMessages) : []),
1022
1100
  ...(summaryContent ? [{ ...summaryMessage, content: summaryContent }] : []),
1023
1101
  ...invalidateNativeHistory(recent),
1024
1102
  ];
1025
1103
  // The longest summary that fits beside `recent`.
1026
- const fitSummary = (recent) => {
1104
+ const fitSummary = (recent, pins) => {
1027
1105
  let low = 0;
1028
1106
  let high = summary.length;
1029
1107
  let fitted = '';
1030
1108
  while (low <= high) {
1031
1109
  const length = Math.floor((low + high) / 2);
1032
1110
  const candidate = length === 0 ? '' : truncate(summary, length);
1033
- const candidateTokens = estimateConversationTokens(buildMessages(candidate, recent));
1111
+ const candidateTokens = estimateConversationTokens(buildMessages(candidate, recent, pins));
1034
1112
  if (candidateTokens <= targetTokens) {
1035
1113
  fitted = candidate;
1036
1114
  low = length + 1;
@@ -1041,15 +1119,20 @@ export async function compactMessages(messages, model, summarizer, targetPercent
1041
1119
  }
1042
1120
  return fitted;
1043
1121
  };
1044
- const fittedSummary = fitSummary(recentMessages);
1045
- const newMessages = buildMessages(fittedSummary, recentMessages);
1122
+ let layoutPins = carriedPinned;
1123
+ let fittedSummary = fitSummary(recentMessages, layoutPins);
1124
+ if (summary.trim().length > 0 && fittedSummary.length === 0 && pinnedMessages.length > 0) {
1125
+ layoutPins = [];
1126
+ fittedSummary = fitSummary(recentMessages, layoutPins);
1127
+ }
1128
+ const newMessages = buildMessages(fittedSummary, recentMessages, layoutPins);
1046
1129
  const tokensAfter = estimateConversationTokens(newMessages);
1047
1130
  // The split measures recent turns shortened and keeps them whole, so they can crowd the summary out. Shortening
1048
1131
  // them makes room again; the summary is fitted to what is kept, never dropped while room can be made for it.
1049
1132
  if (tokensAfter > targetTokens || fittedSummary.length < summary.length) {
1050
1133
  const deflated = deflateMessages(recentMessages);
1051
- const deflatedSummary = fitSummary(deflated);
1052
- const shrunk = buildMessages(deflatedSummary, deflated);
1134
+ const deflatedSummary = fitSummary(deflated, layoutPins);
1135
+ const shrunk = buildMessages(deflatedSummary, deflated, layoutPins);
1053
1136
  const shrunkTokens = estimateConversationTokens(shrunk);
1054
1137
  if (shrunkTokens < tokensAfter || deflatedSummary.length > fittedSummary.length) {
1055
1138
  return { messages: shrunk, removed: oldMessages.length, tokensBefore, tokensAfter: shrunkTokens };
@@ -25,6 +25,8 @@ export interface GitProgramFiles {
25
25
  * command broke of it (putBackBrokenRepositories).
26
26
  */
27
27
  repositories: KnownRepositoryState[];
28
+ /** Outermost writable roots from which the step after a command confines every host operation without following links. */
29
+ roots: string[];
28
30
  }
29
31
  /** HEAD as git takes it for a repository's: a file's text (as its bytes) and mode, or where a link leads (refs/...). */
30
32
  export type WholeHead = {
@@ -68,6 +70,17 @@ export interface GitProgramFilesOptions {
68
70
  /** The folders whose work trees a bounded walk looks for (default: the writable roots); none for a profile that names none. */
69
71
  walk?: readonly string[];
70
72
  }
73
+ /**
74
+ * ROOTS, each as given (absolute: the real path one look at it found, utils/sandbox.ts's profileRootLooks), but those
75
+ * inside another of them: a root inside another root is that root's (as bubblewrap binds it), so the pins from a root
76
+ * down to a repository, and the walk for work trees, run from the outermost root, and none of them is resolved again.
77
+ * They stopped at the innermost root, so under allowedPaths [ws, ws/proj] nothing pinned ws/proj, which bubblewrap no
78
+ * longer binds as a mount point of its own: a command renamed it away, with the repository's protected files, and made a
79
+ * repository of its own there whose core.fsmonitor the person's git ran; and each root, resolved again by its path, had a
80
+ * folder above a nested root that a command swapped for a link lead the walk, the pins and the step after the command to
81
+ * a repository outside every root (appstore's NESTED-GIT-PIN and RESIDUAL-SCOPE).
82
+ */
83
+ export declare function outermostRoots(roots: readonly string[]): string[];
71
84
  /**
72
85
  * Where ZTC keeps knownGitDirectories for the ZTCs started after it: in its own state under HOME (~/.ztc), which no
73
86
  * command under a profile that limits the agent reaches (utils/ztc_own_state.ts), and not in its config folder, which a
@@ -85,23 +98,17 @@ export declare function loadKnownRepositoryRecord(): void;
85
98
  /**
86
99
  * What a sandboxed command working in DIRECTORIES (its cwd, the session's, the writable roots), with WRITE_ROOTS
87
100
  * writable, may not change of the repositories there and of those a walk of the writable roots finds, and of every
88
- * repository an earlier plan of this process found (knownGitDirectories).
101
+ * repository an earlier plan of this process found (knownGitDirectories). WRITE_ROOTS are the real paths one look at each
102
+ * root found (utils/sandbox.ts's profileRootLooks), which the plan takes as they are, the outermost of them alone
103
+ * (outermostRoots): it resolved each again by its path, and stopped its pins at a root inside another.
89
104
  */
90
105
  export declare function gitProgramFiles(directories: readonly string[], writeRoots: readonly string[], options?: GitProgramFilesOptions): GitProgramFiles;
91
106
  /**
92
107
  * The step after a command, on both backends (utils/sandbox.ts), once it has ended and before anything reads its result
93
108
  * or any other git runs there: each repository the plan knew (FILES.repositories) that git takes for none now, put back
94
- * as a plan last saw it whole. A command may write a repository's HEAD, refs and objects (checkouts, commits and fetches
95
- * do), and git takes a git directory whose HEAD names no ref or commit, or whose refs or objects folder it cannot enter,
96
- * for no repository: in a work tree whose .git that is, it looks for one in the folders above, where the same command
97
- * may have made one (git init, which a command may run anywhere it writes, or a .git file naming a git directory of its
98
- * own), and the person's git there, or a host service's, would read that config and start what it names (the walk-up
99
- * route of the R3e review). So HEAD is put back as it was, the permissions of the git directory and of the folders from
100
- * below the writable root down to the work tree too (bwrap lets a command change a pinned folder's; git, in a shell
101
- * already in a folder it cannot reach from the top, looks above on Linux), and a refs or objects folder git cannot enter
102
- * is an empty one again: one that is missing made new, one git may not enter moved aside first. A repository git takes
103
- * for one is the command's as it left it: a checkout, a commit, a branch switch, a detached HEAD, refs packed or
104
- * emptied. What ZTC did, for the command's result.
109
+ * as a plan last saw it whole. Every host mutation walks from the outermost writable root without following links
110
+ * (`O_NOFOLLOW` per component via `dir_fd`), so a folder swapped for a link by a background command cannot redirect
111
+ * chmod, HEAD rewrite, or directory restoration outside the workspace roots. What ZTC did, for the command's result.
105
112
  */
106
113
  export declare function putBackBrokenRepositories(files: GitProgramFiles): string[];
107
114
  /**