@zergai/ztc 0.23.0-beta.1 → 0.24.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 (146) hide show
  1. package/README.md +299 -13
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +2 -2
  7. package/dist/agent/agent.js +57 -14
  8. package/dist/agent/backends/http_error.d.ts +2 -0
  9. package/dist/agent/backends/http_error.js +2 -0
  10. package/dist/agent/backends/router_gate.d.ts +3 -2
  11. package/dist/agent/backends/router_gate.js +5 -4
  12. package/dist/agent/backends/router_keys.d.ts +14 -0
  13. package/dist/agent/backends/router_keys.js +19 -0
  14. package/dist/agent/backends/router_refusal.d.ts +5 -3
  15. package/dist/agent/backends/router_refusal.js +28 -6
  16. package/dist/agent/backends/types.d.ts +1 -1
  17. package/dist/agent/backends/zrouter_stream.js +10 -6
  18. package/dist/agent/commands/agent_cli.d.ts +11 -1
  19. package/dist/agent/commands/agent_cli.js +295 -38
  20. package/dist/agent/commands/diff.js +4 -1
  21. package/dist/agent/commands/help.js +4 -1
  22. package/dist/agent/commands/plan.js +3 -1
  23. package/dist/agent/commands/session_redaction.d.ts +16 -0
  24. package/dist/agent/commands/session_redaction.js +77 -0
  25. package/dist/agent/commands/settings.js +144 -0
  26. package/dist/agent/commands/types.d.ts +5 -0
  27. package/dist/agent/commands/usage_spec.d.ts +4 -0
  28. package/dist/agent/commands/usage_spec.js +10 -4
  29. package/dist/agent/runtime/policy.d.ts +25 -0
  30. package/dist/agent/runtime/policy.js +154 -26
  31. package/dist/agent/runtime/source_verification.js +6 -2
  32. package/dist/agent/runtime/tool_runtime.js +81 -3
  33. package/dist/agent/tools/apply_patch.js +678 -131
  34. package/dist/agent/tools/bus_message.d.ts +26 -1
  35. package/dist/agent/tools/bus_message.js +126 -10
  36. package/dist/agent/tools/file.d.ts +16 -1
  37. package/dist/agent/tools/file.js +43 -5
  38. package/dist/agent/tools/index.d.ts +1 -1
  39. package/dist/agent/tools/index.js +1 -1
  40. package/dist/agent/tools/pane.js +5 -0
  41. package/dist/agent/tools/search.js +5 -1
  42. package/dist/agent/tools/supervision.js +16 -2
  43. package/dist/agent/tools/types.d.ts +22 -0
  44. package/dist/app/mirror_startup.d.ts +7 -5
  45. package/dist/app/mirror_startup.js +7 -5
  46. package/dist/app/navigator_mirrors.d.ts +20 -0
  47. package/dist/app/navigator_mirrors.js +36 -0
  48. package/dist/app/workspace_layout_controller.d.ts +11 -2
  49. package/dist/app/workspace_layout_controller.js +13 -2
  50. package/dist/batch/worktree.js +9 -1
  51. package/dist/cli_ratatui.d.ts +264 -12
  52. package/dist/cli_ratatui.js +1198 -103
  53. package/dist/config/types.d.ts +29 -0
  54. package/dist/desktop/daily/source_baseline.js +3 -1
  55. package/dist/diagnostics/session_export.d.ts +1 -0
  56. package/dist/diagnostics/session_export.js +229 -26
  57. package/dist/emulation/tool_adapters.js +42 -5
  58. package/dist/headless.js +24 -5
  59. package/dist/instance_registry.d.ts +7 -0
  60. package/dist/mcp/workspace_server.d.ts +12 -1
  61. package/dist/mcp/workspace_server.js +75 -8
  62. package/dist/panes/agent_cli.d.ts +60 -3
  63. package/dist/panes/agent_cli.js +169 -16
  64. package/dist/panes/agent_pane_sessions.d.ts +22 -0
  65. package/dist/panes/agent_pane_sessions.js +111 -0
  66. package/dist/panes/agent_panes.d.ts +77 -3
  67. package/dist/panes/agent_panes.js +199 -10
  68. package/dist/panes/agent_profiles.d.ts +5 -0
  69. package/dist/panes/agent_profiles.js +7 -0
  70. package/dist/panes/agent_resume.d.ts +134 -0
  71. package/dist/panes/agent_resume.js +155 -0
  72. package/dist/panes/agent_sessions/claude_head.d.ts +32 -0
  73. package/dist/panes/agent_sessions/claude_head.js +122 -0
  74. package/dist/panes/agent_sessions/claude_store.d.ts +59 -0
  75. package/dist/panes/agent_sessions/claude_store.js +223 -0
  76. package/dist/panes/agent_sessions/codex_head.d.ts +55 -0
  77. package/dist/panes/agent_sessions/codex_head.js +161 -0
  78. package/dist/panes/agent_sessions/codex_store.d.ts +43 -0
  79. package/dist/panes/agent_sessions/codex_store.js +187 -0
  80. package/dist/panes/agent_sessions/controller.d.ts +74 -0
  81. package/dist/panes/agent_sessions/controller.js +110 -0
  82. package/dist/panes/agent_sessions/cut_json.d.ts +14 -0
  83. package/dist/panes/agent_sessions/cut_json.js +109 -0
  84. package/dist/panes/agent_sessions/limits.d.ts +48 -0
  85. package/dist/panes/agent_sessions/limits.js +48 -0
  86. package/dist/panes/agent_sessions/scan.d.ts +49 -0
  87. package/dist/panes/agent_sessions/scan.js +86 -0
  88. package/dist/panes/agent_sessions/store_fs.d.ts +51 -0
  89. package/dist/panes/agent_sessions/store_fs.js +128 -0
  90. package/dist/panes/agent_sessions/stores.d.ts +36 -0
  91. package/dist/panes/agent_sessions/stores.js +89 -0
  92. package/dist/panes/agent_sessions/title.d.ts +9 -0
  93. package/dist/panes/agent_sessions/title.js +51 -0
  94. package/dist/panes/agent_sessions/types.d.ts +48 -0
  95. package/dist/panes/agent_sessions/types.js +2 -0
  96. package/dist/panes/reply_arbitrator.d.ts +39 -0
  97. package/dist/panes/reply_arbitrator.js +185 -0
  98. package/dist/panes/reply_modes.d.ts +291 -0
  99. package/dist/panes/reply_modes.js +598 -0
  100. package/dist/runtime_info.js +11 -2
  101. package/dist/session.js +4 -2
  102. package/dist/simulation/living/context.d.ts +8 -8
  103. package/dist/simulation/living/types.d.ts +5 -5
  104. package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
  105. package/dist/ui/ratatui/ipc_path.d.ts +5 -0
  106. package/dist/ui/ratatui/ipc_path.js +23 -3
  107. package/dist/ui/ratatui/pane_credential_broker.d.ts +23 -8
  108. package/dist/ui/ratatui/pane_credential_broker.js +49 -14
  109. package/dist/ui/ratatui/pane_relay.d.ts +5 -2
  110. package/dist/ui/ratatui/pane_relay.js +86 -19
  111. package/dist/ui/ratatui/process.js +3 -0
  112. package/dist/ui/ratatui/protocol.d.ts +50 -1
  113. package/dist/ui/ratatui/protocol.js +56 -0
  114. package/dist/ui/ratatui/relay_policy.d.ts +39 -0
  115. package/dist/ui/ratatui/relay_policy.js +94 -0
  116. package/dist/ui/ratatui/screen_privacy.d.ts +15 -0
  117. package/dist/ui/ratatui/screen_privacy.js +24 -0
  118. package/dist/ui/scrollback.js +8 -0
  119. package/dist/ui/widgets/agent_sessions_panel.d.ts +139 -0
  120. package/dist/ui/widgets/agent_sessions_panel.js +542 -0
  121. package/dist/ui/widgets/log_view.d.ts +5 -1
  122. package/dist/ui/widgets/log_view.js +40 -4
  123. package/dist/utils/atomic_write.js +9 -11
  124. package/dist/utils/canonical_path.d.ts +19 -0
  125. package/dist/utils/canonical_path.js +44 -0
  126. package/dist/utils/compaction.d.ts +2 -1
  127. package/dist/utils/compaction.js +3 -1
  128. package/dist/utils/git_directory_names.d.ts +51 -0
  129. package/dist/utils/git_directory_names.js +429 -0
  130. package/dist/utils/temporary_write_root.d.ts +6 -1
  131. package/dist/utils/temporary_write_root.js +32 -2
  132. package/dist/utils/tool_result_message.d.ts +4 -1
  133. package/dist/utils/tool_result_message.js +6 -2
  134. package/dist/web/bus_hold.d.ts +70 -0
  135. package/dist/web/bus_hold.js +118 -0
  136. package/dist/web/mirror_client.d.ts +7 -3
  137. package/dist/web/mirror_client.js +61 -23
  138. package/dist/web/mirror_route_gate.d.ts +40 -0
  139. package/dist/web/mirror_route_gate.js +71 -0
  140. package/dist/web/mirror_stream.d.ts +147 -22
  141. package/dist/web/mirror_stream.js +350 -83
  142. package/dist/web/pane_credentials.d.ts +32 -1
  143. package/dist/web/pane_credentials.js +62 -2
  144. package/dist/workspace_collision.js +11 -2
  145. package/dist/zlm-embed.mjs +940 -273
  146. package/package.json +34 -12
