@team-agent/installer 0.5.124 → 0.5.125

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 (97) hide show
  1. package/Cargo.lock +1 -8
  2. package/Cargo.toml +1 -1
  3. package/README.md +2 -2
  4. package/README.zh.md +2 -2
  5. package/crates/team-agent/Cargo.toml +0 -1
  6. package/crates/team-agent/src/cli/diagnose.rs +39 -1
  7. package/crates/team-agent/src/cli/emit.rs +41 -15
  8. package/crates/team-agent/src/cli/intent/runtime.rs +5 -53
  9. package/crates/team-agent/src/cli/intent/runtime_tests.rs +0 -120
  10. package/crates/team-agent/src/cli/leader.rs +2 -3
  11. package/crates/team-agent/src/cli/leader_prompt.rs +1 -1
  12. package/crates/team-agent/src/cli/mod.rs +6 -5
  13. package/crates/team-agent/src/cli/models.rs +40 -119
  14. package/crates/team-agent/src/cli/route.rs +1 -1
  15. package/crates/team-agent/src/cli/send/persist.rs +36 -0
  16. package/crates/team-agent/src/cli/send/presentation.rs +7 -1
  17. package/crates/team-agent/src/cli/send.rs +3 -1
  18. package/crates/team-agent/src/cli/spec.rs +1 -2
  19. package/crates/team-agent/src/cli/status_port/brief.rs +66 -0
  20. package/crates/team-agent/src/cli/tests/base.rs +4 -11
  21. package/crates/team-agent/src/cli/tests/status_send.rs +17 -0
  22. package/crates/team-agent/src/compiler/tests.rs +21 -5
  23. package/crates/team-agent/src/compiler.rs +24 -1
  24. package/crates/team-agent/src/contract_runtime/backend.rs +22 -6
  25. package/crates/team-agent/src/contract_runtime/config.rs +34 -24
  26. package/crates/team-agent/src/contract_runtime/discovery.rs +33 -0
  27. package/crates/team-agent/src/contract_runtime/framework.rs +89 -34
  28. package/crates/team-agent/src/contract_runtime/registry.rs +258 -21
  29. package/crates/team-agent/src/coordinator/runtime_detectors.rs +0 -1
  30. package/crates/team-agent/src/coordinator/tick.rs +89 -1
  31. package/crates/team-agent/src/db/message_store.rs +78 -3
  32. package/crates/team-agent/src/layout/worker_window_helpers.rs +0 -1
  33. package/crates/team-agent/src/leader/prompt.rs +1 -2
  34. package/crates/team-agent/src/leader/provider_attribution.rs +0 -52
  35. package/crates/team-agent/src/leader/start.rs +0 -1
  36. package/crates/team-agent/src/leader/tests/prompt_contract.rs +2 -3
  37. package/crates/team-agent/src/lifecycle/launch/add_agent.rs +91 -0
  38. package/crates/team-agent/src/lifecycle/launch/add_agent_state.rs +14 -1
  39. package/crates/team-agent/src/lifecycle/launch/agent_state.rs +0 -9
  40. package/crates/team-agent/src/lifecycle/launch/fork_agent.rs +0 -1
  41. package/crates/team-agent/src/lifecycle/launch/mcp_config.rs +2 -2
  42. package/crates/team-agent/src/lifecycle/launch/spawn.rs +0 -28
  43. package/crates/team-agent/src/lifecycle/launch/spec_state.rs +0 -1
  44. package/crates/team-agent/src/lifecycle/launch/worker_env.rs +0 -108
  45. package/crates/team-agent/src/lifecycle/launch.rs +2 -20
  46. package/crates/team-agent/src/lifecycle/profile_launch.rs +11 -39
  47. package/crates/team-agent/src/lifecycle/profile_smoke.rs +1 -2
  48. package/crates/team-agent/src/lifecycle/restart/common.rs +1 -63
  49. package/crates/team-agent/src/lifecycle/role_config.rs +42 -3
  50. package/crates/team-agent/src/lifecycle/tests/cli_argv_routing_red.rs +38 -7
  51. package/crates/team-agent/src/lifecycle/tests/clone_fork_copilot_perms_red.rs +6 -2
  52. package/crates/team-agent/src/lifecycle/tests/restart_rebind_hotfix_252_red.rs +0 -1
  53. package/crates/team-agent/src/lifecycle/tests/worker_spawn_env_red.rs +0 -137
  54. package/crates/team-agent/src/lifecycle/tests.rs +0 -3
  55. package/crates/team-agent/src/lifecycle/worker_command_context.rs +2 -4
  56. package/crates/team-agent/src/mcp_server/readiness.rs +148 -97
  57. package/crates/team-agent/src/mcp_server/readiness_tests.rs +115 -16
  58. package/crates/team-agent/src/messaging/delivery.rs +181 -35
  59. package/crates/team-agent/src/messaging/delivery_consumption_tests.rs +4 -4
  60. package/crates/team-agent/src/messaging/enter_rescue_tests.rs +1 -1
  61. package/crates/team-agent/src/messaging/helpers.rs +19 -0
  62. package/crates/team-agent/src/messaging/tests/dup_inject.rs +66 -4
  63. package/crates/team-agent/src/messaging/tests/runtime.rs +110 -4
  64. package/crates/team-agent/src/messaging/tests/spine.rs +22 -6
  65. package/crates/team-agent/src/model/enums.rs +1 -8
  66. package/crates/team-agent/src/provider/adapter.rs +1 -67
  67. package/crates/team-agent/src/provider/adapters/mod.rs +0 -1
  68. package/crates/team-agent/src/provider/argv_route.rs +1 -5
  69. package/crates/team-agent/src/provider/bypass_flags.rs +3 -11
  70. package/crates/team-agent/src/provider/classify.rs +68 -3
  71. package/crates/team-agent/src/provider/faults.rs +1 -1
  72. package/crates/team-agent/src/provider/model_catalog.rs +2 -73
  73. package/crates/team-agent/src/provider/session/capture.rs +1 -1
  74. package/crates/team-agent/src/provider/session/context_fork.rs +4 -4
  75. package/crates/team-agent/src/provider/session_scan/common.rs +1 -2
  76. package/crates/team-agent/src/provider/session_scan.rs +0 -4
  77. package/crates/team-agent/src/provider/submit_now.rs +5 -28
  78. package/crates/team-agent/src/provider/tests/adapter.rs +5 -184
  79. package/crates/team-agent/src/provider/tests/classify.rs +53 -0
  80. package/crates/team-agent/src/provider/tests/command_helpers.rs +1 -4
  81. package/crates/team-agent/src/provider/types.rs +1 -1
  82. package/crates/team-agent/src/provider/wire.rs +48 -8
  83. package/crates/team-agent/src/tmux_backend/native_input_tests.rs +2 -178
  84. package/crates/team-agent/src/tmux_backend/tests.rs +151 -0
  85. package/crates/team-agent/src/tmux_backend.rs +43 -8
  86. package/crates/team-agent/src/transport/native_input.rs +2 -231
  87. package/package.json +4 -4
  88. package/skills/team-agent/SKILL.md +1 -1
  89. package/crates/team-agent/src/lifecycle/launch/cursor_create_chat.rs +0 -229
  90. package/crates/team-agent/src/lifecycle/launch/cursor_mcp.rs +0 -522
  91. package/crates/team-agent/src/lifecycle/launch/cursor_mcp_iso.rs +0 -282
  92. package/crates/team-agent/src/lifecycle/tests/cursor_mcp_overlay.rs +0 -576
  93. package/crates/team-agent/src/lifecycle/tests/cursor_require_explicit_model_red.rs +0 -222
  94. package/crates/team-agent/src/lifecycle/tests/cursor_restart_resume_red.rs +0 -511
  95. package/crates/team-agent/src/provider/adapters/cursor_agent.rs +0 -44
  96. package/crates/team-agent/src/provider/session_scan/cursor.rs +0 -538
  97. package/crates/team-agent/src/provider/testdata/cursor-list-models-native.stdout +0 -250