@@ -17,6 +17,7 @@ import { customPaneOptions, storedCustomPaneOptions, withCustomPaneOptions, } fr
17
17
  import { getMcpServerStatuses } from '../../mcp/registry.js';
18
18
  import { claudeBadgesOn } from '../../panes/claude_notifications.js';
19
19
  import { agentPermissionsSetting } from '../../panes/agent_cli.js';
20
+ import { DEFAULT_REPLY_MODE, MAX_ARBITRATOR_TIMEOUT_SECONDS, formatReplyModeSetting, parseReplyArbitrator, parseReplyMode, replyModeRefusal, replyModeSettings, ReplyModeError, } from '../../panes/reply_modes.js';
20
21
  import { CLAUDE_SUBSCRIPTION_POLICY, isRetiredModel, isRetiredProvider, retiredProviderMessage } from '../../config/retired_routes.js';
21
22
  import { subsCommand } from './subs.js';
22
23
  import { modelForProviderSwitch } from './provider_model_defaults.js';
@@ -941,6 +942,32 @@ export async function buildSettingsCategories(ctx) {
941
942
  ],
942
943
  description: 'Claude Code and Codex panes you open. Panes an agent opens always ask. A permission flag you give a pane yourself still wins; delegated workers always stay read-only.',
943
944
  },
945
+ {
946
+ name: 'panesAgentReplyMode',
947
+ label: 'Agent reply mode',
948
+ value: formatReplyModeSetting(replyModeSettings(config.panes).mode),
949
+ type: 'text',
950
+ placeholder: formatReplyModeSetting(DEFAULT_REPLY_MODE),
951
+ description: 'How Main answers a Claude Code or Codex pane by itself when the pane that starts the exchange names no reply mode. '
952
+ + '"capped N": N automatic answers with no message from you, the last saying so, then none until your next message here '
953
+ + '(default capped 5). "uncapped": every message. "arbitrator NAME": before each answer after the first, the arbitrator '
954
+ + 'decides whether the exchange goes on; "model" is Main\'s own model, or name one of your reply arbitrators.',
955
+ },
956
+ {
957
+ name: 'panesReplyArbitrators',
958
+ label: 'Reply arbitrators',
959
+ value: describeReplyArbitrators(config),
960
+ // Informational row, as Custom pane options is: Enter opens the manager that owns the list.
961
+ type: 'select',
962
+ options: [
963
+ {
964
+ value: describeReplyArbitrators(config),
965
+ label: describeReplyArbitrators(config),
966
+ description: 'The arbitrators a reply mode may name besides "model": a model on Main\'s route, or an HTTP(S) endpoint. '
967
+ + 'Only these read an exchange, never one an agent names. Enter to add or remove one.',
968
+ },
969
+ ],
970
+ },
944
971
  ],
945
972
  },