@@ -24,7 +24,7 @@ impl NativeInputRequest {
24
24
  }
25
25
 
26
26
  pub fn supported(&self) -> bool {
27
- matches!(self.provider, Provider::Pi | Provider::CursorAgent)
27
+ self.provider == Provider::Pi
28
28
  && self.message_id.starts_with("msg_")
29
29
  && self
30
30
  .message_id
@@ -196,7 +196,7 @@ fn input_digest(text: &str) -> String {
196
196
  }
197
197
 
198
198
  pub(crate) fn supports_input_observation(provider: Provider) -> bool {
199
- matches!(provider, Provider::Pi | Provider::CursorAgent)
199
+ provider == Provider::Pi
200
200
  }
201
201
 
202
202
  pub(crate) fn inspect_input(
@@ -206,79 +206,10 @@ pub(crate) fn inspect_input(
206
206
  ) -> Option<InputFrame> {
207
207
  match provider {
208
208
  Provider::Pi => pi_input(text, pane_height),
209
- Provider::CursorAgent => cursor_input(text, pane_height),
210
209
  _ => None,
211
210
  }
212
211
  }
213
212
 
214
- fn cursor_input(text: &str, pane_height: u32) -> Option<InputFrame> {
215
- use team_agent_contract::contract::delivery::InputSurface;
216
- if pane_height == 0 {
217
- return None;
218
- }
219
- let text_rows: Vec<_> = text.lines().collect();
220
- // Only the current viewport authorizes input; retain full history below
221
- // solely for same-message transcript correlation.
222
- let viewport_start = text_rows.len().saturating_sub(pane_height as usize);
223
- let viewport = text_rows[viewport_start..].join("\n");
224
- let (surface, rows, capsule, busy) =
225
- team_agent_contract::providers::cursor::interaction::inspect_legacy_composer(&viewport)?;
226
- let first = match *rows.first()? {
227
- "→" => "",
228
- row => row.strip_prefix("→ ")?,
229
- };
230
- let footer = rows.iter().rposition(|row| {
231
- row.strip_suffix("Run Everything").is_some_and(|prefix| {
232
- !prefix.trim().is_empty() && !prefix.trim_start().starts_with("→ ")
233
- })
234
- })?;
235
- if footer == 0 {
236
- return None;
237
- }
238
- let tail: Vec<_> = rows[footer + 1..]
239
- .iter()
240
- .filter(|row| !row.is_empty())
241
- .copied()
242
- .collect();
243
- if tail.is_empty() {
244
- return None;
245
- }
246
- // Startup history can leave Tail(200) between Ready/Pasted/Accepted. The
247
- // immutable carrier birth/nonce remains in NativeInputBinding; this UI
248
- // context is the current native cwd/footer tail, not a version attestation.
249
- let identity = format!(
250
- "cursor-current-composer-v1:{}",
251
- input_digest(&tail.join("\n"))
252
- );
253
- let footer_row = rows[footer]
254
- .split_whitespace()
255
- .collect::<Vec<_>>()
256
- .join(" ");
257
- let ready = matches!(surface, InputSurface::ComposerReady | InputSurface::Busy);
258
- if (ready || capsule.is_some()) && rows[1..footer].iter().any(|row| !row.trim().is_empty()) {
259
- return None;
260
- }
261
- let composer = if ready {
262
- String::new()
263
- } else {
264
- std::iter::once(first)
265
- .chain(rows[1..footer].iter().copied())
266
- .collect::<Vec<_>>()
267
- .join("\n")
268
- };
269
- let arrow = text_rows
270
- .iter()
271
- .rposition(|line| line.trim() == "→" || line.trim().starts_with("→ "))?;
272
- Some(InputFrame {
273
- composer,
274
- transcript: text.lines().take(arrow).collect::<Vec<_>>().join("\n"),
275
- identity,
276
- footer: footer_row,
277
- busy,
278
- capsule: capsule.map(str::to_owned),
279
- })
280
- }
281
-
282
213
  fn border(line: &str) -> bool {
283
214
  line.chars().filter(|character| *character == '─').count() >= 8
284
215
  && line.trim_start().starts_with('─')
@@ -400,10 +331,6 @@ mod tests {
400
331
  #![allow(clippy::unwrap_used, clippy::panic)]
401
332
  use super::*;
402
333
 
403
- fn cursor(composer: &str, transcript: &str) -> String {
404
- format!("Cursor Agent\nv2026.10.01-e373342\n{transcript}\n→ {composer}\nGrok 4.7 High Run Everything\n/owned/project\n")
405
- }
406
-
407
334
  fn pi(composer: &str, transcript: &str) -> String {
408
335
  format!("{transcript}\n──────────────── ↑ 20 more ─ runner-luna ─\n{composer}\n────────────────────────\ngpt-6-luna · max · 0%/272k · 0% · $0.00\n")
409
336
  }
@@ -561,160 +488,4 @@ mod tests {
561
488
  assert_eq!(pi_paste_capsule(label), None, "{label}");
562
489
  }
563
490
  }
564
-
565
- // Native Issue #328 current-composer rows; transcript removed and private
566
- // cwd replaced with /owned/project. Startup banner is genuinely absent
567
- // from the owned pane's Tail(200), not a fabricated invalid version.
568
- const CURSOR_FOLLOWUP: &str =
569
- include_str!("../../tests/fixtures/cursor-followup-headerless.txt");
570
-
571
- #[test]
572
- fn native_input_cursor_clean_followup_does_not_require_scrolled_startup_banner() {
573
- let ready = inspect_input(Provider::CursorAgent, CURSOR_FOLLOWUP).unwrap();
574
- assert!(ready.empty());
575
- assert!(!ready.busy);
576
- assert!(ready.capsule.is_none());
577
- let header = format!("Cursor Agent\nv2026.10.14-0f9edde\n{CURSOR_FOLLOWUP}");
578
- let with_header = inspect_input(Provider::CursorAgent, &header).unwrap();
579
- assert!(with_header.empty() && !with_header.busy);
580
- assert_eq!(ready.footer, with_header.footer);
581
- assert_eq!(
582
- ready.identity, with_header.identity,
583
- "startup history is not a new UI identity"
584
- );
585
- }
586
-
587
- #[test]
588
- fn native_input_cursor_headerless_followup_retains_draft_busy_and_footer_fences() {
589
- let label = "[Pasted text #2 +25 lines]";
590
- let folded = CURSOR_FOLLOWUP.replace("Add a follow-up", label);
591
- let draft = inspect_input(Provider::CursorAgent, &folded).unwrap();
592
- assert!(!draft.empty());
593
- assert_eq!(draft.capsule.as_deref(), Some(label));
594
- let dirty = CURSOR_FOLLOWUP.replace("Add a follow-up", "Add a follow-up draft");
595
- assert!(!inspect_input(Provider::CursorAgent, &dirty)
596
- .unwrap()
597
- .empty());
598
- for dirty in [
599
- CURSOR_FOLLOWUP.replace("Add a follow-up", "Add a follow-up\nforeign draft"),
600
- CURSOR_FOLLOWUP.replace("Add a follow-up", &format!("{label}\nforeign draft")),
601
- ] {
602
- assert!(inspect_input(Provider::CursorAgent, &dirty).is_none());
603
- }
604
- let busy = CURSOR_FOLLOWUP.replace("Add a follow-up", "Add a follow-up ctrl+c to stop");
605
- assert!(inspect_input(Provider::CursorAgent, &busy).unwrap().busy);
606
- let working = format!("⠘⠆ Working\n{CURSOR_FOLLOWUP}");
607
- assert!(inspect_input(Provider::CursorAgent, &working).unwrap().busy);
608
- for unknown in [
609
- "→ Add a follow-up\n".to_string(),
610
- CURSOR_FOLLOWUP.replace("Run Everything", "unknown footer"),
611
- CURSOR_FOLLOWUP.replace(" /owned/project\n", ""),
612
- ] {
613
- assert!(inspect_input(Provider::CursorAgent, &unknown).is_none());
614
- }
615
- }
616
-
617
- #[test]
618
- fn native_input_cursor_real_expanded_followup_is_nonempty_current_marker_not_capsule() {
619
- let expanded = include_str!("../../tests/fixtures/cursor-followup-expanded.txt");
620
- let marker = "[team-agent-token:msg_one]";
621
- for prefix in [
622
- "".to_string(),
623
- format!("Cursor Agent\nv2026.10.14-0f9edde\n{CURSOR_FOLLOWUP}"),
624
- ] {
625
- let text = format!("{prefix}{expanded}");
626
- let frame = inspect_input(Provider::CursorAgent, &text).unwrap();
627
- assert!(!frame.empty() && !frame.busy);
628
- assert!(frame.has_marker(marker));
629
- assert!(frame.capsule.is_none());
630
- assert!(!frame.transcript.contains(marker));
631
- let changed = text.replace("/owned/project", "/different/project");
632
- assert_ne!(
633
- frame.identity,
634
- inspect_input(Provider::CursorAgent, &changed)
635
- .unwrap()
636
- .identity
637
- );
638
- }
639
- let duplicate = expanded.replace(marker, &format!("{marker}\n{marker}"));
640
- assert!(!inspect_input(Provider::CursorAgent, &duplicate)
641
- .unwrap()
642
- .has_marker(marker));
643
- let busy = expanded.replace(" →", "⠘⠆ Working\n →");
644
- assert!(inspect_input(Provider::CursorAgent, &busy).unwrap().busy);
645
- for unknown in [
646
- "→\nGrok 4.7 High Run Everything\n/owned/project\n".to_string(),
647
- "→\nforeign draft\n→ Add a follow-up\nGrok 4.7 High Run Everything\n/owned/project\n"
648
- .to_string(),
649
- expanded.replace("Run Everything", "unknown footer"),
650
- expanded.replace(" /owned/project\n", ""),
651
- format!("{expanded}{}", "unknown current row\n".repeat(24)),
652
- ] {
653
- assert!(super::inspect_input(Provider::CursorAgent, &unknown, 24).is_none());
654
- }
655
- }
656
-
657
- #[test]
658
- fn native_input_cursor_requires_composer_in_current_viewport_not_old_history() {
659
- for header in ["", "Cursor Agent\nv2026.10.14-0f9edde\n"] {
660
- let hidden = format!(
661
- "{header}{CURSOR_FOLLOWUP}{}",
662
- "unknown current row\n".repeat(24)
663
- );
664
- assert!(super::inspect_input(Provider::CursorAgent, &hidden, 24).is_none());
665
- }
666
- assert!(super::inspect_input(Provider::CursorAgent, CURSOR_FOLLOWUP, 0).is_none());
667
- let current = super::inspect_input(Provider::CursorAgent, CURSOR_FOLLOWUP, 24).unwrap();
668
- let changed = CURSOR_FOLLOWUP.replace("/owned/project", "/different/project");
669
- let changed = super::inspect_input(Provider::CursorAgent, &changed, 24).unwrap();
670
- assert_ne!(current.identity, changed.identity);
671
- }
672
-
673
- #[test]
674
- fn native_input_cursor_separates_folded_draft_from_history_and_busy() {
675
- let capsule = "[Pasted text #1 +25 lines]";
676
- let draft = inspect_input(Provider::CursorAgent, &cursor(capsule, "")).unwrap();
677
- assert!(!draft.empty());
678
- assert_eq!(draft.capsule.as_deref(), Some(capsule));
679
- let ready = inspect_input(
680
- Provider::CursorAgent,
681
- &cursor("Plan, search, build anything", capsule),
682
- )
683
- .unwrap();
684
- assert!(ready.empty());
685
- assert!(ready.capsule.is_none());
686
- let busy = inspect_input(
687
- Provider::CursorAgent,
688
- &cursor("Add a follow-up ctrl+c to stop", capsule),
689
- )
690
- .unwrap();
691
- assert!(busy.busy);
692
- assert!(
693
- inspect_input(Provider::CursorAgent, &cursor(capsule, "⠘⠆ Working"))
694
- .unwrap()
695
- .busy
696
- );
697
- assert!(inspect_input(Provider::CursorAgent, "→ [Pasted text #1 +25 lines]").is_none());
698
- assert!(inspect_input(
699
- Provider::CursorAgent,
700
- &cursor("Plan, search, build anything\nextra editable text", "")
701
- )
702
- .is_none());
703
- assert!(inspect_input(
704
- Provider::CursorAgent,
705
- &cursor("[Pasted text #1 +25 lines]\nsecond block", "")
706
- )
707
- .is_none());
708
- assert!(inspect_input(
709
- Provider::CursorAgent,
710
- "Cursor Agent\nv2026.10.01-e373342\n→ Run Everything\n"
711
- )
712
- .is_none());
713
- let malformed = inspect_input(
714
- Provider::CursorAgent,
715
- &cursor("[Pasted text #0 +25 lines]", ""),
716
- )
717
- .unwrap();
718
- assert!(malformed.capsule.is_none());
719
- }
720
491
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@team-agent/installer",
3
- "version": "0.5.124",
3
+ "version": "0.5.125",
4
4
  "description": "npx installer for Team Agent",
5
5
  "keywords": [
6
6
  "codex",
@@ -20,9 +20,9 @@
20
20
  "team-agent-installer": "npm/install.mjs"
21
21
  },
22
22
  "optionalDependencies": {
23
- "@team-agent/cli-darwin-arm64": "0.5.124",
24
- "@team-agent/cli-darwin-x64": "0.5.124",
25
- "@team-agent/cli-linux-x64": "0.5.124"
23
+ "@team-agent/cli-darwin-arm64": "0.5.125",
24
+ "@team-agent/cli-darwin-x64": "0.5.125",
25
+ "@team-agent/cli-linux-x64": "0.5.125"
26
26
  },
27
27
  "scripts": {
28
28
  "postinstall": "node npm/bincheck.mjs",
@@ -113,7 +113,7 @@ team-agent route disable
113
113
 
114
114
  `set` replaces one mapping, `add` appends without deduplication, `clear` removes it; none changes the switch. `enable`/`disable` preserve mappings in `~/.team-agent/argv-routing.json`. `TEAM_AGENT_CLI_ARGV_ROUTING` overrides the switch: `1/true/on`, `0/false/off` (case-insensitive, trimmed); invalid values disable routing. Check `persisted_enabled`, `effective_enabled` and `override_status`.
115
115
 
116
- Keys: `claude`, `codex`, `copilot`, `gemini_cli`, `grok`, `cursor_agent`, `pi`. Claude/Claude Code share `claude`; aliases `claude_code/claude-code`, `agent/cursor` are accepted. Everything after the first `--`, including `--help`, `--json`, empty strings and `{workspace}`, is literal argv. No shell expansion. Do not route secrets or override framework-managed session/MCP/permission flags.
116
+ Keys: `claude`, `codex`, `copilot`, `gemini_cli`, `grok`, `pi`. Claude/Claude Code share `claude`; aliases `claude_code/claude-code` are accepted. Everything after the first `--`, including `--help`, `--json`, empty strings and `{workspace}`, is literal argv. No shell expansion. Do not route secrets or override framework-managed session/MCP/permission flags.
117
117
 
118
118
  Mappings affect the next actual native spawn, not running/attached processes, dry-run or helper probes. Invalid enabled configuration refuses spawn; an emergency environment OFF avoids reading it, while `route disable` will not overwrite a broken file. Pi `--mode rpc` does not provide an RPC host or replace Team Agent's transport.
119
119
 
@@ -1,229 +0,0 @@
1
- //! ---
2
- //! purpose: cursor 候选 A——`agent create-chat` 解析首行 chatId 后按记录 PID 杀
3
- //! contract:
4
- //! provides:
5
- //! - name: apply_cursor_create_chat_plan
6
- //! what: 无 pending 时把 CLI chatId 写入 expected_session_id 并 `--resume` 该 id
7
- //! - name: create_cursor_chat_id
8
- //! what: 跑 create-chat,读第一行 UUID,只杀本调用记录的 PID
9
- //! requires:
10
- //! - name: cursor-agent-cli
11
- //! what: PATH 上的 `agent`;不存在或首行非法则返回 None(降级候选 B)
12
- //! boundary:
13
- //! - 不发明 --session-id;不 pkill/killall;不 wait 子进程自行退出
14
- //! - 不读 chats 正文、不打印 proxy 值
15
- //! - 已有 expected_session_id 或 argv 已含 --resume 则不动
16
- //! - 2026-08-21 活体:create-chat 后 `--resume` 的存档在 pane stop 后被清;
17
- //! TUI 自建会话能留盘。fresh 路径不调用本函数(走 scan 唯一 hex)。
18
- //! maturity: wired
19
- //! ---
20
-
21
- use std::io::{BufRead, BufReader};
22
- use std::path::Path;
23
- use std::process::{Command, Stdio};
24
- use std::sync::mpsc;
25
- use std::thread;
26
- use std::time::Duration;
27
-
28
- use crate::provider::types::{CommandPlan, SessionId};
29
-
30
- const FIRST_LINE_TIMEOUT: Duration = Duration::from_secs(5);
31
- const TERM_GRACE: Duration = Duration::from_millis(200);
32
-
33
- /// ---
34
- /// purpose: 冷启/无 session 的 cursor 计划绑定 create-chat 得到的 chatId
35
- /// params:
36
- /// plan: build_command_plan 产出;workspace: 物理 cwd
37
- /// returns: 成功则 expected_session_id 与 argv `--resume <id>` 齐;失败则计划不变
38
- /// contract:
39
- /// provides:
40
- /// - name: apply_cursor_create_chat_plan
41
- /// what: 只在无 pending 且 argv 无 --resume 时写入 CLI chatId
42
- /// boundary:
43
- /// - 库测试(cfg(test))不调真实 agent,避免订阅/挂起;具名测试打 create_cursor_chat_id
44
- /// - 不在 launch/restart fresh 调用:活体证实 `--resume` 空聊存档停 pane 后消失
45
- /// ---
46
- pub(crate) fn apply_cursor_create_chat_plan(plan: &mut CommandPlan, workspace: &Path) {
47
- if cfg!(test) {
48
- return;
49
- }
50
- if plan.expected_session_id.is_some() {
51
- return;
52
- }
53
- if plan.argv.iter().any(|flag| flag == "--resume") {
54
- return;
55
- }
56
- let Some(chat_id) = create_cursor_chat_id(workspace) else {
57
- return;
58
- };
59
- plan.expected_session_id = Some(SessionId::new(chat_id.clone()));
60
- plan.argv.push("--resume".to_string());
61
- plan.argv.push(chat_id);
62
- }
63
-
64
- /// ---
65
- /// purpose: 跑 `agent create-chat`,解析首行 UUID,按记录 PID 终止挂起进程
66
- /// params:
67
- /// workspace: create-chat 的 cwd(物理 workspace)
68
- /// returns: 合法 UUID;命令缺失/超时/非法首行则 None
69
- /// contract:
70
- /// provides:
71
- /// - name: create_cursor_chat_id
72
- /// what: 读一行就停;不 wait 退出;只杀本 Child.id()
73
- /// boundary:
74
- /// - 禁 pkill/killall;pid 0/1 不杀
75
- /// ---
76
- pub(crate) fn create_cursor_chat_id(workspace: &Path) -> Option<String> {
77
- create_cursor_chat_id_with_command("agent", workspace)
78
- }
79
-
80
- fn create_cursor_chat_id_with_command(program: &str, workspace: &Path) -> Option<String> {
81
- let mut child = Command::new(program)
82
- .arg("create-chat")
83
- .current_dir(workspace)
84
- .stdin(Stdio::null())
85
- .stdout(Stdio::piped())
86
- .stderr(Stdio::null())
87
- .spawn()
88
- .ok()?;
89
- let pid = child.id();
90
- let stdout = child.stdout.take()?;
91
- let (tx, rx) = mpsc::channel();
92
- thread::spawn(move || {
93
- let mut reader = BufReader::new(stdout);
94
- let mut line = String::new();
95
- let result = reader.read_line(&mut line).ok().and_then(|_| parse_chat_id_line(&line));
96
- let _ = tx.send(result);
97
- });
98
- let parsed = match rx.recv_timeout(FIRST_LINE_TIMEOUT) {
99
- Ok(value) => value,
100
- Err(_) => None,
101
- };
102
- kill_recorded_pid(pid);
103
- let _ = child.wait();
104
- parsed
105
- }
106
-
107
- fn parse_chat_id_line(line: &str) -> Option<String> {
108
- let token = line
109
- .trim()
110
- .split_whitespace()
111
- .next()
112
- .unwrap_or("")
113
- .trim_matches(['"', '\'']);
114
- is_chat_uuid(token).then(|| token.to_string())
115
- }
116
-
117
- fn is_chat_uuid(value: &str) -> bool {
118
- let bytes = value.as_bytes();
119
- if bytes.len() != 36 {
120
- return false;
121
- }
122
- for (i, b) in bytes.iter().enumerate() {
123
- if i == 8 || i == 13 || i == 18 || i == 23 {
124
- if *b != b'-' {
125
- return false;
126
- }
127
- } else if !b.is_ascii_hexdigit() {
128
- return false;
129
- }
130
- }
131
- true
132
- }
133
-
134
- fn kill_recorded_pid(pid: u32) {
135
- if pid == 0 || pid == 1 {
136
- return;
137
- }
138
- #[cfg(unix)]
139
- {
140
- let raw = pid as i32;
141
- unsafe {
142
- libc::kill(raw, libc::SIGTERM);
143
- }
144
- thread::sleep(TERM_GRACE);
145
- unsafe {
146
- libc::kill(raw, libc::SIGKILL);
147
- }
148
- }
149
- #[cfg(not(unix))]
150
- {
151
- let _ = pid;
152
- }
153
- }
154
-
155
- #[cfg(test)]
156
- mod tests {
157
- #![allow(clippy::unwrap_used)]
158
-
159
- use super::*;
160
- use std::os::unix::fs::PermissionsExt;
161
- use std::sync::atomic::{AtomicU64, Ordering};
162
-
163
- fn tmp_root(tag: &str) -> std::path::PathBuf {
164
- static CTR: AtomicU64 = AtomicU64::new(0);
165
- let dir = std::env::temp_dir().join(format!(
166
- "ta-d117-create-chat-{}-{}-{}",
167
- tag,
168
- std::process::id(),
169
- CTR.fetch_add(1, Ordering::Relaxed)
170
- ));
171
- let _ = std::fs::remove_dir_all(&dir);
172
- std::fs::create_dir_all(&dir).unwrap();
173
- dir
174
- }
175
-
176
- fn write_stub(dir: &Path, body: &str) -> std::path::PathBuf {
177
- let path = dir.join("agent");
178
- std::fs::write(&path, body).unwrap();
179
- let mut perm = std::fs::metadata(&path).unwrap().permissions();
180
- perm.set_mode(0o755);
181
- std::fs::set_permissions(&path, perm).unwrap();
182
- path
183
- }
184
-
185
- #[test]
186
- fn create_chat_reads_first_line_and_kills_recorded_pid() {
187
- let base = tmp_root("ok");
188
- let ws = base.join("ws");
189
- std::fs::create_dir_all(&ws).unwrap();
190
- let bin = write_stub(
191
- &base,
192
- "#!/bin/sh\necho '681c8837-d564-44fa-98bf-4ff5a66592e2'\nkill -STOP $$\n",
193
- );
194
- let got = create_cursor_chat_id_with_command(bin.to_str().unwrap(), &ws);
195
- assert_eq!(
196
- got.as_deref(),
197
- Some("681c8837-d564-44fa-98bf-4ff5a66592e2")
198
- );
199
- let _ = std::fs::remove_dir_all(&base);
200
- }
201
-
202
- #[test]
203
- fn create_chat_rejects_non_uuid_first_line() {
204
- let base = tmp_root("bad");
205
- let ws = base.join("ws");
206
- std::fs::create_dir_all(&ws).unwrap();
207
- let bin = write_stub(&base, "#!/bin/sh\necho not-a-uuid\nkill -STOP $$\n");
208
- let got = create_cursor_chat_id_with_command(bin.to_str().unwrap(), &ws);
209
- assert!(got.is_none());
210
- let _ = std::fs::remove_dir_all(&base);
211
- }
212
-
213
- #[test]
214
- fn apply_is_noop_when_resume_already_present() {
215
- let mut plan = CommandPlan {
216
- argv: vec![
217
- "agent".into(),
218
- "--resume".into(),
219
- "already-bound".into(),
220
- ],
221
- expected_session_id: None,
222
- provider_projects_root: None,
223
- managed_mcp_config: false,
224
- };
225
- apply_cursor_create_chat_plan(&mut plan, Path::new("/tmp"));
226
- assert!(plan.expected_session_id.is_none());
227
- assert_eq!(plan.argv.iter().filter(|a| *a == "--resume").count(), 1);
228
- }
229
- }