946
973
  {
@@ -1117,6 +1144,101 @@ function describeCustomPaneOptions(config) {
1117
1144
  ? `${usable.length} offered, ${unusable} without a command`
1118
1145
  : `${usable.length} option${usable.length === 1 ? '' : 's'}`;
1119
1146
  }
1147
+ /** Summary for the reply arbitrators row: their names, or "none". */
1148
+ function describeReplyArbitrators(config) {
1149
+ const arbitrators = replyModeSettings(config.panes).arbitrators;
1150
+ if (arbitrators.length === 0)
1151
+ return 'none';
1152
+ return arbitrators.map(arbitrator => arbitrator.name).join(', ');
1153
+ }
1154
+ /** What a reply arbitrator is, for its row in the manager. */
1155
+ function describeReplyArbitrator(arbitrator) {
1156
+ const timeout = arbitrator.timeoutSeconds === undefined ? '' : `, ${arbitrator.timeoutSeconds} s to decide`;
1157
+ return arbitrator.kind === 'http' ? `HTTP: ${arbitrator.url}${timeout}`
1158
+ : `model: ${arbitrator.provider ? `${arbitrator.provider} / ` : ''}${arbitrator.model}${timeout}`;
1159
+ }
1160
+ /**
1161
+ * Add and remove the reply arbitrators, the person's only: an agent can name one of them in a reply mode, never set one
1162
+ * up. A select loop, as the custom pane options manager is, that re-reads the config on each pass; `reopen` hands the
1163
+ * person back to /settings when they are done.
1164
+ */
1165
+ function openReplyArbitratorManager(ctx, reopen) {
1166
+ const stored = () => replyModeSettings(ctx.config.get().panes).arbitrators;
1167
+ const showList = () => {
1168
+ const arbitrators = stored();
1169
+ ctx.select.showSelect({
1170
+ title: 'Reply arbitrators',
1171
+ question: 'Before each automatic answer after the first, an exchange with the reply mode "arbitrator NAME" asks this one whether to go on.',
1172
+ type: 'select',
1173
+ options: [
1174
+ ...arbitrators.map(arbitrator => ({ value: `remove:${arbitrator.name}`, label: `Remove ${arbitrator.name}`, description: describeReplyArbitrator(arbitrator) })),
1175
+ { value: 'add_model', label: 'Add a model arbitrator…', description: 'A model on Main\'s route, asked a fixed short prompt' },
1176
+ { value: 'add_http', label: 'Add an HTTP arbitrator…', description: 'An endpoint that answers a POST of the exchange\'s summary with {continue, reason}' },
1177
+ { value: 'done', label: 'Done' },
1178
+ ],
1179
+ }, (value) => {
1180
+ if (value === 'add_model' || value === 'add_http') {
1181
+ addArbitrator(value === 'add_model' ? 'model' : 'http');
1182
+ return;
1183
+ }
1184
+ if (typeof value === 'string' && value.startsWith('remove:')) {
1185
+ const name = value.slice('remove:'.length);
1186
+ save(stored().filter(arbitrator => arbitrator.name !== name), `Removed the reply arbitrator "${name}".`);
1187
+ return;
1188
+ }
1189
+ reopen?.();
1190
+ });
1191
+ };
1192
+ const save = (next, note) => {
1193
+ ctx.config.set('panes', { ...ctx.config.get().panes, replyArbitrators: next });
1194
+ void (async () => {
1195
+ await ctx.config.save();
1196
+ ctx.addMessage({ role: 'system', content: `✓ ${note}` });
1197
+ showList();
1198
+ })();
1199
+ };
1200
+ const addArbitrator = (kind) => {
1201
+ const timeoutQuestion = { name: 'timeoutSeconds', question: `Seconds it has to decide (1-${MAX_ARBITRATOR_TIMEOUT_SECONDS}; blank for 20)`,
1202
+ header: 'Timeout', type: 'text', required: false };
1203
+ ctx.questionnaire.showQuestionnaire({
1204
+ title: kind === 'model' ? 'Add a model arbitrator' : 'Add an HTTP arbitrator',
1205
+ questions: [
1206
+ { name: 'name', question: 'Name, as a reply mode names it ("arbitrator NAME")', header: 'Name', type: 'text', required: true },
1207
+ ...(kind === 'model'
1208
+ ? [{ name: 'model', question: 'Model, as /model lists it', header: 'Model', type: 'text', required: true },
1209
+ { name: 'provider', question: 'Provider, as /provider lists it (blank for Main\'s)', header: 'Provider', type: 'text', required: false }]
1210
+ : [{ name: 'url', question: 'Endpoint URL (https, or http for localhost)', header: 'URL', type: 'text', required: true }]),
1211
+ timeoutQuestion,
1212
+ ],
1213
+ }, (answers) => {
1214
+ if (!answers) {
1215
+ showList();
1216
+ return;
1217
+ }
1218
+ const field = (name) => String(answers[name] ?? '').trim();
1219
+ let arbitrator;
1220
+ try {
1221
+ arbitrator = parseReplyArbitrator({
1222
+ name: field('name'), kind,
1223
+ ...(kind === 'model' ? { model: field('model'), provider: field('provider') } : { url: field('url') }),
1224
+ ...(field('timeoutSeconds') ? { timeoutSeconds: field('timeoutSeconds') } : {}),
1225
+ });
1226
+ }
1227
+ catch (error) {
1228
+ ctx.addMessage({ role: 'system', content: `✗ ${error instanceof Error ? error.message : String(error)}` });
1229
+ showList();
1230
+ return;
1231
+ }
1232
+ if (stored().some(other => other.name === arbitrator.name)) {
1233
+ ctx.addMessage({ role: 'system', content: `✗ A reply arbitrator is named "${arbitrator.name}" already; remove it first, or pick another name.` });
1234
+ showList();
1235
+ return;
1236
+ }
1237
+ save([...stored(), arbitrator], `Added the reply arbitrator "${arbitrator.name}" (${describeReplyArbitrator(arbitrator)}).`);
1238
+ });
1239
+ };
1240
+ showList();
1241
+ }
1120
1242
  /**
1121
1243
  * Add, edit, and remove the chooser's custom options.
1122
1244
  *
@@ -1319,6 +1441,25 @@ function applySettingChange(ctx, setting, value, selection) {
1319
1441
  throw new Error('Claude Code and Codex permissions must be bypass or ask.');
1320
1442
  ctx.config.set('panes', { ...ctx.config.get().panes, agentPermissions: value });
1321
1443
  break;
1444
+ case 'panesAgentReplyMode': {
1445
+ let mode;
1446
+ try {
1447
+ mode = parseReplyMode(value.trim() || formatReplyModeSetting(DEFAULT_REPLY_MODE));
1448
+ }
1449
+ catch (error) {
1450
+ if (error instanceof ReplyModeError)
1451
+ throw new Error(`Agent reply mode: ${error.message}`);
1452
+ throw error;
1453
+ }
1454
+ const refused = replyModeRefusal(mode, replyModeSettings(ctx.config.get().panes).arbitrators);
1455
+ if (refused)
1456
+ throw new Error(`Agent reply mode: ${refused}`);
1457
+ ctx.config.set('panes', { ...ctx.config.get().panes, agentReplyMode: mode });
1458
+ break;
1459
+ }
1460
+ case 'panesReplyArbitrators':
1461
+ // Only the manager on this row (Enter) writes the list, as it is for custom pane options.
1462
+ throw new Error('Reply arbitrators are added and removed from the manager on this row (Enter).');
1322
1463
  case 'authMode':
1323
1464
  if (ctx.config.setAuthMode)
1324
1465
  ctx.config.setAuthMode(value);
@@ -2304,6 +2445,9 @@ async function openSettings(ctx, open = {}) {
2304
2445
  if (setting.name === 'panesCustomOptions') {
2305
2446
  setting.onActivate = () => openCustomPaneManager(ctx, () => showSettings('custom pane options'));
2306
2447
  }
2448
+ if (setting.name === 'panesReplyArbitrators') {
2449
+ setting.onActivate = () => openReplyArbitratorManager(ctx, () => showSettings('reply arbitrators'));
2450
+ }
2307
2451
  if (setting.name === 'factoryReset') {
2308
2452
  setting.onActivate = () => openFactoryResetConfirmation(ctx, () => openSettings(ctx, { category: PROFILE }));
2309
2453
  }
@@ -567,6 +567,11 @@ export interface CommandContext {
567
567
  settingsPanel?: SettingsPanelController;
568
568
  statusLinePanel?: StatusLinePanelController;
569
569
  resumePanel?: ResumePanelController;
570
+ /**
571
+ * The person's Claude Code and Codex sessions, for /claude and /codex resume: only Main has it, never a headless
572
+ * run, the classic renderer or a pane (see panes/agent_sessions/controller.ts).
573
+ */
574
+ agentSessions?: import('../../panes/agent_sessions/controller.js').AgentSessionsController;
570
575
  /** Explicit user history replacement; absent in renderers without a picker. */
571
576
  rewindPanel?: {
572
577
  open: () => void;
@@ -5,6 +5,10 @@ export interface SlashUsageVariant {
5
5
  export interface SlashUsageSpec {
6
6
  default: string;
7
7
  variants?: SlashUsageVariant[];
8
+ /** Match variants' words exactly, as a command that reads them in one case does (default: in any case). */
9
+ caseSensitive?: boolean;
10
+ /** Leading arguments that start with this are not counted, as /claude's and /codex's @profile isn't. */
11
+ skipLeading?: string;
8
12
  }
9
13
  export type SlashUsage = string | SlashUsageSpec | undefined;
10
14
  export interface SlashCommandUsage {
@@ -1,19 +1,25 @@
1
1
  export function resolveSlashUsage(usage, args) {
2
2
  if (!usage || typeof usage === 'string')
3
3
  return usage;
4
+ let first = 0;
5
+ const skip = usage.skipLeading;
6
+ while (skip && first < args.length && args[first].startsWith(skip))
7
+ first += 1;
8
+ const counted = args.slice(first);
4
9
  for (const variant of usage.variants ?? []) {
5
- if (matchesVariant(variant, args))
10
+ if (matchesVariant(variant, counted, usage.caseSensitive === true))
6
11
  return variant.usage;
7
12
  }
8
13
  return usage.default;
9
14
  }
10
- function matchesVariant(variant, args) {
15
+ function matchesVariant(variant, args, caseSensitive) {
11
16
  const conditions = variant.when ?? {};
17
+ const fold = (word) => (caseSensitive ? word : word.toLowerCase());
12
18
  return Object.entries(conditions).every(([key, values]) => {
13
19
  const index = Number(key);
14
20
  if (!Number.isInteger(index) || index < 0)
15
21
  return false;
16
- const arg = (args[index] ?? '').toLowerCase();
17
- return values.map(value => value.toLowerCase()).includes(arg);
22
+ const arg = fold(args[index] ?? '');
23
+ return values.map(fold).includes(arg);
18
24
  });
19
25
  }
@@ -6,6 +6,17 @@ export interface ToolPolicyRequest {
6
6
  capabilities: ToolCapability[];
7
7
  /** Host-declared effective directory, after hooks and adapter mapping. */
8
8
  executionCwd?: string;
9
+ /** Host-declared shell text the call runs, after adapter mapping (exec_command runs `cmd` before `command`). The
10
+ * shell policy checks it in place of a `command` or `checked` argument. */
11
+ executionCommand?: string;
12
+ /** The path arguments are files the call creates, changes or deletes (a tool's writePaths), not directories it
13
+ * reads or runs in. */
14
+ writeTargets?: boolean;
15
+ /** Every path the whole call writes, deletes or moves (absolute, the request's own path among them). The
16
+ * git-directory check reads it so a set that completes a git directory across its paths is refused as one. Pass
17
+ * the same array for each of a call's paths, and a fresh one for each admission pass: the policy indexes it once
18
+ * per array, against the disk it sees then. */
19
+ writeSet?: readonly string[];
9
20
  }
10
21
  export interface ToolPolicyDecision {
11
22
  allowed: boolean;
@@ -23,9 +34,23 @@ export declare class CapabilityPolicy implements Policy {
23
34
  private permissions;
24
35
  private profile?;
25
36
  private cwd;
37
+ /** Each write set a caller names, resolved once, so admitting a call's N paths reads its set once, not N times. */
38
+ private readonly resolvedWriteSets;
26
39
  constructor(permissions?: Partial<Record<string, boolean>>, profile?: ZTCPermissionProfile, cwd?: string);
27
40
  evaluateTool(request: ToolPolicyRequest): ToolPolicyDecision;
28
41
  private evaluatePathPolicy;
42
+ /**
43
+ * Rules for the files a call writes, under a profile that limits the agent. Such a write may not reach git's own
44
+ * directory: a setting there (a filter, core.fsmonitor) is a command any git ZTC starts in that work tree runs as
45
+ * ZTC, outside the profile and any OS sandbox. Nor may it replace an allowed root itself when that root is a
46
+ * directory (or does not exist yet), since an atomic write makes its temporary file beside its target, which for
47
+ * such a root is outside it.
48
+ */
49
+ private evaluateWriteTargets;
50
+ /** `named` resolved against this policy's working directory, once per array (a fresh one each admission pass). */
51
+ private resolvedWriteSet;
52
+ /** Whether the agent works under limits that a command run through git could step past: paths or shell. */
53
+ private limitsAgent;
29
54
  private evaluateShellPolicy;
30
55
  private evaluateNetworkPolicy;
31
56
  }
@@ -1,9 +1,11 @@
1
- import { realpathSync } from 'node:fs';
2
1
  import { ToolCapability } from './capabilities.js';
2
+ import { lstatSync } from 'fs';
3
3
  import { homedir } from 'os';
4
- import { resolve, isAbsolute, sep, dirname, basename } from 'path';
4
+ import { resolve, isAbsolute, relative, sep } from 'path';
5
5
  import { parseCheckedCommandPlan } from './checked_commands.js';
6
6
  import { formatCheckedStageCommand } from '../../utils/checked_shell.js';
7
+ import { canonicalPath, isWellFormedText, sameFileKey } from '../../utils/canonical_path.js';
8
+ import { gitDirectoryComponent, gitDirectoryPlantedByWriteSet, linkedGitDirectoryHolding } from '../../utils/git_directory_names.js';
7
9
  export class AllowAllPolicy {
8
10
  evaluateTool() {
9
11
  return { allowed: true };
@@ -13,6 +15,8 @@ export class CapabilityPolicy {
13
15
  permissions;
14
16
  profile;
15
17
  cwd;
18
+ /** Each write set a caller names, resolved once, so admitting a call's N paths reads its set once, not N times. */
19
+ resolvedWriteSets = new WeakMap();
16
20
  constructor(permissions, profile, cwd = process.cwd()) {
17
21
  this.permissions = {
18
22
  file_read: true,
@@ -41,6 +45,10 @@ export class CapabilityPolicy {
41
45
  if (!pathDecision.allowed) {
42
46
  return pathDecision;
43
47
  }
48
+ const targetDecision = this.evaluateWriteTargets(request);
49
+ if (!targetDecision.allowed) {
50
+ return targetDecision;
51
+ }
44
52
  const shellDecision = this.evaluateShellPolicy(request);
45
53
  if (!shellDecision.allowed) {
46
54
  return shellDecision;
@@ -56,6 +64,10 @@ export class CapabilityPolicy {
56
64
  if (!this.profile || !request.capabilities.some(capability => (capability === ToolCapability.FILE_READ || capability === ToolCapability.FILE_WRITE))) {
57
65
  return { allowed: true };
58
66
  }
67
+ const unreadable = nonStringPathArgument(request.args);
68
+ if (unreadable !== null) {
69
+ return { allowed: false, reason: `Permission denied: path argument must be a string (${unreadable})` };
70
+ }
59
71
  const paths = extractPathArgs(request.args, request.executionCwd);
60
72
  if (paths.length === 0) {
61
73
  return { allowed: true };
@@ -63,9 +75,20 @@ export class CapabilityPolicy {
63
75
  const deniedRoots = (this.profile.deniedPaths || []).map(path => normalizeRoot(path, this.cwd));
64
76
  const allowedRoots = (this.profile.allowedPaths || []).map(path => normalizeRoot(path, this.cwd));
65
77
  for (const path of paths) {
78
+ // Node writes a lone surrogate as U+FFFD, so such a path names a file other than the one its string spells.
79
+ if (!isWellFormedText(path)) {
80
+ return { allowed: false, reason: `Permission denied: a path must be well-formed Unicode text (${JSON.stringify(path)})` };
81
+ }
66
82
  const absolutePath = normalizeRoot(path, this.cwd);
67
83
  const allowed = allowedRoots.filter(root => isWithinRoot(absolutePath, root));
68
- const denied = deniedRoots.filter(root => isWithinRoot(absolutePath, root));
84
+ // Canonical paths carry each existing component as the filesystem
85
+ // stores it, but a denied root that does not exist yet has no stored
86
+ // spelling: on a volume that ignores case or Unicode normalization,
87
+ // creating SECRETS or café (decomposed) creates the denied secrets or
88
+ // café. A denial therefore matches every spelling that can name the
89
+ // same file. An allowance stays exact, since on a filesystem that keeps
90
+ // those spellings apart, folding would allow a different directory.
91
+ const denied = deniedRoots.filter(root => isWithinRoot(sameFileKey(absolutePath), sameFileKey(root)));
69
92
  const exception = this.profile.pathPrecedence === 'specific' && allowed.some(root => denied.every(blocked => root.length > blocked.length));
70
93
  if (denied.length > 0 && !exception) {
71
94
  return {
@@ -82,15 +105,94 @@ export class CapabilityPolicy {
82
105
  }
83
106
  return { allowed: true };
84
107
  }
108
+ /**
109
+ * Rules for the files a call writes, under a profile that limits the agent. Such a write may not reach git's own
110
+ * directory: a setting there (a filter, core.fsmonitor) is a command any git ZTC starts in that work tree runs as
111
+ * ZTC, outside the profile and any OS sandbox. Nor may it replace an allowed root itself when that root is a
112
+ * directory (or does not exist yet), since an atomic write makes its temporary file beside its target, which for
113
+ * such a root is outside it.
114
+ */
115
+ evaluateWriteTargets(request) {
116
+ if (request.writeTargets !== true || !this.limitsAgent()) {
117
+ return { allowed: true };
118
+ }
119
+ const allowed = this.profile?.allowedPaths || [];
120
+ const allowedRoots = allowed.map(path => normalizeRoot(path, this.cwd));
121
+ const spelledRoots = allowed.map(path => resolve(this.cwd, expandHome(path)));
122
+ // Every path the whole call writes, so a set that completes a git directory across several of them (or several
123
+ // calls, with the disk carrying the earlier ones) is refused as one. The request's own path stands in when a
124
+ // caller names no set.
125
+ const writeSet = request.writeSet === undefined
126
+ ? extractPathArgs(request.args, request.executionCwd).map(path => resolve(this.cwd, expandHome(path)))
127
+ : this.resolvedWriteSet(request.writeSet);
128
+ for (const path of extractPathArgs(request.args, request.executionCwd)) {
129
+ // As the path policy refuses under a profile: the file Node writes is not the one the string spells.
130
+ if (!isWellFormedText(path)) {
131
+ return { allowed: false, reason: `Permission denied: a path must be well-formed Unicode text (${JSON.stringify(path)})` };
132
+ }
133
+ const canonical = normalizeRoot(path, this.cwd);
134
+ if (allowedRoots.includes(canonical) && !isRegularFile(canonical)) {
135
+ return { allowed: false, reason: `Permission denied: a write cannot replace an allowed root itself (${path})` };
136
+ }
137
+ // As written and as resolved: a link may lead into .git, and a .git that does not exist yet has no stored
138
+ // spelling. Only the components below the allowed root holding the path count: a work tree kept under a .git
139
+ // above the root (`git worktree add .git/wt/x`) stays writable. A git directory a .git file names, such as a
140
+ // separate or a linked worktree's, and any other directory git takes for its own, may have any name.
141
+ const spelled = resolve(this.cwd, expandHome(path));
142
+ const gitDirectory = gitDirectoryComponent(belowRoot(spelled, spelledRoots))
143
+ ?? gitDirectoryComponent(belowRoot(canonical, allowedRoots)) ?? linkedGitDirectoryHolding(canonical, [this.cwd]);
144
+ if (gitDirectory !== null) {
145
+ return {
146
+ allowed: false,
147
+ reason: `Permission denied: path is inside a git directory (${gitDirectory}), which a confined write may not change (${path})`,
148
+ };
149
+ }
150
+ // And a write that would make a plain directory into one git takes for its own: a filter or core.fsmonitor in
151
+ // its config is a command git then runs as ZTC, outside the profile and any sandbox.
152
+ const planted = gitDirectoryPlantedByWriteSet(spelled, writeSet);
153
+ if (planted !== null) {
154
+ return {
155
+ allowed: false,
156
+ reason: `Permission denied: this write would make a git directory (${planted}), which a confined write may not create (${path})`,
157
+ };
158
+ }
159
+ }
160
+ return { allowed: true };
161
+ }
162
+ /** `named` resolved against this policy's working directory, once per array (a fresh one each admission pass). */
163
+ resolvedWriteSet(named) {
164
+ let resolved = this.resolvedWriteSets.get(named);
165
+ if (resolved === undefined) {
166
+ resolved = named.map(path => resolve(this.cwd, expandHome(path)));
167
+ this.resolvedWriteSets.set(named, resolved);
168
+ }
169
+ return resolved;
170
+ }
171
+ /** Whether the agent works under limits that a command run through git could step past: paths or shell. */
172
+ limitsAgent() {
173
+ const profile = this.profile;
174
+ if (this.permissions.shell_exec === false)
175
+ return true;
176
+ if (!profile)
177
+ return false;
178
+ return Boolean(profile.allowedPaths?.length || profile.deniedPaths?.length
179
+ || profile.allowedShellCommands?.length || profile.deniedShellCommands?.length)
180
+ || profile.capabilities?.shell_exec === false
181
+ || profile.approvalRequiredCapabilities?.includes(ToolCapability.SHELL_EXEC) === true;
182
+ }
85
183
  evaluateShellPolicy(request) {
86
184
  if (!this.profile || !request.capabilities.includes(ToolCapability.SHELL_EXEC)) {
87
185
  return { allowed: true };
88
186
  }
89
- const checked = Object.hasOwn(request.args, 'checked') ? parseCheckedCommandPlan(request.args.checked) : undefined;
187
+ // A host-declared command is what runs: an adapter that drops a `checked` plan must not be judged by it.
188
+ const declared = request.executionCommand;
189
+ const checked = declared === undefined && Object.hasOwn(request.args, 'checked')
190
+ ? parseCheckedCommandPlan(request.args.checked) : undefined;
90
191
  if (checked === null)
91
192
  return { allowed: false, reason: 'Permission denied: invalid checked command plan' };
92
- const commands = checked ? checked.steps.flatMap(step => step.pipeline.map(formatCheckedStageCommand))
93
- : [typeof request.args.command === 'string' ? request.args.command.trim() : ''];
193
+ const commands = declared !== undefined ? [declared.trim()]
194
+ : checked ? checked.steps.flatMap(step => step.pipeline.map(formatCheckedStageCommand))
195
+ : [typeof request.args.command === 'string' ? request.args.command.trim() : ''];
94
196
  const denied = this.profile.deniedShellCommands || [];
95
197
  const allowed = this.profile.allowedShellCommands || [];
96
198
  for (const command of commands) {
@@ -115,7 +217,7 @@ export class CapabilityPolicy {
115
217
  if (!this.profile || !request.capabilities.includes(ToolCapability.NETWORK)) {
116
218
  return { allowed: true };
117
219
  }
118
- const hosts = extractNetworkHosts(request.args);
220
+ const hosts = extractNetworkHosts(request.args, request.executionCommand);
119
221
  if (hosts.length === 0) {
120
222
  return { allowed: true };
121
223
  }
@@ -138,11 +240,29 @@ export class CapabilityPolicy {
138
240
  return { allowed: true };
139
241
  }
140
242
  }
243
+ /** The arguments the path policy reads as paths, besides the `paths` list. */
244
+ const PATH_ARGUMENTS = ['path', 'file_path', 'filepath', 'directory', 'cwd', 'workdir', 'repo_path', 'artifact_path'];
245
+ /**
246
+ * The name of a path argument the policy cannot judge, or null: one that holds something other than a string (or
247
+ * nothing), or a `paths` that is not a list of strings. The policy reads only strings as paths, and a tool may turn
248
+ * any other value into one (String(['~/.ssh/id_rsa']) is the path), so such a call is refused, never judged on the
249
+ * string paths beside it.
250
+ */
251
+ function nonStringPathArgument(args) {
252
+ for (const key of PATH_ARGUMENTS) {
253
+ const value = args[key];
254
+ if (value !== undefined && value !== null && typeof value !== 'string')
255
+ return key;
256
+ }
257
+ const list = args.paths;
258
+ if (list === undefined || list === null)
259
+ return null;
260
+ return Array.isArray(list) && list.every(value => typeof value === 'string') ? null : 'paths';
261
+ }
141
262
  function extractPathArgs(args, executionCwd) {
142
263
  // Declared execution mapping owns cwd/workdir precedence. Undeclared tools
143
264
  // retain conservative checks of both raw fields and all other file paths.
144
- const candidates = ['path', 'file_path', 'filepath', 'directory',
145
- ...(executionCwd === undefined ? ['cwd', 'workdir'] : []), 'repo_path', 'artifact_path'];
265
+ const candidates = PATH_ARGUMENTS.filter(key => executionCwd === undefined || (key !== 'cwd' && key !== 'workdir'));
146
266
  const paths = executionCwd === undefined ? [] : [executionCwd];
147
267
  for (const key of candidates) {
148
268
  const value = args[key];
@@ -160,14 +280,35 @@ function extractPathArgs(args, executionCwd) {
160
280
  }
161
281
  return paths;
162
282
  }
283
+ function expandHome(path) {
284
+ return path === '~' ? homedir() : path.replace(/^~(?=\/|$)/, homedir());
285
+ }
163
286
  function normalizeRoot(path, cwd) {
164
- const expanded = path === '~' ? homedir() : path.replace(/^~(?=\/|$)/, homedir());
287
+ const expanded = expandHome(path);
165
288
  return canonicalPolicyPath(resolve(isAbsolute(expanded) ? expanded : resolve(cwd, expanded)), cwd);
166
289
  }
167
290
  function isWithinRoot(path, root) {
168
291
  return path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
169
292
  }
170
- function extractNetworkHosts(args) {
293
+ /** `path` below the longest of `roots` that holds it, relative to that root; all of `path` when none does. */
294
+ function belowRoot(path, roots) {
295
+ let holder;
296
+ for (const root of roots) {
297
+ if (isWithinRoot(path, root) && (holder === undefined || root.length > holder.length))
298
+ holder = root;
299
+ }
300
+ return holder === undefined ? path : relative(holder, path);
301
+ }
302
+ /** Whether `path` (canonical) is an existing regular file. */
303
+ function isRegularFile(path) {
304
+ try {
305
+ return lstatSync(path).isFile();
306
+ }
307
+ catch {
308
+ return false;
309
+ }
310
+ }
311
+ function extractNetworkHosts(args, executionCommand) {
171
312
  const hosts = new Set();
172
313
  const candidates = ['url', 'uri', 'endpoint', 'host', 'hostname', 'base_url', 'baseUrl'];
173
314
  for (const key of candidates) {
@@ -176,7 +317,7 @@ function extractNetworkHosts(args) {
176
317
  addHost(hosts, value);
177
318
  }
178
319
  }
179
- const command = typeof args.command === 'string' ? args.command : '';
320
+ const command = executionCommand ?? (typeof args.command === 'string' ? args.command : '');
180
321
  for (const match of command.matchAll(/https?:\/\/[^\s'"<>]+/gi)) {
181
322
  addHost(hosts, match[0]);
182
323
  }
@@ -210,18 +351,5 @@ function hostMatchesPattern(host, pattern) {
210
351
  return normalizedHost === normalizedPattern;
211
352
  }
212
353
  export function canonicalPolicyPath(path, cwd) {
213
- const expanded = path === '~' ? homedir() : path.replace(/^~(?=\/|$)/, homedir());
214
- const absolute = resolve(cwd, expanded);
215
- try {
216
- return realpathSync(absolute);
217
- }
218
- catch (error) {
219
- const code = error.code;
220
- if (code !== 'ENOENT' && code !== 'ENOTDIR')
221
- throw error;
222
- const parent = dirname(absolute);
223
- if (parent === absolute)
224
- return absolute;
225
- return resolve(canonicalPolicyPath(parent, cwd), basename(absolute));
226
- }
354
+ return canonicalPath(resolve(cwd, expandHome(path)));
227
355
  }
@@ -46,9 +46,13 @@ async function gitIdentity(cwd) {
46
46
  delete env[key];
47
47
  const options = { cwd, timeout: 2000, maxBuffer: 256 * 1024, encoding: 'utf8',
48
48
  env };
49
+ // core.fsmonitor=false stops a repository fsmonitor command on the status; safe.bareRepository=explicit stops
50
+ // git from discovering a planted directory as an implicit bare repository and reading its config, so a planted
51
+ // repo's HEAD and status are not adopted as this work tree's.
52
+ const probe = ['-c', 'core.fsmonitor=false', '-c', 'safe.bareRepository=explicit'];
49
53
  const [head, status] = await Promise.all([
50
- exec('git', ['rev-parse', '--verify', 'HEAD'], options),
51
- exec('git', ['-c', 'core.fsmonitor=false', 'status', '--porcelain=v1', '--untracked-files=normal'], options),
54
+ exec('git', [...probe, 'rev-parse', '--verify', 'HEAD'], options),
55
+ exec('git', [...probe, 'status', '--porcelain=v1', '--untracked-files=normal'], options),
52
56
  ]);
53
57
  const commit = head.stdout.trim();
54
58
  return { commit: /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(commit) ? commit : null, dirty: status.stdout.length > 0 };